OSDN Git Service

2011-08-31 Jose Ruiz <ruiz@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch6.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M _ C H 6                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Expander; use Expander;
33 with Exp_Ch6;  use Exp_Ch6;
34 with Exp_Ch7;  use Exp_Ch7;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Disp; use Exp_Disp;
37 with Exp_Tss;  use Exp_Tss;
38 with Exp_Util; use Exp_Util;
39 with Fname;    use Fname;
40 with Freeze;   use Freeze;
41 with Itypes;   use Itypes;
42 with Lib.Xref; use Lib.Xref;
43 with Layout;   use Layout;
44 with Namet;    use Namet;
45 with Lib;      use Lib;
46 with Nlists;   use Nlists;
47 with Nmake;    use Nmake;
48 with Opt;      use Opt;
49 with Output;   use Output;
50 with Restrict; use Restrict;
51 with Rident;   use Rident;
52 with Rtsfind;  use Rtsfind;
53 with Sem;      use Sem;
54 with Sem_Aux;  use Sem_Aux;
55 with Sem_Cat;  use Sem_Cat;
56 with Sem_Ch3;  use Sem_Ch3;
57 with Sem_Ch4;  use Sem_Ch4;
58 with Sem_Ch5;  use Sem_Ch5;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Ch10; use Sem_Ch10;
61 with Sem_Ch12; use Sem_Ch12;
62 with Sem_Ch13; use Sem_Ch13;
63 with Sem_Disp; use Sem_Disp;
64 with Sem_Dist; use Sem_Dist;
65 with Sem_Elim; use Sem_Elim;
66 with Sem_Eval; use Sem_Eval;
67 with Sem_Mech; use Sem_Mech;
68 with Sem_Prag; use Sem_Prag;
69 with Sem_Res;  use Sem_Res;
70 with Sem_Util; use Sem_Util;
71 with Sem_Type; use Sem_Type;
72 with Sem_Warn; use Sem_Warn;
73 with Sinput;   use Sinput;
74 with Stand;    use Stand;
75 with Sinfo;    use Sinfo;
76 with Sinfo.CN; use Sinfo.CN;
77 with Snames;   use Snames;
78 with Stringt;  use Stringt;
79 with Style;
80 with Stylesw;  use Stylesw;
81 with Tbuild;   use Tbuild;
82 with Uintp;    use Uintp;
83 with Urealp;   use Urealp;
84 with Validsw;  use Validsw;
85
86 package body Sem_Ch6 is
87
88    May_Hide_Profile : Boolean := False;
89    --  This flag is used to indicate that two formals in two subprograms being
90    --  checked for conformance differ only in that one is an access parameter
91    --  while the other is of a general access type with the same designated
92    --  type. In this case, if the rest of the signatures match, a call to
93    --  either subprogram may be ambiguous, which is worth a warning. The flag
94    --  is set in Compatible_Types, and the warning emitted in
95    --  New_Overloaded_Entity.
96
97    -----------------------
98    -- Local Subprograms --
99    -----------------------
100
101    procedure Analyze_Return_Statement (N : Node_Id);
102    --  Common processing for simple and extended return statements
103
104    procedure Analyze_Function_Return (N : Node_Id);
105    --  Subsidiary to Analyze_Return_Statement. Called when the return statement
106    --  applies to a [generic] function.
107
108    procedure Analyze_Return_Type (N : Node_Id);
109    --  Subsidiary to Process_Formals: analyze subtype mark in function
110    --  specification in a context where the formals are visible and hide
111    --  outer homographs.
112
113    procedure Analyze_Subprogram_Body_Helper (N : Node_Id);
114    --  Does all the real work of Analyze_Subprogram_Body. This is split out so
115    --  that we can use RETURN but not skip the debug output at the end.
116
117    procedure Analyze_Generic_Subprogram_Body (N : Node_Id; Gen_Id : Entity_Id);
118    --  Analyze a generic subprogram body. N is the body to be analyzed, and
119    --  Gen_Id is the defining entity Id for the corresponding spec.
120
121    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id);
122    --  If a subprogram has pragma Inline and inlining is active, use generic
123    --  machinery to build an unexpanded body for the subprogram. This body is
124    --  subsequently used for inline expansions at call sites. If subprogram can
125    --  be inlined (depending on size and nature of local declarations) this
126    --  function returns true. Otherwise subprogram body is treated normally.
127    --  If proper warnings are enabled and the subprogram contains a construct
128    --  that cannot be inlined, the offending construct is flagged accordingly.
129
130    function Can_Override_Operator (Subp : Entity_Id) return Boolean;
131    --  Returns true if Subp can override a predefined operator.
132
133    procedure Check_Conformance
134      (New_Id                   : Entity_Id;
135       Old_Id                   : Entity_Id;
136       Ctype                    : Conformance_Type;
137       Errmsg                   : Boolean;
138       Conforms                 : out Boolean;
139       Err_Loc                  : Node_Id := Empty;
140       Get_Inst                 : Boolean := False;
141       Skip_Controlling_Formals : Boolean := False);
142    --  Given two entities, this procedure checks that the profiles associated
143    --  with these entities meet the conformance criterion given by the third
144    --  parameter. If they conform, Conforms is set True and control returns
145    --  to the caller. If they do not conform, Conforms is set to False, and
146    --  in addition, if Errmsg is True on the call, proper messages are output
147    --  to complain about the conformance failure. If Err_Loc is non_Empty
148    --  the error messages are placed on Err_Loc, if Err_Loc is empty, then
149    --  error messages are placed on the appropriate part of the construct
150    --  denoted by New_Id. If Get_Inst is true, then this is a mode conformance
151    --  against a formal access-to-subprogram type so Get_Instance_Of must
152    --  be called.
153
154    procedure Check_Subprogram_Order (N : Node_Id);
155    --  N is the N_Subprogram_Body node for a subprogram. This routine applies
156    --  the alpha ordering rule for N if this ordering requirement applicable.
157
158    procedure Check_Returns
159      (HSS  : Node_Id;
160       Mode : Character;
161       Err  : out Boolean;
162       Proc : Entity_Id := Empty);
163    --  Called to check for missing return statements in a function body, or for
164    --  returns present in a procedure body which has No_Return set. HSS is the
165    --  handled statement sequence for the subprogram body. This procedure
166    --  checks all flow paths to make sure they either have return (Mode = 'F',
167    --  used for functions) or do not have a return (Mode = 'P', used for
168    --  No_Return procedures). The flag Err is set if there are any control
169    --  paths not explicitly terminated by a return in the function case, and is
170    --  True otherwise. Proc is the entity for the procedure case and is used
171    --  in posting the warning message.
172
173    procedure Check_Untagged_Equality (Eq_Op : Entity_Id);
174    --  In Ada 2012, a primitive equality operator on an untagged record type
175    --  must appear before the type is frozen, and have the same visibility as
176    --  that of the type. This procedure checks that this rule is met, and
177    --  otherwise emits an error on the subprogram declaration and a warning
178    --  on the earlier freeze point if it is easy to locate.
179
180    procedure Enter_Overloaded_Entity (S : Entity_Id);
181    --  This procedure makes S, a new overloaded entity, into the first visible
182    --  entity with that name.
183
184    procedure Install_Entity (E : Entity_Id);
185    --  Make single entity visible (used for generic formals as well)
186
187    function Is_Non_Overriding_Operation
188      (Prev_E : Entity_Id;
189       New_E  : Entity_Id) return Boolean;
190    --  Enforce the rule given in 12.3(18): a private operation in an instance
191    --  overrides an inherited operation only if the corresponding operation
192    --  was overriding in the generic. This can happen for primitive operations
193    --  of types derived (in the generic unit) from formal private or formal
194    --  derived types.
195
196    procedure Make_Inequality_Operator (S : Entity_Id);
197    --  Create the declaration for an inequality operator that is implicitly
198    --  created by a user-defined equality operator that yields a boolean.
199
200    procedure May_Need_Actuals (Fun : Entity_Id);
201    --  Flag functions that can be called without parameters, i.e. those that
202    --  have no parameters, or those for which defaults exist for all parameters
203
204    procedure Process_PPCs
205      (N       : Node_Id;
206       Spec_Id : Entity_Id;
207       Body_Id : Entity_Id);
208    --  Called from Analyze[_Generic]_Subprogram_Body to deal with scanning post
209    --  conditions for the body and assembling and inserting the _postconditions
210    --  procedure. N is the node for the subprogram body and Body_Id/Spec_Id are
211    --  the entities for the body and separate spec (if there is no separate
212    --  spec, Spec_Id is Empty). Note that invariants and predicates may also
213    --  provide postconditions, and are also handled in this procedure.
214
215    procedure Set_Formal_Validity (Formal_Id : Entity_Id);
216    --  Formal_Id is an formal parameter entity. This procedure deals with
217    --  setting the proper validity status for this entity, which depends on
218    --  the kind of parameter and the validity checking mode.
219
220    ---------------------------------------------
221    -- Analyze_Abstract_Subprogram_Declaration --
222    ---------------------------------------------
223
224    procedure Analyze_Abstract_Subprogram_Declaration (N : Node_Id) is
225       Designator : constant Entity_Id :=
226                      Analyze_Subprogram_Specification (Specification (N));
227       Scop       : constant Entity_Id := Current_Scope;
228
229    begin
230       Check_SPARK_Restriction ("abstract subprogram is not allowed", N);
231
232       Generate_Definition (Designator);
233       Set_Contract (Designator, Make_Contract (Sloc (Designator)));
234       Set_Is_Abstract_Subprogram (Designator);
235       New_Overloaded_Entity (Designator);
236       Check_Delayed_Subprogram (Designator);
237
238       Set_Categorization_From_Scope (Designator, Scop);
239
240       if Ekind (Scope (Designator)) = E_Protected_Type then
241          Error_Msg_N
242            ("abstract subprogram not allowed in protected type", N);
243
244       --  Issue a warning if the abstract subprogram is neither a dispatching
245       --  operation nor an operation that overrides an inherited subprogram or
246       --  predefined operator, since this most likely indicates a mistake.
247
248       elsif Warn_On_Redundant_Constructs
249         and then not Is_Dispatching_Operation (Designator)
250         and then not Present (Overridden_Operation (Designator))
251         and then (not Is_Operator_Symbol_Name (Chars (Designator))
252                    or else Scop /= Scope (Etype (First_Formal (Designator))))
253       then
254          Error_Msg_N
255            ("?abstract subprogram is not dispatching or overriding", N);
256       end if;
257
258       Generate_Reference_To_Formals (Designator);
259       Check_Eliminated (Designator);
260
261       if Has_Aspects (N) then
262          Analyze_Aspect_Specifications (N, Designator);
263       end if;
264    end Analyze_Abstract_Subprogram_Declaration;
265
266    ---------------------------------
267    -- Analyze_Expression_Function --
268    ---------------------------------
269
270    procedure Analyze_Expression_Function (N : Node_Id) is
271       Loc      : constant Source_Ptr := Sloc (N);
272       LocX     : constant Source_Ptr := Sloc (Expression (N));
273       Def_Id   : constant Entity_Id  := Defining_Entity (Specification (N));
274       New_Body : Node_Id;
275       New_Decl : Node_Id;
276
277       Prev : constant Entity_Id := Current_Entity_In_Scope (Def_Id);
278       --  If the expression is a completion, Prev is the entity whose
279       --  declaration is completed.
280
281    begin
282       --  This is one of the occasions on which we transform the tree during
283       --  semantic analysis. If this is a completion, transform the expression
284       --  function into an equivalent subprogram body, and analyze it.
285
286       --  Expression functions are inlined unconditionally. The back-end will
287       --  determine whether this is possible.
288
289       Inline_Processing_Required := True;
290
291       New_Body :=
292         Make_Subprogram_Body (Loc,
293           Specification              => Specification (N),
294           Declarations               => Empty_List,
295           Handled_Statement_Sequence =>
296             Make_Handled_Sequence_Of_Statements (LocX,
297               Statements => New_List (
298                 Make_Simple_Return_Statement (LocX,
299                   Expression => Expression (N)))));
300
301       if Present (Prev)
302         and then Ekind (Prev) = E_Generic_Function
303       then
304          --  If the expression completes a generic subprogram, we must create a
305          --  separate node for the body, because at instantiation the original
306          --  node of the generic copy must be a generic subprogram body, and
307          --  cannot be a expression function. Otherwise we just rewrite the
308          --  expression with the non-generic body.
309
310          Insert_After (N, New_Body);
311          Rewrite (N, Make_Null_Statement (Loc));
312          Analyze (N);
313          Analyze (New_Body);
314          Set_Is_Inlined (Prev);
315
316       elsif Present (Prev) then
317          Rewrite (N, New_Body);
318          Set_Is_Inlined (Prev);
319          Analyze (N);
320
321       --  If this is not a completion, create both a declaration and a body,
322       --  so that the expression can be inlined whenever possible.
323
324       else
325          New_Decl :=
326            Make_Subprogram_Declaration (Loc,
327              Specification => Specification (N));
328          Rewrite (N, New_Decl);
329          Analyze (N);
330          Set_Is_Inlined (Defining_Entity (New_Decl));
331
332          --  Create new set of formals for specification in body.
333
334          Set_Specification (New_Body,
335            Make_Function_Specification (Loc,
336              Defining_Unit_Name =>
337                Make_Defining_Identifier (Loc, Chars (Defining_Entity (N))),
338              Parameter_Specifications =>
339                Copy_Parameter_List (Defining_Entity (New_Decl)),
340              Result_Definition =>
341                New_Copy_Tree (Result_Definition (Specification (New_Decl)))));
342
343          Insert_After (N, New_Body);
344          Analyze (New_Body);
345       end if;
346    end Analyze_Expression_Function;
347
348    ----------------------------------------
349    -- Analyze_Extended_Return_Statement  --
350    ----------------------------------------
351
352    procedure Analyze_Extended_Return_Statement (N : Node_Id) is
353    begin
354       Analyze_Return_Statement (N);
355    end Analyze_Extended_Return_Statement;
356
357    ----------------------------
358    -- Analyze_Function_Call  --
359    ----------------------------
360
361    procedure Analyze_Function_Call (N : Node_Id) is
362       P       : constant Node_Id := Name (N);
363       Actuals : constant List_Id := Parameter_Associations (N);
364       Actual  : Node_Id;
365
366    begin
367       Analyze (P);
368
369       --  A call of the form A.B (X) may be an Ada05 call, which is rewritten
370       --  as B (A, X). If the rewriting is successful, the call has been
371       --  analyzed and we just return.
372
373       if Nkind (P) = N_Selected_Component
374         and then Name (N) /= P
375         and then Is_Rewrite_Substitution (N)
376         and then Present (Etype (N))
377       then
378          return;
379       end if;
380
381       --  If error analyzing name, then set Any_Type as result type and return
382
383       if Etype (P) = Any_Type then
384          Set_Etype (N, Any_Type);
385          return;
386       end if;
387
388       --  Otherwise analyze the parameters
389
390       if Present (Actuals) then
391          Actual := First (Actuals);
392          while Present (Actual) loop
393             Analyze (Actual);
394             Check_Parameterless_Call (Actual);
395             Next (Actual);
396          end loop;
397       end if;
398
399       Analyze_Call (N);
400    end Analyze_Function_Call;
401
402    -----------------------------
403    -- Analyze_Function_Return --
404    -----------------------------
405
406    procedure Analyze_Function_Return (N : Node_Id) is
407       Loc        : constant Source_Ptr  := Sloc (N);
408       Stm_Entity : constant Entity_Id   := Return_Statement_Entity (N);
409       Scope_Id   : constant Entity_Id   := Return_Applies_To (Stm_Entity);
410
411       R_Type : constant Entity_Id := Etype (Scope_Id);
412       --  Function result subtype
413
414       procedure Check_Limited_Return (Expr : Node_Id);
415       --  Check the appropriate (Ada 95 or Ada 2005) rules for returning
416       --  limited types. Used only for simple return statements.
417       --  Expr is the expression returned.
418
419       procedure Check_Return_Subtype_Indication (Obj_Decl : Node_Id);
420       --  Check that the return_subtype_indication properly matches the result
421       --  subtype of the function, as required by RM-6.5(5.1/2-5.3/2).
422
423       --------------------------
424       -- Check_Limited_Return --
425       --------------------------
426
427       procedure Check_Limited_Return (Expr : Node_Id) is
428       begin
429          --  Ada 2005 (AI-318-02): Return-by-reference types have been
430          --  removed and replaced by anonymous access results. This is an
431          --  incompatibility with Ada 95. Not clear whether this should be
432          --  enforced yet or perhaps controllable with special switch. ???
433
434          if Is_Limited_Type (R_Type)
435            and then Comes_From_Source (N)
436            and then not In_Instance_Body
437            and then not OK_For_Limited_Init_In_05 (R_Type, Expr)
438          then
439             --  Error in Ada 2005
440
441             if Ada_Version >= Ada_2005
442               and then not Debug_Flag_Dot_L
443               and then not GNAT_Mode
444             then
445                Error_Msg_N
446                  ("(Ada 2005) cannot copy object of a limited type " &
447                   "(RM-2005 6.5(5.5/2))", Expr);
448
449                if Is_Immutably_Limited_Type (R_Type) then
450                   Error_Msg_N
451                     ("\return by reference not permitted in Ada 2005", Expr);
452                end if;
453
454             --  Warn in Ada 95 mode, to give folks a heads up about this
455             --  incompatibility.
456
457             --  In GNAT mode, this is just a warning, to allow it to be
458             --  evilly turned off. Otherwise it is a real error.
459
460             --  In a generic context, simplify the warning because it makes
461             --  no sense to discuss pass-by-reference or copy.
462
463             elsif Warn_On_Ada_2005_Compatibility or GNAT_Mode then
464                if Inside_A_Generic then
465                   Error_Msg_N
466                     ("return of limited object not permitted in Ada2005 "
467                      & "(RM-2005 6.5(5.5/2))?", Expr);
468
469                elsif Is_Immutably_Limited_Type (R_Type) then
470                   Error_Msg_N
471                     ("return by reference not permitted in Ada 2005 "
472                      & "(RM-2005 6.5(5.5/2))?", Expr);
473                else
474                   Error_Msg_N
475                     ("cannot copy object of a limited type in Ada 2005 "
476                      & "(RM-2005 6.5(5.5/2))?", Expr);
477                end if;
478
479             --  Ada 95 mode, compatibility warnings disabled
480
481             else
482                return; --  skip continuation messages below
483             end if;
484
485             if not Inside_A_Generic then
486                Error_Msg_N
487                  ("\consider switching to return of access type", Expr);
488                Explain_Limited_Type (R_Type, Expr);
489             end if;
490          end if;
491       end Check_Limited_Return;
492
493       -------------------------------------
494       -- Check_Return_Subtype_Indication --
495       -------------------------------------
496
497       procedure Check_Return_Subtype_Indication (Obj_Decl : Node_Id) is
498          Return_Obj : constant Node_Id   := Defining_Identifier (Obj_Decl);
499
500          R_Stm_Type : constant Entity_Id := Etype (Return_Obj);
501          --  Subtype given in the extended return statement (must match R_Type)
502
503          Subtype_Ind : constant Node_Id :=
504                          Object_Definition (Original_Node (Obj_Decl));
505
506          R_Type_Is_Anon_Access :
507            constant Boolean :=
508              Ekind (R_Type) = E_Anonymous_Access_Subprogram_Type
509                or else
510              Ekind (R_Type) = E_Anonymous_Access_Protected_Subprogram_Type
511                or else
512              Ekind (R_Type) = E_Anonymous_Access_Type;
513          --  True if return type of the function is an anonymous access type
514          --  Can't we make Is_Anonymous_Access_Type in einfo ???
515
516          R_Stm_Type_Is_Anon_Access :
517            constant Boolean :=
518              Ekind (R_Stm_Type) = E_Anonymous_Access_Subprogram_Type
519                or else
520              Ekind (R_Stm_Type) = E_Anonymous_Access_Protected_Subprogram_Type
521                or else
522              Ekind (R_Stm_Type) = E_Anonymous_Access_Type;
523          --  True if type of the return object is an anonymous access type
524
525       begin
526          --  First, avoid cascaded errors
527
528          if Error_Posted (Obj_Decl) or else Error_Posted (Subtype_Ind) then
529             return;
530          end if;
531
532          --  "return access T" case; check that the return statement also has
533          --  "access T", and that the subtypes statically match:
534          --   if this is an access to subprogram the signatures must match.
535
536          if R_Type_Is_Anon_Access then
537             if R_Stm_Type_Is_Anon_Access then
538                if
539                  Ekind (Designated_Type (R_Stm_Type)) /= E_Subprogram_Type
540                then
541                   if Base_Type (Designated_Type (R_Stm_Type)) /=
542                      Base_Type (Designated_Type (R_Type))
543                     or else not Subtypes_Statically_Match (R_Stm_Type, R_Type)
544                   then
545                      Error_Msg_N
546                       ("subtype must statically match function result subtype",
547                        Subtype_Mark (Subtype_Ind));
548                   end if;
549
550                else
551                   --  For two anonymous access to subprogram types, the
552                   --  types themselves must be type conformant.
553
554                   if not Conforming_Types
555                     (R_Stm_Type, R_Type, Fully_Conformant)
556                   then
557                      Error_Msg_N
558                       ("subtype must statically match function result subtype",
559                          Subtype_Ind);
560                   end if;
561                end if;
562
563             else
564                Error_Msg_N ("must use anonymous access type", Subtype_Ind);
565             end if;
566
567          --  If the return object is of an anonymous access type, then report
568          --  an error if the function's result type is not also anonymous.
569
570          elsif R_Stm_Type_Is_Anon_Access
571            and then not R_Type_Is_Anon_Access
572          then
573             Error_Msg_N ("anonymous access not allowed for function with " &
574                          "named access result", Subtype_Ind);
575
576          --  Subtype indication case: check that the return object's type is
577          --  covered by the result type, and that the subtypes statically match
578          --  when the result subtype is constrained. Also handle record types
579          --  with unknown discriminants for which we have built the underlying
580          --  record view. Coverage is needed to allow specific-type return
581          --  objects when the result type is class-wide (see AI05-32).
582
583          elsif Covers (Base_Type (R_Type), Base_Type (R_Stm_Type))
584            or else (Is_Underlying_Record_View (Base_Type (R_Stm_Type))
585                      and then
586                        Covers
587                          (Base_Type (R_Type),
588                           Underlying_Record_View (Base_Type (R_Stm_Type))))
589          then
590             --  A null exclusion may be present on the return type, on the
591             --  function specification, on the object declaration or on the
592             --  subtype itself.
593
594             if Is_Access_Type (R_Type)
595               and then
596                (Can_Never_Be_Null (R_Type)
597                  or else Null_Exclusion_Present (Parent (Scope_Id))) /=
598                                               Can_Never_Be_Null (R_Stm_Type)
599             then
600                Error_Msg_N
601                  ("subtype must statically match function result subtype",
602                   Subtype_Ind);
603             end if;
604
605             --  AI05-103: for elementary types, subtypes must statically match
606
607             if Is_Constrained (R_Type)
608               or else Is_Access_Type (R_Type)
609             then
610                if not Subtypes_Statically_Match (R_Stm_Type, R_Type) then
611                   Error_Msg_N
612                     ("subtype must statically match function result subtype",
613                      Subtype_Ind);
614                end if;
615             end if;
616
617          elsif Etype (Base_Type (R_Type)) = R_Stm_Type
618            and then Is_Null_Extension (Base_Type (R_Type))
619          then
620             null;
621
622          else
623             Error_Msg_N
624               ("wrong type for return_subtype_indication", Subtype_Ind);
625          end if;
626       end Check_Return_Subtype_Indication;
627
628       ---------------------
629       -- Local Variables --
630       ---------------------
631
632       Expr : Node_Id;
633
634    --  Start of processing for Analyze_Function_Return
635
636    begin
637       Set_Return_Present (Scope_Id);
638
639       if Nkind (N) = N_Simple_Return_Statement then
640          Expr := Expression (N);
641
642          --  Guard against a malformed expression. The parser may have tried to
643          --  recover but the node is not analyzable.
644
645          if Nkind (Expr) = N_Error then
646             Set_Etype (Expr, Any_Type);
647             Expander_Mode_Save_And_Set (False);
648             return;
649
650          else
651             --  The resolution of a controlled [extension] aggregate associated
652             --  with a return statement creates a temporary which needs to be
653             --  finalized on function exit. Wrap the return statement inside a
654             --  block so that the finalization machinery can detect this case.
655             --  This early expansion is done only when the return statement is
656             --  not part of a handled sequence of statements.
657
658             if Nkind_In (Expr, N_Aggregate,
659                                N_Extension_Aggregate)
660               and then Needs_Finalization (R_Type)
661               and then Nkind (Parent (N)) /= N_Handled_Sequence_Of_Statements
662             then
663                Rewrite (N,
664                  Make_Block_Statement (Loc,
665                    Handled_Statement_Sequence =>
666                      Make_Handled_Sequence_Of_Statements (Loc,
667                        Statements => New_List (Relocate_Node (N)))));
668
669                Analyze (N);
670                return;
671             end if;
672
673             Analyze_And_Resolve (Expr, R_Type);
674             Check_Limited_Return (Expr);
675          end if;
676
677          --  RETURN only allowed in SPARK as the last statement in function
678
679          if Nkind (Parent (N)) /= N_Handled_Sequence_Of_Statements
680            and then
681              (Nkind (Parent (Parent (N))) /= N_Subprogram_Body
682                or else Present (Next (N)))
683          then
684             Check_SPARK_Restriction
685               ("RETURN should be the last statement in function", N);
686          end if;
687
688       else
689          Check_SPARK_Restriction ("extended RETURN is not allowed", N);
690
691          --  Analyze parts specific to extended_return_statement:
692
693          declare
694             Obj_Decl : constant Node_Id :=
695                          Last (Return_Object_Declarations (N));
696
697             HSS : constant Node_Id := Handled_Statement_Sequence (N);
698
699          begin
700             Expr := Expression (Obj_Decl);
701
702             --  Note: The check for OK_For_Limited_Init will happen in
703             --  Analyze_Object_Declaration; we treat it as a normal
704             --  object declaration.
705
706             Set_Is_Return_Object (Defining_Identifier (Obj_Decl));
707             Analyze (Obj_Decl);
708
709             Check_Return_Subtype_Indication (Obj_Decl);
710
711             if Present (HSS) then
712                Analyze (HSS);
713
714                if Present (Exception_Handlers (HSS)) then
715
716                   --  ???Has_Nested_Block_With_Handler needs to be set.
717                   --  Probably by creating an actual N_Block_Statement.
718                   --  Probably in Expand.
719
720                   null;
721                end if;
722             end if;
723
724             --  Mark the return object as referenced, since the return is an
725             --  implicit reference of the object.
726
727             Set_Referenced (Defining_Identifier (Obj_Decl));
728
729             Check_References (Stm_Entity);
730          end;
731       end if;
732
733       --  Case of Expr present
734
735       if Present (Expr)
736
737          --  Defend against previous errors
738
739         and then Nkind (Expr) /= N_Empty
740         and then Present (Etype (Expr))
741       then
742          --  Apply constraint check. Note that this is done before the implicit
743          --  conversion of the expression done for anonymous access types to
744          --  ensure correct generation of the null-excluding check associated
745          --  with null-excluding expressions found in return statements.
746
747          Apply_Constraint_Check (Expr, R_Type);
748
749          --  Ada 2005 (AI-318-02): When the result type is an anonymous access
750          --  type, apply an implicit conversion of the expression to that type
751          --  to force appropriate static and run-time accessibility checks.
752
753          if Ada_Version >= Ada_2005
754            and then Ekind (R_Type) = E_Anonymous_Access_Type
755          then
756             Rewrite (Expr, Convert_To (R_Type, Relocate_Node (Expr)));
757             Analyze_And_Resolve (Expr, R_Type);
758          end if;
759
760          --  If the result type is class-wide, then check that the return
761          --  expression's type is not declared at a deeper level than the
762          --  function (RM05-6.5(5.6/2)).
763
764          if Ada_Version >= Ada_2005
765            and then Is_Class_Wide_Type (R_Type)
766          then
767             if Type_Access_Level (Etype (Expr)) >
768                  Subprogram_Access_Level (Scope_Id)
769             then
770                Error_Msg_N
771                  ("level of return expression type is deeper than " &
772                   "class-wide function!", Expr);
773             end if;
774          end if;
775
776          --  Check incorrect use of dynamically tagged expression
777
778          if Is_Tagged_Type (R_Type) then
779             Check_Dynamically_Tagged_Expression
780               (Expr => Expr,
781                Typ  => R_Type,
782                Related_Nod => N);
783          end if;
784
785          --  ??? A real run-time accessibility check is needed in cases
786          --  involving dereferences of access parameters. For now we just
787          --  check the static cases.
788
789          if (Ada_Version < Ada_2005 or else Debug_Flag_Dot_L)
790            and then Is_Immutably_Limited_Type (Etype (Scope_Id))
791            and then Object_Access_Level (Expr) >
792                       Subprogram_Access_Level (Scope_Id)
793          then
794
795             --  Suppress the message in a generic, where the rewriting
796             --  is irrelevant.
797
798             if Inside_A_Generic then
799                null;
800
801             else
802                Rewrite (N,
803                  Make_Raise_Program_Error (Loc,
804                    Reason => PE_Accessibility_Check_Failed));
805                Analyze (N);
806
807                Error_Msg_N
808                  ("cannot return a local value by reference?", N);
809                Error_Msg_NE
810                  ("\& will be raised at run time?",
811                    N, Standard_Program_Error);
812             end if;
813          end if;
814
815          if Known_Null (Expr)
816            and then Nkind (Parent (Scope_Id)) = N_Function_Specification
817            and then Null_Exclusion_Present (Parent (Scope_Id))
818          then
819             Apply_Compile_Time_Constraint_Error
820               (N      => Expr,
821                Msg    => "(Ada 2005) null not allowed for "
822                          & "null-excluding return?",
823                Reason => CE_Null_Not_Allowed);
824          end if;
825
826          --  Apply checks suggested by AI05-0144 (dangerous order dependence)
827
828          Check_Order_Dependence;
829       end if;
830    end Analyze_Function_Return;
831
832    -------------------------------------
833    -- Analyze_Generic_Subprogram_Body --
834    -------------------------------------
835
836    procedure Analyze_Generic_Subprogram_Body
837      (N      : Node_Id;
838       Gen_Id : Entity_Id)
839    is
840       Gen_Decl : constant Node_Id     := Unit_Declaration_Node (Gen_Id);
841       Kind     : constant Entity_Kind := Ekind (Gen_Id);
842       Body_Id  : Entity_Id;
843       New_N    : Node_Id;
844       Spec     : Node_Id;
845
846    begin
847       --  Copy body and disable expansion while analyzing the generic For a
848       --  stub, do not copy the stub (which would load the proper body), this
849       --  will be done when the proper body is analyzed.
850
851       if Nkind (N) /= N_Subprogram_Body_Stub then
852          New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
853          Rewrite (N, New_N);
854          Start_Generic;
855       end if;
856
857       Spec := Specification (N);
858
859       --  Within the body of the generic, the subprogram is callable, and
860       --  behaves like the corresponding non-generic unit.
861
862       Body_Id := Defining_Entity (Spec);
863
864       if Kind = E_Generic_Procedure
865         and then Nkind (Spec) /= N_Procedure_Specification
866       then
867          Error_Msg_N ("invalid body for generic procedure ", Body_Id);
868          return;
869
870       elsif Kind = E_Generic_Function
871         and then Nkind (Spec) /= N_Function_Specification
872       then
873          Error_Msg_N ("invalid body for generic function ", Body_Id);
874          return;
875       end if;
876
877       Set_Corresponding_Body (Gen_Decl, Body_Id);
878
879       if Has_Completion (Gen_Id)
880         and then Nkind (Parent (N)) /= N_Subunit
881       then
882          Error_Msg_N ("duplicate generic body", N);
883          return;
884       else
885          Set_Has_Completion (Gen_Id);
886       end if;
887
888       if Nkind (N) = N_Subprogram_Body_Stub then
889          Set_Ekind (Defining_Entity (Specification (N)), Kind);
890       else
891          Set_Corresponding_Spec (N, Gen_Id);
892       end if;
893
894       if Nkind (Parent (N)) = N_Compilation_Unit then
895          Set_Cunit_Entity (Current_Sem_Unit, Defining_Entity (N));
896       end if;
897
898       --  Make generic parameters immediately visible in the body. They are
899       --  needed to process the formals declarations. Then make the formals
900       --  visible in a separate step.
901
902       Push_Scope (Gen_Id);
903
904       declare
905          E         : Entity_Id;
906          First_Ent : Entity_Id;
907
908       begin
909          First_Ent := First_Entity (Gen_Id);
910
911          E := First_Ent;
912          while Present (E) and then not Is_Formal (E) loop
913             Install_Entity (E);
914             Next_Entity (E);
915          end loop;
916
917          Set_Use (Generic_Formal_Declarations (Gen_Decl));
918
919          --  Now generic formals are visible, and the specification can be
920          --  analyzed, for subsequent conformance check.
921
922          Body_Id := Analyze_Subprogram_Specification (Spec);
923
924          --  Make formal parameters visible
925
926          if Present (E) then
927
928             --  E is the first formal parameter, we loop through the formals
929             --  installing them so that they will be visible.
930
931             Set_First_Entity (Gen_Id, E);
932             while Present (E) loop
933                Install_Entity (E);
934                Next_Formal (E);
935             end loop;
936          end if;
937
938          --  Visible generic entity is callable within its own body
939
940          Set_Ekind          (Gen_Id,  Ekind (Body_Id));
941          Set_Ekind          (Body_Id, E_Subprogram_Body);
942          Set_Convention     (Body_Id, Convention (Gen_Id));
943          Set_Is_Obsolescent (Body_Id, Is_Obsolescent (Gen_Id));
944          Set_Scope          (Body_Id, Scope (Gen_Id));
945          Check_Fully_Conformant (Body_Id, Gen_Id, Body_Id);
946
947          if Nkind (N) = N_Subprogram_Body_Stub then
948
949             --  No body to analyze, so restore state of generic unit
950
951             Set_Ekind (Gen_Id, Kind);
952             Set_Ekind (Body_Id, Kind);
953
954             if Present (First_Ent) then
955                Set_First_Entity (Gen_Id, First_Ent);
956             end if;
957
958             End_Scope;
959             return;
960          end if;
961
962          --  If this is a compilation unit, it must be made visible explicitly,
963          --  because the compilation of the declaration, unlike other library
964          --  unit declarations, does not. If it is not a unit, the following
965          --  is redundant but harmless.
966
967          Set_Is_Immediately_Visible (Gen_Id);
968          Reference_Body_Formals (Gen_Id, Body_Id);
969
970          if Is_Child_Unit (Gen_Id) then
971             Generate_Reference (Gen_Id, Scope (Gen_Id), 'k', False);
972          end if;
973
974          Set_Actual_Subtypes (N, Current_Scope);
975
976          --  Deal with preconditions and postconditions. In formal verification
977          --  mode, we keep pre- and postconditions attached to entities rather
978          --  than inserted in the code, in order to facilitate a distinct
979          --  treatment for them.
980
981          if not Alfa_Mode then
982             Process_PPCs (N, Gen_Id, Body_Id);
983          end if;
984
985          --  If the generic unit carries pre- or post-conditions, copy them
986          --  to the original generic tree, so that they are properly added
987          --  to any instantiation.
988
989          declare
990             Orig : constant Node_Id := Original_Node (N);
991             Cond : Node_Id;
992
993          begin
994             Cond := First (Declarations (N));
995             while Present (Cond) loop
996                if Nkind (Cond) = N_Pragma
997                  and then Pragma_Name (Cond) = Name_Check
998                then
999                   Prepend (New_Copy_Tree (Cond), Declarations (Orig));
1000
1001                elsif Nkind (Cond) = N_Pragma
1002                  and then Pragma_Name (Cond) = Name_Postcondition
1003                then
1004                   Set_Ekind (Defining_Entity (Orig), Ekind (Gen_Id));
1005                   Prepend (New_Copy_Tree (Cond), Declarations (Orig));
1006                else
1007                   exit;
1008                end if;
1009
1010                Next (Cond);
1011             end loop;
1012          end;
1013
1014          Analyze_Declarations (Declarations (N));
1015          Check_Completion;
1016          Analyze (Handled_Statement_Sequence (N));
1017
1018          Save_Global_References (Original_Node (N));
1019
1020          --  Prior to exiting the scope, include generic formals again (if any
1021          --  are present) in the set of local entities.
1022
1023          if Present (First_Ent) then
1024             Set_First_Entity (Gen_Id, First_Ent);
1025          end if;
1026
1027          Check_References (Gen_Id);
1028       end;
1029
1030       Process_End_Label (Handled_Statement_Sequence (N), 't', Current_Scope);
1031       End_Scope;
1032       Check_Subprogram_Order (N);
1033
1034       --  Outside of its body, unit is generic again
1035
1036       Set_Ekind (Gen_Id, Kind);
1037       Generate_Reference (Gen_Id, Body_Id, 'b', Set_Ref => False);
1038
1039       if Style_Check then
1040          Style.Check_Identifier (Body_Id, Gen_Id);
1041       end if;
1042
1043       End_Generic;
1044    end Analyze_Generic_Subprogram_Body;
1045
1046    -----------------------------
1047    -- Analyze_Operator_Symbol --
1048    -----------------------------
1049
1050    --  An operator symbol such as "+" or "and" may appear in context where the
1051    --  literal denotes an entity name, such as "+"(x, y) or in context when it
1052    --  is just a string, as in (conjunction = "or"). In these cases the parser
1053    --  generates this node, and the semantics does the disambiguation. Other
1054    --  such case are actuals in an instantiation, the generic unit in an
1055    --  instantiation, and pragma arguments.
1056
1057    procedure Analyze_Operator_Symbol (N : Node_Id) is
1058       Par : constant Node_Id := Parent (N);
1059
1060    begin
1061       if        (Nkind (Par) = N_Function_Call
1062                    and then N = Name (Par))
1063         or else  Nkind (Par) = N_Function_Instantiation
1064         or else (Nkind (Par) = N_Indexed_Component
1065                    and then N = Prefix (Par))
1066         or else (Nkind (Par) = N_Pragma_Argument_Association
1067                    and then not Is_Pragma_String_Literal (Par))
1068         or else  Nkind (Par) = N_Subprogram_Renaming_Declaration
1069         or else (Nkind (Par) = N_Attribute_Reference
1070                   and then Attribute_Name (Par) /= Name_Value)
1071       then
1072          Find_Direct_Name (N);
1073
1074       else
1075          Change_Operator_Symbol_To_String_Literal (N);
1076          Analyze (N);
1077       end if;
1078    end Analyze_Operator_Symbol;
1079
1080    -----------------------------------
1081    -- Analyze_Parameter_Association --
1082    -----------------------------------
1083
1084    procedure Analyze_Parameter_Association (N : Node_Id) is
1085    begin
1086       Analyze (Explicit_Actual_Parameter (N));
1087    end Analyze_Parameter_Association;
1088
1089    ----------------------------
1090    -- Analyze_Procedure_Call --
1091    ----------------------------
1092
1093    procedure Analyze_Procedure_Call (N : Node_Id) is
1094       Loc     : constant Source_Ptr := Sloc (N);
1095       P       : constant Node_Id    := Name (N);
1096       Actuals : constant List_Id    := Parameter_Associations (N);
1097       Actual  : Node_Id;
1098       New_N   : Node_Id;
1099
1100       procedure Analyze_Call_And_Resolve;
1101       --  Do Analyze and Resolve calls for procedure call
1102       --  At end, check illegal order dependence.
1103
1104       ------------------------------
1105       -- Analyze_Call_And_Resolve --
1106       ------------------------------
1107
1108       procedure Analyze_Call_And_Resolve is
1109       begin
1110          if Nkind (N) = N_Procedure_Call_Statement then
1111             Analyze_Call (N);
1112             Resolve (N, Standard_Void_Type);
1113
1114             --  Apply checks suggested by AI05-0144
1115
1116             Check_Order_Dependence;
1117
1118          else
1119             Analyze (N);
1120          end if;
1121       end Analyze_Call_And_Resolve;
1122
1123    --  Start of processing for Analyze_Procedure_Call
1124
1125    begin
1126       --  The syntactic construct: PREFIX ACTUAL_PARAMETER_PART can denote
1127       --  a procedure call or an entry call. The prefix may denote an access
1128       --  to subprogram type, in which case an implicit dereference applies.
1129       --  If the prefix is an indexed component (without implicit dereference)
1130       --  then the construct denotes a call to a member of an entire family.
1131       --  If the prefix is a simple name, it may still denote a call to a
1132       --  parameterless member of an entry family. Resolution of these various
1133       --  interpretations is delicate.
1134
1135       Analyze (P);
1136
1137       --  If this is a call of the form Obj.Op, the call may have been
1138       --  analyzed and possibly rewritten into a block, in which case
1139       --  we are done.
1140
1141       if Analyzed (N) then
1142          return;
1143       end if;
1144
1145       --  If there is an error analyzing the name (which may have been
1146       --  rewritten if the original call was in prefix notation) then error
1147       --  has been emitted already, mark node and return.
1148
1149       if Error_Posted (N)
1150         or else Etype (Name (N)) = Any_Type
1151       then
1152          Set_Etype (N, Any_Type);
1153          return;
1154       end if;
1155
1156       --  Otherwise analyze the parameters
1157
1158       if Present (Actuals) then
1159          Actual := First (Actuals);
1160
1161          while Present (Actual) loop
1162             Analyze (Actual);
1163             Check_Parameterless_Call (Actual);
1164             Next (Actual);
1165          end loop;
1166       end if;
1167
1168       --  Special processing for Elab_Spec, Elab_Body and Elab_Subp_Body calls
1169
1170       if Nkind (P) = N_Attribute_Reference
1171         and then (Attribute_Name (P) = Name_Elab_Spec
1172                    or else Attribute_Name (P) = Name_Elab_Body
1173                    or else Attribute_Name (P) = Name_Elab_Subp_Body)
1174       then
1175          if Present (Actuals) then
1176             Error_Msg_N
1177               ("no parameters allowed for this call", First (Actuals));
1178             return;
1179          end if;
1180
1181          Set_Etype (N, Standard_Void_Type);
1182          Set_Analyzed (N);
1183
1184       elsif Is_Entity_Name (P)
1185         and then Is_Record_Type (Etype (Entity (P)))
1186         and then Remote_AST_I_Dereference (P)
1187       then
1188          return;
1189
1190       elsif Is_Entity_Name (P)
1191         and then Ekind (Entity (P)) /= E_Entry_Family
1192       then
1193          if Is_Access_Type (Etype (P))
1194            and then Ekind (Designated_Type (Etype (P))) = E_Subprogram_Type
1195            and then No (Actuals)
1196            and then Comes_From_Source (N)
1197          then
1198             Error_Msg_N ("missing explicit dereference in call", N);
1199          end if;
1200
1201          Analyze_Call_And_Resolve;
1202
1203       --  If the prefix is the simple name of an entry family, this is
1204       --  a parameterless call from within the task body itself.
1205
1206       elsif Is_Entity_Name (P)
1207         and then Nkind (P) = N_Identifier
1208         and then Ekind (Entity (P)) = E_Entry_Family
1209         and then Present (Actuals)
1210         and then No (Next (First (Actuals)))
1211       then
1212          --  Can be call to parameterless entry family. What appears to be the
1213          --  sole argument is in fact the entry index. Rewrite prefix of node
1214          --  accordingly. Source representation is unchanged by this
1215          --  transformation.
1216
1217          New_N :=
1218            Make_Indexed_Component (Loc,
1219              Prefix =>
1220                Make_Selected_Component (Loc,
1221                  Prefix => New_Occurrence_Of (Scope (Entity (P)), Loc),
1222                  Selector_Name => New_Occurrence_Of (Entity (P), Loc)),
1223              Expressions => Actuals);
1224          Set_Name (N, New_N);
1225          Set_Etype (New_N, Standard_Void_Type);
1226          Set_Parameter_Associations (N, No_List);
1227          Analyze_Call_And_Resolve;
1228
1229       elsif Nkind (P) = N_Explicit_Dereference then
1230          if Ekind (Etype (P)) = E_Subprogram_Type then
1231             Analyze_Call_And_Resolve;
1232          else
1233             Error_Msg_N ("expect access to procedure in call", P);
1234          end if;
1235
1236       --  The name can be a selected component or an indexed component that
1237       --  yields an access to subprogram. Such a prefix is legal if the call
1238       --  has parameter associations.
1239
1240       elsif Is_Access_Type (Etype (P))
1241         and then Ekind (Designated_Type (Etype (P))) = E_Subprogram_Type
1242       then
1243          if Present (Actuals) then
1244             Analyze_Call_And_Resolve;
1245          else
1246             Error_Msg_N ("missing explicit dereference in call ", N);
1247          end if;
1248
1249       --  If not an access to subprogram, then the prefix must resolve to the
1250       --  name of an entry, entry family, or protected operation.
1251
1252       --  For the case of a simple entry call, P is a selected component where
1253       --  the prefix is the task and the selector name is the entry. A call to
1254       --  a protected procedure will have the same syntax. If the protected
1255       --  object contains overloaded operations, the entity may appear as a
1256       --  function, the context will select the operation whose type is Void.
1257
1258       elsif Nkind (P) = N_Selected_Component
1259         and then (Ekind (Entity (Selector_Name (P))) = E_Entry
1260                     or else
1261                   Ekind (Entity (Selector_Name (P))) = E_Procedure
1262                     or else
1263                   Ekind (Entity (Selector_Name (P))) = E_Function)
1264       then
1265          Analyze_Call_And_Resolve;
1266
1267       elsif Nkind (P) = N_Selected_Component
1268         and then Ekind (Entity (Selector_Name (P))) = E_Entry_Family
1269         and then Present (Actuals)
1270         and then No (Next (First (Actuals)))
1271       then
1272          --  Can be call to parameterless entry family. What appears to be the
1273          --  sole argument is in fact the entry index. Rewrite prefix of node
1274          --  accordingly. Source representation is unchanged by this
1275          --  transformation.
1276
1277          New_N :=
1278            Make_Indexed_Component (Loc,
1279              Prefix => New_Copy (P),
1280              Expressions => Actuals);
1281          Set_Name (N, New_N);
1282          Set_Etype (New_N, Standard_Void_Type);
1283          Set_Parameter_Associations (N, No_List);
1284          Analyze_Call_And_Resolve;
1285
1286       --  For the case of a reference to an element of an entry family, P is
1287       --  an indexed component whose prefix is a selected component (task and
1288       --  entry family), and whose index is the entry family index.
1289
1290       elsif Nkind (P) = N_Indexed_Component
1291         and then Nkind (Prefix (P)) = N_Selected_Component
1292         and then Ekind (Entity (Selector_Name (Prefix (P)))) = E_Entry_Family
1293       then
1294          Analyze_Call_And_Resolve;
1295
1296       --  If the prefix is the name of an entry family, it is a call from
1297       --  within the task body itself.
1298
1299       elsif Nkind (P) = N_Indexed_Component
1300         and then Nkind (Prefix (P)) = N_Identifier
1301         and then Ekind (Entity (Prefix (P))) = E_Entry_Family
1302       then
1303          New_N :=
1304            Make_Selected_Component (Loc,
1305              Prefix => New_Occurrence_Of (Scope (Entity (Prefix (P))), Loc),
1306              Selector_Name => New_Occurrence_Of (Entity (Prefix (P)), Loc));
1307          Rewrite (Prefix (P), New_N);
1308          Analyze (P);
1309          Analyze_Call_And_Resolve;
1310
1311       --  Anything else is an error
1312
1313       else
1314          Error_Msg_N ("invalid procedure or entry call", N);
1315       end if;
1316    end Analyze_Procedure_Call;
1317
1318    ------------------------------
1319    -- Analyze_Return_Statement --
1320    ------------------------------
1321
1322    procedure Analyze_Return_Statement (N : Node_Id) is
1323
1324       pragma Assert (Nkind_In (N, N_Simple_Return_Statement,
1325                                   N_Extended_Return_Statement));
1326
1327       Returns_Object : constant Boolean :=
1328                          Nkind (N) = N_Extended_Return_Statement
1329                            or else
1330                             (Nkind (N) = N_Simple_Return_Statement
1331                               and then Present (Expression (N)));
1332       --  True if we're returning something; that is, "return <expression>;"
1333       --  or "return Result : T [:= ...]". False for "return;". Used for error
1334       --  checking: If Returns_Object is True, N should apply to a function
1335       --  body; otherwise N should apply to a procedure body, entry body,
1336       --  accept statement, or extended return statement.
1337
1338       function Find_What_It_Applies_To return Entity_Id;
1339       --  Find the entity representing the innermost enclosing body, accept
1340       --  statement, or extended return statement. If the result is a callable
1341       --  construct or extended return statement, then this will be the value
1342       --  of the Return_Applies_To attribute. Otherwise, the program is
1343       --  illegal. See RM-6.5(4/2).
1344
1345       -----------------------------
1346       -- Find_What_It_Applies_To --
1347       -----------------------------
1348
1349       function Find_What_It_Applies_To return Entity_Id is
1350          Result : Entity_Id := Empty;
1351
1352       begin
1353          --  Loop outward through the Scope_Stack, skipping blocks, loops,
1354          --  and postconditions.
1355
1356          for J in reverse 0 .. Scope_Stack.Last loop
1357             Result := Scope_Stack.Table (J).Entity;
1358             exit when not Ekind_In (Result, E_Block, E_Loop)
1359               and then Chars (Result) /= Name_uPostconditions;
1360          end loop;
1361
1362          pragma Assert (Present (Result));
1363          return Result;
1364       end Find_What_It_Applies_To;
1365
1366       --  Local declarations
1367
1368       Scope_Id   : constant Entity_Id   := Find_What_It_Applies_To;
1369       Kind       : constant Entity_Kind := Ekind (Scope_Id);
1370       Loc        : constant Source_Ptr  := Sloc (N);
1371       Stm_Entity : constant Entity_Id   :=
1372                      New_Internal_Entity
1373                        (E_Return_Statement, Current_Scope, Loc, 'R');
1374
1375    --  Start of processing for Analyze_Return_Statement
1376
1377    begin
1378       Set_Return_Statement_Entity (N, Stm_Entity);
1379
1380       Set_Etype (Stm_Entity, Standard_Void_Type);
1381       Set_Return_Applies_To (Stm_Entity, Scope_Id);
1382
1383       --  Place Return entity on scope stack, to simplify enforcement of 6.5
1384       --  (4/2): an inner return statement will apply to this extended return.
1385
1386       if Nkind (N) = N_Extended_Return_Statement then
1387          Push_Scope (Stm_Entity);
1388       end if;
1389
1390       --  Check that pragma No_Return is obeyed. Don't complain about the
1391       --  implicitly-generated return that is placed at the end.
1392
1393       if No_Return (Scope_Id) and then Comes_From_Source (N) then
1394          Error_Msg_N ("RETURN statement not allowed (No_Return)", N);
1395       end if;
1396
1397       --  Warn on any unassigned OUT parameters if in procedure
1398
1399       if Ekind (Scope_Id) = E_Procedure then
1400          Warn_On_Unassigned_Out_Parameter (N, Scope_Id);
1401       end if;
1402
1403       --  Check that functions return objects, and other things do not
1404
1405       if Kind = E_Function or else Kind = E_Generic_Function then
1406          if not Returns_Object then
1407             Error_Msg_N ("missing expression in return from function", N);
1408          end if;
1409
1410       elsif Kind = E_Procedure or else Kind = E_Generic_Procedure then
1411          if Returns_Object then
1412             Error_Msg_N ("procedure cannot return value (use function)", N);
1413          end if;
1414
1415       elsif Kind = E_Entry or else Kind = E_Entry_Family then
1416          if Returns_Object then
1417             if Is_Protected_Type (Scope (Scope_Id)) then
1418                Error_Msg_N ("entry body cannot return value", N);
1419             else
1420                Error_Msg_N ("accept statement cannot return value", N);
1421             end if;
1422          end if;
1423
1424       elsif Kind = E_Return_Statement then
1425
1426          --  We are nested within another return statement, which must be an
1427          --  extended_return_statement.
1428
1429          if Returns_Object then
1430             Error_Msg_N
1431               ("extended_return_statement cannot return value; " &
1432                "use `""RETURN;""`", N);
1433          end if;
1434
1435       else
1436          Error_Msg_N ("illegal context for return statement", N);
1437       end if;
1438
1439       if Ekind_In (Kind, E_Function, E_Generic_Function) then
1440          Analyze_Function_Return (N);
1441
1442       elsif Ekind_In (Kind, E_Procedure, E_Generic_Procedure) then
1443          Set_Return_Present (Scope_Id);
1444       end if;
1445
1446       if Nkind (N) = N_Extended_Return_Statement then
1447          End_Scope;
1448       end if;
1449
1450       Kill_Current_Values (Last_Assignment_Only => True);
1451       Check_Unreachable_Code (N);
1452    end Analyze_Return_Statement;
1453
1454    -------------------------------------
1455    -- Analyze_Simple_Return_Statement --
1456    -------------------------------------
1457
1458    procedure Analyze_Simple_Return_Statement (N : Node_Id) is
1459    begin
1460       if Present (Expression (N)) then
1461          Mark_Coextensions (N, Expression (N));
1462       end if;
1463
1464       Analyze_Return_Statement (N);
1465    end Analyze_Simple_Return_Statement;
1466
1467    -------------------------
1468    -- Analyze_Return_Type --
1469    -------------------------
1470
1471    procedure Analyze_Return_Type (N : Node_Id) is
1472       Designator : constant Entity_Id := Defining_Entity (N);
1473       Typ        : Entity_Id := Empty;
1474
1475    begin
1476       --  Normal case where result definition does not indicate an error
1477
1478       if Result_Definition (N) /= Error then
1479          if Nkind (Result_Definition (N)) = N_Access_Definition then
1480             Check_SPARK_Restriction
1481               ("access result is not allowed", Result_Definition (N));
1482
1483             --  Ada 2005 (AI-254): Handle anonymous access to subprograms
1484
1485             declare
1486                AD : constant Node_Id :=
1487                       Access_To_Subprogram_Definition (Result_Definition (N));
1488             begin
1489                if Present (AD) and then Protected_Present (AD) then
1490                   Typ := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1491                else
1492                   Typ := Access_Definition (N, Result_Definition (N));
1493                end if;
1494             end;
1495
1496             Set_Parent (Typ, Result_Definition (N));
1497             Set_Is_Local_Anonymous_Access (Typ);
1498             Set_Etype (Designator, Typ);
1499
1500             --  Ada 2005 (AI-231): Ensure proper usage of null exclusion
1501
1502             Null_Exclusion_Static_Checks (N);
1503
1504          --  Subtype_Mark case
1505
1506          else
1507             Find_Type (Result_Definition (N));
1508             Typ := Entity (Result_Definition (N));
1509             Set_Etype (Designator, Typ);
1510
1511             --  Unconstrained array as result is not allowed in SPARK
1512
1513             if Is_Array_Type (Typ)
1514               and then not Is_Constrained (Typ)
1515             then
1516                Check_SPARK_Restriction
1517                  ("returning an unconstrained array is not allowed",
1518                   Result_Definition (N));
1519             end if;
1520
1521             --  Ada 2005 (AI-231): Ensure proper usage of null exclusion
1522
1523             Null_Exclusion_Static_Checks (N);
1524
1525             --  If a null exclusion is imposed on the result type, then create
1526             --  a null-excluding itype (an access subtype) and use it as the
1527             --  function's Etype. Note that the null exclusion checks are done
1528             --  right before this, because they don't get applied to types that
1529             --  do not come from source.
1530
1531             if Is_Access_Type (Typ)
1532               and then Null_Exclusion_Present (N)
1533             then
1534                Set_Etype  (Designator,
1535                  Create_Null_Excluding_Itype
1536                   (T           => Typ,
1537                    Related_Nod => N,
1538                    Scope_Id    => Scope (Current_Scope)));
1539
1540                --  The new subtype must be elaborated before use because
1541                --  it is visible outside of the function. However its base
1542                --  type may not be frozen yet, so the reference that will
1543                --  force elaboration must be attached to the freezing of
1544                --  the base type.
1545
1546                --  If the return specification appears on a proper body,
1547                --  the subtype will have been created already on the spec.
1548
1549                if Is_Frozen (Typ) then
1550                   if Nkind (Parent (N)) = N_Subprogram_Body
1551                     and then Nkind (Parent (Parent (N))) = N_Subunit
1552                   then
1553                      null;
1554                   else
1555                      Build_Itype_Reference (Etype (Designator), Parent (N));
1556                   end if;
1557
1558                else
1559                   Ensure_Freeze_Node (Typ);
1560
1561                   declare
1562                      IR : constant Node_Id := Make_Itype_Reference (Sloc (N));
1563                   begin
1564                      Set_Itype (IR, Etype (Designator));
1565                      Append_Freeze_Actions (Typ, New_List (IR));
1566                   end;
1567                end if;
1568
1569             else
1570                Set_Etype (Designator, Typ);
1571             end if;
1572
1573             if Ekind (Typ) = E_Incomplete_Type
1574               and then Is_Value_Type (Typ)
1575             then
1576                null;
1577
1578             elsif Ekind (Typ) = E_Incomplete_Type
1579               or else (Is_Class_Wide_Type (Typ)
1580                          and then
1581                            Ekind (Root_Type (Typ)) = E_Incomplete_Type)
1582             then
1583                --  AI05-0151: Tagged incomplete types are allowed in all formal
1584                --  parts. Untagged incomplete types are not allowed in bodies.
1585
1586                if Ada_Version >= Ada_2012 then
1587                   if Is_Tagged_Type (Typ) then
1588                      null;
1589
1590                   elsif Nkind_In (Parent (Parent (N)),
1591                      N_Accept_Statement,
1592                      N_Entry_Body,
1593                      N_Subprogram_Body)
1594                   then
1595                      Error_Msg_NE
1596                        ("invalid use of untagged incomplete type&",
1597                           Designator, Typ);
1598                   end if;
1599
1600                   --  The type must be completed in the current package. This
1601                   --  is checked at the end of the package declaraton, when
1602                   --  Taft amemdment types are identified.
1603
1604                   if Ekind (Scope (Current_Scope)) = E_Package
1605                     and then In_Private_Part (Scope (Current_Scope))
1606                   then
1607                      Append_Elmt (Designator, Private_Dependents (Typ));
1608                   end if;
1609
1610                else
1611                   Error_Msg_NE
1612                     ("invalid use of incomplete type&", Designator, Typ);
1613                end if;
1614             end if;
1615          end if;
1616
1617       --  Case where result definition does indicate an error
1618
1619       else
1620          Set_Etype (Designator, Any_Type);
1621       end if;
1622    end Analyze_Return_Type;
1623
1624    -----------------------------
1625    -- Analyze_Subprogram_Body --
1626    -----------------------------
1627
1628    procedure Analyze_Subprogram_Body (N : Node_Id) is
1629       Loc       : constant Source_Ptr := Sloc (N);
1630       Body_Spec : constant Node_Id    := Specification (N);
1631       Body_Id   : constant Entity_Id  := Defining_Entity (Body_Spec);
1632
1633    begin
1634       if Debug_Flag_C then
1635          Write_Str ("==> subprogram body ");
1636          Write_Name (Chars (Body_Id));
1637          Write_Str (" from ");
1638          Write_Location (Loc);
1639          Write_Eol;
1640          Indent;
1641       end if;
1642
1643       Trace_Scope (N, Body_Id, " Analyze subprogram: ");
1644
1645       --  The real work is split out into the helper, so it can do "return;"
1646       --  without skipping the debug output:
1647
1648       Analyze_Subprogram_Body_Helper (N);
1649
1650       if Debug_Flag_C then
1651          Outdent;
1652          Write_Str ("<== subprogram body ");
1653          Write_Name (Chars (Body_Id));
1654          Write_Str (" from ");
1655          Write_Location (Loc);
1656          Write_Eol;
1657       end if;
1658    end Analyze_Subprogram_Body;
1659
1660    ------------------------------------
1661    -- Analyze_Subprogram_Body_Helper --
1662    ------------------------------------
1663
1664    --  This procedure is called for regular subprogram bodies, generic bodies,
1665    --  and for subprogram stubs of both kinds. In the case of stubs, only the
1666    --  specification matters, and is used to create a proper declaration for
1667    --  the subprogram, or to perform conformance checks.
1668
1669    procedure Analyze_Subprogram_Body_Helper (N : Node_Id) is
1670       Loc          : constant Source_Ptr := Sloc (N);
1671       Body_Deleted : constant Boolean    := False;
1672       Body_Spec    : constant Node_Id    := Specification (N);
1673       Body_Id      : Entity_Id           := Defining_Entity (Body_Spec);
1674       Prev_Id      : constant Entity_Id  := Current_Entity_In_Scope (Body_Id);
1675       Conformant   : Boolean;
1676       HSS          : Node_Id;
1677       P_Ent        : Entity_Id;
1678       Prot_Typ     : Entity_Id := Empty;
1679       Spec_Id      : Entity_Id;
1680       Spec_Decl    : Node_Id   := Empty;
1681
1682       Last_Real_Spec_Entity : Entity_Id := Empty;
1683       --  When we analyze a separate spec, the entity chain ends up containing
1684       --  the formals, as well as any itypes generated during analysis of the
1685       --  default expressions for parameters, or the arguments of associated
1686       --  precondition/postcondition pragmas (which are analyzed in the context
1687       --  of the spec since they have visibility on formals).
1688       --
1689       --  These entities belong with the spec and not the body. However we do
1690       --  the analysis of the body in the context of the spec (again to obtain
1691       --  visibility to the formals), and all the entities generated during
1692       --  this analysis end up also chained to the entity chain of the spec.
1693       --  But they really belong to the body, and there is circuitry to move
1694       --  them from the spec to the body.
1695       --
1696       --  However, when we do this move, we don't want to move the real spec
1697       --  entities (first para above) to the body. The Last_Real_Spec_Entity
1698       --  variable points to the last real spec entity, so we only move those
1699       --  chained beyond that point. It is initialized to Empty to deal with
1700       --  the case where there is no separate spec.
1701
1702       procedure Check_Anonymous_Return;
1703       --  Ada 2005: if a function returns an access type that denotes a task,
1704       --  or a type that contains tasks, we must create a master entity for
1705       --  the anonymous type, which typically will be used in an allocator
1706       --  in the body of the function.
1707
1708       procedure Check_Inline_Pragma (Spec : in out Node_Id);
1709       --  Look ahead to recognize a pragma that may appear after the body.
1710       --  If there is a previous spec, check that it appears in the same
1711       --  declarative part. If the pragma is Inline_Always, perform inlining
1712       --  unconditionally, otherwise only if Front_End_Inlining is requested.
1713       --  If the body acts as a spec, and inlining is required, we create a
1714       --  subprogram declaration for it, in order to attach the body to inline.
1715       --  If pragma does not appear after the body, check whether there is
1716       --  an inline pragma before any local declarations.
1717
1718       procedure Check_Missing_Return;
1719       --  Checks for a function with a no return statements, and also performs
1720       --  the warning checks implemented by Check_Returns. In formal mode, also
1721       --  verify that a function ends with a RETURN and that a procedure does
1722       --  not contain any RETURN.
1723
1724       function Disambiguate_Spec return Entity_Id;
1725       --  When a primitive is declared between the private view and the full
1726       --  view of a concurrent type which implements an interface, a special
1727       --  mechanism is used to find the corresponding spec of the primitive
1728       --  body.
1729
1730       function Is_Private_Concurrent_Primitive
1731         (Subp_Id : Entity_Id) return Boolean;
1732       --  Determine whether subprogram Subp_Id is a primitive of a concurrent
1733       --  type that implements an interface and has a private view.
1734
1735       procedure Set_Trivial_Subprogram (N : Node_Id);
1736       --  Sets the Is_Trivial_Subprogram flag in both spec and body of the
1737       --  subprogram whose body is being analyzed. N is the statement node
1738       --  causing the flag to be set, if the following statement is a return
1739       --  of an entity, we mark the entity as set in source to suppress any
1740       --  warning on the stylized use of function stubs with a dummy return.
1741
1742       procedure Verify_Overriding_Indicator;
1743       --  If there was a previous spec, the entity has been entered in the
1744       --  current scope previously. If the body itself carries an overriding
1745       --  indicator, check that it is consistent with the known status of the
1746       --  entity.
1747
1748       ----------------------------
1749       -- Check_Anonymous_Return --
1750       ----------------------------
1751
1752       procedure Check_Anonymous_Return is
1753          Decl : Node_Id;
1754          Par  : Node_Id;
1755          Scop : Entity_Id;
1756
1757       begin
1758          if Present (Spec_Id) then
1759             Scop := Spec_Id;
1760          else
1761             Scop := Body_Id;
1762          end if;
1763
1764          if Ekind (Scop) = E_Function
1765            and then Ekind (Etype (Scop)) = E_Anonymous_Access_Type
1766            and then not Is_Thunk (Scop)
1767            and then (Has_Task (Designated_Type (Etype (Scop)))
1768                       or else
1769                        (Is_Class_Wide_Type (Designated_Type (Etype (Scop)))
1770                           and then
1771                         Is_Limited_Record (Designated_Type (Etype (Scop)))))
1772            and then Expander_Active
1773
1774             --  Avoid cases with no tasking support
1775
1776            and then RTE_Available (RE_Current_Master)
1777            and then not Restriction_Active (No_Task_Hierarchy)
1778          then
1779             Decl :=
1780               Make_Object_Declaration (Loc,
1781                 Defining_Identifier =>
1782                   Make_Defining_Identifier (Loc, Name_uMaster),
1783                 Constant_Present => True,
1784                 Object_Definition =>
1785                   New_Reference_To (RTE (RE_Master_Id), Loc),
1786                 Expression =>
1787                   Make_Explicit_Dereference (Loc,
1788                     New_Reference_To (RTE (RE_Current_Master), Loc)));
1789
1790             if Present (Declarations (N)) then
1791                Prepend (Decl, Declarations (N));
1792             else
1793                Set_Declarations (N, New_List (Decl));
1794             end if;
1795
1796             Set_Master_Id (Etype (Scop), Defining_Identifier (Decl));
1797             Set_Has_Master_Entity (Scop);
1798
1799             --  Now mark the containing scope as a task master
1800
1801             Par := N;
1802             while Nkind (Par) /= N_Compilation_Unit loop
1803                Par := Parent (Par);
1804                pragma Assert (Present (Par));
1805
1806                --  If we fall off the top, we are at the outer level, and
1807                --  the environment task is our effective master, so nothing
1808                --  to mark.
1809
1810                if Nkind_In
1811                    (Par, N_Task_Body, N_Block_Statement, N_Subprogram_Body)
1812                then
1813                   Set_Is_Task_Master (Par, True);
1814                   exit;
1815                end if;
1816             end loop;
1817          end if;
1818       end Check_Anonymous_Return;
1819
1820       -------------------------
1821       -- Check_Inline_Pragma --
1822       -------------------------
1823
1824       procedure Check_Inline_Pragma (Spec : in out Node_Id) is
1825          Prag  : Node_Id;
1826          Plist : List_Id;
1827
1828          function Is_Inline_Pragma (N : Node_Id) return Boolean;
1829          --  True when N is a pragma Inline or Inline_Always that applies
1830          --  to this subprogram.
1831
1832          -----------------------
1833          --  Is_Inline_Pragma --
1834          -----------------------
1835
1836          function Is_Inline_Pragma (N : Node_Id) return Boolean is
1837          begin
1838             return
1839               Nkind (N) = N_Pragma
1840                 and then
1841                    (Pragma_Name (N) = Name_Inline_Always
1842                      or else
1843                       (Front_End_Inlining
1844                         and then Pragma_Name (N) = Name_Inline))
1845                 and then
1846                    Chars
1847                      (Expression (First (Pragma_Argument_Associations (N))))
1848                         = Chars (Body_Id);
1849          end Is_Inline_Pragma;
1850
1851       --  Start of processing for Check_Inline_Pragma
1852
1853       begin
1854          if not Expander_Active then
1855             return;
1856          end if;
1857
1858          if Is_List_Member (N)
1859            and then Present (Next (N))
1860            and then Is_Inline_Pragma (Next (N))
1861          then
1862             Prag := Next (N);
1863
1864          elsif Nkind (N) /= N_Subprogram_Body_Stub
1865            and then Present (Declarations (N))
1866            and then Is_Inline_Pragma (First (Declarations (N)))
1867          then
1868             Prag := First (Declarations (N));
1869
1870          else
1871             Prag := Empty;
1872          end if;
1873
1874          if Present (Prag) then
1875             if Present (Spec_Id) then
1876                if In_Same_List (N, Unit_Declaration_Node (Spec_Id)) then
1877                   Analyze (Prag);
1878                end if;
1879
1880             else
1881                --  Create a subprogram declaration, to make treatment uniform
1882
1883                declare
1884                   Subp : constant Entity_Id :=
1885                            Make_Defining_Identifier (Loc, Chars (Body_Id));
1886                   Decl : constant Node_Id :=
1887                            Make_Subprogram_Declaration (Loc,
1888                              Specification =>
1889                                New_Copy_Tree (Specification (N)));
1890
1891                begin
1892                   Set_Defining_Unit_Name (Specification (Decl), Subp);
1893
1894                   if Present (First_Formal (Body_Id)) then
1895                      Plist := Copy_Parameter_List (Body_Id);
1896                      Set_Parameter_Specifications
1897                        (Specification (Decl), Plist);
1898                   end if;
1899
1900                   Insert_Before (N, Decl);
1901                   Analyze (Decl);
1902                   Analyze (Prag);
1903                   Set_Has_Pragma_Inline (Subp);
1904
1905                   if Pragma_Name (Prag) = Name_Inline_Always then
1906                      Set_Is_Inlined (Subp);
1907                      Set_Has_Pragma_Inline_Always (Subp);
1908                   end if;
1909
1910                   Spec := Subp;
1911                end;
1912             end if;
1913          end if;
1914       end Check_Inline_Pragma;
1915
1916       --------------------------
1917       -- Check_Missing_Return --
1918       --------------------------
1919
1920       procedure Check_Missing_Return is
1921          Id          : Entity_Id;
1922          Missing_Ret : Boolean;
1923
1924       begin
1925          if Nkind (Body_Spec) = N_Function_Specification then
1926             if Present (Spec_Id) then
1927                Id := Spec_Id;
1928             else
1929                Id := Body_Id;
1930             end if;
1931
1932             if Return_Present (Id) then
1933                Check_Returns (HSS, 'F', Missing_Ret);
1934
1935                if Missing_Ret then
1936                   Set_Has_Missing_Return (Id);
1937                end if;
1938
1939             elsif (Is_Generic_Subprogram (Id)
1940                      or else not Is_Machine_Code_Subprogram (Id))
1941               and then not Body_Deleted
1942             then
1943                Error_Msg_N ("missing RETURN statement in function body", N);
1944             end if;
1945
1946          --  If procedure with No_Return, check returns
1947
1948          elsif Nkind (Body_Spec) = N_Procedure_Specification
1949            and then Present (Spec_Id)
1950            and then No_Return (Spec_Id)
1951          then
1952             Check_Returns (HSS, 'P', Missing_Ret, Spec_Id);
1953          end if;
1954
1955          --  Special checks in SPARK mode
1956
1957          if Nkind (Body_Spec) = N_Function_Specification then
1958
1959             --  In SPARK mode, last statement of a function should be a return
1960
1961             declare
1962                Stat : constant Node_Id := Last_Source_Statement (HSS);
1963             begin
1964                if Present (Stat)
1965                  and then not Nkind_In (Stat, N_Simple_Return_Statement,
1966                                               N_Extended_Return_Statement)
1967                then
1968                   Check_SPARK_Restriction
1969                     ("last statement in function should be RETURN", Stat);
1970                end if;
1971             end;
1972
1973          --  In SPARK mode, verify that a procedure has no return
1974
1975          elsif Nkind (Body_Spec) = N_Procedure_Specification then
1976             if Present (Spec_Id) then
1977                Id := Spec_Id;
1978             else
1979                Id := Body_Id;
1980             end if;
1981
1982             --  Would be nice to point to return statement here, can we
1983             --  borrow the Check_Returns procedure here ???
1984
1985             if Return_Present (Id) then
1986                Check_SPARK_Restriction
1987                  ("procedure should not have RETURN", N);
1988             end if;
1989          end if;
1990       end Check_Missing_Return;
1991
1992       -----------------------
1993       -- Disambiguate_Spec --
1994       -----------------------
1995
1996       function Disambiguate_Spec return Entity_Id is
1997          Priv_Spec : Entity_Id;
1998          Spec_N    : Entity_Id;
1999
2000          procedure Replace_Types (To_Corresponding : Boolean);
2001          --  Depending on the flag, replace the type of formal parameters of
2002          --  Body_Id if it is a concurrent type implementing interfaces with
2003          --  the corresponding record type or the other way around.
2004
2005          procedure Replace_Types (To_Corresponding : Boolean) is
2006             Formal     : Entity_Id;
2007             Formal_Typ : Entity_Id;
2008
2009          begin
2010             Formal := First_Formal (Body_Id);
2011             while Present (Formal) loop
2012                Formal_Typ := Etype (Formal);
2013
2014                if Is_Class_Wide_Type (Formal_Typ) then
2015                   Formal_Typ := Root_Type (Formal_Typ);
2016                end if;
2017
2018                --  From concurrent type to corresponding record
2019
2020                if To_Corresponding then
2021                   if Is_Concurrent_Type (Formal_Typ)
2022                     and then Present (Corresponding_Record_Type (Formal_Typ))
2023                     and then Present (Interfaces (
2024                                Corresponding_Record_Type (Formal_Typ)))
2025                   then
2026                      Set_Etype (Formal,
2027                        Corresponding_Record_Type (Formal_Typ));
2028                   end if;
2029
2030                --  From corresponding record to concurrent type
2031
2032                else
2033                   if Is_Concurrent_Record_Type (Formal_Typ)
2034                     and then Present (Interfaces (Formal_Typ))
2035                   then
2036                      Set_Etype (Formal,
2037                        Corresponding_Concurrent_Type (Formal_Typ));
2038                   end if;
2039                end if;
2040
2041                Next_Formal (Formal);
2042             end loop;
2043          end Replace_Types;
2044
2045       --  Start of processing for Disambiguate_Spec
2046
2047       begin
2048          --  Try to retrieve the specification of the body as is. All error
2049          --  messages are suppressed because the body may not have a spec in
2050          --  its current state.
2051
2052          Spec_N := Find_Corresponding_Spec (N, False);
2053
2054          --  It is possible that this is the body of a primitive declared
2055          --  between a private and a full view of a concurrent type. The
2056          --  controlling parameter of the spec carries the concurrent type,
2057          --  not the corresponding record type as transformed by Analyze_
2058          --  Subprogram_Specification. In such cases, we undo the change
2059          --  made by the analysis of the specification and try to find the
2060          --  spec again.
2061
2062          --  Note that wrappers already have their corresponding specs and
2063          --  bodies set during their creation, so if the candidate spec is
2064          --  a wrapper, then we definitely need to swap all types to their
2065          --  original concurrent status.
2066
2067          if No (Spec_N)
2068            or else Is_Primitive_Wrapper (Spec_N)
2069          then
2070             --  Restore all references of corresponding record types to the
2071             --  original concurrent types.
2072
2073             Replace_Types (To_Corresponding => False);
2074             Priv_Spec := Find_Corresponding_Spec (N, False);
2075
2076             --  The current body truly belongs to a primitive declared between
2077             --  a private and a full view. We leave the modified body as is,
2078             --  and return the true spec.
2079
2080             if Present (Priv_Spec)
2081               and then Is_Private_Primitive (Priv_Spec)
2082             then
2083                return Priv_Spec;
2084             end if;
2085
2086             --  In case that this is some sort of error, restore the original
2087             --  state of the body.
2088
2089             Replace_Types (To_Corresponding => True);
2090          end if;
2091
2092          return Spec_N;
2093       end Disambiguate_Spec;
2094
2095       -------------------------------------
2096       -- Is_Private_Concurrent_Primitive --
2097       -------------------------------------
2098
2099       function Is_Private_Concurrent_Primitive
2100         (Subp_Id : Entity_Id) return Boolean
2101       is
2102          Formal_Typ : Entity_Id;
2103
2104       begin
2105          if Present (First_Formal (Subp_Id)) then
2106             Formal_Typ := Etype (First_Formal (Subp_Id));
2107
2108             if Is_Concurrent_Record_Type (Formal_Typ) then
2109                if Is_Class_Wide_Type (Formal_Typ) then
2110                   Formal_Typ := Root_Type (Formal_Typ);
2111                end if;
2112
2113                Formal_Typ := Corresponding_Concurrent_Type (Formal_Typ);
2114             end if;
2115
2116             --  The type of the first formal is a concurrent tagged type with
2117             --  a private view.
2118
2119             return
2120               Is_Concurrent_Type (Formal_Typ)
2121                 and then Is_Tagged_Type (Formal_Typ)
2122                 and then Has_Private_Declaration (Formal_Typ);
2123          end if;
2124
2125          return False;
2126       end Is_Private_Concurrent_Primitive;
2127
2128       ----------------------------
2129       -- Set_Trivial_Subprogram --
2130       ----------------------------
2131
2132       procedure Set_Trivial_Subprogram (N : Node_Id) is
2133          Nxt : constant Node_Id := Next (N);
2134
2135       begin
2136          Set_Is_Trivial_Subprogram (Body_Id);
2137
2138          if Present (Spec_Id) then
2139             Set_Is_Trivial_Subprogram (Spec_Id);
2140          end if;
2141
2142          if Present (Nxt)
2143            and then Nkind (Nxt) = N_Simple_Return_Statement
2144            and then No (Next (Nxt))
2145            and then Present (Expression (Nxt))
2146            and then Is_Entity_Name (Expression (Nxt))
2147          then
2148             Set_Never_Set_In_Source (Entity (Expression (Nxt)), False);
2149          end if;
2150       end Set_Trivial_Subprogram;
2151
2152       ---------------------------------
2153       -- Verify_Overriding_Indicator --
2154       ---------------------------------
2155
2156       procedure Verify_Overriding_Indicator is
2157       begin
2158          if Must_Override (Body_Spec) then
2159             if Nkind (Spec_Id) = N_Defining_Operator_Symbol
2160               and then  Operator_Matches_Spec (Spec_Id, Spec_Id)
2161             then
2162                null;
2163
2164             elsif not Present (Overridden_Operation (Spec_Id)) then
2165                Error_Msg_NE
2166                  ("subprogram& is not overriding", Body_Spec, Spec_Id);
2167             end if;
2168
2169          elsif Must_Not_Override (Body_Spec) then
2170             if Present (Overridden_Operation (Spec_Id)) then
2171                Error_Msg_NE
2172                  ("subprogram& overrides inherited operation",
2173                   Body_Spec, Spec_Id);
2174
2175             elsif Nkind (Spec_Id) = N_Defining_Operator_Symbol
2176               and then  Operator_Matches_Spec (Spec_Id, Spec_Id)
2177             then
2178                Error_Msg_NE
2179                  ("subprogram & overrides predefined operator ",
2180                     Body_Spec, Spec_Id);
2181
2182             --  If this is not a primitive operation or protected subprogram,
2183             --  then the overriding indicator is altogether illegal.
2184
2185             elsif not Is_Primitive (Spec_Id)
2186               and then Ekind (Scope (Spec_Id)) /= E_Protected_Type
2187             then
2188                Error_Msg_N
2189                  ("overriding indicator only allowed " &
2190                   "if subprogram is primitive",
2191                   Body_Spec);
2192             end if;
2193
2194          elsif Style_Check
2195            and then Present (Overridden_Operation (Spec_Id))
2196          then
2197             pragma Assert (Unit_Declaration_Node (Body_Id) = N);
2198             Style.Missing_Overriding (N, Body_Id);
2199
2200          elsif Style_Check
2201            and then Can_Override_Operator (Spec_Id)
2202            and then not Is_Predefined_File_Name
2203                           (Unit_File_Name (Get_Source_Unit (Spec_Id)))
2204          then
2205             pragma Assert (Unit_Declaration_Node (Body_Id) = N);
2206             Style.Missing_Overriding (N, Body_Id);
2207          end if;
2208       end Verify_Overriding_Indicator;
2209
2210    --  Start of processing for Analyze_Subprogram_Body_Helper
2211
2212    begin
2213       --  Generic subprograms are handled separately. They always have a
2214       --  generic specification. Determine whether current scope has a
2215       --  previous declaration.
2216
2217       --  If the subprogram body is defined within an instance of the same
2218       --  name, the instance appears as a package renaming, and will be hidden
2219       --  within the subprogram.
2220
2221       if Present (Prev_Id)
2222         and then not Is_Overloadable (Prev_Id)
2223         and then (Nkind (Parent (Prev_Id)) /= N_Package_Renaming_Declaration
2224                    or else Comes_From_Source (Prev_Id))
2225       then
2226          if Is_Generic_Subprogram (Prev_Id) then
2227             Spec_Id := Prev_Id;
2228             Set_Is_Compilation_Unit (Body_Id, Is_Compilation_Unit (Spec_Id));
2229             Set_Is_Child_Unit       (Body_Id, Is_Child_Unit       (Spec_Id));
2230
2231             Analyze_Generic_Subprogram_Body (N, Spec_Id);
2232
2233             if Nkind (N) = N_Subprogram_Body then
2234                HSS := Handled_Statement_Sequence (N);
2235                Check_Missing_Return;
2236             end if;
2237
2238             return;
2239
2240          else
2241             --  Previous entity conflicts with subprogram name. Attempting to
2242             --  enter name will post error.
2243
2244             Enter_Name (Body_Id);
2245             return;
2246          end if;
2247
2248       --  Non-generic case, find the subprogram declaration, if one was seen,
2249       --  or enter new overloaded entity in the current scope. If the
2250       --  Current_Entity is the Body_Id itself, the unit is being analyzed as
2251       --  part of the context of one of its subunits. No need to redo the
2252       --  analysis.
2253
2254       elsif Prev_Id = Body_Id
2255         and then Has_Completion (Body_Id)
2256       then
2257          return;
2258
2259       else
2260          Body_Id := Analyze_Subprogram_Specification (Body_Spec);
2261
2262          if Nkind (N) = N_Subprogram_Body_Stub
2263            or else No (Corresponding_Spec (N))
2264          then
2265             if Is_Private_Concurrent_Primitive (Body_Id) then
2266                Spec_Id := Disambiguate_Spec;
2267             else
2268                Spec_Id := Find_Corresponding_Spec (N);
2269             end if;
2270
2271             --  If this is a duplicate body, no point in analyzing it
2272
2273             if Error_Posted (N) then
2274                return;
2275             end if;
2276
2277             --  A subprogram body should cause freezing of its own declaration,
2278             --  but if there was no previous explicit declaration, then the
2279             --  subprogram will get frozen too late (there may be code within
2280             --  the body that depends on the subprogram having been frozen,
2281             --  such as uses of extra formals), so we force it to be frozen
2282             --  here. Same holds if the body and spec are compilation units.
2283             --  Finally, if the return type is an anonymous access to protected
2284             --  subprogram, it must be frozen before the body because its
2285             --  expansion has generated an equivalent type that is used when
2286             --  elaborating the body.
2287
2288             if No (Spec_Id) then
2289                Freeze_Before (N, Body_Id);
2290
2291             elsif Nkind (Parent (N)) = N_Compilation_Unit then
2292                Freeze_Before (N, Spec_Id);
2293
2294             elsif Is_Access_Subprogram_Type (Etype (Body_Id)) then
2295                Freeze_Before (N, Etype (Body_Id));
2296             end if;
2297
2298          else
2299             Spec_Id := Corresponding_Spec (N);
2300          end if;
2301       end if;
2302
2303       --  Do not inline any subprogram that contains nested subprograms, since
2304       --  the backend inlining circuit seems to generate uninitialized
2305       --  references in this case. We know this happens in the case of front
2306       --  end ZCX support, but it also appears it can happen in other cases as
2307       --  well. The backend often rejects attempts to inline in the case of
2308       --  nested procedures anyway, so little if anything is lost by this.
2309       --  Note that this is test is for the benefit of the back-end. There is
2310       --  a separate test for front-end inlining that also rejects nested
2311       --  subprograms.
2312
2313       --  Do not do this test if errors have been detected, because in some
2314       --  error cases, this code blows up, and we don't need it anyway if
2315       --  there have been errors, since we won't get to the linker anyway.
2316
2317       if Comes_From_Source (Body_Id)
2318         and then Serious_Errors_Detected = 0
2319       then
2320          P_Ent := Body_Id;
2321          loop
2322             P_Ent := Scope (P_Ent);
2323             exit when No (P_Ent) or else P_Ent = Standard_Standard;
2324
2325             if Is_Subprogram (P_Ent) then
2326                Set_Is_Inlined (P_Ent, False);
2327
2328                if Comes_From_Source (P_Ent)
2329                  and then Has_Pragma_Inline (P_Ent)
2330                then
2331                   Cannot_Inline
2332                     ("cannot inline& (nested subprogram)?",
2333                      N, P_Ent);
2334                end if;
2335             end if;
2336          end loop;
2337       end if;
2338
2339       Check_Inline_Pragma (Spec_Id);
2340
2341       --  Deal with special case of a fully private operation in the body of
2342       --  the protected type. We must create a declaration for the subprogram,
2343       --  in order to attach the protected subprogram that will be used in
2344       --  internal calls. We exclude compiler generated bodies from the
2345       --  expander since the issue does not arise for those cases.
2346
2347       if No (Spec_Id)
2348         and then Comes_From_Source (N)
2349         and then Is_Protected_Type (Current_Scope)
2350       then
2351          Spec_Id := Build_Private_Protected_Declaration (N);
2352       end if;
2353
2354       --  If a separate spec is present, then deal with freezing issues
2355
2356       if Present (Spec_Id) then
2357          Spec_Decl := Unit_Declaration_Node (Spec_Id);
2358          Verify_Overriding_Indicator;
2359
2360          --  In general, the spec will be frozen when we start analyzing the
2361          --  body. However, for internally generated operations, such as
2362          --  wrapper functions for inherited operations with controlling
2363          --  results, the spec may not have been frozen by the time we expand
2364          --  the freeze actions that include the bodies. In particular, extra
2365          --  formals for accessibility or for return-in-place may need to be
2366          --  generated. Freeze nodes, if any, are inserted before the current
2367          --  body. These freeze actions are also needed in ASIS mode to enable
2368          --  the proper back-annotations.
2369
2370          if not Is_Frozen (Spec_Id)
2371            and then (Expander_Active or ASIS_Mode)
2372          then
2373             --  Force the generation of its freezing node to ensure proper
2374             --  management of access types in the backend.
2375
2376             --  This is definitely needed for some cases, but it is not clear
2377             --  why, to be investigated further???
2378
2379             Set_Has_Delayed_Freeze (Spec_Id);
2380             Freeze_Before (N, Spec_Id);
2381          end if;
2382       end if;
2383
2384       --  Mark presence of postcondition procedure in current scope and mark
2385       --  the procedure itself as needing debug info. The latter is important
2386       --  when analyzing decision coverage (for example, for MC/DC coverage).
2387
2388       if Chars (Body_Id) = Name_uPostconditions then
2389          Set_Has_Postconditions (Current_Scope);
2390          Set_Debug_Info_Needed (Body_Id);
2391       end if;
2392
2393       --  Place subprogram on scope stack, and make formals visible. If there
2394       --  is a spec, the visible entity remains that of the spec.
2395
2396       if Present (Spec_Id) then
2397          Generate_Reference (Spec_Id, Body_Id, 'b', Set_Ref => False);
2398
2399          if Is_Child_Unit (Spec_Id) then
2400             Generate_Reference (Spec_Id, Scope (Spec_Id), 'k', False);
2401          end if;
2402
2403          if Style_Check then
2404             Style.Check_Identifier (Body_Id, Spec_Id);
2405          end if;
2406
2407          Set_Is_Compilation_Unit (Body_Id, Is_Compilation_Unit (Spec_Id));
2408          Set_Is_Child_Unit       (Body_Id, Is_Child_Unit       (Spec_Id));
2409
2410          if Is_Abstract_Subprogram (Spec_Id) then
2411             Error_Msg_N ("an abstract subprogram cannot have a body", N);
2412             return;
2413
2414          else
2415             Set_Convention (Body_Id, Convention (Spec_Id));
2416             Set_Has_Completion (Spec_Id);
2417
2418             if Is_Protected_Type (Scope (Spec_Id)) then
2419                Prot_Typ := Scope (Spec_Id);
2420             end if;
2421
2422             --  If this is a body generated for a renaming, do not check for
2423             --  full conformance. The check is redundant, because the spec of
2424             --  the body is a copy of the spec in the renaming declaration,
2425             --  and the test can lead to spurious errors on nested defaults.
2426
2427             if Present (Spec_Decl)
2428               and then not Comes_From_Source (N)
2429               and then
2430                 (Nkind (Original_Node (Spec_Decl)) =
2431                                         N_Subprogram_Renaming_Declaration
2432                    or else (Present (Corresponding_Body (Spec_Decl))
2433                               and then
2434                                 Nkind (Unit_Declaration_Node
2435                                         (Corresponding_Body (Spec_Decl))) =
2436                                            N_Subprogram_Renaming_Declaration))
2437             then
2438                Conformant := True;
2439
2440             --  Conversely, the spec may have been generated for specless body
2441             --  with an inline pragma.
2442
2443             elsif Comes_From_Source (N)
2444               and then not Comes_From_Source (Spec_Id)
2445               and then Has_Pragma_Inline (Spec_Id)
2446             then
2447                Conformant := True;
2448
2449             else
2450                Check_Conformance
2451                  (Body_Id, Spec_Id,
2452                   Fully_Conformant, True, Conformant, Body_Id);
2453             end if;
2454
2455             --  If the body is not fully conformant, we have to decide if we
2456             --  should analyze it or not. If it has a really messed up profile
2457             --  then we probably should not analyze it, since we will get too
2458             --  many bogus messages.
2459
2460             --  Our decision is to go ahead in the non-fully conformant case
2461             --  only if it is at least mode conformant with the spec. Note
2462             --  that the call to Check_Fully_Conformant has issued the proper
2463             --  error messages to complain about the lack of conformance.
2464
2465             if not Conformant
2466               and then not Mode_Conformant (Body_Id, Spec_Id)
2467             then
2468                return;
2469             end if;
2470          end if;
2471
2472          if Spec_Id /= Body_Id then
2473             Reference_Body_Formals (Spec_Id, Body_Id);
2474          end if;
2475
2476          if Nkind (N) /= N_Subprogram_Body_Stub then
2477             Set_Corresponding_Spec (N, Spec_Id);
2478
2479             --  Ada 2005 (AI-345): If the operation is a primitive operation
2480             --  of a concurrent type, the type of the first parameter has been
2481             --  replaced with the corresponding record, which is the proper
2482             --  run-time structure to use. However, within the body there may
2483             --  be uses of the formals that depend on primitive operations
2484             --  of the type (in particular calls in prefixed form) for which
2485             --  we need the original concurrent type. The operation may have
2486             --  several controlling formals, so the replacement must be done
2487             --  for all of them.
2488
2489             if Comes_From_Source (Spec_Id)
2490               and then Present (First_Entity (Spec_Id))
2491               and then Ekind (Etype (First_Entity (Spec_Id))) = E_Record_Type
2492               and then Is_Tagged_Type (Etype (First_Entity (Spec_Id)))
2493               and then
2494                 Present (Interfaces (Etype (First_Entity (Spec_Id))))
2495               and then
2496                 Present
2497                   (Corresponding_Concurrent_Type
2498                      (Etype (First_Entity (Spec_Id))))
2499             then
2500                declare
2501                   Typ  : constant Entity_Id := Etype (First_Entity (Spec_Id));
2502                   Form : Entity_Id;
2503
2504                begin
2505                   Form := First_Formal (Spec_Id);
2506                   while Present (Form) loop
2507                      if Etype (Form) = Typ then
2508                         Set_Etype (Form, Corresponding_Concurrent_Type (Typ));
2509                      end if;
2510
2511                      Next_Formal (Form);
2512                   end loop;
2513                end;
2514             end if;
2515
2516             --  Make the formals visible, and place subprogram on scope stack.
2517             --  This is also the point at which we set Last_Real_Spec_Entity
2518             --  to mark the entities which will not be moved to the body.
2519
2520             Install_Formals (Spec_Id);
2521             Last_Real_Spec_Entity := Last_Entity (Spec_Id);
2522             Push_Scope (Spec_Id);
2523
2524             --  Make sure that the subprogram is immediately visible. For
2525             --  child units that have no separate spec this is indispensable.
2526             --  Otherwise it is safe albeit redundant.
2527
2528             Set_Is_Immediately_Visible (Spec_Id);
2529          end if;
2530
2531          Set_Corresponding_Body (Unit_Declaration_Node (Spec_Id), Body_Id);
2532          Set_Ekind (Body_Id, E_Subprogram_Body);
2533          Set_Scope (Body_Id, Scope (Spec_Id));
2534          Set_Is_Obsolescent (Body_Id, Is_Obsolescent (Spec_Id));
2535
2536       --  Case of subprogram body with no previous spec
2537
2538       else
2539          --  Check for style warning required
2540
2541          if Style_Check
2542
2543            --  Only apply check for source level subprograms for which checks
2544            --  have not been suppressed.
2545
2546            and then Comes_From_Source (Body_Id)
2547            and then not Suppress_Style_Checks (Body_Id)
2548
2549            --  No warnings within an instance
2550
2551            and then not In_Instance
2552
2553            --  No warnings for expression functions
2554
2555            and then Nkind (Original_Node (N)) /= N_Expression_Function
2556          then
2557             Style.Body_With_No_Spec (N);
2558          end if;
2559
2560          New_Overloaded_Entity (Body_Id);
2561
2562          if Nkind (N) /= N_Subprogram_Body_Stub then
2563             Set_Acts_As_Spec (N);
2564             Generate_Definition (Body_Id);
2565             Set_Contract (Body_Id, Make_Contract (Sloc (Body_Id)));
2566             Generate_Reference
2567               (Body_Id, Body_Id, 'b', Set_Ref => False, Force => True);
2568             Generate_Reference_To_Formals (Body_Id);
2569             Install_Formals (Body_Id);
2570             Push_Scope (Body_Id);
2571          end if;
2572       end if;
2573
2574       --  If the return type is an anonymous access type whose designated type
2575       --  is the limited view of a class-wide type and the non-limited view is
2576       --  available, update the return type accordingly.
2577
2578       if Ada_Version >= Ada_2005
2579         and then Comes_From_Source (N)
2580       then
2581          declare
2582             Etyp : Entity_Id;
2583             Rtyp : Entity_Id;
2584
2585          begin
2586             Rtyp := Etype (Current_Scope);
2587
2588             if Ekind (Rtyp) = E_Anonymous_Access_Type then
2589                Etyp := Directly_Designated_Type (Rtyp);
2590
2591                if Is_Class_Wide_Type (Etyp)
2592                  and then From_With_Type (Etyp)
2593                then
2594                   Set_Directly_Designated_Type
2595                     (Etype (Current_Scope), Available_View (Etyp));
2596                end if;
2597             end if;
2598          end;
2599       end if;
2600
2601       --  If this is the proper body of a stub, we must verify that the stub
2602       --  conforms to the body, and to the previous spec if one was present.
2603       --  we know already that the body conforms to that spec. This test is
2604       --  only required for subprograms that come from source.
2605
2606       if Nkind (Parent (N)) = N_Subunit
2607         and then Comes_From_Source (N)
2608         and then not Error_Posted (Body_Id)
2609         and then Nkind (Corresponding_Stub (Parent (N))) =
2610                                                 N_Subprogram_Body_Stub
2611       then
2612          declare
2613             Old_Id : constant Entity_Id :=
2614                        Defining_Entity
2615                          (Specification (Corresponding_Stub (Parent (N))));
2616
2617             Conformant : Boolean := False;
2618
2619          begin
2620             if No (Spec_Id) then
2621                Check_Fully_Conformant (Body_Id, Old_Id);
2622
2623             else
2624                Check_Conformance
2625                  (Body_Id, Old_Id, Fully_Conformant, False, Conformant);
2626
2627                if not Conformant then
2628
2629                   --  The stub was taken to be a new declaration. Indicate
2630                   --  that it lacks a body.
2631
2632                   Set_Has_Completion (Old_Id, False);
2633                end if;
2634             end if;
2635          end;
2636       end if;
2637
2638       Set_Has_Completion (Body_Id);
2639       Check_Eliminated (Body_Id);
2640
2641       if Nkind (N) = N_Subprogram_Body_Stub then
2642          return;
2643
2644       elsif Present (Spec_Id)
2645         and then Expander_Active
2646         and then
2647           (Has_Pragma_Inline_Always (Spec_Id)
2648              or else (Has_Pragma_Inline (Spec_Id) and Front_End_Inlining))
2649       then
2650          Build_Body_To_Inline (N, Spec_Id);
2651       end if;
2652
2653       --  Ada 2005 (AI-262): In library subprogram bodies, after the analysis
2654       --  if its specification we have to install the private withed units.
2655       --  This holds for child units as well.
2656
2657       if Is_Compilation_Unit (Body_Id)
2658         or else Nkind (Parent (N)) = N_Compilation_Unit
2659       then
2660          Install_Private_With_Clauses (Body_Id);
2661       end if;
2662
2663       Check_Anonymous_Return;
2664
2665       --  Set the Protected_Formal field of each extra formal of the protected
2666       --  subprogram to reference the corresponding extra formal of the
2667       --  subprogram that implements it. For regular formals this occurs when
2668       --  the protected subprogram's declaration is expanded, but the extra
2669       --  formals don't get created until the subprogram is frozen. We need to
2670       --  do this before analyzing the protected subprogram's body so that any
2671       --  references to the original subprogram's extra formals will be changed
2672       --  refer to the implementing subprogram's formals (see Expand_Formal).
2673
2674       if Present (Spec_Id)
2675         and then Is_Protected_Type (Scope (Spec_Id))
2676         and then Present (Protected_Body_Subprogram (Spec_Id))
2677       then
2678          declare
2679             Impl_Subp       : constant Entity_Id :=
2680                                 Protected_Body_Subprogram (Spec_Id);
2681             Prot_Ext_Formal : Entity_Id := Extra_Formals (Spec_Id);
2682             Impl_Ext_Formal : Entity_Id := Extra_Formals (Impl_Subp);
2683          begin
2684             while Present (Prot_Ext_Formal) loop
2685                pragma Assert (Present (Impl_Ext_Formal));
2686                Set_Protected_Formal (Prot_Ext_Formal, Impl_Ext_Formal);
2687                Next_Formal_With_Extras (Prot_Ext_Formal);
2688                Next_Formal_With_Extras (Impl_Ext_Formal);
2689             end loop;
2690          end;
2691       end if;
2692
2693       --  Now we can go on to analyze the body
2694
2695       HSS := Handled_Statement_Sequence (N);
2696       Set_Actual_Subtypes (N, Current_Scope);
2697
2698       --  Deal with preconditions and postconditions. In formal verification
2699       --  mode, we keep pre- and postconditions attached to entities rather
2700       --  than inserted in the code, in order to facilitate a distinct
2701       --  treatment for them.
2702
2703       if not Alfa_Mode then
2704          Process_PPCs (N, Spec_Id, Body_Id);
2705       end if;
2706
2707       --  Add a declaration for the Protection object, renaming declarations
2708       --  for discriminals and privals and finally a declaration for the entry
2709       --  family index (if applicable). This form of early expansion is done
2710       --  when the Expander is active because Install_Private_Data_Declarations
2711       --  references entities which were created during regular expansion.
2712
2713       if Full_Expander_Active
2714         and then Comes_From_Source (N)
2715         and then Present (Prot_Typ)
2716         and then Present (Spec_Id)
2717         and then not Is_Eliminated (Spec_Id)
2718       then
2719          Install_Private_Data_Declarations
2720            (Sloc (N), Spec_Id, Prot_Typ, N, Declarations (N));
2721       end if;
2722
2723       --  Analyze the declarations (this call will analyze the precondition
2724       --  Check pragmas we prepended to the list, as well as the declaration
2725       --  of the _Postconditions procedure).
2726
2727       Analyze_Declarations (Declarations (N));
2728
2729       --  Check completion, and analyze the statements
2730
2731       Check_Completion;
2732       Inspect_Deferred_Constant_Completion (Declarations (N));
2733       Analyze (HSS);
2734
2735       --  Deal with end of scope processing for the body
2736
2737       Process_End_Label (HSS, 't', Current_Scope);
2738       End_Scope;
2739       Check_Subprogram_Order (N);
2740       Set_Analyzed (Body_Id);
2741
2742       --  If we have a separate spec, then the analysis of the declarations
2743       --  caused the entities in the body to be chained to the spec id, but
2744       --  we want them chained to the body id. Only the formal parameters
2745       --  end up chained to the spec id in this case.
2746
2747       if Present (Spec_Id) then
2748
2749          --  We must conform to the categorization of our spec
2750
2751          Validate_Categorization_Dependency (N, Spec_Id);
2752
2753          --  And if this is a child unit, the parent units must conform
2754
2755          if Is_Child_Unit (Spec_Id) then
2756             Validate_Categorization_Dependency
2757               (Unit_Declaration_Node (Spec_Id), Spec_Id);
2758          end if;
2759
2760          --  Here is where we move entities from the spec to the body
2761
2762          --  Case where there are entities that stay with the spec
2763
2764          if Present (Last_Real_Spec_Entity) then
2765
2766             --  No body entities (happens when the only real spec entities
2767             --  come from precondition and postcondition pragmas)
2768
2769             if No (Last_Entity (Body_Id)) then
2770                Set_First_Entity
2771                  (Body_Id, Next_Entity (Last_Real_Spec_Entity));
2772
2773             --  Body entities present (formals), so chain stuff past them
2774
2775             else
2776                Set_Next_Entity
2777                  (Last_Entity (Body_Id), Next_Entity (Last_Real_Spec_Entity));
2778             end if;
2779
2780             Set_Next_Entity (Last_Real_Spec_Entity, Empty);
2781             Set_Last_Entity (Body_Id, Last_Entity (Spec_Id));
2782             Set_Last_Entity (Spec_Id, Last_Real_Spec_Entity);
2783
2784          --  Case where there are no spec entities, in this case there can
2785          --  be no body entities either, so just move everything.
2786
2787          else
2788             pragma Assert (No (Last_Entity (Body_Id)));
2789             Set_First_Entity (Body_Id, First_Entity (Spec_Id));
2790             Set_Last_Entity  (Body_Id, Last_Entity (Spec_Id));
2791             Set_First_Entity (Spec_Id, Empty);
2792             Set_Last_Entity  (Spec_Id, Empty);
2793          end if;
2794       end if;
2795
2796       Check_Missing_Return;
2797
2798       --  Now we are going to check for variables that are never modified in
2799       --  the body of the procedure. But first we deal with a special case
2800       --  where we want to modify this check. If the body of the subprogram
2801       --  starts with a raise statement or its equivalent, or if the body
2802       --  consists entirely of a null statement, then it is pretty obvious
2803       --  that it is OK to not reference the parameters. For example, this
2804       --  might be the following common idiom for a stubbed function:
2805       --  statement of the procedure raises an exception. In particular this
2806       --  deals with the common idiom of a stubbed function, which might
2807       --  appear as something like
2808
2809       --     function F (A : Integer) return Some_Type;
2810       --        X : Some_Type;
2811       --     begin
2812       --        raise Program_Error;
2813       --        return X;
2814       --     end F;
2815
2816       --  Here the purpose of X is simply to satisfy the annoying requirement
2817       --  in Ada that there be at least one return, and we certainly do not
2818       --  want to go posting warnings on X that it is not initialized! On
2819       --  the other hand, if X is entirely unreferenced that should still
2820       --  get a warning.
2821
2822       --  What we do is to detect these cases, and if we find them, flag the
2823       --  subprogram as being Is_Trivial_Subprogram and then use that flag to
2824       --  suppress unwanted warnings. For the case of the function stub above
2825       --  we have a special test to set X as apparently assigned to suppress
2826       --  the warning.
2827
2828       declare
2829          Stm : Node_Id;
2830
2831       begin
2832          --  Skip initial labels (for one thing this occurs when we are in
2833          --  front end ZCX mode, but in any case it is irrelevant), and also
2834          --  initial Push_xxx_Error_Label nodes, which are also irrelevant.
2835
2836          Stm := First (Statements (HSS));
2837          while Nkind (Stm) = N_Label
2838            or else Nkind (Stm) in N_Push_xxx_Label
2839          loop
2840             Next (Stm);
2841          end loop;
2842
2843          --  Do the test on the original statement before expansion
2844
2845          declare
2846             Ostm : constant Node_Id := Original_Node (Stm);
2847
2848          begin
2849             --  If explicit raise statement, turn on flag
2850
2851             if Nkind (Ostm) = N_Raise_Statement then
2852                Set_Trivial_Subprogram (Stm);
2853
2854             --  If null statement, and no following statements, turn on flag
2855
2856             elsif Nkind (Stm) = N_Null_Statement
2857               and then Comes_From_Source (Stm)
2858               and then No (Next (Stm))
2859             then
2860                Set_Trivial_Subprogram (Stm);
2861
2862             --  Check for explicit call cases which likely raise an exception
2863
2864             elsif Nkind (Ostm) = N_Procedure_Call_Statement then
2865                if Is_Entity_Name (Name (Ostm)) then
2866                   declare
2867                      Ent : constant Entity_Id := Entity (Name (Ostm));
2868
2869                   begin
2870                      --  If the procedure is marked No_Return, then likely it
2871                      --  raises an exception, but in any case it is not coming
2872                      --  back here, so turn on the flag.
2873
2874                      if Present (Ent)
2875                        and then Ekind (Ent) = E_Procedure
2876                        and then No_Return (Ent)
2877                      then
2878                         Set_Trivial_Subprogram (Stm);
2879                      end if;
2880                   end;
2881                end if;
2882             end if;
2883          end;
2884       end;
2885
2886       --  Check for variables that are never modified
2887
2888       declare
2889          E1, E2 : Entity_Id;
2890
2891       begin
2892          --  If there is a separate spec, then transfer Never_Set_In_Source
2893          --  flags from out parameters to the corresponding entities in the
2894          --  body. The reason we do that is we want to post error flags on
2895          --  the body entities, not the spec entities.
2896
2897          if Present (Spec_Id) then
2898             E1 := First_Entity (Spec_Id);
2899             while Present (E1) loop
2900                if Ekind (E1) = E_Out_Parameter then
2901                   E2 := First_Entity (Body_Id);
2902                   while Present (E2) loop
2903                      exit when Chars (E1) = Chars (E2);
2904                      Next_Entity (E2);
2905                   end loop;
2906
2907                   if Present (E2) then
2908                      Set_Never_Set_In_Source (E2, Never_Set_In_Source (E1));
2909                   end if;
2910                end if;
2911
2912                Next_Entity (E1);
2913             end loop;
2914          end if;
2915
2916          --  Check references in body unless it was deleted. Note that the
2917          --  check of Body_Deleted here is not just for efficiency, it is
2918          --  necessary to avoid junk warnings on formal parameters.
2919
2920          if not Body_Deleted then
2921             Check_References (Body_Id);
2922          end if;
2923       end;
2924    end Analyze_Subprogram_Body_Helper;
2925
2926    ------------------------------------
2927    -- Analyze_Subprogram_Declaration --
2928    ------------------------------------
2929
2930    procedure Analyze_Subprogram_Declaration (N : Node_Id) is
2931       Loc        : constant Source_Ptr := Sloc (N);
2932       Scop       : constant Entity_Id  := Current_Scope;
2933       Designator : Entity_Id;
2934       Form       : Node_Id;
2935       Null_Body  : Node_Id := Empty;
2936
2937    --  Start of processing for Analyze_Subprogram_Declaration
2938
2939    begin
2940       --  Null procedures are not allowed in SPARK
2941
2942       if Nkind (Specification (N)) = N_Procedure_Specification
2943         and then Null_Present (Specification (N))
2944       then
2945          Check_SPARK_Restriction ("null procedure is not allowed", N);
2946       end if;
2947
2948       --  For a null procedure, capture the profile before analysis, for
2949       --  expansion at the freeze point and at each point of call. The body
2950       --  will only be used if the procedure has preconditions. In that case
2951       --  the body is analyzed at the freeze point.
2952
2953       if Nkind (Specification (N)) = N_Procedure_Specification
2954         and then Null_Present (Specification (N))
2955         and then Expander_Active
2956       then
2957          Null_Body :=
2958            Make_Subprogram_Body (Loc,
2959              Specification =>
2960                New_Copy_Tree (Specification (N)),
2961              Declarations =>
2962                New_List,
2963              Handled_Statement_Sequence =>
2964                Make_Handled_Sequence_Of_Statements (Loc,
2965                  Statements => New_List (Make_Null_Statement (Loc))));
2966
2967          --  Create new entities for body and formals
2968
2969          Set_Defining_Unit_Name (Specification (Null_Body),
2970            Make_Defining_Identifier (Loc, Chars (Defining_Entity (N))));
2971          Set_Corresponding_Body (N, Defining_Entity (Null_Body));
2972
2973          Form := First (Parameter_Specifications (Specification (Null_Body)));
2974          while Present (Form) loop
2975             Set_Defining_Identifier (Form,
2976               Make_Defining_Identifier (Loc,
2977                 Chars (Defining_Identifier (Form))));
2978
2979             --  Resolve the types of the formals now, because the freeze point
2980             --  may appear in a different context, e.g. an instantiation.
2981
2982             if Nkind (Parameter_Type (Form)) /= N_Access_Definition then
2983                Find_Type (Parameter_Type (Form));
2984
2985             elsif
2986               No (Access_To_Subprogram_Definition (Parameter_Type (Form)))
2987             then
2988                Find_Type (Subtype_Mark (Parameter_Type (Form)));
2989
2990             else
2991
2992                --  the case of a null procedure with a formal that is an
2993                --  access_to_subprogram type, and that is used as an actual
2994                --  in an instantiation is left to the enthusiastic reader.
2995
2996                null;
2997             end if;
2998
2999             Next (Form);
3000          end loop;
3001
3002          if Is_Protected_Type (Current_Scope) then
3003             Error_Msg_N ("protected operation cannot be a null procedure", N);
3004          end if;
3005       end if;
3006
3007       Designator := Analyze_Subprogram_Specification (Specification (N));
3008       Generate_Definition (Designator);
3009       --  ??? why this call, already in Analyze_Subprogram_Specification
3010
3011       if Debug_Flag_C then
3012          Write_Str ("==> subprogram spec ");
3013          Write_Name (Chars (Designator));
3014          Write_Str (" from ");
3015          Write_Location (Sloc (N));
3016          Write_Eol;
3017          Indent;
3018       end if;
3019
3020       if Nkind (Specification (N)) = N_Procedure_Specification
3021         and then Null_Present (Specification (N))
3022       then
3023          Set_Has_Completion (Designator);
3024
3025          if Present (Null_Body) then
3026             Set_Corresponding_Body (N, Defining_Entity (Null_Body));
3027             Set_Body_To_Inline (N, Null_Body);
3028             Set_Is_Inlined (Designator);
3029          end if;
3030       end if;
3031
3032       Validate_RCI_Subprogram_Declaration (N);
3033       New_Overloaded_Entity (Designator);
3034       Check_Delayed_Subprogram (Designator);
3035
3036       --  If the type of the first formal of the current subprogram is a
3037       --  nongeneric tagged private type, mark the subprogram as being a
3038       --  private primitive. Ditto if this is a function with controlling
3039       --  result, and the return type is currently private. In both cases,
3040       --  the type of the controlling argument or result must be in the
3041       --  current scope for the operation to be primitive.
3042
3043       if Has_Controlling_Result (Designator)
3044         and then Is_Private_Type (Etype (Designator))
3045         and then Scope (Etype (Designator)) = Current_Scope
3046         and then not Is_Generic_Actual_Type (Etype (Designator))
3047       then
3048          Set_Is_Private_Primitive (Designator);
3049
3050       elsif Present (First_Formal (Designator)) then
3051          declare
3052             Formal_Typ : constant Entity_Id :=
3053                            Etype (First_Formal (Designator));
3054          begin
3055             Set_Is_Private_Primitive (Designator,
3056               Is_Tagged_Type (Formal_Typ)
3057                 and then Scope (Formal_Typ) = Current_Scope
3058                 and then Is_Private_Type (Formal_Typ)
3059                 and then not Is_Generic_Actual_Type (Formal_Typ));
3060          end;
3061       end if;
3062
3063       --  Ada 2005 (AI-251): Abstract interface primitives must be abstract
3064       --  or null.
3065
3066       if Ada_Version >= Ada_2005
3067         and then Comes_From_Source (N)
3068         and then Is_Dispatching_Operation (Designator)
3069       then
3070          declare
3071             E    : Entity_Id;
3072             Etyp : Entity_Id;
3073
3074          begin
3075             if Has_Controlling_Result (Designator) then
3076                Etyp := Etype (Designator);
3077
3078             else
3079                E := First_Entity (Designator);
3080                while Present (E)
3081                  and then Is_Formal (E)
3082                  and then not Is_Controlling_Formal (E)
3083                loop
3084                   Next_Entity (E);
3085                end loop;
3086
3087                Etyp := Etype (E);
3088             end if;
3089
3090             if Is_Access_Type (Etyp) then
3091                Etyp := Directly_Designated_Type (Etyp);
3092             end if;
3093
3094             if Is_Interface (Etyp)
3095               and then not Is_Abstract_Subprogram (Designator)
3096               and then not (Ekind (Designator) = E_Procedure
3097                               and then Null_Present (Specification (N)))
3098             then
3099                Error_Msg_Name_1 := Chars (Defining_Entity (N));
3100                Error_Msg_N
3101                  ("(Ada 2005) interface subprogram % must be abstract or null",
3102                   N);
3103             end if;
3104          end;
3105       end if;
3106
3107       --  What is the following code for, it used to be
3108
3109       --  ???   Set_Suppress_Elaboration_Checks
3110       --  ???     (Designator, Elaboration_Checks_Suppressed (Designator));
3111
3112       --  The following seems equivalent, but a bit dubious
3113
3114       if Elaboration_Checks_Suppressed (Designator) then
3115          Set_Kill_Elaboration_Checks (Designator);
3116       end if;
3117
3118       if Scop /= Standard_Standard
3119         and then not Is_Child_Unit (Designator)
3120       then
3121          Set_Categorization_From_Scope (Designator, Scop);
3122       else
3123          --  For a compilation unit, check for library-unit pragmas
3124
3125          Push_Scope (Designator);
3126          Set_Categorization_From_Pragmas (N);
3127          Validate_Categorization_Dependency (N, Designator);
3128          Pop_Scope;
3129       end if;
3130
3131       --  For a compilation unit, set body required. This flag will only be
3132       --  reset if a valid Import or Interface pragma is processed later on.
3133
3134       if Nkind (Parent (N)) = N_Compilation_Unit then
3135          Set_Body_Required (Parent (N), True);
3136
3137          if Ada_Version >= Ada_2005
3138            and then Nkind (Specification (N)) = N_Procedure_Specification
3139            and then Null_Present (Specification (N))
3140          then
3141             Error_Msg_N
3142               ("null procedure cannot be declared at library level", N);
3143          end if;
3144       end if;
3145
3146       Generate_Reference_To_Formals (Designator);
3147       Check_Eliminated (Designator);
3148
3149       if Debug_Flag_C then
3150          Outdent;
3151          Write_Str ("<== subprogram spec ");
3152          Write_Name (Chars (Designator));
3153          Write_Str (" from ");
3154          Write_Location (Sloc (N));
3155          Write_Eol;
3156       end if;
3157
3158       if Is_Protected_Type (Current_Scope) then
3159
3160          --  Indicate that this is a protected operation, because it may be
3161          --  used in subsequent declarations within the protected type.
3162
3163          Set_Convention (Designator, Convention_Protected);
3164       end if;
3165
3166       List_Inherited_Pre_Post_Aspects (Designator);
3167
3168       if Has_Aspects (N) then
3169          Analyze_Aspect_Specifications (N, Designator);
3170       end if;
3171    end Analyze_Subprogram_Declaration;
3172
3173    --------------------------------------
3174    -- Analyze_Subprogram_Specification --
3175    --------------------------------------
3176
3177    --  Reminder: N here really is a subprogram specification (not a subprogram
3178    --  declaration). This procedure is called to analyze the specification in
3179    --  both subprogram bodies and subprogram declarations (specs).
3180
3181    function Analyze_Subprogram_Specification (N : Node_Id) return Entity_Id is
3182       Designator : constant Entity_Id := Defining_Entity (N);
3183       Formals    : constant List_Id   := Parameter_Specifications (N);
3184
3185    --  Start of processing for Analyze_Subprogram_Specification
3186
3187    begin
3188       --  User-defined operator is not allowed in SPARK, except as a renaming
3189
3190       if Nkind (Defining_Unit_Name (N)) = N_Defining_Operator_Symbol
3191         and then Nkind (Parent (N)) /= N_Subprogram_Renaming_Declaration
3192       then
3193          Check_SPARK_Restriction ("user-defined operator is not allowed", N);
3194       end if;
3195
3196       --  Proceed with analysis
3197
3198       Generate_Definition (Designator);
3199       Set_Contract (Designator, Make_Contract (Sloc (Designator)));
3200
3201       if Nkind (N) = N_Function_Specification then
3202          Set_Ekind (Designator, E_Function);
3203          Set_Mechanism (Designator, Default_Mechanism);
3204       else
3205          Set_Ekind (Designator, E_Procedure);
3206          Set_Etype (Designator, Standard_Void_Type);
3207       end if;
3208
3209       --  Introduce new scope for analysis of the formals and the return type
3210
3211       Set_Scope (Designator, Current_Scope);
3212
3213       if Present (Formals) then
3214          Push_Scope (Designator);
3215          Process_Formals (Formals, N);
3216
3217          --  Ada 2005 (AI-345): If this is an overriding operation of an
3218          --  inherited interface operation, and the controlling type is
3219          --  a synchronized type, replace the type with its corresponding
3220          --  record, to match the proper signature of an overriding operation.
3221          --  Same processing for an access parameter whose designated type is
3222          --  derived from a synchronized interface.
3223
3224          if Ada_Version >= Ada_2005 then
3225             declare
3226                Formal     : Entity_Id;
3227                Formal_Typ : Entity_Id;
3228                Rec_Typ    : Entity_Id;
3229                Desig_Typ  : Entity_Id;
3230
3231             begin
3232                Formal := First_Formal (Designator);
3233                while Present (Formal) loop
3234                   Formal_Typ := Etype (Formal);
3235
3236                   if Is_Concurrent_Type (Formal_Typ)
3237                     and then Present (Corresponding_Record_Type (Formal_Typ))
3238                   then
3239                      Rec_Typ := Corresponding_Record_Type (Formal_Typ);
3240
3241                      if Present (Interfaces (Rec_Typ)) then
3242                         Set_Etype (Formal, Rec_Typ);
3243                      end if;
3244
3245                   elsif Ekind (Formal_Typ) = E_Anonymous_Access_Type then
3246                      Desig_Typ := Designated_Type (Formal_Typ);
3247
3248                      if Is_Concurrent_Type (Desig_Typ)
3249                        and then Present (Corresponding_Record_Type (Desig_Typ))
3250                      then
3251                         Rec_Typ := Corresponding_Record_Type (Desig_Typ);
3252
3253                         if Present (Interfaces (Rec_Typ)) then
3254                            Set_Directly_Designated_Type (Formal_Typ, Rec_Typ);
3255                         end if;
3256                      end if;
3257                   end if;
3258
3259                   Next_Formal (Formal);
3260                end loop;
3261             end;
3262          end if;
3263
3264          End_Scope;
3265
3266       --  The subprogram scope is pushed and popped around the processing of
3267       --  the return type for consistency with call above to Process_Formals
3268       --  (which itself can call Analyze_Return_Type), and to ensure that any
3269       --  itype created for the return type will be associated with the proper
3270       --  scope.
3271
3272       elsif Nkind (N) = N_Function_Specification then
3273          Push_Scope (Designator);
3274          Analyze_Return_Type (N);
3275          End_Scope;
3276       end if;
3277
3278       --  Function case
3279
3280       if Nkind (N) = N_Function_Specification then
3281
3282          --  Deal with operator symbol case
3283
3284          if Nkind (Designator) = N_Defining_Operator_Symbol then
3285             Valid_Operator_Definition (Designator);
3286          end if;
3287
3288          May_Need_Actuals (Designator);
3289
3290          --  Ada 2005 (AI-251): If the return type is abstract, verify that
3291          --  the subprogram is abstract also. This does not apply to renaming
3292          --  declarations, where abstractness is inherited.
3293
3294          --  In case of primitives associated with abstract interface types
3295          --  the check is applied later (see Analyze_Subprogram_Declaration).
3296
3297          if not Nkind_In (Parent (N), N_Subprogram_Renaming_Declaration,
3298                                       N_Abstract_Subprogram_Declaration,
3299                                       N_Formal_Abstract_Subprogram_Declaration)
3300          then
3301             if Is_Abstract_Type (Etype (Designator))
3302               and then not Is_Interface (Etype (Designator))
3303             then
3304                Error_Msg_N
3305                  ("function that returns abstract type must be abstract", N);
3306
3307             --  Ada 2012 (AI-0073): Extend this test to subprograms with an
3308             --  access result whose designated type is abstract.
3309
3310             elsif Nkind (Result_Definition (N)) = N_Access_Definition
3311               and then
3312                 not Is_Class_Wide_Type (Designated_Type (Etype (Designator)))
3313               and then Is_Abstract_Type (Designated_Type (Etype (Designator)))
3314               and then Ada_Version >= Ada_2012
3315             then
3316                Error_Msg_N ("function whose access result designates "
3317                  & "abstract type must be abstract", N);
3318             end if;
3319          end if;
3320       end if;
3321
3322       return Designator;
3323    end Analyze_Subprogram_Specification;
3324
3325    --------------------------
3326    -- Build_Body_To_Inline --
3327    --------------------------
3328
3329    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id) is
3330       Decl            : constant Node_Id := Unit_Declaration_Node (Subp);
3331       Original_Body   : Node_Id;
3332       Body_To_Analyze : Node_Id;
3333       Max_Size        : constant := 10;
3334       Stat_Count      : Integer := 0;
3335
3336       function Has_Excluded_Declaration (Decls : List_Id) return Boolean;
3337       --  Check for declarations that make inlining not worthwhile
3338
3339       function Has_Excluded_Statement   (Stats : List_Id) return Boolean;
3340       --  Check for statements that make inlining not worthwhile: any tasking
3341       --  statement, nested at any level. Keep track of total number of
3342       --  elementary statements, as a measure of acceptable size.
3343
3344       function Has_Pending_Instantiation return Boolean;
3345       --  If some enclosing body contains instantiations that appear before the
3346       --  corresponding generic body, the enclosing body has a freeze node so
3347       --  that it can be elaborated after the generic itself. This might
3348       --  conflict with subsequent inlinings, so that it is unsafe to try to
3349       --  inline in such a case.
3350
3351       function Has_Single_Return return Boolean;
3352       --  In general we cannot inline functions that return unconstrained type.
3353       --  However, we can handle such functions if all return statements return
3354       --  a local variable that is the only declaration in the body of the
3355       --  function. In that case the call can be replaced by that local
3356       --  variable as is done for other inlined calls.
3357
3358       procedure Remove_Pragmas;
3359       --  A pragma Unreferenced or pragma Unmodified that mentions a formal
3360       --  parameter has no meaning when the body is inlined and the formals
3361       --  are rewritten. Remove it from body to inline. The analysis of the
3362       --  non-inlined body will handle the pragma properly.
3363
3364       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean;
3365       --  If the body of the subprogram includes a call that returns an
3366       --  unconstrained type, the secondary stack is involved, and it
3367       --  is not worth inlining.
3368
3369       ------------------------------
3370       -- Has_Excluded_Declaration --
3371       ------------------------------
3372
3373       function Has_Excluded_Declaration (Decls : List_Id) return Boolean is
3374          D : Node_Id;
3375
3376          function Is_Unchecked_Conversion (D : Node_Id) return Boolean;
3377          --  Nested subprograms make a given body ineligible for inlining, but
3378          --  we make an exception for instantiations of unchecked conversion.
3379          --  The body has not been analyzed yet, so check the name, and verify
3380          --  that the visible entity with that name is the predefined unit.
3381
3382          -----------------------------
3383          -- Is_Unchecked_Conversion --
3384          -----------------------------
3385
3386          function Is_Unchecked_Conversion (D : Node_Id) return Boolean is
3387             Id   : constant Node_Id := Name (D);
3388             Conv : Entity_Id;
3389
3390          begin
3391             if Nkind (Id) = N_Identifier
3392               and then Chars (Id) = Name_Unchecked_Conversion
3393             then
3394                Conv := Current_Entity (Id);
3395
3396             elsif Nkind_In (Id, N_Selected_Component, N_Expanded_Name)
3397               and then Chars (Selector_Name (Id)) = Name_Unchecked_Conversion
3398             then
3399                Conv := Current_Entity (Selector_Name (Id));
3400             else
3401                return False;
3402             end if;
3403
3404             return Present (Conv)
3405               and then Is_Predefined_File_Name
3406                          (Unit_File_Name (Get_Source_Unit (Conv)))
3407               and then Is_Intrinsic_Subprogram (Conv);
3408          end Is_Unchecked_Conversion;
3409
3410       --  Start of processing for Has_Excluded_Declaration
3411
3412       begin
3413          D := First (Decls);
3414          while Present (D) loop
3415             if (Nkind (D) = N_Function_Instantiation
3416                   and then not Is_Unchecked_Conversion (D))
3417               or else Nkind_In (D, N_Protected_Type_Declaration,
3418                                    N_Package_Declaration,
3419                                    N_Package_Instantiation,
3420                                    N_Subprogram_Body,
3421                                    N_Procedure_Instantiation,
3422                                    N_Task_Type_Declaration)
3423             then
3424                Cannot_Inline
3425                  ("cannot inline & (non-allowed declaration)?", D, Subp);
3426                return True;
3427             end if;
3428
3429             Next (D);
3430          end loop;
3431
3432          return False;
3433       end Has_Excluded_Declaration;
3434
3435       ----------------------------
3436       -- Has_Excluded_Statement --
3437       ----------------------------
3438
3439       function Has_Excluded_Statement (Stats : List_Id) return Boolean is
3440          S : Node_Id;
3441          E : Node_Id;
3442
3443       begin
3444          S := First (Stats);
3445          while Present (S) loop
3446             Stat_Count := Stat_Count + 1;
3447
3448             if Nkind_In (S, N_Abort_Statement,
3449                             N_Asynchronous_Select,
3450                             N_Conditional_Entry_Call,
3451                             N_Delay_Relative_Statement,
3452                             N_Delay_Until_Statement,
3453                             N_Selective_Accept,
3454                             N_Timed_Entry_Call)
3455             then
3456                Cannot_Inline
3457                  ("cannot inline & (non-allowed statement)?", S, Subp);
3458                return True;
3459
3460             elsif Nkind (S) = N_Block_Statement then
3461                if Present (Declarations (S))
3462                  and then Has_Excluded_Declaration (Declarations (S))
3463                then
3464                   return True;
3465
3466                elsif Present (Handled_Statement_Sequence (S))
3467                   and then
3468                     (Present
3469                       (Exception_Handlers (Handled_Statement_Sequence (S)))
3470                      or else
3471                        Has_Excluded_Statement
3472                          (Statements (Handled_Statement_Sequence (S))))
3473                then
3474                   return True;
3475                end if;
3476
3477             elsif Nkind (S) = N_Case_Statement then
3478                E := First (Alternatives (S));
3479                while Present (E) loop
3480                   if Has_Excluded_Statement (Statements (E)) then
3481                      return True;
3482                   end if;
3483
3484                   Next (E);
3485                end loop;
3486
3487             elsif Nkind (S) = N_If_Statement then
3488                if Has_Excluded_Statement (Then_Statements (S)) then
3489                   return True;
3490                end if;
3491
3492                if Present (Elsif_Parts (S)) then
3493                   E := First (Elsif_Parts (S));
3494                   while Present (E) loop
3495                      if Has_Excluded_Statement (Then_Statements (E)) then
3496                         return True;
3497                      end if;
3498                      Next (E);
3499                   end loop;
3500                end if;
3501
3502                if Present (Else_Statements (S))
3503                  and then Has_Excluded_Statement (Else_Statements (S))
3504                then
3505                   return True;
3506                end if;
3507
3508             elsif Nkind (S) = N_Loop_Statement
3509               and then Has_Excluded_Statement (Statements (S))
3510             then
3511                return True;
3512
3513             elsif Nkind (S) = N_Extended_Return_Statement then
3514                if Has_Excluded_Statement
3515                   (Statements (Handled_Statement_Sequence (S)))
3516                  or else Present
3517                    (Exception_Handlers (Handled_Statement_Sequence (S)))
3518                then
3519                   return True;
3520                end if;
3521             end if;
3522
3523             Next (S);
3524          end loop;
3525
3526          return False;
3527       end Has_Excluded_Statement;
3528
3529       -------------------------------
3530       -- Has_Pending_Instantiation --
3531       -------------------------------
3532
3533       function Has_Pending_Instantiation return Boolean is
3534          S : Entity_Id;
3535
3536       begin
3537          S := Current_Scope;
3538          while Present (S) loop
3539             if Is_Compilation_Unit (S)
3540               or else Is_Child_Unit (S)
3541             then
3542                return False;
3543
3544             elsif Ekind (S) = E_Package
3545               and then Has_Forward_Instantiation (S)
3546             then
3547                return True;
3548             end if;
3549
3550             S := Scope (S);
3551          end loop;
3552
3553          return False;
3554       end Has_Pending_Instantiation;
3555
3556       ------------------------
3557       --  Has_Single_Return --
3558       ------------------------
3559
3560       function Has_Single_Return return Boolean is
3561          Return_Statement : Node_Id := Empty;
3562
3563          function Check_Return (N : Node_Id) return Traverse_Result;
3564
3565          ------------------
3566          -- Check_Return --
3567          ------------------
3568
3569          function Check_Return (N : Node_Id) return Traverse_Result is
3570          begin
3571             if Nkind (N) = N_Simple_Return_Statement then
3572                if Present (Expression (N))
3573                  and then Is_Entity_Name (Expression (N))
3574                then
3575                   if No (Return_Statement) then
3576                      Return_Statement := N;
3577                      return OK;
3578
3579                   elsif Chars (Expression (N)) =
3580                         Chars (Expression (Return_Statement))
3581                   then
3582                      return OK;
3583
3584                   else
3585                      return Abandon;
3586                   end if;
3587
3588                --  A return statement within an extended return is a noop
3589                --  after inlining.
3590
3591                elsif No (Expression (N))
3592                  and then Nkind (Parent (Parent (N))) =
3593                  N_Extended_Return_Statement
3594                then
3595                   return OK;
3596
3597                else
3598                   --  Expression has wrong form
3599
3600                   return Abandon;
3601                end if;
3602
3603             --  We can only inline a build-in-place function if
3604             --  it has a single extended return.
3605
3606             elsif Nkind (N) = N_Extended_Return_Statement then
3607                if No (Return_Statement) then
3608                   Return_Statement := N;
3609                   return OK;
3610
3611                else
3612                   return Abandon;
3613                end if;
3614
3615             else
3616                return OK;
3617             end if;
3618          end Check_Return;
3619
3620          function Check_All_Returns is new Traverse_Func (Check_Return);
3621
3622       --  Start of processing for Has_Single_Return
3623
3624       begin
3625          if Check_All_Returns (N) /= OK then
3626             return False;
3627
3628          elsif Nkind (Return_Statement) = N_Extended_Return_Statement then
3629             return True;
3630
3631          else
3632             return Present (Declarations (N))
3633               and then Present (First (Declarations (N)))
3634               and then Chars (Expression (Return_Statement)) =
3635                  Chars (Defining_Identifier (First (Declarations (N))));
3636          end if;
3637       end Has_Single_Return;
3638
3639       --------------------
3640       -- Remove_Pragmas --
3641       --------------------
3642
3643       procedure Remove_Pragmas is
3644          Decl : Node_Id;
3645          Nxt  : Node_Id;
3646
3647       begin
3648          Decl := First (Declarations (Body_To_Analyze));
3649          while Present (Decl) loop
3650             Nxt := Next (Decl);
3651
3652             if Nkind (Decl) = N_Pragma
3653               and then (Pragma_Name (Decl) = Name_Unreferenced
3654                           or else
3655                         Pragma_Name (Decl) = Name_Unmodified)
3656             then
3657                Remove (Decl);
3658             end if;
3659
3660             Decl := Nxt;
3661          end loop;
3662       end Remove_Pragmas;
3663
3664       --------------------------
3665       -- Uses_Secondary_Stack --
3666       --------------------------
3667
3668       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean is
3669          function Check_Call (N : Node_Id) return Traverse_Result;
3670          --  Look for function calls that return an unconstrained type
3671
3672          ----------------
3673          -- Check_Call --
3674          ----------------
3675
3676          function Check_Call (N : Node_Id) return Traverse_Result is
3677          begin
3678             if Nkind (N) = N_Function_Call
3679               and then Is_Entity_Name (Name (N))
3680               and then Is_Composite_Type (Etype (Entity (Name (N))))
3681               and then not Is_Constrained (Etype (Entity (Name (N))))
3682             then
3683                Cannot_Inline
3684                  ("cannot inline & (call returns unconstrained type)?",
3685                     N, Subp);
3686                return Abandon;
3687             else
3688                return OK;
3689             end if;
3690          end Check_Call;
3691
3692          function Check_Calls is new Traverse_Func (Check_Call);
3693
3694       begin
3695          return Check_Calls (Bod) = Abandon;
3696       end Uses_Secondary_Stack;
3697
3698    --  Start of processing for Build_Body_To_Inline
3699
3700    begin
3701       --  Return immediately if done already
3702
3703       if Nkind (Decl) = N_Subprogram_Declaration
3704         and then Present (Body_To_Inline (Decl))
3705       then
3706          return;
3707
3708       --  Functions that return unconstrained composite types require
3709       --  secondary stack handling, and cannot currently be inlined, unless
3710       --  all return statements return a local variable that is the first
3711       --  local declaration in the body.
3712
3713       elsif Ekind (Subp) = E_Function
3714         and then not Is_Scalar_Type (Etype (Subp))
3715         and then not Is_Access_Type (Etype (Subp))
3716         and then not Is_Constrained (Etype (Subp))
3717       then
3718          if not Has_Single_Return then
3719             Cannot_Inline
3720               ("cannot inline & (unconstrained return type)?", N, Subp);
3721             return;
3722          end if;
3723
3724       --  Ditto for functions that return controlled types, where controlled
3725       --  actions interfere in complex ways with inlining.
3726
3727       elsif Ekind (Subp) = E_Function
3728         and then Needs_Finalization (Etype (Subp))
3729       then
3730          Cannot_Inline
3731            ("cannot inline & (controlled return type)?", N, Subp);
3732          return;
3733       end if;
3734
3735       if Present (Declarations (N))
3736         and then Has_Excluded_Declaration (Declarations (N))
3737       then
3738          return;
3739       end if;
3740
3741       if Present (Handled_Statement_Sequence (N)) then
3742          if Present (Exception_Handlers (Handled_Statement_Sequence (N))) then
3743             Cannot_Inline
3744               ("cannot inline& (exception handler)?",
3745                First (Exception_Handlers (Handled_Statement_Sequence (N))),
3746                Subp);
3747             return;
3748          elsif
3749            Has_Excluded_Statement
3750              (Statements (Handled_Statement_Sequence (N)))
3751          then
3752             return;
3753          end if;
3754       end if;
3755
3756       --  We do not inline a subprogram  that is too large, unless it is
3757       --  marked Inline_Always. This pragma does not suppress the other
3758       --  checks on inlining (forbidden declarations, handlers, etc).
3759
3760       if Stat_Count > Max_Size
3761         and then not Has_Pragma_Inline_Always (Subp)
3762       then
3763          Cannot_Inline ("cannot inline& (body too large)?", N, Subp);
3764          return;
3765       end if;
3766
3767       if Has_Pending_Instantiation then
3768          Cannot_Inline
3769            ("cannot inline& (forward instance within enclosing body)?",
3770              N, Subp);
3771          return;
3772       end if;
3773
3774       --  Within an instance, the body to inline must be treated as a nested
3775       --  generic, so that the proper global references are preserved.
3776
3777       --  Note that we do not do this at the library level, because it is not
3778       --  needed, and furthermore this causes trouble if front end inlining
3779       --  is activated (-gnatN).
3780
3781       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
3782          Save_Env (Scope (Current_Scope), Scope (Current_Scope));
3783          Original_Body := Copy_Generic_Node (N, Empty, True);
3784       else
3785          Original_Body := Copy_Separate_Tree (N);
3786       end if;
3787
3788       --  We need to capture references to the formals in order to substitute
3789       --  the actuals at the point of inlining, i.e. instantiation. To treat
3790       --  the formals as globals to the body to inline, we nest it within
3791       --  a dummy parameterless subprogram, declared within the real one.
3792       --  To avoid generating an internal name (which is never public, and
3793       --  which affects serial numbers of other generated names), we use
3794       --  an internal symbol that cannot conflict with user declarations.
3795
3796       Set_Parameter_Specifications (Specification (Original_Body), No_List);
3797       Set_Defining_Unit_Name
3798         (Specification (Original_Body),
3799           Make_Defining_Identifier (Sloc (N), Name_uParent));
3800       Set_Corresponding_Spec (Original_Body, Empty);
3801
3802       Body_To_Analyze := Copy_Generic_Node (Original_Body, Empty, False);
3803
3804       --  Set return type of function, which is also global and does not need
3805       --  to be resolved.
3806
3807       if Ekind (Subp) = E_Function then
3808          Set_Result_Definition (Specification (Body_To_Analyze),
3809            New_Occurrence_Of (Etype (Subp), Sloc (N)));
3810       end if;
3811
3812       if No (Declarations (N)) then
3813          Set_Declarations (N, New_List (Body_To_Analyze));
3814       else
3815          Append (Body_To_Analyze, Declarations (N));
3816       end if;
3817
3818       Expander_Mode_Save_And_Set (False);
3819       Remove_Pragmas;
3820
3821       Analyze (Body_To_Analyze);
3822       Push_Scope (Defining_Entity (Body_To_Analyze));
3823       Save_Global_References (Original_Body);
3824       End_Scope;
3825       Remove (Body_To_Analyze);
3826
3827       Expander_Mode_Restore;
3828
3829       --  Restore environment if previously saved
3830
3831       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
3832          Restore_Env;
3833       end if;
3834
3835       --  If secondary stk used there is no point in inlining. We have
3836       --  already issued the warning in this case, so nothing to do.
3837
3838       if Uses_Secondary_Stack (Body_To_Analyze) then
3839          return;
3840       end if;
3841
3842       Set_Body_To_Inline (Decl, Original_Body);
3843       Set_Ekind (Defining_Entity (Original_Body), Ekind (Subp));
3844       Set_Is_Inlined (Subp);
3845    end Build_Body_To_Inline;
3846
3847    -------------------
3848    -- Cannot_Inline --
3849    -------------------
3850
3851    procedure Cannot_Inline (Msg : String; N : Node_Id; Subp : Entity_Id) is
3852    begin
3853       --  Do not emit warning if this is a predefined unit which is not the
3854       --  main unit. With validity checks enabled, some predefined subprograms
3855       --  may contain nested subprograms and become ineligible for inlining.
3856
3857       if Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Subp)))
3858         and then not In_Extended_Main_Source_Unit (Subp)
3859       then
3860          null;
3861
3862       elsif Has_Pragma_Inline_Always (Subp) then
3863
3864          --  Remove last character (question mark) to make this into an error,
3865          --  because the Inline_Always pragma cannot be obeyed.
3866
3867          Error_Msg_NE (Msg (Msg'First .. Msg'Last - 1), N, Subp);
3868
3869       elsif Ineffective_Inline_Warnings then
3870          Error_Msg_NE (Msg, N, Subp);
3871       end if;
3872    end Cannot_Inline;
3873
3874    -----------------------
3875    -- Check_Conformance --
3876    -----------------------
3877
3878    procedure Check_Conformance
3879      (New_Id                   : Entity_Id;
3880       Old_Id                   : Entity_Id;
3881       Ctype                    : Conformance_Type;
3882       Errmsg                   : Boolean;
3883       Conforms                 : out Boolean;
3884       Err_Loc                  : Node_Id := Empty;
3885       Get_Inst                 : Boolean := False;
3886       Skip_Controlling_Formals : Boolean := False)
3887    is
3888       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id);
3889       --  Sets Conforms to False. If Errmsg is False, then that's all it does.
3890       --  If Errmsg is True, then processing continues to post an error message
3891       --  for conformance error on given node. Two messages are output. The
3892       --  first message points to the previous declaration with a general "no
3893       --  conformance" message. The second is the detailed reason, supplied as
3894       --  Msg. The parameter N provide information for a possible & insertion
3895       --  in the message, and also provides the location for posting the
3896       --  message in the absence of a specified Err_Loc location.
3897
3898       -----------------------
3899       -- Conformance_Error --
3900       -----------------------
3901
3902       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id) is
3903          Enode : Node_Id;
3904
3905       begin
3906          Conforms := False;
3907
3908          if Errmsg then
3909             if No (Err_Loc) then
3910                Enode := N;
3911             else
3912                Enode := Err_Loc;
3913             end if;
3914
3915             Error_Msg_Sloc := Sloc (Old_Id);
3916
3917             case Ctype is
3918                when Type_Conformant =>
3919                   Error_Msg_N -- CODEFIX
3920                     ("not type conformant with declaration#!", Enode);
3921
3922                when Mode_Conformant =>
3923                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3924                      Error_Msg_N
3925                        ("not mode conformant with operation inherited#!",
3926                          Enode);
3927                   else
3928                      Error_Msg_N
3929                        ("not mode conformant with declaration#!", Enode);
3930                   end if;
3931
3932                when Subtype_Conformant =>
3933                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3934                      Error_Msg_N
3935                        ("not subtype conformant with operation inherited#!",
3936                          Enode);
3937                   else
3938                      Error_Msg_N
3939                        ("not subtype conformant with declaration#!", Enode);
3940                   end if;
3941
3942                when Fully_Conformant =>
3943                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3944                      Error_Msg_N -- CODEFIX
3945                        ("not fully conformant with operation inherited#!",
3946                          Enode);
3947                   else
3948                      Error_Msg_N -- CODEFIX
3949                        ("not fully conformant with declaration#!", Enode);
3950                   end if;
3951             end case;
3952
3953             Error_Msg_NE (Msg, Enode, N);
3954          end if;
3955       end Conformance_Error;
3956
3957       --  Local Variables
3958
3959       Old_Type           : constant Entity_Id := Etype (Old_Id);
3960       New_Type           : constant Entity_Id := Etype (New_Id);
3961       Old_Formal         : Entity_Id;
3962       New_Formal         : Entity_Id;
3963       Access_Types_Match : Boolean;
3964       Old_Formal_Base    : Entity_Id;
3965       New_Formal_Base    : Entity_Id;
3966
3967    --  Start of processing for Check_Conformance
3968
3969    begin
3970       Conforms := True;
3971
3972       --  We need a special case for operators, since they don't appear
3973       --  explicitly.
3974
3975       if Ctype = Type_Conformant then
3976          if Ekind (New_Id) = E_Operator
3977            and then Operator_Matches_Spec (New_Id, Old_Id)
3978          then
3979             return;
3980          end if;
3981       end if;
3982
3983       --  If both are functions/operators, check return types conform
3984
3985       if Old_Type /= Standard_Void_Type
3986         and then New_Type /= Standard_Void_Type
3987       then
3988
3989          --  If we are checking interface conformance we omit controlling
3990          --  arguments and result, because we are only checking the conformance
3991          --  of the remaining parameters.
3992
3993          if Has_Controlling_Result (Old_Id)
3994            and then Has_Controlling_Result (New_Id)
3995            and then Skip_Controlling_Formals
3996          then
3997             null;
3998
3999          elsif not Conforming_Types (Old_Type, New_Type, Ctype, Get_Inst) then
4000             Conformance_Error ("\return type does not match!", New_Id);
4001             return;
4002          end if;
4003
4004          --  Ada 2005 (AI-231): In case of anonymous access types check the
4005          --  null-exclusion and access-to-constant attributes match.
4006
4007          if Ada_Version >= Ada_2005
4008            and then Ekind (Etype (Old_Type)) = E_Anonymous_Access_Type
4009            and then
4010              (Can_Never_Be_Null (Old_Type)
4011                 /= Can_Never_Be_Null (New_Type)
4012               or else Is_Access_Constant (Etype (Old_Type))
4013                         /= Is_Access_Constant (Etype (New_Type)))
4014          then
4015             Conformance_Error ("\return type does not match!", New_Id);
4016             return;
4017          end if;
4018
4019       --  If either is a function/operator and the other isn't, error
4020
4021       elsif Old_Type /= Standard_Void_Type
4022         or else New_Type /= Standard_Void_Type
4023       then
4024          Conformance_Error ("\functions can only match functions!", New_Id);
4025          return;
4026       end if;
4027
4028       --  In subtype conformant case, conventions must match (RM 6.3.1(16)).
4029       --  If this is a renaming as body, refine error message to indicate that
4030       --  the conflict is with the original declaration. If the entity is not
4031       --  frozen, the conventions don't have to match, the one of the renamed
4032       --  entity is inherited.
4033
4034       if Ctype >= Subtype_Conformant then
4035          if Convention (Old_Id) /= Convention (New_Id) then
4036
4037             if not Is_Frozen (New_Id) then
4038                null;
4039
4040             elsif Present (Err_Loc)
4041               and then Nkind (Err_Loc) = N_Subprogram_Renaming_Declaration
4042               and then Present (Corresponding_Spec (Err_Loc))
4043             then
4044                Error_Msg_Name_1 := Chars (New_Id);
4045                Error_Msg_Name_2 :=
4046                  Name_Ada + Convention_Id'Pos (Convention (New_Id));
4047                Conformance_Error ("\prior declaration for% has convention %!");
4048
4049             else
4050                Conformance_Error ("\calling conventions do not match!");
4051             end if;
4052
4053             return;
4054
4055          elsif Is_Formal_Subprogram (Old_Id)
4056            or else Is_Formal_Subprogram (New_Id)
4057          then
4058             Conformance_Error ("\formal subprograms not allowed!");
4059             return;
4060          end if;
4061       end if;
4062
4063       --  Deal with parameters
4064
4065       --  Note: we use the entity information, rather than going directly
4066       --  to the specification in the tree. This is not only simpler, but
4067       --  absolutely necessary for some cases of conformance tests between
4068       --  operators, where the declaration tree simply does not exist!
4069
4070       Old_Formal := First_Formal (Old_Id);
4071       New_Formal := First_Formal (New_Id);
4072       while Present (Old_Formal) and then Present (New_Formal) loop
4073          if Is_Controlling_Formal (Old_Formal)
4074            and then Is_Controlling_Formal (New_Formal)
4075            and then Skip_Controlling_Formals
4076          then
4077             --  The controlling formals will have different types when
4078             --  comparing an interface operation with its match, but both
4079             --  or neither must be access parameters.
4080
4081             if Is_Access_Type (Etype (Old_Formal))
4082                  =
4083                Is_Access_Type (Etype (New_Formal))
4084             then
4085                goto Skip_Controlling_Formal;
4086             else
4087                Conformance_Error
4088                  ("\access parameter does not match!", New_Formal);
4089             end if;
4090          end if;
4091
4092          if Ctype = Fully_Conformant then
4093
4094             --  Names must match. Error message is more accurate if we do
4095             --  this before checking that the types of the formals match.
4096
4097             if Chars (Old_Formal) /= Chars (New_Formal) then
4098                Conformance_Error ("\name & does not match!", New_Formal);
4099
4100                --  Set error posted flag on new formal as well to stop
4101                --  junk cascaded messages in some cases.
4102
4103                Set_Error_Posted (New_Formal);
4104                return;
4105             end if;
4106
4107             --  Null exclusion must match
4108
4109             if Null_Exclusion_Present (Parent (Old_Formal))
4110                  /=
4111                Null_Exclusion_Present (Parent (New_Formal))
4112             then
4113                --  Only give error if both come from source. This should be
4114                --  investigated some time, since it should not be needed ???
4115
4116                if Comes_From_Source (Old_Formal)
4117                     and then
4118                   Comes_From_Source (New_Formal)
4119                then
4120                   Conformance_Error
4121                     ("\null exclusion for & does not match", New_Formal);
4122
4123                   --  Mark error posted on the new formal to avoid duplicated
4124                   --  complaint about types not matching.
4125
4126                   Set_Error_Posted (New_Formal);
4127                end if;
4128             end if;
4129          end if;
4130
4131          --  Ada 2005 (AI-423): Possible access [sub]type and itype match. This
4132          --  case occurs whenever a subprogram is being renamed and one of its
4133          --  parameters imposes a null exclusion. For example:
4134
4135          --     type T is null record;
4136          --     type Acc_T is access T;
4137          --     subtype Acc_T_Sub is Acc_T;
4138
4139          --     procedure P     (Obj : not null Acc_T_Sub);  --  itype
4140          --     procedure Ren_P (Obj :          Acc_T_Sub)   --  subtype
4141          --       renames P;
4142
4143          Old_Formal_Base := Etype (Old_Formal);
4144          New_Formal_Base := Etype (New_Formal);
4145
4146          if Get_Inst then
4147             Old_Formal_Base := Get_Instance_Of (Old_Formal_Base);
4148             New_Formal_Base := Get_Instance_Of (New_Formal_Base);
4149          end if;
4150
4151          Access_Types_Match := Ada_Version >= Ada_2005
4152
4153             --  Ensure that this rule is only applied when New_Id is a
4154             --  renaming of Old_Id.
4155
4156            and then Nkind (Parent (Parent (New_Id))) =
4157                       N_Subprogram_Renaming_Declaration
4158            and then Nkind (Name (Parent (Parent (New_Id)))) in N_Has_Entity
4159            and then Present (Entity (Name (Parent (Parent (New_Id)))))
4160            and then Entity (Name (Parent (Parent (New_Id)))) = Old_Id
4161
4162             --  Now handle the allowed access-type case
4163
4164            and then Is_Access_Type (Old_Formal_Base)
4165            and then Is_Access_Type (New_Formal_Base)
4166
4167             --  The type kinds must match. The only exception occurs with
4168             --  multiple generics of the form:
4169
4170             --   generic                    generic
4171             --     type F is private;         type A is private;
4172             --     type F_Ptr is access F;    type A_Ptr is access A;
4173             --     with proc F_P (X : F_Ptr); with proc A_P (X : A_Ptr);
4174             --   package F_Pack is ...      package A_Pack is
4175             --                                package F_Inst is
4176             --                                  new F_Pack (A, A_Ptr, A_P);
4177
4178             --  When checking for conformance between the parameters of A_P
4179             --  and F_P, the type kinds of F_Ptr and A_Ptr will not match
4180             --  because the compiler has transformed A_Ptr into a subtype of
4181             --  F_Ptr. We catch this case in the code below.
4182
4183            and then (Ekind (Old_Formal_Base) = Ekind (New_Formal_Base)
4184                   or else
4185                     (Is_Generic_Type (Old_Formal_Base)
4186                        and then Is_Generic_Type (New_Formal_Base)
4187                        and then Is_Internal (New_Formal_Base)
4188                        and then Etype (Etype (New_Formal_Base)) =
4189                                   Old_Formal_Base))
4190            and then Directly_Designated_Type (Old_Formal_Base) =
4191                       Directly_Designated_Type (New_Formal_Base)
4192            and then ((Is_Itype (Old_Formal_Base)
4193                        and then Can_Never_Be_Null (Old_Formal_Base))
4194                     or else
4195                      (Is_Itype (New_Formal_Base)
4196                        and then Can_Never_Be_Null (New_Formal_Base)));
4197
4198          --  Types must always match. In the visible part of an instance,
4199          --  usual overloading rules for dispatching operations apply, and
4200          --  we check base types (not the actual subtypes).
4201
4202          if In_Instance_Visible_Part
4203            and then Is_Dispatching_Operation (New_Id)
4204          then
4205             if not Conforming_Types
4206                      (T1       => Base_Type (Etype (Old_Formal)),
4207                       T2       => Base_Type (Etype (New_Formal)),
4208                       Ctype    => Ctype,
4209                       Get_Inst => Get_Inst)
4210                and then not Access_Types_Match
4211             then
4212                Conformance_Error ("\type of & does not match!", New_Formal);
4213                return;
4214             end if;
4215
4216          elsif not Conforming_Types
4217                      (T1       => Old_Formal_Base,
4218                       T2       => New_Formal_Base,
4219                       Ctype    => Ctype,
4220                       Get_Inst => Get_Inst)
4221            and then not Access_Types_Match
4222          then
4223             --  Don't give error message if old type is Any_Type. This test
4224             --  avoids some cascaded errors, e.g. in case of a bad spec.
4225
4226             if Errmsg and then Old_Formal_Base = Any_Type then
4227                Conforms := False;
4228             else
4229                Conformance_Error ("\type of & does not match!", New_Formal);
4230             end if;
4231
4232             return;
4233          end if;
4234
4235          --  For mode conformance, mode must match
4236
4237          if Ctype >= Mode_Conformant then
4238             if Parameter_Mode (Old_Formal) /= Parameter_Mode (New_Formal) then
4239                if not Ekind_In (New_Id, E_Function, E_Procedure)
4240                  or else not Is_Primitive_Wrapper (New_Id)
4241                then
4242                   Conformance_Error ("\mode of & does not match!", New_Formal);
4243
4244                else
4245                   declare
4246                      T : constant  Entity_Id := Find_Dispatching_Type (New_Id);
4247                   begin
4248                      if Is_Protected_Type
4249                           (Corresponding_Concurrent_Type (T))
4250                      then
4251                         Error_Msg_PT (T, New_Id);
4252                      else
4253                         Conformance_Error
4254                           ("\mode of & does not match!", New_Formal);
4255                      end if;
4256                   end;
4257                end if;
4258
4259                return;
4260
4261             --  Part of mode conformance for access types is having the same
4262             --  constant modifier.
4263
4264             elsif Access_Types_Match
4265               and then Is_Access_Constant (Old_Formal_Base) /=
4266                        Is_Access_Constant (New_Formal_Base)
4267             then
4268                Conformance_Error
4269                  ("\constant modifier does not match!", New_Formal);
4270                return;
4271             end if;
4272          end if;
4273
4274          if Ctype >= Subtype_Conformant then
4275
4276             --  Ada 2005 (AI-231): In case of anonymous access types check
4277             --  the null-exclusion and access-to-constant attributes must
4278             --  match. For null exclusion, we test the types rather than the
4279             --  formals themselves, since the attribute is only set reliably
4280             --  on the formals in the Ada 95 case, and we exclude the case
4281             --  where Old_Formal is marked as controlling, to avoid errors
4282             --  when matching completing bodies with dispatching declarations
4283             --  (access formals in the bodies aren't marked Can_Never_Be_Null).
4284
4285             if Ada_Version >= Ada_2005
4286               and then Ekind (Etype (Old_Formal)) = E_Anonymous_Access_Type
4287               and then Ekind (Etype (New_Formal)) = E_Anonymous_Access_Type
4288               and then
4289                 ((Can_Never_Be_Null (Etype (Old_Formal)) /=
4290                   Can_Never_Be_Null (Etype (New_Formal))
4291                     and then
4292                       not Is_Controlling_Formal (Old_Formal))
4293                    or else
4294                  Is_Access_Constant (Etype (Old_Formal)) /=
4295                  Is_Access_Constant (Etype (New_Formal)))
4296
4297               --  Do not complain if error already posted on New_Formal. This
4298               --  avoids some redundant error messages.
4299
4300               and then not Error_Posted (New_Formal)
4301             then
4302                --  It is allowed to omit the null-exclusion in case of stream
4303                --  attribute subprograms. We recognize stream subprograms
4304                --  through their TSS-generated suffix.
4305
4306                declare
4307                   TSS_Name : constant TSS_Name_Type := Get_TSS_Name (New_Id);
4308                begin
4309                   if TSS_Name /= TSS_Stream_Read
4310                     and then TSS_Name /= TSS_Stream_Write
4311                     and then TSS_Name /= TSS_Stream_Input
4312                     and then TSS_Name /= TSS_Stream_Output
4313                   then
4314                      Conformance_Error
4315                        ("\type of & does not match!", New_Formal);
4316                      return;
4317                   end if;
4318                end;
4319             end if;
4320          end if;
4321
4322          --  Full conformance checks
4323
4324          if Ctype = Fully_Conformant then
4325
4326             --  We have checked already that names match
4327
4328             if Parameter_Mode (Old_Formal) = E_In_Parameter then
4329
4330                --  Check default expressions for in parameters
4331
4332                declare
4333                   NewD : constant Boolean :=
4334                            Present (Default_Value (New_Formal));
4335                   OldD : constant Boolean :=
4336                            Present (Default_Value (Old_Formal));
4337                begin
4338                   if NewD or OldD then
4339
4340                      --  The old default value has been analyzed because the
4341                      --  current full declaration will have frozen everything
4342                      --  before. The new default value has not been analyzed,
4343                      --  so analyze it now before we check for conformance.
4344
4345                      if NewD then
4346                         Push_Scope (New_Id);
4347                         Preanalyze_Spec_Expression
4348                           (Default_Value (New_Formal), Etype (New_Formal));
4349                         End_Scope;
4350                      end if;
4351
4352                      if not (NewD and OldD)
4353                        or else not Fully_Conformant_Expressions
4354                                     (Default_Value (Old_Formal),
4355                                      Default_Value (New_Formal))
4356                      then
4357                         Conformance_Error
4358                           ("\default expression for & does not match!",
4359                            New_Formal);
4360                         return;
4361                      end if;
4362                   end if;
4363                end;
4364             end if;
4365          end if;
4366
4367          --  A couple of special checks for Ada 83 mode. These checks are
4368          --  skipped if either entity is an operator in package Standard,
4369          --  or if either old or new instance is not from the source program.
4370
4371          if Ada_Version = Ada_83
4372            and then Sloc (Old_Id) > Standard_Location
4373            and then Sloc (New_Id) > Standard_Location
4374            and then Comes_From_Source (Old_Id)
4375            and then Comes_From_Source (New_Id)
4376          then
4377             declare
4378                Old_Param : constant Node_Id := Declaration_Node (Old_Formal);
4379                New_Param : constant Node_Id := Declaration_Node (New_Formal);
4380
4381             begin
4382                --  Explicit IN must be present or absent in both cases. This
4383                --  test is required only in the full conformance case.
4384
4385                if In_Present (Old_Param) /= In_Present (New_Param)
4386                  and then Ctype = Fully_Conformant
4387                then
4388                   Conformance_Error
4389                     ("\(Ada 83) IN must appear in both declarations",
4390                      New_Formal);
4391                   return;
4392                end if;
4393
4394                --  Grouping (use of comma in param lists) must be the same
4395                --  This is where we catch a misconformance like:
4396
4397                --    A, B : Integer
4398                --    A : Integer; B : Integer
4399
4400                --  which are represented identically in the tree except
4401                --  for the setting of the flags More_Ids and Prev_Ids.
4402
4403                if More_Ids (Old_Param) /= More_Ids (New_Param)
4404                  or else Prev_Ids (Old_Param) /= Prev_Ids (New_Param)
4405                then
4406                   Conformance_Error
4407                     ("\grouping of & does not match!", New_Formal);
4408                   return;
4409                end if;
4410             end;
4411          end if;
4412
4413          --  This label is required when skipping controlling formals
4414
4415          <<Skip_Controlling_Formal>>
4416
4417          Next_Formal (Old_Formal);
4418          Next_Formal (New_Formal);
4419       end loop;
4420
4421       if Present (Old_Formal) then
4422          Conformance_Error ("\too few parameters!");
4423          return;
4424
4425       elsif Present (New_Formal) then
4426          Conformance_Error ("\too many parameters!", New_Formal);
4427          return;
4428       end if;
4429    end Check_Conformance;
4430
4431    -----------------------
4432    -- Check_Conventions --
4433    -----------------------
4434
4435    procedure Check_Conventions (Typ : Entity_Id) is
4436       Ifaces_List : Elist_Id;
4437
4438       procedure Check_Convention (Op : Entity_Id);
4439       --  Verify that the convention of inherited dispatching operation Op is
4440       --  consistent among all subprograms it overrides. In order to minimize
4441       --  the search, Search_From is utilized to designate a specific point in
4442       --  the list rather than iterating over the whole list once more.
4443
4444       ----------------------
4445       -- Check_Convention --
4446       ----------------------
4447
4448       procedure Check_Convention (Op : Entity_Id) is
4449          Iface_Elmt      : Elmt_Id;
4450          Iface_Prim_Elmt : Elmt_Id;
4451          Iface_Prim      : Entity_Id;
4452
4453       begin
4454          Iface_Elmt := First_Elmt (Ifaces_List);
4455          while Present (Iface_Elmt) loop
4456             Iface_Prim_Elmt :=
4457                First_Elmt (Primitive_Operations (Node (Iface_Elmt)));
4458             while Present (Iface_Prim_Elmt) loop
4459                Iface_Prim := Node (Iface_Prim_Elmt);
4460
4461                if Is_Interface_Conformant (Typ, Iface_Prim, Op)
4462                  and then Convention (Iface_Prim) /= Convention (Op)
4463                then
4464                   Error_Msg_N
4465                     ("inconsistent conventions in primitive operations", Typ);
4466
4467                   Error_Msg_Name_1 := Chars (Op);
4468                   Error_Msg_Name_2 := Get_Convention_Name (Convention (Op));
4469                   Error_Msg_Sloc   := Sloc (Op);
4470
4471                   if Comes_From_Source (Op) or else No (Alias (Op)) then
4472                      if not Present (Overridden_Operation (Op)) then
4473                         Error_Msg_N ("\\primitive % defined #", Typ);
4474                      else
4475                         Error_Msg_N
4476                           ("\\overriding operation % with " &
4477                            "convention % defined #", Typ);
4478                      end if;
4479
4480                   else pragma Assert (Present (Alias (Op)));
4481                      Error_Msg_Sloc := Sloc (Alias (Op));
4482                      Error_Msg_N
4483                        ("\\inherited operation % with " &
4484                         "convention % defined #", Typ);
4485                   end if;
4486
4487                   Error_Msg_Name_1 := Chars (Op);
4488                   Error_Msg_Name_2 :=
4489                     Get_Convention_Name (Convention (Iface_Prim));
4490                   Error_Msg_Sloc := Sloc (Iface_Prim);
4491                   Error_Msg_N
4492                     ("\\overridden operation % with " &
4493                      "convention % defined #", Typ);
4494
4495                   --  Avoid cascading errors
4496
4497                   return;
4498                end if;
4499
4500                Next_Elmt (Iface_Prim_Elmt);
4501             end loop;
4502
4503             Next_Elmt (Iface_Elmt);
4504          end loop;
4505       end Check_Convention;
4506
4507       --  Local variables
4508
4509       Prim_Op      : Entity_Id;
4510       Prim_Op_Elmt : Elmt_Id;
4511
4512    --  Start of processing for Check_Conventions
4513
4514    begin
4515       if not Has_Interfaces (Typ) then
4516          return;
4517       end if;
4518
4519       Collect_Interfaces (Typ, Ifaces_List);
4520
4521       --  The algorithm checks every overriding dispatching operation against
4522       --  all the corresponding overridden dispatching operations, detecting
4523       --  differences in conventions.
4524
4525       Prim_Op_Elmt := First_Elmt (Primitive_Operations (Typ));
4526       while Present (Prim_Op_Elmt) loop
4527          Prim_Op := Node (Prim_Op_Elmt);
4528
4529          --  A small optimization: skip the predefined dispatching operations
4530          --  since they always have the same convention.
4531
4532          if not Is_Predefined_Dispatching_Operation (Prim_Op) then
4533             Check_Convention (Prim_Op);
4534          end if;
4535
4536          Next_Elmt (Prim_Op_Elmt);
4537       end loop;
4538    end Check_Conventions;
4539
4540    ------------------------------
4541    -- Check_Delayed_Subprogram --
4542    ------------------------------
4543
4544    procedure Check_Delayed_Subprogram (Designator : Entity_Id) is
4545       F : Entity_Id;
4546
4547       procedure Possible_Freeze (T : Entity_Id);
4548       --  T is the type of either a formal parameter or of the return type.
4549       --  If T is not yet frozen and needs a delayed freeze, then the
4550       --  subprogram itself must be delayed. If T is the limited view of an
4551       --  incomplete type the subprogram must be frozen as well, because
4552       --  T may depend on local types that have not been frozen yet.
4553
4554       ---------------------
4555       -- Possible_Freeze --
4556       ---------------------
4557
4558       procedure Possible_Freeze (T : Entity_Id) is
4559       begin
4560          if Has_Delayed_Freeze (T) and then not Is_Frozen (T) then
4561             Set_Has_Delayed_Freeze (Designator);
4562
4563          elsif Is_Access_Type (T)
4564            and then Has_Delayed_Freeze (Designated_Type (T))
4565            and then not Is_Frozen (Designated_Type (T))
4566          then
4567             Set_Has_Delayed_Freeze (Designator);
4568
4569          elsif Ekind (T) = E_Incomplete_Type and then From_With_Type (T) then
4570             Set_Has_Delayed_Freeze (Designator);
4571
4572          --  AI05-0151: In Ada 2012, Incomplete types can appear in the profile
4573          --  of a subprogram or entry declaration.
4574
4575          elsif Ekind (T) = E_Incomplete_Type
4576            and then Ada_Version >= Ada_2012
4577          then
4578             Set_Has_Delayed_Freeze (Designator);
4579          end if;
4580
4581       end Possible_Freeze;
4582
4583    --  Start of processing for Check_Delayed_Subprogram
4584
4585    begin
4586       --  All subprograms, including abstract subprograms, may need a freeze
4587       --  node if some formal type or the return type needs one.
4588
4589       Possible_Freeze (Etype (Designator));
4590       Possible_Freeze (Base_Type (Etype (Designator))); -- needed ???
4591
4592       --  Need delayed freeze if any of the formal types themselves need
4593       --  a delayed freeze and are not yet frozen.
4594
4595       F := First_Formal (Designator);
4596       while Present (F) loop
4597          Possible_Freeze (Etype (F));
4598          Possible_Freeze (Base_Type (Etype (F))); -- needed ???
4599          Next_Formal (F);
4600       end loop;
4601
4602       --  Mark functions that return by reference. Note that it cannot be
4603       --  done for delayed_freeze subprograms because the underlying
4604       --  returned type may not be known yet (for private types)
4605
4606       if not Has_Delayed_Freeze (Designator)
4607         and then Expander_Active
4608       then
4609          declare
4610             Typ  : constant Entity_Id := Etype (Designator);
4611             Utyp : constant Entity_Id := Underlying_Type (Typ);
4612
4613          begin
4614             if Is_Immutably_Limited_Type (Typ) then
4615                Set_Returns_By_Ref (Designator);
4616
4617             elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
4618                Set_Returns_By_Ref (Designator);
4619             end if;
4620          end;
4621       end if;
4622    end Check_Delayed_Subprogram;
4623
4624    ------------------------------------
4625    -- Check_Discriminant_Conformance --
4626    ------------------------------------
4627
4628    procedure Check_Discriminant_Conformance
4629      (N        : Node_Id;
4630       Prev     : Entity_Id;
4631       Prev_Loc : Node_Id)
4632    is
4633       Old_Discr      : Entity_Id := First_Discriminant (Prev);
4634       New_Discr      : Node_Id   := First (Discriminant_Specifications (N));
4635       New_Discr_Id   : Entity_Id;
4636       New_Discr_Type : Entity_Id;
4637
4638       procedure Conformance_Error (Msg : String; N : Node_Id);
4639       --  Post error message for conformance error on given node. Two messages
4640       --  are output. The first points to the previous declaration with a
4641       --  general "no conformance" message. The second is the detailed reason,
4642       --  supplied as Msg. The parameter N provide information for a possible
4643       --  & insertion in the message.
4644
4645       -----------------------
4646       -- Conformance_Error --
4647       -----------------------
4648
4649       procedure Conformance_Error (Msg : String; N : Node_Id) is
4650       begin
4651          Error_Msg_Sloc := Sloc (Prev_Loc);
4652          Error_Msg_N -- CODEFIX
4653            ("not fully conformant with declaration#!", N);
4654          Error_Msg_NE (Msg, N, N);
4655       end Conformance_Error;
4656
4657    --  Start of processing for Check_Discriminant_Conformance
4658
4659    begin
4660       while Present (Old_Discr) and then Present (New_Discr) loop
4661
4662          New_Discr_Id := Defining_Identifier (New_Discr);
4663
4664          --  The subtype mark of the discriminant on the full type has not
4665          --  been analyzed so we do it here. For an access discriminant a new
4666          --  type is created.
4667
4668          if Nkind (Discriminant_Type (New_Discr)) = N_Access_Definition then
4669             New_Discr_Type :=
4670               Access_Definition (N, Discriminant_Type (New_Discr));
4671
4672          else
4673             Analyze (Discriminant_Type (New_Discr));
4674             New_Discr_Type := Etype (Discriminant_Type (New_Discr));
4675
4676             --  Ada 2005: if the discriminant definition carries a null
4677             --  exclusion, create an itype to check properly for consistency
4678             --  with partial declaration.
4679
4680             if Is_Access_Type (New_Discr_Type)
4681                  and then Null_Exclusion_Present (New_Discr)
4682             then
4683                New_Discr_Type :=
4684                  Create_Null_Excluding_Itype
4685                    (T           => New_Discr_Type,
4686                     Related_Nod => New_Discr,
4687                     Scope_Id    => Current_Scope);
4688             end if;
4689          end if;
4690
4691          if not Conforming_Types
4692                   (Etype (Old_Discr), New_Discr_Type, Fully_Conformant)
4693          then
4694             Conformance_Error ("type of & does not match!", New_Discr_Id);
4695             return;
4696          else
4697             --  Treat the new discriminant as an occurrence of the old one,
4698             --  for navigation purposes, and fill in some semantic
4699             --  information, for completeness.
4700
4701             Generate_Reference (Old_Discr, New_Discr_Id, 'r');
4702             Set_Etype (New_Discr_Id, Etype (Old_Discr));
4703             Set_Scope (New_Discr_Id, Scope (Old_Discr));
4704          end if;
4705
4706          --  Names must match
4707
4708          if Chars (Old_Discr) /= Chars (Defining_Identifier (New_Discr)) then
4709             Conformance_Error ("name & does not match!", New_Discr_Id);
4710             return;
4711          end if;
4712
4713          --  Default expressions must match
4714
4715          declare
4716             NewD : constant Boolean :=
4717                      Present (Expression (New_Discr));
4718             OldD : constant Boolean :=
4719                      Present (Expression (Parent (Old_Discr)));
4720
4721          begin
4722             if NewD or OldD then
4723
4724                --  The old default value has been analyzed and expanded,
4725                --  because the current full declaration will have frozen
4726                --  everything before. The new default values have not been
4727                --  expanded, so expand now to check conformance.
4728
4729                if NewD then
4730                   Preanalyze_Spec_Expression
4731                     (Expression (New_Discr), New_Discr_Type);
4732                end if;
4733
4734                if not (NewD and OldD)
4735                  or else not Fully_Conformant_Expressions
4736                               (Expression (Parent (Old_Discr)),
4737                                Expression (New_Discr))
4738
4739                then
4740                   Conformance_Error
4741                     ("default expression for & does not match!",
4742                      New_Discr_Id);
4743                   return;
4744                end if;
4745             end if;
4746          end;
4747
4748          --  In Ada 83 case, grouping must match: (A,B : X) /= (A : X; B : X)
4749
4750          if Ada_Version = Ada_83 then
4751             declare
4752                Old_Disc : constant Node_Id := Declaration_Node (Old_Discr);
4753
4754             begin
4755                --  Grouping (use of comma in param lists) must be the same
4756                --  This is where we catch a misconformance like:
4757
4758                --    A, B : Integer
4759                --    A : Integer; B : Integer
4760
4761                --  which are represented identically in the tree except
4762                --  for the setting of the flags More_Ids and Prev_Ids.
4763
4764                if More_Ids (Old_Disc) /= More_Ids (New_Discr)
4765                  or else Prev_Ids (Old_Disc) /= Prev_Ids (New_Discr)
4766                then
4767                   Conformance_Error
4768                     ("grouping of & does not match!", New_Discr_Id);
4769                   return;
4770                end if;
4771             end;
4772          end if;
4773
4774          Next_Discriminant (Old_Discr);
4775          Next (New_Discr);
4776       end loop;
4777
4778       if Present (Old_Discr) then
4779          Conformance_Error ("too few discriminants!", Defining_Identifier (N));
4780          return;
4781
4782       elsif Present (New_Discr) then
4783          Conformance_Error
4784            ("too many discriminants!", Defining_Identifier (New_Discr));
4785          return;
4786       end if;
4787    end Check_Discriminant_Conformance;
4788
4789    ----------------------------
4790    -- Check_Fully_Conformant --
4791    ----------------------------
4792
4793    procedure Check_Fully_Conformant
4794      (New_Id  : Entity_Id;
4795       Old_Id  : Entity_Id;
4796       Err_Loc : Node_Id := Empty)
4797    is
4798       Result : Boolean;
4799       pragma Warnings (Off, Result);
4800    begin
4801       Check_Conformance
4802         (New_Id, Old_Id, Fully_Conformant, True, Result, Err_Loc);
4803    end Check_Fully_Conformant;
4804
4805    ---------------------------
4806    -- Check_Mode_Conformant --
4807    ---------------------------
4808
4809    procedure Check_Mode_Conformant
4810      (New_Id   : Entity_Id;
4811       Old_Id   : Entity_Id;
4812       Err_Loc  : Node_Id := Empty;
4813       Get_Inst : Boolean := False)
4814    is
4815       Result : Boolean;
4816       pragma Warnings (Off, Result);
4817    begin
4818       Check_Conformance
4819         (New_Id, Old_Id, Mode_Conformant, True, Result, Err_Loc, Get_Inst);
4820    end Check_Mode_Conformant;
4821
4822    --------------------------------
4823    -- Check_Overriding_Indicator --
4824    --------------------------------
4825
4826    procedure Check_Overriding_Indicator
4827      (Subp            : Entity_Id;
4828       Overridden_Subp : Entity_Id;
4829       Is_Primitive    : Boolean)
4830    is
4831       Decl : Node_Id;
4832       Spec : Node_Id;
4833
4834    begin
4835       --  No overriding indicator for literals
4836
4837       if Ekind (Subp) = E_Enumeration_Literal then
4838          return;
4839
4840       elsif Ekind (Subp) = E_Entry then
4841          Decl := Parent (Subp);
4842
4843          --  No point in analyzing a malformed operator
4844
4845       elsif Nkind (Subp) = N_Defining_Operator_Symbol
4846         and then Error_Posted (Subp)
4847       then
4848          return;
4849
4850       else
4851          Decl := Unit_Declaration_Node (Subp);
4852       end if;
4853
4854       if Nkind_In (Decl, N_Subprogram_Body,
4855                          N_Subprogram_Body_Stub,
4856                          N_Subprogram_Declaration,
4857                          N_Abstract_Subprogram_Declaration,
4858                          N_Subprogram_Renaming_Declaration)
4859       then
4860          Spec := Specification (Decl);
4861
4862       elsif Nkind (Decl) = N_Entry_Declaration then
4863          Spec := Decl;
4864
4865       else
4866          return;
4867       end if;
4868
4869       --  The overriding operation is type conformant with the overridden one,
4870       --  but the names of the formals are not required to match. If the names
4871       --  appear permuted in the overriding operation, this is a possible
4872       --  source of confusion that is worth diagnosing. Controlling formals
4873       --  often carry names that reflect the type, and it is not worthwhile
4874       --  requiring that their names match.
4875
4876       if Present (Overridden_Subp)
4877         and then Nkind (Subp) /= N_Defining_Operator_Symbol
4878       then
4879          declare
4880             Form1 : Entity_Id;
4881             Form2 : Entity_Id;
4882
4883          begin
4884             Form1 := First_Formal (Subp);
4885             Form2 := First_Formal (Overridden_Subp);
4886
4887             --  If the overriding operation is a synchronized operation, skip
4888             --  the first parameter of the overridden operation, which is
4889             --  implicit in the new one. If the operation is declared in the
4890             --  body it is not primitive and all formals must match.
4891
4892             if Is_Concurrent_Type (Scope (Subp))
4893               and then Is_Tagged_Type (Scope (Subp))
4894               and then not Has_Completion (Scope (Subp))
4895             then
4896                Form2 := Next_Formal (Form2);
4897             end if;
4898
4899             if Present (Form1) then
4900                Form1 := Next_Formal (Form1);
4901                Form2 := Next_Formal (Form2);
4902             end if;
4903
4904             while Present (Form1) loop
4905                if not Is_Controlling_Formal (Form1)
4906                  and then Present (Next_Formal (Form2))
4907                  and then Chars (Form1) = Chars (Next_Formal (Form2))
4908                then
4909                   Error_Msg_Node_2 := Alias (Overridden_Subp);
4910                   Error_Msg_Sloc := Sloc (Error_Msg_Node_2);
4911                   Error_Msg_NE
4912                     ("& does not match corresponding formal of&#",
4913                      Form1, Form1);
4914                   exit;
4915                end if;
4916
4917                Next_Formal (Form1);
4918                Next_Formal (Form2);
4919             end loop;
4920          end;
4921       end if;
4922
4923       --  If there is an overridden subprogram, then check that there is no
4924       --  "not overriding" indicator, and mark the subprogram as overriding.
4925       --  This is not done if the overridden subprogram is marked as hidden,
4926       --  which can occur for the case of inherited controlled operations
4927       --  (see Derive_Subprogram), unless the inherited subprogram's parent
4928       --  subprogram is not itself hidden. (Note: This condition could probably
4929       --  be simplified, leaving out the testing for the specific controlled
4930       --  cases, but it seems safer and clearer this way, and echoes similar
4931       --  special-case tests of this kind in other places.)
4932
4933       if Present (Overridden_Subp)
4934         and then (not Is_Hidden (Overridden_Subp)
4935                    or else
4936                      ((Chars (Overridden_Subp) = Name_Initialize
4937                          or else
4938                        Chars (Overridden_Subp) = Name_Adjust
4939                          or else
4940                        Chars (Overridden_Subp) = Name_Finalize)
4941                       and then Present (Alias (Overridden_Subp))
4942                       and then not Is_Hidden (Alias (Overridden_Subp))))
4943       then
4944          if Must_Not_Override (Spec) then
4945             Error_Msg_Sloc := Sloc (Overridden_Subp);
4946
4947             if Ekind (Subp) = E_Entry then
4948                Error_Msg_NE
4949                  ("entry & overrides inherited operation #", Spec, Subp);
4950             else
4951                Error_Msg_NE
4952                  ("subprogram & overrides inherited operation #", Spec, Subp);
4953             end if;
4954
4955          elsif Is_Subprogram (Subp) then
4956             if Is_Init_Proc (Subp) then
4957                null;
4958
4959             elsif No (Overridden_Operation (Subp)) then
4960
4961                --  For entities generated by Derive_Subprograms the overridden
4962                --  operation is the inherited primitive (which is available
4963                --  through the attribute alias)
4964
4965                if (Is_Dispatching_Operation (Subp)
4966                     or else Is_Dispatching_Operation (Overridden_Subp))
4967                  and then not Comes_From_Source (Overridden_Subp)
4968                  and then Find_Dispatching_Type (Overridden_Subp) =
4969                           Find_Dispatching_Type (Subp)
4970                  and then Present (Alias (Overridden_Subp))
4971                  and then Comes_From_Source (Alias (Overridden_Subp))
4972                then
4973                   Set_Overridden_Operation (Subp, Alias (Overridden_Subp));
4974
4975                else
4976                   Set_Overridden_Operation (Subp, Overridden_Subp);
4977                end if;
4978             end if;
4979          end if;
4980
4981          --  If primitive flag is set or this is a protected operation, then
4982          --  the operation is overriding at the point of its declaration, so
4983          --  warn if necessary. Otherwise it may have been declared before the
4984          --  operation it overrides and no check is required.
4985
4986          if Style_Check
4987            and then not Must_Override (Spec)
4988            and then (Is_Primitive
4989                       or else Ekind (Scope (Subp)) = E_Protected_Type)
4990          then
4991             Style.Missing_Overriding (Decl, Subp);
4992          end if;
4993
4994       --  If Subp is an operator, it may override a predefined operation, if
4995       --  it is defined in the same scope as the type to which it applies.
4996       --  In that case Overridden_Subp is empty because of our implicit
4997       --  representation for predefined operators. We have to check whether the
4998       --  signature of Subp matches that of a predefined operator. Note that
4999       --  first argument provides the name of the operator, and the second
5000       --  argument the signature that may match that of a standard operation.
5001       --  If the indicator is overriding, then the operator must match a
5002       --  predefined signature, because we know already that there is no
5003       --  explicit overridden operation.
5004
5005       elsif Nkind (Subp) = N_Defining_Operator_Symbol then
5006          if Must_Not_Override (Spec) then
5007
5008             --  If this is not a primitive or a protected subprogram, then
5009             --  "not overriding" is illegal.
5010
5011             if not Is_Primitive
5012               and then Ekind (Scope (Subp)) /= E_Protected_Type
5013             then
5014                Error_Msg_N
5015                  ("overriding indicator only allowed "
5016                   & "if subprogram is primitive", Subp);
5017
5018             elsif Can_Override_Operator (Subp) then
5019                Error_Msg_NE
5020                  ("subprogram& overrides predefined operator ", Spec, Subp);
5021             end if;
5022
5023          elsif Must_Override (Spec) then
5024             if No (Overridden_Operation (Subp))
5025               and then not Can_Override_Operator (Subp)
5026             then
5027                Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
5028             end if;
5029
5030          elsif not Error_Posted (Subp)
5031            and then Style_Check
5032            and then Can_Override_Operator (Subp)
5033            and then
5034              not Is_Predefined_File_Name
5035                    (Unit_File_Name (Get_Source_Unit (Subp)))
5036          then
5037             --  If style checks are enabled, indicate that the indicator is
5038             --  missing. However, at the point of declaration, the type of
5039             --  which this is a primitive operation may be private, in which
5040             --  case the indicator would be premature.
5041
5042             if Has_Private_Declaration (Etype (Subp))
5043               or else Has_Private_Declaration (Etype (First_Formal (Subp)))
5044             then
5045                null;
5046             else
5047                Style.Missing_Overriding (Decl, Subp);
5048             end if;
5049          end if;
5050
5051       elsif Must_Override (Spec) then
5052          if Ekind (Subp) = E_Entry then
5053             Error_Msg_NE ("entry & is not overriding", Spec, Subp);
5054          else
5055             Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
5056          end if;
5057
5058       --  If the operation is marked "not overriding" and it's not primitive
5059       --  then an error is issued, unless this is an operation of a task or
5060       --  protected type (RM05-8.3.1(3/2-4/2)). Error cases where "overriding"
5061       --  has been specified have already been checked above.
5062
5063       elsif Must_Not_Override (Spec)
5064         and then not Is_Primitive
5065         and then Ekind (Subp) /= E_Entry
5066         and then Ekind (Scope (Subp)) /= E_Protected_Type
5067       then
5068          Error_Msg_N
5069            ("overriding indicator only allowed if subprogram is primitive",
5070             Subp);
5071          return;
5072       end if;
5073    end Check_Overriding_Indicator;
5074
5075    -------------------
5076    -- Check_Returns --
5077    -------------------
5078
5079    --  Note: this procedure needs to know far too much about how the expander
5080    --  messes with exceptions. The use of the flag Exception_Junk and the
5081    --  incorporation of knowledge of Exp_Ch11.Expand_Local_Exception_Handlers
5082    --  works, but is not very clean. It would be better if the expansion
5083    --  routines would leave Original_Node working nicely, and we could use
5084    --  Original_Node here to ignore all the peculiar expander messing ???
5085
5086    procedure Check_Returns
5087      (HSS  : Node_Id;
5088       Mode : Character;
5089       Err  : out Boolean;
5090       Proc : Entity_Id := Empty)
5091    is
5092       Handler : Node_Id;
5093
5094       procedure Check_Statement_Sequence (L : List_Id);
5095       --  Internal recursive procedure to check a list of statements for proper
5096       --  termination by a return statement (or a transfer of control or a
5097       --  compound statement that is itself internally properly terminated).
5098
5099       ------------------------------
5100       -- Check_Statement_Sequence --
5101       ------------------------------
5102
5103       procedure Check_Statement_Sequence (L : List_Id) is
5104          Last_Stm : Node_Id;
5105          Stm      : Node_Id;
5106          Kind     : Node_Kind;
5107
5108          Raise_Exception_Call : Boolean;
5109          --  Set True if statement sequence terminated by Raise_Exception call
5110          --  or a Reraise_Occurrence call.
5111
5112       begin
5113          Raise_Exception_Call := False;
5114
5115          --  Get last real statement
5116
5117          Last_Stm := Last (L);
5118
5119          --  Deal with digging out exception handler statement sequences that
5120          --  have been transformed by the local raise to goto optimization.
5121          --  See Exp_Ch11.Expand_Local_Exception_Handlers for details. If this
5122          --  optimization has occurred, we are looking at something like:
5123
5124          --  begin
5125          --     original stmts in block
5126
5127          --  exception            \
5128          --     when excep1 =>     |
5129          --        goto L1;        | omitted if No_Exception_Propagation
5130          --     when excep2 =>     |
5131          --        goto L2;       /
5132          --  end;
5133
5134          --  goto L3;      -- skip handler when exception not raised
5135
5136          --  <<L1>>        -- target label for local exception
5137          --     begin
5138          --        estmts1
5139          --     end;
5140
5141          --     goto L3;
5142
5143          --  <<L2>>
5144          --     begin
5145          --        estmts2
5146          --     end;
5147
5148          --  <<L3>>
5149
5150          --  and what we have to do is to dig out the estmts1 and estmts2
5151          --  sequences (which were the original sequences of statements in
5152          --  the exception handlers) and check them.
5153
5154          if Nkind (Last_Stm) = N_Label
5155            and then Exception_Junk (Last_Stm)
5156          then
5157             Stm := Last_Stm;
5158             loop
5159                Prev (Stm);
5160                exit when No (Stm);
5161                exit when Nkind (Stm) /= N_Block_Statement;
5162                exit when not Exception_Junk (Stm);
5163                Prev (Stm);
5164                exit when No (Stm);
5165                exit when Nkind (Stm) /= N_Label;
5166                exit when not Exception_Junk (Stm);
5167                Check_Statement_Sequence
5168                  (Statements (Handled_Statement_Sequence (Next (Stm))));
5169
5170                Prev (Stm);
5171                Last_Stm := Stm;
5172                exit when No (Stm);
5173                exit when Nkind (Stm) /= N_Goto_Statement;
5174                exit when not Exception_Junk (Stm);
5175             end loop;
5176          end if;
5177
5178          --  Don't count pragmas
5179
5180          while Nkind (Last_Stm) = N_Pragma
5181
5182          --  Don't count call to SS_Release (can happen after Raise_Exception)
5183
5184            or else
5185              (Nkind (Last_Stm) = N_Procedure_Call_Statement
5186                 and then
5187               Nkind (Name (Last_Stm)) = N_Identifier
5188                 and then
5189               Is_RTE (Entity (Name (Last_Stm)), RE_SS_Release))
5190
5191          --  Don't count exception junk
5192
5193            or else
5194              (Nkind_In (Last_Stm, N_Goto_Statement,
5195                                    N_Label,
5196                                    N_Object_Declaration)
5197                 and then Exception_Junk (Last_Stm))
5198            or else Nkind (Last_Stm) in N_Push_xxx_Label
5199            or else Nkind (Last_Stm) in N_Pop_xxx_Label
5200          loop
5201             Prev (Last_Stm);
5202          end loop;
5203
5204          --  Here we have the "real" last statement
5205
5206          Kind := Nkind (Last_Stm);
5207
5208          --  Transfer of control, OK. Note that in the No_Return procedure
5209          --  case, we already diagnosed any explicit return statements, so
5210          --  we can treat them as OK in this context.
5211
5212          if Is_Transfer (Last_Stm) then
5213             return;
5214
5215          --  Check cases of explicit non-indirect procedure calls
5216
5217          elsif Kind = N_Procedure_Call_Statement
5218            and then Is_Entity_Name (Name (Last_Stm))
5219          then
5220             --  Check call to Raise_Exception procedure which is treated
5221             --  specially, as is a call to Reraise_Occurrence.
5222
5223             --  We suppress the warning in these cases since it is likely that
5224             --  the programmer really does not expect to deal with the case
5225             --  of Null_Occurrence, and thus would find a warning about a
5226             --  missing return curious, and raising Program_Error does not
5227             --  seem such a bad behavior if this does occur.
5228
5229             --  Note that in the Ada 2005 case for Raise_Exception, the actual
5230             --  behavior will be to raise Constraint_Error (see AI-329).
5231
5232             if Is_RTE (Entity (Name (Last_Stm)), RE_Raise_Exception)
5233                  or else
5234                Is_RTE (Entity (Name (Last_Stm)), RE_Reraise_Occurrence)
5235             then
5236                Raise_Exception_Call := True;
5237
5238                --  For Raise_Exception call, test first argument, if it is
5239                --  an attribute reference for a 'Identity call, then we know
5240                --  that the call cannot possibly return.
5241
5242                declare
5243                   Arg : constant Node_Id :=
5244                           Original_Node (First_Actual (Last_Stm));
5245                begin
5246                   if Nkind (Arg) = N_Attribute_Reference
5247                     and then Attribute_Name (Arg) = Name_Identity
5248                   then
5249                      return;
5250                   end if;
5251                end;
5252             end if;
5253
5254          --  If statement, need to look inside if there is an else and check
5255          --  each constituent statement sequence for proper termination.
5256
5257          elsif Kind = N_If_Statement
5258            and then Present (Else_Statements (Last_Stm))
5259          then
5260             Check_Statement_Sequence (Then_Statements (Last_Stm));
5261             Check_Statement_Sequence (Else_Statements (Last_Stm));
5262
5263             if Present (Elsif_Parts (Last_Stm)) then
5264                declare
5265                   Elsif_Part : Node_Id := First (Elsif_Parts (Last_Stm));
5266
5267                begin
5268                   while Present (Elsif_Part) loop
5269                      Check_Statement_Sequence (Then_Statements (Elsif_Part));
5270                      Next (Elsif_Part);
5271                   end loop;
5272                end;
5273             end if;
5274
5275             return;
5276
5277          --  Case statement, check each case for proper termination
5278
5279          elsif Kind = N_Case_Statement then
5280             declare
5281                Case_Alt : Node_Id;
5282             begin
5283                Case_Alt := First_Non_Pragma (Alternatives (Last_Stm));
5284                while Present (Case_Alt) loop
5285                   Check_Statement_Sequence (Statements (Case_Alt));
5286                   Next_Non_Pragma (Case_Alt);
5287                end loop;
5288             end;
5289
5290             return;
5291
5292          --  Block statement, check its handled sequence of statements
5293
5294          elsif Kind = N_Block_Statement then
5295             declare
5296                Err1 : Boolean;
5297
5298             begin
5299                Check_Returns
5300                  (Handled_Statement_Sequence (Last_Stm), Mode, Err1);
5301
5302                if Err1 then
5303                   Err := True;
5304                end if;
5305
5306                return;
5307             end;
5308
5309          --  Loop statement. If there is an iteration scheme, we can definitely
5310          --  fall out of the loop. Similarly if there is an exit statement, we
5311          --  can fall out. In either case we need a following return.
5312
5313          elsif Kind = N_Loop_Statement then
5314             if Present (Iteration_Scheme (Last_Stm))
5315               or else Has_Exit (Entity (Identifier (Last_Stm)))
5316             then
5317                null;
5318
5319             --  A loop with no exit statement or iteration scheme is either
5320             --  an infinite loop, or it has some other exit (raise/return).
5321             --  In either case, no warning is required.
5322
5323             else
5324                return;
5325             end if;
5326
5327          --  Timed entry call, check entry call and delay alternatives
5328
5329          --  Note: in expanded code, the timed entry call has been converted
5330          --  to a set of expanded statements on which the check will work
5331          --  correctly in any case.
5332
5333          elsif Kind = N_Timed_Entry_Call then
5334             declare
5335                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
5336                DCA : constant Node_Id := Delay_Alternative      (Last_Stm);
5337
5338             begin
5339                --  If statement sequence of entry call alternative is missing,
5340                --  then we can definitely fall through, and we post the error
5341                --  message on the entry call alternative itself.
5342
5343                if No (Statements (ECA)) then
5344                   Last_Stm := ECA;
5345
5346                --  If statement sequence of delay alternative is missing, then
5347                --  we can definitely fall through, and we post the error
5348                --  message on the delay alternative itself.
5349
5350                --  Note: if both ECA and DCA are missing the return, then we
5351                --  post only one message, should be enough to fix the bugs.
5352                --  If not we will get a message next time on the DCA when the
5353                --  ECA is fixed!
5354
5355                elsif No (Statements (DCA)) then
5356                   Last_Stm := DCA;
5357
5358                --  Else check both statement sequences
5359
5360                else
5361                   Check_Statement_Sequence (Statements (ECA));
5362                   Check_Statement_Sequence (Statements (DCA));
5363                   return;
5364                end if;
5365             end;
5366
5367          --  Conditional entry call, check entry call and else part
5368
5369          --  Note: in expanded code, the conditional entry call has been
5370          --  converted to a set of expanded statements on which the check
5371          --  will work correctly in any case.
5372
5373          elsif Kind = N_Conditional_Entry_Call then
5374             declare
5375                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
5376
5377             begin
5378                --  If statement sequence of entry call alternative is missing,
5379                --  then we can definitely fall through, and we post the error
5380                --  message on the entry call alternative itself.
5381
5382                if No (Statements (ECA)) then
5383                   Last_Stm := ECA;
5384
5385                --  Else check statement sequence and else part
5386
5387                else
5388                   Check_Statement_Sequence (Statements (ECA));
5389                   Check_Statement_Sequence (Else_Statements (Last_Stm));
5390                   return;
5391                end if;
5392             end;
5393          end if;
5394
5395          --  If we fall through, issue appropriate message
5396
5397          if Mode = 'F' then
5398             if not Raise_Exception_Call then
5399                Error_Msg_N
5400                  ("?RETURN statement missing following this statement!",
5401                   Last_Stm);
5402                Error_Msg_N
5403                  ("\?Program_Error may be raised at run time!",
5404                   Last_Stm);
5405             end if;
5406
5407             --  Note: we set Err even though we have not issued a warning
5408             --  because we still have a case of a missing return. This is
5409             --  an extremely marginal case, probably will never be noticed
5410             --  but we might as well get it right.
5411
5412             Err := True;
5413
5414          --  Otherwise we have the case of a procedure marked No_Return
5415
5416          else
5417             if not Raise_Exception_Call then
5418                Error_Msg_N
5419                  ("?implied return after this statement " &
5420                   "will raise Program_Error",
5421                   Last_Stm);
5422                Error_Msg_NE
5423                  ("\?procedure & is marked as No_Return!",
5424                   Last_Stm, Proc);
5425             end if;
5426
5427             declare
5428                RE : constant Node_Id :=
5429                       Make_Raise_Program_Error (Sloc (Last_Stm),
5430                         Reason => PE_Implicit_Return);
5431             begin
5432                Insert_After (Last_Stm, RE);
5433                Analyze (RE);
5434             end;
5435          end if;
5436       end Check_Statement_Sequence;
5437
5438    --  Start of processing for Check_Returns
5439
5440    begin
5441       Err := False;
5442       Check_Statement_Sequence (Statements (HSS));
5443
5444       if Present (Exception_Handlers (HSS)) then
5445          Handler := First_Non_Pragma (Exception_Handlers (HSS));
5446          while Present (Handler) loop
5447             Check_Statement_Sequence (Statements (Handler));
5448             Next_Non_Pragma (Handler);
5449          end loop;
5450       end if;
5451    end Check_Returns;
5452
5453    ----------------------------
5454    -- Check_Subprogram_Order --
5455    ----------------------------
5456
5457    procedure Check_Subprogram_Order (N : Node_Id) is
5458
5459       function Subprogram_Name_Greater (S1, S2 : String) return Boolean;
5460       --  This is used to check if S1 > S2 in the sense required by this
5461       --  test, for example nameab < namec, but name2 < name10.
5462
5463       -----------------------------
5464       -- Subprogram_Name_Greater --
5465       -----------------------------
5466
5467       function Subprogram_Name_Greater (S1, S2 : String) return Boolean is
5468          L1, L2 : Positive;
5469          N1, N2 : Natural;
5470
5471       begin
5472          --  Remove trailing numeric parts
5473
5474          L1 := S1'Last;
5475          while S1 (L1) in '0' .. '9' loop
5476             L1 := L1 - 1;
5477          end loop;
5478
5479          L2 := S2'Last;
5480          while S2 (L2) in '0' .. '9' loop
5481             L2 := L2 - 1;
5482          end loop;
5483
5484          --  If non-numeric parts non-equal, that's decisive
5485
5486          if S1 (S1'First .. L1) < S2 (S2'First .. L2) then
5487             return False;
5488
5489          elsif S1 (S1'First .. L1) > S2 (S2'First .. L2) then
5490             return True;
5491
5492          --  If non-numeric parts equal, compare suffixed numeric parts. Note
5493          --  that a missing suffix is treated as numeric zero in this test.
5494
5495          else
5496             N1 := 0;
5497             while L1 < S1'Last loop
5498                L1 := L1 + 1;
5499                N1 := N1 * 10 + Character'Pos (S1 (L1)) - Character'Pos ('0');
5500             end loop;
5501
5502             N2 := 0;
5503             while L2 < S2'Last loop
5504                L2 := L2 + 1;
5505                N2 := N2 * 10 + Character'Pos (S2 (L2)) - Character'Pos ('0');
5506             end loop;
5507
5508             return N1 > N2;
5509          end if;
5510       end Subprogram_Name_Greater;
5511
5512    --  Start of processing for Check_Subprogram_Order
5513
5514    begin
5515       --  Check body in alpha order if this is option
5516
5517       if Style_Check
5518         and then Style_Check_Order_Subprograms
5519         and then Nkind (N) = N_Subprogram_Body
5520         and then Comes_From_Source (N)
5521         and then In_Extended_Main_Source_Unit (N)
5522       then
5523          declare
5524             LSN : String_Ptr
5525                     renames Scope_Stack.Table
5526                               (Scope_Stack.Last).Last_Subprogram_Name;
5527
5528             Body_Id : constant Entity_Id :=
5529                         Defining_Entity (Specification (N));
5530
5531          begin
5532             Get_Decoded_Name_String (Chars (Body_Id));
5533
5534             if LSN /= null then
5535                if Subprogram_Name_Greater
5536                     (LSN.all, Name_Buffer (1 .. Name_Len))
5537                then
5538                   Style.Subprogram_Not_In_Alpha_Order (Body_Id);
5539                end if;
5540
5541                Free (LSN);
5542             end if;
5543
5544             LSN := new String'(Name_Buffer (1 .. Name_Len));
5545          end;
5546       end if;
5547    end Check_Subprogram_Order;
5548
5549    ------------------------------
5550    -- Check_Subtype_Conformant --
5551    ------------------------------
5552
5553    procedure Check_Subtype_Conformant
5554      (New_Id                   : Entity_Id;
5555       Old_Id                   : Entity_Id;
5556       Err_Loc                  : Node_Id := Empty;
5557       Skip_Controlling_Formals : Boolean := False)
5558    is
5559       Result : Boolean;
5560       pragma Warnings (Off, Result);
5561    begin
5562       Check_Conformance
5563         (New_Id, Old_Id, Subtype_Conformant, True, Result, Err_Loc,
5564          Skip_Controlling_Formals => Skip_Controlling_Formals);
5565    end Check_Subtype_Conformant;
5566
5567    ---------------------------
5568    -- Check_Type_Conformant --
5569    ---------------------------
5570
5571    procedure Check_Type_Conformant
5572      (New_Id  : Entity_Id;
5573       Old_Id  : Entity_Id;
5574       Err_Loc : Node_Id := Empty)
5575    is
5576       Result : Boolean;
5577       pragma Warnings (Off, Result);
5578    begin
5579       Check_Conformance
5580         (New_Id, Old_Id, Type_Conformant, True, Result, Err_Loc);
5581    end Check_Type_Conformant;
5582
5583    ---------------------------
5584    -- Can_Override_Operator --
5585    ---------------------------
5586
5587    function Can_Override_Operator (Subp : Entity_Id) return Boolean is
5588       Typ : Entity_Id;
5589    begin
5590       if Nkind (Subp) /= N_Defining_Operator_Symbol then
5591          return False;
5592
5593       else
5594          Typ := Base_Type (Etype (First_Formal (Subp)));
5595
5596          return Operator_Matches_Spec (Subp, Subp)
5597            and then Scope (Subp) = Scope (Typ)
5598            and then not Is_Class_Wide_Type (Typ);
5599       end if;
5600    end Can_Override_Operator;
5601
5602    ----------------------
5603    -- Conforming_Types --
5604    ----------------------
5605
5606    function Conforming_Types
5607      (T1       : Entity_Id;
5608       T2       : Entity_Id;
5609       Ctype    : Conformance_Type;
5610       Get_Inst : Boolean := False) return Boolean
5611    is
5612       Type_1 : Entity_Id := T1;
5613       Type_2 : Entity_Id := T2;
5614       Are_Anonymous_Access_To_Subprogram_Types : Boolean := False;
5615
5616       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean;
5617       --  If neither T1 nor T2 are generic actual types, or if they are in
5618       --  different scopes (e.g. parent and child instances), then verify that
5619       --  the base types are equal. Otherwise T1 and T2 must be on the same
5620       --  subtype chain. The whole purpose of this procedure is to prevent
5621       --  spurious ambiguities in an instantiation that may arise if two
5622       --  distinct generic types are instantiated with the same actual.
5623
5624       function Find_Designated_Type (T : Entity_Id) return Entity_Id;
5625       --  An access parameter can designate an incomplete type. If the
5626       --  incomplete type is the limited view of a type from a limited_
5627       --  with_clause, check whether the non-limited view is available. If
5628       --  it is a (non-limited) incomplete type, get the full view.
5629
5630       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean;
5631       --  Returns True if and only if either T1 denotes a limited view of T2
5632       --  or T2 denotes a limited view of T1. This can arise when the limited
5633       --  with view of a type is used in a subprogram declaration and the
5634       --  subprogram body is in the scope of a regular with clause for the
5635       --  same unit. In such a case, the two type entities can be considered
5636       --  identical for purposes of conformance checking.
5637
5638       ----------------------
5639       -- Base_Types_Match --
5640       ----------------------
5641
5642       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean is
5643       begin
5644          if T1 = T2 then
5645             return True;
5646
5647          elsif Base_Type (T1) = Base_Type (T2) then
5648
5649             --  The following is too permissive. A more precise test should
5650             --  check that the generic actual is an ancestor subtype of the
5651             --  other ???.
5652
5653             return not Is_Generic_Actual_Type (T1)
5654               or else not Is_Generic_Actual_Type (T2)
5655               or else Scope (T1) /= Scope (T2);
5656
5657          else
5658             return False;
5659          end if;
5660       end Base_Types_Match;
5661
5662       --------------------------
5663       -- Find_Designated_Type --
5664       --------------------------
5665
5666       function Find_Designated_Type (T : Entity_Id) return Entity_Id is
5667          Desig : Entity_Id;
5668
5669       begin
5670          Desig := Directly_Designated_Type (T);
5671
5672          if Ekind (Desig) = E_Incomplete_Type then
5673
5674             --  If regular incomplete type, get full view if available
5675
5676             if Present (Full_View (Desig)) then
5677                Desig := Full_View (Desig);
5678
5679             --  If limited view of a type, get non-limited view if available,
5680             --  and check again for a regular incomplete type.
5681
5682             elsif Present (Non_Limited_View (Desig)) then
5683                Desig := Get_Full_View (Non_Limited_View (Desig));
5684             end if;
5685          end if;
5686
5687          return Desig;
5688       end Find_Designated_Type;
5689
5690       -------------------------------
5691       -- Matches_Limited_With_View --
5692       -------------------------------
5693
5694       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean is
5695       begin
5696          --  In some cases a type imported through a limited_with clause, and
5697          --  its nonlimited view are both visible, for example in an anonymous
5698          --  access-to-class-wide type in a formal. Both entities designate the
5699          --  same type.
5700
5701          if From_With_Type (T1)
5702            and then T2 = Available_View (T1)
5703          then
5704             return True;
5705
5706          elsif From_With_Type (T2)
5707            and then T1 = Available_View (T2)
5708          then
5709             return True;
5710
5711          elsif From_With_Type (T1)
5712            and then From_With_Type (T2)
5713            and then Available_View (T1) = Available_View (T2)
5714          then
5715             return True;
5716
5717          else
5718             return False;
5719          end if;
5720       end Matches_Limited_With_View;
5721
5722    --  Start of processing for Conforming_Types
5723
5724    begin
5725       --  The context is an instance association for a formal
5726       --  access-to-subprogram type; the formal parameter types require
5727       --  mapping because they may denote other formal parameters of the
5728       --  generic unit.
5729
5730       if Get_Inst then
5731          Type_1 := Get_Instance_Of (T1);
5732          Type_2 := Get_Instance_Of (T2);
5733       end if;
5734
5735       --  If one of the types is a view of the other introduced by a limited
5736       --  with clause, treat these as conforming for all purposes.
5737
5738       if Matches_Limited_With_View (T1, T2) then
5739          return True;
5740
5741       elsif Base_Types_Match (Type_1, Type_2) then
5742          return Ctype <= Mode_Conformant
5743            or else Subtypes_Statically_Match (Type_1, Type_2);
5744
5745       elsif Is_Incomplete_Or_Private_Type (Type_1)
5746         and then Present (Full_View (Type_1))
5747         and then Base_Types_Match (Full_View (Type_1), Type_2)
5748       then
5749          return Ctype <= Mode_Conformant
5750            or else Subtypes_Statically_Match (Full_View (Type_1), Type_2);
5751
5752       elsif Ekind (Type_2) = E_Incomplete_Type
5753         and then Present (Full_View (Type_2))
5754         and then Base_Types_Match (Type_1, Full_View (Type_2))
5755       then
5756          return Ctype <= Mode_Conformant
5757            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
5758
5759       elsif Is_Private_Type (Type_2)
5760         and then In_Instance
5761         and then Present (Full_View (Type_2))
5762         and then Base_Types_Match (Type_1, Full_View (Type_2))
5763       then
5764          return Ctype <= Mode_Conformant
5765            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
5766       end if;
5767
5768       --  Ada 2005 (AI-254): Anonymous access-to-subprogram types must be
5769       --  treated recursively because they carry a signature.
5770
5771       Are_Anonymous_Access_To_Subprogram_Types :=
5772         Ekind (Type_1) = Ekind (Type_2)
5773           and then
5774             (Ekind (Type_1) = E_Anonymous_Access_Subprogram_Type
5775              or else
5776                Ekind (Type_1) = E_Anonymous_Access_Protected_Subprogram_Type);
5777
5778       --  Test anonymous access type case. For this case, static subtype
5779       --  matching is required for mode conformance (RM 6.3.1(15)). We check
5780       --  the base types because we may have built internal subtype entities
5781       --  to handle null-excluding types (see Process_Formals).
5782
5783       if (Ekind (Base_Type (Type_1)) = E_Anonymous_Access_Type
5784             and then
5785           Ekind (Base_Type (Type_2)) = E_Anonymous_Access_Type)
5786         or else Are_Anonymous_Access_To_Subprogram_Types -- Ada 2005 (AI-254)
5787       then
5788          declare
5789             Desig_1 : Entity_Id;
5790             Desig_2 : Entity_Id;
5791
5792          begin
5793             --  In Ada2005, access constant indicators must match for
5794             --  subtype conformance.
5795
5796             if Ada_Version >= Ada_2005
5797               and then Ctype >= Subtype_Conformant
5798               and then
5799                 Is_Access_Constant (Type_1) /= Is_Access_Constant (Type_2)
5800             then
5801                return False;
5802             end if;
5803
5804             Desig_1 := Find_Designated_Type (Type_1);
5805             Desig_2 := Find_Designated_Type (Type_2);
5806
5807             --  If the context is an instance association for a formal
5808             --  access-to-subprogram type; formal access parameter designated
5809             --  types require mapping because they may denote other formal
5810             --  parameters of the generic unit.
5811
5812             if Get_Inst then
5813                Desig_1 := Get_Instance_Of (Desig_1);
5814                Desig_2 := Get_Instance_Of (Desig_2);
5815             end if;
5816
5817             --  It is possible for a Class_Wide_Type to be introduced for an
5818             --  incomplete type, in which case there is a separate class_ wide
5819             --  type for the full view. The types conform if their Etypes
5820             --  conform, i.e. one may be the full view of the other. This can
5821             --  only happen in the context of an access parameter, other uses
5822             --  of an incomplete Class_Wide_Type are illegal.
5823
5824             if Is_Class_Wide_Type (Desig_1)
5825                  and then
5826                Is_Class_Wide_Type (Desig_2)
5827             then
5828                return
5829                  Conforming_Types
5830                    (Etype (Base_Type (Desig_1)),
5831                     Etype (Base_Type (Desig_2)), Ctype);
5832
5833             elsif Are_Anonymous_Access_To_Subprogram_Types then
5834                if Ada_Version < Ada_2005 then
5835                   return Ctype = Type_Conformant
5836                     or else
5837                       Subtypes_Statically_Match (Desig_1, Desig_2);
5838
5839                --  We must check the conformance of the signatures themselves
5840
5841                else
5842                   declare
5843                      Conformant : Boolean;
5844                   begin
5845                      Check_Conformance
5846                        (Desig_1, Desig_2, Ctype, False, Conformant);
5847                      return Conformant;
5848                   end;
5849                end if;
5850
5851             else
5852                return Base_Type (Desig_1) = Base_Type (Desig_2)
5853                 and then (Ctype = Type_Conformant
5854                             or else
5855                           Subtypes_Statically_Match (Desig_1, Desig_2));
5856             end if;
5857          end;
5858
5859       --  Otherwise definitely no match
5860
5861       else
5862          if ((Ekind (Type_1) = E_Anonymous_Access_Type
5863                and then Is_Access_Type (Type_2))
5864             or else (Ekind (Type_2) = E_Anonymous_Access_Type
5865                        and then Is_Access_Type (Type_1)))
5866            and then
5867              Conforming_Types
5868                (Designated_Type (Type_1), Designated_Type (Type_2), Ctype)
5869          then
5870             May_Hide_Profile := True;
5871          end if;
5872
5873          return False;
5874       end if;
5875    end Conforming_Types;
5876
5877    --------------------------
5878    -- Create_Extra_Formals --
5879    --------------------------
5880
5881    procedure Create_Extra_Formals (E : Entity_Id) is
5882       Formal      : Entity_Id;
5883       First_Extra : Entity_Id := Empty;
5884       Last_Extra  : Entity_Id;
5885       Formal_Type : Entity_Id;
5886       P_Formal    : Entity_Id := Empty;
5887
5888       function Add_Extra_Formal
5889         (Assoc_Entity : Entity_Id;
5890          Typ          : Entity_Id;
5891          Scope        : Entity_Id;
5892          Suffix       : String) return Entity_Id;
5893       --  Add an extra formal to the current list of formals and extra formals.
5894       --  The extra formal is added to the end of the list of extra formals,
5895       --  and also returned as the result. These formals are always of mode IN.
5896       --  The new formal has the type Typ, is declared in Scope, and its name
5897       --  is given by a concatenation of the name of Assoc_Entity and Suffix.
5898       --  The following suffixes are currently used. They should not be changed
5899       --  without coordinating with CodePeer, which makes use of these to
5900       --  provide better messages.
5901
5902       --  O denotes the Constrained bit.
5903       --  L denotes the accessibility level.
5904       --  BIP_xxx denotes an extra formal for a build-in-place function. See
5905       --  the full list in exp_ch6.BIP_Formal_Kind.
5906
5907       ----------------------
5908       -- Add_Extra_Formal --
5909       ----------------------
5910
5911       function Add_Extra_Formal
5912         (Assoc_Entity : Entity_Id;
5913          Typ          : Entity_Id;
5914          Scope        : Entity_Id;
5915          Suffix       : String) return Entity_Id
5916       is
5917          EF : constant Entity_Id :=
5918                 Make_Defining_Identifier (Sloc (Assoc_Entity),
5919                   Chars  => New_External_Name (Chars (Assoc_Entity),
5920                                                Suffix => Suffix));
5921
5922       begin
5923          --  A little optimization. Never generate an extra formal for the
5924          --  _init operand of an initialization procedure, since it could
5925          --  never be used.
5926
5927          if Chars (Formal) = Name_uInit then
5928             return Empty;
5929          end if;
5930
5931          Set_Ekind           (EF, E_In_Parameter);
5932          Set_Actual_Subtype  (EF, Typ);
5933          Set_Etype           (EF, Typ);
5934          Set_Scope           (EF, Scope);
5935          Set_Mechanism       (EF, Default_Mechanism);
5936          Set_Formal_Validity (EF);
5937
5938          if No (First_Extra) then
5939             First_Extra := EF;
5940             Set_Extra_Formals (Scope, First_Extra);
5941          end if;
5942
5943          if Present (Last_Extra) then
5944             Set_Extra_Formal (Last_Extra, EF);
5945          end if;
5946
5947          Last_Extra := EF;
5948
5949          return EF;
5950       end Add_Extra_Formal;
5951
5952    --  Start of processing for Create_Extra_Formals
5953
5954    begin
5955       --  We never generate extra formals if expansion is not active
5956       --  because we don't need them unless we are generating code.
5957
5958       if not Expander_Active then
5959          return;
5960       end if;
5961
5962       --  If this is a derived subprogram then the subtypes of the parent
5963       --  subprogram's formal parameters will be used to determine the need
5964       --  for extra formals.
5965
5966       if Is_Overloadable (E) and then Present (Alias (E)) then
5967          P_Formal := First_Formal (Alias (E));
5968       end if;
5969
5970       Last_Extra := Empty;
5971       Formal := First_Formal (E);
5972       while Present (Formal) loop
5973          Last_Extra := Formal;
5974          Next_Formal (Formal);
5975       end loop;
5976
5977       --  If Extra_formals were already created, don't do it again. This
5978       --  situation may arise for subprogram types created as part of
5979       --  dispatching calls (see Expand_Dispatching_Call)
5980
5981       if Present (Last_Extra) and then
5982         Present (Extra_Formal (Last_Extra))
5983       then
5984          return;
5985       end if;
5986
5987       --  If the subprogram is a predefined dispatching subprogram then don't
5988       --  generate any extra constrained or accessibility level formals. In
5989       --  general we suppress these for internal subprograms (by not calling
5990       --  Freeze_Subprogram and Create_Extra_Formals at all), but internally
5991       --  generated stream attributes do get passed through because extra
5992       --  build-in-place formals are needed in some cases (limited 'Input).
5993
5994       if Is_Predefined_Internal_Operation (E) then
5995          goto Test_For_BIP_Extras;
5996       end if;
5997
5998       Formal := First_Formal (E);
5999       while Present (Formal) loop
6000
6001          --  Create extra formal for supporting the attribute 'Constrained.
6002          --  The case of a private type view without discriminants also
6003          --  requires the extra formal if the underlying type has defaulted
6004          --  discriminants.
6005
6006          if Ekind (Formal) /= E_In_Parameter then
6007             if Present (P_Formal) then
6008                Formal_Type := Etype (P_Formal);
6009             else
6010                Formal_Type := Etype (Formal);
6011             end if;
6012
6013             --  Do not produce extra formals for Unchecked_Union parameters.
6014             --  Jump directly to the end of the loop.
6015
6016             if Is_Unchecked_Union (Base_Type (Formal_Type)) then
6017                goto Skip_Extra_Formal_Generation;
6018             end if;
6019
6020             if not Has_Discriminants (Formal_Type)
6021               and then Ekind (Formal_Type) in Private_Kind
6022               and then Present (Underlying_Type (Formal_Type))
6023             then
6024                Formal_Type := Underlying_Type (Formal_Type);
6025             end if;
6026
6027             --  Suppress the extra formal if formal's subtype is constrained or
6028             --  indefinite, or we're compiling for Ada 2012 and the underlying
6029             --  type is tagged and limited. In Ada 2012, a limited tagged type
6030             --  can have defaulted discriminants, but 'Constrained is required
6031             --  to return True, so the formal is never needed (see AI05-0214).
6032             --  Note that this ensures consistency of calling sequences for
6033             --  dispatching operations when some types in a class have defaults
6034             --  on discriminants and others do not (and requiring the extra
6035             --  formal would introduce distributed overhead).
6036
6037             if Has_Discriminants (Formal_Type)
6038               and then not Is_Constrained (Formal_Type)
6039               and then not Is_Indefinite_Subtype (Formal_Type)
6040               and then (Ada_Version < Ada_2012
6041                          or else
6042                            not (Is_Tagged_Type (Underlying_Type (Formal_Type))
6043                                  and then Is_Limited_Type (Formal_Type)))
6044             then
6045                Set_Extra_Constrained
6046                  (Formal, Add_Extra_Formal (Formal, Standard_Boolean, E, "O"));
6047             end if;
6048          end if;
6049
6050          --  Create extra formal for supporting accessibility checking. This
6051          --  is done for both anonymous access formals and formals of named
6052          --  access types that are marked as controlling formals. The latter
6053          --  case can occur when Expand_Dispatching_Call creates a subprogram
6054          --  type and substitutes the types of access-to-class-wide actuals
6055          --  for the anonymous access-to-specific-type of controlling formals.
6056          --  Base_Type is applied because in cases where there is a null
6057          --  exclusion the formal may have an access subtype.
6058
6059          --  This is suppressed if we specifically suppress accessibility
6060          --  checks at the package level for either the subprogram, or the
6061          --  package in which it resides. However, we do not suppress it
6062          --  simply if the scope has accessibility checks suppressed, since
6063          --  this could cause trouble when clients are compiled with a
6064          --  different suppression setting. The explicit checks at the
6065          --  package level are safe from this point of view.
6066
6067          if (Ekind (Base_Type (Etype (Formal))) = E_Anonymous_Access_Type
6068               or else (Is_Controlling_Formal (Formal)
6069                         and then Is_Access_Type (Base_Type (Etype (Formal)))))
6070            and then not
6071              (Explicit_Suppress (E, Accessibility_Check)
6072                or else
6073               Explicit_Suppress (Scope (E), Accessibility_Check))
6074            and then
6075              (No (P_Formal)
6076                or else Present (Extra_Accessibility (P_Formal)))
6077          then
6078             Set_Extra_Accessibility
6079               (Formal, Add_Extra_Formal (Formal, Standard_Natural, E, "L"));
6080          end if;
6081
6082          --  This label is required when skipping extra formal generation for
6083          --  Unchecked_Union parameters.
6084
6085          <<Skip_Extra_Formal_Generation>>
6086
6087          if Present (P_Formal) then
6088             Next_Formal (P_Formal);
6089          end if;
6090
6091          Next_Formal (Formal);
6092       end loop;
6093
6094       <<Test_For_BIP_Extras>>
6095
6096       --  Ada 2005 (AI-318-02): In the case of build-in-place functions, add
6097       --  appropriate extra formals. See type Exp_Ch6.BIP_Formal_Kind.
6098
6099       if Ada_Version >= Ada_2005 and then Is_Build_In_Place_Function (E) then
6100          declare
6101             Result_Subt : constant Entity_Id := Etype (E);
6102
6103             Discard : Entity_Id;
6104             pragma Warnings (Off, Discard);
6105
6106          begin
6107             --  In the case of functions with unconstrained result subtypes,
6108             --  add a 4-state formal indicating whether the return object is
6109             --  allocated by the caller (1), or should be allocated by the
6110             --  callee on the secondary stack (2), in the global heap (3), or
6111             --  in a user-defined storage pool (4). For the moment we just use
6112             --  Natural for the type of this formal. Note that this formal
6113             --  isn't usually needed in the case where the result subtype is
6114             --  constrained, but it is needed when the function has a tagged
6115             --  result, because generally such functions can be called in a
6116             --  dispatching context and such calls must be handled like calls
6117             --  to a class-wide function.
6118
6119             if not Is_Constrained (Underlying_Type (Result_Subt))
6120               or else Is_Tagged_Type (Underlying_Type (Result_Subt))
6121             then
6122                Discard :=
6123                  Add_Extra_Formal
6124                    (E, Standard_Natural,
6125                     E, BIP_Formal_Suffix (BIP_Alloc_Form));
6126             end if;
6127
6128             --  In the case of functions whose result type needs finalization,
6129             --  add an extra formal which represents the finalization master.
6130
6131             if Needs_BIP_Finalization_Master (E) then
6132                Discard :=
6133                  Add_Extra_Formal
6134                    (E, RTE (RE_Finalization_Master_Ptr),
6135                     E, BIP_Formal_Suffix (BIP_Finalization_Master));
6136             end if;
6137
6138             --  If the result type contains tasks, we have two extra formals:
6139             --  the master of the tasks to be created, and the caller's
6140             --  activation chain.
6141
6142             if Has_Task (Result_Subt) then
6143                Discard :=
6144                  Add_Extra_Formal
6145                    (E, RTE (RE_Master_Id),
6146                     E, BIP_Formal_Suffix (BIP_Master));
6147                Discard :=
6148                  Add_Extra_Formal
6149                    (E, RTE (RE_Activation_Chain_Access),
6150                     E, BIP_Formal_Suffix (BIP_Activation_Chain));
6151             end if;
6152
6153             --  All build-in-place functions get an extra formal that will be
6154             --  passed the address of the return object within the caller.
6155
6156             declare
6157                Formal_Type : constant Entity_Id :=
6158                                Create_Itype
6159                                  (E_Anonymous_Access_Type, E,
6160                                   Scope_Id => Scope (E));
6161             begin
6162                Set_Directly_Designated_Type (Formal_Type, Result_Subt);
6163                Set_Etype (Formal_Type, Formal_Type);
6164                Set_Depends_On_Private
6165                  (Formal_Type, Has_Private_Component (Formal_Type));
6166                Set_Is_Public (Formal_Type, Is_Public (Scope (Formal_Type)));
6167                Set_Is_Access_Constant (Formal_Type, False);
6168
6169                --  Ada 2005 (AI-50217): Propagate the attribute that indicates
6170                --  the designated type comes from the limited view (for
6171                --  back-end purposes).
6172
6173                Set_From_With_Type (Formal_Type, From_With_Type (Result_Subt));
6174
6175                Layout_Type (Formal_Type);
6176
6177                Discard :=
6178                  Add_Extra_Formal
6179                    (E, Formal_Type, E, BIP_Formal_Suffix (BIP_Object_Access));
6180             end;
6181          end;
6182       end if;
6183    end Create_Extra_Formals;
6184
6185    -----------------------------
6186    -- Enter_Overloaded_Entity --
6187    -----------------------------
6188
6189    procedure Enter_Overloaded_Entity (S : Entity_Id) is
6190       E   : Entity_Id := Current_Entity_In_Scope (S);
6191       C_E : Entity_Id := Current_Entity (S);
6192
6193    begin
6194       if Present (E) then
6195          Set_Has_Homonym (E);
6196          Set_Has_Homonym (S);
6197       end if;
6198
6199       Set_Is_Immediately_Visible (S);
6200       Set_Scope (S, Current_Scope);
6201
6202       --  Chain new entity if front of homonym in current scope, so that
6203       --  homonyms are contiguous.
6204
6205       if Present (E)
6206         and then E /= C_E
6207       then
6208          while Homonym (C_E) /= E loop
6209             C_E := Homonym (C_E);
6210          end loop;
6211
6212          Set_Homonym (C_E, S);
6213
6214       else
6215          E := C_E;
6216          Set_Current_Entity (S);
6217       end if;
6218
6219       Set_Homonym (S, E);
6220
6221       Append_Entity (S, Current_Scope);
6222       Set_Public_Status (S);
6223
6224       if Debug_Flag_E then
6225          Write_Str ("New overloaded entity chain: ");
6226          Write_Name (Chars (S));
6227
6228          E := S;
6229          while Present (E) loop
6230             Write_Str (" "); Write_Int (Int (E));
6231             E := Homonym (E);
6232          end loop;
6233
6234          Write_Eol;
6235       end if;
6236
6237       --  Generate warning for hiding
6238
6239       if Warn_On_Hiding
6240         and then Comes_From_Source (S)
6241         and then In_Extended_Main_Source_Unit (S)
6242       then
6243          E := S;
6244          loop
6245             E := Homonym (E);
6246             exit when No (E);
6247
6248             --  Warn unless genuine overloading. Do not emit warning on
6249             --  hiding predefined operators in Standard (these are either an
6250             --  (artifact of our implicit declarations, or simple noise) but
6251             --  keep warning on a operator defined on a local subtype, because
6252             --  of the real danger that different operators may be applied in
6253             --  various parts of the program.
6254
6255             --  Note that if E and S have the same scope, there is never any
6256             --  hiding. Either the two conflict, and the program is illegal,
6257             --  or S is overriding an implicit inherited subprogram.
6258
6259             if Scope (E) /= Scope (S)
6260                   and then (not Is_Overloadable (E)
6261                              or else Subtype_Conformant (E, S))
6262                   and then (Is_Immediately_Visible (E)
6263                               or else
6264                             Is_Potentially_Use_Visible (S))
6265             then
6266                if Scope (E) /= Standard_Standard then
6267                   Error_Msg_Sloc := Sloc (E);
6268                   Error_Msg_N ("declaration of & hides one#?", S);
6269
6270                elsif Nkind (S) = N_Defining_Operator_Symbol
6271                  and then
6272                    Scope (Base_Type (Etype (First_Formal (S)))) /= Scope (S)
6273                then
6274                   Error_Msg_N
6275                     ("declaration of & hides predefined operator?", S);
6276                end if;
6277             end if;
6278          end loop;
6279       end if;
6280    end Enter_Overloaded_Entity;
6281
6282    -----------------------------
6283    -- Check_Untagged_Equality --
6284    -----------------------------
6285
6286    procedure Check_Untagged_Equality (Eq_Op : Entity_Id) is
6287       Typ      : constant Entity_Id := Etype (First_Formal (Eq_Op));
6288       Decl     : constant Node_Id   := Unit_Declaration_Node (Eq_Op);
6289       Obj_Decl : Node_Id;
6290
6291    begin
6292       if Nkind (Decl) = N_Subprogram_Declaration
6293         and then Is_Record_Type (Typ)
6294         and then not Is_Tagged_Type (Typ)
6295       then
6296          --  If the type is not declared in a package, or if we are in the
6297          --  body of the package or in some other scope, the new operation is
6298          --  not primitive, and therefore legal, though suspicious. If the
6299          --  type is a generic actual (sub)type, the operation is not primitive
6300          --  either because the base type is declared elsewhere.
6301
6302          if Is_Frozen (Typ) then
6303             if Ekind (Scope (Typ)) /= E_Package
6304               or else Scope (Typ) /= Current_Scope
6305             then
6306                null;
6307
6308             elsif Is_Generic_Actual_Type (Typ) then
6309                null;
6310
6311             elsif In_Package_Body (Scope (Typ)) then
6312                Error_Msg_NE
6313                  ("equality operator must be declared "
6314                    & "before type& is frozen", Eq_Op, Typ);
6315                Error_Msg_N
6316                  ("\move declaration to package spec", Eq_Op);
6317
6318             else
6319                Error_Msg_NE
6320                  ("equality operator must be declared "
6321                    & "before type& is frozen", Eq_Op, Typ);
6322
6323                Obj_Decl := Next (Parent (Typ));
6324                while Present (Obj_Decl)
6325                  and then Obj_Decl /= Decl
6326                loop
6327                   if Nkind (Obj_Decl) = N_Object_Declaration
6328                     and then Etype (Defining_Identifier (Obj_Decl)) = Typ
6329                   then
6330                      Error_Msg_NE ("type& is frozen by declaration?",
6331                         Obj_Decl, Typ);
6332                      Error_Msg_N
6333                        ("\an equality operator cannot be declared after this "
6334                          & "point (RM 4.5.2 (9.8)) (Ada 2012))?", Obj_Decl);
6335                      exit;
6336                   end if;
6337
6338                   Next (Obj_Decl);
6339                end loop;
6340             end if;
6341
6342          elsif not In_Same_List (Parent (Typ), Decl)
6343            and then not Is_Limited_Type (Typ)
6344          then
6345
6346             --  This makes it illegal to have a primitive equality declared in
6347             --  the private part if the type is visible.
6348
6349             Error_Msg_N ("equality operator appears too late", Eq_Op);
6350          end if;
6351       end if;
6352    end Check_Untagged_Equality;
6353
6354    -----------------------------
6355    -- Find_Corresponding_Spec --
6356    -----------------------------
6357
6358    function Find_Corresponding_Spec
6359      (N          : Node_Id;
6360       Post_Error : Boolean := True) return Entity_Id
6361    is
6362       Spec       : constant Node_Id   := Specification (N);
6363       Designator : constant Entity_Id := Defining_Entity (Spec);
6364
6365       E : Entity_Id;
6366
6367    begin
6368       E := Current_Entity (Designator);
6369       while Present (E) loop
6370
6371          --  We are looking for a matching spec. It must have the same scope,
6372          --  and the same name, and either be type conformant, or be the case
6373          --  of a library procedure spec and its body (which belong to one
6374          --  another regardless of whether they are type conformant or not).
6375
6376          if Scope (E) = Current_Scope then
6377             if Current_Scope = Standard_Standard
6378               or else (Ekind (E) = Ekind (Designator)
6379                          and then Type_Conformant (E, Designator))
6380             then
6381                --  Within an instantiation, we know that spec and body are
6382                --  subtype conformant, because they were subtype conformant
6383                --  in the generic. We choose the subtype-conformant entity
6384                --  here as well, to resolve spurious ambiguities in the
6385                --  instance that were not present in the generic (i.e. when
6386                --  two different types are given the same actual). If we are
6387                --  looking for a spec to match a body, full conformance is
6388                --  expected.
6389
6390                if In_Instance then
6391                   Set_Convention (Designator, Convention (E));
6392
6393                   --  Skip past subprogram bodies and subprogram renamings that
6394                   --  may appear to have a matching spec, but that aren't fully
6395                   --  conformant with it. That can occur in cases where an
6396                   --  actual type causes unrelated homographs in the instance.
6397
6398                   if Nkind_In (N, N_Subprogram_Body,
6399                                   N_Subprogram_Renaming_Declaration)
6400                     and then Present (Homonym (E))
6401                     and then not Fully_Conformant (Designator, E)
6402                   then
6403                      goto Next_Entity;
6404
6405                   elsif not Subtype_Conformant (Designator, E) then
6406                      goto Next_Entity;
6407                   end if;
6408                end if;
6409
6410                --  Ada 2012 (AI05-0165): For internally generated bodies of
6411                --  null procedures locate the internally generated spec. We
6412                --  enforce mode conformance since a tagged type may inherit
6413                --  from interfaces several null primitives which differ only
6414                --  in the mode of the formals.
6415
6416                if not (Comes_From_Source (E))
6417                  and then Is_Null_Procedure (E)
6418                  and then not Mode_Conformant (Designator, E)
6419                then
6420                   null;
6421
6422                elsif not Has_Completion (E) then
6423                   if Nkind (N) /= N_Subprogram_Body_Stub then
6424                      Set_Corresponding_Spec (N, E);
6425                   end if;
6426
6427                   Set_Has_Completion (E);
6428                   return E;
6429
6430                elsif Nkind (Parent (N)) = N_Subunit then
6431
6432                   --  If this is the proper body of a subunit, the completion
6433                   --  flag is set when analyzing the stub.
6434
6435                   return E;
6436
6437                --  If E is an internal function with a controlling result
6438                --  that was created for an operation inherited by a null
6439                --  extension, it may be overridden by a body without a previous
6440                --  spec (one more reason why these should be shunned). In that
6441                --  case remove the generated body if present, because the
6442                --  current one is the explicit overriding.
6443
6444                elsif Ekind (E) = E_Function
6445                  and then Ada_Version >= Ada_2005
6446                  and then not Comes_From_Source (E)
6447                  and then Has_Controlling_Result (E)
6448                  and then Is_Null_Extension (Etype (E))
6449                  and then Comes_From_Source (Spec)
6450                then
6451                   Set_Has_Completion (E, False);
6452
6453                   if Expander_Active
6454                     and then Nkind (Parent (E)) = N_Function_Specification
6455                   then
6456                      Remove
6457                        (Unit_Declaration_Node
6458                           (Corresponding_Body (Unit_Declaration_Node (E))));
6459
6460                      return E;
6461
6462                   --  If expansion is disabled, or if the wrapper function has
6463                   --  not been generated yet, this a late body overriding an
6464                   --  inherited operation, or it is an overriding by some other
6465                   --  declaration before the controlling result is frozen. In
6466                   --  either case this is a declaration of a new entity.
6467
6468                   else
6469                      return Empty;
6470                   end if;
6471
6472                --  If the body already exists, then this is an error unless
6473                --  the previous declaration is the implicit declaration of a
6474                --  derived subprogram. It is also legal for an instance to
6475                --  contain type conformant overloadable declarations (but the
6476                --  generic declaration may not), per 8.3(26/2).
6477
6478                elsif No (Alias (E))
6479                  and then not Is_Intrinsic_Subprogram (E)
6480                  and then not In_Instance
6481                  and then Post_Error
6482                then
6483                   Error_Msg_Sloc := Sloc (E);
6484
6485                   if Is_Imported (E) then
6486                      Error_Msg_NE
6487                       ("body not allowed for imported subprogram & declared#",
6488                         N, E);
6489                   else
6490                      Error_Msg_NE ("duplicate body for & declared#", N, E);
6491                   end if;
6492                end if;
6493
6494             --  Child units cannot be overloaded, so a conformance mismatch
6495             --  between body and a previous spec is an error.
6496
6497             elsif Is_Child_Unit (E)
6498               and then
6499                 Nkind (Unit_Declaration_Node (Designator)) = N_Subprogram_Body
6500               and then
6501                 Nkind (Parent (Unit_Declaration_Node (Designator))) =
6502                   N_Compilation_Unit
6503               and then Post_Error
6504             then
6505                Error_Msg_N
6506                  ("body of child unit does not match previous declaration", N);
6507             end if;
6508          end if;
6509
6510          <<Next_Entity>>
6511             E := Homonym (E);
6512       end loop;
6513
6514       --  On exit, we know that no previous declaration of subprogram exists
6515
6516       return Empty;
6517    end Find_Corresponding_Spec;
6518
6519    ----------------------
6520    -- Fully_Conformant --
6521    ----------------------
6522
6523    function Fully_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
6524       Result : Boolean;
6525    begin
6526       Check_Conformance (New_Id, Old_Id, Fully_Conformant, False, Result);
6527       return Result;
6528    end Fully_Conformant;
6529
6530    ----------------------------------
6531    -- Fully_Conformant_Expressions --
6532    ----------------------------------
6533
6534    function Fully_Conformant_Expressions
6535      (Given_E1 : Node_Id;
6536       Given_E2 : Node_Id) return Boolean
6537    is
6538       E1 : constant Node_Id := Original_Node (Given_E1);
6539       E2 : constant Node_Id := Original_Node (Given_E2);
6540       --  We always test conformance on original nodes, since it is possible
6541       --  for analysis and/or expansion to make things look as though they
6542       --  conform when they do not, e.g. by converting 1+2 into 3.
6543
6544       function FCE (Given_E1, Given_E2 : Node_Id) return Boolean
6545         renames Fully_Conformant_Expressions;
6546
6547       function FCL (L1, L2 : List_Id) return Boolean;
6548       --  Compare elements of two lists for conformance. Elements have to
6549       --  be conformant, and actuals inserted as default parameters do not
6550       --  match explicit actuals with the same value.
6551
6552       function FCO (Op_Node, Call_Node : Node_Id) return Boolean;
6553       --  Compare an operator node with a function call
6554
6555       ---------
6556       -- FCL --
6557       ---------
6558
6559       function FCL (L1, L2 : List_Id) return Boolean is
6560          N1, N2 : Node_Id;
6561
6562       begin
6563          if L1 = No_List then
6564             N1 := Empty;
6565          else
6566             N1 := First (L1);
6567          end if;
6568
6569          if L2 = No_List then
6570             N2 := Empty;
6571          else
6572             N2 := First (L2);
6573          end if;
6574
6575          --  Compare two lists, skipping rewrite insertions (we want to
6576          --  compare the original trees, not the expanded versions!)
6577
6578          loop
6579             if Is_Rewrite_Insertion (N1) then
6580                Next (N1);
6581             elsif Is_Rewrite_Insertion (N2) then
6582                Next (N2);
6583             elsif No (N1) then
6584                return No (N2);
6585             elsif No (N2) then
6586                return False;
6587             elsif not FCE (N1, N2) then
6588                return False;
6589             else
6590                Next (N1);
6591                Next (N2);
6592             end if;
6593          end loop;
6594       end FCL;
6595
6596       ---------
6597       -- FCO --
6598       ---------
6599
6600       function FCO (Op_Node, Call_Node : Node_Id) return Boolean is
6601          Actuals : constant List_Id := Parameter_Associations (Call_Node);
6602          Act     : Node_Id;
6603
6604       begin
6605          if No (Actuals)
6606             or else Entity (Op_Node) /= Entity (Name (Call_Node))
6607          then
6608             return False;
6609
6610          else
6611             Act := First (Actuals);
6612
6613             if Nkind (Op_Node) in N_Binary_Op then
6614                if not FCE (Left_Opnd (Op_Node), Act) then
6615                   return False;
6616                end if;
6617
6618                Next (Act);
6619             end if;
6620
6621             return Present (Act)
6622               and then FCE (Right_Opnd (Op_Node), Act)
6623               and then No (Next (Act));
6624          end if;
6625       end FCO;
6626
6627    --  Start of processing for Fully_Conformant_Expressions
6628
6629    begin
6630       --  Non-conformant if paren count does not match. Note: if some idiot
6631       --  complains that we don't do this right for more than 3 levels of
6632       --  parentheses, they will be treated with the respect they deserve!
6633
6634       if Paren_Count (E1) /= Paren_Count (E2) then
6635          return False;
6636
6637       --  If same entities are referenced, then they are conformant even if
6638       --  they have different forms (RM 8.3.1(19-20)).
6639
6640       elsif Is_Entity_Name (E1) and then Is_Entity_Name (E2) then
6641          if Present (Entity (E1)) then
6642             return Entity (E1) = Entity (E2)
6643               or else (Chars (Entity (E1)) = Chars (Entity (E2))
6644                         and then Ekind (Entity (E1)) = E_Discriminant
6645                         and then Ekind (Entity (E2)) = E_In_Parameter);
6646
6647          elsif Nkind (E1) = N_Expanded_Name
6648            and then Nkind (E2) = N_Expanded_Name
6649            and then Nkind (Selector_Name (E1)) = N_Character_Literal
6650            and then Nkind (Selector_Name (E2)) = N_Character_Literal
6651          then
6652             return Chars (Selector_Name (E1)) = Chars (Selector_Name (E2));
6653
6654          else
6655             --  Identifiers in component associations don't always have
6656             --  entities, but their names must conform.
6657
6658             return Nkind  (E1) = N_Identifier
6659               and then Nkind (E2) = N_Identifier
6660               and then Chars (E1) = Chars (E2);
6661          end if;
6662
6663       elsif Nkind (E1) = N_Character_Literal
6664         and then Nkind (E2) = N_Expanded_Name
6665       then
6666          return Nkind (Selector_Name (E2)) = N_Character_Literal
6667            and then Chars (E1) = Chars (Selector_Name (E2));
6668
6669       elsif Nkind (E2) = N_Character_Literal
6670         and then Nkind (E1) = N_Expanded_Name
6671       then
6672          return Nkind (Selector_Name (E1)) = N_Character_Literal
6673            and then Chars (E2) = Chars (Selector_Name (E1));
6674
6675       elsif Nkind (E1) in N_Op
6676         and then Nkind (E2) = N_Function_Call
6677       then
6678          return FCO (E1, E2);
6679
6680       elsif Nkind (E2) in N_Op
6681         and then Nkind (E1) = N_Function_Call
6682       then
6683          return FCO (E2, E1);
6684
6685       --  Otherwise we must have the same syntactic entity
6686
6687       elsif Nkind (E1) /= Nkind (E2) then
6688          return False;
6689
6690       --  At this point, we specialize by node type
6691
6692       else
6693          case Nkind (E1) is
6694
6695             when N_Aggregate =>
6696                return
6697                  FCL (Expressions (E1), Expressions (E2))
6698                    and then
6699                  FCL (Component_Associations (E1),
6700                       Component_Associations (E2));
6701
6702             when N_Allocator =>
6703                if Nkind (Expression (E1)) = N_Qualified_Expression
6704                     or else
6705                   Nkind (Expression (E2)) = N_Qualified_Expression
6706                then
6707                   return FCE (Expression (E1), Expression (E2));
6708
6709                --  Check that the subtype marks and any constraints
6710                --  are conformant
6711
6712                else
6713                   declare
6714                      Indic1 : constant Node_Id := Expression (E1);
6715                      Indic2 : constant Node_Id := Expression (E2);
6716                      Elt1   : Node_Id;
6717                      Elt2   : Node_Id;
6718
6719                   begin
6720                      if Nkind (Indic1) /= N_Subtype_Indication then
6721                         return
6722                           Nkind (Indic2) /= N_Subtype_Indication
6723                             and then Entity (Indic1) = Entity (Indic2);
6724
6725                      elsif Nkind (Indic2) /= N_Subtype_Indication then
6726                         return
6727                           Nkind (Indic1) /= N_Subtype_Indication
6728                             and then Entity (Indic1) = Entity (Indic2);
6729
6730                      else
6731                         if Entity (Subtype_Mark (Indic1)) /=
6732                           Entity (Subtype_Mark (Indic2))
6733                         then
6734                            return False;
6735                         end if;
6736
6737                         Elt1 := First (Constraints (Constraint (Indic1)));
6738                         Elt2 := First (Constraints (Constraint (Indic2)));
6739                         while Present (Elt1) and then Present (Elt2) loop
6740                            if not FCE (Elt1, Elt2) then
6741                               return False;
6742                            end if;
6743
6744                            Next (Elt1);
6745                            Next (Elt2);
6746                         end loop;
6747
6748                         return True;
6749                      end if;
6750                   end;
6751                end if;
6752
6753             when N_Attribute_Reference =>
6754                return
6755                  Attribute_Name (E1) = Attribute_Name (E2)
6756                    and then FCL (Expressions (E1), Expressions (E2));
6757
6758             when N_Binary_Op =>
6759                return
6760                  Entity (E1) = Entity (E2)
6761                    and then FCE (Left_Opnd  (E1), Left_Opnd  (E2))
6762                    and then FCE (Right_Opnd (E1), Right_Opnd (E2));
6763
6764             when N_Short_Circuit | N_Membership_Test =>
6765                return
6766                  FCE (Left_Opnd  (E1), Left_Opnd  (E2))
6767                    and then
6768                  FCE (Right_Opnd (E1), Right_Opnd (E2));
6769
6770             when N_Case_Expression =>
6771                declare
6772                   Alt1 : Node_Id;
6773                   Alt2 : Node_Id;
6774
6775                begin
6776                   if not FCE (Expression (E1), Expression (E2)) then
6777                      return False;
6778
6779                   else
6780                      Alt1 := First (Alternatives (E1));
6781                      Alt2 := First (Alternatives (E2));
6782                      loop
6783                         if Present (Alt1) /= Present (Alt2) then
6784                            return False;
6785                         elsif No (Alt1) then
6786                            return True;
6787                         end if;
6788
6789                         if not FCE (Expression (Alt1), Expression (Alt2))
6790                           or else not FCL (Discrete_Choices (Alt1),
6791                                            Discrete_Choices (Alt2))
6792                         then
6793                            return False;
6794                         end if;
6795
6796                         Next (Alt1);
6797                         Next (Alt2);
6798                      end loop;
6799                   end if;
6800                end;
6801
6802             when N_Character_Literal =>
6803                return
6804                  Char_Literal_Value (E1) = Char_Literal_Value (E2);
6805
6806             when N_Component_Association =>
6807                return
6808                  FCL (Choices (E1), Choices (E2))
6809                    and then
6810                  FCE (Expression (E1), Expression (E2));
6811
6812             when N_Conditional_Expression =>
6813                return
6814                  FCL (Expressions (E1), Expressions (E2));
6815
6816             when N_Explicit_Dereference =>
6817                return
6818                  FCE (Prefix (E1), Prefix (E2));
6819
6820             when N_Extension_Aggregate =>
6821                return
6822                  FCL (Expressions (E1), Expressions (E2))
6823                    and then Null_Record_Present (E1) =
6824                             Null_Record_Present (E2)
6825                    and then FCL (Component_Associations (E1),
6826                                Component_Associations (E2));
6827
6828             when N_Function_Call =>
6829                return
6830                  FCE (Name (E1), Name (E2))
6831                    and then
6832                  FCL (Parameter_Associations (E1),
6833                       Parameter_Associations (E2));
6834
6835             when N_Indexed_Component =>
6836                return
6837                  FCE (Prefix (E1), Prefix (E2))
6838                    and then
6839                  FCL (Expressions (E1), Expressions (E2));
6840
6841             when N_Integer_Literal =>
6842                return (Intval (E1) = Intval (E2));
6843
6844             when N_Null =>
6845                return True;
6846
6847             when N_Operator_Symbol =>
6848                return
6849                  Chars (E1) = Chars (E2);
6850
6851             when N_Others_Choice =>
6852                return True;
6853
6854             when N_Parameter_Association =>
6855                return
6856                  Chars (Selector_Name (E1))  = Chars (Selector_Name (E2))
6857                    and then FCE (Explicit_Actual_Parameter (E1),
6858                                  Explicit_Actual_Parameter (E2));
6859
6860             when N_Qualified_Expression =>
6861                return
6862                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6863                    and then
6864                  FCE (Expression (E1), Expression (E2));
6865
6866             when N_Quantified_Expression =>
6867                if not FCE (Condition (E1), Condition (E2)) then
6868                   return False;
6869                end if;
6870
6871                if Present (Loop_Parameter_Specification (E1))
6872                  and then Present (Loop_Parameter_Specification (E2))
6873                then
6874                   declare
6875                      L1 : constant Node_Id :=
6876                        Loop_Parameter_Specification (E1);
6877                      L2 : constant Node_Id :=
6878                        Loop_Parameter_Specification (E2);
6879
6880                   begin
6881                      return
6882                        Reverse_Present (L1) = Reverse_Present (L2)
6883                          and then
6884                            FCE (Defining_Identifier (L1),
6885                                 Defining_Identifier (L2))
6886                          and then
6887                            FCE (Discrete_Subtype_Definition (L1),
6888                                 Discrete_Subtype_Definition (L2));
6889                   end;
6890
6891                else   --  quantified expression with an iterator
6892                   declare
6893                      I1 : constant Node_Id := Iterator_Specification (E1);
6894                      I2 : constant Node_Id := Iterator_Specification (E2);
6895
6896                   begin
6897                      return
6898                        FCE (Defining_Identifier (I1),
6899                             Defining_Identifier (I2))
6900                        and then
6901                          Of_Present (I1) = Of_Present (I2)
6902                        and then
6903                          Reverse_Present (I1) = Reverse_Present (I2)
6904                        and then FCE (Name (I1), Name (I2))
6905                        and then FCE (Subtype_Indication (I1),
6906                                       Subtype_Indication (I2));
6907                   end;
6908                end if;
6909
6910             when N_Range =>
6911                return
6912                  FCE (Low_Bound (E1), Low_Bound (E2))
6913                    and then
6914                  FCE (High_Bound (E1), High_Bound (E2));
6915
6916             when N_Real_Literal =>
6917                return (Realval (E1) = Realval (E2));
6918
6919             when N_Selected_Component =>
6920                return
6921                  FCE (Prefix (E1), Prefix (E2))
6922                    and then
6923                  FCE (Selector_Name (E1), Selector_Name (E2));
6924
6925             when N_Slice =>
6926                return
6927                  FCE (Prefix (E1), Prefix (E2))
6928                    and then
6929                  FCE (Discrete_Range (E1), Discrete_Range (E2));
6930
6931             when N_String_Literal =>
6932                declare
6933                   S1 : constant String_Id := Strval (E1);
6934                   S2 : constant String_Id := Strval (E2);
6935                   L1 : constant Nat       := String_Length (S1);
6936                   L2 : constant Nat       := String_Length (S2);
6937
6938                begin
6939                   if L1 /= L2 then
6940                      return False;
6941
6942                   else
6943                      for J in 1 .. L1 loop
6944                         if Get_String_Char (S1, J) /=
6945                            Get_String_Char (S2, J)
6946                         then
6947                            return False;
6948                         end if;
6949                      end loop;
6950
6951                      return True;
6952                   end if;
6953                end;
6954
6955             when N_Type_Conversion =>
6956                return
6957                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6958                    and then
6959                  FCE (Expression (E1), Expression (E2));
6960
6961             when N_Unary_Op =>
6962                return
6963                  Entity (E1) = Entity (E2)
6964                    and then
6965                  FCE (Right_Opnd (E1), Right_Opnd (E2));
6966
6967             when N_Unchecked_Type_Conversion =>
6968                return
6969                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6970                    and then
6971                  FCE (Expression (E1), Expression (E2));
6972
6973             --  All other node types cannot appear in this context. Strictly
6974             --  we should raise a fatal internal error. Instead we just ignore
6975             --  the nodes. This means that if anyone makes a mistake in the
6976             --  expander and mucks an expression tree irretrievably, the
6977             --  result will be a failure to detect a (probably very obscure)
6978             --  case of non-conformance, which is better than bombing on some
6979             --  case where two expressions do in fact conform.
6980
6981             when others =>
6982                return True;
6983
6984          end case;
6985       end if;
6986    end Fully_Conformant_Expressions;
6987
6988    ----------------------------------------
6989    -- Fully_Conformant_Discrete_Subtypes --
6990    ----------------------------------------
6991
6992    function Fully_Conformant_Discrete_Subtypes
6993      (Given_S1 : Node_Id;
6994       Given_S2 : Node_Id) return Boolean
6995    is
6996       S1 : constant Node_Id := Original_Node (Given_S1);
6997       S2 : constant Node_Id := Original_Node (Given_S2);
6998
6999       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean;
7000       --  Special-case for a bound given by a discriminant, which in the body
7001       --  is replaced with the discriminal of the enclosing type.
7002
7003       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean;
7004       --  Check both bounds
7005
7006       -----------------------
7007       -- Conforming_Bounds --
7008       -----------------------
7009
7010       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean is
7011       begin
7012          if Is_Entity_Name (B1)
7013            and then Is_Entity_Name (B2)
7014            and then Ekind (Entity (B1)) = E_Discriminant
7015          then
7016             return Chars (B1) = Chars (B2);
7017
7018          else
7019             return Fully_Conformant_Expressions (B1, B2);
7020          end if;
7021       end Conforming_Bounds;
7022
7023       -----------------------
7024       -- Conforming_Ranges --
7025       -----------------------
7026
7027       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean is
7028       begin
7029          return
7030            Conforming_Bounds (Low_Bound (R1), Low_Bound (R2))
7031              and then
7032            Conforming_Bounds (High_Bound (R1), High_Bound (R2));
7033       end Conforming_Ranges;
7034
7035    --  Start of processing for Fully_Conformant_Discrete_Subtypes
7036
7037    begin
7038       if Nkind (S1) /= Nkind (S2) then
7039          return False;
7040
7041       elsif Is_Entity_Name (S1) then
7042          return Entity (S1) = Entity (S2);
7043
7044       elsif Nkind (S1) = N_Range then
7045          return Conforming_Ranges (S1, S2);
7046
7047       elsif Nkind (S1) = N_Subtype_Indication then
7048          return
7049             Entity (Subtype_Mark (S1)) = Entity (Subtype_Mark (S2))
7050               and then
7051             Conforming_Ranges
7052               (Range_Expression (Constraint (S1)),
7053                Range_Expression (Constraint (S2)));
7054       else
7055          return True;
7056       end if;
7057    end Fully_Conformant_Discrete_Subtypes;
7058
7059    --------------------
7060    -- Install_Entity --
7061    --------------------
7062
7063    procedure Install_Entity (E : Entity_Id) is
7064       Prev : constant Entity_Id := Current_Entity (E);
7065    begin
7066       Set_Is_Immediately_Visible (E);
7067       Set_Current_Entity (E);
7068       Set_Homonym (E, Prev);
7069    end Install_Entity;
7070
7071    ---------------------
7072    -- Install_Formals --
7073    ---------------------
7074
7075    procedure Install_Formals (Id : Entity_Id) is
7076       F : Entity_Id;
7077    begin
7078       F := First_Formal (Id);
7079       while Present (F) loop
7080          Install_Entity (F);
7081          Next_Formal (F);
7082       end loop;
7083    end Install_Formals;
7084
7085    -----------------------------
7086    -- Is_Interface_Conformant --
7087    -----------------------------
7088
7089    function Is_Interface_Conformant
7090      (Tagged_Type : Entity_Id;
7091       Iface_Prim  : Entity_Id;
7092       Prim        : Entity_Id) return Boolean
7093    is
7094       Iface : constant Entity_Id := Find_Dispatching_Type (Iface_Prim);
7095       Typ   : constant Entity_Id := Find_Dispatching_Type (Prim);
7096
7097       function Controlling_Formal (Prim : Entity_Id) return Entity_Id;
7098       --  Return the controlling formal of Prim
7099
7100       ------------------------
7101       -- Controlling_Formal --
7102       ------------------------
7103
7104       function Controlling_Formal (Prim : Entity_Id) return Entity_Id is
7105          E : Entity_Id := First_Entity (Prim);
7106
7107       begin
7108          while Present (E) loop
7109             if Is_Formal (E) and then Is_Controlling_Formal (E) then
7110                return E;
7111             end if;
7112
7113             Next_Entity (E);
7114          end loop;
7115
7116          return Empty;
7117       end Controlling_Formal;
7118
7119       --  Local variables
7120
7121       Iface_Ctrl_F : constant Entity_Id := Controlling_Formal (Iface_Prim);
7122       Prim_Ctrl_F  : constant Entity_Id := Controlling_Formal (Prim);
7123
7124    --  Start of processing for Is_Interface_Conformant
7125
7126    begin
7127       pragma Assert (Is_Subprogram (Iface_Prim)
7128         and then Is_Subprogram (Prim)
7129         and then Is_Dispatching_Operation (Iface_Prim)
7130         and then Is_Dispatching_Operation (Prim));
7131
7132       pragma Assert (Is_Interface (Iface)
7133         or else (Present (Alias (Iface_Prim))
7134                    and then
7135                      Is_Interface
7136                        (Find_Dispatching_Type (Ultimate_Alias (Iface_Prim)))));
7137
7138       if Prim = Iface_Prim
7139         or else not Is_Subprogram (Prim)
7140         or else Ekind (Prim) /= Ekind (Iface_Prim)
7141         or else not Is_Dispatching_Operation (Prim)
7142         or else Scope (Prim) /= Scope (Tagged_Type)
7143         or else No (Typ)
7144         or else Base_Type (Typ) /= Tagged_Type
7145         or else not Primitive_Names_Match (Iface_Prim, Prim)
7146       then
7147          return False;
7148
7149       --  The mode of the controlling formals must match
7150
7151       elsif Present (Iface_Ctrl_F)
7152          and then Present (Prim_Ctrl_F)
7153          and then Ekind (Iface_Ctrl_F) /= Ekind (Prim_Ctrl_F)
7154       then
7155          return False;
7156
7157       --  Case of a procedure, or a function whose result type matches the
7158       --  result type of the interface primitive, or a function that has no
7159       --  controlling result (I or access I).
7160
7161       elsif Ekind (Iface_Prim) = E_Procedure
7162         or else Etype (Prim) = Etype (Iface_Prim)
7163         or else not Has_Controlling_Result (Prim)
7164       then
7165          return Type_Conformant
7166                   (Iface_Prim, Prim, Skip_Controlling_Formals => True);
7167
7168       --  Case of a function returning an interface, or an access to one.
7169       --  Check that the return types correspond.
7170
7171       elsif Implements_Interface (Typ, Iface) then
7172          if (Ekind (Etype (Prim)) = E_Anonymous_Access_Type)
7173               /=
7174             (Ekind (Etype (Iface_Prim)) = E_Anonymous_Access_Type)
7175          then
7176             return False;
7177          else
7178             return
7179               Type_Conformant (Prim, Iface_Prim,
7180                 Skip_Controlling_Formals => True);
7181          end if;
7182
7183       else
7184          return False;
7185       end if;
7186    end Is_Interface_Conformant;
7187
7188    ---------------------------------
7189    -- Is_Non_Overriding_Operation --
7190    ---------------------------------
7191
7192    function Is_Non_Overriding_Operation
7193      (Prev_E : Entity_Id;
7194       New_E  : Entity_Id) return Boolean
7195    is
7196       Formal : Entity_Id;
7197       F_Typ  : Entity_Id;
7198       G_Typ  : Entity_Id := Empty;
7199
7200       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id;
7201       --  If F_Type is a derived type associated with a generic actual subtype,
7202       --  then return its Generic_Parent_Type attribute, else return Empty.
7203
7204       function Types_Correspond
7205         (P_Type : Entity_Id;
7206          N_Type : Entity_Id) return Boolean;
7207       --  Returns true if and only if the types (or designated types in the
7208       --  case of anonymous access types) are the same or N_Type is derived
7209       --  directly or indirectly from P_Type.
7210
7211       -----------------------------
7212       -- Get_Generic_Parent_Type --
7213       -----------------------------
7214
7215       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id is
7216          G_Typ : Entity_Id;
7217          Defn  : Node_Id;
7218          Indic : Node_Id;
7219
7220       begin
7221          if Is_Derived_Type (F_Typ)
7222            and then Nkind (Parent (F_Typ)) = N_Full_Type_Declaration
7223          then
7224             --  The tree must be traversed to determine the parent subtype in
7225             --  the generic unit, which unfortunately isn't always available
7226             --  via semantic attributes. ??? (Note: The use of Original_Node
7227             --  is needed for cases where a full derived type has been
7228             --  rewritten.)
7229
7230             Defn := Type_Definition (Original_Node (Parent (F_Typ)));
7231             if Nkind (Defn) = N_Derived_Type_Definition then
7232                Indic := Subtype_Indication (Defn);
7233
7234                if Nkind (Indic) = N_Subtype_Indication then
7235                   G_Typ := Entity (Subtype_Mark (Indic));
7236                else
7237                   G_Typ := Entity (Indic);
7238                end if;
7239
7240                if Nkind (Parent (G_Typ)) = N_Subtype_Declaration
7241                  and then Present (Generic_Parent_Type (Parent (G_Typ)))
7242                then
7243                   return Generic_Parent_Type (Parent (G_Typ));
7244                end if;
7245             end if;
7246          end if;
7247
7248          return Empty;
7249       end Get_Generic_Parent_Type;
7250
7251       ----------------------
7252       -- Types_Correspond --
7253       ----------------------
7254
7255       function Types_Correspond
7256         (P_Type : Entity_Id;
7257          N_Type : Entity_Id) return Boolean
7258       is
7259          Prev_Type : Entity_Id := Base_Type (P_Type);
7260          New_Type  : Entity_Id := Base_Type (N_Type);
7261
7262       begin
7263          if Ekind (Prev_Type) = E_Anonymous_Access_Type then
7264             Prev_Type := Designated_Type (Prev_Type);
7265          end if;
7266
7267          if Ekind (New_Type) = E_Anonymous_Access_Type then
7268             New_Type := Designated_Type (New_Type);
7269          end if;
7270
7271          if Prev_Type = New_Type then
7272             return True;
7273
7274          elsif not Is_Class_Wide_Type (New_Type) then
7275             while Etype (New_Type) /= New_Type loop
7276                New_Type := Etype (New_Type);
7277                if New_Type = Prev_Type then
7278                   return True;
7279                end if;
7280             end loop;
7281          end if;
7282          return False;
7283       end Types_Correspond;
7284
7285    --  Start of processing for Is_Non_Overriding_Operation
7286
7287    begin
7288       --  In the case where both operations are implicit derived subprograms
7289       --  then neither overrides the other. This can only occur in certain
7290       --  obscure cases (e.g., derivation from homographs created in a generic
7291       --  instantiation).
7292
7293       if Present (Alias (Prev_E)) and then Present (Alias (New_E)) then
7294          return True;
7295
7296       elsif Ekind (Current_Scope) = E_Package
7297         and then Is_Generic_Instance (Current_Scope)
7298         and then In_Private_Part (Current_Scope)
7299         and then Comes_From_Source (New_E)
7300       then
7301          --  We examine the formals and result type of the inherited operation,
7302          --  to determine whether their type is derived from (the instance of)
7303          --  a generic type. The first such formal or result type is the one
7304          --  tested.
7305
7306          Formal := First_Formal (Prev_E);
7307          while Present (Formal) loop
7308             F_Typ := Base_Type (Etype (Formal));
7309
7310             if Ekind (F_Typ) = E_Anonymous_Access_Type then
7311                F_Typ := Designated_Type (F_Typ);
7312             end if;
7313
7314             G_Typ := Get_Generic_Parent_Type (F_Typ);
7315             exit when Present (G_Typ);
7316
7317             Next_Formal (Formal);
7318          end loop;
7319
7320          if No (G_Typ) and then Ekind (Prev_E) = E_Function then
7321             G_Typ := Get_Generic_Parent_Type (Base_Type (Etype (Prev_E)));
7322          end if;
7323
7324          if No (G_Typ) then
7325             return False;
7326          end if;
7327
7328          --  If the generic type is a private type, then the original operation
7329          --  was not overriding in the generic, because there was no primitive
7330          --  operation to override.
7331
7332          if Nkind (Parent (G_Typ)) = N_Formal_Type_Declaration
7333            and then Nkind (Formal_Type_Definition (Parent (G_Typ))) =
7334                       N_Formal_Private_Type_Definition
7335          then
7336             return True;
7337
7338          --  The generic parent type is the ancestor of a formal derived
7339          --  type declaration. We need to check whether it has a primitive
7340          --  operation that should be overridden by New_E in the generic.
7341
7342          else
7343             declare
7344                P_Formal : Entity_Id;
7345                N_Formal : Entity_Id;
7346                P_Typ    : Entity_Id;
7347                N_Typ    : Entity_Id;
7348                P_Prim   : Entity_Id;
7349                Prim_Elt : Elmt_Id := First_Elmt (Primitive_Operations (G_Typ));
7350
7351             begin
7352                while Present (Prim_Elt) loop
7353                   P_Prim := Node (Prim_Elt);
7354
7355                   if Chars (P_Prim) = Chars (New_E)
7356                     and then Ekind (P_Prim) = Ekind (New_E)
7357                   then
7358                      P_Formal := First_Formal (P_Prim);
7359                      N_Formal := First_Formal (New_E);
7360                      while Present (P_Formal) and then Present (N_Formal) loop
7361                         P_Typ := Etype (P_Formal);
7362                         N_Typ := Etype (N_Formal);
7363
7364                         if not Types_Correspond (P_Typ, N_Typ) then
7365                            exit;
7366                         end if;
7367
7368                         Next_Entity (P_Formal);
7369                         Next_Entity (N_Formal);
7370                      end loop;
7371
7372                      --  Found a matching primitive operation belonging to the
7373                      --  formal ancestor type, so the new subprogram is
7374                      --  overriding.
7375
7376                      if No (P_Formal)
7377                        and then No (N_Formal)
7378                        and then (Ekind (New_E) /= E_Function
7379                                   or else
7380                                  Types_Correspond
7381                                    (Etype (P_Prim), Etype (New_E)))
7382                      then
7383                         return False;
7384                      end if;
7385                   end if;
7386
7387                   Next_Elmt (Prim_Elt);
7388                end loop;
7389
7390                --  If no match found, then the new subprogram does not
7391                --  override in the generic (nor in the instance).
7392
7393                return True;
7394             end;
7395          end if;
7396       else
7397          return False;
7398       end if;
7399    end Is_Non_Overriding_Operation;
7400
7401    -------------------------------------
7402    -- List_Inherited_Pre_Post_Aspects --
7403    -------------------------------------
7404
7405    procedure List_Inherited_Pre_Post_Aspects (E : Entity_Id) is
7406    begin
7407       if Opt.List_Inherited_Aspects
7408         and then (Is_Subprogram (E) or else Is_Generic_Subprogram (E))
7409       then
7410          declare
7411             Inherited : constant Subprogram_List :=
7412                           Inherited_Subprograms (E);
7413             P         : Node_Id;
7414
7415          begin
7416             for J in Inherited'Range loop
7417                P := Spec_PPC_List (Contract (Inherited (J)));
7418
7419                while Present (P) loop
7420                   Error_Msg_Sloc := Sloc (P);
7421
7422                   if Class_Present (P) and then not Split_PPC (P) then
7423                      if Pragma_Name (P) = Name_Precondition then
7424                         Error_Msg_N
7425                           ("?info: & inherits `Pre''Class` aspect from #", E);
7426                      else
7427                         Error_Msg_N
7428                           ("?info: & inherits `Post''Class` aspect from #", E);
7429                      end if;
7430                   end if;
7431
7432                   P := Next_Pragma (P);
7433                end loop;
7434             end loop;
7435          end;
7436       end if;
7437    end List_Inherited_Pre_Post_Aspects;
7438
7439    ------------------------------
7440    -- Make_Inequality_Operator --
7441    ------------------------------
7442
7443    --  S is the defining identifier of an equality operator. We build a
7444    --  subprogram declaration with the right signature. This operation is
7445    --  intrinsic, because it is always expanded as the negation of the
7446    --  call to the equality function.
7447
7448    procedure Make_Inequality_Operator (S : Entity_Id) is
7449       Loc     : constant Source_Ptr := Sloc (S);
7450       Decl    : Node_Id;
7451       Formals : List_Id;
7452       Op_Name : Entity_Id;
7453
7454       FF : constant Entity_Id := First_Formal (S);
7455       NF : constant Entity_Id := Next_Formal (FF);
7456
7457    begin
7458       --  Check that equality was properly defined, ignore call if not
7459
7460       if No (NF) then
7461          return;
7462       end if;
7463
7464       declare
7465          A : constant Entity_Id :=
7466                Make_Defining_Identifier (Sloc (FF),
7467                  Chars => Chars (FF));
7468
7469          B : constant Entity_Id :=
7470                Make_Defining_Identifier (Sloc (NF),
7471                  Chars => Chars (NF));
7472
7473       begin
7474          Op_Name := Make_Defining_Operator_Symbol (Loc, Name_Op_Ne);
7475
7476          Formals := New_List (
7477            Make_Parameter_Specification (Loc,
7478              Defining_Identifier => A,
7479              Parameter_Type      =>
7480                New_Reference_To (Etype (First_Formal (S)),
7481                  Sloc (Etype (First_Formal (S))))),
7482
7483            Make_Parameter_Specification (Loc,
7484              Defining_Identifier => B,
7485              Parameter_Type      =>
7486                New_Reference_To (Etype (Next_Formal (First_Formal (S))),
7487                  Sloc (Etype (Next_Formal (First_Formal (S)))))));
7488
7489          Decl :=
7490            Make_Subprogram_Declaration (Loc,
7491              Specification =>
7492                Make_Function_Specification (Loc,
7493                  Defining_Unit_Name       => Op_Name,
7494                  Parameter_Specifications => Formals,
7495                  Result_Definition        =>
7496                    New_Reference_To (Standard_Boolean, Loc)));
7497
7498          --  Insert inequality right after equality if it is explicit or after
7499          --  the derived type when implicit. These entities are created only
7500          --  for visibility purposes, and eventually replaced in the course of
7501          --  expansion, so they do not need to be attached to the tree and seen
7502          --  by the back-end. Keeping them internal also avoids spurious
7503          --  freezing problems. The declaration is inserted in the tree for
7504          --  analysis, and removed afterwards. If the equality operator comes
7505          --  from an explicit declaration, attach the inequality immediately
7506          --  after. Else the equality is inherited from a derived type
7507          --  declaration, so insert inequality after that declaration.
7508
7509          if No (Alias (S)) then
7510             Insert_After (Unit_Declaration_Node (S), Decl);
7511          elsif Is_List_Member (Parent (S)) then
7512             Insert_After (Parent (S), Decl);
7513          else
7514             Insert_After (Parent (Etype (First_Formal (S))), Decl);
7515          end if;
7516
7517          Mark_Rewrite_Insertion (Decl);
7518          Set_Is_Intrinsic_Subprogram (Op_Name);
7519          Analyze (Decl);
7520          Remove (Decl);
7521          Set_Has_Completion (Op_Name);
7522          Set_Corresponding_Equality (Op_Name, S);
7523          Set_Is_Abstract_Subprogram (Op_Name, Is_Abstract_Subprogram (S));
7524       end;
7525    end Make_Inequality_Operator;
7526
7527    ----------------------
7528    -- May_Need_Actuals --
7529    ----------------------
7530
7531    procedure May_Need_Actuals (Fun : Entity_Id) is
7532       F : Entity_Id;
7533       B : Boolean;
7534
7535    begin
7536       F := First_Formal (Fun);
7537       B := True;
7538       while Present (F) loop
7539          if No (Default_Value (F)) then
7540             B := False;
7541             exit;
7542          end if;
7543
7544          Next_Formal (F);
7545       end loop;
7546
7547       Set_Needs_No_Actuals (Fun, B);
7548    end May_Need_Actuals;
7549
7550    ---------------------
7551    -- Mode_Conformant --
7552    ---------------------
7553
7554    function Mode_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
7555       Result : Boolean;
7556    begin
7557       Check_Conformance (New_Id, Old_Id, Mode_Conformant, False, Result);
7558       return Result;
7559    end Mode_Conformant;
7560
7561    ---------------------------
7562    -- New_Overloaded_Entity --
7563    ---------------------------
7564
7565    procedure New_Overloaded_Entity
7566      (S            : Entity_Id;
7567       Derived_Type : Entity_Id := Empty)
7568    is
7569       Overridden_Subp : Entity_Id := Empty;
7570       --  Set if the current scope has an operation that is type-conformant
7571       --  with S, and becomes hidden by S.
7572
7573       Is_Primitive_Subp : Boolean;
7574       --  Set to True if the new subprogram is primitive
7575
7576       E : Entity_Id;
7577       --  Entity that S overrides
7578
7579       Prev_Vis : Entity_Id := Empty;
7580       --  Predecessor of E in Homonym chain
7581
7582       procedure Check_For_Primitive_Subprogram
7583         (Is_Primitive  : out Boolean;
7584          Is_Overriding : Boolean := False);
7585       --  If the subprogram being analyzed is a primitive operation of the type
7586       --  of a formal or result, set the Has_Primitive_Operations flag on the
7587       --  type, and set Is_Primitive to True (otherwise set to False). Set the
7588       --  corresponding flag on the entity itself for later use.
7589
7590       procedure Check_Synchronized_Overriding
7591         (Def_Id          : Entity_Id;
7592          Overridden_Subp : out Entity_Id);
7593       --  First determine if Def_Id is an entry or a subprogram either defined
7594       --  in the scope of a task or protected type, or is a primitive of such
7595       --  a type. Check whether Def_Id overrides a subprogram of an interface
7596       --  implemented by the synchronized type, return the overridden entity
7597       --  or Empty.
7598
7599       function Is_Private_Declaration (E : Entity_Id) return Boolean;
7600       --  Check that E is declared in the private part of the current package,
7601       --  or in the package body, where it may hide a previous declaration.
7602       --  We can't use In_Private_Part by itself because this flag is also
7603       --  set when freezing entities, so we must examine the place of the
7604       --  declaration in the tree, and recognize wrapper packages as well.
7605
7606       function Is_Overriding_Alias
7607         (Old_E : Entity_Id;
7608          New_E : Entity_Id) return Boolean;
7609       --  Check whether new subprogram and old subprogram are both inherited
7610       --  from subprograms that have distinct dispatch table entries. This can
7611       --  occur with derivations from instances with accidental homonyms.
7612       --  The function is conservative given that the converse is only true
7613       --  within instances that contain accidental overloadings.
7614
7615       ------------------------------------
7616       -- Check_For_Primitive_Subprogram --
7617       ------------------------------------
7618
7619       procedure Check_For_Primitive_Subprogram
7620         (Is_Primitive  : out Boolean;
7621          Is_Overriding : Boolean := False)
7622       is
7623          Formal : Entity_Id;
7624          F_Typ  : Entity_Id;
7625          B_Typ  : Entity_Id;
7626
7627          function Visible_Part_Type (T : Entity_Id) return Boolean;
7628          --  Returns true if T is declared in the visible part of the current
7629          --  package scope; otherwise returns false. Assumes that T is declared
7630          --  in a package.
7631
7632          procedure Check_Private_Overriding (T : Entity_Id);
7633          --  Checks that if a primitive abstract subprogram of a visible
7634          --  abstract type is declared in a private part, then it must override
7635          --  an abstract subprogram declared in the visible part. Also checks
7636          --  that if a primitive function with a controlling result is declared
7637          --  in a private part, then it must override a function declared in
7638          --  the visible part.
7639
7640          ------------------------------
7641          -- Check_Private_Overriding --
7642          ------------------------------
7643
7644          procedure Check_Private_Overriding (T : Entity_Id) is
7645          begin
7646             if Is_Package_Or_Generic_Package (Current_Scope)
7647               and then In_Private_Part (Current_Scope)
7648               and then Visible_Part_Type (T)
7649               and then not In_Instance
7650             then
7651                if Is_Abstract_Type (T)
7652                  and then Is_Abstract_Subprogram (S)
7653                  and then (not Is_Overriding
7654                             or else not Is_Abstract_Subprogram (E))
7655                then
7656                   Error_Msg_N
7657                     ("abstract subprograms must be visible "
7658                      & "(RM 3.9.3(10))!", S);
7659
7660                elsif Ekind (S) = E_Function
7661                  and then not Is_Overriding
7662                then
7663                   if Is_Tagged_Type (T)
7664                     and then T = Base_Type (Etype (S))
7665                   then
7666                      Error_Msg_N
7667                        ("private function with tagged result must"
7668                         & " override visible-part function", S);
7669                      Error_Msg_N
7670                        ("\move subprogram to the visible part"
7671                         & " (RM 3.9.3(10))", S);
7672
7673                   --  AI05-0073: extend this test to the case of a function
7674                   --  with a controlling access result.
7675
7676                   elsif Ekind (Etype (S)) = E_Anonymous_Access_Type
7677                     and then Is_Tagged_Type (Designated_Type (Etype (S)))
7678                     and then
7679                       not Is_Class_Wide_Type (Designated_Type (Etype (S)))
7680                     and then Ada_Version >= Ada_2012
7681                   then
7682                      Error_Msg_N
7683                        ("private function with controlling access result "
7684                           & "must override visible-part function", S);
7685                      Error_Msg_N
7686                        ("\move subprogram to the visible part"
7687                           & " (RM 3.9.3(10))", S);
7688                   end if;
7689                end if;
7690             end if;
7691          end Check_Private_Overriding;
7692
7693          -----------------------
7694          -- Visible_Part_Type --
7695          -----------------------
7696
7697          function Visible_Part_Type (T : Entity_Id) return Boolean is
7698             P : constant Node_Id := Unit_Declaration_Node (Scope (T));
7699             N : Node_Id;
7700
7701          begin
7702             --  If the entity is a private type, then it must be declared in a
7703             --  visible part.
7704
7705             if Ekind (T) in Private_Kind then
7706                return True;
7707             end if;
7708
7709             --  Otherwise, we traverse the visible part looking for its
7710             --  corresponding declaration. We cannot use the declaration
7711             --  node directly because in the private part the entity of a
7712             --  private type is the one in the full view, which does not
7713             --  indicate that it is the completion of something visible.
7714
7715             N := First (Visible_Declarations (Specification (P)));
7716             while Present (N) loop
7717                if Nkind (N) = N_Full_Type_Declaration
7718                  and then Present (Defining_Identifier (N))
7719                  and then T = Defining_Identifier (N)
7720                then
7721                   return True;
7722
7723                elsif Nkind_In (N, N_Private_Type_Declaration,
7724                                   N_Private_Extension_Declaration)
7725                  and then Present (Defining_Identifier (N))
7726                  and then T = Full_View (Defining_Identifier (N))
7727                then
7728                   return True;
7729                end if;
7730
7731                Next (N);
7732             end loop;
7733
7734             return False;
7735          end Visible_Part_Type;
7736
7737       --  Start of processing for Check_For_Primitive_Subprogram
7738
7739       begin
7740          Is_Primitive := False;
7741
7742          if not Comes_From_Source (S) then
7743             null;
7744
7745          --  If subprogram is at library level, it is not primitive operation
7746
7747          elsif Current_Scope = Standard_Standard then
7748             null;
7749
7750          elsif (Is_Package_Or_Generic_Package (Current_Scope)
7751                  and then not In_Package_Body (Current_Scope))
7752            or else Is_Overriding
7753          then
7754             --  For function, check return type
7755
7756             if Ekind (S) = E_Function then
7757                if Ekind (Etype (S)) = E_Anonymous_Access_Type then
7758                   F_Typ := Designated_Type (Etype (S));
7759                else
7760                   F_Typ := Etype (S);
7761                end if;
7762
7763                B_Typ := Base_Type (F_Typ);
7764
7765                if Scope (B_Typ) = Current_Scope
7766                  and then not Is_Class_Wide_Type (B_Typ)
7767                  and then not Is_Generic_Type (B_Typ)
7768                then
7769                   Is_Primitive := True;
7770                   Set_Has_Primitive_Operations (B_Typ);
7771                   Set_Is_Primitive (S);
7772                   Check_Private_Overriding (B_Typ);
7773                end if;
7774             end if;
7775
7776             --  For all subprograms, check formals
7777
7778             Formal := First_Formal (S);
7779             while Present (Formal) loop
7780                if Ekind (Etype (Formal)) = E_Anonymous_Access_Type then
7781                   F_Typ := Designated_Type (Etype (Formal));
7782                else
7783                   F_Typ := Etype (Formal);
7784                end if;
7785
7786                B_Typ := Base_Type (F_Typ);
7787
7788                if Ekind (B_Typ) = E_Access_Subtype then
7789                   B_Typ := Base_Type (B_Typ);
7790                end if;
7791
7792                if Scope (B_Typ) = Current_Scope
7793                  and then not Is_Class_Wide_Type (B_Typ)
7794                  and then not Is_Generic_Type (B_Typ)
7795                then
7796                   Is_Primitive := True;
7797                   Set_Is_Primitive (S);
7798                   Set_Has_Primitive_Operations (B_Typ);
7799                   Check_Private_Overriding (B_Typ);
7800                end if;
7801
7802                Next_Formal (Formal);
7803             end loop;
7804          end if;
7805       end Check_For_Primitive_Subprogram;
7806
7807       -----------------------------------
7808       -- Check_Synchronized_Overriding --
7809       -----------------------------------
7810
7811       procedure Check_Synchronized_Overriding
7812         (Def_Id          : Entity_Id;
7813          Overridden_Subp : out Entity_Id)
7814       is
7815          Ifaces_List : Elist_Id;
7816          In_Scope    : Boolean;
7817          Typ         : Entity_Id;
7818
7819          function Matches_Prefixed_View_Profile
7820            (Prim_Params  : List_Id;
7821             Iface_Params : List_Id) return Boolean;
7822          --  Determine whether a subprogram's parameter profile Prim_Params
7823          --  matches that of a potentially overridden interface subprogram
7824          --  Iface_Params. Also determine if the type of first parameter of
7825          --  Iface_Params is an implemented interface.
7826
7827          -----------------------------------
7828          -- Matches_Prefixed_View_Profile --
7829          -----------------------------------
7830
7831          function Matches_Prefixed_View_Profile
7832            (Prim_Params  : List_Id;
7833             Iface_Params : List_Id) return Boolean
7834          is
7835             Iface_Id     : Entity_Id;
7836             Iface_Param  : Node_Id;
7837             Iface_Typ    : Entity_Id;
7838             Prim_Id      : Entity_Id;
7839             Prim_Param   : Node_Id;
7840             Prim_Typ     : Entity_Id;
7841
7842             function Is_Implemented
7843               (Ifaces_List : Elist_Id;
7844                Iface       : Entity_Id) return Boolean;
7845             --  Determine if Iface is implemented by the current task or
7846             --  protected type.
7847
7848             --------------------
7849             -- Is_Implemented --
7850             --------------------
7851
7852             function Is_Implemented
7853               (Ifaces_List : Elist_Id;
7854                Iface       : Entity_Id) return Boolean
7855             is
7856                Iface_Elmt : Elmt_Id;
7857
7858             begin
7859                Iface_Elmt := First_Elmt (Ifaces_List);
7860                while Present (Iface_Elmt) loop
7861                   if Node (Iface_Elmt) = Iface then
7862                      return True;
7863                   end if;
7864
7865                   Next_Elmt (Iface_Elmt);
7866                end loop;
7867
7868                return False;
7869             end Is_Implemented;
7870
7871          --  Start of processing for Matches_Prefixed_View_Profile
7872
7873          begin
7874             Iface_Param := First (Iface_Params);
7875             Iface_Typ   := Etype (Defining_Identifier (Iface_Param));
7876
7877             if Is_Access_Type (Iface_Typ) then
7878                Iface_Typ := Designated_Type (Iface_Typ);
7879             end if;
7880
7881             Prim_Param := First (Prim_Params);
7882
7883             --  The first parameter of the potentially overridden subprogram
7884             --  must be an interface implemented by Prim.
7885
7886             if not Is_Interface (Iface_Typ)
7887               or else not Is_Implemented (Ifaces_List, Iface_Typ)
7888             then
7889                return False;
7890             end if;
7891
7892             --  The checks on the object parameters are done, move onto the
7893             --  rest of the parameters.
7894
7895             if not In_Scope then
7896                Prim_Param := Next (Prim_Param);
7897             end if;
7898
7899             Iface_Param := Next (Iface_Param);
7900             while Present (Iface_Param) and then Present (Prim_Param) loop
7901                Iface_Id  := Defining_Identifier (Iface_Param);
7902                Iface_Typ := Find_Parameter_Type (Iface_Param);
7903
7904                Prim_Id  := Defining_Identifier (Prim_Param);
7905                Prim_Typ := Find_Parameter_Type (Prim_Param);
7906
7907                if Ekind (Iface_Typ) = E_Anonymous_Access_Type
7908                  and then Ekind (Prim_Typ) = E_Anonymous_Access_Type
7909                  and then Is_Concurrent_Type (Designated_Type (Prim_Typ))
7910                then
7911                   Iface_Typ := Designated_Type (Iface_Typ);
7912                   Prim_Typ := Designated_Type (Prim_Typ);
7913                end if;
7914
7915                --  Case of multiple interface types inside a parameter profile
7916
7917                --     (Obj_Param : in out Iface; ...; Param : Iface)
7918
7919                --  If the interface type is implemented, then the matching type
7920                --  in the primitive should be the implementing record type.
7921
7922                if Ekind (Iface_Typ) = E_Record_Type
7923                  and then Is_Interface (Iface_Typ)
7924                  and then Is_Implemented (Ifaces_List, Iface_Typ)
7925                then
7926                   if Prim_Typ /= Typ then
7927                      return False;
7928                   end if;
7929
7930                --  The two parameters must be both mode and subtype conformant
7931
7932                elsif Ekind (Iface_Id) /= Ekind (Prim_Id)
7933                  or else not
7934                    Conforming_Types (Iface_Typ, Prim_Typ, Subtype_Conformant)
7935                then
7936                   return False;
7937                end if;
7938
7939                Next (Iface_Param);
7940                Next (Prim_Param);
7941             end loop;
7942
7943             --  One of the two lists contains more parameters than the other
7944
7945             if Present (Iface_Param) or else Present (Prim_Param) then
7946                return False;
7947             end if;
7948
7949             return True;
7950          end Matches_Prefixed_View_Profile;
7951
7952       --  Start of processing for Check_Synchronized_Overriding
7953
7954       begin
7955          Overridden_Subp := Empty;
7956
7957          --  Def_Id must be an entry or a subprogram. We should skip predefined
7958          --  primitives internally generated by the frontend; however at this
7959          --  stage predefined primitives are still not fully decorated. As a
7960          --  minor optimization we skip here internally generated subprograms.
7961
7962          if (Ekind (Def_Id) /= E_Entry
7963               and then Ekind (Def_Id) /= E_Function
7964               and then Ekind (Def_Id) /= E_Procedure)
7965            or else not Comes_From_Source (Def_Id)
7966          then
7967             return;
7968          end if;
7969
7970          --  Search for the concurrent declaration since it contains the list
7971          --  of all implemented interfaces. In this case, the subprogram is
7972          --  declared within the scope of a protected or a task type.
7973
7974          if Present (Scope (Def_Id))
7975            and then Is_Concurrent_Type (Scope (Def_Id))
7976            and then not Is_Generic_Actual_Type (Scope (Def_Id))
7977          then
7978             Typ := Scope (Def_Id);
7979             In_Scope := True;
7980
7981          --  The enclosing scope is not a synchronized type and the subprogram
7982          --  has no formals.
7983
7984          elsif No (First_Formal (Def_Id)) then
7985             return;
7986
7987          --  The subprogram has formals and hence it may be a primitive of a
7988          --  concurrent type.
7989
7990          else
7991             Typ := Etype (First_Formal (Def_Id));
7992
7993             if Is_Access_Type (Typ) then
7994                Typ := Directly_Designated_Type (Typ);
7995             end if;
7996
7997             if Is_Concurrent_Type (Typ)
7998               and then not Is_Generic_Actual_Type (Typ)
7999             then
8000                In_Scope := False;
8001
8002             --  This case occurs when the concurrent type is declared within
8003             --  a generic unit. As a result the corresponding record has been
8004             --  built and used as the type of the first formal, we just have
8005             --  to retrieve the corresponding concurrent type.
8006
8007             elsif Is_Concurrent_Record_Type (Typ)
8008               and then not Is_Class_Wide_Type (Typ)
8009               and then Present (Corresponding_Concurrent_Type (Typ))
8010             then
8011                Typ := Corresponding_Concurrent_Type (Typ);
8012                In_Scope := False;
8013
8014             else
8015                return;
8016             end if;
8017          end if;
8018
8019          --  There is no overriding to check if is an inherited operation in a
8020          --  type derivation on for a generic actual.
8021
8022          Collect_Interfaces (Typ, Ifaces_List);
8023
8024          if Is_Empty_Elmt_List (Ifaces_List) then
8025             return;
8026          end if;
8027
8028          --  Determine whether entry or subprogram Def_Id overrides a primitive
8029          --  operation that belongs to one of the interfaces in Ifaces_List.
8030
8031          declare
8032             Candidate : Entity_Id := Empty;
8033             Hom       : Entity_Id := Empty;
8034             Iface_Typ : Entity_Id;
8035             Subp      : Entity_Id := Empty;
8036
8037          begin
8038             --  Traverse the homonym chain, looking for a potentially
8039             --  overridden subprogram that belongs to an implemented
8040             --  interface.
8041
8042             Hom := Current_Entity_In_Scope (Def_Id);
8043             while Present (Hom) loop
8044                Subp := Hom;
8045
8046                if Subp = Def_Id
8047                  or else not Is_Overloadable (Subp)
8048                  or else not Is_Primitive (Subp)
8049                  or else not Is_Dispatching_Operation (Subp)
8050                  or else not Present (Find_Dispatching_Type (Subp))
8051                  or else not Is_Interface (Find_Dispatching_Type (Subp))
8052                then
8053                   null;
8054
8055                --  Entries and procedures can override abstract or null
8056                --  interface procedures.
8057
8058                elsif (Ekind (Def_Id) = E_Procedure
8059                         or else Ekind (Def_Id) = E_Entry)
8060                  and then Ekind (Subp) = E_Procedure
8061                  and then Matches_Prefixed_View_Profile
8062                             (Parameter_Specifications (Parent (Def_Id)),
8063                              Parameter_Specifications (Parent (Subp)))
8064                then
8065                   Candidate := Subp;
8066
8067                   --  For an overridden subprogram Subp, check whether the mode
8068                   --  of its first parameter is correct depending on the kind
8069                   --  of synchronized type.
8070
8071                   declare
8072                      Formal : constant Node_Id := First_Formal (Candidate);
8073
8074                   begin
8075                      --  In order for an entry or a protected procedure to
8076                      --  override, the first parameter of the overridden
8077                      --  routine must be of mode "out", "in out" or
8078                      --  access-to-variable.
8079
8080                      if (Ekind (Candidate) = E_Entry
8081                          or else Ekind (Candidate) = E_Procedure)
8082                        and then Is_Protected_Type (Typ)
8083                        and then Ekind (Formal) /= E_In_Out_Parameter
8084                        and then Ekind (Formal) /= E_Out_Parameter
8085                        and then Nkind (Parameter_Type (Parent (Formal)))
8086                                   /= N_Access_Definition
8087                      then
8088                         null;
8089
8090                      --  All other cases are OK since a task entry or routine
8091                      --  does not have a restriction on the mode of the first
8092                      --  parameter of the overridden interface routine.
8093
8094                      else
8095                         Overridden_Subp := Candidate;
8096                         return;
8097                      end if;
8098                   end;
8099
8100                --  Functions can override abstract interface functions
8101
8102                elsif Ekind (Def_Id) = E_Function
8103                  and then Ekind (Subp) = E_Function
8104                  and then Matches_Prefixed_View_Profile
8105                             (Parameter_Specifications (Parent (Def_Id)),
8106                              Parameter_Specifications (Parent (Subp)))
8107                  and then Etype (Result_Definition (Parent (Def_Id))) =
8108                           Etype (Result_Definition (Parent (Subp)))
8109                then
8110                   Overridden_Subp := Subp;
8111                   return;
8112                end if;
8113
8114                Hom := Homonym (Hom);
8115             end loop;
8116
8117             --  After examining all candidates for overriding, we are left with
8118             --  the best match which is a mode incompatible interface routine.
8119             --  Do not emit an error if the Expander is active since this error
8120             --  will be detected later on after all concurrent types are
8121             --  expanded and all wrappers are built. This check is meant for
8122             --  spec-only compilations.
8123
8124             if Present (Candidate) and then not Expander_Active then
8125                Iface_Typ :=
8126                  Find_Parameter_Type (Parent (First_Formal (Candidate)));
8127
8128                --  Def_Id is primitive of a protected type, declared inside the
8129                --  type, and the candidate is primitive of a limited or
8130                --  synchronized interface.
8131
8132                if In_Scope
8133                  and then Is_Protected_Type (Typ)
8134                  and then
8135                    (Is_Limited_Interface (Iface_Typ)
8136                      or else Is_Protected_Interface (Iface_Typ)
8137                      or else Is_Synchronized_Interface (Iface_Typ)
8138                      or else Is_Task_Interface (Iface_Typ))
8139                then
8140                   Error_Msg_PT (Parent (Typ), Candidate);
8141                end if;
8142             end if;
8143
8144             Overridden_Subp := Candidate;
8145             return;
8146          end;
8147       end Check_Synchronized_Overriding;
8148
8149       ----------------------------
8150       -- Is_Private_Declaration --
8151       ----------------------------
8152
8153       function Is_Private_Declaration (E : Entity_Id) return Boolean is
8154          Priv_Decls : List_Id;
8155          Decl       : constant Node_Id := Unit_Declaration_Node (E);
8156
8157       begin
8158          if Is_Package_Or_Generic_Package (Current_Scope)
8159            and then In_Private_Part (Current_Scope)
8160          then
8161             Priv_Decls :=
8162               Private_Declarations (
8163                 Specification (Unit_Declaration_Node (Current_Scope)));
8164
8165             return In_Package_Body (Current_Scope)
8166               or else
8167                 (Is_List_Member (Decl)
8168                    and then List_Containing (Decl) = Priv_Decls)
8169               or else (Nkind (Parent (Decl)) = N_Package_Specification
8170                          and then not
8171                            Is_Compilation_Unit
8172                              (Defining_Entity (Parent (Decl)))
8173                          and then List_Containing (Parent (Parent (Decl)))
8174                                     = Priv_Decls);
8175          else
8176             return False;
8177          end if;
8178       end Is_Private_Declaration;
8179
8180       --------------------------
8181       -- Is_Overriding_Alias --
8182       --------------------------
8183
8184       function Is_Overriding_Alias
8185         (Old_E : Entity_Id;
8186          New_E : Entity_Id) return Boolean
8187       is
8188          AO : constant Entity_Id := Alias (Old_E);
8189          AN : constant Entity_Id := Alias (New_E);
8190
8191       begin
8192          return Scope (AO) /= Scope (AN)
8193            or else No (DTC_Entity (AO))
8194            or else No (DTC_Entity (AN))
8195            or else DT_Position (AO) = DT_Position (AN);
8196       end Is_Overriding_Alias;
8197
8198    --  Start of processing for New_Overloaded_Entity
8199
8200    begin
8201       --  We need to look for an entity that S may override. This must be a
8202       --  homonym in the current scope, so we look for the first homonym of
8203       --  S in the current scope as the starting point for the search.
8204
8205       E := Current_Entity_In_Scope (S);
8206
8207       --  Ada 2005 (AI-251): Derivation of abstract interface primitives.
8208       --  They are directly added to the list of primitive operations of
8209       --  Derived_Type, unless this is a rederivation in the private part
8210       --  of an operation that was already derived in the visible part of
8211       --  the current package.
8212
8213       if Ada_Version >= Ada_2005
8214         and then Present (Derived_Type)
8215         and then Present (Alias (S))
8216         and then Is_Dispatching_Operation (Alias (S))
8217         and then Present (Find_Dispatching_Type (Alias (S)))
8218         and then Is_Interface (Find_Dispatching_Type (Alias (S)))
8219       then
8220          --  For private types, when the full-view is processed we propagate to
8221          --  the full view the non-overridden entities whose attribute "alias"
8222          --  references an interface primitive. These entities were added by
8223          --  Derive_Subprograms to ensure that interface primitives are
8224          --  covered.
8225
8226          --  Inside_Freeze_Actions is non zero when S corresponds with an
8227          --  internal entity that links an interface primitive with its
8228          --  covering primitive through attribute Interface_Alias (see
8229          --  Add_Internal_Interface_Entities).
8230
8231          if Inside_Freezing_Actions = 0
8232            and then Is_Package_Or_Generic_Package (Current_Scope)
8233            and then In_Private_Part (Current_Scope)
8234            and then Nkind (Parent (E)) = N_Private_Extension_Declaration
8235            and then Nkind (Parent (S)) = N_Full_Type_Declaration
8236            and then Full_View (Defining_Identifier (Parent (E)))
8237                       = Defining_Identifier (Parent (S))
8238            and then Alias (E) = Alias (S)
8239          then
8240             Check_Operation_From_Private_View (S, E);
8241             Set_Is_Dispatching_Operation (S);
8242
8243          --  Common case
8244
8245          else
8246             Enter_Overloaded_Entity (S);
8247             Check_Dispatching_Operation (S, Empty);
8248             Check_For_Primitive_Subprogram (Is_Primitive_Subp);
8249          end if;
8250
8251          return;
8252       end if;
8253
8254       --  If there is no homonym then this is definitely not overriding
8255
8256       if No (E) then
8257          Enter_Overloaded_Entity (S);
8258          Check_Dispatching_Operation (S, Empty);
8259          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
8260
8261          --  If subprogram has an explicit declaration, check whether it
8262          --  has an overriding indicator.
8263
8264          if Comes_From_Source (S) then
8265             Check_Synchronized_Overriding (S, Overridden_Subp);
8266
8267             --  (Ada 2012: AI05-0125-1): If S is a dispatching operation then
8268             --  it may have overridden some hidden inherited primitive. Update
8269             --  Overridden_Subp to avoid spurious errors when checking the
8270             --  overriding indicator.
8271
8272             if Ada_Version >= Ada_2012
8273               and then No (Overridden_Subp)
8274               and then Is_Dispatching_Operation (S)
8275               and then Present (Overridden_Operation (S))
8276             then
8277                Overridden_Subp := Overridden_Operation (S);
8278             end if;
8279
8280             Check_Overriding_Indicator
8281               (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
8282          end if;
8283
8284       --  If there is a homonym that is not overloadable, then we have an
8285       --  error, except for the special cases checked explicitly below.
8286
8287       elsif not Is_Overloadable (E) then
8288
8289          --  Check for spurious conflict produced by a subprogram that has the
8290          --  same name as that of the enclosing generic package. The conflict
8291          --  occurs within an instance, between the subprogram and the renaming
8292          --  declaration for the package. After the subprogram, the package
8293          --  renaming declaration becomes hidden.
8294
8295          if Ekind (E) = E_Package
8296            and then Present (Renamed_Object (E))
8297            and then Renamed_Object (E) = Current_Scope
8298            and then Nkind (Parent (Renamed_Object (E))) =
8299                                                      N_Package_Specification
8300            and then Present (Generic_Parent (Parent (Renamed_Object (E))))
8301          then
8302             Set_Is_Hidden (E);
8303             Set_Is_Immediately_Visible (E, False);
8304             Enter_Overloaded_Entity (S);
8305             Set_Homonym (S, Homonym (E));
8306             Check_Dispatching_Operation (S, Empty);
8307             Check_Overriding_Indicator (S, Empty, Is_Primitive => False);
8308
8309          --  If the subprogram is implicit it is hidden by the previous
8310          --  declaration. However if it is dispatching, it must appear in the
8311          --  dispatch table anyway, because it can be dispatched to even if it
8312          --  cannot be called directly.
8313
8314          elsif Present (Alias (S)) and then not Comes_From_Source (S) then
8315             Set_Scope (S, Current_Scope);
8316
8317             if Is_Dispatching_Operation (Alias (S)) then
8318                Check_Dispatching_Operation (S, Empty);
8319             end if;
8320
8321             return;
8322
8323          else
8324             Error_Msg_Sloc := Sloc (E);
8325
8326             --  Generate message, with useful additional warning if in generic
8327
8328             if Is_Generic_Unit (E) then
8329                Error_Msg_N ("previous generic unit cannot be overloaded", S);
8330                Error_Msg_N ("\& conflicts with declaration#", S);
8331             else
8332                Error_Msg_N ("& conflicts with declaration#", S);
8333             end if;
8334
8335             return;
8336          end if;
8337
8338       --  E exists and is overloadable
8339
8340       else
8341          Check_Synchronized_Overriding (S, Overridden_Subp);
8342
8343          --  Loop through E and its homonyms to determine if any of them is
8344          --  the candidate for overriding by S.
8345
8346          while Present (E) loop
8347
8348             --  Definitely not interesting if not in the current scope
8349
8350             if Scope (E) /= Current_Scope then
8351                null;
8352
8353             --  Ada 2012 (AI05-0165): For internally generated bodies of
8354             --  null procedures locate the internally generated spec. We
8355             --  enforce mode conformance since a tagged type may inherit
8356             --  from interfaces several null primitives which differ only
8357             --  in the mode of the formals.
8358
8359             elsif not Comes_From_Source (S)
8360               and then Is_Null_Procedure (S)
8361               and then not Mode_Conformant (E, S)
8362             then
8363                null;
8364
8365             --  Check if we have type conformance
8366
8367             elsif Type_Conformant (E, S) then
8368
8369                --  If the old and new entities have the same profile and one
8370                --  is not the body of the other, then this is an error, unless
8371                --  one of them is implicitly declared.
8372
8373                --  There are some cases when both can be implicit, for example
8374                --  when both a literal and a function that overrides it are
8375                --  inherited in a derivation, or when an inherited operation
8376                --  of a tagged full type overrides the inherited operation of
8377                --  a private extension. Ada 83 had a special rule for the
8378                --  literal case. In Ada95, the later implicit operation hides
8379                --  the former, and the literal is always the former. In the
8380                --  odd case where both are derived operations declared at the
8381                --  same point, both operations should be declared, and in that
8382                --  case we bypass the following test and proceed to the next
8383                --  part. This can only occur for certain obscure cases in
8384                --  instances, when an operation on a type derived from a formal
8385                --  private type does not override a homograph inherited from
8386                --  the actual. In subsequent derivations of such a type, the
8387                --  DT positions of these operations remain distinct, if they
8388                --  have been set.
8389
8390                if Present (Alias (S))
8391                  and then (No (Alias (E))
8392                             or else Comes_From_Source (E)
8393                             or else Is_Abstract_Subprogram (S)
8394                             or else
8395                               (Is_Dispatching_Operation (E)
8396                                  and then Is_Overriding_Alias (E, S)))
8397                  and then Ekind (E) /= E_Enumeration_Literal
8398                then
8399                   --  When an derived operation is overloaded it may be due to
8400                   --  the fact that the full view of a private extension
8401                   --  re-inherits. It has to be dealt with.
8402
8403                   if Is_Package_Or_Generic_Package (Current_Scope)
8404                     and then In_Private_Part (Current_Scope)
8405                   then
8406                      Check_Operation_From_Private_View (S, E);
8407                   end if;
8408
8409                   --  In any case the implicit operation remains hidden by the
8410                   --  existing declaration, which is overriding. Indicate that
8411                   --  E overrides the operation from which S is inherited.
8412
8413                   if Present (Alias (S)) then
8414                      Set_Overridden_Operation (E, Alias (S));
8415                   else
8416                      Set_Overridden_Operation (E, S);
8417                   end if;
8418
8419                   if Comes_From_Source (E) then
8420                      Check_Overriding_Indicator (E, S, Is_Primitive => False);
8421                   end if;
8422
8423                   return;
8424
8425                --  Within an instance, the renaming declarations for actual
8426                --  subprograms may become ambiguous, but they do not hide each
8427                --  other.
8428
8429                elsif Ekind (E) /= E_Entry
8430                  and then not Comes_From_Source (E)
8431                  and then not Is_Generic_Instance (E)
8432                  and then (Present (Alias (E))
8433                             or else Is_Intrinsic_Subprogram (E))
8434                  and then (not In_Instance
8435                             or else No (Parent (E))
8436                             or else Nkind (Unit_Declaration_Node (E)) /=
8437                                       N_Subprogram_Renaming_Declaration)
8438                then
8439                   --  A subprogram child unit is not allowed to override an
8440                   --  inherited subprogram (10.1.1(20)).
8441
8442                   if Is_Child_Unit (S) then
8443                      Error_Msg_N
8444                        ("child unit overrides inherited subprogram in parent",
8445                         S);
8446                      return;
8447                   end if;
8448
8449                   if Is_Non_Overriding_Operation (E, S) then
8450                      Enter_Overloaded_Entity (S);
8451
8452                      if No (Derived_Type)
8453                        or else Is_Tagged_Type (Derived_Type)
8454                      then
8455                         Check_Dispatching_Operation (S, Empty);
8456                      end if;
8457
8458                      return;
8459                   end if;
8460
8461                   --  E is a derived operation or an internal operator which
8462                   --  is being overridden. Remove E from further visibility.
8463                   --  Furthermore, if E is a dispatching operation, it must be
8464                   --  replaced in the list of primitive operations of its type
8465                   --  (see Override_Dispatching_Operation).
8466
8467                   Overridden_Subp := E;
8468
8469                   declare
8470                      Prev : Entity_Id;
8471
8472                   begin
8473                      Prev := First_Entity (Current_Scope);
8474                      while Present (Prev)
8475                        and then Next_Entity (Prev) /= E
8476                      loop
8477                         Next_Entity (Prev);
8478                      end loop;
8479
8480                      --  It is possible for E to be in the current scope and
8481                      --  yet not in the entity chain. This can only occur in a
8482                      --  generic context where E is an implicit concatenation
8483                      --  in the formal part, because in a generic body the
8484                      --  entity chain starts with the formals.
8485
8486                      pragma Assert
8487                        (Present (Prev) or else Chars (E) = Name_Op_Concat);
8488
8489                      --  E must be removed both from the entity_list of the
8490                      --  current scope, and from the visibility chain
8491
8492                      if Debug_Flag_E then
8493                         Write_Str ("Override implicit operation ");
8494                         Write_Int (Int (E));
8495                         Write_Eol;
8496                      end if;
8497
8498                      --  If E is a predefined concatenation, it stands for four
8499                      --  different operations. As a result, a single explicit
8500                      --  declaration does not hide it. In a possible ambiguous
8501                      --  situation, Disambiguate chooses the user-defined op,
8502                      --  so it is correct to retain the previous internal one.
8503
8504                      if Chars (E) /= Name_Op_Concat
8505                        or else Ekind (E) /= E_Operator
8506                      then
8507                         --  For nondispatching derived operations that are
8508                         --  overridden by a subprogram declared in the private
8509                         --  part of a package, we retain the derived subprogram
8510                         --  but mark it as not immediately visible. If the
8511                         --  derived operation was declared in the visible part
8512                         --  then this ensures that it will still be visible
8513                         --  outside the package with the proper signature
8514                         --  (calls from outside must also be directed to this
8515                         --  version rather than the overriding one, unlike the
8516                         --  dispatching case). Calls from inside the package
8517                         --  will still resolve to the overriding subprogram
8518                         --  since the derived one is marked as not visible
8519                         --  within the package.
8520
8521                         --  If the private operation is dispatching, we achieve
8522                         --  the overriding by keeping the implicit operation
8523                         --  but setting its alias to be the overriding one. In
8524                         --  this fashion the proper body is executed in all
8525                         --  cases, but the original signature is used outside
8526                         --  of the package.
8527
8528                         --  If the overriding is not in the private part, we
8529                         --  remove the implicit operation altogether.
8530
8531                         if Is_Private_Declaration (S) then
8532                            if not Is_Dispatching_Operation (E) then
8533                               Set_Is_Immediately_Visible (E, False);
8534                            else
8535                               --  Work done in Override_Dispatching_Operation,
8536                               --  so nothing else need to be done here.
8537
8538                               null;
8539                            end if;
8540
8541                         else
8542                            --  Find predecessor of E in Homonym chain
8543
8544                            if E = Current_Entity (E) then
8545                               Prev_Vis := Empty;
8546                            else
8547                               Prev_Vis := Current_Entity (E);
8548                               while Homonym (Prev_Vis) /= E loop
8549                                  Prev_Vis := Homonym (Prev_Vis);
8550                               end loop;
8551                            end if;
8552
8553                            if Prev_Vis /= Empty then
8554
8555                               --  Skip E in the visibility chain
8556
8557                               Set_Homonym (Prev_Vis, Homonym (E));
8558
8559                            else
8560                               Set_Name_Entity_Id (Chars (E), Homonym (E));
8561                            end if;
8562
8563                            Set_Next_Entity (Prev, Next_Entity (E));
8564
8565                            if No (Next_Entity (Prev)) then
8566                               Set_Last_Entity (Current_Scope, Prev);
8567                            end if;
8568                         end if;
8569                      end if;
8570
8571                      Enter_Overloaded_Entity (S);
8572
8573                      --  For entities generated by Derive_Subprograms the
8574                      --  overridden operation is the inherited primitive
8575                      --  (which is available through the attribute alias).
8576
8577                      if not (Comes_From_Source (E))
8578                        and then Is_Dispatching_Operation (E)
8579                        and then Find_Dispatching_Type (E) =
8580                                 Find_Dispatching_Type (S)
8581                        and then Present (Alias (E))
8582                        and then Comes_From_Source (Alias (E))
8583                      then
8584                         Set_Overridden_Operation (S, Alias (E));
8585
8586                      --  Normal case of setting entity as overridden
8587
8588                      --  Note: Static_Initialization and Overridden_Operation
8589                      --  attributes use the same field in subprogram entities.
8590                      --  Static_Initialization is only defined for internal
8591                      --  initialization procedures, where Overridden_Operation
8592                      --  is irrelevant. Therefore the setting of this attribute
8593                      --  must check whether the target is an init_proc.
8594
8595                      elsif not Is_Init_Proc (S) then
8596                         Set_Overridden_Operation (S, E);
8597                      end if;
8598
8599                      Check_Overriding_Indicator (S, E, Is_Primitive => True);
8600
8601                      --  If S is a user-defined subprogram or a null procedure
8602                      --  expanded to override an inherited null procedure, or a
8603                      --  predefined dispatching primitive then indicate that E
8604                      --  overrides the operation from which S is inherited.
8605
8606                      if Comes_From_Source (S)
8607                        or else
8608                          (Present (Parent (S))
8609                            and then
8610                              Nkind (Parent (S)) = N_Procedure_Specification
8611                            and then
8612                              Null_Present (Parent (S)))
8613                        or else
8614                          (Present (Alias (E))
8615                            and then
8616                              Is_Predefined_Dispatching_Operation (Alias (E)))
8617                      then
8618                         if Present (Alias (E)) then
8619                            Set_Overridden_Operation (S, Alias (E));
8620                         end if;
8621                      end if;
8622
8623                      if Is_Dispatching_Operation (E) then
8624
8625                         --  An overriding dispatching subprogram inherits the
8626                         --  convention of the overridden subprogram (AI-117).
8627
8628                         Set_Convention (S, Convention (E));
8629                         Check_Dispatching_Operation (S, E);
8630
8631                      else
8632                         Check_Dispatching_Operation (S, Empty);
8633                      end if;
8634
8635                      Check_For_Primitive_Subprogram
8636                        (Is_Primitive_Subp, Is_Overriding => True);
8637                      goto Check_Inequality;
8638                   end;
8639
8640                --  Apparent redeclarations in instances can occur when two
8641                --  formal types get the same actual type. The subprograms in
8642                --  in the instance are legal,  even if not callable from the
8643                --  outside. Calls from within are disambiguated elsewhere.
8644                --  For dispatching operations in the visible part, the usual
8645                --  rules apply, and operations with the same profile are not
8646                --  legal (B830001).
8647
8648                elsif (In_Instance_Visible_Part
8649                        and then not Is_Dispatching_Operation (E))
8650                  or else In_Instance_Not_Visible
8651                then
8652                   null;
8653
8654                --  Here we have a real error (identical profile)
8655
8656                else
8657                   Error_Msg_Sloc := Sloc (E);
8658
8659                   --  Avoid cascaded errors if the entity appears in
8660                   --  subsequent calls.
8661
8662                   Set_Scope (S, Current_Scope);
8663
8664                   --  Generate error, with extra useful warning for the case
8665                   --  of a generic instance with no completion.
8666
8667                   if Is_Generic_Instance (S)
8668                     and then not Has_Completion (E)
8669                   then
8670                      Error_Msg_N
8671                        ("instantiation cannot provide body for&", S);
8672                      Error_Msg_N ("\& conflicts with declaration#", S);
8673                   else
8674                      Error_Msg_N ("& conflicts with declaration#", S);
8675                   end if;
8676
8677                   return;
8678                end if;
8679
8680             else
8681                --  If one subprogram has an access parameter and the other
8682                --  a parameter of an access type, calls to either might be
8683                --  ambiguous. Verify that parameters match except for the
8684                --  access parameter.
8685
8686                if May_Hide_Profile then
8687                   declare
8688                      F1 : Entity_Id;
8689                      F2 : Entity_Id;
8690
8691                   begin
8692                      F1 := First_Formal (S);
8693                      F2 := First_Formal (E);
8694                      while Present (F1) and then Present (F2) loop
8695                         if Is_Access_Type (Etype (F1)) then
8696                            if not Is_Access_Type (Etype (F2))
8697                               or else not Conforming_Types
8698                                 (Designated_Type (Etype (F1)),
8699                                  Designated_Type (Etype (F2)),
8700                                  Type_Conformant)
8701                            then
8702                               May_Hide_Profile := False;
8703                            end if;
8704
8705                         elsif
8706                           not Conforming_Types
8707                             (Etype (F1), Etype (F2), Type_Conformant)
8708                         then
8709                            May_Hide_Profile := False;
8710                         end if;
8711
8712                         Next_Formal (F1);
8713                         Next_Formal (F2);
8714                      end loop;
8715
8716                      if May_Hide_Profile
8717                        and then No (F1)
8718                        and then No (F2)
8719                      then
8720                         Error_Msg_NE ("calls to& may be ambiguous?", S, S);
8721                      end if;
8722                   end;
8723                end if;
8724             end if;
8725
8726             E := Homonym (E);
8727          end loop;
8728
8729          --  On exit, we know that S is a new entity
8730
8731          Enter_Overloaded_Entity (S);
8732          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
8733          Check_Overriding_Indicator
8734            (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
8735
8736          --  Overloading is not allowed in SPARK, except for operators
8737
8738          if Nkind (S) /= N_Defining_Operator_Symbol then
8739             Error_Msg_Sloc := Sloc (Homonym (S));
8740             Check_SPARK_Restriction
8741               ("overloading not allowed with entity#", S);
8742          end if;
8743
8744          --  If S is a derived operation for an untagged type then by
8745          --  definition it's not a dispatching operation (even if the parent
8746          --  operation was dispatching), so Check_Dispatching_Operation is not
8747          --  called in that case.
8748
8749          if No (Derived_Type)
8750            or else Is_Tagged_Type (Derived_Type)
8751          then
8752             Check_Dispatching_Operation (S, Empty);
8753          end if;
8754       end if;
8755
8756       --  If this is a user-defined equality operator that is not a derived
8757       --  subprogram, create the corresponding inequality. If the operation is
8758       --  dispatching, the expansion is done elsewhere, and we do not create
8759       --  an explicit inequality operation.
8760
8761       <<Check_Inequality>>
8762          if Chars (S) = Name_Op_Eq
8763            and then Etype (S) = Standard_Boolean
8764            and then Present (Parent (S))
8765            and then not Is_Dispatching_Operation (S)
8766          then
8767             Make_Inequality_Operator (S);
8768
8769             if Ada_Version >= Ada_2012 then
8770                Check_Untagged_Equality (S);
8771             end if;
8772          end if;
8773    end New_Overloaded_Entity;
8774
8775    ---------------------
8776    -- Process_Formals --
8777    ---------------------
8778
8779    procedure Process_Formals
8780      (T           : List_Id;
8781       Related_Nod : Node_Id)
8782    is
8783       Param_Spec  : Node_Id;
8784       Formal      : Entity_Id;
8785       Formal_Type : Entity_Id;
8786       Default     : Node_Id;
8787       Ptype       : Entity_Id;
8788
8789       Num_Out_Params  : Nat       := 0;
8790       First_Out_Param : Entity_Id := Empty;
8791       --  Used for setting Is_Only_Out_Parameter
8792
8793       function Designates_From_With_Type (Typ : Entity_Id) return Boolean;
8794       --  Determine whether an access type designates a type coming from a
8795       --  limited view.
8796
8797       function Is_Class_Wide_Default (D : Node_Id) return Boolean;
8798       --  Check whether the default has a class-wide type. After analysis the
8799       --  default has the type of the formal, so we must also check explicitly
8800       --  for an access attribute.
8801
8802       -------------------------------
8803       -- Designates_From_With_Type --
8804       -------------------------------
8805
8806       function Designates_From_With_Type (Typ : Entity_Id) return Boolean is
8807          Desig : Entity_Id := Typ;
8808
8809       begin
8810          if Is_Access_Type (Desig) then
8811             Desig := Directly_Designated_Type (Desig);
8812          end if;
8813
8814          if Is_Class_Wide_Type (Desig) then
8815             Desig := Root_Type (Desig);
8816          end if;
8817
8818          return
8819            Ekind (Desig) = E_Incomplete_Type
8820              and then From_With_Type (Desig);
8821       end Designates_From_With_Type;
8822
8823       ---------------------------
8824       -- Is_Class_Wide_Default --
8825       ---------------------------
8826
8827       function Is_Class_Wide_Default (D : Node_Id) return Boolean is
8828       begin
8829          return Is_Class_Wide_Type (Designated_Type (Etype (D)))
8830            or else (Nkind (D) =  N_Attribute_Reference
8831                      and then Attribute_Name (D) = Name_Access
8832                      and then Is_Class_Wide_Type (Etype (Prefix (D))));
8833       end Is_Class_Wide_Default;
8834
8835    --  Start of processing for Process_Formals
8836
8837    begin
8838       --  In order to prevent premature use of the formals in the same formal
8839       --  part, the Ekind is left undefined until all default expressions are
8840       --  analyzed. The Ekind is established in a separate loop at the end.
8841
8842       Param_Spec := First (T);
8843       while Present (Param_Spec) loop
8844          Formal := Defining_Identifier (Param_Spec);
8845          Set_Never_Set_In_Source (Formal, True);
8846          Enter_Name (Formal);
8847
8848          --  Case of ordinary parameters
8849
8850          if Nkind (Parameter_Type (Param_Spec)) /= N_Access_Definition then
8851             Find_Type (Parameter_Type (Param_Spec));
8852             Ptype := Parameter_Type (Param_Spec);
8853
8854             if Ptype = Error then
8855                goto Continue;
8856             end if;
8857
8858             Formal_Type := Entity (Ptype);
8859
8860             if Is_Incomplete_Type (Formal_Type)
8861               or else
8862                (Is_Class_Wide_Type (Formal_Type)
8863                   and then Is_Incomplete_Type (Root_Type (Formal_Type)))
8864             then
8865                --  Ada 2005 (AI-326): Tagged incomplete types allowed in
8866                --  primitive operations, as long as their completion is
8867                --  in the same declarative part. If in the private part
8868                --  this means that the type cannot be a Taft-amendment type.
8869                --  Check is done on package exit. For access to subprograms,
8870                --  the use is legal for Taft-amendment types.
8871
8872                if Is_Tagged_Type (Formal_Type) then
8873                   if Ekind (Scope (Current_Scope)) = E_Package
8874                     and then not From_With_Type (Formal_Type)
8875                     and then not Is_Class_Wide_Type (Formal_Type)
8876                   then
8877                      if not Nkind_In
8878                        (Parent (T), N_Access_Function_Definition,
8879                                     N_Access_Procedure_Definition)
8880                      then
8881                         Append_Elmt
8882                           (Current_Scope,
8883                              Private_Dependents (Base_Type (Formal_Type)));
8884
8885                         --  Freezing is delayed to ensure that Register_Prim
8886                         --  will get called for this operation, which is needed
8887                         --  in cases where static dispatch tables aren't built.
8888                         --  (Note that the same is done for controlling access
8889                         --  parameter cases in function Access_Definition.)
8890
8891                         Set_Has_Delayed_Freeze (Current_Scope);
8892                      end if;
8893                   end if;
8894
8895                --  Special handling of Value_Type for CIL case
8896
8897                elsif Is_Value_Type (Formal_Type) then
8898                   null;
8899
8900                elsif not Nkind_In (Parent (T), N_Access_Function_Definition,
8901                                                N_Access_Procedure_Definition)
8902                then
8903
8904                   --  AI05-0151: Tagged incomplete types are allowed in all
8905                   --  formal parts. Untagged incomplete types are not allowed
8906                   --  in bodies.
8907
8908                   if Ada_Version >= Ada_2012 then
8909                      if Is_Tagged_Type (Formal_Type) then
8910                         null;
8911
8912                      elsif Nkind_In (Parent (Parent (T)), N_Accept_Statement,
8913                                                           N_Entry_Body,
8914                                                           N_Subprogram_Body)
8915                      then
8916                         Error_Msg_NE
8917                           ("invalid use of untagged incomplete type&",
8918                            Ptype, Formal_Type);
8919                      end if;
8920
8921                   else
8922                      Error_Msg_NE
8923                        ("invalid use of incomplete type&",
8924                         Param_Spec, Formal_Type);
8925
8926                      --  Further checks on the legality of incomplete types
8927                      --  in formal parts are delayed until the freeze point
8928                      --  of the enclosing subprogram or access to subprogram.
8929                   end if;
8930                end if;
8931
8932             elsif Ekind (Formal_Type) = E_Void then
8933                Error_Msg_NE
8934                  ("premature use of&",
8935                   Parameter_Type (Param_Spec), Formal_Type);
8936             end if;
8937
8938             --  Ada 2005 (AI-231): Create and decorate an internal subtype
8939             --  declaration corresponding to the null-excluding type of the
8940             --  formal in the enclosing scope. Finally, replace the parameter
8941             --  type of the formal with the internal subtype.
8942
8943             if Ada_Version >= Ada_2005
8944               and then Null_Exclusion_Present (Param_Spec)
8945             then
8946                if not Is_Access_Type (Formal_Type) then
8947                   Error_Msg_N
8948                     ("`NOT NULL` allowed only for an access type", Param_Spec);
8949
8950                else
8951                   if Can_Never_Be_Null (Formal_Type)
8952                     and then Comes_From_Source (Related_Nod)
8953                   then
8954                      Error_Msg_NE
8955                        ("`NOT NULL` not allowed (& already excludes null)",
8956                         Param_Spec, Formal_Type);
8957                   end if;
8958
8959                   Formal_Type :=
8960                     Create_Null_Excluding_Itype
8961                       (T           => Formal_Type,
8962                        Related_Nod => Related_Nod,
8963                        Scope_Id    => Scope (Current_Scope));
8964
8965                   --  If the designated type of the itype is an itype we
8966                   --  decorate it with the Has_Delayed_Freeze attribute to
8967                   --  avoid problems with the backend.
8968
8969                   --  Example:
8970                   --     type T is access procedure;
8971                   --     procedure Op (O : not null T);
8972
8973                   if Is_Itype (Directly_Designated_Type (Formal_Type)) then
8974                      Set_Has_Delayed_Freeze (Formal_Type);
8975                   end if;
8976                end if;
8977             end if;
8978
8979          --  An access formal type
8980
8981          else
8982             Formal_Type :=
8983               Access_Definition (Related_Nod, Parameter_Type (Param_Spec));
8984
8985             --  No need to continue if we already notified errors
8986
8987             if not Present (Formal_Type) then
8988                return;
8989             end if;
8990
8991             --  Ada 2005 (AI-254)
8992
8993             declare
8994                AD : constant Node_Id :=
8995                       Access_To_Subprogram_Definition
8996                         (Parameter_Type (Param_Spec));
8997             begin
8998                if Present (AD) and then Protected_Present (AD) then
8999                   Formal_Type :=
9000                     Replace_Anonymous_Access_To_Protected_Subprogram
9001                       (Param_Spec);
9002                end if;
9003             end;
9004          end if;
9005
9006          Set_Etype (Formal, Formal_Type);
9007
9008          Default := Expression (Param_Spec);
9009
9010          if Present (Default) then
9011             Check_SPARK_Restriction
9012               ("default expression is not allowed", Default);
9013
9014             if Out_Present (Param_Spec) then
9015                Error_Msg_N
9016                  ("default initialization only allowed for IN parameters",
9017                   Param_Spec);
9018             end if;
9019
9020             --  Do the special preanalysis of the expression (see section on
9021             --  "Handling of Default Expressions" in the spec of package Sem).
9022
9023             Preanalyze_Spec_Expression (Default, Formal_Type);
9024
9025             --  An access to constant cannot be the default for
9026             --  an access parameter that is an access to variable.
9027
9028             if Ekind (Formal_Type) = E_Anonymous_Access_Type
9029               and then not Is_Access_Constant (Formal_Type)
9030               and then Is_Access_Type (Etype (Default))
9031               and then Is_Access_Constant (Etype (Default))
9032             then
9033                Error_Msg_N
9034                  ("formal that is access to variable cannot be initialized " &
9035                     "with an access-to-constant expression", Default);
9036             end if;
9037
9038             --  Check that the designated type of an access parameter's default
9039             --  is not a class-wide type unless the parameter's designated type
9040             --  is also class-wide.
9041
9042             if Ekind (Formal_Type) = E_Anonymous_Access_Type
9043               and then not Designates_From_With_Type (Formal_Type)
9044               and then Is_Class_Wide_Default (Default)
9045               and then not Is_Class_Wide_Type (Designated_Type (Formal_Type))
9046             then
9047                Error_Msg_N
9048                  ("access to class-wide expression not allowed here", Default);
9049             end if;
9050
9051             --  Check incorrect use of dynamically tagged expressions
9052
9053             if Is_Tagged_Type (Formal_Type) then
9054                Check_Dynamically_Tagged_Expression
9055                  (Expr        => Default,
9056                   Typ         => Formal_Type,
9057                   Related_Nod => Default);
9058             end if;
9059          end if;
9060
9061          --  Ada 2005 (AI-231): Static checks
9062
9063          if Ada_Version >= Ada_2005
9064            and then Is_Access_Type (Etype (Formal))
9065            and then Can_Never_Be_Null (Etype (Formal))
9066          then
9067             Null_Exclusion_Static_Checks (Param_Spec);
9068          end if;
9069
9070       <<Continue>>
9071          Next (Param_Spec);
9072       end loop;
9073
9074       --  If this is the formal part of a function specification, analyze the
9075       --  subtype mark in the context where the formals are visible but not
9076       --  yet usable, and may hide outer homographs.
9077
9078       if Nkind (Related_Nod) = N_Function_Specification then
9079          Analyze_Return_Type (Related_Nod);
9080       end if;
9081
9082       --  Now set the kind (mode) of each formal
9083
9084       Param_Spec := First (T);
9085       while Present (Param_Spec) loop
9086          Formal := Defining_Identifier (Param_Spec);
9087          Set_Formal_Mode (Formal);
9088
9089          if Ekind (Formal) = E_In_Parameter then
9090             Set_Default_Value (Formal, Expression (Param_Spec));
9091
9092             if Present (Expression (Param_Spec)) then
9093                Default :=  Expression (Param_Spec);
9094
9095                if Is_Scalar_Type (Etype (Default)) then
9096                   if Nkind
9097                        (Parameter_Type (Param_Spec)) /= N_Access_Definition
9098                   then
9099                      Formal_Type := Entity (Parameter_Type (Param_Spec));
9100
9101                   else
9102                      Formal_Type := Access_Definition
9103                        (Related_Nod, Parameter_Type (Param_Spec));
9104                   end if;
9105
9106                   Apply_Scalar_Range_Check (Default, Formal_Type);
9107                end if;
9108             end if;
9109
9110          elsif Ekind (Formal) = E_Out_Parameter then
9111             Num_Out_Params := Num_Out_Params + 1;
9112
9113             if Num_Out_Params = 1 then
9114                First_Out_Param := Formal;
9115             end if;
9116
9117          elsif Ekind (Formal) = E_In_Out_Parameter then
9118             Num_Out_Params := Num_Out_Params + 1;
9119          end if;
9120
9121          Next (Param_Spec);
9122       end loop;
9123
9124       if Present (First_Out_Param) and then Num_Out_Params = 1 then
9125          Set_Is_Only_Out_Parameter (First_Out_Param);
9126       end if;
9127    end Process_Formals;
9128
9129    ------------------
9130    -- Process_PPCs --
9131    ------------------
9132
9133    procedure Process_PPCs
9134      (N       : Node_Id;
9135       Spec_Id : Entity_Id;
9136       Body_Id : Entity_Id)
9137    is
9138       Loc   : constant Source_Ptr := Sloc (N);
9139       Prag  : Node_Id;
9140       Parms : List_Id;
9141
9142       Designator : Entity_Id;
9143       --  Subprogram designator, set from Spec_Id if present, else Body_Id
9144
9145       Precond : Node_Id := Empty;
9146       --  Set non-Empty if we prepend precondition to the declarations. This
9147       --  is used to hook up inherited preconditions (adding the condition
9148       --  expression with OR ELSE, and adding the message).
9149
9150       Inherited_Precond : Node_Id;
9151       --  Precondition inherited from parent subprogram
9152
9153       Inherited : constant Subprogram_List :=
9154                      Inherited_Subprograms (Spec_Id);
9155       --  List of subprograms inherited by this subprogram
9156
9157       Plist : List_Id := No_List;
9158       --  List of generated postconditions
9159
9160       function Grab_PPC (Pspec : Entity_Id := Empty) return Node_Id;
9161       --  Prag contains an analyzed precondition or postcondition pragma. This
9162       --  function copies the pragma, changes it to the corresponding Check
9163       --  pragma and returns the Check pragma as the result. If Pspec is non-
9164       --  empty, this is the case of inheriting a PPC, where we must change
9165       --  references to parameters of the inherited subprogram to point to the
9166       --  corresponding parameters of the current subprogram.
9167
9168       function Invariants_Or_Predicates_Present return Boolean;
9169       --  Determines if any invariants or predicates are present for any OUT
9170       --  or IN OUT parameters of the subprogram, or (for a function) if the
9171       --  return value has an invariant.
9172
9173       --------------
9174       -- Grab_PPC --
9175       --------------
9176
9177       function Grab_PPC (Pspec : Entity_Id := Empty) return Node_Id is
9178          Nam : constant Name_Id := Pragma_Name (Prag);
9179          Map : Elist_Id;
9180          CP  : Node_Id;
9181
9182       begin
9183          --  Prepare map if this is the case where we have to map entities of
9184          --  arguments in the overridden subprogram to corresponding entities
9185          --  of the current subprogram.
9186
9187          if No (Pspec) then
9188             Map := No_Elist;
9189
9190          else
9191             declare
9192                PF : Entity_Id;
9193                CF : Entity_Id;
9194
9195             begin
9196                Map := New_Elmt_List;
9197                PF := First_Formal (Pspec);
9198                CF := First_Formal (Designator);
9199                while Present (PF) loop
9200                   Append_Elmt (PF, Map);
9201                   Append_Elmt (CF, Map);
9202                   Next_Formal (PF);
9203                   Next_Formal (CF);
9204                end loop;
9205             end;
9206          end if;
9207
9208          --  Now we can copy the tree, doing any required substitutions
9209
9210          CP := New_Copy_Tree (Prag, Map => Map, New_Scope => Current_Scope);
9211
9212          --  Set Analyzed to false, since we want to reanalyze the check
9213          --  procedure. Note that it is only at the outer level that we
9214          --  do this fiddling, for the spec cases, the already preanalyzed
9215          --  parameters are not affected.
9216
9217          Set_Analyzed (CP, False);
9218
9219          --  We also make sure Comes_From_Source is False for the copy
9220
9221          Set_Comes_From_Source (CP, False);
9222
9223          --  For a postcondition pragma within a generic, preserve the pragma
9224          --  for later expansion.
9225
9226          if Nam = Name_Postcondition
9227            and then not Expander_Active
9228          then
9229             return CP;
9230          end if;
9231
9232          --  Change copy of pragma into corresponding pragma Check
9233
9234          Prepend_To (Pragma_Argument_Associations (CP),
9235            Make_Pragma_Argument_Association (Sloc (Prag),
9236              Expression => Make_Identifier (Loc, Nam)));
9237          Set_Pragma_Identifier (CP, Make_Identifier (Sloc (Prag), Name_Check));
9238
9239          --  If this is inherited case and the current message starts with
9240          --  "failed p", we change it to "failed inherited p...".
9241
9242          if Present (Pspec) then
9243             declare
9244                Msg : constant Node_Id :=
9245                        Last (Pragma_Argument_Associations (CP));
9246
9247             begin
9248                if Chars (Msg) = Name_Message then
9249                   String_To_Name_Buffer (Strval (Expression (Msg)));
9250
9251                   if Name_Buffer (1 .. 8) = "failed p" then
9252                      Insert_Str_In_Name_Buffer ("inherited ", 8);
9253                      Set_Strval
9254                        (Expression (Last (Pragma_Argument_Associations (CP))),
9255                         String_From_Name_Buffer);
9256                   end if;
9257                end if;
9258             end;
9259          end if;
9260
9261          --  Return the check pragma
9262
9263          return CP;
9264       end Grab_PPC;
9265
9266       --------------------------------------
9267       -- Invariants_Or_Predicates_Present --
9268       --------------------------------------
9269
9270       function Invariants_Or_Predicates_Present return Boolean is
9271          Formal : Entity_Id;
9272
9273       begin
9274          --  Check function return result
9275
9276          if Ekind (Designator) /= E_Procedure
9277            and then Has_Invariants (Etype (Designator))
9278          then
9279             return True;
9280          end if;
9281
9282          --  Check parameters
9283
9284          Formal := First_Formal (Designator);
9285          while Present (Formal) loop
9286             if Ekind (Formal) /= E_In_Parameter
9287               and then
9288                 (Has_Invariants (Etype (Formal))
9289                   or else Present (Predicate_Function (Etype (Formal))))
9290             then
9291                return True;
9292             end if;
9293
9294             Next_Formal (Formal);
9295          end loop;
9296
9297          return False;
9298       end Invariants_Or_Predicates_Present;
9299
9300    --  Start of processing for Process_PPCs
9301
9302    begin
9303       --  Capture designator from spec if present, else from body
9304
9305       if Present (Spec_Id) then
9306          Designator := Spec_Id;
9307       else
9308          Designator := Body_Id;
9309       end if;
9310
9311       --  Grab preconditions from spec
9312
9313       if Present (Spec_Id) then
9314
9315          --  Loop through PPC pragmas from spec. Note that preconditions from
9316          --  the body will be analyzed and converted when we scan the body
9317          --  declarations below.
9318
9319          Prag := Spec_PPC_List (Contract (Spec_Id));
9320          while Present (Prag) loop
9321             if Pragma_Name (Prag) = Name_Precondition then
9322
9323                --  For Pre (or Precondition pragma), we simply prepend the
9324                --  pragma to the list of declarations right away so that it
9325                --  will be executed at the start of the procedure. Note that
9326                --  this processing reverses the order of the list, which is
9327                --  what we want since new entries were chained to the head of
9328                --  the list. There can be more than one precondition when we
9329                --  use pragma Precondition.
9330
9331                if not Class_Present (Prag) then
9332                   Prepend (Grab_PPC, Declarations (N));
9333
9334                --  For Pre'Class there can only be one pragma, and we save
9335                --  it in Precond for now. We will add inherited Pre'Class
9336                --  stuff before inserting this pragma in the declarations.
9337                else
9338                   Precond := Grab_PPC;
9339                end if;
9340             end if;
9341
9342             Prag := Next_Pragma (Prag);
9343          end loop;
9344
9345          --  Now deal with inherited preconditions
9346
9347          for J in Inherited'Range loop
9348             Prag := Spec_PPC_List (Contract (Inherited (J)));
9349
9350             while Present (Prag) loop
9351                if Pragma_Name (Prag) = Name_Precondition
9352                  and then Class_Present (Prag)
9353                then
9354                   Inherited_Precond := Grab_PPC (Inherited (J));
9355
9356                   --  No precondition so far, so establish this as the first
9357
9358                   if No (Precond) then
9359                      Precond := Inherited_Precond;
9360
9361                   --  Here we already have a precondition, add inherited one
9362
9363                   else
9364                      --  Add new precondition to old one using OR ELSE
9365
9366                      declare
9367                         New_Expr : constant Node_Id :=
9368                                      Get_Pragma_Arg
9369                                        (Next
9370                                          (First
9371                                            (Pragma_Argument_Associations
9372                                              (Inherited_Precond))));
9373                         Old_Expr : constant Node_Id :=
9374                                      Get_Pragma_Arg
9375                                        (Next
9376                                          (First
9377                                            (Pragma_Argument_Associations
9378                                              (Precond))));
9379
9380                      begin
9381                         if Paren_Count (Old_Expr) = 0 then
9382                            Set_Paren_Count (Old_Expr, 1);
9383                         end if;
9384
9385                         if Paren_Count (New_Expr) = 0 then
9386                            Set_Paren_Count (New_Expr, 1);
9387                         end if;
9388
9389                         Rewrite (Old_Expr,
9390                           Make_Or_Else (Sloc (Old_Expr),
9391                             Left_Opnd  => Relocate_Node (Old_Expr),
9392                             Right_Opnd => New_Expr));
9393                      end;
9394
9395                      --  Add new message in the form:
9396
9397                      --     failed precondition from bla
9398                      --       also failed inherited precondition from bla
9399                      --       ...
9400
9401                      --  Skip this if exception locations are suppressed
9402
9403                      if not Exception_Locations_Suppressed then
9404                         declare
9405                            New_Msg : constant Node_Id :=
9406                                        Get_Pragma_Arg
9407                                          (Last
9408                                             (Pragma_Argument_Associations
9409                                                (Inherited_Precond)));
9410                            Old_Msg : constant Node_Id :=
9411                                        Get_Pragma_Arg
9412                                          (Last
9413                                             (Pragma_Argument_Associations
9414                                                (Precond)));
9415                         begin
9416                            Start_String (Strval (Old_Msg));
9417                            Store_String_Chars (ASCII.LF & "  also ");
9418                            Store_String_Chars (Strval (New_Msg));
9419                            Set_Strval (Old_Msg, End_String);
9420                         end;
9421                      end if;
9422                   end if;
9423                end if;
9424
9425                Prag := Next_Pragma (Prag);
9426             end loop;
9427          end loop;
9428
9429          --  If we have built a precondition for Pre'Class (including any
9430          --  Pre'Class aspects inherited from parent subprograms), then we
9431          --  insert this composite precondition at this stage.
9432
9433          if Present (Precond) then
9434             Prepend (Precond, Declarations (N));
9435          end if;
9436       end if;
9437
9438       --  Build postconditions procedure if needed and prepend the following
9439       --  declaration to the start of the declarations for the subprogram.
9440
9441       --     procedure _postconditions [(_Result : resulttype)] is
9442       --     begin
9443       --        pragma Check (Postcondition, condition [,message]);
9444       --        pragma Check (Postcondition, condition [,message]);
9445       --        ...
9446       --        Invariant_Procedure (_Result) ...
9447       --        Invariant_Procedure (Arg1)
9448       --        ...
9449       --     end;
9450
9451       --  First we deal with the postconditions in the body
9452
9453       if Is_Non_Empty_List (Declarations (N)) then
9454
9455          --  Loop through declarations
9456
9457          Prag := First (Declarations (N));
9458          while Present (Prag) loop
9459             if Nkind (Prag) = N_Pragma then
9460
9461                --  If pragma, capture if enabled postcondition, else ignore
9462
9463                if Pragma_Name (Prag) = Name_Postcondition
9464                  and then Check_Enabled (Name_Postcondition)
9465                then
9466                   if Plist = No_List then
9467                      Plist := Empty_List;
9468                   end if;
9469
9470                   Analyze (Prag);
9471
9472                   --  If expansion is disabled, as in a generic unit, save
9473                   --  pragma for later expansion.
9474
9475                   if not Expander_Active then
9476                      Prepend (Grab_PPC, Declarations (N));
9477                   else
9478                      Append (Grab_PPC, Plist);
9479                   end if;
9480                end if;
9481
9482                Next (Prag);
9483
9484             --  Not a pragma, if comes from source, then end scan
9485
9486             elsif Comes_From_Source (Prag) then
9487                exit;
9488
9489             --  Skip stuff not coming from source
9490
9491             else
9492                Next (Prag);
9493             end if;
9494          end loop;
9495       end if;
9496
9497       --  Now deal with any postconditions from the spec
9498
9499       if Present (Spec_Id) then
9500          Spec_Postconditions : declare
9501             procedure Process_Post_Conditions
9502               (Spec  : Node_Id;
9503                Class : Boolean);
9504             --  This processes the Spec_PPC_List from Spec, processing any
9505             --  postconditions from the list. If Class is True, then only
9506             --  postconditions marked with Class_Present are considered.
9507             --  The caller has checked that Spec_PPC_List is non-Empty.
9508
9509             -----------------------------
9510             -- Process_Post_Conditions --
9511             -----------------------------
9512
9513             procedure Process_Post_Conditions
9514               (Spec  : Node_Id;
9515                Class : Boolean)
9516             is
9517                Pspec : Node_Id;
9518
9519             begin
9520                if Class then
9521                   Pspec := Spec;
9522                else
9523                   Pspec := Empty;
9524                end if;
9525
9526                --  Loop through PPC pragmas from spec
9527
9528                Prag := Spec_PPC_List (Contract (Spec));
9529                loop
9530                   if Pragma_Name (Prag) = Name_Postcondition
9531                     and then (not Class or else Class_Present (Prag))
9532                   then
9533                      if Plist = No_List then
9534                         Plist := Empty_List;
9535                      end if;
9536
9537                      if not Expander_Active then
9538                         Prepend
9539                           (Grab_PPC (Pspec), Declarations (N));
9540                      else
9541                         Append (Grab_PPC (Pspec), Plist);
9542                      end if;
9543                   end if;
9544
9545                   Prag := Next_Pragma (Prag);
9546                   exit when No (Prag);
9547                end loop;
9548             end Process_Post_Conditions;
9549
9550          --  Start of processing for Spec_Postconditions
9551
9552          begin
9553             if Present (Spec_PPC_List (Contract (Spec_Id))) then
9554                Process_Post_Conditions (Spec_Id, Class => False);
9555             end if;
9556
9557             --  Process inherited postconditions
9558
9559             for J in Inherited'Range loop
9560                if Present (Spec_PPC_List (Contract (Inherited (J)))) then
9561                   Process_Post_Conditions (Inherited (J), Class => True);
9562                end if;
9563             end loop;
9564          end Spec_Postconditions;
9565       end if;
9566
9567       --  If we had any postconditions and expansion is enabled, or if the
9568       --  procedure has invariants, then build the _Postconditions procedure.
9569
9570       if (Present (Plist) or else Invariants_Or_Predicates_Present)
9571         and then Expander_Active
9572       then
9573          if No (Plist) then
9574             Plist := Empty_List;
9575          end if;
9576
9577          --  Special processing for function case
9578
9579          if Ekind (Designator) /= E_Procedure then
9580             declare
9581                Rent : constant Entity_Id :=
9582                         Make_Defining_Identifier (Loc,
9583                           Chars => Name_uResult);
9584                Ftyp : constant Entity_Id := Etype (Designator);
9585
9586             begin
9587                Set_Etype (Rent, Ftyp);
9588
9589                --  Add argument for return
9590
9591                Parms :=
9592                  New_List (
9593                    Make_Parameter_Specification (Loc,
9594                      Parameter_Type      => New_Occurrence_Of (Ftyp, Loc),
9595                      Defining_Identifier => Rent));
9596
9597                --  Add invariant call if returning type with invariants
9598
9599                if Has_Invariants (Etype (Rent))
9600                  and then Present (Invariant_Procedure (Etype (Rent)))
9601                then
9602                   Append_To (Plist,
9603                     Make_Invariant_Call (New_Occurrence_Of (Rent, Loc)));
9604                end if;
9605             end;
9606
9607          --  Procedure rather than a function
9608
9609          else
9610             Parms := No_List;
9611          end if;
9612
9613          --  Add invariant calls and predicate calls for parameters. Note that
9614          --  this is done for functions as well, since in Ada 2012 they can
9615          --  have IN OUT args.
9616
9617          declare
9618             Formal : Entity_Id;
9619             Ftype  : Entity_Id;
9620
9621          begin
9622             Formal := First_Formal (Designator);
9623             while Present (Formal) loop
9624                if Ekind (Formal) /= E_In_Parameter then
9625                   Ftype := Etype (Formal);
9626
9627                   if Has_Invariants (Ftype)
9628                     and then Present (Invariant_Procedure (Ftype))
9629                   then
9630                      Append_To (Plist,
9631                        Make_Invariant_Call
9632                          (New_Occurrence_Of (Formal, Loc)));
9633                   end if;
9634
9635                   if Present (Predicate_Function (Ftype)) then
9636                      Append_To (Plist,
9637                        Make_Predicate_Check
9638                          (Ftype, New_Occurrence_Of (Formal, Loc)));
9639                   end if;
9640                end if;
9641
9642                Next_Formal (Formal);
9643             end loop;
9644          end;
9645
9646          --  Build and insert postcondition procedure
9647
9648          declare
9649             Post_Proc : constant Entity_Id :=
9650                           Make_Defining_Identifier (Loc,
9651                             Chars => Name_uPostconditions);
9652             --  The entity for the _Postconditions procedure
9653
9654          begin
9655             Prepend_To (Declarations (N),
9656               Make_Subprogram_Body (Loc,
9657                 Specification =>
9658                   Make_Procedure_Specification (Loc,
9659                     Defining_Unit_Name => Post_Proc,
9660                     Parameter_Specifications => Parms),
9661
9662                 Declarations => Empty_List,
9663
9664                 Handled_Statement_Sequence =>
9665                   Make_Handled_Sequence_Of_Statements (Loc,
9666                     Statements => Plist)));
9667
9668             Set_Ekind (Post_Proc, E_Procedure);
9669
9670             --  If this is a procedure, set the Postcondition_Proc attribute on
9671             --  the proper defining entity for the subprogram.
9672
9673             if Ekind (Designator) = E_Procedure then
9674                Set_Postcondition_Proc (Designator, Post_Proc);
9675             end if;
9676          end;
9677
9678          Set_Has_Postconditions (Designator);
9679       end if;
9680    end Process_PPCs;
9681
9682    ----------------------------
9683    -- Reference_Body_Formals --
9684    ----------------------------
9685
9686    procedure Reference_Body_Formals (Spec : Entity_Id; Bod : Entity_Id) is
9687       Fs : Entity_Id;
9688       Fb : Entity_Id;
9689
9690    begin
9691       if Error_Posted (Spec) then
9692          return;
9693       end if;
9694
9695       --  Iterate over both lists. They may be of different lengths if the two
9696       --  specs are not conformant.
9697
9698       Fs := First_Formal (Spec);
9699       Fb := First_Formal (Bod);
9700       while Present (Fs) and then Present (Fb) loop
9701          Generate_Reference (Fs, Fb, 'b');
9702
9703          if Style_Check then
9704             Style.Check_Identifier (Fb, Fs);
9705          end if;
9706
9707          Set_Spec_Entity (Fb, Fs);
9708          Set_Referenced (Fs, False);
9709          Next_Formal (Fs);
9710          Next_Formal (Fb);
9711       end loop;
9712    end Reference_Body_Formals;
9713
9714    -------------------------
9715    -- Set_Actual_Subtypes --
9716    -------------------------
9717
9718    procedure Set_Actual_Subtypes (N : Node_Id; Subp : Entity_Id) is
9719       Decl           : Node_Id;
9720       Formal         : Entity_Id;
9721       T              : Entity_Id;
9722       First_Stmt     : Node_Id := Empty;
9723       AS_Needed      : Boolean;
9724
9725    begin
9726       --  If this is an empty initialization procedure, no need to create
9727       --  actual subtypes (small optimization).
9728
9729       if Ekind (Subp) = E_Procedure
9730         and then Is_Null_Init_Proc (Subp)
9731       then
9732          return;
9733       end if;
9734
9735       Formal := First_Formal (Subp);
9736       while Present (Formal) loop
9737          T := Etype (Formal);
9738
9739          --  We never need an actual subtype for a constrained formal
9740
9741          if Is_Constrained (T) then
9742             AS_Needed := False;
9743
9744          --  If we have unknown discriminants, then we do not need an actual
9745          --  subtype, or more accurately we cannot figure it out! Note that
9746          --  all class-wide types have unknown discriminants.
9747
9748          elsif Has_Unknown_Discriminants (T) then
9749             AS_Needed := False;
9750
9751          --  At this stage we have an unconstrained type that may need an
9752          --  actual subtype. For sure the actual subtype is needed if we have
9753          --  an unconstrained array type.
9754
9755          elsif Is_Array_Type (T) then
9756             AS_Needed := True;
9757
9758          --  The only other case needing an actual subtype is an unconstrained
9759          --  record type which is an IN parameter (we cannot generate actual
9760          --  subtypes for the OUT or IN OUT case, since an assignment can
9761          --  change the discriminant values. However we exclude the case of
9762          --  initialization procedures, since discriminants are handled very
9763          --  specially in this context, see the section entitled "Handling of
9764          --  Discriminants" in Einfo.
9765
9766          --  We also exclude the case of Discrim_SO_Functions (functions used
9767          --  in front end layout mode for size/offset values), since in such
9768          --  functions only discriminants are referenced, and not only are such
9769          --  subtypes not needed, but they cannot always be generated, because
9770          --  of order of elaboration issues.
9771
9772          elsif Is_Record_Type (T)
9773            and then Ekind (Formal) = E_In_Parameter
9774            and then Chars (Formal) /= Name_uInit
9775            and then not Is_Unchecked_Union (T)
9776            and then not Is_Discrim_SO_Function (Subp)
9777          then
9778             AS_Needed := True;
9779
9780          --  All other cases do not need an actual subtype
9781
9782          else
9783             AS_Needed := False;
9784          end if;
9785
9786          --  Generate actual subtypes for unconstrained arrays and
9787          --  unconstrained discriminated records.
9788
9789          if AS_Needed then
9790             if Nkind (N) = N_Accept_Statement then
9791
9792                --  If expansion is active, the formal is replaced by a local
9793                --  variable that renames the corresponding entry of the
9794                --  parameter block, and it is this local variable that may
9795                --  require an actual subtype.
9796
9797                if Full_Expander_Active then
9798                   Decl := Build_Actual_Subtype (T, Renamed_Object (Formal));
9799                else
9800                   Decl := Build_Actual_Subtype (T, Formal);
9801                end if;
9802
9803                if Present (Handled_Statement_Sequence (N)) then
9804                   First_Stmt :=
9805                     First (Statements (Handled_Statement_Sequence (N)));
9806                   Prepend (Decl, Statements (Handled_Statement_Sequence (N)));
9807                   Mark_Rewrite_Insertion (Decl);
9808                else
9809                   --  If the accept statement has no body, there will be no
9810                   --  reference to the actuals, so no need to compute actual
9811                   --  subtypes.
9812
9813                   return;
9814                end if;
9815
9816             else
9817                Decl := Build_Actual_Subtype (T, Formal);
9818                Prepend (Decl, Declarations (N));
9819                Mark_Rewrite_Insertion (Decl);
9820             end if;
9821
9822             --  The declaration uses the bounds of an existing object, and
9823             --  therefore needs no constraint checks.
9824
9825             Analyze (Decl, Suppress => All_Checks);
9826
9827             --  We need to freeze manually the generated type when it is
9828             --  inserted anywhere else than in a declarative part.
9829
9830             if Present (First_Stmt) then
9831                Insert_List_Before_And_Analyze (First_Stmt,
9832                  Freeze_Entity (Defining_Identifier (Decl), N));
9833             end if;
9834
9835             if Nkind (N) = N_Accept_Statement
9836               and then Full_Expander_Active
9837             then
9838                Set_Actual_Subtype (Renamed_Object (Formal),
9839                  Defining_Identifier (Decl));
9840             else
9841                Set_Actual_Subtype (Formal, Defining_Identifier (Decl));
9842             end if;
9843          end if;
9844
9845          Next_Formal (Formal);
9846       end loop;
9847    end Set_Actual_Subtypes;
9848
9849    ---------------------
9850    -- Set_Formal_Mode --
9851    ---------------------
9852
9853    procedure Set_Formal_Mode (Formal_Id : Entity_Id) is
9854       Spec : constant Node_Id := Parent (Formal_Id);
9855
9856    begin
9857       --  Note: we set Is_Known_Valid for IN parameters and IN OUT parameters
9858       --  since we ensure that corresponding actuals are always valid at the
9859       --  point of the call.
9860
9861       if Out_Present (Spec) then
9862          if Ekind (Scope (Formal_Id)) = E_Function
9863            or else Ekind (Scope (Formal_Id)) = E_Generic_Function
9864          then
9865             --  [IN] OUT parameters allowed for functions in Ada 2012
9866
9867             if Ada_Version >= Ada_2012 then
9868                if In_Present (Spec) then
9869                   Set_Ekind (Formal_Id, E_In_Out_Parameter);
9870                else
9871                   Set_Ekind (Formal_Id, E_Out_Parameter);
9872                end if;
9873
9874             --  But not in earlier versions of Ada
9875
9876             else
9877                Error_Msg_N ("functions can only have IN parameters", Spec);
9878                Set_Ekind (Formal_Id, E_In_Parameter);
9879             end if;
9880
9881          elsif In_Present (Spec) then
9882             Set_Ekind (Formal_Id, E_In_Out_Parameter);
9883
9884          else
9885             Set_Ekind               (Formal_Id, E_Out_Parameter);
9886             Set_Never_Set_In_Source (Formal_Id, True);
9887             Set_Is_True_Constant    (Formal_Id, False);
9888             Set_Current_Value       (Formal_Id, Empty);
9889          end if;
9890
9891       else
9892          Set_Ekind (Formal_Id, E_In_Parameter);
9893       end if;
9894
9895       --  Set Is_Known_Non_Null for access parameters since the language
9896       --  guarantees that access parameters are always non-null. We also set
9897       --  Can_Never_Be_Null, since there is no way to change the value.
9898
9899       if Nkind (Parameter_Type (Spec)) = N_Access_Definition then
9900
9901          --  Ada 2005 (AI-231): In Ada95, access parameters are always non-
9902          --  null; In Ada 2005, only if then null_exclusion is explicit.
9903
9904          if Ada_Version < Ada_2005
9905            or else Can_Never_Be_Null (Etype (Formal_Id))
9906          then
9907             Set_Is_Known_Non_Null (Formal_Id);
9908             Set_Can_Never_Be_Null (Formal_Id);
9909          end if;
9910
9911       --  Ada 2005 (AI-231): Null-exclusion access subtype
9912
9913       elsif Is_Access_Type (Etype (Formal_Id))
9914         and then Can_Never_Be_Null (Etype (Formal_Id))
9915       then
9916          Set_Is_Known_Non_Null (Formal_Id);
9917       end if;
9918
9919       Set_Mechanism (Formal_Id, Default_Mechanism);
9920       Set_Formal_Validity (Formal_Id);
9921    end Set_Formal_Mode;
9922
9923    -------------------------
9924    -- Set_Formal_Validity --
9925    -------------------------
9926
9927    procedure Set_Formal_Validity (Formal_Id : Entity_Id) is
9928    begin
9929       --  If no validity checking, then we cannot assume anything about the
9930       --  validity of parameters, since we do not know there is any checking
9931       --  of the validity on the call side.
9932
9933       if not Validity_Checks_On then
9934          return;
9935
9936       --  If validity checking for parameters is enabled, this means we are
9937       --  not supposed to make any assumptions about argument values.
9938
9939       elsif Validity_Check_Parameters then
9940          return;
9941
9942       --  If we are checking in parameters, we will assume that the caller is
9943       --  also checking parameters, so we can assume the parameter is valid.
9944
9945       elsif Ekind (Formal_Id) = E_In_Parameter
9946         and then Validity_Check_In_Params
9947       then
9948          Set_Is_Known_Valid (Formal_Id, True);
9949
9950       --  Similar treatment for IN OUT parameters
9951
9952       elsif Ekind (Formal_Id) = E_In_Out_Parameter
9953         and then Validity_Check_In_Out_Params
9954       then
9955          Set_Is_Known_Valid (Formal_Id, True);
9956       end if;
9957    end Set_Formal_Validity;
9958
9959    ------------------------
9960    -- Subtype_Conformant --
9961    ------------------------
9962
9963    function Subtype_Conformant
9964      (New_Id                   : Entity_Id;
9965       Old_Id                   : Entity_Id;
9966       Skip_Controlling_Formals : Boolean := False) return Boolean
9967    is
9968       Result : Boolean;
9969    begin
9970       Check_Conformance (New_Id, Old_Id, Subtype_Conformant, False, Result,
9971         Skip_Controlling_Formals => Skip_Controlling_Formals);
9972       return Result;
9973    end Subtype_Conformant;
9974
9975    ---------------------
9976    -- Type_Conformant --
9977    ---------------------
9978
9979    function Type_Conformant
9980      (New_Id                   : Entity_Id;
9981       Old_Id                   : Entity_Id;
9982       Skip_Controlling_Formals : Boolean := False) return Boolean
9983    is
9984       Result : Boolean;
9985    begin
9986       May_Hide_Profile := False;
9987
9988       Check_Conformance
9989         (New_Id, Old_Id, Type_Conformant, False, Result,
9990          Skip_Controlling_Formals => Skip_Controlling_Formals);
9991       return Result;
9992    end Type_Conformant;
9993
9994    -------------------------------
9995    -- Valid_Operator_Definition --
9996    -------------------------------
9997
9998    procedure Valid_Operator_Definition (Designator : Entity_Id) is
9999       N    : Integer := 0;
10000       F    : Entity_Id;
10001       Id   : constant Name_Id := Chars (Designator);
10002       N_OK : Boolean;
10003
10004    begin
10005       F := First_Formal (Designator);
10006       while Present (F) loop
10007          N := N + 1;
10008
10009          if Present (Default_Value (F)) then
10010             Error_Msg_N
10011               ("default values not allowed for operator parameters",
10012                Parent (F));
10013          end if;
10014
10015          Next_Formal (F);
10016       end loop;
10017
10018       --  Verify that user-defined operators have proper number of arguments
10019       --  First case of operators which can only be unary
10020
10021       if Id = Name_Op_Not
10022         or else Id = Name_Op_Abs
10023       then
10024          N_OK := (N = 1);
10025
10026       --  Case of operators which can be unary or binary
10027
10028       elsif Id = Name_Op_Add
10029         or Id = Name_Op_Subtract
10030       then
10031          N_OK := (N in 1 .. 2);
10032
10033       --  All other operators can only be binary
10034
10035       else
10036          N_OK := (N = 2);
10037       end if;
10038
10039       if not N_OK then
10040          Error_Msg_N
10041            ("incorrect number of arguments for operator", Designator);
10042       end if;
10043
10044       if Id = Name_Op_Ne
10045         and then Base_Type (Etype (Designator)) = Standard_Boolean
10046         and then not Is_Intrinsic_Subprogram (Designator)
10047       then
10048          Error_Msg_N
10049             ("explicit definition of inequality not allowed", Designator);
10050       end if;
10051    end Valid_Operator_Definition;
10052
10053 end Sem_Ch6;