OSDN Git Service

gcc/ada/
[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-2008, 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_Tss;  use Exp_Tss;
37 with Exp_Util; use Exp_Util;
38 with Fname;    use Fname;
39 with Freeze;   use Freeze;
40 with Itypes;   use Itypes;
41 with Lib.Xref; use Lib.Xref;
42 with Layout;   use Layout;
43 with Namet;    use Namet;
44 with Lib;      use Lib;
45 with Nlists;   use Nlists;
46 with Nmake;    use Nmake;
47 with Opt;      use Opt;
48 with Output;   use Output;
49 with Rtsfind;  use Rtsfind;
50 with Sem;      use Sem;
51 with Sem_Cat;  use Sem_Cat;
52 with Sem_Ch3;  use Sem_Ch3;
53 with Sem_Ch4;  use Sem_Ch4;
54 with Sem_Ch5;  use Sem_Ch5;
55 with Sem_Ch8;  use Sem_Ch8;
56 with Sem_Ch10; use Sem_Ch10;
57 with Sem_Ch12; use Sem_Ch12;
58 with Sem_Disp; use Sem_Disp;
59 with Sem_Dist; use Sem_Dist;
60 with Sem_Elim; use Sem_Elim;
61 with Sem_Eval; use Sem_Eval;
62 with Sem_Mech; use Sem_Mech;
63 with Sem_Prag; use Sem_Prag;
64 with Sem_Res;  use Sem_Res;
65 with Sem_Util; use Sem_Util;
66 with Sem_Type; use Sem_Type;
67 with Sem_Warn; use Sem_Warn;
68 with Sinput;   use Sinput;
69 with Stand;    use Stand;
70 with Sinfo;    use Sinfo;
71 with Sinfo.CN; use Sinfo.CN;
72 with Snames;   use Snames;
73 with Stringt;  use Stringt;
74 with Style;
75 with Stylesw;  use Stylesw;
76 with Tbuild;   use Tbuild;
77 with Uintp;    use Uintp;
78 with Urealp;   use Urealp;
79 with Validsw;  use Validsw;
80
81 package body Sem_Ch6 is
82
83    May_Hide_Profile : Boolean := False;
84    --  This flag is used to indicate that two formals in two subprograms being
85    --  checked for conformance differ only in that one is an access parameter
86    --  while the other is of a general access type with the same designated
87    --  type. In this case, if the rest of the signatures match, a call to
88    --  either subprogram may be ambiguous, which is worth a warning. The flag
89    --  is set in Compatible_Types, and the warning emitted in
90    --  New_Overloaded_Entity.
91
92    -----------------------
93    -- Local Subprograms --
94    -----------------------
95
96    procedure Analyze_Return_Statement (N : Node_Id);
97    --  Common processing for simple_ and extended_return_statements
98
99    procedure Analyze_Function_Return (N : Node_Id);
100    --  Subsidiary to Analyze_Return_Statement. Called when the return statement
101    --  applies to a [generic] function.
102
103    procedure Analyze_Return_Type (N : Node_Id);
104    --  Subsidiary to Process_Formals: analyze subtype mark in function
105    --  specification, in a context where the formals are visible and hide
106    --  outer homographs.
107
108    procedure Analyze_Generic_Subprogram_Body (N : Node_Id; Gen_Id : Entity_Id);
109    --  Analyze a generic subprogram body. N is the body to be analyzed, and
110    --  Gen_Id is the defining entity Id for the corresponding spec.
111
112    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id);
113    --  If a subprogram has pragma Inline and inlining is active, use generic
114    --  machinery to build an unexpanded body for the subprogram. This body is
115    --  subsequently used for inline expansions at call sites. If subprogram can
116    --  be inlined (depending on size and nature of local declarations) this
117    --  function returns true. Otherwise subprogram body is treated normally.
118    --  If proper warnings are enabled and the subprogram contains a construct
119    --  that cannot be inlined, the offending construct is flagged accordingly.
120
121    procedure Check_Conformance
122      (New_Id                   : Entity_Id;
123       Old_Id                   : Entity_Id;
124       Ctype                    : Conformance_Type;
125       Errmsg                   : Boolean;
126       Conforms                 : out Boolean;
127       Err_Loc                  : Node_Id := Empty;
128       Get_Inst                 : Boolean := False;
129       Skip_Controlling_Formals : Boolean := False);
130    --  Given two entities, this procedure checks that the profiles associated
131    --  with these entities meet the conformance criterion given by the third
132    --  parameter. If they conform, Conforms is set True and control returns
133    --  to the caller. If they do not conform, Conforms is set to False, and
134    --  in addition, if Errmsg is True on the call, proper messages are output
135    --  to complain about the conformance failure. If Err_Loc is non_Empty
136    --  the error messages are placed on Err_Loc, if Err_Loc is empty, then
137    --  error messages are placed on the appropriate part of the construct
138    --  denoted by New_Id. If Get_Inst is true, then this is a mode conformance
139    --  against a formal access-to-subprogram type so Get_Instance_Of must
140    --  be called.
141
142    procedure Check_Subprogram_Order (N : Node_Id);
143    --  N is the N_Subprogram_Body node for a subprogram. This routine applies
144    --  the alpha ordering rule for N if this ordering requirement applicable.
145
146    procedure Check_Returns
147      (HSS  : Node_Id;
148       Mode : Character;
149       Err  : out Boolean;
150       Proc : Entity_Id := Empty);
151    --  Called to check for missing return statements in a function body, or for
152    --  returns present in a procedure body which has No_Return set. HSS is the
153    --  handled statement sequence for the subprogram body. This procedure
154    --  checks all flow paths to make sure they either have return (Mode = 'F',
155    --  used for functions) or do not have a return (Mode = 'P', used for
156    --  No_Return procedures). The flag Err is set if there are any control
157    --  paths not explicitly terminated by a return in the function case, and is
158    --  True otherwise. Proc is the entity for the procedure case and is used
159    --  in posting the warning message.
160
161    procedure Enter_Overloaded_Entity (S : Entity_Id);
162    --  This procedure makes S, a new overloaded entity, into the first visible
163    --  entity with that name.
164
165    procedure Install_Entity (E : Entity_Id);
166    --  Make single entity visible. Used for generic formals as well
167
168    function Is_Non_Overriding_Operation
169      (Prev_E : Entity_Id;
170       New_E  : Entity_Id) return Boolean;
171    --  Enforce the rule given in 12.3(18): a private operation in an instance
172    --  overrides an inherited operation only if the corresponding operation
173    --  was overriding in the generic. This can happen for primitive operations
174    --  of types derived (in the generic unit) from formal private or formal
175    --  derived types.
176
177    procedure Make_Inequality_Operator (S : Entity_Id);
178    --  Create the declaration for an inequality operator that is implicitly
179    --  created by a user-defined equality operator that yields a boolean.
180
181    procedure May_Need_Actuals (Fun : Entity_Id);
182    --  Flag functions that can be called without parameters, i.e. those that
183    --  have no parameters, or those for which defaults exist for all parameters
184
185    procedure Process_PPCs
186      (N       : Node_Id;
187       Spec_Id : Entity_Id;
188       Body_Id : Entity_Id);
189    --  Called from Analyze_Body to deal with scanning post conditions for the
190    --  body and assembling and inserting the _postconditions procedure. N is
191    --  the node for the subprogram body and Body_Id/Spec_Id are the entities
192    --  for the body and separate spec (if there is no separate spec, Spec_Id
193    --  is Empty).
194
195    procedure Set_Formal_Validity (Formal_Id : Entity_Id);
196    --  Formal_Id is an formal parameter entity. This procedure deals with
197    --  setting the proper validity status for this entity, which depends
198    --  on the kind of parameter and the validity checking mode.
199
200    ------------------------------
201    -- Analyze_Return_Statement --
202    ------------------------------
203
204    procedure Analyze_Return_Statement (N : Node_Id) is
205
206       pragma Assert (Nkind_In (N, N_Simple_Return_Statement,
207                                   N_Extended_Return_Statement));
208
209       Returns_Object : constant Boolean :=
210                          Nkind (N) = N_Extended_Return_Statement
211                            or else
212                             (Nkind (N) = N_Simple_Return_Statement
213                               and then Present (Expression (N)));
214       --  True if we're returning something; that is, "return <expression>;"
215       --  or "return Result : T [:= ...]". False for "return;". Used for error
216       --  checking: If Returns_Object is True, N should apply to a function
217       --  body; otherwise N should apply to a procedure body, entry body,
218       --  accept statement, or extended return statement.
219
220       function Find_What_It_Applies_To return Entity_Id;
221       --  Find the entity representing the innermost enclosing body, accept
222       --  statement, or extended return statement. If the result is a callable
223       --  construct or extended return statement, then this will be the value
224       --  of the Return_Applies_To attribute. Otherwise, the program is
225       --  illegal. See RM-6.5(4/2).
226
227       -----------------------------
228       -- Find_What_It_Applies_To --
229       -----------------------------
230
231       function Find_What_It_Applies_To return Entity_Id is
232          Result : Entity_Id := Empty;
233
234       begin
235          --  Loop outward through the Scope_Stack, skipping blocks and loops
236
237          for J in reverse 0 .. Scope_Stack.Last loop
238             Result := Scope_Stack.Table (J).Entity;
239             exit when Ekind (Result) /= E_Block and then
240                       Ekind (Result) /= E_Loop;
241          end loop;
242
243          pragma Assert (Present (Result));
244          return Result;
245       end Find_What_It_Applies_To;
246
247       --  Local declarations
248
249       Scope_Id   : constant Entity_Id   := Find_What_It_Applies_To;
250       Kind       : constant Entity_Kind := Ekind (Scope_Id);
251       Loc        : constant Source_Ptr  := Sloc (N);
252       Stm_Entity : constant Entity_Id   :=
253                      New_Internal_Entity
254                        (E_Return_Statement, Current_Scope, Loc, 'R');
255
256    --  Start of processing for Analyze_Return_Statement
257
258    begin
259       Set_Return_Statement_Entity (N, Stm_Entity);
260
261       Set_Etype (Stm_Entity, Standard_Void_Type);
262       Set_Return_Applies_To (Stm_Entity, Scope_Id);
263
264       --  Place Return entity on scope stack, to simplify enforcement of 6.5
265       --  (4/2): an inner return statement will apply to this extended return.
266
267       if Nkind (N) = N_Extended_Return_Statement then
268          Push_Scope (Stm_Entity);
269       end if;
270
271       --  Check that pragma No_Return is obeyed
272
273       if No_Return (Scope_Id) then
274          Error_Msg_N ("RETURN statement not allowed (No_Return)", N);
275       end if;
276
277       --  Warn on any unassigned OUT parameters if in procedure
278
279       if Ekind (Scope_Id) = E_Procedure then
280          Warn_On_Unassigned_Out_Parameter (N, Scope_Id);
281       end if;
282
283       --  Check that functions return objects, and other things do not
284
285       if Kind = E_Function or else Kind = E_Generic_Function then
286          if not Returns_Object then
287             Error_Msg_N ("missing expression in return from function", N);
288          end if;
289
290       elsif Kind = E_Procedure or else Kind = E_Generic_Procedure then
291          if Returns_Object then
292             Error_Msg_N ("procedure cannot return value (use function)", N);
293          end if;
294
295       elsif Kind = E_Entry or else Kind = E_Entry_Family then
296          if Returns_Object then
297             if Is_Protected_Type (Scope (Scope_Id)) then
298                Error_Msg_N ("entry body cannot return value", N);
299             else
300                Error_Msg_N ("accept statement cannot return value", N);
301             end if;
302          end if;
303
304       elsif Kind = E_Return_Statement then
305
306          --  We are nested within another return statement, which must be an
307          --  extended_return_statement.
308
309          if Returns_Object then
310             Error_Msg_N
311               ("extended_return_statement cannot return value; " &
312                "use `""RETURN;""`", N);
313          end if;
314
315       else
316          Error_Msg_N ("illegal context for return statement", N);
317       end if;
318
319       if Kind = E_Function or else Kind = E_Generic_Function then
320          Analyze_Function_Return (N);
321       end if;
322
323       if Nkind (N) = N_Extended_Return_Statement then
324          End_Scope;
325       end if;
326
327       Kill_Current_Values (Last_Assignment_Only => True);
328       Check_Unreachable_Code (N);
329    end Analyze_Return_Statement;
330
331    ---------------------------------------------
332    -- Analyze_Abstract_Subprogram_Declaration --
333    ---------------------------------------------
334
335    procedure Analyze_Abstract_Subprogram_Declaration (N : Node_Id) is
336       Designator : constant Entity_Id :=
337                      Analyze_Subprogram_Specification (Specification (N));
338       Scop       : constant Entity_Id := Current_Scope;
339
340    begin
341       Generate_Definition (Designator);
342       Set_Is_Abstract_Subprogram (Designator);
343       New_Overloaded_Entity (Designator);
344       Check_Delayed_Subprogram (Designator);
345
346       Set_Categorization_From_Scope (Designator, Scop);
347
348       if Ekind (Scope (Designator)) = E_Protected_Type then
349          Error_Msg_N
350            ("abstract subprogram not allowed in protected type", N);
351
352       --  Issue a warning if the abstract subprogram is neither a dispatching
353       --  operation nor an operation that overrides an inherited subprogram or
354       --  predefined operator, since this most likely indicates a mistake.
355
356       elsif Warn_On_Redundant_Constructs
357         and then not Is_Dispatching_Operation (Designator)
358         and then not Is_Overriding_Operation (Designator)
359         and then (not Is_Operator_Symbol_Name (Chars (Designator))
360                    or else Scop /= Scope (Etype (First_Formal (Designator))))
361       then
362          Error_Msg_N
363            ("?abstract subprogram is not dispatching or overriding", N);
364       end if;
365
366       Generate_Reference_To_Formals (Designator);
367    end Analyze_Abstract_Subprogram_Declaration;
368
369    ----------------------------------------
370    -- Analyze_Extended_Return_Statement  --
371    ----------------------------------------
372
373    procedure Analyze_Extended_Return_Statement (N : Node_Id) is
374    begin
375       Analyze_Return_Statement (N);
376    end Analyze_Extended_Return_Statement;
377
378    ----------------------------
379    -- Analyze_Function_Call  --
380    ----------------------------
381
382    procedure Analyze_Function_Call (N : Node_Id) is
383       P      : constant Node_Id := Name (N);
384       L      : constant List_Id := Parameter_Associations (N);
385       Actual : Node_Id;
386
387    begin
388       Analyze (P);
389
390       --  A call of the form A.B (X) may be an Ada05 call, which is rewritten
391       --  as B (A, X). If the rewriting is successful, the call has been
392       --  analyzed and we just return.
393
394       if Nkind (P) = N_Selected_Component
395         and then Name (N) /= P
396         and then Is_Rewrite_Substitution (N)
397         and then Present (Etype (N))
398       then
399          return;
400       end if;
401
402       --  If error analyzing name, then set Any_Type as result type and return
403
404       if Etype (P) = Any_Type then
405          Set_Etype (N, Any_Type);
406          return;
407       end if;
408
409       --  Otherwise analyze the parameters
410
411       if Present (L) then
412          Actual := First (L);
413          while Present (Actual) loop
414             Analyze (Actual);
415             Check_Parameterless_Call (Actual);
416             Next (Actual);
417          end loop;
418       end if;
419
420       Analyze_Call (N);
421    end Analyze_Function_Call;
422
423    -----------------------------
424    -- Analyze_Function_Return --
425    -----------------------------
426
427    procedure Analyze_Function_Return (N : Node_Id) is
428       Loc        : constant Source_Ptr  := Sloc (N);
429       Stm_Entity : constant Entity_Id   := Return_Statement_Entity (N);
430       Scope_Id   : constant Entity_Id   := Return_Applies_To (Stm_Entity);
431
432       R_Type : constant Entity_Id := Etype (Scope_Id);
433       --  Function result subtype
434
435       procedure Check_Limited_Return (Expr : Node_Id);
436       --  Check the appropriate (Ada 95 or Ada 2005) rules for returning
437       --  limited types. Used only for simple return statements.
438       --  Expr is the expression returned.
439
440       procedure Check_Return_Subtype_Indication (Obj_Decl : Node_Id);
441       --  Check that the return_subtype_indication properly matches the result
442       --  subtype of the function, as required by RM-6.5(5.1/2-5.3/2).
443
444       --------------------------
445       -- Check_Limited_Return --
446       --------------------------
447
448       procedure Check_Limited_Return (Expr : Node_Id) is
449       begin
450          --  Ada 2005 (AI-318-02): Return-by-reference types have been
451          --  removed and replaced by anonymous access results. This is an
452          --  incompatibility with Ada 95. Not clear whether this should be
453          --  enforced yet or perhaps controllable with special switch. ???
454
455          if Is_Limited_Type (R_Type)
456            and then Comes_From_Source (N)
457            and then not In_Instance_Body
458            and then not OK_For_Limited_Init_In_05 (Expr)
459          then
460             --  Error in Ada 2005
461
462             if Ada_Version >= Ada_05
463               and then not Debug_Flag_Dot_L
464               and then not GNAT_Mode
465             then
466                Error_Msg_N
467                  ("(Ada 2005) cannot copy object of a limited type " &
468                   "(RM-2005 6.5(5.5/2))", Expr);
469                if Is_Inherently_Limited_Type (R_Type) then
470                   Error_Msg_N
471                     ("\return by reference not permitted in Ada 2005", Expr);
472                end if;
473
474             --  Warn in Ada 95 mode, to give folks a heads up about this
475             --  incompatibility.
476
477             --  In GNAT mode, this is just a warning, to allow it to be
478             --  evilly turned off. Otherwise it is a real error.
479
480             elsif Warn_On_Ada_2005_Compatibility or GNAT_Mode then
481                if Is_Inherently_Limited_Type (R_Type) then
482                   Error_Msg_N
483                     ("return by reference not permitted in Ada 2005 " &
484                      "(RM-2005 6.5(5.5/2))?", Expr);
485                else
486                   Error_Msg_N
487                     ("cannot copy object of a limited type in Ada 2005 " &
488                      "(RM-2005 6.5(5.5/2))?", Expr);
489                end if;
490
491             --  Ada 95 mode, compatibility warnings disabled
492
493             else
494                return; --  skip continuation messages below
495             end if;
496
497             Error_Msg_N
498               ("\consider switching to return of access type", Expr);
499             Explain_Limited_Type (R_Type, Expr);
500          end if;
501       end Check_Limited_Return;
502
503       -------------------------------------
504       -- Check_Return_Subtype_Indication --
505       -------------------------------------
506
507       procedure Check_Return_Subtype_Indication (Obj_Decl : Node_Id) is
508          Return_Obj  : constant Node_Id   := Defining_Identifier (Obj_Decl);
509          R_Stm_Type  : constant Entity_Id := Etype (Return_Obj);
510          --  Subtype given in the extended return statement;
511          --  this must match R_Type.
512
513          Subtype_Ind : constant Node_Id :=
514                          Object_Definition (Original_Node (Obj_Decl));
515
516          R_Type_Is_Anon_Access :
517            constant Boolean :=
518              Ekind (R_Type) = E_Anonymous_Access_Subprogram_Type
519                or else
520              Ekind (R_Type) = E_Anonymous_Access_Protected_Subprogram_Type
521                or else
522              Ekind (R_Type) = E_Anonymous_Access_Type;
523          --  True if return type of the function is an anonymous access type
524          --  Can't we make Is_Anonymous_Access_Type in einfo ???
525
526          R_Stm_Type_Is_Anon_Access :
527            constant Boolean :=
528              Ekind (R_Stm_Type) = E_Anonymous_Access_Subprogram_Type
529                or else
530              Ekind (R_Stm_Type) = E_Anonymous_Access_Protected_Subprogram_Type
531                or else
532              Ekind (R_Stm_Type) = E_Anonymous_Access_Type;
533          --  True if type of the return object is an anonymous access type
534
535       begin
536          --  First, avoid cascade errors:
537
538          if Error_Posted (Obj_Decl) or else Error_Posted (Subtype_Ind) then
539             return;
540          end if;
541
542          --  "return access T" case; check that the return statement also has
543          --  "access T", and that the subtypes statically match:
544
545          if R_Type_Is_Anon_Access then
546             if R_Stm_Type_Is_Anon_Access then
547                if Base_Type (Designated_Type (R_Stm_Type)) /=
548                     Base_Type (Designated_Type (R_Type))
549                  or else not Subtypes_Statically_Match (R_Stm_Type, R_Type)
550                then
551                   Error_Msg_N
552                     ("subtype must statically match function result subtype",
553                      Subtype_Mark (Subtype_Ind));
554                end if;
555
556             else
557                Error_Msg_N ("must use anonymous access type", Subtype_Ind);
558             end if;
559
560          --  Subtype_indication case; check that the types are the same, and
561          --  statically match if appropriate. A null exclusion may be present
562          --  on the return type, on the function specification, on the object
563          --  declaration or on the subtype itself.
564
565          elsif Base_Type (R_Stm_Type) = Base_Type (R_Type) then
566             if Is_Access_Type (R_Type)
567               and then
568                (Can_Never_Be_Null (R_Type)
569                  or else Null_Exclusion_Present (Parent (Scope_Id))) /=
570                                               Can_Never_Be_Null (R_Stm_Type)
571             then
572                Error_Msg_N
573                  ("subtype must statically match function result subtype",
574                   Subtype_Ind);
575             end if;
576
577             if Is_Constrained (R_Type) then
578                if not Subtypes_Statically_Match (R_Stm_Type, R_Type) then
579                   Error_Msg_N
580                     ("subtype must statically match function result subtype",
581                      Subtype_Ind);
582                end if;
583             end if;
584
585          --  If the function's result type doesn't match the return object
586          --  entity's type, then we check for the case where the result type
587          --  is class-wide, and allow the declaration if the type of the object
588          --  definition matches the class-wide type. This prevents rejection
589          --  in the case where the object declaration is initialized by a call
590          --  to a build-in-place function with a specific result type and the
591          --  object entity had its type changed to that specific type. (Note
592          --  that the ARG believes that return objects should be allowed to
593          --  have a type covered by a class-wide result type in any case, so
594          --  once that relaxation is made (see AI05-32), the above check for
595          --  type compatibility should be changed to test Covers rather than
596          --  equality, and then the following special test will no longer be
597          --  needed. ???)
598
599          elsif Is_Class_Wide_Type (R_Type)
600            and then
601              R_Type = Etype (Object_Definition (Original_Node (Obj_Decl)))
602          then
603             null;
604
605          else
606             Error_Msg_N
607               ("wrong type for return_subtype_indication", Subtype_Ind);
608          end if;
609       end Check_Return_Subtype_Indication;
610
611       ---------------------
612       -- Local Variables --
613       ---------------------
614
615       Expr : Node_Id;
616
617    --  Start of processing for Analyze_Function_Return
618
619    begin
620       Set_Return_Present (Scope_Id);
621
622       if Nkind (N) = N_Simple_Return_Statement then
623          Expr := Expression (N);
624          Analyze_And_Resolve (Expr, R_Type);
625          Check_Limited_Return (Expr);
626
627       else
628          --  Analyze parts specific to extended_return_statement:
629
630          declare
631             Obj_Decl : constant Node_Id :=
632                          Last (Return_Object_Declarations (N));
633
634             HSS : constant Node_Id := Handled_Statement_Sequence (N);
635
636          begin
637             Expr := Expression (Obj_Decl);
638
639             --  Note: The check for OK_For_Limited_Init will happen in
640             --  Analyze_Object_Declaration; we treat it as a normal
641             --  object declaration.
642
643             Analyze (Obj_Decl);
644
645             Set_Is_Return_Object (Defining_Identifier (Obj_Decl));
646             Check_Return_Subtype_Indication (Obj_Decl);
647
648             if Present (HSS) then
649                Analyze (HSS);
650
651                if Present (Exception_Handlers (HSS)) then
652
653                   --  ???Has_Nested_Block_With_Handler needs to be set.
654                   --  Probably by creating an actual N_Block_Statement.
655                   --  Probably in Expand.
656
657                   null;
658                end if;
659             end if;
660
661             Check_References (Stm_Entity);
662          end;
663       end if;
664
665       --  Case of Expr present
666
667       if Present (Expr)
668
669          --  Defend against previous errors
670
671         and then Nkind (Expr) /= N_Empty
672         and then Present (Etype (Expr))
673       then
674          --  Apply constraint check. Note that this is done before the implicit
675          --  conversion of the expression done for anonymous access types to
676          --  ensure correct generation of the null-excluding check associated
677          --  with null-excluding expressions found in return statements.
678
679          Apply_Constraint_Check (Expr, R_Type);
680
681          --  Ada 2005 (AI-318-02): When the result type is an anonymous access
682          --  type, apply an implicit conversion of the expression to that type
683          --  to force appropriate static and run-time accessibility checks.
684
685          if Ada_Version >= Ada_05
686            and then Ekind (R_Type) = E_Anonymous_Access_Type
687          then
688             Rewrite (Expr, Convert_To (R_Type, Relocate_Node (Expr)));
689             Analyze_And_Resolve (Expr, R_Type);
690          end if;
691
692          --  If the result type is class-wide, then check that the return
693          --  expression's type is not declared at a deeper level than the
694          --  function (RM05-6.5(5.6/2)).
695
696          if Ada_Version >= Ada_05
697            and then Is_Class_Wide_Type (R_Type)
698          then
699             if Type_Access_Level (Etype (Expr)) >
700                  Subprogram_Access_Level (Scope_Id)
701             then
702                Error_Msg_N
703                  ("level of return expression type is deeper than " &
704                   "class-wide function!", Expr);
705             end if;
706          end if;
707
708          if (Is_Class_Wide_Type (Etype (Expr))
709               or else Is_Dynamically_Tagged (Expr))
710            and then not Is_Class_Wide_Type (R_Type)
711          then
712             Error_Msg_N
713               ("dynamically tagged expression not allowed!", Expr);
714          end if;
715
716          --  ??? A real run-time accessibility check is needed in cases
717          --  involving dereferences of access parameters. For now we just
718          --  check the static cases.
719
720          if (Ada_Version < Ada_05 or else Debug_Flag_Dot_L)
721            and then Is_Inherently_Limited_Type (Etype (Scope_Id))
722            and then Object_Access_Level (Expr) >
723                       Subprogram_Access_Level (Scope_Id)
724          then
725             Rewrite (N,
726               Make_Raise_Program_Error (Loc,
727                 Reason => PE_Accessibility_Check_Failed));
728             Analyze (N);
729
730             Error_Msg_N
731               ("cannot return a local value by reference?", N);
732             Error_Msg_NE
733               ("\& will be raised at run time?",
734                N, Standard_Program_Error);
735          end if;
736
737          if Known_Null (Expr)
738            and then Nkind (Parent (Scope_Id)) = N_Function_Specification
739            and then Null_Exclusion_Present (Parent (Scope_Id))
740          then
741             Apply_Compile_Time_Constraint_Error
742               (N      => Expr,
743                Msg    => "(Ada 2005) null not allowed for "
744                          & "null-excluding return?",
745                Reason => CE_Null_Not_Allowed);
746          end if;
747       end if;
748    end Analyze_Function_Return;
749
750    -------------------------------------
751    -- Analyze_Generic_Subprogram_Body --
752    -------------------------------------
753
754    procedure Analyze_Generic_Subprogram_Body
755      (N      : Node_Id;
756       Gen_Id : Entity_Id)
757    is
758       Gen_Decl : constant Node_Id     := Unit_Declaration_Node (Gen_Id);
759       Kind     : constant Entity_Kind := Ekind (Gen_Id);
760       Body_Id  : Entity_Id;
761       New_N    : Node_Id;
762       Spec     : Node_Id;
763
764    begin
765       --  Copy body and disable expansion while analyzing the generic For a
766       --  stub, do not copy the stub (which would load the proper body), this
767       --  will be done when the proper body is analyzed.
768
769       if Nkind (N) /= N_Subprogram_Body_Stub then
770          New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
771          Rewrite (N, New_N);
772          Start_Generic;
773       end if;
774
775       Spec := Specification (N);
776
777       --  Within the body of the generic, the subprogram is callable, and
778       --  behaves like the corresponding non-generic unit.
779
780       Body_Id := Defining_Entity (Spec);
781
782       if Kind = E_Generic_Procedure
783         and then Nkind (Spec) /= N_Procedure_Specification
784       then
785          Error_Msg_N ("invalid body for generic procedure ", Body_Id);
786          return;
787
788       elsif Kind = E_Generic_Function
789         and then Nkind (Spec) /= N_Function_Specification
790       then
791          Error_Msg_N ("invalid body for generic function ", Body_Id);
792          return;
793       end if;
794
795       Set_Corresponding_Body (Gen_Decl, Body_Id);
796
797       if Has_Completion (Gen_Id)
798         and then Nkind (Parent (N)) /= N_Subunit
799       then
800          Error_Msg_N ("duplicate generic body", N);
801          return;
802       else
803          Set_Has_Completion (Gen_Id);
804       end if;
805
806       if Nkind (N) = N_Subprogram_Body_Stub then
807          Set_Ekind (Defining_Entity (Specification (N)), Kind);
808       else
809          Set_Corresponding_Spec (N, Gen_Id);
810       end if;
811
812       if Nkind (Parent (N)) = N_Compilation_Unit then
813          Set_Cunit_Entity (Current_Sem_Unit, Defining_Entity (N));
814       end if;
815
816       --  Make generic parameters immediately visible in the body. They are
817       --  needed to process the formals declarations. Then make the formals
818       --  visible in a separate step.
819
820       Push_Scope (Gen_Id);
821
822       declare
823          E         : Entity_Id;
824          First_Ent : Entity_Id;
825
826       begin
827          First_Ent := First_Entity (Gen_Id);
828
829          E := First_Ent;
830          while Present (E) and then not Is_Formal (E) loop
831             Install_Entity (E);
832             Next_Entity (E);
833          end loop;
834
835          Set_Use (Generic_Formal_Declarations (Gen_Decl));
836
837          --  Now generic formals are visible, and the specification can be
838          --  analyzed, for subsequent conformance check.
839
840          Body_Id := Analyze_Subprogram_Specification (Spec);
841
842          --  Make formal parameters visible
843
844          if Present (E) then
845
846             --  E is the first formal parameter, we loop through the formals
847             --  installing them so that they will be visible.
848
849             Set_First_Entity (Gen_Id, E);
850             while Present (E) loop
851                Install_Entity (E);
852                Next_Formal (E);
853             end loop;
854          end if;
855
856          --  Visible generic entity is callable within its own body
857
858          Set_Ekind          (Gen_Id,  Ekind (Body_Id));
859          Set_Ekind          (Body_Id, E_Subprogram_Body);
860          Set_Convention     (Body_Id, Convention (Gen_Id));
861          Set_Is_Obsolescent (Body_Id, Is_Obsolescent (Gen_Id));
862          Set_Scope          (Body_Id, Scope (Gen_Id));
863          Check_Fully_Conformant (Body_Id, Gen_Id, Body_Id);
864
865          if Nkind (N) = N_Subprogram_Body_Stub then
866
867             --  No body to analyze, so restore state of generic unit
868
869             Set_Ekind (Gen_Id, Kind);
870             Set_Ekind (Body_Id, Kind);
871
872             if Present (First_Ent) then
873                Set_First_Entity (Gen_Id, First_Ent);
874             end if;
875
876             End_Scope;
877             return;
878          end if;
879
880          --  If this is a compilation unit, it must be made visible explicitly,
881          --  because the compilation of the declaration, unlike other library
882          --  unit declarations, does not. If it is not a unit, the following
883          --  is redundant but harmless.
884
885          Set_Is_Immediately_Visible (Gen_Id);
886          Reference_Body_Formals (Gen_Id, Body_Id);
887
888          if Is_Child_Unit (Gen_Id) then
889             Generate_Reference (Gen_Id, Scope (Gen_Id), 'k', False);
890          end if;
891
892          Set_Actual_Subtypes (N, Current_Scope);
893          Analyze_Declarations (Declarations (N));
894          Check_Completion;
895          Analyze (Handled_Statement_Sequence (N));
896
897          Save_Global_References (Original_Node (N));
898
899          --  Prior to exiting the scope, include generic formals again (if any
900          --  are present) in the set of local entities.
901
902          if Present (First_Ent) then
903             Set_First_Entity (Gen_Id, First_Ent);
904          end if;
905
906          Check_References (Gen_Id);
907       end;
908
909       Process_End_Label (Handled_Statement_Sequence (N), 't', Current_Scope);
910       End_Scope;
911       Check_Subprogram_Order (N);
912
913       --  Outside of its body, unit is generic again
914
915       Set_Ekind (Gen_Id, Kind);
916       Generate_Reference (Gen_Id, Body_Id, 'b', Set_Ref => False);
917
918       if Style_Check then
919          Style.Check_Identifier (Body_Id, Gen_Id);
920       end if;
921       End_Generic;
922    end Analyze_Generic_Subprogram_Body;
923
924    -----------------------------
925    -- Analyze_Operator_Symbol --
926    -----------------------------
927
928    --  An operator symbol such as "+" or "and" may appear in context where the
929    --  literal denotes an entity name, such as "+"(x, y) or in context when it
930    --  is just a string, as in (conjunction = "or"). In these cases the parser
931    --  generates this node, and the semantics does the disambiguation. Other
932    --  such case are actuals in an instantiation, the generic unit in an
933    --  instantiation, and pragma arguments.
934
935    procedure Analyze_Operator_Symbol (N : Node_Id) is
936       Par : constant Node_Id := Parent (N);
937
938    begin
939       if        (Nkind (Par) = N_Function_Call
940                    and then N = Name (Par))
941         or else  Nkind (Par) = N_Function_Instantiation
942         or else (Nkind (Par) = N_Indexed_Component
943                    and then N = Prefix (Par))
944         or else (Nkind (Par) = N_Pragma_Argument_Association
945                    and then not Is_Pragma_String_Literal (Par))
946         or else  Nkind (Par) = N_Subprogram_Renaming_Declaration
947         or else (Nkind (Par) = N_Attribute_Reference
948                   and then Attribute_Name (Par) /= Name_Value)
949       then
950          Find_Direct_Name (N);
951
952       else
953          Change_Operator_Symbol_To_String_Literal (N);
954          Analyze (N);
955       end if;
956    end Analyze_Operator_Symbol;
957
958    -----------------------------------
959    -- Analyze_Parameter_Association --
960    -----------------------------------
961
962    procedure Analyze_Parameter_Association (N : Node_Id) is
963    begin
964       Analyze (Explicit_Actual_Parameter (N));
965    end Analyze_Parameter_Association;
966
967    ----------------------------
968    -- Analyze_Procedure_Call --
969    ----------------------------
970
971    procedure Analyze_Procedure_Call (N : Node_Id) is
972       Loc     : constant Source_Ptr := Sloc (N);
973       P       : constant Node_Id    := Name (N);
974       Actuals : constant List_Id    := Parameter_Associations (N);
975       Actual  : Node_Id;
976       New_N   : Node_Id;
977
978       procedure Analyze_Call_And_Resolve;
979       --  Do Analyze and Resolve calls for procedure call
980
981       ------------------------------
982       -- Analyze_Call_And_Resolve --
983       ------------------------------
984
985       procedure Analyze_Call_And_Resolve is
986       begin
987          if Nkind (N) = N_Procedure_Call_Statement then
988             Analyze_Call (N);
989             Resolve (N, Standard_Void_Type);
990          else
991             Analyze (N);
992          end if;
993       end Analyze_Call_And_Resolve;
994
995    --  Start of processing for Analyze_Procedure_Call
996
997    begin
998       --  The syntactic construct: PREFIX ACTUAL_PARAMETER_PART can denote
999       --  a procedure call or an entry call. The prefix may denote an access
1000       --  to subprogram type, in which case an implicit dereference applies.
1001       --  If the prefix is an indexed component (without implicit dereference)
1002       --  then the construct denotes a call to a member of an entire family.
1003       --  If the prefix is a simple name, it may still denote a call to a
1004       --  parameterless member of an entry family. Resolution of these various
1005       --  interpretations is delicate.
1006
1007       Analyze (P);
1008
1009       --  If this is a call of the form Obj.Op, the call may have been
1010       --  analyzed and possibly rewritten into a block, in which case
1011       --  we are done.
1012
1013       if Analyzed (N) then
1014          return;
1015       end if;
1016
1017       --  If error analyzing prefix, then set Any_Type as result and return
1018
1019       if Etype (P) = Any_Type then
1020          Set_Etype (N, Any_Type);
1021          return;
1022       end if;
1023
1024       --  Otherwise analyze the parameters
1025
1026       if Present (Actuals) then
1027          Actual := First (Actuals);
1028
1029          while Present (Actual) loop
1030             Analyze (Actual);
1031             Check_Parameterless_Call (Actual);
1032             Next (Actual);
1033          end loop;
1034       end if;
1035
1036       --  Special processing for Elab_Spec and Elab_Body calls
1037
1038       if Nkind (P) = N_Attribute_Reference
1039         and then (Attribute_Name (P) = Name_Elab_Spec
1040                    or else Attribute_Name (P) = Name_Elab_Body)
1041       then
1042          if Present (Actuals) then
1043             Error_Msg_N
1044               ("no parameters allowed for this call", First (Actuals));
1045             return;
1046          end if;
1047
1048          Set_Etype (N, Standard_Void_Type);
1049          Set_Analyzed (N);
1050
1051       elsif Is_Entity_Name (P)
1052         and then Is_Record_Type (Etype (Entity (P)))
1053         and then Remote_AST_I_Dereference (P)
1054       then
1055          return;
1056
1057       elsif Is_Entity_Name (P)
1058         and then Ekind (Entity (P)) /= E_Entry_Family
1059       then
1060          if Is_Access_Type (Etype (P))
1061            and then Ekind (Designated_Type (Etype (P))) = E_Subprogram_Type
1062            and then No (Actuals)
1063            and then Comes_From_Source (N)
1064          then
1065             Error_Msg_N ("missing explicit dereference in call", N);
1066          end if;
1067
1068          Analyze_Call_And_Resolve;
1069
1070       --  If the prefix is the simple name of an entry family, this is
1071       --  a parameterless call from within the task body itself.
1072
1073       elsif Is_Entity_Name (P)
1074         and then Nkind (P) = N_Identifier
1075         and then Ekind (Entity (P)) = E_Entry_Family
1076         and then Present (Actuals)
1077         and then No (Next (First (Actuals)))
1078       then
1079          --  Can be call to parameterless entry family. What appears to be the
1080          --  sole argument is in fact the entry index. Rewrite prefix of node
1081          --  accordingly. Source representation is unchanged by this
1082          --  transformation.
1083
1084          New_N :=
1085            Make_Indexed_Component (Loc,
1086              Prefix =>
1087                Make_Selected_Component (Loc,
1088                  Prefix => New_Occurrence_Of (Scope (Entity (P)), Loc),
1089                  Selector_Name => New_Occurrence_Of (Entity (P), Loc)),
1090              Expressions => Actuals);
1091          Set_Name (N, New_N);
1092          Set_Etype (New_N, Standard_Void_Type);
1093          Set_Parameter_Associations (N, No_List);
1094          Analyze_Call_And_Resolve;
1095
1096       elsif Nkind (P) = N_Explicit_Dereference then
1097          if Ekind (Etype (P)) = E_Subprogram_Type then
1098             Analyze_Call_And_Resolve;
1099          else
1100             Error_Msg_N ("expect access to procedure in call", P);
1101          end if;
1102
1103       --  The name can be a selected component or an indexed component that
1104       --  yields an access to subprogram. Such a prefix is legal if the call
1105       --  has parameter associations.
1106
1107       elsif Is_Access_Type (Etype (P))
1108         and then Ekind (Designated_Type (Etype (P))) = E_Subprogram_Type
1109       then
1110          if Present (Actuals) then
1111             Analyze_Call_And_Resolve;
1112          else
1113             Error_Msg_N ("missing explicit dereference in call ", N);
1114          end if;
1115
1116       --  If not an access to subprogram, then the prefix must resolve to the
1117       --  name of an entry, entry family, or protected operation.
1118
1119       --  For the case of a simple entry call, P is a selected component where
1120       --  the prefix is the task and the selector name is the entry. A call to
1121       --  a protected procedure will have the same syntax. If the protected
1122       --  object contains overloaded operations, the entity may appear as a
1123       --  function, the context will select the operation whose type is Void.
1124
1125       elsif Nkind (P) = N_Selected_Component
1126         and then (Ekind (Entity (Selector_Name (P))) = E_Entry
1127                     or else
1128                   Ekind (Entity (Selector_Name (P))) = E_Procedure
1129                     or else
1130                   Ekind (Entity (Selector_Name (P))) = E_Function)
1131       then
1132          Analyze_Call_And_Resolve;
1133
1134       elsif Nkind (P) = N_Selected_Component
1135         and then Ekind (Entity (Selector_Name (P))) = E_Entry_Family
1136         and then Present (Actuals)
1137         and then No (Next (First (Actuals)))
1138       then
1139          --  Can be call to parameterless entry family. What appears to be the
1140          --  sole argument is in fact the entry index. Rewrite prefix of node
1141          --  accordingly. Source representation is unchanged by this
1142          --  transformation.
1143
1144          New_N :=
1145            Make_Indexed_Component (Loc,
1146              Prefix => New_Copy (P),
1147              Expressions => Actuals);
1148          Set_Name (N, New_N);
1149          Set_Etype (New_N, Standard_Void_Type);
1150          Set_Parameter_Associations (N, No_List);
1151          Analyze_Call_And_Resolve;
1152
1153       --  For the case of a reference to an element of an entry family, P is
1154       --  an indexed component whose prefix is a selected component (task and
1155       --  entry family), and whose index is the entry family index.
1156
1157       elsif Nkind (P) = N_Indexed_Component
1158         and then Nkind (Prefix (P)) = N_Selected_Component
1159         and then Ekind (Entity (Selector_Name (Prefix (P)))) = E_Entry_Family
1160       then
1161          Analyze_Call_And_Resolve;
1162
1163       --  If the prefix is the name of an entry family, it is a call from
1164       --  within the task body itself.
1165
1166       elsif Nkind (P) = N_Indexed_Component
1167         and then Nkind (Prefix (P)) = N_Identifier
1168         and then Ekind (Entity (Prefix (P))) = E_Entry_Family
1169       then
1170          New_N :=
1171            Make_Selected_Component (Loc,
1172              Prefix => New_Occurrence_Of (Scope (Entity (Prefix (P))), Loc),
1173              Selector_Name => New_Occurrence_Of (Entity (Prefix (P)), Loc));
1174          Rewrite (Prefix (P), New_N);
1175          Analyze (P);
1176          Analyze_Call_And_Resolve;
1177
1178       --  Anything else is an error
1179
1180       else
1181          Error_Msg_N ("invalid procedure or entry call", N);
1182       end if;
1183    end Analyze_Procedure_Call;
1184
1185    -------------------------------------
1186    -- Analyze_Simple_Return_Statement --
1187    -------------------------------------
1188
1189    procedure Analyze_Simple_Return_Statement (N : Node_Id) is
1190    begin
1191       if Present (Expression (N)) then
1192          Mark_Coextensions (N, Expression (N));
1193       end if;
1194
1195       Analyze_Return_Statement (N);
1196    end Analyze_Simple_Return_Statement;
1197
1198    -------------------------
1199    -- Analyze_Return_Type --
1200    -------------------------
1201
1202    procedure Analyze_Return_Type (N : Node_Id) is
1203       Designator : constant Entity_Id := Defining_Entity (N);
1204       Typ        : Entity_Id := Empty;
1205
1206    begin
1207       --  Normal case where result definition does not indicate an error
1208
1209       if Result_Definition (N) /= Error then
1210          if Nkind (Result_Definition (N)) = N_Access_Definition then
1211             Typ := Access_Definition (N, Result_Definition (N));
1212             Set_Parent (Typ, Result_Definition (N));
1213             Set_Is_Local_Anonymous_Access (Typ);
1214             Set_Etype (Designator, Typ);
1215
1216          --  Subtype_Mark case
1217
1218          else
1219             Find_Type (Result_Definition (N));
1220             Typ := Entity (Result_Definition (N));
1221             Set_Etype (Designator, Typ);
1222
1223             if Ekind (Typ) = E_Incomplete_Type
1224               and then Is_Value_Type (Typ)
1225             then
1226                null;
1227
1228             elsif Ekind (Typ) = E_Incomplete_Type
1229               or else (Is_Class_Wide_Type (Typ)
1230                          and then
1231                            Ekind (Root_Type (Typ)) = E_Incomplete_Type)
1232             then
1233                Error_Msg_N
1234                  ("invalid use of incomplete type", Result_Definition (N));
1235             end if;
1236          end if;
1237
1238          --  Ada 2005 (AI-231): Ensure proper usage of null exclusion
1239
1240          Null_Exclusion_Static_Checks (N);
1241
1242       --  Case where result definition does indicate an error
1243
1244       else
1245          Set_Etype (Designator, Any_Type);
1246       end if;
1247    end Analyze_Return_Type;
1248
1249    -----------------------------
1250    -- Analyze_Subprogram_Body --
1251    -----------------------------
1252
1253    --  This procedure is called for regular subprogram bodies, generic bodies,
1254    --  and for subprogram stubs of both kinds. In the case of stubs, only the
1255    --  specification matters, and is used to create a proper declaration for
1256    --  the subprogram, or to perform conformance checks.
1257
1258    procedure Analyze_Subprogram_Body (N : Node_Id) is
1259       Loc          : constant Source_Ptr := Sloc (N);
1260       Body_Spec    : constant Node_Id    := Specification (N);
1261       Body_Id      : Entity_Id           := Defining_Entity (Body_Spec);
1262       Prev_Id      : constant Entity_Id  := Current_Entity_In_Scope (Body_Id);
1263       Body_Deleted : constant Boolean    := False;
1264       Conformant   : Boolean;
1265       HSS          : Node_Id;
1266       Missing_Ret  : Boolean;
1267       P_Ent        : Entity_Id;
1268       Prot_Typ     : Entity_Id := Empty;
1269       Spec_Id      : Entity_Id;
1270       Spec_Decl    : Node_Id   := Empty;
1271
1272       Last_Real_Spec_Entity : Entity_Id := Empty;
1273       --  When we analyze a separate spec, the entity chain ends up containing
1274       --  the formals, as well as any itypes generated during analysis of the
1275       --  default expressions for parameters, or the arguments of associated
1276       --  precondition/postcondition pragmas (which are analyzed in the context
1277       --  of the spec since they have visibility on formals).
1278       --
1279       --  These entities belong with the spec and not the body. However we do
1280       --  the analysis of the body in the context of the spec (again to obtain
1281       --  visibility to the formals), and all the entities generated during
1282       --  this analysis end up also chained to the entity chain of the spec.
1283       --  But they really belong to the body, and there is circuitry to move
1284       --  them from the spec to the body.
1285       --
1286       --  However, when we do this move, we don't want to move the real spec
1287       --  entities (first para above) to the body. The Last_Real_Spec_Entity
1288       --  variable points to the last real spec entity, so we only move those
1289       --  chained beyond that point. It is initialized to Empty to deal with
1290       --  the case where there is no separate spec.
1291
1292       procedure Check_Anonymous_Return;
1293       --  (Ada 2005): if a function returns an access type that denotes a task,
1294       --  or a type that contains tasks, we must create a master entity for
1295       --  the anonymous type, which typically will be used in an allocator
1296       --  in the body of the function.
1297
1298       procedure Check_Inline_Pragma (Spec : in out Node_Id);
1299       --  Look ahead to recognize a pragma that may appear after the body.
1300       --  If there is a previous spec, check that it appears in the same
1301       --  declarative part. If the pragma is Inline_Always, perform inlining
1302       --  unconditionally, otherwise only if Front_End_Inlining is requested.
1303       --  If the body acts as a spec, and inlining is required, we create a
1304       --  subprogram declaration for it, in order to attach the body to inline.
1305       --  If pragma does not appear after the body, check whether there is
1306       --  an inline pragma before any local declarations.
1307
1308       procedure Set_Trivial_Subprogram (N : Node_Id);
1309       --  Sets the Is_Trivial_Subprogram flag in both spec and body of the
1310       --  subprogram whose body is being analyzed. N is the statement node
1311       --  causing the flag to be set, if the following statement is a return
1312       --  of an entity, we mark the entity as set in source to suppress any
1313       --  warning on the stylized use of function stubs with a dummy return.
1314
1315       procedure Verify_Overriding_Indicator;
1316       --  If there was a previous spec, the entity has been entered in the
1317       --  current scope previously. If the body itself carries an overriding
1318       --  indicator, check that it is consistent with the known status of the
1319       --  entity.
1320
1321       ----------------------------
1322       -- Check_Anonymous_Return --
1323       ----------------------------
1324
1325       procedure Check_Anonymous_Return is
1326          Decl : Node_Id;
1327          Scop : Entity_Id;
1328
1329       begin
1330          if Present (Spec_Id) then
1331             Scop := Spec_Id;
1332          else
1333             Scop := Body_Id;
1334          end if;
1335
1336          if Ekind (Scop) = E_Function
1337            and then Ekind (Etype (Scop)) = E_Anonymous_Access_Type
1338            and then Has_Task (Designated_Type (Etype (Scop)))
1339            and then Expander_Active
1340          then
1341             Decl :=
1342               Make_Object_Declaration (Loc,
1343                 Defining_Identifier =>
1344                   Make_Defining_Identifier (Loc, Name_uMaster),
1345                 Constant_Present => True,
1346                 Object_Definition =>
1347                   New_Reference_To (RTE (RE_Master_Id), Loc),
1348                 Expression =>
1349                   Make_Explicit_Dereference (Loc,
1350                     New_Reference_To (RTE (RE_Current_Master), Loc)));
1351
1352             if Present (Declarations (N)) then
1353                Prepend (Decl, Declarations (N));
1354             else
1355                Set_Declarations (N, New_List (Decl));
1356             end if;
1357
1358             Set_Master_Id (Etype (Scop), Defining_Identifier (Decl));
1359             Set_Has_Master_Entity (Scop);
1360          end if;
1361       end Check_Anonymous_Return;
1362
1363       -------------------------
1364       -- Check_Inline_Pragma --
1365       -------------------------
1366
1367       procedure Check_Inline_Pragma (Spec : in out Node_Id) is
1368          Prag  : Node_Id;
1369          Plist : List_Id;
1370
1371          function Is_Inline_Pragma (N : Node_Id) return Boolean;
1372          --  Simple predicate, used twice.
1373
1374          -----------------------
1375          --  Is_Inline_Pragma --
1376          -----------------------
1377
1378          function Is_Inline_Pragma (N : Node_Id) return Boolean is
1379          begin
1380             return
1381               Nkind (N) = N_Pragma
1382                 and then
1383                    (Pragma_Name (N) = Name_Inline_Always
1384                      or else
1385                       (Front_End_Inlining
1386                         and then Pragma_Name (N) = Name_Inline))
1387                 and then
1388                    Chars
1389                      (Expression (First (Pragma_Argument_Associations (N))))
1390                         = Chars (Body_Id);
1391          end Is_Inline_Pragma;
1392
1393       --  Start of processing for Check_Inline_Pragma
1394
1395       begin
1396          if not Expander_Active then
1397             return;
1398          end if;
1399
1400          if Is_List_Member (N)
1401            and then Present (Next (N))
1402            and then Is_Inline_Pragma (Next (N))
1403          then
1404             Prag := Next (N);
1405
1406          elsif Nkind (N) /= N_Subprogram_Body_Stub
1407            and then Present (Declarations (N))
1408            and then Is_Inline_Pragma (First (Declarations (N)))
1409          then
1410             Prag := First (Declarations (N));
1411
1412          else
1413             Prag := Empty;
1414          end if;
1415
1416          if Present (Prag) then
1417             if Present (Spec_Id) then
1418                if List_Containing (N) =
1419                  List_Containing (Unit_Declaration_Node (Spec_Id))
1420                then
1421                   Analyze (Prag);
1422                end if;
1423
1424             else
1425                --  Create a subprogram declaration, to make treatment uniform
1426
1427                declare
1428                   Subp : constant Entity_Id :=
1429                     Make_Defining_Identifier (Loc, Chars (Body_Id));
1430                   Decl : constant Node_Id :=
1431                     Make_Subprogram_Declaration (Loc,
1432                       Specification =>  New_Copy_Tree (Specification (N)));
1433                begin
1434                   Set_Defining_Unit_Name (Specification (Decl), Subp);
1435
1436                   if Present (First_Formal (Body_Id)) then
1437                      Plist := Copy_Parameter_List (Body_Id);
1438                      Set_Parameter_Specifications
1439                        (Specification (Decl), Plist);
1440                   end if;
1441
1442                   Insert_Before (N, Decl);
1443                   Analyze (Decl);
1444                   Analyze (Prag);
1445                   Set_Has_Pragma_Inline (Subp);
1446
1447                   if Pragma_Name (Prag) = Name_Inline_Always then
1448                      Set_Is_Inlined (Subp);
1449                      Set_Has_Pragma_Inline_Always (Subp);
1450                   end if;
1451
1452                   Spec := Subp;
1453                end;
1454             end if;
1455          end if;
1456       end Check_Inline_Pragma;
1457
1458       ----------------------------
1459       -- Set_Trivial_Subprogram --
1460       ----------------------------
1461
1462       procedure Set_Trivial_Subprogram (N : Node_Id) is
1463          Nxt : constant Node_Id := Next (N);
1464
1465       begin
1466          Set_Is_Trivial_Subprogram (Body_Id);
1467
1468          if Present (Spec_Id) then
1469             Set_Is_Trivial_Subprogram (Spec_Id);
1470          end if;
1471
1472          if Present (Nxt)
1473            and then Nkind (Nxt) = N_Simple_Return_Statement
1474            and then No (Next (Nxt))
1475            and then Present (Expression (Nxt))
1476            and then Is_Entity_Name (Expression (Nxt))
1477          then
1478             Set_Never_Set_In_Source (Entity (Expression (Nxt)), False);
1479          end if;
1480       end Set_Trivial_Subprogram;
1481
1482       ---------------------------------
1483       -- Verify_Overriding_Indicator --
1484       ---------------------------------
1485
1486       procedure Verify_Overriding_Indicator is
1487       begin
1488          if Must_Override (Body_Spec) then
1489             if Nkind (Spec_Id) = N_Defining_Operator_Symbol
1490               and then  Operator_Matches_Spec (Spec_Id, Spec_Id)
1491             then
1492                null;
1493
1494             elsif not Is_Overriding_Operation (Spec_Id) then
1495                Error_Msg_NE
1496                  ("subprogram& is not overriding", Body_Spec, Spec_Id);
1497             end if;
1498
1499          elsif Must_Not_Override (Body_Spec) then
1500             if Is_Overriding_Operation (Spec_Id) then
1501                Error_Msg_NE
1502                  ("subprogram& overrides inherited operation",
1503                   Body_Spec, Spec_Id);
1504
1505             elsif Nkind (Spec_Id) = N_Defining_Operator_Symbol
1506               and then  Operator_Matches_Spec (Spec_Id, Spec_Id)
1507             then
1508                Error_Msg_NE
1509                  ("subprogram & overrides predefined operator ",
1510                     Body_Spec, Spec_Id);
1511
1512             --  If this is not a primitive operation the overriding indicator
1513             --  is altogether illegal.
1514
1515             elsif not Is_Primitive (Spec_Id) then
1516                Error_Msg_N ("overriding indicator only allowed " &
1517                 "if subprogram is primitive",
1518                 Body_Spec);
1519             end if;
1520          end if;
1521       end Verify_Overriding_Indicator;
1522
1523    --  Start of processing for Analyze_Subprogram_Body
1524
1525    begin
1526       if Debug_Flag_C then
1527          Write_Str ("====  Compiling subprogram body ");
1528          Write_Name (Chars (Body_Id));
1529          Write_Str (" from ");
1530          Write_Location (Loc);
1531          Write_Eol;
1532       end if;
1533
1534       Trace_Scope (N, Body_Id, " Analyze subprogram: ");
1535
1536       --  Generic subprograms are handled separately. They always have a
1537       --  generic specification. Determine whether current scope has a
1538       --  previous declaration.
1539
1540       --  If the subprogram body is defined within an instance of the same
1541       --  name, the instance appears as a package renaming, and will be hidden
1542       --  within the subprogram.
1543
1544       if Present (Prev_Id)
1545         and then not Is_Overloadable (Prev_Id)
1546         and then (Nkind (Parent (Prev_Id)) /= N_Package_Renaming_Declaration
1547                    or else Comes_From_Source (Prev_Id))
1548       then
1549          if Is_Generic_Subprogram (Prev_Id) then
1550             Spec_Id := Prev_Id;
1551             Set_Is_Compilation_Unit (Body_Id, Is_Compilation_Unit (Spec_Id));
1552             Set_Is_Child_Unit       (Body_Id, Is_Child_Unit       (Spec_Id));
1553
1554             Analyze_Generic_Subprogram_Body (N, Spec_Id);
1555             return;
1556
1557          else
1558             --  Previous entity conflicts with subprogram name. Attempting to
1559             --  enter name will post error.
1560
1561             Enter_Name (Body_Id);
1562             return;
1563          end if;
1564
1565       --  Non-generic case, find the subprogram declaration, if one was seen,
1566       --  or enter new overloaded entity in the current scope. If the
1567       --  Current_Entity is the Body_Id itself, the unit is being analyzed as
1568       --  part of the context of one of its subunits. No need to redo the
1569       --  analysis.
1570
1571       elsif Prev_Id = Body_Id
1572         and then Has_Completion (Body_Id)
1573       then
1574          return;
1575
1576       else
1577          Body_Id := Analyze_Subprogram_Specification (Body_Spec);
1578
1579          if Nkind (N) = N_Subprogram_Body_Stub
1580            or else No (Corresponding_Spec (N))
1581          then
1582             Spec_Id := Find_Corresponding_Spec (N);
1583
1584             --  If this is a duplicate body, no point in analyzing it
1585
1586             if Error_Posted (N) then
1587                return;
1588             end if;
1589
1590             --  A subprogram body should cause freezing of its own declaration,
1591             --  but if there was no previous explicit declaration, then the
1592             --  subprogram will get frozen too late (there may be code within
1593             --  the body that depends on the subprogram having been frozen,
1594             --  such as uses of extra formals), so we force it to be frozen
1595             --  here. Same holds if the body and spec are compilation units.
1596
1597             if No (Spec_Id) then
1598                Freeze_Before (N, Body_Id);
1599
1600             elsif Nkind (Parent (N)) = N_Compilation_Unit then
1601                Freeze_Before (N, Spec_Id);
1602             end if;
1603          else
1604             Spec_Id := Corresponding_Spec (N);
1605          end if;
1606       end if;
1607
1608       --  Do not inline any subprogram that contains nested subprograms, since
1609       --  the backend inlining circuit seems to generate uninitialized
1610       --  references in this case. We know this happens in the case of front
1611       --  end ZCX support, but it also appears it can happen in other cases as
1612       --  well. The backend often rejects attempts to inline in the case of
1613       --  nested procedures anyway, so little if anything is lost by this.
1614       --  Note that this is test is for the benefit of the back-end. There is
1615       --  a separate test for front-end inlining that also rejects nested
1616       --  subprograms.
1617
1618       --  Do not do this test if errors have been detected, because in some
1619       --  error cases, this code blows up, and we don't need it anyway if
1620       --  there have been errors, since we won't get to the linker anyway.
1621
1622       if Comes_From_Source (Body_Id)
1623         and then Serious_Errors_Detected = 0
1624       then
1625          P_Ent := Body_Id;
1626          loop
1627             P_Ent := Scope (P_Ent);
1628             exit when No (P_Ent) or else P_Ent = Standard_Standard;
1629
1630             if Is_Subprogram (P_Ent) then
1631                Set_Is_Inlined (P_Ent, False);
1632
1633                if Comes_From_Source (P_Ent)
1634                  and then Has_Pragma_Inline (P_Ent)
1635                then
1636                   Cannot_Inline
1637                     ("cannot inline& (nested subprogram)?",
1638                      N, P_Ent);
1639                end if;
1640             end if;
1641          end loop;
1642       end if;
1643
1644       Check_Inline_Pragma (Spec_Id);
1645
1646       --  Case of fully private operation in the body of the protected type.
1647       --  We must create a declaration for the subprogram, in order to attach
1648       --  the protected subprogram that will be used in internal calls.
1649
1650       if No (Spec_Id)
1651         and then Comes_From_Source (N)
1652         and then Is_Protected_Type (Current_Scope)
1653       then
1654          declare
1655             Decl     : Node_Id;
1656             Plist    : List_Id;
1657             Formal   : Entity_Id;
1658             New_Spec : Node_Id;
1659
1660          begin
1661             Formal := First_Formal (Body_Id);
1662
1663             --  The protected operation always has at least one formal, namely
1664             --  the object itself, but it is only placed in the parameter list
1665             --  if expansion is enabled.
1666
1667             if Present (Formal)
1668               or else Expander_Active
1669             then
1670                Plist := Copy_Parameter_List (Body_Id);
1671             else
1672                Plist := No_List;
1673             end if;
1674
1675             if Nkind (Body_Spec) = N_Procedure_Specification then
1676                New_Spec :=
1677                  Make_Procedure_Specification (Loc,
1678                     Defining_Unit_Name =>
1679                       Make_Defining_Identifier (Sloc (Body_Id),
1680                         Chars => Chars (Body_Id)),
1681                     Parameter_Specifications => Plist);
1682             else
1683                New_Spec :=
1684                  Make_Function_Specification (Loc,
1685                     Defining_Unit_Name =>
1686                       Make_Defining_Identifier (Sloc (Body_Id),
1687                         Chars => Chars (Body_Id)),
1688                     Parameter_Specifications => Plist,
1689                     Result_Definition =>
1690                       New_Occurrence_Of (Etype (Body_Id), Loc));
1691             end if;
1692
1693             Decl :=
1694               Make_Subprogram_Declaration (Loc,
1695                 Specification => New_Spec);
1696             Insert_Before (N, Decl);
1697             Spec_Id := Defining_Unit_Name (New_Spec);
1698
1699             --  Indicate that the entity comes from source, to ensure that
1700             --  cross-reference information is properly generated. The body
1701             --  itself is rewritten during expansion, and the body entity will
1702             --  not appear in calls to the operation.
1703
1704             Set_Comes_From_Source (Spec_Id, True);
1705             Analyze (Decl);
1706             Set_Has_Completion (Spec_Id);
1707             Set_Convention (Spec_Id, Convention_Protected);
1708          end;
1709
1710       elsif Present (Spec_Id) then
1711          Spec_Decl := Unit_Declaration_Node (Spec_Id);
1712          Verify_Overriding_Indicator;
1713
1714          --  In general, the spec will be frozen when we start analyzing the
1715          --  body. However, for internally generated operations, such as
1716          --  wrapper functions for inherited operations with controlling
1717          --  results, the spec may not have been frozen by the time we
1718          --  expand the freeze actions that include the bodies. In particular,
1719          --  extra formals for accessibility or for return-in-place may need
1720          --  to be generated. Freeze nodes, if any, are inserted before the
1721          --  current body.
1722
1723          if not Is_Frozen (Spec_Id)
1724            and then Expander_Active
1725          then
1726             --  Force the generation of its freezing node to ensure proper
1727             --  management of access types in the backend.
1728
1729             --  This is definitely needed for some cases, but it is not clear
1730             --  why, to be investigated further???
1731
1732             Set_Has_Delayed_Freeze (Spec_Id);
1733             Insert_Actions (N, Freeze_Entity (Spec_Id, Loc));
1734          end if;
1735       end if;
1736
1737       --  Place subprogram on scope stack, and make formals visible. If there
1738       --  is a spec, the visible entity remains that of the spec.
1739
1740       if Present (Spec_Id) then
1741          Generate_Reference (Spec_Id, Body_Id, 'b', Set_Ref => False);
1742
1743          if Is_Child_Unit (Spec_Id) then
1744             Generate_Reference (Spec_Id, Scope (Spec_Id), 'k', False);
1745          end if;
1746
1747          if Style_Check then
1748             Style.Check_Identifier (Body_Id, Spec_Id);
1749          end if;
1750
1751          Set_Is_Compilation_Unit (Body_Id, Is_Compilation_Unit (Spec_Id));
1752          Set_Is_Child_Unit       (Body_Id, Is_Child_Unit       (Spec_Id));
1753
1754          if Is_Abstract_Subprogram (Spec_Id) then
1755             Error_Msg_N ("an abstract subprogram cannot have a body", N);
1756             return;
1757
1758          else
1759             Set_Convention (Body_Id, Convention (Spec_Id));
1760             Set_Has_Completion (Spec_Id);
1761
1762             if Is_Protected_Type (Scope (Spec_Id)) then
1763                Prot_Typ := Scope (Spec_Id);
1764             end if;
1765
1766             --  If this is a body generated for a renaming, do not check for
1767             --  full conformance. The check is redundant, because the spec of
1768             --  the body is a copy of the spec in the renaming declaration,
1769             --  and the test can lead to spurious errors on nested defaults.
1770
1771             if Present (Spec_Decl)
1772               and then not Comes_From_Source (N)
1773               and then
1774                 (Nkind (Original_Node (Spec_Decl)) =
1775                                         N_Subprogram_Renaming_Declaration
1776                    or else (Present (Corresponding_Body (Spec_Decl))
1777                               and then
1778                                 Nkind (Unit_Declaration_Node
1779                                         (Corresponding_Body (Spec_Decl))) =
1780                                            N_Subprogram_Renaming_Declaration))
1781             then
1782                Conformant := True;
1783
1784             else
1785                Check_Conformance
1786                  (Body_Id, Spec_Id,
1787                   Fully_Conformant, True, Conformant, Body_Id);
1788             end if;
1789
1790             --  If the body is not fully conformant, we have to decide if we
1791             --  should analyze it or not. If it has a really messed up profile
1792             --  then we probably should not analyze it, since we will get too
1793             --  many bogus messages.
1794
1795             --  Our decision is to go ahead in the non-fully conformant case
1796             --  only if it is at least mode conformant with the spec. Note
1797             --  that the call to Check_Fully_Conformant has issued the proper
1798             --  error messages to complain about the lack of conformance.
1799
1800             if not Conformant
1801               and then not Mode_Conformant (Body_Id, Spec_Id)
1802             then
1803                return;
1804             end if;
1805          end if;
1806
1807          if Spec_Id /= Body_Id then
1808             Reference_Body_Formals (Spec_Id, Body_Id);
1809          end if;
1810
1811          if Nkind (N) /= N_Subprogram_Body_Stub then
1812             Set_Corresponding_Spec (N, Spec_Id);
1813
1814             --  Ada 2005 (AI-345): If the operation is a primitive operation
1815             --  of a concurrent type, the type of the first parameter has been
1816             --  replaced with the corresponding record, which is the proper
1817             --  run-time structure to use. However, within the body there may
1818             --  be uses of the formals that depend on primitive operations
1819             --  of the type (in particular calls in prefixed form) for which
1820             --  we need the original concurrent type. The operation may have
1821             --  several controlling formals, so the replacement must be done
1822             --  for all of them.
1823
1824             if Comes_From_Source (Spec_Id)
1825               and then Present (First_Entity (Spec_Id))
1826               and then Ekind (Etype (First_Entity (Spec_Id))) = E_Record_Type
1827               and then Is_Tagged_Type (Etype (First_Entity (Spec_Id)))
1828               and then
1829                 Present (Abstract_Interfaces (Etype (First_Entity (Spec_Id))))
1830               and then
1831                 Present
1832                   (Corresponding_Concurrent_Type
1833                      (Etype (First_Entity (Spec_Id))))
1834             then
1835                declare
1836                   Typ  : constant Entity_Id := Etype (First_Entity (Spec_Id));
1837                   Form : Entity_Id;
1838
1839                begin
1840                   Form := First_Formal (Spec_Id);
1841                   while Present (Form) loop
1842                      if Etype (Form) = Typ then
1843                         Set_Etype (Form, Corresponding_Concurrent_Type (Typ));
1844                      end if;
1845
1846                      Next_Formal (Form);
1847                   end loop;
1848                end;
1849             end if;
1850
1851             --  Make the formals visible, and place subprogram on scope stack.
1852             --  This is also the point at which we set Last_Real_Spec_Entity
1853             --  to mark the entities which will not be moved to the body.
1854
1855             Install_Formals (Spec_Id);
1856             Last_Real_Spec_Entity := Last_Entity (Spec_Id);
1857             Push_Scope (Spec_Id);
1858
1859             --  Make sure that the subprogram is immediately visible. For
1860             --  child units that have no separate spec this is indispensable.
1861             --  Otherwise it is safe albeit redundant.
1862
1863             Set_Is_Immediately_Visible (Spec_Id);
1864          end if;
1865
1866          Set_Corresponding_Body (Unit_Declaration_Node (Spec_Id), Body_Id);
1867          Set_Ekind (Body_Id, E_Subprogram_Body);
1868          Set_Scope (Body_Id, Scope (Spec_Id));
1869          Set_Is_Obsolescent (Body_Id, Is_Obsolescent (Spec_Id));
1870
1871       --  Case of subprogram body with no previous spec
1872
1873       else
1874          if Style_Check
1875            and then Comes_From_Source (Body_Id)
1876            and then not Suppress_Style_Checks (Body_Id)
1877            and then not In_Instance
1878          then
1879             Style.Body_With_No_Spec (N);
1880          end if;
1881
1882          New_Overloaded_Entity (Body_Id);
1883
1884          if Nkind (N) /= N_Subprogram_Body_Stub then
1885             Set_Acts_As_Spec (N);
1886             Generate_Definition (Body_Id);
1887             Generate_Reference
1888               (Body_Id, Body_Id, 'b', Set_Ref => False, Force => True);
1889             Generate_Reference_To_Formals (Body_Id);
1890             Install_Formals (Body_Id);
1891             Push_Scope (Body_Id);
1892          end if;
1893       end if;
1894
1895       --  If the return type is an anonymous access type whose designated type
1896       --  is the limited view of a class-wide type and the non-limited view is
1897       --  available, update the return type accordingly.
1898
1899       if Ada_Version >= Ada_05
1900         and then Comes_From_Source (N)
1901       then
1902          declare
1903             Etyp : Entity_Id;
1904             Rtyp : Entity_Id;
1905
1906          begin
1907             Rtyp := Etype (Current_Scope);
1908
1909             if Ekind (Rtyp) = E_Anonymous_Access_Type then
1910                Etyp := Directly_Designated_Type (Rtyp);
1911
1912                if Is_Class_Wide_Type (Etyp)
1913                  and then From_With_Type (Etyp)
1914                then
1915                   Set_Directly_Designated_Type
1916                     (Etype (Current_Scope), Available_View (Etyp));
1917                end if;
1918             end if;
1919          end;
1920       end if;
1921
1922       --  If this is the proper body of a stub, we must verify that the stub
1923       --  conforms to the body, and to the previous spec if one was present.
1924       --  we know already that the body conforms to that spec. This test is
1925       --  only required for subprograms that come from source.
1926
1927       if Nkind (Parent (N)) = N_Subunit
1928         and then Comes_From_Source (N)
1929         and then not Error_Posted (Body_Id)
1930         and then Nkind (Corresponding_Stub (Parent (N))) =
1931                                                 N_Subprogram_Body_Stub
1932       then
1933          declare
1934             Old_Id : constant Entity_Id :=
1935                        Defining_Entity
1936                          (Specification (Corresponding_Stub (Parent (N))));
1937
1938             Conformant : Boolean := False;
1939
1940          begin
1941             if No (Spec_Id) then
1942                Check_Fully_Conformant (Body_Id, Old_Id);
1943
1944             else
1945                Check_Conformance
1946                  (Body_Id, Old_Id, Fully_Conformant, False, Conformant);
1947
1948                if not Conformant then
1949
1950                   --  The stub was taken to be a new declaration. Indicate
1951                   --  that it lacks a body.
1952
1953                   Set_Has_Completion (Old_Id, False);
1954                end if;
1955             end if;
1956          end;
1957       end if;
1958
1959       Set_Has_Completion (Body_Id);
1960       Check_Eliminated (Body_Id);
1961
1962       if Nkind (N) = N_Subprogram_Body_Stub then
1963          return;
1964
1965       elsif Present (Spec_Id)
1966         and then Expander_Active
1967         and then
1968           (Has_Pragma_Inline_Always (Spec_Id)
1969              or else (Has_Pragma_Inline (Spec_Id) and Front_End_Inlining))
1970       then
1971          Build_Body_To_Inline (N, Spec_Id);
1972       end if;
1973
1974       --  Ada 2005 (AI-262): In library subprogram bodies, after the analysis
1975       --  if its specification we have to install the private withed units.
1976       --  This holds for child units as well.
1977
1978       if Is_Compilation_Unit (Body_Id)
1979         or else Nkind (Parent (N)) = N_Compilation_Unit
1980       then
1981          Install_Private_With_Clauses (Body_Id);
1982       end if;
1983
1984       Check_Anonymous_Return;
1985
1986       --  Set the Protected_Formal field of each extra formal of the protected
1987       --  subprogram to reference the corresponding extra formal of the
1988       --  subprogram that implements it. For regular formals this occurs when
1989       --  the protected subprogram's declaration is expanded, but the extra
1990       --  formals don't get created until the subprogram is frozen. We need to
1991       --  do this before analyzing the protected subprogram's body so that any
1992       --  references to the original subprogram's extra formals will be changed
1993       --  refer to the implementing subprogram's formals (see Expand_Formal).
1994
1995       if Present (Spec_Id)
1996         and then Is_Protected_Type (Scope (Spec_Id))
1997         and then Present (Protected_Body_Subprogram (Spec_Id))
1998       then
1999          declare
2000             Impl_Subp       : constant Entity_Id :=
2001                                 Protected_Body_Subprogram (Spec_Id);
2002             Prot_Ext_Formal : Entity_Id := Extra_Formals (Spec_Id);
2003             Impl_Ext_Formal : Entity_Id := Extra_Formals (Impl_Subp);
2004          begin
2005             while Present (Prot_Ext_Formal) loop
2006                pragma Assert (Present (Impl_Ext_Formal));
2007                Set_Protected_Formal (Prot_Ext_Formal, Impl_Ext_Formal);
2008                Next_Formal_With_Extras (Prot_Ext_Formal);
2009                Next_Formal_With_Extras (Impl_Ext_Formal);
2010             end loop;
2011          end;
2012       end if;
2013
2014       --  Now we can go on to analyze the body
2015
2016       HSS := Handled_Statement_Sequence (N);
2017       Set_Actual_Subtypes (N, Current_Scope);
2018
2019       --  Deal with preconditions and postconditions
2020
2021       Process_PPCs (N, Spec_Id, Body_Id);
2022
2023       --  Add a declaration for the Protection object, renaming declarations
2024       --  for discriminals and privals and finally a declaration for the entry
2025       --  family index (if applicable). This form of early expansion is done
2026       --  when the Expander is active because Install_Private_Data_Declarations
2027       --  references entities which were created during regular expansion.
2028
2029       if Expander_Active
2030         and then Comes_From_Source (N)
2031         and then Present (Prot_Typ)
2032         and then Present (Spec_Id)
2033         and then not Is_Eliminated (Spec_Id)
2034       then
2035          Install_Private_Data_Declarations
2036            (Sloc (N), Spec_Id, Prot_Typ, N, Declarations (N));
2037       end if;
2038
2039       --  Analyze the declarations (this call will analyze the precondition
2040       --  Check pragmas we prepended to the list, as well as the declaration
2041       --  of the _Postconditions procedure).
2042
2043       Analyze_Declarations (Declarations (N));
2044
2045       --  Check completion, and analyze the statements
2046
2047       Check_Completion;
2048       Analyze (HSS);
2049
2050       --  Deal with end of scope processing for the body
2051
2052       Process_End_Label (HSS, 't', Current_Scope);
2053       End_Scope;
2054       Check_Subprogram_Order (N);
2055       Set_Analyzed (Body_Id);
2056
2057       --  If we have a separate spec, then the analysis of the declarations
2058       --  caused the entities in the body to be chained to the spec id, but
2059       --  we want them chained to the body id. Only the formal parameters
2060       --  end up chained to the spec id in this case.
2061
2062       if Present (Spec_Id) then
2063
2064          --  We must conform to the categorization of our spec
2065
2066          Validate_Categorization_Dependency (N, Spec_Id);
2067
2068          --  And if this is a child unit, the parent units must conform
2069
2070          if Is_Child_Unit (Spec_Id) then
2071             Validate_Categorization_Dependency
2072               (Unit_Declaration_Node (Spec_Id), Spec_Id);
2073          end if;
2074
2075          --  Here is where we move entities from the spec to the body
2076
2077          --  Case where there are entities that stay with the spec
2078
2079          if Present (Last_Real_Spec_Entity) then
2080
2081             --  No body entities (happens when the only real spec entities
2082             --  come from precondition and postcondition pragmas)
2083
2084             if No (Last_Entity (Body_Id)) then
2085                Set_First_Entity
2086                  (Body_Id, Next_Entity (Last_Real_Spec_Entity));
2087
2088             --  Body entities present (formals), so chain stuff past them
2089
2090             else
2091                Set_Next_Entity
2092                  (Last_Entity (Body_Id), Next_Entity (Last_Real_Spec_Entity));
2093             end if;
2094
2095             Set_Next_Entity (Last_Real_Spec_Entity, Empty);
2096             Set_Last_Entity (Body_Id, Last_Entity (Spec_Id));
2097             Set_Last_Entity (Spec_Id, Last_Real_Spec_Entity);
2098
2099          --  Case where there are no spec entities, in this case there can
2100          --  be no body entities either, so just move everything.
2101
2102          else
2103             pragma Assert (No (Last_Entity (Body_Id)));
2104             Set_First_Entity (Body_Id, First_Entity (Spec_Id));
2105             Set_Last_Entity  (Body_Id, Last_Entity (Spec_Id));
2106             Set_First_Entity (Spec_Id, Empty);
2107             Set_Last_Entity  (Spec_Id, Empty);
2108          end if;
2109       end if;
2110
2111       --  If function, check return statements
2112
2113       if Nkind (Body_Spec) = N_Function_Specification then
2114          declare
2115             Id : Entity_Id;
2116
2117          begin
2118             if Present (Spec_Id) then
2119                Id := Spec_Id;
2120             else
2121                Id := Body_Id;
2122             end if;
2123
2124             if Return_Present (Id) then
2125                Check_Returns (HSS, 'F', Missing_Ret);
2126
2127                if Missing_Ret then
2128                   Set_Has_Missing_Return (Id);
2129                end if;
2130
2131             elsif not Is_Machine_Code_Subprogram (Id)
2132               and then not Body_Deleted
2133             then
2134                Error_Msg_N ("missing RETURN statement in function body", N);
2135             end if;
2136          end;
2137
2138       --  If procedure with No_Return, check returns
2139
2140       elsif Nkind (Body_Spec) = N_Procedure_Specification
2141         and then Present (Spec_Id)
2142         and then No_Return (Spec_Id)
2143       then
2144          Check_Returns (HSS, 'P', Missing_Ret, Spec_Id);
2145       end if;
2146
2147       --  Now we are going to check for variables that are never modified in
2148       --  the body of the procedure. But first we deal with a special case
2149       --  where we want to modify this check. If the body of the subprogram
2150       --  starts with a raise statement or its equivalent, or if the body
2151       --  consists entirely of a null statement, then it is pretty obvious
2152       --  that it is OK to not reference the parameters. For example, this
2153       --  might be the following common idiom for a stubbed function:
2154       --  statement of the procedure raises an exception. In particular this
2155       --  deals with the common idiom of a stubbed function, which might
2156       --  appear as something like
2157
2158       --     function F (A : Integer) return Some_Type;
2159       --        X : Some_Type;
2160       --     begin
2161       --        raise Program_Error;
2162       --        return X;
2163       --     end F;
2164
2165       --  Here the purpose of X is simply to satisfy the annoying requirement
2166       --  in Ada that there be at least one return, and we certainly do not
2167       --  want to go posting warnings on X that it is not initialized! On
2168       --  the other hand, if X is entirely unreferenced that should still
2169       --  get a warning.
2170
2171       --  What we do is to detect these cases, and if we find them, flag the
2172       --  subprogram as being Is_Trivial_Subprogram and then use that flag to
2173       --  suppress unwanted warnings. For the case of the function stub above
2174       --  we have a special test to set X as apparently assigned to suppress
2175       --  the warning.
2176
2177       declare
2178          Stm : Node_Id;
2179
2180       begin
2181          --  Skip initial labels (for one thing this occurs when we are in
2182          --  front end ZCX mode, but in any case it is irrelevant), and also
2183          --  initial Push_xxx_Error_Label nodes, which are also irrelevant.
2184
2185          Stm := First (Statements (HSS));
2186          while Nkind (Stm) = N_Label
2187            or else Nkind (Stm) in N_Push_xxx_Label
2188          loop
2189             Next (Stm);
2190          end loop;
2191
2192          --  Do the test on the original statement before expansion
2193
2194          declare
2195             Ostm : constant Node_Id := Original_Node (Stm);
2196
2197          begin
2198             --  If explicit raise statement, turn on flag
2199
2200             if Nkind (Ostm) = N_Raise_Statement then
2201                Set_Trivial_Subprogram (Stm);
2202
2203             --  If null statement, and no following statements, turn on flag
2204
2205             elsif Nkind (Stm) = N_Null_Statement
2206               and then Comes_From_Source (Stm)
2207               and then No (Next (Stm))
2208             then
2209                Set_Trivial_Subprogram (Stm);
2210
2211             --  Check for explicit call cases which likely raise an exception
2212
2213             elsif Nkind (Ostm) = N_Procedure_Call_Statement then
2214                if Is_Entity_Name (Name (Ostm)) then
2215                   declare
2216                      Ent : constant Entity_Id := Entity (Name (Ostm));
2217
2218                   begin
2219                      --  If the procedure is marked No_Return, then likely it
2220                      --  raises an exception, but in any case it is not coming
2221                      --  back here, so turn on the flag.
2222
2223                      if Ekind (Ent) = E_Procedure
2224                        and then No_Return (Ent)
2225                      then
2226                         Set_Trivial_Subprogram (Stm);
2227
2228                      --  If the procedure name is Raise_Exception, then also
2229                      --  assume that it raises an exception. The main target
2230                      --  here is Ada.Exceptions.Raise_Exception, but this name
2231                      --  is pretty evocative in any context! Note that the
2232                      --  procedure in Ada.Exceptions is not marked No_Return
2233                      --  because of the annoying case of the null exception Id
2234                      --  when operating in Ada 95 mode.
2235
2236                      elsif Chars (Ent) = Name_Raise_Exception then
2237                         Set_Trivial_Subprogram (Stm);
2238                      end if;
2239                   end;
2240                end if;
2241             end if;
2242          end;
2243       end;
2244
2245       --  Check for variables that are never modified
2246
2247       declare
2248          E1, E2 : Entity_Id;
2249
2250       begin
2251          --  If there is a separate spec, then transfer Never_Set_In_Source
2252          --  flags from out parameters to the corresponding entities in the
2253          --  body. The reason we do that is we want to post error flags on
2254          --  the body entities, not the spec entities.
2255
2256          if Present (Spec_Id) then
2257             E1 := First_Entity (Spec_Id);
2258             while Present (E1) loop
2259                if Ekind (E1) = E_Out_Parameter then
2260                   E2 := First_Entity (Body_Id);
2261                   while Present (E2) loop
2262                      exit when Chars (E1) = Chars (E2);
2263                      Next_Entity (E2);
2264                   end loop;
2265
2266                   if Present (E2) then
2267                      Set_Never_Set_In_Source (E2, Never_Set_In_Source (E1));
2268                   end if;
2269                end if;
2270
2271                Next_Entity (E1);
2272             end loop;
2273          end if;
2274
2275          --  Check references in body unless it was deleted. Note that the
2276          --  check of Body_Deleted here is not just for efficiency, it is
2277          --  necessary to avoid junk warnings on formal parameters.
2278
2279          if not Body_Deleted then
2280             Check_References (Body_Id);
2281          end if;
2282       end;
2283    end Analyze_Subprogram_Body;
2284
2285    ------------------------------------
2286    -- Analyze_Subprogram_Declaration --
2287    ------------------------------------
2288
2289    procedure Analyze_Subprogram_Declaration (N : Node_Id) is
2290       Designator : constant Entity_Id :=
2291                      Analyze_Subprogram_Specification (Specification (N));
2292       Scop       : constant Entity_Id := Current_Scope;
2293
2294    --  Start of processing for Analyze_Subprogram_Declaration
2295
2296    begin
2297       Generate_Definition (Designator);
2298
2299       --  Check for RCI unit subprogram declarations for illegal inlined
2300       --  subprograms and subprograms having access parameter or limited
2301       --  parameter without Read and Write attributes (RM E.2.3(12-13)).
2302
2303       Validate_RCI_Subprogram_Declaration (N);
2304
2305       Trace_Scope
2306         (N,
2307          Defining_Entity (N),
2308          " Analyze subprogram spec: ");
2309
2310       if Debug_Flag_C then
2311          Write_Str ("====  Compiling subprogram spec ");
2312          Write_Name (Chars (Designator));
2313          Write_Str (" from ");
2314          Write_Location (Sloc (N));
2315          Write_Eol;
2316       end if;
2317
2318       New_Overloaded_Entity (Designator);
2319       Check_Delayed_Subprogram (Designator);
2320
2321       --  Ada 2005 (AI-251): Abstract interface primitives must be abstract
2322       --  or null.
2323
2324       if Ada_Version >= Ada_05
2325         and then Comes_From_Source (N)
2326         and then Is_Dispatching_Operation (Designator)
2327       then
2328          declare
2329             E    : Entity_Id;
2330             Etyp : Entity_Id;
2331
2332          begin
2333             if Has_Controlling_Result (Designator) then
2334                Etyp := Etype (Designator);
2335
2336             else
2337                E := First_Entity (Designator);
2338                while Present (E)
2339                  and then Is_Formal (E)
2340                  and then not Is_Controlling_Formal (E)
2341                loop
2342                   Next_Entity (E);
2343                end loop;
2344
2345                Etyp := Etype (E);
2346             end if;
2347
2348             if Is_Access_Type (Etyp) then
2349                Etyp := Directly_Designated_Type (Etyp);
2350             end if;
2351
2352             if Is_Interface (Etyp)
2353               and then not Is_Abstract_Subprogram (Designator)
2354               and then not (Ekind (Designator) = E_Procedure
2355                               and then Null_Present (Specification (N)))
2356             then
2357                Error_Msg_Name_1 := Chars (Defining_Entity (N));
2358                Error_Msg_N
2359                  ("(Ada 2005) interface subprogram % must be abstract or null",
2360                   N);
2361             end if;
2362          end;
2363       end if;
2364
2365       --  What is the following code for, it used to be
2366
2367       --  ???   Set_Suppress_Elaboration_Checks
2368       --  ???     (Designator, Elaboration_Checks_Suppressed (Designator));
2369
2370       --  The following seems equivalent, but a bit dubious
2371
2372       if Elaboration_Checks_Suppressed (Designator) then
2373          Set_Kill_Elaboration_Checks (Designator);
2374       end if;
2375
2376       if Scop /= Standard_Standard
2377         and then not Is_Child_Unit (Designator)
2378       then
2379          Set_Categorization_From_Scope (Designator, Scop);
2380       else
2381          --  For a compilation unit, check for library-unit pragmas
2382
2383          Push_Scope (Designator);
2384          Set_Categorization_From_Pragmas (N);
2385          Validate_Categorization_Dependency (N, Designator);
2386          Pop_Scope;
2387       end if;
2388
2389       --  For a compilation unit, set body required. This flag will only be
2390       --  reset if a valid Import or Interface pragma is processed later on.
2391
2392       if Nkind (Parent (N)) = N_Compilation_Unit then
2393          Set_Body_Required (Parent (N), True);
2394
2395          if Ada_Version >= Ada_05
2396            and then Nkind (Specification (N)) = N_Procedure_Specification
2397            and then Null_Present (Specification (N))
2398          then
2399             Error_Msg_N
2400               ("null procedure cannot be declared at library level", N);
2401          end if;
2402       end if;
2403
2404       Generate_Reference_To_Formals (Designator);
2405       Check_Eliminated (Designator);
2406
2407       --  Ada 2005: if procedure is declared with "is null" qualifier,
2408       --  it requires no body.
2409
2410       if Nkind (Specification (N)) = N_Procedure_Specification
2411         and then Null_Present (Specification (N))
2412       then
2413          Set_Has_Completion (Designator);
2414          Set_Is_Inlined (Designator);
2415
2416          if Is_Protected_Type (Current_Scope) then
2417             Error_Msg_N
2418               ("protected operation cannot be a null procedure", N);
2419          end if;
2420       end if;
2421    end Analyze_Subprogram_Declaration;
2422
2423    --------------------------------------
2424    -- Analyze_Subprogram_Specification --
2425    --------------------------------------
2426
2427    --  Reminder: N here really is a subprogram specification (not a subprogram
2428    --  declaration). This procedure is called to analyze the specification in
2429    --  both subprogram bodies and subprogram declarations (specs).
2430
2431    function Analyze_Subprogram_Specification (N : Node_Id) return Entity_Id is
2432       Designator : constant Entity_Id := Defining_Entity (N);
2433       Formals    : constant List_Id   := Parameter_Specifications (N);
2434       Formal     : Entity_Id;
2435       Formal_Typ : Entity_Id;
2436
2437    --  Start of processing for Analyze_Subprogram_Specification
2438
2439    begin
2440       Generate_Definition (Designator);
2441
2442       if Nkind (N) = N_Function_Specification then
2443          Set_Ekind (Designator, E_Function);
2444          Set_Mechanism (Designator, Default_Mechanism);
2445
2446       else
2447          Set_Ekind (Designator, E_Procedure);
2448          Set_Etype (Designator, Standard_Void_Type);
2449       end if;
2450
2451       --  Introduce new scope for analysis of the formals and the return type
2452
2453       Set_Scope (Designator, Current_Scope);
2454
2455       if Present (Formals) then
2456          Push_Scope (Designator);
2457          Process_Formals (Formals, N);
2458
2459          --  Ada 2005 (AI-345): Allow the overriding of interface primitives
2460          --  by subprograms which belong to a concurrent type implementing an
2461          --  interface. Set the parameter type of each controlling formal to
2462          --  the corresponding record type.
2463
2464          if Ada_Version >= Ada_05 then
2465             Formal := First_Formal (Designator);
2466             while Present (Formal) loop
2467                Formal_Typ := Etype (Formal);
2468
2469                if (Ekind (Formal_Typ) = E_Protected_Type
2470                      or else Ekind (Formal_Typ) = E_Task_Type)
2471                  and then Present (Corresponding_Record_Type (Formal_Typ))
2472                  and then Present (Abstract_Interfaces
2473                                   (Corresponding_Record_Type (Formal_Typ)))
2474                then
2475                   Set_Etype (Formal,
2476                     Corresponding_Record_Type (Formal_Typ));
2477                end if;
2478
2479                Formal := Next_Formal (Formal);
2480             end loop;
2481          end if;
2482
2483          End_Scope;
2484
2485       elsif Nkind (N) = N_Function_Specification then
2486          Analyze_Return_Type (N);
2487       end if;
2488
2489       if Nkind (N) = N_Function_Specification then
2490          if Nkind (Designator) = N_Defining_Operator_Symbol then
2491             Valid_Operator_Definition (Designator);
2492          end if;
2493
2494          May_Need_Actuals (Designator);
2495
2496          --  Ada 2005 (AI-251): In case of primitives associated with abstract
2497          --  interface types the following error message will be reported later
2498          --  (see Analyze_Subprogram_Declaration).
2499
2500          if Is_Abstract_Type (Etype (Designator))
2501            and then not Is_Interface (Etype (Designator))
2502            and then Nkind (Parent (N)) /=
2503                       N_Abstract_Subprogram_Declaration
2504            and then
2505              (Nkind (Parent (N))) /= N_Formal_Abstract_Subprogram_Declaration
2506                 and then
2507                   (Nkind (Parent (N)) /= N_Subprogram_Renaming_Declaration
2508                      or else not Is_Entity_Name (Name (Parent (N)))
2509                      or else not Is_Abstract_Subprogram
2510                                     (Entity (Name (Parent (N)))))
2511          then
2512             Error_Msg_N
2513               ("function that returns abstract type must be abstract", N);
2514          end if;
2515       end if;
2516
2517       return Designator;
2518    end Analyze_Subprogram_Specification;
2519
2520    --------------------------
2521    -- Build_Body_To_Inline --
2522    --------------------------
2523
2524    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id) is
2525       Decl            : constant Node_Id := Unit_Declaration_Node (Subp);
2526       Original_Body   : Node_Id;
2527       Body_To_Analyze : Node_Id;
2528       Max_Size        : constant := 10;
2529       Stat_Count      : Integer := 0;
2530
2531       function Has_Excluded_Declaration (Decls : List_Id) return Boolean;
2532       --  Check for declarations that make inlining not worthwhile
2533
2534       function Has_Excluded_Statement   (Stats : List_Id) return Boolean;
2535       --  Check for statements that make inlining not worthwhile: any tasking
2536       --  statement, nested at any level. Keep track of total number of
2537       --  elementary statements, as a measure of acceptable size.
2538
2539       function Has_Pending_Instantiation return Boolean;
2540       --  If some enclosing body contains instantiations that appear before the
2541       --  corresponding generic body, the enclosing body has a freeze node so
2542       --  that it can be elaborated after the generic itself. This might
2543       --  conflict with subsequent inlinings, so that it is unsafe to try to
2544       --  inline in such a case.
2545
2546       function Has_Single_Return return Boolean;
2547       --  In general we cannot inline functions that return unconstrained type.
2548       --  However, we can handle such functions if all return statements return
2549       --  a local variable that is the only declaration in the body of the
2550       --  function. In that case the call can be replaced by that local
2551       --  variable as is done for other inlined calls.
2552
2553       procedure Remove_Pragmas;
2554       --  A pragma Unreferenced or pragma Unmodified that mentions a formal
2555       --  parameter has no meaning when the body is inlined and the formals
2556       --  are rewritten. Remove it from body to inline. The analysis of the
2557       --  non-inlined body will handle the pragma properly.
2558
2559       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean;
2560       --  If the body of the subprogram includes a call that returns an
2561       --  unconstrained type, the secondary stack is involved, and it
2562       --  is not worth inlining.
2563
2564       ------------------------------
2565       -- Has_Excluded_Declaration --
2566       ------------------------------
2567
2568       function Has_Excluded_Declaration (Decls : List_Id) return Boolean is
2569          D : Node_Id;
2570
2571          function Is_Unchecked_Conversion (D : Node_Id) return Boolean;
2572          --  Nested subprograms make a given body ineligible for inlining, but
2573          --  we make an exception for instantiations of unchecked conversion.
2574          --  The body has not been analyzed yet, so check the name, and verify
2575          --  that the visible entity with that name is the predefined unit.
2576
2577          -----------------------------
2578          -- Is_Unchecked_Conversion --
2579          -----------------------------
2580
2581          function Is_Unchecked_Conversion (D : Node_Id) return Boolean is
2582             Id   : constant Node_Id := Name (D);
2583             Conv : Entity_Id;
2584
2585          begin
2586             if Nkind (Id) = N_Identifier
2587               and then Chars (Id) = Name_Unchecked_Conversion
2588             then
2589                Conv := Current_Entity (Id);
2590
2591             elsif Nkind_In (Id, N_Selected_Component, N_Expanded_Name)
2592               and then Chars (Selector_Name (Id)) = Name_Unchecked_Conversion
2593             then
2594                Conv := Current_Entity (Selector_Name (Id));
2595             else
2596                return False;
2597             end if;
2598
2599             return Present (Conv)
2600               and then Is_Predefined_File_Name
2601                          (Unit_File_Name (Get_Source_Unit (Conv)))
2602               and then Is_Intrinsic_Subprogram (Conv);
2603          end Is_Unchecked_Conversion;
2604
2605       --  Start of processing for Has_Excluded_Declaration
2606
2607       begin
2608          D := First (Decls);
2609          while Present (D) loop
2610             if (Nkind (D) = N_Function_Instantiation
2611                   and then not Is_Unchecked_Conversion (D))
2612               or else Nkind_In (D, N_Protected_Type_Declaration,
2613                                    N_Package_Declaration,
2614                                    N_Package_Instantiation,
2615                                    N_Subprogram_Body,
2616                                    N_Procedure_Instantiation,
2617                                    N_Task_Type_Declaration)
2618             then
2619                Cannot_Inline
2620                  ("cannot inline & (non-allowed declaration)?", D, Subp);
2621                return True;
2622             end if;
2623
2624             Next (D);
2625          end loop;
2626
2627          return False;
2628       end Has_Excluded_Declaration;
2629
2630       ----------------------------
2631       -- Has_Excluded_Statement --
2632       ----------------------------
2633
2634       function Has_Excluded_Statement (Stats : List_Id) return Boolean is
2635          S : Node_Id;
2636          E : Node_Id;
2637
2638       begin
2639          S := First (Stats);
2640          while Present (S) loop
2641             Stat_Count := Stat_Count + 1;
2642
2643             if Nkind_In (S, N_Abort_Statement,
2644                             N_Asynchronous_Select,
2645                             N_Conditional_Entry_Call,
2646                             N_Delay_Relative_Statement,
2647                             N_Delay_Until_Statement,
2648                             N_Selective_Accept,
2649                             N_Timed_Entry_Call)
2650             then
2651                Cannot_Inline
2652                  ("cannot inline & (non-allowed statement)?", S, Subp);
2653                return True;
2654
2655             elsif Nkind (S) = N_Block_Statement then
2656                if Present (Declarations (S))
2657                  and then Has_Excluded_Declaration (Declarations (S))
2658                then
2659                   return True;
2660
2661                elsif Present (Handled_Statement_Sequence (S))
2662                   and then
2663                     (Present
2664                       (Exception_Handlers (Handled_Statement_Sequence (S)))
2665                      or else
2666                        Has_Excluded_Statement
2667                          (Statements (Handled_Statement_Sequence (S))))
2668                then
2669                   return True;
2670                end if;
2671
2672             elsif Nkind (S) = N_Case_Statement then
2673                E := First (Alternatives (S));
2674                while Present (E) loop
2675                   if Has_Excluded_Statement (Statements (E)) then
2676                      return True;
2677                   end if;
2678
2679                   Next (E);
2680                end loop;
2681
2682             elsif Nkind (S) = N_If_Statement then
2683                if Has_Excluded_Statement (Then_Statements (S)) then
2684                   return True;
2685                end if;
2686
2687                if Present (Elsif_Parts (S)) then
2688                   E := First (Elsif_Parts (S));
2689                   while Present (E) loop
2690                      if Has_Excluded_Statement (Then_Statements (E)) then
2691                         return True;
2692                      end if;
2693                      Next (E);
2694                   end loop;
2695                end if;
2696
2697                if Present (Else_Statements (S))
2698                  and then Has_Excluded_Statement (Else_Statements (S))
2699                then
2700                   return True;
2701                end if;
2702
2703             elsif Nkind (S) = N_Loop_Statement
2704               and then Has_Excluded_Statement (Statements (S))
2705             then
2706                return True;
2707             end if;
2708
2709             Next (S);
2710          end loop;
2711
2712          return False;
2713       end Has_Excluded_Statement;
2714
2715       -------------------------------
2716       -- Has_Pending_Instantiation --
2717       -------------------------------
2718
2719       function Has_Pending_Instantiation return Boolean is
2720          S : Entity_Id;
2721
2722       begin
2723          S := Current_Scope;
2724          while Present (S) loop
2725             if Is_Compilation_Unit (S)
2726               or else Is_Child_Unit (S)
2727             then
2728                return False;
2729             elsif Ekind (S) = E_Package
2730               and then Has_Forward_Instantiation (S)
2731             then
2732                return True;
2733             end if;
2734
2735             S := Scope (S);
2736          end loop;
2737
2738          return False;
2739       end Has_Pending_Instantiation;
2740
2741       ------------------------
2742       --  Has_Single_Return --
2743       ------------------------
2744
2745       function Has_Single_Return return Boolean is
2746          Return_Statement : Node_Id := Empty;
2747
2748          function Check_Return (N : Node_Id) return Traverse_Result;
2749
2750          ------------------
2751          -- Check_Return --
2752          ------------------
2753
2754          function Check_Return (N : Node_Id) return Traverse_Result is
2755          begin
2756             if Nkind (N) = N_Simple_Return_Statement then
2757                if Present (Expression (N))
2758                  and then Is_Entity_Name (Expression (N))
2759                then
2760                   if No (Return_Statement) then
2761                      Return_Statement := N;
2762                      return OK;
2763
2764                   elsif Chars (Expression (N)) =
2765                         Chars (Expression (Return_Statement))
2766                   then
2767                      return OK;
2768
2769                   else
2770                      return Abandon;
2771                   end if;
2772
2773                else
2774                   --  Expression has wrong form
2775
2776                   return Abandon;
2777                end if;
2778
2779             else
2780                return OK;
2781             end if;
2782          end Check_Return;
2783
2784          function Check_All_Returns is new Traverse_Func (Check_Return);
2785
2786       --  Start of processing for Has_Single_Return
2787
2788       begin
2789          return Check_All_Returns (N) = OK
2790            and then Present (Declarations (N))
2791            and then Present (First (Declarations (N)))
2792            and then Chars (Expression (Return_Statement)) =
2793                     Chars (Defining_Identifier (First (Declarations (N))));
2794       end Has_Single_Return;
2795
2796       --------------------
2797       -- Remove_Pragmas --
2798       --------------------
2799
2800       procedure Remove_Pragmas is
2801          Decl : Node_Id;
2802          Nxt  : Node_Id;
2803
2804       begin
2805          Decl := First (Declarations (Body_To_Analyze));
2806          while Present (Decl) loop
2807             Nxt := Next (Decl);
2808
2809             if Nkind (Decl) = N_Pragma
2810               and then (Pragma_Name (Decl) = Name_Unreferenced
2811                           or else
2812                         Pragma_Name (Decl) = Name_Unmodified)
2813             then
2814                Remove (Decl);
2815             end if;
2816
2817             Decl := Nxt;
2818          end loop;
2819       end Remove_Pragmas;
2820
2821       --------------------------
2822       -- Uses_Secondary_Stack --
2823       --------------------------
2824
2825       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean is
2826          function Check_Call (N : Node_Id) return Traverse_Result;
2827          --  Look for function calls that return an unconstrained type
2828
2829          ----------------
2830          -- Check_Call --
2831          ----------------
2832
2833          function Check_Call (N : Node_Id) return Traverse_Result is
2834          begin
2835             if Nkind (N) = N_Function_Call
2836               and then Is_Entity_Name (Name (N))
2837               and then Is_Composite_Type (Etype (Entity (Name (N))))
2838               and then not Is_Constrained (Etype (Entity (Name (N))))
2839             then
2840                Cannot_Inline
2841                  ("cannot inline & (call returns unconstrained type)?",
2842                     N, Subp);
2843                return Abandon;
2844             else
2845                return OK;
2846             end if;
2847          end Check_Call;
2848
2849          function Check_Calls is new Traverse_Func (Check_Call);
2850
2851       begin
2852          return Check_Calls (Bod) = Abandon;
2853       end Uses_Secondary_Stack;
2854
2855    --  Start of processing for Build_Body_To_Inline
2856
2857    begin
2858       if Nkind (Decl) = N_Subprogram_Declaration
2859         and then Present (Body_To_Inline (Decl))
2860       then
2861          return;    --  Done already.
2862
2863       --  Functions that return unconstrained composite types require
2864       --  secondary stack handling, and cannot currently be inlined, unless
2865       --  all return statements return a local variable that is the first
2866       --  local declaration in the body.
2867
2868       elsif Ekind (Subp) = E_Function
2869         and then not Is_Scalar_Type (Etype (Subp))
2870         and then not Is_Access_Type (Etype (Subp))
2871         and then not Is_Constrained (Etype (Subp))
2872       then
2873          if not Has_Single_Return then
2874             Cannot_Inline
2875               ("cannot inline & (unconstrained return type)?", N, Subp);
2876             return;
2877          end if;
2878
2879       --  Ditto for functions that return controlled types, where controlled
2880       --  actions interfere in complex ways with inlining.
2881
2882       elsif Ekind (Subp) = E_Function
2883         and then Controlled_Type (Etype (Subp))
2884       then
2885          Cannot_Inline
2886            ("cannot inline & (controlled return type)?", N, Subp);
2887          return;
2888       end if;
2889
2890       if Present (Declarations (N))
2891         and then Has_Excluded_Declaration (Declarations (N))
2892       then
2893          return;
2894       end if;
2895
2896       if Present (Handled_Statement_Sequence (N)) then
2897          if Present (Exception_Handlers (Handled_Statement_Sequence (N))) then
2898             Cannot_Inline
2899               ("cannot inline& (exception handler)?",
2900                First (Exception_Handlers (Handled_Statement_Sequence (N))),
2901                Subp);
2902             return;
2903          elsif
2904            Has_Excluded_Statement
2905              (Statements (Handled_Statement_Sequence (N)))
2906          then
2907             return;
2908          end if;
2909       end if;
2910
2911       --  We do not inline a subprogram  that is too large, unless it is
2912       --  marked Inline_Always. This pragma does not suppress the other
2913       --  checks on inlining (forbidden declarations, handlers, etc).
2914
2915       if Stat_Count > Max_Size
2916         and then not Has_Pragma_Inline_Always (Subp)
2917       then
2918          Cannot_Inline ("cannot inline& (body too large)?", N, Subp);
2919          return;
2920       end if;
2921
2922       if Has_Pending_Instantiation then
2923          Cannot_Inline
2924            ("cannot inline& (forward instance within enclosing body)?",
2925              N, Subp);
2926          return;
2927       end if;
2928
2929       --  Within an instance, the body to inline must be treated as a nested
2930       --  generic, so that the proper global references are preserved.
2931
2932       --  Note that we do not do this at the library level, because it is not
2933       --  needed, and furthermore this causes trouble if front end inlining
2934       --  is activated (-gnatN).
2935
2936       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
2937          Save_Env (Scope (Current_Scope), Scope (Current_Scope));
2938          Original_Body := Copy_Generic_Node (N, Empty, True);
2939       else
2940          Original_Body := Copy_Separate_Tree (N);
2941       end if;
2942
2943       --  We need to capture references to the formals in order to substitute
2944       --  the actuals at the point of inlining, i.e. instantiation. To treat
2945       --  the formals as globals to the body to inline, we nest it within
2946       --  a dummy parameterless subprogram, declared within the real one.
2947       --  To avoid generating an internal name (which is never public, and
2948       --  which affects serial numbers of other generated names), we use
2949       --  an internal symbol that cannot conflict with user declarations.
2950
2951       Set_Parameter_Specifications (Specification (Original_Body), No_List);
2952       Set_Defining_Unit_Name
2953         (Specification (Original_Body),
2954           Make_Defining_Identifier (Sloc (N), Name_uParent));
2955       Set_Corresponding_Spec (Original_Body, Empty);
2956
2957       Body_To_Analyze := Copy_Generic_Node (Original_Body, Empty, False);
2958
2959       --  Set return type of function, which is also global and does not need
2960       --  to be resolved.
2961
2962       if Ekind (Subp) = E_Function then
2963          Set_Result_Definition (Specification (Body_To_Analyze),
2964            New_Occurrence_Of (Etype (Subp), Sloc (N)));
2965       end if;
2966
2967       if No (Declarations (N)) then
2968          Set_Declarations (N, New_List (Body_To_Analyze));
2969       else
2970          Append (Body_To_Analyze, Declarations (N));
2971       end if;
2972
2973       Expander_Mode_Save_And_Set (False);
2974       Remove_Pragmas;
2975
2976       Analyze (Body_To_Analyze);
2977       Push_Scope (Defining_Entity (Body_To_Analyze));
2978       Save_Global_References (Original_Body);
2979       End_Scope;
2980       Remove (Body_To_Analyze);
2981
2982       Expander_Mode_Restore;
2983
2984       --  Restore environment if previously saved
2985
2986       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
2987          Restore_Env;
2988       end if;
2989
2990       --  If secondary stk used there is no point in inlining. We have
2991       --  already issued the warning in this case, so nothing to do.
2992
2993       if Uses_Secondary_Stack (Body_To_Analyze) then
2994          return;
2995       end if;
2996
2997       Set_Body_To_Inline (Decl, Original_Body);
2998       Set_Ekind (Defining_Entity (Original_Body), Ekind (Subp));
2999       Set_Is_Inlined (Subp);
3000    end Build_Body_To_Inline;
3001
3002    -------------------
3003    -- Cannot_Inline --
3004    -------------------
3005
3006    procedure Cannot_Inline (Msg : String; N : Node_Id; Subp : Entity_Id) is
3007    begin
3008       --  Do not emit warning if this is a predefined unit which is not
3009       --  the main unit. With validity checks enabled, some predefined
3010       --  subprograms may contain nested subprograms and become ineligible
3011       --  for inlining.
3012
3013       if Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Subp)))
3014         and then not In_Extended_Main_Source_Unit (Subp)
3015       then
3016          null;
3017
3018       elsif Has_Pragma_Inline_Always (Subp) then
3019
3020          --  Remove last character (question mark) to make this into an error,
3021          --  because the Inline_Always pragma cannot be obeyed.
3022
3023          Error_Msg_NE (Msg (Msg'First .. Msg'Last - 1), N, Subp);
3024
3025       elsif Ineffective_Inline_Warnings then
3026          Error_Msg_NE (Msg, N, Subp);
3027       end if;
3028    end Cannot_Inline;
3029
3030    -----------------------
3031    -- Check_Conformance --
3032    -----------------------
3033
3034    procedure Check_Conformance
3035      (New_Id                   : Entity_Id;
3036       Old_Id                   : Entity_Id;
3037       Ctype                    : Conformance_Type;
3038       Errmsg                   : Boolean;
3039       Conforms                 : out Boolean;
3040       Err_Loc                  : Node_Id := Empty;
3041       Get_Inst                 : Boolean := False;
3042       Skip_Controlling_Formals : Boolean := False)
3043    is
3044       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id);
3045       --  Post error message for conformance error on given node. Two messages
3046       --  are output. The first points to the previous declaration with a
3047       --  general "no conformance" message. The second is the detailed reason,
3048       --  supplied as Msg. The parameter N provide information for a possible
3049       --  & insertion in the message, and also provides the location for
3050       --  posting the message in the absence of a specified Err_Loc location.
3051
3052       -----------------------
3053       -- Conformance_Error --
3054       -----------------------
3055
3056       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id) is
3057          Enode : Node_Id;
3058
3059       begin
3060          Conforms := False;
3061
3062          if Errmsg then
3063             if No (Err_Loc) then
3064                Enode := N;
3065             else
3066                Enode := Err_Loc;
3067             end if;
3068
3069             Error_Msg_Sloc := Sloc (Old_Id);
3070
3071             case Ctype is
3072                when Type_Conformant =>
3073                   Error_Msg_N
3074                     ("not type conformant with declaration#!", Enode);
3075
3076                when Mode_Conformant =>
3077                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3078                      Error_Msg_N
3079                        ("not mode conformant with operation inherited#!",
3080                          Enode);
3081                   else
3082                      Error_Msg_N
3083                        ("not mode conformant with declaration#!", Enode);
3084                   end if;
3085
3086                when Subtype_Conformant =>
3087                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3088                      Error_Msg_N
3089                        ("not subtype conformant with operation inherited#!",
3090                          Enode);
3091                   else
3092                      Error_Msg_N
3093                        ("not subtype conformant with declaration#!", Enode);
3094                   end if;
3095
3096                when Fully_Conformant =>
3097                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3098                      Error_Msg_N
3099                        ("not fully conformant with operation inherited#!",
3100                          Enode);
3101                   else
3102                      Error_Msg_N
3103                        ("not fully conformant with declaration#!", Enode);
3104                   end if;
3105             end case;
3106
3107             Error_Msg_NE (Msg, Enode, N);
3108          end if;
3109       end Conformance_Error;
3110
3111       --  Local Variables
3112
3113       Old_Type           : constant Entity_Id := Etype (Old_Id);
3114       New_Type           : constant Entity_Id := Etype (New_Id);
3115       Old_Formal         : Entity_Id;
3116       New_Formal         : Entity_Id;
3117       Access_Types_Match : Boolean;
3118       Old_Formal_Base    : Entity_Id;
3119       New_Formal_Base    : Entity_Id;
3120
3121    --  Start of processing for Check_Conformance
3122
3123    begin
3124       Conforms := True;
3125
3126       --  We need a special case for operators, since they don't appear
3127       --  explicitly.
3128
3129       if Ctype = Type_Conformant then
3130          if Ekind (New_Id) = E_Operator
3131            and then Operator_Matches_Spec (New_Id, Old_Id)
3132          then
3133             return;
3134          end if;
3135       end if;
3136
3137       --  If both are functions/operators, check return types conform
3138
3139       if Old_Type /= Standard_Void_Type
3140         and then New_Type /= Standard_Void_Type
3141       then
3142          if not Conforming_Types (Old_Type, New_Type, Ctype, Get_Inst) then
3143             Conformance_Error ("\return type does not match!", New_Id);
3144             return;
3145          end if;
3146
3147          --  Ada 2005 (AI-231): In case of anonymous access types check the
3148          --  null-exclusion and access-to-constant attributes match.
3149
3150          if Ada_Version >= Ada_05
3151            and then Ekind (Etype (Old_Type)) = E_Anonymous_Access_Type
3152            and then
3153              (Can_Never_Be_Null (Old_Type)
3154                 /= Can_Never_Be_Null (New_Type)
3155               or else Is_Access_Constant (Etype (Old_Type))
3156                         /= Is_Access_Constant (Etype (New_Type)))
3157          then
3158             Conformance_Error ("\return type does not match!", New_Id);
3159             return;
3160          end if;
3161
3162       --  If either is a function/operator and the other isn't, error
3163
3164       elsif Old_Type /= Standard_Void_Type
3165         or else New_Type /= Standard_Void_Type
3166       then
3167          Conformance_Error ("\functions can only match functions!", New_Id);
3168          return;
3169       end if;
3170
3171       --  In subtype conformant case, conventions must match (RM 6.3.1(16)).
3172       --  If this is a renaming as body, refine error message to indicate that
3173       --  the conflict is with the original declaration. If the entity is not
3174       --  frozen, the conventions don't have to match, the one of the renamed
3175       --  entity is inherited.
3176
3177       if Ctype >= Subtype_Conformant then
3178          if Convention (Old_Id) /= Convention (New_Id) then
3179
3180             if not Is_Frozen (New_Id) then
3181                null;
3182
3183             elsif Present (Err_Loc)
3184               and then Nkind (Err_Loc) = N_Subprogram_Renaming_Declaration
3185               and then Present (Corresponding_Spec (Err_Loc))
3186             then
3187                Error_Msg_Name_1 := Chars (New_Id);
3188                Error_Msg_Name_2 :=
3189                  Name_Ada + Convention_Id'Pos (Convention (New_Id));
3190
3191                Conformance_Error ("\prior declaration for% has convention %!");
3192
3193             else
3194                Conformance_Error ("\calling conventions do not match!");
3195             end if;
3196
3197             return;
3198
3199          elsif Is_Formal_Subprogram (Old_Id)
3200            or else Is_Formal_Subprogram (New_Id)
3201          then
3202             Conformance_Error ("\formal subprograms not allowed!");
3203             return;
3204          end if;
3205       end if;
3206
3207       --  Deal with parameters
3208
3209       --  Note: we use the entity information, rather than going directly
3210       --  to the specification in the tree. This is not only simpler, but
3211       --  absolutely necessary for some cases of conformance tests between
3212       --  operators, where the declaration tree simply does not exist!
3213
3214       Old_Formal := First_Formal (Old_Id);
3215       New_Formal := First_Formal (New_Id);
3216
3217       while Present (Old_Formal) and then Present (New_Formal) loop
3218          if Is_Controlling_Formal (Old_Formal)
3219            and then Is_Controlling_Formal (New_Formal)
3220            and then Skip_Controlling_Formals
3221          then
3222             goto Skip_Controlling_Formal;
3223          end if;
3224
3225          if Ctype = Fully_Conformant then
3226
3227             --  Names must match. Error message is more accurate if we do
3228             --  this before checking that the types of the formals match.
3229
3230             if Chars (Old_Formal) /= Chars (New_Formal) then
3231                Conformance_Error ("\name & does not match!", New_Formal);
3232
3233                --  Set error posted flag on new formal as well to stop
3234                --  junk cascaded messages in some cases.
3235
3236                Set_Error_Posted (New_Formal);
3237                return;
3238             end if;
3239          end if;
3240
3241          --  Ada 2005 (AI-423): Possible access [sub]type and itype match. This
3242          --  case occurs whenever a subprogram is being renamed and one of its
3243          --  parameters imposes a null exclusion. For example:
3244
3245          --     type T is null record;
3246          --     type Acc_T is access T;
3247          --     subtype Acc_T_Sub is Acc_T;
3248
3249          --     procedure P     (Obj : not null Acc_T_Sub);  --  itype
3250          --     procedure Ren_P (Obj :          Acc_T_Sub)   --  subtype
3251          --       renames P;
3252
3253          Old_Formal_Base := Etype (Old_Formal);
3254          New_Formal_Base := Etype (New_Formal);
3255
3256          if Get_Inst then
3257             Old_Formal_Base := Get_Instance_Of (Old_Formal_Base);
3258             New_Formal_Base := Get_Instance_Of (New_Formal_Base);
3259          end if;
3260
3261          Access_Types_Match := Ada_Version >= Ada_05
3262
3263             --  Ensure that this rule is only applied when New_Id is a
3264             --  renaming of Old_Id.
3265
3266            and then Nkind (Parent (Parent (New_Id))) =
3267                       N_Subprogram_Renaming_Declaration
3268            and then Nkind (Name (Parent (Parent (New_Id)))) in N_Has_Entity
3269            and then Present (Entity (Name (Parent (Parent (New_Id)))))
3270            and then Entity (Name (Parent (Parent (New_Id)))) = Old_Id
3271
3272             --  Now handle the allowed access-type case
3273
3274            and then Is_Access_Type (Old_Formal_Base)
3275            and then Is_Access_Type (New_Formal_Base)
3276
3277             --  The type kinds must match. The only exception occurs with
3278             --  multiple generics of the form:
3279
3280             --   generic                    generic
3281             --     type F is private;         type A is private;
3282             --     type F_Ptr is access F;    type A_Ptr is access A;
3283             --     with proc F_P (X : F_Ptr); with proc A_P (X : A_Ptr);
3284             --   package F_Pack is ...      package A_Pack is
3285             --                                package F_Inst is
3286             --                                  new F_Pack (A, A_Ptr, A_P);
3287
3288             --  When checking for conformance between the parameters of A_P
3289             --  and F_P, the type kinds of F_Ptr and A_Ptr will not match
3290             --  because the compiler has transformed A_Ptr into a subtype of
3291             --  F_Ptr. We catch this case in the code below.
3292
3293            and then (Ekind (Old_Formal_Base) = Ekind (New_Formal_Base)
3294                   or else
3295                     (Is_Generic_Type (Old_Formal_Base)
3296                        and then Is_Generic_Type (New_Formal_Base)
3297                        and then Is_Internal (New_Formal_Base)
3298                        and then Etype (Etype (New_Formal_Base)) =
3299                                   Old_Formal_Base))
3300            and then Directly_Designated_Type (Old_Formal_Base) =
3301                       Directly_Designated_Type (New_Formal_Base)
3302            and then ((Is_Itype (Old_Formal_Base)
3303                        and then Can_Never_Be_Null (Old_Formal_Base))
3304                     or else
3305                      (Is_Itype (New_Formal_Base)
3306                        and then Can_Never_Be_Null (New_Formal_Base)));
3307
3308          --  Types must always match. In the visible part of an instance,
3309          --  usual overloading rules for dispatching operations apply, and
3310          --  we check base types (not the actual subtypes).
3311
3312          if In_Instance_Visible_Part
3313            and then Is_Dispatching_Operation (New_Id)
3314          then
3315             if not Conforming_Types
3316                      (T1       => Base_Type (Etype (Old_Formal)),
3317                       T2       => Base_Type (Etype (New_Formal)),
3318                       Ctype    => Ctype,
3319                       Get_Inst => Get_Inst)
3320                and then not Access_Types_Match
3321             then
3322                Conformance_Error ("\type of & does not match!", New_Formal);
3323                return;
3324             end if;
3325
3326          elsif not Conforming_Types
3327                      (T1       => Old_Formal_Base,
3328                       T2       => New_Formal_Base,
3329                       Ctype    => Ctype,
3330                       Get_Inst => Get_Inst)
3331            and then not Access_Types_Match
3332          then
3333             Conformance_Error ("\type of & does not match!", New_Formal);
3334             return;
3335          end if;
3336
3337          --  For mode conformance, mode must match
3338
3339          if Ctype >= Mode_Conformant then
3340             if Parameter_Mode (Old_Formal) /= Parameter_Mode (New_Formal) then
3341                Conformance_Error ("\mode of & does not match!", New_Formal);
3342                return;
3343
3344             --  Part of mode conformance for access types is having the same
3345             --  constant modifier.
3346
3347             elsif Access_Types_Match
3348               and then Is_Access_Constant (Old_Formal_Base) /=
3349                        Is_Access_Constant (New_Formal_Base)
3350             then
3351                Conformance_Error
3352                  ("\constant modifier does not match!", New_Formal);
3353                return;
3354             end if;
3355          end if;
3356
3357          if Ctype >= Subtype_Conformant then
3358
3359             --  Ada 2005 (AI-231): In case of anonymous access types check
3360             --  the null-exclusion and access-to-constant attributes must
3361             --  match.
3362
3363             if Ada_Version >= Ada_05
3364               and then Ekind (Etype (Old_Formal)) = E_Anonymous_Access_Type
3365               and then Ekind (Etype (New_Formal)) = E_Anonymous_Access_Type
3366               and then
3367                 (Can_Never_Be_Null (Old_Formal) /=
3368                  Can_Never_Be_Null (New_Formal)
3369                    or else
3370                  Is_Access_Constant (Etype (Old_Formal)) /=
3371                  Is_Access_Constant (Etype (New_Formal)))
3372             then
3373                --  It is allowed to omit the null-exclusion in case of stream
3374                --  attribute subprograms. We recognize stream subprograms
3375                --  through their TSS-generated suffix.
3376
3377                declare
3378                   TSS_Name : constant TSS_Name_Type := Get_TSS_Name (New_Id);
3379                begin
3380                   if TSS_Name /= TSS_Stream_Read
3381                     and then TSS_Name /= TSS_Stream_Write
3382                     and then TSS_Name /= TSS_Stream_Input
3383                     and then TSS_Name /= TSS_Stream_Output
3384                   then
3385                      Conformance_Error
3386                        ("\type of & does not match!", New_Formal);
3387                      return;
3388                   end if;
3389                end;
3390             end if;
3391          end if;
3392
3393          --  Full conformance checks
3394
3395          if Ctype = Fully_Conformant then
3396
3397             --  We have checked already that names match
3398
3399             if Parameter_Mode (Old_Formal) = E_In_Parameter then
3400
3401                --  Check default expressions for in parameters
3402
3403                declare
3404                   NewD : constant Boolean :=
3405                            Present (Default_Value (New_Formal));
3406                   OldD : constant Boolean :=
3407                            Present (Default_Value (Old_Formal));
3408                begin
3409                   if NewD or OldD then
3410
3411                      --  The old default value has been analyzed because the
3412                      --  current full declaration will have frozen everything
3413                      --  before. The new default value has not been analyzed,
3414                      --  so analyze it now before we check for conformance.
3415
3416                      if NewD then
3417                         Push_Scope (New_Id);
3418                         Preanalyze_Spec_Expression
3419                           (Default_Value (New_Formal), Etype (New_Formal));
3420                         End_Scope;
3421                      end if;
3422
3423                      if not (NewD and OldD)
3424                        or else not Fully_Conformant_Expressions
3425                                     (Default_Value (Old_Formal),
3426                                      Default_Value (New_Formal))
3427                      then
3428                         Conformance_Error
3429                           ("\default expression for & does not match!",
3430                            New_Formal);
3431                         return;
3432                      end if;
3433                   end if;
3434                end;
3435             end if;
3436          end if;
3437
3438          --  A couple of special checks for Ada 83 mode. These checks are
3439          --  skipped if either entity is an operator in package Standard,
3440          --  or if either old or new instance is not from the source program.
3441
3442          if Ada_Version = Ada_83
3443            and then Sloc (Old_Id) > Standard_Location
3444            and then Sloc (New_Id) > Standard_Location
3445            and then Comes_From_Source (Old_Id)
3446            and then Comes_From_Source (New_Id)
3447          then
3448             declare
3449                Old_Param : constant Node_Id := Declaration_Node (Old_Formal);
3450                New_Param : constant Node_Id := Declaration_Node (New_Formal);
3451
3452             begin
3453                --  Explicit IN must be present or absent in both cases. This
3454                --  test is required only in the full conformance case.
3455
3456                if In_Present (Old_Param) /= In_Present (New_Param)
3457                  and then Ctype = Fully_Conformant
3458                then
3459                   Conformance_Error
3460                     ("\(Ada 83) IN must appear in both declarations",
3461                      New_Formal);
3462                   return;
3463                end if;
3464
3465                --  Grouping (use of comma in param lists) must be the same
3466                --  This is where we catch a misconformance like:
3467
3468                --    A, B : Integer
3469                --    A : Integer; B : Integer
3470
3471                --  which are represented identically in the tree except
3472                --  for the setting of the flags More_Ids and Prev_Ids.
3473
3474                if More_Ids (Old_Param) /= More_Ids (New_Param)
3475                  or else Prev_Ids (Old_Param) /= Prev_Ids (New_Param)
3476                then
3477                   Conformance_Error
3478                     ("\grouping of & does not match!", New_Formal);
3479                   return;
3480                end if;
3481             end;
3482          end if;
3483
3484          --  This label is required when skipping controlling formals
3485
3486          <<Skip_Controlling_Formal>>
3487
3488          Next_Formal (Old_Formal);
3489          Next_Formal (New_Formal);
3490       end loop;
3491
3492       if Present (Old_Formal) then
3493          Conformance_Error ("\too few parameters!");
3494          return;
3495
3496       elsif Present (New_Formal) then
3497          Conformance_Error ("\too many parameters!", New_Formal);
3498          return;
3499       end if;
3500    end Check_Conformance;
3501
3502    -----------------------
3503    -- Check_Conventions --
3504    -----------------------
3505
3506    procedure Check_Conventions (Typ : Entity_Id) is
3507
3508       function Skip_Check (Op : Entity_Id) return Boolean;
3509       pragma Inline (Skip_Check);
3510       --  A small optimization: skip the predefined dispatching operations,
3511       --  since they always have the same convention. Also do not consider
3512       --  abstract primitives since those are left by an erroneous overriding.
3513       --  This function returns True for any operation that is thus exempted
3514       --  exempted from checking.
3515
3516       procedure Check_Convention
3517         (Op          : Entity_Id;
3518          Search_From : Elmt_Id);
3519       --  Verify that the convention of inherited dispatching operation Op is
3520       --  consistent among all subprograms it overrides. In order to minimize
3521       --  the search, Search_From is utilized to designate a specific point in
3522       --  the list rather than iterating over the whole list once more.
3523
3524       ----------------------
3525       -- Check_Convention --
3526       ----------------------
3527
3528       procedure Check_Convention
3529         (Op          : Entity_Id;
3530          Search_From : Elmt_Id)
3531       is
3532          procedure Error_Msg_Operation (Op : Entity_Id);
3533          --  Emit a continuation to an error message depicting the kind, name,
3534          --  convention and source location of subprogram Op.
3535
3536          -------------------------
3537          -- Error_Msg_Operation --
3538          -------------------------
3539
3540          procedure Error_Msg_Operation (Op : Entity_Id) is
3541          begin
3542             Error_Msg_Name_1 := Chars (Op);
3543
3544             --  Error messages of primitive subprograms do not contain a
3545             --  convention attribute since the convention may have been first
3546             --  inherited from a parent subprogram, then changed by a pragma.
3547
3548             if Comes_From_Source (Op) then
3549                Error_Msg_Sloc := Sloc (Op);
3550                Error_Msg_N
3551                 ("\ primitive % defined #", Typ);
3552
3553             else
3554                Error_Msg_Name_2 := Get_Convention_Name (Convention (Op));
3555
3556                if Present (Abstract_Interface_Alias (Op)) then
3557                   Error_Msg_Sloc := Sloc (Abstract_Interface_Alias (Op));
3558                   Error_Msg_N ("\\overridden operation % with " &
3559                                "convention % defined #", Typ);
3560
3561                else pragma Assert (Present (Alias (Op)));
3562                   Error_Msg_Sloc := Sloc (Alias (Op));
3563                   Error_Msg_N ("\\inherited operation % with " &
3564                                "convention % defined #", Typ);
3565                end if;
3566             end if;
3567          end Error_Msg_Operation;
3568
3569          --  Local variables
3570
3571          Second_Prim_Op      : Entity_Id;
3572          Second_Prim_Op_Elmt : Elmt_Id;
3573
3574       --  Start of processing for Check_Convention
3575
3576       begin
3577          Second_Prim_Op_Elmt := Next_Elmt (Search_From);
3578          while Present (Second_Prim_Op_Elmt) loop
3579             Second_Prim_Op := Node (Second_Prim_Op_Elmt);
3580
3581             if not Skip_Check (Second_Prim_Op)
3582               and then Chars (Second_Prim_Op) = Chars (Op)
3583               and then Type_Conformant (Second_Prim_Op, Op)
3584               and then Convention (Second_Prim_Op) /= Convention (Op)
3585             then
3586                Error_Msg_N
3587                  ("inconsistent conventions in primitive operations", Typ);
3588
3589                Error_Msg_Operation (Op);
3590                Error_Msg_Operation (Second_Prim_Op);
3591
3592                --  Avoid cascading errors
3593
3594                return;
3595             end if;
3596
3597             Next_Elmt (Second_Prim_Op_Elmt);
3598          end loop;
3599       end Check_Convention;
3600
3601       ----------------
3602       -- Skip_Check --
3603       ----------------
3604
3605       function Skip_Check (Op : Entity_Id) return Boolean is
3606       begin
3607          return Is_Predefined_Dispatching_Operation (Op)
3608            or else Is_Abstract_Subprogram (Op);
3609       end Skip_Check;
3610
3611       --  Local variables
3612
3613       Prim_Op      : Entity_Id;
3614       Prim_Op_Elmt : Elmt_Id;
3615
3616    --  Start of processing for Check_Conventions
3617
3618    begin
3619       --  The algorithm checks every overriding dispatching operation against
3620       --  all the corresponding overridden dispatching operations, detecting
3621       --  differences in conventions.
3622
3623       Prim_Op_Elmt := First_Elmt (Primitive_Operations (Typ));
3624       while Present (Prim_Op_Elmt) loop
3625          Prim_Op := Node (Prim_Op_Elmt);
3626
3627          --  A small optimization: skip the predefined dispatching operations
3628          --  since they always have the same convention. Also avoid processing
3629          --  of abstract primitives left from an erroneous overriding.
3630
3631          if not Skip_Check (Prim_Op) then
3632             Check_Convention
3633               (Op          => Prim_Op,
3634                Search_From => Prim_Op_Elmt);
3635          end if;
3636
3637          Next_Elmt (Prim_Op_Elmt);
3638       end loop;
3639    end Check_Conventions;
3640
3641    ------------------------------
3642    -- Check_Delayed_Subprogram --
3643    ------------------------------
3644
3645    procedure Check_Delayed_Subprogram (Designator : Entity_Id) is
3646       F : Entity_Id;
3647
3648       procedure Possible_Freeze (T : Entity_Id);
3649       --  T is the type of either a formal parameter or of the return type.
3650       --  If T is not yet frozen and needs a delayed freeze, then the
3651       --  subprogram itself must be delayed.
3652
3653       ---------------------
3654       -- Possible_Freeze --
3655       ---------------------
3656
3657       procedure Possible_Freeze (T : Entity_Id) is
3658       begin
3659          if Has_Delayed_Freeze (T)
3660            and then not Is_Frozen (T)
3661          then
3662             Set_Has_Delayed_Freeze (Designator);
3663
3664          elsif Is_Access_Type (T)
3665            and then Has_Delayed_Freeze (Designated_Type (T))
3666            and then not Is_Frozen (Designated_Type (T))
3667          then
3668             Set_Has_Delayed_Freeze (Designator);
3669          end if;
3670       end Possible_Freeze;
3671
3672    --  Start of processing for Check_Delayed_Subprogram
3673
3674    begin
3675       --  Never need to freeze abstract subprogram
3676
3677       if Ekind (Designator) /= E_Subprogram_Type
3678         and then Is_Abstract_Subprogram (Designator)
3679       then
3680          null;
3681       else
3682          --  Need delayed freeze if return type itself needs a delayed
3683          --  freeze and is not yet frozen.
3684
3685          Possible_Freeze (Etype (Designator));
3686          Possible_Freeze (Base_Type (Etype (Designator))); -- needed ???
3687
3688          --  Need delayed freeze if any of the formal types themselves need
3689          --  a delayed freeze and are not yet frozen.
3690
3691          F := First_Formal (Designator);
3692          while Present (F) loop
3693             Possible_Freeze (Etype (F));
3694             Possible_Freeze (Base_Type (Etype (F))); -- needed ???
3695             Next_Formal (F);
3696          end loop;
3697       end if;
3698
3699       --  Mark functions that return by reference. Note that it cannot be
3700       --  done for delayed_freeze subprograms because the underlying
3701       --  returned type may not be known yet (for private types)
3702
3703       if not Has_Delayed_Freeze (Designator)
3704         and then Expander_Active
3705       then
3706          declare
3707             Typ  : constant Entity_Id := Etype (Designator);
3708             Utyp : constant Entity_Id := Underlying_Type (Typ);
3709
3710          begin
3711             if Is_Inherently_Limited_Type (Typ) then
3712                Set_Returns_By_Ref (Designator);
3713
3714             elsif Present (Utyp) and then CW_Or_Controlled_Type (Utyp) then
3715                Set_Returns_By_Ref (Designator);
3716             end if;
3717          end;
3718       end if;
3719    end Check_Delayed_Subprogram;
3720
3721    ------------------------------------
3722    -- Check_Discriminant_Conformance --
3723    ------------------------------------
3724
3725    procedure Check_Discriminant_Conformance
3726      (N        : Node_Id;
3727       Prev     : Entity_Id;
3728       Prev_Loc : Node_Id)
3729    is
3730       Old_Discr      : Entity_Id := First_Discriminant (Prev);
3731       New_Discr      : Node_Id   := First (Discriminant_Specifications (N));
3732       New_Discr_Id   : Entity_Id;
3733       New_Discr_Type : Entity_Id;
3734
3735       procedure Conformance_Error (Msg : String; N : Node_Id);
3736       --  Post error message for conformance error on given node. Two messages
3737       --  are output. The first points to the previous declaration with a
3738       --  general "no conformance" message. The second is the detailed reason,
3739       --  supplied as Msg. The parameter N provide information for a possible
3740       --  & insertion in the message.
3741
3742       -----------------------
3743       -- Conformance_Error --
3744       -----------------------
3745
3746       procedure Conformance_Error (Msg : String; N : Node_Id) is
3747       begin
3748          Error_Msg_Sloc := Sloc (Prev_Loc);
3749          Error_Msg_N ("not fully conformant with declaration#!", N);
3750          Error_Msg_NE (Msg, N, N);
3751       end Conformance_Error;
3752
3753    --  Start of processing for Check_Discriminant_Conformance
3754
3755    begin
3756       while Present (Old_Discr) and then Present (New_Discr) loop
3757
3758          New_Discr_Id := Defining_Identifier (New_Discr);
3759
3760          --  The subtype mark of the discriminant on the full type has not
3761          --  been analyzed so we do it here. For an access discriminant a new
3762          --  type is created.
3763
3764          if Nkind (Discriminant_Type (New_Discr)) = N_Access_Definition then
3765             New_Discr_Type :=
3766               Access_Definition (N, Discriminant_Type (New_Discr));
3767
3768          else
3769             Analyze (Discriminant_Type (New_Discr));
3770             New_Discr_Type := Etype (Discriminant_Type (New_Discr));
3771          end if;
3772
3773          if not Conforming_Types
3774                   (Etype (Old_Discr), New_Discr_Type, Fully_Conformant)
3775          then
3776             Conformance_Error ("type of & does not match!", New_Discr_Id);
3777             return;
3778          else
3779             --  Treat the new discriminant as an occurrence of the old one,
3780             --  for navigation purposes, and fill in some semantic
3781             --  information, for completeness.
3782
3783             Generate_Reference (Old_Discr, New_Discr_Id, 'r');
3784             Set_Etype (New_Discr_Id, Etype (Old_Discr));
3785             Set_Scope (New_Discr_Id, Scope (Old_Discr));
3786          end if;
3787
3788          --  Names must match
3789
3790          if Chars (Old_Discr) /= Chars (Defining_Identifier (New_Discr)) then
3791             Conformance_Error ("name & does not match!", New_Discr_Id);
3792             return;
3793          end if;
3794
3795          --  Default expressions must match
3796
3797          declare
3798             NewD : constant Boolean :=
3799                      Present (Expression (New_Discr));
3800             OldD : constant Boolean :=
3801                      Present (Expression (Parent (Old_Discr)));
3802
3803          begin
3804             if NewD or OldD then
3805
3806                --  The old default value has been analyzed and expanded,
3807                --  because the current full declaration will have frozen
3808                --  everything before. The new default values have not been
3809                --  expanded, so expand now to check conformance.
3810
3811                if NewD then
3812                   Preanalyze_Spec_Expression
3813                     (Expression (New_Discr), New_Discr_Type);
3814                end if;
3815
3816                if not (NewD and OldD)
3817                  or else not Fully_Conformant_Expressions
3818                               (Expression (Parent (Old_Discr)),
3819                                Expression (New_Discr))
3820
3821                then
3822                   Conformance_Error
3823                     ("default expression for & does not match!",
3824                      New_Discr_Id);
3825                   return;
3826                end if;
3827             end if;
3828          end;
3829
3830          --  In Ada 83 case, grouping must match: (A,B : X) /= (A : X; B : X)
3831
3832          if Ada_Version = Ada_83 then
3833             declare
3834                Old_Disc : constant Node_Id := Declaration_Node (Old_Discr);
3835
3836             begin
3837                --  Grouping (use of comma in param lists) must be the same
3838                --  This is where we catch a misconformance like:
3839
3840                --    A,B : Integer
3841                --    A : Integer; B : Integer
3842
3843                --  which are represented identically in the tree except
3844                --  for the setting of the flags More_Ids and Prev_Ids.
3845
3846                if More_Ids (Old_Disc) /= More_Ids (New_Discr)
3847                  or else Prev_Ids (Old_Disc) /= Prev_Ids (New_Discr)
3848                then
3849                   Conformance_Error
3850                     ("grouping of & does not match!", New_Discr_Id);
3851                   return;
3852                end if;
3853             end;
3854          end if;
3855
3856          Next_Discriminant (Old_Discr);
3857          Next (New_Discr);
3858       end loop;
3859
3860       if Present (Old_Discr) then
3861          Conformance_Error ("too few discriminants!", Defining_Identifier (N));
3862          return;
3863
3864       elsif Present (New_Discr) then
3865          Conformance_Error
3866            ("too many discriminants!", Defining_Identifier (New_Discr));
3867          return;
3868       end if;
3869    end Check_Discriminant_Conformance;
3870
3871    ----------------------------
3872    -- Check_Fully_Conformant --
3873    ----------------------------
3874
3875    procedure Check_Fully_Conformant
3876      (New_Id  : Entity_Id;
3877       Old_Id  : Entity_Id;
3878       Err_Loc : Node_Id := Empty)
3879    is
3880       Result : Boolean;
3881       pragma Warnings (Off, Result);
3882    begin
3883       Check_Conformance
3884         (New_Id, Old_Id, Fully_Conformant, True, Result, Err_Loc);
3885    end Check_Fully_Conformant;
3886
3887    ---------------------------
3888    -- Check_Mode_Conformant --
3889    ---------------------------
3890
3891    procedure Check_Mode_Conformant
3892      (New_Id   : Entity_Id;
3893       Old_Id   : Entity_Id;
3894       Err_Loc  : Node_Id := Empty;
3895       Get_Inst : Boolean := False)
3896    is
3897       Result : Boolean;
3898       pragma Warnings (Off, Result);
3899    begin
3900       Check_Conformance
3901         (New_Id, Old_Id, Mode_Conformant, True, Result, Err_Loc, Get_Inst);
3902    end Check_Mode_Conformant;
3903
3904    --------------------------------
3905    -- Check_Overriding_Indicator --
3906    --------------------------------
3907
3908    procedure Check_Overriding_Indicator
3909      (Subp            : Entity_Id;
3910       Overridden_Subp : Entity_Id;
3911       Is_Primitive    : Boolean)
3912    is
3913       Decl : Node_Id;
3914       Spec : Node_Id;
3915
3916    begin
3917       --  No overriding indicator for literals
3918
3919       if Ekind (Subp) = E_Enumeration_Literal then
3920          return;
3921
3922       elsif Ekind (Subp) = E_Entry then
3923          Decl := Parent (Subp);
3924
3925       else
3926          Decl := Unit_Declaration_Node (Subp);
3927       end if;
3928
3929       if Nkind_In (Decl, N_Subprogram_Body,
3930                          N_Subprogram_Body_Stub,
3931                          N_Subprogram_Declaration,
3932                          N_Abstract_Subprogram_Declaration,
3933                          N_Subprogram_Renaming_Declaration)
3934       then
3935          Spec := Specification (Decl);
3936
3937       elsif Nkind (Decl) = N_Entry_Declaration then
3938          Spec := Decl;
3939
3940       else
3941          return;
3942       end if;
3943
3944       if Present (Overridden_Subp) then
3945          if Must_Not_Override (Spec) then
3946             Error_Msg_Sloc := Sloc (Overridden_Subp);
3947
3948             if Ekind (Subp) = E_Entry then
3949                Error_Msg_NE
3950                  ("entry & overrides inherited operation #", Spec, Subp);
3951             else
3952                Error_Msg_NE
3953                  ("subprogram & overrides inherited operation #", Spec, Subp);
3954             end if;
3955
3956          elsif Is_Subprogram (Subp) then
3957             Set_Is_Overriding_Operation (Subp);
3958          end if;
3959
3960       --  If Subp is an operator, it may override a predefined operation.
3961       --  In that case overridden_subp is empty because of our implicit
3962       --  representation for predefined operators. We have to check whether the
3963       --  signature of Subp matches that of a predefined operator. Note that
3964       --  first argument provides the name of the operator, and the second
3965       --  argument the signature that may match that of a standard operation.
3966       --  If the indicator is overriding, then the operator must match a
3967       --  predefined signature, because we know already that there is no
3968       --  explicit overridden operation.
3969
3970       elsif Nkind (Subp) = N_Defining_Operator_Symbol then
3971
3972          if Must_Not_Override (Spec) then
3973             if not Is_Primitive then
3974                Error_Msg_N
3975                  ("overriding indicator only allowed "
3976                     & "if subprogram is primitive", Subp);
3977
3978             elsif Operator_Matches_Spec (Subp, Subp) then
3979                Error_Msg_NE
3980                  ("subprogram & overrides predefined operator ", Spec, Subp);
3981             end if;
3982
3983          elsif Is_Overriding_Operation (Subp) then
3984             null;
3985
3986          elsif Must_Override (Spec) then
3987             if not Operator_Matches_Spec (Subp, Subp) then
3988                Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
3989
3990             else
3991                Set_Is_Overriding_Operation (Subp);
3992             end if;
3993          end if;
3994
3995       elsif Must_Override (Spec) then
3996          if Ekind (Subp) = E_Entry then
3997             Error_Msg_NE ("entry & is not overriding", Spec, Subp);
3998          else
3999             Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
4000          end if;
4001
4002       --  If the operation is marked "not overriding" and it's not primitive
4003       --  then an error is issued, unless this is an operation of a task or
4004       --  protected type (RM05-8.3.1(3/2-4/2)). Error cases where "overriding"
4005       --  has been specified have already been checked above.
4006
4007       elsif Must_Not_Override (Spec)
4008         and then not Is_Primitive
4009         and then Ekind (Subp) /= E_Entry
4010         and then Ekind (Scope (Subp)) /= E_Protected_Type
4011       then
4012          Error_Msg_N
4013            ("overriding indicator only allowed if subprogram is primitive",
4014             Subp);
4015          return;
4016       end if;
4017    end Check_Overriding_Indicator;
4018
4019    -------------------
4020    -- Check_Returns --
4021    -------------------
4022
4023    --  Note: this procedure needs to know far too much about how the expander
4024    --  messes with exceptions. The use of the flag Exception_Junk and the
4025    --  incorporation of knowledge of Exp_Ch11.Expand_Local_Exception_Handlers
4026    --  works, but is not very clean. It would be better if the expansion
4027    --  routines would leave Original_Node working nicely, and we could use
4028    --  Original_Node here to ignore all the peculiar expander messing ???
4029
4030    procedure Check_Returns
4031      (HSS  : Node_Id;
4032       Mode : Character;
4033       Err  : out Boolean;
4034       Proc : Entity_Id := Empty)
4035    is
4036       Handler : Node_Id;
4037
4038       procedure Check_Statement_Sequence (L : List_Id);
4039       --  Internal recursive procedure to check a list of statements for proper
4040       --  termination by a return statement (or a transfer of control or a
4041       --  compound statement that is itself internally properly terminated).
4042
4043       ------------------------------
4044       -- Check_Statement_Sequence --
4045       ------------------------------
4046
4047       procedure Check_Statement_Sequence (L : List_Id) is
4048          Last_Stm : Node_Id;
4049          Stm      : Node_Id;
4050          Kind     : Node_Kind;
4051
4052          Raise_Exception_Call : Boolean;
4053          --  Set True if statement sequence terminated by Raise_Exception call
4054          --  or a Reraise_Occurrence call.
4055
4056       begin
4057          Raise_Exception_Call := False;
4058
4059          --  Get last real statement
4060
4061          Last_Stm := Last (L);
4062
4063          --  Deal with digging out exception handler statement sequences that
4064          --  have been transformed by the local raise to goto optimization.
4065          --  See Exp_Ch11.Expand_Local_Exception_Handlers for details. If this
4066          --  optimization has occurred, we are looking at something like:
4067
4068          --  begin
4069          --     original stmts in block
4070
4071          --  exception            \
4072          --     when excep1 =>     |
4073          --        goto L1;        | omitted if No_Exception_Propagation
4074          --     when excep2 =>     |
4075          --        goto L2;       /
4076          --  end;
4077
4078          --  goto L3;      -- skip handler when exception not raised
4079
4080          --  <<L1>>        -- target label for local exception
4081          --     begin
4082          --        estmts1
4083          --     end;
4084
4085          --     goto L3;
4086
4087          --  <<L2>>
4088          --     begin
4089          --        estmts2
4090          --     end;
4091
4092          --  <<L3>>
4093
4094          --  and what we have to do is to dig out the estmts1 and estmts2
4095          --  sequences (which were the original sequences of statements in
4096          --  the exception handlers) and check them.
4097
4098          if Nkind (Last_Stm) = N_Label
4099            and then Exception_Junk (Last_Stm)
4100          then
4101             Stm := Last_Stm;
4102             loop
4103                Prev (Stm);
4104                exit when No (Stm);
4105                exit when Nkind (Stm) /= N_Block_Statement;
4106                exit when not Exception_Junk (Stm);
4107                Prev (Stm);
4108                exit when No (Stm);
4109                exit when Nkind (Stm) /= N_Label;
4110                exit when not Exception_Junk (Stm);
4111                Check_Statement_Sequence
4112                  (Statements (Handled_Statement_Sequence (Next (Stm))));
4113
4114                Prev (Stm);
4115                Last_Stm := Stm;
4116                exit when No (Stm);
4117                exit when Nkind (Stm) /= N_Goto_Statement;
4118                exit when not Exception_Junk (Stm);
4119             end loop;
4120          end if;
4121
4122          --  Don't count pragmas
4123
4124          while Nkind (Last_Stm) = N_Pragma
4125
4126          --  Don't count call to SS_Release (can happen after Raise_Exception)
4127
4128            or else
4129              (Nkind (Last_Stm) = N_Procedure_Call_Statement
4130                 and then
4131               Nkind (Name (Last_Stm)) = N_Identifier
4132                 and then
4133               Is_RTE (Entity (Name (Last_Stm)), RE_SS_Release))
4134
4135          --  Don't count exception junk
4136
4137            or else
4138              (Nkind_In (Last_Stm, N_Goto_Statement,
4139                                    N_Label,
4140                                    N_Object_Declaration)
4141                 and then Exception_Junk (Last_Stm))
4142            or else Nkind (Last_Stm) in N_Push_xxx_Label
4143            or else Nkind (Last_Stm) in N_Pop_xxx_Label
4144          loop
4145             Prev (Last_Stm);
4146          end loop;
4147
4148          --  Here we have the "real" last statement
4149
4150          Kind := Nkind (Last_Stm);
4151
4152          --  Transfer of control, OK. Note that in the No_Return procedure
4153          --  case, we already diagnosed any explicit return statements, so
4154          --  we can treat them as OK in this context.
4155
4156          if Is_Transfer (Last_Stm) then
4157             return;
4158
4159          --  Check cases of explicit non-indirect procedure calls
4160
4161          elsif Kind = N_Procedure_Call_Statement
4162            and then Is_Entity_Name (Name (Last_Stm))
4163          then
4164             --  Check call to Raise_Exception procedure which is treated
4165             --  specially, as is a call to Reraise_Occurrence.
4166
4167             --  We suppress the warning in these cases since it is likely that
4168             --  the programmer really does not expect to deal with the case
4169             --  of Null_Occurrence, and thus would find a warning about a
4170             --  missing return curious, and raising Program_Error does not
4171             --  seem such a bad behavior if this does occur.
4172
4173             --  Note that in the Ada 2005 case for Raise_Exception, the actual
4174             --  behavior will be to raise Constraint_Error (see AI-329).
4175
4176             if Is_RTE (Entity (Name (Last_Stm)), RE_Raise_Exception)
4177                  or else
4178                Is_RTE (Entity (Name (Last_Stm)), RE_Reraise_Occurrence)
4179             then
4180                Raise_Exception_Call := True;
4181
4182                --  For Raise_Exception call, test first argument, if it is
4183                --  an attribute reference for a 'Identity call, then we know
4184                --  that the call cannot possibly return.
4185
4186                declare
4187                   Arg : constant Node_Id :=
4188                           Original_Node (First_Actual (Last_Stm));
4189                begin
4190                   if Nkind (Arg) = N_Attribute_Reference
4191                     and then Attribute_Name (Arg) = Name_Identity
4192                   then
4193                      return;
4194                   end if;
4195                end;
4196             end if;
4197
4198          --  If statement, need to look inside if there is an else and check
4199          --  each constituent statement sequence for proper termination.
4200
4201          elsif Kind = N_If_Statement
4202            and then Present (Else_Statements (Last_Stm))
4203          then
4204             Check_Statement_Sequence (Then_Statements (Last_Stm));
4205             Check_Statement_Sequence (Else_Statements (Last_Stm));
4206
4207             if Present (Elsif_Parts (Last_Stm)) then
4208                declare
4209                   Elsif_Part : Node_Id := First (Elsif_Parts (Last_Stm));
4210
4211                begin
4212                   while Present (Elsif_Part) loop
4213                      Check_Statement_Sequence (Then_Statements (Elsif_Part));
4214                      Next (Elsif_Part);
4215                   end loop;
4216                end;
4217             end if;
4218
4219             return;
4220
4221          --  Case statement, check each case for proper termination
4222
4223          elsif Kind = N_Case_Statement then
4224             declare
4225                Case_Alt : Node_Id;
4226             begin
4227                Case_Alt := First_Non_Pragma (Alternatives (Last_Stm));
4228                while Present (Case_Alt) loop
4229                   Check_Statement_Sequence (Statements (Case_Alt));
4230                   Next_Non_Pragma (Case_Alt);
4231                end loop;
4232             end;
4233
4234             return;
4235
4236          --  Block statement, check its handled sequence of statements
4237
4238          elsif Kind = N_Block_Statement then
4239             declare
4240                Err1 : Boolean;
4241
4242             begin
4243                Check_Returns
4244                  (Handled_Statement_Sequence (Last_Stm), Mode, Err1);
4245
4246                if Err1 then
4247                   Err := True;
4248                end if;
4249
4250                return;
4251             end;
4252
4253          --  Loop statement. If there is an iteration scheme, we can definitely
4254          --  fall out of the loop. Similarly if there is an exit statement, we
4255          --  can fall out. In either case we need a following return.
4256
4257          elsif Kind = N_Loop_Statement then
4258             if Present (Iteration_Scheme (Last_Stm))
4259               or else Has_Exit (Entity (Identifier (Last_Stm)))
4260             then
4261                null;
4262
4263             --  A loop with no exit statement or iteration scheme is either
4264             --  an infinite loop, or it has some other exit (raise/return).
4265             --  In either case, no warning is required.
4266
4267             else
4268                return;
4269             end if;
4270
4271          --  Timed entry call, check entry call and delay alternatives
4272
4273          --  Note: in expanded code, the timed entry call has been converted
4274          --  to a set of expanded statements on which the check will work
4275          --  correctly in any case.
4276
4277          elsif Kind = N_Timed_Entry_Call then
4278             declare
4279                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
4280                DCA : constant Node_Id := Delay_Alternative      (Last_Stm);
4281
4282             begin
4283                --  If statement sequence of entry call alternative is missing,
4284                --  then we can definitely fall through, and we post the error
4285                --  message on the entry call alternative itself.
4286
4287                if No (Statements (ECA)) then
4288                   Last_Stm := ECA;
4289
4290                --  If statement sequence of delay alternative is missing, then
4291                --  we can definitely fall through, and we post the error
4292                --  message on the delay alternative itself.
4293
4294                --  Note: if both ECA and DCA are missing the return, then we
4295                --  post only one message, should be enough to fix the bugs.
4296                --  If not we will get a message next time on the DCA when the
4297                --  ECA is fixed!
4298
4299                elsif No (Statements (DCA)) then
4300                   Last_Stm := DCA;
4301
4302                --  Else check both statement sequences
4303
4304                else
4305                   Check_Statement_Sequence (Statements (ECA));
4306                   Check_Statement_Sequence (Statements (DCA));
4307                   return;
4308                end if;
4309             end;
4310
4311          --  Conditional entry call, check entry call and else part
4312
4313          --  Note: in expanded code, the conditional entry call has been
4314          --  converted to a set of expanded statements on which the check
4315          --  will work correctly in any case.
4316
4317          elsif Kind = N_Conditional_Entry_Call then
4318             declare
4319                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
4320
4321             begin
4322                --  If statement sequence of entry call alternative is missing,
4323                --  then we can definitely fall through, and we post the error
4324                --  message on the entry call alternative itself.
4325
4326                if No (Statements (ECA)) then
4327                   Last_Stm := ECA;
4328
4329                --  Else check statement sequence and else part
4330
4331                else
4332                   Check_Statement_Sequence (Statements (ECA));
4333                   Check_Statement_Sequence (Else_Statements (Last_Stm));
4334                   return;
4335                end if;
4336             end;
4337          end if;
4338
4339          --  If we fall through, issue appropriate message
4340
4341          if Mode = 'F' then
4342             if not Raise_Exception_Call then
4343                Error_Msg_N
4344                  ("?RETURN statement missing following this statement!",
4345                   Last_Stm);
4346                Error_Msg_N
4347                  ("\?Program_Error may be raised at run time!",
4348                   Last_Stm);
4349             end if;
4350
4351             --  Note: we set Err even though we have not issued a warning
4352             --  because we still have a case of a missing return. This is
4353             --  an extremely marginal case, probably will never be noticed
4354             --  but we might as well get it right.
4355
4356             Err := True;
4357
4358          --  Otherwise we have the case of a procedure marked No_Return
4359
4360          else
4361             if not Raise_Exception_Call then
4362                Error_Msg_N
4363                  ("?implied return after this statement " &
4364                   "will raise Program_Error",
4365                   Last_Stm);
4366                Error_Msg_NE
4367                  ("\?procedure & is marked as No_Return!",
4368                   Last_Stm, Proc);
4369             end if;
4370
4371             declare
4372                RE : constant Node_Id :=
4373                       Make_Raise_Program_Error (Sloc (Last_Stm),
4374                         Reason => PE_Implicit_Return);
4375             begin
4376                Insert_After (Last_Stm, RE);
4377                Analyze (RE);
4378             end;
4379          end if;
4380       end Check_Statement_Sequence;
4381
4382    --  Start of processing for Check_Returns
4383
4384    begin
4385       Err := False;
4386       Check_Statement_Sequence (Statements (HSS));
4387
4388       if Present (Exception_Handlers (HSS)) then
4389          Handler := First_Non_Pragma (Exception_Handlers (HSS));
4390          while Present (Handler) loop
4391             Check_Statement_Sequence (Statements (Handler));
4392             Next_Non_Pragma (Handler);
4393          end loop;
4394       end if;
4395    end Check_Returns;
4396
4397    ----------------------------
4398    -- Check_Subprogram_Order --
4399    ----------------------------
4400
4401    procedure Check_Subprogram_Order (N : Node_Id) is
4402
4403       function Subprogram_Name_Greater (S1, S2 : String) return Boolean;
4404       --  This is used to check if S1 > S2 in the sense required by this
4405       --  test, for example nameab < namec, but name2 < name10.
4406
4407       -----------------------------
4408       -- Subprogram_Name_Greater --
4409       -----------------------------
4410
4411       function Subprogram_Name_Greater (S1, S2 : String) return Boolean is
4412          L1, L2 : Positive;
4413          N1, N2 : Natural;
4414
4415       begin
4416          --  Remove trailing numeric parts
4417
4418          L1 := S1'Last;
4419          while S1 (L1) in '0' .. '9' loop
4420             L1 := L1 - 1;
4421          end loop;
4422
4423          L2 := S2'Last;
4424          while S2 (L2) in '0' .. '9' loop
4425             L2 := L2 - 1;
4426          end loop;
4427
4428          --  If non-numeric parts non-equal, that's decisive
4429
4430          if S1 (S1'First .. L1) < S2 (S2'First .. L2) then
4431             return False;
4432
4433          elsif S1 (S1'First .. L1) > S2 (S2'First .. L2) then
4434             return True;
4435
4436          --  If non-numeric parts equal, compare suffixed numeric parts. Note
4437          --  that a missing suffix is treated as numeric zero in this test.
4438
4439          else
4440             N1 := 0;
4441             while L1 < S1'Last loop
4442                L1 := L1 + 1;
4443                N1 := N1 * 10 + Character'Pos (S1 (L1)) - Character'Pos ('0');
4444             end loop;
4445
4446             N2 := 0;
4447             while L2 < S2'Last loop
4448                L2 := L2 + 1;
4449                N2 := N2 * 10 + Character'Pos (S2 (L2)) - Character'Pos ('0');
4450             end loop;
4451
4452             return N1 > N2;
4453          end if;
4454       end Subprogram_Name_Greater;
4455
4456    --  Start of processing for Check_Subprogram_Order
4457
4458    begin
4459       --  Check body in alpha order if this is option
4460
4461       if Style_Check
4462         and then Style_Check_Order_Subprograms
4463         and then Nkind (N) = N_Subprogram_Body
4464         and then Comes_From_Source (N)
4465         and then In_Extended_Main_Source_Unit (N)
4466       then
4467          declare
4468             LSN : String_Ptr
4469                     renames Scope_Stack.Table
4470                               (Scope_Stack.Last).Last_Subprogram_Name;
4471
4472             Body_Id : constant Entity_Id :=
4473                         Defining_Entity (Specification (N));
4474
4475          begin
4476             Get_Decoded_Name_String (Chars (Body_Id));
4477
4478             if LSN /= null then
4479                if Subprogram_Name_Greater
4480                     (LSN.all, Name_Buffer (1 .. Name_Len))
4481                then
4482                   Style.Subprogram_Not_In_Alpha_Order (Body_Id);
4483                end if;
4484
4485                Free (LSN);
4486             end if;
4487
4488             LSN := new String'(Name_Buffer (1 .. Name_Len));
4489          end;
4490       end if;
4491    end Check_Subprogram_Order;
4492
4493    ------------------------------
4494    -- Check_Subtype_Conformant --
4495    ------------------------------
4496
4497    procedure Check_Subtype_Conformant
4498      (New_Id  : Entity_Id;
4499       Old_Id  : Entity_Id;
4500       Err_Loc : Node_Id := Empty)
4501    is
4502       Result : Boolean;
4503       pragma Warnings (Off, Result);
4504    begin
4505       Check_Conformance
4506         (New_Id, Old_Id, Subtype_Conformant, True, Result, Err_Loc);
4507    end Check_Subtype_Conformant;
4508
4509    ---------------------------
4510    -- Check_Type_Conformant --
4511    ---------------------------
4512
4513    procedure Check_Type_Conformant
4514      (New_Id  : Entity_Id;
4515       Old_Id  : Entity_Id;
4516       Err_Loc : Node_Id := Empty)
4517    is
4518       Result : Boolean;
4519       pragma Warnings (Off, Result);
4520    begin
4521       Check_Conformance
4522         (New_Id, Old_Id, Type_Conformant, True, Result, Err_Loc);
4523    end Check_Type_Conformant;
4524
4525    ----------------------
4526    -- Conforming_Types --
4527    ----------------------
4528
4529    function Conforming_Types
4530      (T1       : Entity_Id;
4531       T2       : Entity_Id;
4532       Ctype    : Conformance_Type;
4533       Get_Inst : Boolean := False) return Boolean
4534    is
4535       Type_1 : Entity_Id := T1;
4536       Type_2 : Entity_Id := T2;
4537       Are_Anonymous_Access_To_Subprogram_Types : Boolean := False;
4538
4539       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean;
4540       --  If neither T1 nor T2 are generic actual types, or if they are in
4541       --  different scopes (e.g. parent and child instances), then verify that
4542       --  the base types are equal. Otherwise T1 and T2 must be on the same
4543       --  subtype chain. The whole purpose of this procedure is to prevent
4544       --  spurious ambiguities in an instantiation that may arise if two
4545       --  distinct generic types are instantiated with the same actual.
4546
4547       function Find_Designated_Type (T : Entity_Id) return Entity_Id;
4548       --  An access parameter can designate an incomplete type. If the
4549       --  incomplete type is the limited view of a type from a limited_
4550       --  with_clause, check whether the non-limited view is available. If
4551       --  it is a (non-limited) incomplete type, get the full view.
4552
4553       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean;
4554       --  Returns True if and only if either T1 denotes a limited view of T2
4555       --  or T2 denotes a limited view of T1. This can arise when the limited
4556       --  with view of a type is used in a subprogram declaration and the
4557       --  subprogram body is in the scope of a regular with clause for the
4558       --  same unit. In such a case, the two type entities can be considered
4559       --  identical for purposes of conformance checking.
4560
4561       ----------------------
4562       -- Base_Types_Match --
4563       ----------------------
4564
4565       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean is
4566       begin
4567          if T1 = T2 then
4568             return True;
4569
4570          elsif Base_Type (T1) = Base_Type (T2) then
4571
4572             --  The following is too permissive. A more precise test should
4573             --  check that the generic actual is an ancestor subtype of the
4574             --  other ???.
4575
4576             return not Is_Generic_Actual_Type (T1)
4577               or else not Is_Generic_Actual_Type (T2)
4578               or else Scope (T1) /= Scope (T2);
4579
4580          else
4581             return False;
4582          end if;
4583       end Base_Types_Match;
4584
4585       --------------------------
4586       -- Find_Designated_Type --
4587       --------------------------
4588
4589       function Find_Designated_Type (T : Entity_Id) return Entity_Id is
4590          Desig : Entity_Id;
4591
4592       begin
4593          Desig := Directly_Designated_Type (T);
4594
4595          if Ekind (Desig) = E_Incomplete_Type then
4596
4597             --  If regular incomplete type, get full view if available
4598
4599             if Present (Full_View (Desig)) then
4600                Desig := Full_View (Desig);
4601
4602             --  If limited view of a type, get non-limited view if available,
4603             --  and check again for a regular incomplete type.
4604
4605             elsif Present (Non_Limited_View (Desig)) then
4606                Desig := Get_Full_View (Non_Limited_View (Desig));
4607             end if;
4608          end if;
4609
4610          return Desig;
4611       end Find_Designated_Type;
4612
4613       -------------------------------
4614       -- Matches_Limited_With_View --
4615       -------------------------------
4616
4617       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean is
4618       begin
4619          --  In some cases a type imported through a limited_with clause, and
4620          --  its nonlimited view are both visible, for example in an anonymous
4621          --  access-to-class-wide type in a formal. Both entities designate the
4622          --  same type.
4623
4624          if From_With_Type (T1)
4625            and then T2 = Available_View (T1)
4626          then
4627             return True;
4628
4629          elsif From_With_Type (T2)
4630            and then T1 = Available_View (T2)
4631          then
4632             return True;
4633
4634          else
4635             return False;
4636          end if;
4637       end Matches_Limited_With_View;
4638
4639    --  Start of processing for Conforming_Types
4640
4641    begin
4642       --  The context is an instance association for a formal
4643       --  access-to-subprogram type; the formal parameter types require
4644       --  mapping because they may denote other formal parameters of the
4645       --  generic unit.
4646
4647       if Get_Inst then
4648          Type_1 := Get_Instance_Of (T1);
4649          Type_2 := Get_Instance_Of (T2);
4650       end if;
4651
4652       --  If one of the types is a view of the other introduced by a limited
4653       --  with clause, treat these as conforming for all purposes.
4654
4655       if Matches_Limited_With_View (T1, T2) then
4656          return True;
4657
4658       elsif Base_Types_Match (Type_1, Type_2) then
4659          return Ctype <= Mode_Conformant
4660            or else Subtypes_Statically_Match (Type_1, Type_2);
4661
4662       elsif Is_Incomplete_Or_Private_Type (Type_1)
4663         and then Present (Full_View (Type_1))
4664         and then Base_Types_Match (Full_View (Type_1), Type_2)
4665       then
4666          return Ctype <= Mode_Conformant
4667            or else Subtypes_Statically_Match (Full_View (Type_1), Type_2);
4668
4669       elsif Ekind (Type_2) = E_Incomplete_Type
4670         and then Present (Full_View (Type_2))
4671         and then Base_Types_Match (Type_1, Full_View (Type_2))
4672       then
4673          return Ctype <= Mode_Conformant
4674            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
4675
4676       elsif Is_Private_Type (Type_2)
4677         and then In_Instance
4678         and then Present (Full_View (Type_2))
4679         and then Base_Types_Match (Type_1, Full_View (Type_2))
4680       then
4681          return Ctype <= Mode_Conformant
4682            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
4683       end if;
4684
4685       --  Ada 2005 (AI-254): Anonymous access-to-subprogram types must be
4686       --  treated recursively because they carry a signature.
4687
4688       Are_Anonymous_Access_To_Subprogram_Types :=
4689         Ekind (Type_1) = Ekind (Type_2)
4690           and then
4691             (Ekind (Type_1) = E_Anonymous_Access_Subprogram_Type
4692              or else
4693                Ekind (Type_1) = E_Anonymous_Access_Protected_Subprogram_Type);
4694
4695       --  Test anonymous access type case. For this case, static subtype
4696       --  matching is required for mode conformance (RM 6.3.1(15)). We check
4697       --  the base types because we may have built internal subtype entities
4698       --  to handle null-excluding types (see Process_Formals).
4699
4700       if (Ekind (Base_Type (Type_1)) = E_Anonymous_Access_Type
4701             and then
4702           Ekind (Base_Type (Type_2)) = E_Anonymous_Access_Type)
4703         or else Are_Anonymous_Access_To_Subprogram_Types -- Ada 2005 (AI-254)
4704       then
4705          declare
4706             Desig_1 : Entity_Id;
4707             Desig_2 : Entity_Id;
4708
4709          begin
4710             --  In Ada2005, access constant indicators must match for
4711             --  subtype conformance.
4712
4713             if Ada_Version >= Ada_05
4714               and then Ctype >= Subtype_Conformant
4715               and then
4716                 Is_Access_Constant (Type_1) /= Is_Access_Constant (Type_2)
4717             then
4718                return False;
4719             end if;
4720
4721             Desig_1 := Find_Designated_Type (Type_1);
4722
4723             Desig_2 := Find_Designated_Type (Type_2);
4724
4725             --  If the context is an instance association for a formal
4726             --  access-to-subprogram type; formal access parameter designated
4727             --  types require mapping because they may denote other formal
4728             --  parameters of the generic unit.
4729
4730             if Get_Inst then
4731                Desig_1 := Get_Instance_Of (Desig_1);
4732                Desig_2 := Get_Instance_Of (Desig_2);
4733             end if;
4734
4735             --  It is possible for a Class_Wide_Type to be introduced for an
4736             --  incomplete type, in which case there is a separate class_ wide
4737             --  type for the full view. The types conform if their Etypes
4738             --  conform, i.e. one may be the full view of the other. This can
4739             --  only happen in the context of an access parameter, other uses
4740             --  of an incomplete Class_Wide_Type are illegal.
4741
4742             if Is_Class_Wide_Type (Desig_1)
4743               and then Is_Class_Wide_Type (Desig_2)
4744             then
4745                return
4746                  Conforming_Types
4747                    (Etype (Base_Type (Desig_1)),
4748                     Etype (Base_Type (Desig_2)), Ctype);
4749
4750             elsif Are_Anonymous_Access_To_Subprogram_Types then
4751                if Ada_Version < Ada_05 then
4752                   return Ctype = Type_Conformant
4753                     or else
4754                       Subtypes_Statically_Match (Desig_1, Desig_2);
4755
4756                --  We must check the conformance of the signatures themselves
4757
4758                else
4759                   declare
4760                      Conformant : Boolean;
4761                   begin
4762                      Check_Conformance
4763                        (Desig_1, Desig_2, Ctype, False, Conformant);
4764                      return Conformant;
4765                   end;
4766                end if;
4767
4768             else
4769                return Base_Type (Desig_1) = Base_Type (Desig_2)
4770                 and then (Ctype = Type_Conformant
4771                             or else
4772                           Subtypes_Statically_Match (Desig_1, Desig_2));
4773             end if;
4774          end;
4775
4776       --  Otherwise definitely no match
4777
4778       else
4779          if ((Ekind (Type_1) = E_Anonymous_Access_Type
4780                and then Is_Access_Type (Type_2))
4781             or else (Ekind (Type_2) = E_Anonymous_Access_Type
4782                        and then Is_Access_Type (Type_1)))
4783            and then
4784              Conforming_Types
4785                (Designated_Type (Type_1), Designated_Type (Type_2), Ctype)
4786          then
4787             May_Hide_Profile := True;
4788          end if;
4789
4790          return False;
4791       end if;
4792    end Conforming_Types;
4793
4794    --------------------------
4795    -- Create_Extra_Formals --
4796    --------------------------
4797
4798    procedure Create_Extra_Formals (E : Entity_Id) is
4799       Formal      : Entity_Id;
4800       First_Extra : Entity_Id := Empty;
4801       Last_Extra  : Entity_Id;
4802       Formal_Type : Entity_Id;
4803       P_Formal    : Entity_Id := Empty;
4804
4805       function Add_Extra_Formal
4806         (Assoc_Entity : Entity_Id;
4807          Typ          : Entity_Id;
4808          Scope        : Entity_Id;
4809          Suffix       : String) return Entity_Id;
4810       --  Add an extra formal to the current list of formals and extra formals.
4811       --  The extra formal is added to the end of the list of extra formals,
4812       --  and also returned as the result. These formals are always of mode IN.
4813       --  The new formal has the type Typ, is declared in Scope, and its name
4814       --  is given by a concatenation of the name of Assoc_Entity and Suffix.
4815
4816       ----------------------
4817       -- Add_Extra_Formal --
4818       ----------------------
4819
4820       function Add_Extra_Formal
4821         (Assoc_Entity : Entity_Id;
4822          Typ          : Entity_Id;
4823          Scope        : Entity_Id;
4824          Suffix       : String) return Entity_Id
4825       is
4826          EF : constant Entity_Id :=
4827                 Make_Defining_Identifier (Sloc (Assoc_Entity),
4828                   Chars  => New_External_Name (Chars (Assoc_Entity),
4829                                                Suffix => Suffix));
4830
4831       begin
4832          --  A little optimization. Never generate an extra formal for the
4833          --  _init operand of an initialization procedure, since it could
4834          --  never be used.
4835
4836          if Chars (Formal) = Name_uInit then
4837             return Empty;
4838          end if;
4839
4840          Set_Ekind           (EF, E_In_Parameter);
4841          Set_Actual_Subtype  (EF, Typ);
4842          Set_Etype           (EF, Typ);
4843          Set_Scope           (EF, Scope);
4844          Set_Mechanism       (EF, Default_Mechanism);
4845          Set_Formal_Validity (EF);
4846
4847          if No (First_Extra) then
4848             First_Extra := EF;
4849             Set_Extra_Formals (Scope, First_Extra);
4850          end if;
4851
4852          if Present (Last_Extra) then
4853             Set_Extra_Formal (Last_Extra, EF);
4854          end if;
4855
4856          Last_Extra := EF;
4857
4858          return EF;
4859       end Add_Extra_Formal;
4860
4861    --  Start of processing for Create_Extra_Formals
4862
4863    begin
4864       --  We never generate extra formals if expansion is not active
4865       --  because we don't need them unless we are generating code.
4866
4867       if not Expander_Active then
4868          return;
4869       end if;
4870
4871       --  If this is a derived subprogram then the subtypes of the parent
4872       --  subprogram's formal parameters will be used to to determine the need
4873       --  for extra formals.
4874
4875       if Is_Overloadable (E) and then Present (Alias (E)) then
4876          P_Formal := First_Formal (Alias (E));
4877       end if;
4878
4879       Last_Extra := Empty;
4880       Formal := First_Formal (E);
4881       while Present (Formal) loop
4882          Last_Extra := Formal;
4883          Next_Formal (Formal);
4884       end loop;
4885
4886       --  If Extra_formals were already created, don't do it again. This
4887       --  situation may arise for subprogram types created as part of
4888       --  dispatching calls (see Expand_Dispatching_Call)
4889
4890       if Present (Last_Extra) and then
4891         Present (Extra_Formal (Last_Extra))
4892       then
4893          return;
4894       end if;
4895
4896       --  If the subprogram is a predefined dispatching subprogram then don't
4897       --  generate any extra constrained or accessibility level formals. In
4898       --  general we suppress these for internal subprograms (by not calling
4899       --  Freeze_Subprogram and Create_Extra_Formals at all), but internally
4900       --  generated stream attributes do get passed through because extra
4901       --  build-in-place formals are needed in some cases (limited 'Input).
4902
4903       if Is_Predefined_Dispatching_Operation (E) then
4904          goto Test_For_BIP_Extras;
4905       end if;
4906
4907       Formal := First_Formal (E);
4908       while Present (Formal) loop
4909
4910          --  Create extra formal for supporting the attribute 'Constrained.
4911          --  The case of a private type view without discriminants also
4912          --  requires the extra formal if the underlying type has defaulted
4913          --  discriminants.
4914
4915          if Ekind (Formal) /= E_In_Parameter then
4916             if Present (P_Formal) then
4917                Formal_Type := Etype (P_Formal);
4918             else
4919                Formal_Type := Etype (Formal);
4920             end if;
4921
4922             --  Do not produce extra formals for Unchecked_Union parameters.
4923             --  Jump directly to the end of the loop.
4924
4925             if Is_Unchecked_Union (Base_Type (Formal_Type)) then
4926                goto Skip_Extra_Formal_Generation;
4927             end if;
4928
4929             if not Has_Discriminants (Formal_Type)
4930               and then Ekind (Formal_Type) in Private_Kind
4931               and then Present (Underlying_Type (Formal_Type))
4932             then
4933                Formal_Type := Underlying_Type (Formal_Type);
4934             end if;
4935
4936             if Has_Discriminants (Formal_Type)
4937               and then not Is_Constrained (Formal_Type)
4938               and then not Is_Indefinite_Subtype (Formal_Type)
4939             then
4940                Set_Extra_Constrained
4941                  (Formal, Add_Extra_Formal (Formal, Standard_Boolean, E, "F"));
4942             end if;
4943          end if;
4944
4945          --  Create extra formal for supporting accessibility checking. This
4946          --  is done for both anonymous access formals and formals of named
4947          --  access types that are marked as controlling formals. The latter
4948          --  case can occur when Expand_Dispatching_Call creates a subprogram
4949          --  type and substitutes the types of access-to-class-wide actuals
4950          --  for the anonymous access-to-specific-type of controlling formals.
4951          --  Base_Type is applied because in cases where there is a null
4952          --  exclusion the formal may have an access subtype.
4953
4954          --  This is suppressed if we specifically suppress accessibility
4955          --  checks at the package level for either the subprogram, or the
4956          --  package in which it resides. However, we do not suppress it
4957          --  simply if the scope has accessibility checks suppressed, since
4958          --  this could cause trouble when clients are compiled with a
4959          --  different suppression setting. The explicit checks at the
4960          --  package level are safe from this point of view.
4961
4962          if (Ekind (Base_Type (Etype (Formal))) = E_Anonymous_Access_Type
4963               or else (Is_Controlling_Formal (Formal)
4964                         and then Is_Access_Type (Base_Type (Etype (Formal)))))
4965            and then not
4966              (Explicit_Suppress (E, Accessibility_Check)
4967                or else
4968               Explicit_Suppress (Scope (E), Accessibility_Check))
4969            and then
4970              (No (P_Formal)
4971                or else Present (Extra_Accessibility (P_Formal)))
4972          then
4973             --  Temporary kludge: for now we avoid creating the extra formal
4974             --  for access parameters of protected operations because of
4975             --  problem with the case of internal protected calls. ???
4976
4977             if Nkind (Parent (Parent (Parent (E)))) /= N_Protected_Definition
4978               and then Nkind (Parent (Parent (Parent (E)))) /= N_Protected_Body
4979             then
4980                Set_Extra_Accessibility
4981                  (Formal, Add_Extra_Formal (Formal, Standard_Natural, E, "F"));
4982             end if;
4983          end if;
4984
4985          --  This label is required when skipping extra formal generation for
4986          --  Unchecked_Union parameters.
4987
4988          <<Skip_Extra_Formal_Generation>>
4989
4990          if Present (P_Formal) then
4991             Next_Formal (P_Formal);
4992          end if;
4993
4994          Next_Formal (Formal);
4995       end loop;
4996
4997       <<Test_For_BIP_Extras>>
4998
4999       --  Ada 2005 (AI-318-02): In the case of build-in-place functions, add
5000       --  appropriate extra formals. See type Exp_Ch6.BIP_Formal_Kind.
5001
5002       if Ada_Version >= Ada_05 and then Is_Build_In_Place_Function (E) then
5003          declare
5004             Result_Subt : constant Entity_Id := Etype (E);
5005
5006             Discard : Entity_Id;
5007             pragma Warnings (Off, Discard);
5008
5009          begin
5010             --  In the case of functions with unconstrained result subtypes,
5011             --  add a 3-state formal indicating whether the return object is
5012             --  allocated by the caller (0), or should be allocated by the
5013             --  callee on the secondary stack (1) or in the global heap (2).
5014             --  For the moment we just use Natural for the type of this formal.
5015             --  Note that this formal isn't usually needed in the case where
5016             --  the result subtype is constrained, but it is needed when the
5017             --  function has a tagged result, because generally such functions
5018             --  can be called in a dispatching context and such calls must be
5019             --  handled like calls to a class-wide function.
5020
5021             if not Is_Constrained (Result_Subt)
5022               or else Is_Tagged_Type (Underlying_Type (Result_Subt))
5023             then
5024                Discard :=
5025                  Add_Extra_Formal
5026                    (E, Standard_Natural,
5027                     E, BIP_Formal_Suffix (BIP_Alloc_Form));
5028             end if;
5029
5030             --  In the case of functions whose result type has controlled
5031             --  parts, we have an extra formal of type
5032             --  System.Finalization_Implementation.Finalizable_Ptr_Ptr. That
5033             --  is, we are passing a pointer to a finalization list (which is
5034             --  itself a pointer). This extra formal is then passed along to
5035             --  Move_Final_List in case of successful completion of a return
5036             --  statement. We cannot pass an 'in out' parameter, because we
5037             --  need to update the finalization list during an abort-deferred
5038             --  region, rather than using copy-back after the function
5039             --  returns. This is true even if we are able to get away with
5040             --  having 'in out' parameters, which are normally illegal for
5041             --  functions. This formal is also needed when the function has
5042             --  a tagged result, because generally such functions can be called
5043             --  in a dispatching context and such calls must be handled like
5044             --  calls to class-wide functions.
5045
5046             if Controlled_Type (Result_Subt)
5047               or else Is_Tagged_Type (Underlying_Type (Result_Subt))
5048             then
5049                Discard :=
5050                  Add_Extra_Formal
5051                    (E, RTE (RE_Finalizable_Ptr_Ptr),
5052                     E, BIP_Formal_Suffix (BIP_Final_List));
5053             end if;
5054
5055             --  If the result type contains tasks, we have two extra formals:
5056             --  the master of the tasks to be created, and the caller's
5057             --  activation chain.
5058
5059             if Has_Task (Result_Subt) then
5060                Discard :=
5061                  Add_Extra_Formal
5062                    (E, RTE (RE_Master_Id),
5063                     E, BIP_Formal_Suffix (BIP_Master));
5064                Discard :=
5065                  Add_Extra_Formal
5066                    (E, RTE (RE_Activation_Chain_Access),
5067                     E, BIP_Formal_Suffix (BIP_Activation_Chain));
5068             end if;
5069
5070             --  All build-in-place functions get an extra formal that will be
5071             --  passed the address of the return object within the caller.
5072
5073             declare
5074                Formal_Type : constant Entity_Id :=
5075                                Create_Itype
5076                                  (E_Anonymous_Access_Type, E,
5077                                   Scope_Id => Scope (E));
5078             begin
5079                Set_Directly_Designated_Type (Formal_Type, Result_Subt);
5080                Set_Etype (Formal_Type, Formal_Type);
5081                Set_Depends_On_Private
5082                  (Formal_Type, Has_Private_Component (Formal_Type));
5083                Set_Is_Public (Formal_Type, Is_Public (Scope (Formal_Type)));
5084                Set_Is_Access_Constant (Formal_Type, False);
5085
5086                --  Ada 2005 (AI-50217): Propagate the attribute that indicates
5087                --  the designated type comes from the limited view (for
5088                --  back-end purposes).
5089
5090                Set_From_With_Type (Formal_Type, From_With_Type (Result_Subt));
5091
5092                Layout_Type (Formal_Type);
5093
5094                Discard :=
5095                  Add_Extra_Formal
5096                    (E, Formal_Type, E, BIP_Formal_Suffix (BIP_Object_Access));
5097             end;
5098          end;
5099       end if;
5100    end Create_Extra_Formals;
5101
5102    -----------------------------
5103    -- Enter_Overloaded_Entity --
5104    -----------------------------
5105
5106    procedure Enter_Overloaded_Entity (S : Entity_Id) is
5107       E   : Entity_Id := Current_Entity_In_Scope (S);
5108       C_E : Entity_Id := Current_Entity (S);
5109
5110    begin
5111       if Present (E) then
5112          Set_Has_Homonym (E);
5113          Set_Has_Homonym (S);
5114       end if;
5115
5116       Set_Is_Immediately_Visible (S);
5117       Set_Scope (S, Current_Scope);
5118
5119       --  Chain new entity if front of homonym in current scope, so that
5120       --  homonyms are contiguous.
5121
5122       if Present (E)
5123         and then E /= C_E
5124       then
5125          while Homonym (C_E) /= E loop
5126             C_E := Homonym (C_E);
5127          end loop;
5128
5129          Set_Homonym (C_E, S);
5130
5131       else
5132          E := C_E;
5133          Set_Current_Entity (S);
5134       end if;
5135
5136       Set_Homonym (S, E);
5137
5138       Append_Entity (S, Current_Scope);
5139       Set_Public_Status (S);
5140
5141       if Debug_Flag_E then
5142          Write_Str ("New overloaded entity chain: ");
5143          Write_Name (Chars (S));
5144
5145          E := S;
5146          while Present (E) loop
5147             Write_Str (" "); Write_Int (Int (E));
5148             E := Homonym (E);
5149          end loop;
5150
5151          Write_Eol;
5152       end if;
5153
5154       --  Generate warning for hiding
5155
5156       if Warn_On_Hiding
5157         and then Comes_From_Source (S)
5158         and then In_Extended_Main_Source_Unit (S)
5159       then
5160          E := S;
5161          loop
5162             E := Homonym (E);
5163             exit when No (E);
5164
5165             --  Warn unless genuine overloading
5166
5167             if (not Is_Overloadable (E) or else Subtype_Conformant (E, S))
5168                   and then (Is_Immediately_Visible (E)
5169                               or else
5170                             Is_Potentially_Use_Visible (S))
5171             then
5172                Error_Msg_Sloc := Sloc (E);
5173                Error_Msg_N ("declaration of & hides one#?", S);
5174             end if;
5175          end loop;
5176       end if;
5177    end Enter_Overloaded_Entity;
5178
5179    -----------------------------
5180    -- Find_Corresponding_Spec --
5181    -----------------------------
5182
5183    function Find_Corresponding_Spec (N : Node_Id) return Entity_Id is
5184       Spec       : constant Node_Id   := Specification (N);
5185       Designator : constant Entity_Id := Defining_Entity (Spec);
5186
5187       E : Entity_Id;
5188
5189    begin
5190       E := Current_Entity (Designator);
5191       while Present (E) loop
5192
5193          --  We are looking for a matching spec. It must have the same scope,
5194          --  and the same name, and either be type conformant, or be the case
5195          --  of a library procedure spec and its body (which belong to one
5196          --  another regardless of whether they are type conformant or not).
5197
5198          if Scope (E) = Current_Scope then
5199             if Current_Scope = Standard_Standard
5200               or else (Ekind (E) = Ekind (Designator)
5201                          and then Type_Conformant (E, Designator))
5202             then
5203                --  Within an instantiation, we know that spec and body are
5204                --  subtype conformant, because they were subtype conformant
5205                --  in the generic. We choose the subtype-conformant entity
5206                --  here as well, to resolve spurious ambiguities in the
5207                --  instance that were not present in the generic (i.e. when
5208                --  two different types are given the same actual). If we are
5209                --  looking for a spec to match a body, full conformance is
5210                --  expected.
5211
5212                if In_Instance then
5213                   Set_Convention (Designator, Convention (E));
5214
5215                   if Nkind (N) = N_Subprogram_Body
5216                     and then Present (Homonym (E))
5217                     and then not Fully_Conformant (E, Designator)
5218                   then
5219                      goto Next_Entity;
5220
5221                   elsif not Subtype_Conformant (E, Designator) then
5222                      goto Next_Entity;
5223                   end if;
5224                end if;
5225
5226                if not Has_Completion (E) then
5227
5228                   if Nkind (N) /= N_Subprogram_Body_Stub then
5229                      Set_Corresponding_Spec (N, E);
5230                   end if;
5231
5232                   Set_Has_Completion (E);
5233                   return E;
5234
5235                elsif Nkind (Parent (N)) = N_Subunit then
5236
5237                   --  If this is the proper body of a subunit, the completion
5238                   --  flag is set when analyzing the stub.
5239
5240                   return E;
5241
5242                --  If E is an internal function with a controlling result
5243                --  that was created for an operation inherited by a null
5244                --  extension, it may be overridden by a body without a previous
5245                --  spec (one more reason why these should be shunned). In that
5246                --  case remove the generated body, because the current one is
5247                --  the explicit overriding.
5248
5249                elsif Ekind (E) = E_Function
5250                  and then Ada_Version >= Ada_05
5251                  and then not Comes_From_Source (E)
5252                  and then Has_Controlling_Result (E)
5253                  and then Is_Null_Extension (Etype (E))
5254                  and then Comes_From_Source (Spec)
5255                then
5256                   Set_Has_Completion (E, False);
5257
5258                   if Expander_Active then
5259                      Remove
5260                        (Unit_Declaration_Node
5261                          (Corresponding_Body (Unit_Declaration_Node (E))));
5262                      return E;
5263
5264                   --  If expansion is disabled, the wrapper function has not
5265                   --  been generated, and this is the standard case of a late
5266                   --  body overriding an inherited operation.
5267
5268                   else
5269                      return Empty;
5270                   end if;
5271
5272                --  If body already exists, this is an error unless the
5273                --  previous declaration is the implicit declaration of
5274                --  a derived subprogram, or this is a spurious overloading
5275                --  in an instance.
5276
5277                elsif No (Alias (E))
5278                  and then not Is_Intrinsic_Subprogram (E)
5279                  and then not In_Instance
5280                then
5281                   Error_Msg_Sloc := Sloc (E);
5282                   if Is_Imported (E) then
5283                      Error_Msg_NE
5284                       ("body not allowed for imported subprogram & declared#",
5285                         N, E);
5286                   else
5287                      Error_Msg_NE ("duplicate body for & declared#", N, E);
5288                   end if;
5289                end if;
5290
5291             elsif Is_Child_Unit (E)
5292               and then
5293                 Nkind (Unit_Declaration_Node (Designator)) = N_Subprogram_Body
5294               and then
5295                 Nkind (Parent (Unit_Declaration_Node (Designator))) =
5296                                                              N_Compilation_Unit
5297             then
5298                --  Child units cannot be overloaded, so a conformance mismatch
5299                --  between body and a previous spec is an error.
5300
5301                Error_Msg_N
5302                  ("body of child unit does not match previous declaration", N);
5303             end if;
5304          end if;
5305
5306          <<Next_Entity>>
5307             E := Homonym (E);
5308       end loop;
5309
5310       --  On exit, we know that no previous declaration of subprogram exists
5311
5312       return Empty;
5313    end Find_Corresponding_Spec;
5314
5315    ----------------------
5316    -- Fully_Conformant --
5317    ----------------------
5318
5319    function Fully_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
5320       Result : Boolean;
5321    begin
5322       Check_Conformance (New_Id, Old_Id, Fully_Conformant, False, Result);
5323       return Result;
5324    end Fully_Conformant;
5325
5326    ----------------------------------
5327    -- Fully_Conformant_Expressions --
5328    ----------------------------------
5329
5330    function Fully_Conformant_Expressions
5331      (Given_E1 : Node_Id;
5332       Given_E2 : Node_Id) return Boolean
5333    is
5334       E1 : constant Node_Id := Original_Node (Given_E1);
5335       E2 : constant Node_Id := Original_Node (Given_E2);
5336       --  We always test conformance on original nodes, since it is possible
5337       --  for analysis and/or expansion to make things look as though they
5338       --  conform when they do not, e.g. by converting 1+2 into 3.
5339
5340       function FCE (Given_E1, Given_E2 : Node_Id) return Boolean
5341         renames Fully_Conformant_Expressions;
5342
5343       function FCL (L1, L2 : List_Id) return Boolean;
5344       --  Compare elements of two lists for conformance. Elements have to
5345       --  be conformant, and actuals inserted as default parameters do not
5346       --  match explicit actuals with the same value.
5347
5348       function FCO (Op_Node, Call_Node : Node_Id) return Boolean;
5349       --  Compare an operator node with a function call
5350
5351       ---------
5352       -- FCL --
5353       ---------
5354
5355       function FCL (L1, L2 : List_Id) return Boolean is
5356          N1, N2 : Node_Id;
5357
5358       begin
5359          if L1 = No_List then
5360             N1 := Empty;
5361          else
5362             N1 := First (L1);
5363          end if;
5364
5365          if L2 = No_List then
5366             N2 := Empty;
5367          else
5368             N2 := First (L2);
5369          end if;
5370
5371          --  Compare two lists, skipping rewrite insertions (we want to
5372          --  compare the original trees, not the expanded versions!)
5373
5374          loop
5375             if Is_Rewrite_Insertion (N1) then
5376                Next (N1);
5377             elsif Is_Rewrite_Insertion (N2) then
5378                Next (N2);
5379             elsif No (N1) then
5380                return No (N2);
5381             elsif No (N2) then
5382                return False;
5383             elsif not FCE (N1, N2) then
5384                return False;
5385             else
5386                Next (N1);
5387                Next (N2);
5388             end if;
5389          end loop;
5390       end FCL;
5391
5392       ---------
5393       -- FCO --
5394       ---------
5395
5396       function FCO (Op_Node, Call_Node : Node_Id) return Boolean is
5397          Actuals : constant List_Id := Parameter_Associations (Call_Node);
5398          Act     : Node_Id;
5399
5400       begin
5401          if No (Actuals)
5402             or else Entity (Op_Node) /= Entity (Name (Call_Node))
5403          then
5404             return False;
5405
5406          else
5407             Act := First (Actuals);
5408
5409             if Nkind (Op_Node) in N_Binary_Op then
5410
5411                if not FCE (Left_Opnd (Op_Node), Act) then
5412                   return False;
5413                end if;
5414
5415                Next (Act);
5416             end if;
5417
5418             return Present (Act)
5419               and then FCE (Right_Opnd (Op_Node), Act)
5420               and then No (Next (Act));
5421          end if;
5422       end FCO;
5423
5424    --  Start of processing for Fully_Conformant_Expressions
5425
5426    begin
5427       --  Non-conformant if paren count does not match. Note: if some idiot
5428       --  complains that we don't do this right for more than 3 levels of
5429       --  parentheses, they will be treated with the respect they deserve!
5430
5431       if Paren_Count (E1) /= Paren_Count (E2) then
5432          return False;
5433
5434       --  If same entities are referenced, then they are conformant even if
5435       --  they have different forms (RM 8.3.1(19-20)).
5436
5437       elsif Is_Entity_Name (E1) and then Is_Entity_Name (E2) then
5438          if Present (Entity (E1)) then
5439             return Entity (E1) = Entity (E2)
5440               or else (Chars (Entity (E1)) = Chars (Entity (E2))
5441                         and then Ekind (Entity (E1)) = E_Discriminant
5442                         and then Ekind (Entity (E2)) = E_In_Parameter);
5443
5444          elsif Nkind (E1) = N_Expanded_Name
5445            and then Nkind (E2) = N_Expanded_Name
5446            and then Nkind (Selector_Name (E1)) = N_Character_Literal
5447            and then Nkind (Selector_Name (E2)) = N_Character_Literal
5448          then
5449             return Chars (Selector_Name (E1)) = Chars (Selector_Name (E2));
5450
5451          else
5452             --  Identifiers in component associations don't always have
5453             --  entities, but their names must conform.
5454
5455             return Nkind  (E1) = N_Identifier
5456               and then Nkind (E2) = N_Identifier
5457               and then Chars (E1) = Chars (E2);
5458          end if;
5459
5460       elsif Nkind (E1) = N_Character_Literal
5461         and then Nkind (E2) = N_Expanded_Name
5462       then
5463          return Nkind (Selector_Name (E2)) = N_Character_Literal
5464            and then Chars (E1) = Chars (Selector_Name (E2));
5465
5466       elsif Nkind (E2) = N_Character_Literal
5467         and then Nkind (E1) = N_Expanded_Name
5468       then
5469          return Nkind (Selector_Name (E1)) = N_Character_Literal
5470            and then Chars (E2) = Chars (Selector_Name (E1));
5471
5472       elsif Nkind (E1) in N_Op
5473         and then Nkind (E2) = N_Function_Call
5474       then
5475          return FCO (E1, E2);
5476
5477       elsif Nkind (E2) in N_Op
5478         and then Nkind (E1) = N_Function_Call
5479       then
5480          return FCO (E2, E1);
5481
5482       --  Otherwise we must have the same syntactic entity
5483
5484       elsif Nkind (E1) /= Nkind (E2) then
5485          return False;
5486
5487       --  At this point, we specialize by node type
5488
5489       else
5490          case Nkind (E1) is
5491
5492             when N_Aggregate =>
5493                return
5494                  FCL (Expressions (E1), Expressions (E2))
5495                    and then FCL (Component_Associations (E1),
5496                                  Component_Associations (E2));
5497
5498             when N_Allocator =>
5499                if Nkind (Expression (E1)) = N_Qualified_Expression
5500                     or else
5501                   Nkind (Expression (E2)) = N_Qualified_Expression
5502                then
5503                   return FCE (Expression (E1), Expression (E2));
5504
5505                --  Check that the subtype marks and any constraints
5506                --  are conformant
5507
5508                else
5509                   declare
5510                      Indic1 : constant Node_Id := Expression (E1);
5511                      Indic2 : constant Node_Id := Expression (E2);
5512                      Elt1   : Node_Id;
5513                      Elt2   : Node_Id;
5514
5515                   begin
5516                      if Nkind (Indic1) /= N_Subtype_Indication then
5517                         return
5518                           Nkind (Indic2) /= N_Subtype_Indication
5519                             and then Entity (Indic1) = Entity (Indic2);
5520
5521                      elsif Nkind (Indic2) /= N_Subtype_Indication then
5522                         return
5523                           Nkind (Indic1) /= N_Subtype_Indication
5524                             and then Entity (Indic1) = Entity (Indic2);
5525
5526                      else
5527                         if Entity (Subtype_Mark (Indic1)) /=
5528                           Entity (Subtype_Mark (Indic2))
5529                         then
5530                            return False;
5531                         end if;
5532
5533                         Elt1 := First (Constraints (Constraint (Indic1)));
5534                         Elt2 := First (Constraints (Constraint (Indic2)));
5535
5536                         while Present (Elt1) and then Present (Elt2) loop
5537                            if not FCE (Elt1, Elt2) then
5538                               return False;
5539                            end if;
5540
5541                            Next (Elt1);
5542                            Next (Elt2);
5543                         end loop;
5544
5545                         return True;
5546                      end if;
5547                   end;
5548                end if;
5549
5550             when N_Attribute_Reference =>
5551                return
5552                  Attribute_Name (E1) = Attribute_Name (E2)
5553                    and then FCL (Expressions (E1), Expressions (E2));
5554
5555             when N_Binary_Op =>
5556                return
5557                  Entity (E1) = Entity (E2)
5558                    and then FCE (Left_Opnd  (E1), Left_Opnd  (E2))
5559                    and then FCE (Right_Opnd (E1), Right_Opnd (E2));
5560
5561             when N_And_Then | N_Or_Else | N_Membership_Test =>
5562                return
5563                  FCE (Left_Opnd  (E1), Left_Opnd  (E2))
5564                    and then
5565                  FCE (Right_Opnd (E1), Right_Opnd (E2));
5566
5567             when N_Character_Literal =>
5568                return
5569                  Char_Literal_Value (E1) = Char_Literal_Value (E2);
5570
5571             when N_Component_Association =>
5572                return
5573                  FCL (Choices (E1), Choices (E2))
5574                    and then FCE (Expression (E1), Expression (E2));
5575
5576             when N_Conditional_Expression =>
5577                return
5578                  FCL (Expressions (E1), Expressions (E2));
5579
5580             when N_Explicit_Dereference =>
5581                return
5582                  FCE (Prefix (E1), Prefix (E2));
5583
5584             when N_Extension_Aggregate =>
5585                return
5586                  FCL (Expressions (E1), Expressions (E2))
5587                    and then Null_Record_Present (E1) =
5588                             Null_Record_Present (E2)
5589                    and then FCL (Component_Associations (E1),
5590                                Component_Associations (E2));
5591
5592             when N_Function_Call =>
5593                return
5594                  FCE (Name (E1), Name (E2))
5595                    and then FCL (Parameter_Associations (E1),
5596                                  Parameter_Associations (E2));
5597
5598             when N_Indexed_Component =>
5599                return
5600                  FCE (Prefix (E1), Prefix (E2))
5601                    and then FCL (Expressions (E1), Expressions (E2));
5602
5603             when N_Integer_Literal =>
5604                return (Intval (E1) = Intval (E2));
5605
5606             when N_Null =>
5607                return True;
5608
5609             when N_Operator_Symbol =>
5610                return
5611                  Chars (E1) = Chars (E2);
5612
5613             when N_Others_Choice =>
5614                return True;
5615
5616             when N_Parameter_Association =>
5617                return
5618                  Chars (Selector_Name (E1))  = Chars (Selector_Name (E2))
5619                    and then FCE (Explicit_Actual_Parameter (E1),
5620                                  Explicit_Actual_Parameter (E2));
5621
5622             when N_Qualified_Expression =>
5623                return
5624                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
5625                    and then FCE (Expression (E1), Expression (E2));
5626
5627             when N_Range =>
5628                return
5629                  FCE (Low_Bound (E1), Low_Bound (E2))
5630                    and then FCE (High_Bound (E1), High_Bound (E2));
5631
5632             when N_Real_Literal =>
5633                return (Realval (E1) = Realval (E2));
5634
5635             when N_Selected_Component =>
5636                return
5637                  FCE (Prefix (E1), Prefix (E2))
5638                    and then FCE (Selector_Name (E1), Selector_Name (E2));
5639
5640             when N_Slice =>
5641                return
5642                  FCE (Prefix (E1), Prefix (E2))
5643                    and then FCE (Discrete_Range (E1), Discrete_Range (E2));
5644
5645             when N_String_Literal =>
5646                declare
5647                   S1 : constant String_Id := Strval (E1);
5648                   S2 : constant String_Id := Strval (E2);
5649                   L1 : constant Nat       := String_Length (S1);
5650                   L2 : constant Nat       := String_Length (S2);
5651
5652                begin
5653                   if L1 /= L2 then
5654                      return False;
5655
5656                   else
5657                      for J in 1 .. L1 loop
5658                         if Get_String_Char (S1, J) /=
5659                            Get_String_Char (S2, J)
5660                         then
5661                            return False;
5662                         end if;
5663                      end loop;
5664
5665                      return True;
5666                   end if;
5667                end;
5668
5669             when N_Type_Conversion =>
5670                return
5671                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
5672                    and then FCE (Expression (E1), Expression (E2));
5673
5674             when N_Unary_Op =>
5675                return
5676                  Entity (E1) = Entity (E2)
5677                    and then FCE (Right_Opnd (E1), Right_Opnd (E2));
5678
5679             when N_Unchecked_Type_Conversion =>
5680                return
5681                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
5682                    and then FCE (Expression (E1), Expression (E2));
5683
5684             --  All other node types cannot appear in this context. Strictly
5685             --  we should raise a fatal internal error. Instead we just ignore
5686             --  the nodes. This means that if anyone makes a mistake in the
5687             --  expander and mucks an expression tree irretrievably, the
5688             --  result will be a failure to detect a (probably very obscure)
5689             --  case of non-conformance, which is better than bombing on some
5690             --  case where two expressions do in fact conform.
5691
5692             when others =>
5693                return True;
5694
5695          end case;
5696       end if;
5697    end Fully_Conformant_Expressions;
5698
5699    ----------------------------------------
5700    -- Fully_Conformant_Discrete_Subtypes --
5701    ----------------------------------------
5702
5703    function Fully_Conformant_Discrete_Subtypes
5704      (Given_S1 : Node_Id;
5705       Given_S2 : Node_Id) return Boolean
5706    is
5707       S1 : constant Node_Id := Original_Node (Given_S1);
5708       S2 : constant Node_Id := Original_Node (Given_S2);
5709
5710       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean;
5711       --  Special-case for a bound given by a discriminant, which in the body
5712       --  is replaced with the discriminal of the enclosing type.
5713
5714       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean;
5715       --  Check both bounds
5716
5717       -----------------------
5718       -- Conforming_Bounds --
5719       -----------------------
5720
5721       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean is
5722       begin
5723          if Is_Entity_Name (B1)
5724            and then Is_Entity_Name (B2)
5725            and then Ekind (Entity (B1)) = E_Discriminant
5726          then
5727             return Chars (B1) = Chars (B2);
5728
5729          else
5730             return Fully_Conformant_Expressions (B1, B2);
5731          end if;
5732       end Conforming_Bounds;
5733
5734       -----------------------
5735       -- Conforming_Ranges --
5736       -----------------------
5737
5738       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean is
5739       begin
5740          return
5741            Conforming_Bounds (Low_Bound (R1), Low_Bound (R2))
5742              and then
5743            Conforming_Bounds (High_Bound (R1), High_Bound (R2));
5744       end Conforming_Ranges;
5745
5746    --  Start of processing for Fully_Conformant_Discrete_Subtypes
5747
5748    begin
5749       if Nkind (S1) /= Nkind (S2) then
5750          return False;
5751
5752       elsif Is_Entity_Name (S1) then
5753          return Entity (S1) = Entity (S2);
5754
5755       elsif Nkind (S1) = N_Range then
5756          return Conforming_Ranges (S1, S2);
5757
5758       elsif Nkind (S1) = N_Subtype_Indication then
5759          return
5760             Entity (Subtype_Mark (S1)) = Entity (Subtype_Mark (S2))
5761               and then
5762             Conforming_Ranges
5763               (Range_Expression (Constraint (S1)),
5764                Range_Expression (Constraint (S2)));
5765       else
5766          return True;
5767       end if;
5768    end Fully_Conformant_Discrete_Subtypes;
5769
5770    --------------------
5771    -- Install_Entity --
5772    --------------------
5773
5774    procedure Install_Entity (E : Entity_Id) is
5775       Prev : constant Entity_Id := Current_Entity (E);
5776    begin
5777       Set_Is_Immediately_Visible (E);
5778       Set_Current_Entity (E);
5779       Set_Homonym (E, Prev);
5780    end Install_Entity;
5781
5782    ---------------------
5783    -- Install_Formals --
5784    ---------------------
5785
5786    procedure Install_Formals (Id : Entity_Id) is
5787       F : Entity_Id;
5788    begin
5789       F := First_Formal (Id);
5790       while Present (F) loop
5791          Install_Entity (F);
5792          Next_Formal (F);
5793       end loop;
5794    end Install_Formals;
5795
5796    ---------------------------------
5797    -- Is_Non_Overriding_Operation --
5798    ---------------------------------
5799
5800    function Is_Non_Overriding_Operation
5801      (Prev_E : Entity_Id;
5802       New_E  : Entity_Id) return Boolean
5803    is
5804       Formal : Entity_Id;
5805       F_Typ  : Entity_Id;
5806       G_Typ  : Entity_Id := Empty;
5807
5808       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id;
5809       --  If F_Type is a derived type associated with a generic actual subtype,
5810       --  then return its Generic_Parent_Type attribute, else return Empty.
5811
5812       function Types_Correspond
5813         (P_Type : Entity_Id;
5814          N_Type : Entity_Id) return Boolean;
5815       --  Returns true if and only if the types (or designated types in the
5816       --  case of anonymous access types) are the same or N_Type is derived
5817       --  directly or indirectly from P_Type.
5818
5819       -----------------------------
5820       -- Get_Generic_Parent_Type --
5821       -----------------------------
5822
5823       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id is
5824          G_Typ : Entity_Id;
5825          Indic : Node_Id;
5826
5827       begin
5828          if Is_Derived_Type (F_Typ)
5829            and then Nkind (Parent (F_Typ)) = N_Full_Type_Declaration
5830          then
5831             --  The tree must be traversed to determine the parent subtype in
5832             --  the generic unit, which unfortunately isn't always available
5833             --  via semantic attributes. ??? (Note: The use of Original_Node
5834             --  is needed for cases where a full derived type has been
5835             --  rewritten.)
5836
5837             Indic := Subtype_Indication
5838                        (Type_Definition (Original_Node (Parent (F_Typ))));
5839
5840             if Nkind (Indic) = N_Subtype_Indication then
5841                G_Typ := Entity (Subtype_Mark (Indic));
5842             else
5843                G_Typ := Entity (Indic);
5844             end if;
5845
5846             if Nkind (Parent (G_Typ)) = N_Subtype_Declaration
5847               and then Present (Generic_Parent_Type (Parent (G_Typ)))
5848             then
5849                return Generic_Parent_Type (Parent (G_Typ));
5850             end if;
5851          end if;
5852
5853          return Empty;
5854       end Get_Generic_Parent_Type;
5855
5856       ----------------------
5857       -- Types_Correspond --
5858       ----------------------
5859
5860       function Types_Correspond
5861         (P_Type : Entity_Id;
5862          N_Type : Entity_Id) return Boolean
5863       is
5864          Prev_Type : Entity_Id := Base_Type (P_Type);
5865          New_Type  : Entity_Id := Base_Type (N_Type);
5866
5867       begin
5868          if Ekind (Prev_Type) = E_Anonymous_Access_Type then
5869             Prev_Type := Designated_Type (Prev_Type);
5870          end if;
5871
5872          if Ekind (New_Type) = E_Anonymous_Access_Type then
5873             New_Type := Designated_Type (New_Type);
5874          end if;
5875
5876          if Prev_Type = New_Type then
5877             return True;
5878
5879          elsif not Is_Class_Wide_Type (New_Type) then
5880             while Etype (New_Type) /= New_Type loop
5881                New_Type := Etype (New_Type);
5882                if New_Type = Prev_Type then
5883                   return True;
5884                end if;
5885             end loop;
5886          end if;
5887          return False;
5888       end Types_Correspond;
5889
5890    --  Start of processing for Is_Non_Overriding_Operation
5891
5892    begin
5893       --  In the case where both operations are implicit derived subprograms
5894       --  then neither overrides the other. This can only occur in certain
5895       --  obscure cases (e.g., derivation from homographs created in a generic
5896       --  instantiation).
5897
5898       if Present (Alias (Prev_E)) and then Present (Alias (New_E)) then
5899          return True;
5900
5901       elsif Ekind (Current_Scope) = E_Package
5902         and then Is_Generic_Instance (Current_Scope)
5903         and then In_Private_Part (Current_Scope)
5904         and then Comes_From_Source (New_E)
5905       then
5906          --  We examine the formals and result subtype of the inherited
5907          --  operation, to determine whether their type is derived from (the
5908          --  instance of) a generic type.
5909
5910          Formal := First_Formal (Prev_E);
5911
5912          while Present (Formal) loop
5913             F_Typ := Base_Type (Etype (Formal));
5914
5915             if Ekind (F_Typ) = E_Anonymous_Access_Type then
5916                F_Typ := Designated_Type (F_Typ);
5917             end if;
5918
5919             G_Typ := Get_Generic_Parent_Type (F_Typ);
5920
5921             Next_Formal (Formal);
5922          end loop;
5923
5924          if No (G_Typ) and then Ekind (Prev_E) = E_Function then
5925             G_Typ := Get_Generic_Parent_Type (Base_Type (Etype (Prev_E)));
5926          end if;
5927
5928          if No (G_Typ) then
5929             return False;
5930          end if;
5931
5932          --  If the generic type is a private type, then the original
5933          --  operation was not overriding in the generic, because there was
5934          --  no primitive operation to override.
5935
5936          if Nkind (Parent (G_Typ)) = N_Formal_Type_Declaration
5937            and then Nkind (Formal_Type_Definition (Parent (G_Typ))) =
5938              N_Formal_Private_Type_Definition
5939          then
5940             return True;
5941
5942          --  The generic parent type is the ancestor of a formal derived
5943          --  type declaration. We need to check whether it has a primitive
5944          --  operation that should be overridden by New_E in the generic.
5945
5946          else
5947             declare
5948                P_Formal : Entity_Id;
5949                N_Formal : Entity_Id;
5950                P_Typ    : Entity_Id;
5951                N_Typ    : Entity_Id;
5952                P_Prim   : Entity_Id;
5953                Prim_Elt : Elmt_Id := First_Elmt (Primitive_Operations (G_Typ));
5954
5955             begin
5956                while Present (Prim_Elt) loop
5957                   P_Prim := Node (Prim_Elt);
5958
5959                   if Chars (P_Prim) = Chars (New_E)
5960                     and then Ekind (P_Prim) = Ekind (New_E)
5961                   then
5962                      P_Formal := First_Formal (P_Prim);
5963                      N_Formal := First_Formal (New_E);
5964                      while Present (P_Formal) and then Present (N_Formal) loop
5965                         P_Typ := Etype (P_Formal);
5966                         N_Typ := Etype (N_Formal);
5967
5968                         if not Types_Correspond (P_Typ, N_Typ) then
5969                            exit;
5970                         end if;
5971
5972                         Next_Entity (P_Formal);
5973                         Next_Entity (N_Formal);
5974                      end loop;
5975
5976                      --  Found a matching primitive operation belonging to the
5977                      --  formal ancestor type, so the new subprogram is
5978                      --  overriding.
5979
5980                      if No (P_Formal)
5981                        and then No (N_Formal)
5982                        and then (Ekind (New_E) /= E_Function
5983                                   or else
5984                                  Types_Correspond
5985                                    (Etype (P_Prim), Etype (New_E)))
5986                      then
5987                         return False;
5988                      end if;
5989                   end if;
5990
5991                   Next_Elmt (Prim_Elt);
5992                end loop;
5993
5994                --  If no match found, then the new subprogram does not
5995                --  override in the generic (nor in the instance).
5996
5997                return True;
5998             end;
5999          end if;
6000       else
6001          return False;
6002       end if;
6003    end Is_Non_Overriding_Operation;
6004
6005    ------------------------------
6006    -- Make_Inequality_Operator --
6007    ------------------------------
6008
6009    --  S is the defining identifier of an equality operator. We build a
6010    --  subprogram declaration with the right signature. This operation is
6011    --  intrinsic, because it is always expanded as the negation of the
6012    --  call to the equality function.
6013
6014    procedure Make_Inequality_Operator (S : Entity_Id) is
6015       Loc     : constant Source_Ptr := Sloc (S);
6016       Decl    : Node_Id;
6017       Formals : List_Id;
6018       Op_Name : Entity_Id;
6019
6020       FF : constant Entity_Id := First_Formal (S);
6021       NF : constant Entity_Id := Next_Formal (FF);
6022
6023    begin
6024       --  Check that equality was properly defined, ignore call if not
6025
6026       if No (NF) then
6027          return;
6028       end if;
6029
6030       declare
6031          A : constant Entity_Id :=
6032                Make_Defining_Identifier (Sloc (FF),
6033                  Chars => Chars (FF));
6034
6035          B : constant Entity_Id :=
6036                Make_Defining_Identifier (Sloc (NF),
6037                  Chars => Chars (NF));
6038
6039       begin
6040          Op_Name := Make_Defining_Operator_Symbol (Loc, Name_Op_Ne);
6041
6042          Formals := New_List (
6043            Make_Parameter_Specification (Loc,
6044              Defining_Identifier => A,
6045              Parameter_Type      =>
6046                New_Reference_To (Etype (First_Formal (S)),
6047                  Sloc (Etype (First_Formal (S))))),
6048
6049            Make_Parameter_Specification (Loc,
6050              Defining_Identifier => B,
6051              Parameter_Type      =>
6052                New_Reference_To (Etype (Next_Formal (First_Formal (S))),
6053                  Sloc (Etype (Next_Formal (First_Formal (S)))))));
6054
6055          Decl :=
6056            Make_Subprogram_Declaration (Loc,
6057              Specification =>
6058                Make_Function_Specification (Loc,
6059                  Defining_Unit_Name       => Op_Name,
6060                  Parameter_Specifications => Formals,
6061                  Result_Definition        =>
6062                    New_Reference_To (Standard_Boolean, Loc)));
6063
6064          --  Insert inequality right after equality if it is explicit or after
6065          --  the derived type when implicit. These entities are created only
6066          --  for visibility purposes, and eventually replaced in the course of
6067          --  expansion, so they do not need to be attached to the tree and seen
6068          --  by the back-end. Keeping them internal also avoids spurious
6069          --  freezing problems. The declaration is inserted in the tree for
6070          --  analysis, and removed afterwards. If the equality operator comes
6071          --  from an explicit declaration, attach the inequality immediately
6072          --  after. Else the equality is inherited from a derived type
6073          --  declaration, so insert inequality after that declaration.
6074
6075          if No (Alias (S)) then
6076             Insert_After (Unit_Declaration_Node (S), Decl);
6077          elsif Is_List_Member (Parent (S)) then
6078             Insert_After (Parent (S), Decl);
6079          else
6080             Insert_After (Parent (Etype (First_Formal (S))), Decl);
6081          end if;
6082
6083          Mark_Rewrite_Insertion (Decl);
6084          Set_Is_Intrinsic_Subprogram (Op_Name);
6085          Analyze (Decl);
6086          Remove (Decl);
6087          Set_Has_Completion (Op_Name);
6088          Set_Corresponding_Equality (Op_Name, S);
6089          Set_Is_Abstract_Subprogram (Op_Name, Is_Abstract_Subprogram (S));
6090       end;
6091    end Make_Inequality_Operator;
6092
6093    ----------------------
6094    -- May_Need_Actuals --
6095    ----------------------
6096
6097    procedure May_Need_Actuals (Fun : Entity_Id) is
6098       F : Entity_Id;
6099       B : Boolean;
6100
6101    begin
6102       F := First_Formal (Fun);
6103       B := True;
6104       while Present (F) loop
6105          if No (Default_Value (F)) then
6106             B := False;
6107             exit;
6108          end if;
6109
6110          Next_Formal (F);
6111       end loop;
6112
6113       Set_Needs_No_Actuals (Fun, B);
6114    end May_Need_Actuals;
6115
6116    ---------------------
6117    -- Mode_Conformant --
6118    ---------------------
6119
6120    function Mode_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
6121       Result : Boolean;
6122    begin
6123       Check_Conformance (New_Id, Old_Id, Mode_Conformant, False, Result);
6124       return Result;
6125    end Mode_Conformant;
6126
6127    ---------------------------
6128    -- New_Overloaded_Entity --
6129    ---------------------------
6130
6131    procedure New_Overloaded_Entity
6132      (S            : Entity_Id;
6133       Derived_Type : Entity_Id := Empty)
6134    is
6135       Overridden_Subp : Entity_Id := Empty;
6136       --  Set if the current scope has an operation that is type-conformant
6137       --  with S, and becomes hidden by S.
6138
6139       Is_Primitive_Subp : Boolean;
6140       --  Set to True if the new subprogram is primitive
6141
6142       E : Entity_Id;
6143       --  Entity that S overrides
6144
6145       Prev_Vis : Entity_Id := Empty;
6146       --  Predecessor of E in Homonym chain
6147
6148       procedure Check_For_Primitive_Subprogram
6149         (Is_Primitive  : out Boolean;
6150          Is_Overriding : Boolean := False);
6151       --  If the subprogram being analyzed is a primitive operation of the type
6152       --  of a formal or result, set the Has_Primitive_Operations flag on the
6153       --  type, and set Is_Primitive to True (otherwise set to False). Set the
6154       --  corresponding flag on the entity itself for later use.
6155
6156       procedure Check_Synchronized_Overriding
6157         (Def_Id          : Entity_Id;
6158          First_Hom       : Entity_Id;
6159          Overridden_Subp : out Entity_Id);
6160       --  First determine if Def_Id is an entry or a subprogram either defined
6161       --  in the scope of a task or protected type, or is a primitive of such
6162       --  a type. Check whether Def_Id overrides a subprogram of an interface
6163       --  implemented by the synchronized type, return the overridden entity
6164       --  or Empty.
6165
6166       function Is_Private_Declaration (E : Entity_Id) return Boolean;
6167       --  Check that E is declared in the private part of the current package,
6168       --  or in the package body, where it may hide a previous declaration.
6169       --  We can't use In_Private_Part by itself because this flag is also
6170       --  set when freezing entities, so we must examine the place of the
6171       --  declaration in the tree, and recognize wrapper packages as well.
6172
6173       ------------------------------------
6174       -- Check_For_Primitive_Subprogram --
6175       ------------------------------------
6176
6177       procedure Check_For_Primitive_Subprogram
6178         (Is_Primitive  : out Boolean;
6179          Is_Overriding : Boolean := False)
6180       is
6181          Formal : Entity_Id;
6182          F_Typ  : Entity_Id;
6183          B_Typ  : Entity_Id;
6184
6185          function Visible_Part_Type (T : Entity_Id) return Boolean;
6186          --  Returns true if T is declared in the visible part of
6187          --  the current package scope; otherwise returns false.
6188          --  Assumes that T is declared in a package.
6189
6190          procedure Check_Private_Overriding (T : Entity_Id);
6191          --  Checks that if a primitive abstract subprogram of a visible
6192          --  abstract type is declared in a private part, then it must
6193          --  override an abstract subprogram declared in the visible part.
6194          --  Also checks that if a primitive function with a controlling
6195          --  result is declared in a private part, then it must override
6196          --  a function declared in the visible part.
6197
6198          ------------------------------
6199          -- Check_Private_Overriding --
6200          ------------------------------
6201
6202          procedure Check_Private_Overriding (T : Entity_Id) is
6203          begin
6204             if Ekind (Current_Scope) = E_Package
6205               and then In_Private_Part (Current_Scope)
6206               and then Visible_Part_Type (T)
6207               and then not In_Instance
6208             then
6209                if Is_Abstract_Type (T)
6210                  and then Is_Abstract_Subprogram (S)
6211                  and then (not Is_Overriding
6212                            or else not Is_Abstract_Subprogram (E))
6213                then
6214                   Error_Msg_N ("abstract subprograms must be visible "
6215                                    & "(RM 3.9.3(10))!", S);
6216
6217                elsif Ekind (S) = E_Function
6218                  and then Is_Tagged_Type (T)
6219                  and then T = Base_Type (Etype (S))
6220                  and then not Is_Overriding
6221                then
6222                   Error_Msg_N
6223                     ("private function with tagged result must"
6224                      & " override visible-part function", S);
6225                   Error_Msg_N
6226                     ("\move subprogram to the visible part"
6227                      & " (RM 3.9.3(10))", S);
6228                end if;
6229             end if;
6230          end Check_Private_Overriding;
6231
6232          -----------------------
6233          -- Visible_Part_Type --
6234          -----------------------
6235
6236          function Visible_Part_Type (T : Entity_Id) return Boolean is
6237             P : constant Node_Id := Unit_Declaration_Node (Scope (T));
6238             N : Node_Id;
6239
6240          begin
6241             --  If the entity is a private type, then it must be
6242             --  declared in a visible part.
6243
6244             if Ekind (T) in Private_Kind then
6245                return True;
6246             end if;
6247
6248             --  Otherwise, we traverse the visible part looking for its
6249             --  corresponding declaration. We cannot use the declaration
6250             --  node directly because in the private part the entity of a
6251             --  private type is the one in the full view, which does not
6252             --  indicate that it is the completion of something visible.
6253
6254             N := First (Visible_Declarations (Specification (P)));
6255             while Present (N) loop
6256                if Nkind (N) = N_Full_Type_Declaration
6257                  and then Present (Defining_Identifier (N))
6258                  and then T = Defining_Identifier (N)
6259                then
6260                   return True;
6261
6262                elsif Nkind_In (N, N_Private_Type_Declaration,
6263                                   N_Private_Extension_Declaration)
6264                  and then Present (Defining_Identifier (N))
6265                  and then T = Full_View (Defining_Identifier (N))
6266                then
6267                   return True;
6268                end if;
6269
6270                Next (N);
6271             end loop;
6272
6273             return False;
6274          end Visible_Part_Type;
6275
6276       --  Start of processing for Check_For_Primitive_Subprogram
6277
6278       begin
6279          Is_Primitive := False;
6280
6281          if not Comes_From_Source (S) then
6282             null;
6283
6284          --  If subprogram is at library level, it is not primitive operation
6285
6286          elsif Current_Scope = Standard_Standard then
6287             null;
6288
6289          elsif ((Ekind (Current_Scope) = E_Package
6290                   or else Ekind (Current_Scope) = E_Generic_Package)
6291                  and then not In_Package_Body (Current_Scope))
6292            or else Is_Overriding
6293          then
6294             --  For function, check return type
6295
6296             if Ekind (S) = E_Function then
6297                if Ekind (Etype (S)) = E_Anonymous_Access_Type then
6298                   F_Typ := Designated_Type (Etype (S));
6299                else
6300                   F_Typ := Etype (S);
6301                end if;
6302
6303                B_Typ := Base_Type (F_Typ);
6304
6305                if Scope (B_Typ) = Current_Scope
6306                  and then not Is_Class_Wide_Type (B_Typ)
6307                  and then not Is_Generic_Type (B_Typ)
6308                then
6309                   Is_Primitive := True;
6310                   Set_Has_Primitive_Operations (B_Typ);
6311                   Set_Is_Primitive (S);
6312                   Check_Private_Overriding (B_Typ);
6313                end if;
6314             end if;
6315
6316             --  For all subprograms, check formals
6317
6318             Formal := First_Formal (S);
6319             while Present (Formal) loop
6320                if Ekind (Etype (Formal)) = E_Anonymous_Access_Type then
6321                   F_Typ := Designated_Type (Etype (Formal));
6322                else
6323                   F_Typ := Etype (Formal);
6324                end if;
6325
6326                B_Typ := Base_Type (F_Typ);
6327
6328                if Ekind (B_Typ) = E_Access_Subtype then
6329                   B_Typ := Base_Type (B_Typ);
6330                end if;
6331
6332                if Scope (B_Typ) = Current_Scope
6333                  and then not Is_Class_Wide_Type (B_Typ)
6334                  and then not Is_Generic_Type (B_Typ)
6335                then
6336                   Is_Primitive := True;
6337                   Set_Is_Primitive (S);
6338                   Set_Has_Primitive_Operations (B_Typ);
6339                   Check_Private_Overriding (B_Typ);
6340                end if;
6341
6342                Next_Formal (Formal);
6343             end loop;
6344          end if;
6345       end Check_For_Primitive_Subprogram;
6346
6347       -----------------------------------
6348       -- Check_Synchronized_Overriding --
6349       -----------------------------------
6350
6351       procedure Check_Synchronized_Overriding
6352         (Def_Id          : Entity_Id;
6353          First_Hom       : Entity_Id;
6354          Overridden_Subp : out Entity_Id)
6355       is
6356          Formal_Typ  : Entity_Id;
6357          Ifaces_List : Elist_Id;
6358          In_Scope    : Boolean;
6359          Typ         : Entity_Id;
6360
6361       begin
6362          Overridden_Subp := Empty;
6363
6364          --  Def_Id must be an entry or a subprogram
6365
6366          if Ekind (Def_Id) /= E_Entry
6367            and then Ekind (Def_Id) /= E_Function
6368            and then Ekind (Def_Id) /= E_Procedure
6369          then
6370             return;
6371          end if;
6372
6373          --  Search for the concurrent declaration since it contains the list
6374          --  of all implemented interfaces. In this case, the subprogram is
6375          --  declared within the scope of a protected or a task type.
6376
6377          if Present (Scope (Def_Id))
6378            and then Is_Concurrent_Type (Scope (Def_Id))
6379            and then not Is_Generic_Actual_Type (Scope (Def_Id))
6380          then
6381             Typ := Scope (Def_Id);
6382             In_Scope := True;
6383
6384          --  The subprogram may be a primitive of a concurrent type
6385
6386          elsif Present (First_Formal (Def_Id)) then
6387             Formal_Typ := Etype (First_Formal (Def_Id));
6388
6389             if Is_Concurrent_Type (Formal_Typ)
6390               and then not Is_Generic_Actual_Type (Formal_Typ)
6391             then
6392                Typ := Formal_Typ;
6393                In_Scope := False;
6394
6395             --  This case occurs when the concurrent type is declared within
6396             --  a generic unit. As a result the corresponding record has been
6397             --  built and used as the type of the first formal, we just have
6398             --  to retrieve the corresponding concurrent type.
6399
6400             elsif Is_Concurrent_Record_Type (Formal_Typ)
6401               and then Present (Corresponding_Concurrent_Type (Formal_Typ))
6402             then
6403                Typ := Corresponding_Concurrent_Type (Formal_Typ);
6404                In_Scope := False;
6405
6406             else
6407                return;
6408             end if;
6409          else
6410             return;
6411          end if;
6412
6413          --  Gather all limited, protected and task interfaces that Typ
6414          --  implements. There is no overriding to check if is an inherited
6415          --  operation in a type derivation on for a generic actual.
6416
6417          if Nkind (Parent (Typ)) /= N_Full_Type_Declaration
6418            and then
6419              not Nkind_In (Parent (Def_Id), N_Subtype_Declaration,
6420                                             N_Task_Type_Declaration,
6421                                             N_Protected_Type_Declaration)
6422          then
6423             Collect_Abstract_Interfaces (Typ, Ifaces_List);
6424
6425             if not Is_Empty_Elmt_List (Ifaces_List) then
6426                Overridden_Subp :=
6427                  Find_Overridden_Synchronized_Primitive
6428                    (Def_Id, First_Hom, Ifaces_List, In_Scope);
6429             end if;
6430          end if;
6431       end Check_Synchronized_Overriding;
6432
6433       ----------------------------
6434       -- Is_Private_Declaration --
6435       ----------------------------
6436
6437       function Is_Private_Declaration (E : Entity_Id) return Boolean is
6438          Priv_Decls : List_Id;
6439          Decl       : constant Node_Id := Unit_Declaration_Node (E);
6440
6441       begin
6442          if Is_Package_Or_Generic_Package (Current_Scope)
6443            and then In_Private_Part (Current_Scope)
6444          then
6445             Priv_Decls :=
6446               Private_Declarations (
6447                 Specification (Unit_Declaration_Node (Current_Scope)));
6448
6449             return In_Package_Body (Current_Scope)
6450               or else
6451                 (Is_List_Member (Decl)
6452                    and then List_Containing (Decl) = Priv_Decls)
6453               or else (Nkind (Parent (Decl)) = N_Package_Specification
6454                          and then not Is_Compilation_Unit (
6455                            Defining_Entity (Parent (Decl)))
6456                          and then List_Containing (Parent (Parent (Decl)))
6457                            = Priv_Decls);
6458          else
6459             return False;
6460          end if;
6461       end Is_Private_Declaration;
6462
6463    --  Start of processing for New_Overloaded_Entity
6464
6465    begin
6466       --  We need to look for an entity that S may override. This must be a
6467       --  homonym in the current scope, so we look for the first homonym of
6468       --  S in the current scope as the starting point for the search.
6469
6470       E := Current_Entity_In_Scope (S);
6471
6472       --  If there is no homonym then this is definitely not overriding
6473
6474       if No (E) then
6475          Enter_Overloaded_Entity (S);
6476          Check_Dispatching_Operation (S, Empty);
6477          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
6478
6479          --  If subprogram has an explicit declaration, check whether it
6480          --  has an overriding indicator.
6481
6482          if Comes_From_Source (S) then
6483             Check_Synchronized_Overriding (S, Homonym (S), Overridden_Subp);
6484             Check_Overriding_Indicator
6485               (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
6486          end if;
6487
6488       --  If there is a homonym that is not overloadable, then we have an
6489       --  error, except for the special cases checked explicitly below.
6490
6491       elsif not Is_Overloadable (E) then
6492
6493          --  Check for spurious conflict produced by a subprogram that has the
6494          --  same name as that of the enclosing generic package. The conflict
6495          --  occurs within an instance, between the subprogram and the renaming
6496          --  declaration for the package. After the subprogram, the package
6497          --  renaming declaration becomes hidden.
6498
6499          if Ekind (E) = E_Package
6500            and then Present (Renamed_Object (E))
6501            and then Renamed_Object (E) = Current_Scope
6502            and then Nkind (Parent (Renamed_Object (E))) =
6503                                                      N_Package_Specification
6504            and then Present (Generic_Parent (Parent (Renamed_Object (E))))
6505          then
6506             Set_Is_Hidden (E);
6507             Set_Is_Immediately_Visible (E, False);
6508             Enter_Overloaded_Entity (S);
6509             Set_Homonym (S, Homonym (E));
6510             Check_Dispatching_Operation (S, Empty);
6511             Check_Overriding_Indicator (S, Empty, Is_Primitive => False);
6512
6513          --  If the subprogram is implicit it is hidden by the previous
6514          --  declaration. However if it is dispatching, it must appear in the
6515          --  dispatch table anyway, because it can be dispatched to even if it
6516          --  cannot be called directly.
6517
6518          elsif Present (Alias (S))
6519            and then not Comes_From_Source (S)
6520          then
6521             Set_Scope (S, Current_Scope);
6522
6523             if Is_Dispatching_Operation (Alias (S)) then
6524                Check_Dispatching_Operation (S, Empty);
6525             end if;
6526
6527             return;
6528
6529          else
6530             Error_Msg_Sloc := Sloc (E);
6531
6532             --  Generate message, with useful additional warning if in generic
6533
6534             if Is_Generic_Unit (E) then
6535                Error_Msg_N ("previous generic unit cannot be overloaded", S);
6536                Error_Msg_N ("\& conflicts with declaration#", S);
6537             else
6538                Error_Msg_N ("& conflicts with declaration#", S);
6539             end if;
6540
6541             return;
6542          end if;
6543
6544       --  E exists and is overloadable
6545
6546       else
6547          --  Ada 2005 (AI-251): Derivation of abstract interface primitives
6548          --  need no check against the homonym chain. They are directly added
6549          --  to the list of primitive operations of Derived_Type.
6550
6551          if Ada_Version >= Ada_05
6552            and then Present (Derived_Type)
6553            and then Is_Dispatching_Operation (Alias (S))
6554            and then Present (Find_Dispatching_Type (Alias (S)))
6555            and then Is_Interface (Find_Dispatching_Type (Alias (S)))
6556            and then not Is_Predefined_Dispatching_Operation (Alias (S))
6557          then
6558             goto Add_New_Entity;
6559          end if;
6560
6561          Check_Synchronized_Overriding (S, E, Overridden_Subp);
6562
6563          --  Loop through E and its homonyms to determine if any of them is
6564          --  the candidate for overriding by S.
6565
6566          while Present (E) loop
6567
6568             --  Definitely not interesting if not in the current scope
6569
6570             if Scope (E) /= Current_Scope then
6571                null;
6572
6573             --  Check if we have type conformance
6574
6575             elsif Type_Conformant (E, S) then
6576
6577                --  If the old and new entities have the same profile and one
6578                --  is not the body of the other, then this is an error, unless
6579                --  one of them is implicitly declared.
6580
6581                --  There are some cases when both can be implicit, for example
6582                --  when both a literal and a function that overrides it are
6583                --  inherited in a derivation, or when an inherited operation
6584                --  of a tagged full type overrides the inherited operation of
6585                --  a private extension. Ada 83 had a special rule for the
6586                --  literal case. In Ada95, the later implicit operation hides
6587                --  the former, and the literal is always the former. In the
6588                --  odd case where both are derived operations declared at the
6589                --  same point, both operations should be declared, and in that
6590                --  case we bypass the following test and proceed to the next
6591                --  part (this can only occur for certain obscure cases
6592                --  involving homographs in instances and can't occur for
6593                --  dispatching operations ???). Note that the following
6594                --  condition is less than clear. For example, it's not at all
6595                --  clear why there's a test for E_Entry here. ???
6596
6597                if Present (Alias (S))
6598                  and then (No (Alias (E))
6599                             or else Comes_From_Source (E)
6600                             or else Is_Dispatching_Operation (E))
6601                  and then
6602                    (Ekind (E) = E_Entry
6603                      or else Ekind (E) /= E_Enumeration_Literal)
6604                then
6605                   --  When an derived operation is overloaded it may be due to
6606                   --  the fact that the full view of a private extension
6607                   --  re-inherits. It has to be dealt with.
6608
6609                   if Is_Package_Or_Generic_Package (Current_Scope)
6610                     and then In_Private_Part (Current_Scope)
6611                   then
6612                      Check_Operation_From_Private_View (S, E);
6613                   end if;
6614
6615                   --  In any case the implicit operation remains hidden by
6616                   --  the existing declaration, which is overriding.
6617
6618                   Set_Is_Overriding_Operation (E);
6619
6620                   if Comes_From_Source (E) then
6621                      Check_Overriding_Indicator (E, S, Is_Primitive => False);
6622
6623                      --  Indicate that E overrides the operation from which
6624                      --  S is inherited.
6625
6626                      if Present (Alias (S)) then
6627                         Set_Overridden_Operation (E, Alias (S));
6628                      else
6629                         Set_Overridden_Operation (E, S);
6630                      end if;
6631                   end if;
6632
6633                   return;
6634
6635                   --  Within an instance, the renaming declarations for
6636                   --  actual subprograms may become ambiguous, but they do
6637                   --  not hide each other.
6638
6639                elsif Ekind (E) /= E_Entry
6640                  and then not Comes_From_Source (E)
6641                  and then not Is_Generic_Instance (E)
6642                  and then (Present (Alias (E))
6643                             or else Is_Intrinsic_Subprogram (E))
6644                  and then (not In_Instance
6645                             or else No (Parent (E))
6646                             or else Nkind (Unit_Declaration_Node (E)) /=
6647                                N_Subprogram_Renaming_Declaration)
6648                then
6649                   --  A subprogram child unit is not allowed to override
6650                   --  an inherited subprogram (10.1.1(20)).
6651
6652                   if Is_Child_Unit (S) then
6653                      Error_Msg_N
6654                        ("child unit overrides inherited subprogram in parent",
6655                         S);
6656                      return;
6657                   end if;
6658
6659                   if Is_Non_Overriding_Operation (E, S) then
6660                      Enter_Overloaded_Entity (S);
6661                      if No (Derived_Type)
6662                        or else Is_Tagged_Type (Derived_Type)
6663                      then
6664                         Check_Dispatching_Operation (S, Empty);
6665                      end if;
6666
6667                      return;
6668                   end if;
6669
6670                   --  E is a derived operation or an internal operator which
6671                   --  is being overridden. Remove E from further visibility.
6672                   --  Furthermore, if E is a dispatching operation, it must be
6673                   --  replaced in the list of primitive operations of its type
6674                   --  (see Override_Dispatching_Operation).
6675
6676                   Overridden_Subp := E;
6677
6678                   declare
6679                      Prev : Entity_Id;
6680
6681                   begin
6682                      Prev := First_Entity (Current_Scope);
6683
6684                      while Present (Prev)
6685                        and then Next_Entity (Prev) /= E
6686                      loop
6687                         Next_Entity (Prev);
6688                      end loop;
6689
6690                      --  It is possible for E to be in the current scope and
6691                      --  yet not in the entity chain. This can only occur in a
6692                      --  generic context where E is an implicit concatenation
6693                      --  in the formal part, because in a generic body the
6694                      --  entity chain starts with the formals.
6695
6696                      pragma Assert
6697                        (Present (Prev) or else Chars (E) = Name_Op_Concat);
6698
6699                      --  E must be removed both from the entity_list of the
6700                      --  current scope, and from the visibility chain
6701
6702                      if Debug_Flag_E then
6703                         Write_Str ("Override implicit operation ");
6704                         Write_Int (Int (E));
6705                         Write_Eol;
6706                      end if;
6707
6708                      --  If E is a predefined concatenation, it stands for four
6709                      --  different operations. As a result, a single explicit
6710                      --  declaration does not hide it. In a possible ambiguous
6711                      --  situation, Disambiguate chooses the user-defined op,
6712                      --  so it is correct to retain the previous internal one.
6713
6714                      if Chars (E) /= Name_Op_Concat
6715                        or else Ekind (E) /= E_Operator
6716                      then
6717                         --  For nondispatching derived operations that are
6718                         --  overridden by a subprogram declared in the private
6719                         --  part of a package, we retain the derived
6720                         --  subprogram but mark it as not immediately visible.
6721                         --  If the derived operation was declared in the
6722                         --  visible part then this ensures that it will still
6723                         --  be visible outside the package with the proper
6724                         --  signature (calls from outside must also be
6725                         --  directed to this version rather than the
6726                         --  overriding one, unlike the dispatching case).
6727                         --  Calls from inside the package will still resolve
6728                         --  to the overriding subprogram since the derived one
6729                         --  is marked as not visible within the package.
6730
6731                         --  If the private operation is dispatching, we achieve
6732                         --  the overriding by keeping the implicit operation
6733                         --  but setting its alias to be the overriding one. In
6734                         --  this fashion the proper body is executed in all
6735                         --  cases, but the original signature is used outside
6736                         --  of the package.
6737
6738                         --  If the overriding is not in the private part, we
6739                         --  remove the implicit operation altogether.
6740
6741                         if Is_Private_Declaration (S) then
6742
6743                            if not Is_Dispatching_Operation (E) then
6744                               Set_Is_Immediately_Visible (E, False);
6745                            else
6746                               --  Work done in Override_Dispatching_Operation,
6747                               --  so nothing else need to be done here.
6748
6749                               null;
6750                            end if;
6751
6752                         else
6753                            --  Find predecessor of E in Homonym chain
6754
6755                            if E = Current_Entity (E) then
6756                               Prev_Vis := Empty;
6757                            else
6758                               Prev_Vis := Current_Entity (E);
6759                               while Homonym (Prev_Vis) /= E loop
6760                                  Prev_Vis := Homonym (Prev_Vis);
6761                               end loop;
6762                            end if;
6763
6764                            if Prev_Vis /= Empty then
6765
6766                               --  Skip E in the visibility chain
6767
6768                               Set_Homonym (Prev_Vis, Homonym (E));
6769
6770                            else
6771                               Set_Name_Entity_Id (Chars (E), Homonym (E));
6772                            end if;
6773
6774                            Set_Next_Entity (Prev, Next_Entity (E));
6775
6776                            if No (Next_Entity (Prev)) then
6777                               Set_Last_Entity (Current_Scope, Prev);
6778                            end if;
6779
6780                         end if;
6781                      end if;
6782
6783                      Enter_Overloaded_Entity (S);
6784                      Set_Is_Overriding_Operation (S);
6785                      Check_Overriding_Indicator (S, E, Is_Primitive => True);
6786
6787                      --  Indicate that S overrides the operation from which
6788                      --  E is inherited.
6789
6790                      if Comes_From_Source (S) then
6791                         if Present (Alias (E)) then
6792                            Set_Overridden_Operation (S, Alias (E));
6793                         else
6794                            Set_Overridden_Operation (S, E);
6795                         end if;
6796                      end if;
6797
6798                      if Is_Dispatching_Operation (E) then
6799
6800                         --  An overriding dispatching subprogram inherits the
6801                         --  convention of the overridden subprogram (by
6802                         --  AI-117).
6803
6804                         Set_Convention (S, Convention (E));
6805                         Check_Dispatching_Operation (S, E);
6806
6807                      else
6808                         Check_Dispatching_Operation (S, Empty);
6809                      end if;
6810
6811                      Check_For_Primitive_Subprogram
6812                        (Is_Primitive_Subp, Is_Overriding => True);
6813                      goto Check_Inequality;
6814                   end;
6815
6816                --  Apparent redeclarations in instances can occur when two
6817                --  formal types get the same actual type. The subprograms in
6818                --  in the instance are legal,  even if not callable from the
6819                --  outside. Calls from within are disambiguated elsewhere.
6820                --  For dispatching operations in the visible part, the usual
6821                --  rules apply, and operations with the same profile are not
6822                --  legal (B830001).
6823
6824                elsif (In_Instance_Visible_Part
6825                        and then not Is_Dispatching_Operation (E))
6826                  or else In_Instance_Not_Visible
6827                then
6828                   null;
6829
6830                --  Here we have a real error (identical profile)
6831
6832                else
6833                   Error_Msg_Sloc := Sloc (E);
6834
6835                   --  Avoid cascaded errors if the entity appears in
6836                   --  subsequent calls.
6837
6838                   Set_Scope (S, Current_Scope);
6839
6840                   --  Generate error, with extra useful warning for the case
6841                   --  of a generic instance with no completion.
6842
6843                   if Is_Generic_Instance (S)
6844                     and then not Has_Completion (E)
6845                   then
6846                      Error_Msg_N
6847                        ("instantiation cannot provide body for&", S);
6848                      Error_Msg_N ("\& conflicts with declaration#", S);
6849                   else
6850                      Error_Msg_N ("& conflicts with declaration#", S);
6851                   end if;
6852
6853                   return;
6854                end if;
6855
6856             else
6857                --  If one subprogram has an access parameter and the other
6858                --  a parameter of an access type, calls to either might be
6859                --  ambiguous. Verify that parameters match except for the
6860                --  access parameter.
6861
6862                if May_Hide_Profile then
6863                   declare
6864                      F1 : Entity_Id;
6865                      F2 : Entity_Id;
6866                   begin
6867                      F1 := First_Formal (S);
6868                      F2 := First_Formal (E);
6869                      while Present (F1) and then Present (F2) loop
6870                         if Is_Access_Type (Etype (F1)) then
6871                            if not Is_Access_Type (Etype (F2))
6872                               or else not Conforming_Types
6873                                 (Designated_Type (Etype (F1)),
6874                                  Designated_Type (Etype (F2)),
6875                                  Type_Conformant)
6876                            then
6877                               May_Hide_Profile := False;
6878                            end if;
6879
6880                         elsif
6881                           not Conforming_Types
6882                             (Etype (F1), Etype (F2), Type_Conformant)
6883                         then
6884                            May_Hide_Profile := False;
6885                         end if;
6886
6887                         Next_Formal (F1);
6888                         Next_Formal (F2);
6889                      end loop;
6890
6891                      if May_Hide_Profile
6892                        and then No (F1)
6893                        and then No (F2)
6894                      then
6895                         Error_Msg_NE ("calls to& may be ambiguous?", S, S);
6896                      end if;
6897                   end;
6898                end if;
6899             end if;
6900
6901             E := Homonym (E);
6902          end loop;
6903
6904          <<Add_New_Entity>>
6905
6906          --  On exit, we know that S is a new entity
6907
6908          Enter_Overloaded_Entity (S);
6909          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
6910          Check_Overriding_Indicator
6911            (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
6912
6913          --  If S is a derived operation for an untagged type then by
6914          --  definition it's not a dispatching operation (even if the parent
6915          --  operation was dispatching), so we don't call
6916          --  Check_Dispatching_Operation in that case.
6917
6918          if No (Derived_Type)
6919            or else Is_Tagged_Type (Derived_Type)
6920          then
6921             Check_Dispatching_Operation (S, Empty);
6922          end if;
6923       end if;
6924
6925       --  If this is a user-defined equality operator that is not a derived
6926       --  subprogram, create the corresponding inequality. If the operation is
6927       --  dispatching, the expansion is done elsewhere, and we do not create
6928       --  an explicit inequality operation.
6929
6930       <<Check_Inequality>>
6931          if Chars (S) = Name_Op_Eq
6932            and then Etype (S) = Standard_Boolean
6933            and then Present (Parent (S))
6934            and then not Is_Dispatching_Operation (S)
6935          then
6936             Make_Inequality_Operator (S);
6937          end if;
6938    end New_Overloaded_Entity;
6939
6940    ---------------------
6941    -- Process_Formals --
6942    ---------------------
6943
6944    procedure Process_Formals
6945      (T           : List_Id;
6946       Related_Nod : Node_Id)
6947    is
6948       Param_Spec  : Node_Id;
6949       Formal      : Entity_Id;
6950       Formal_Type : Entity_Id;
6951       Default     : Node_Id;
6952       Ptype       : Entity_Id;
6953
6954       Num_Out_Params  : Nat       := 0;
6955       First_Out_Param : Entity_Id := Empty;
6956       --  Used for setting Is_Only_Out_Parameter
6957
6958       function Is_Class_Wide_Default (D : Node_Id) return Boolean;
6959       --  Check whether the default has a class-wide type. After analysis the
6960       --  default has the type of the formal, so we must also check explicitly
6961       --  for an access attribute.
6962
6963       ---------------------------
6964       -- Is_Class_Wide_Default --
6965       ---------------------------
6966
6967       function Is_Class_Wide_Default (D : Node_Id) return Boolean is
6968       begin
6969          return Is_Class_Wide_Type (Designated_Type (Etype (D)))
6970            or else (Nkind (D) =  N_Attribute_Reference
6971                       and then Attribute_Name (D) = Name_Access
6972                       and then Is_Class_Wide_Type (Etype (Prefix (D))));
6973       end Is_Class_Wide_Default;
6974
6975    --  Start of processing for Process_Formals
6976
6977    begin
6978       --  In order to prevent premature use of the formals in the same formal
6979       --  part, the Ekind is left undefined until all default expressions are
6980       --  analyzed. The Ekind is established in a separate loop at the end.
6981
6982       Param_Spec := First (T);
6983       while Present (Param_Spec) loop
6984          Formal := Defining_Identifier (Param_Spec);
6985          Set_Never_Set_In_Source (Formal, True);
6986          Enter_Name (Formal);
6987
6988          --  Case of ordinary parameters
6989
6990          if Nkind (Parameter_Type (Param_Spec)) /= N_Access_Definition then
6991             Find_Type (Parameter_Type (Param_Spec));
6992             Ptype := Parameter_Type (Param_Spec);
6993
6994             if Ptype = Error then
6995                goto Continue;
6996             end if;
6997
6998             Formal_Type := Entity (Ptype);
6999
7000             if Is_Incomplete_Type (Formal_Type)
7001               or else
7002                (Is_Class_Wide_Type (Formal_Type)
7003                   and then Is_Incomplete_Type (Root_Type (Formal_Type)))
7004             then
7005                --  Ada 2005 (AI-326): Tagged incomplete types allowed
7006
7007                if Is_Tagged_Type (Formal_Type) then
7008                   null;
7009
7010                --  Special handling of Value_Type for CIL case
7011
7012                elsif Is_Value_Type (Formal_Type) then
7013                   null;
7014
7015                elsif not Nkind_In (Parent (T), N_Access_Function_Definition,
7016                                                N_Access_Procedure_Definition)
7017                then
7018                   Error_Msg_N ("invalid use of incomplete type", Param_Spec);
7019
7020                --  An incomplete type that is not tagged is allowed in an
7021                --  access-to-subprogram type only if it is a local declaration
7022                --  with a forthcoming completion (3.10.1 (9.2/2)).
7023
7024                elsif Scope (Formal_Type) /= Scope (Current_Scope) then
7025                   Error_Msg_N
7026                     ("invalid use of limited view of type", Param_Spec);
7027                end if;
7028
7029             elsif Ekind (Formal_Type) = E_Void then
7030                Error_Msg_NE ("premature use of&",
7031                  Parameter_Type (Param_Spec), Formal_Type);
7032             end if;
7033
7034             --  Ada 2005 (AI-231): Create and decorate an internal subtype
7035             --  declaration corresponding to the null-excluding type of the
7036             --  formal in the enclosing scope. Finally, replace the parameter
7037             --  type of the formal with the internal subtype.
7038
7039             if Ada_Version >= Ada_05
7040               and then Null_Exclusion_Present (Param_Spec)
7041             then
7042                if not Is_Access_Type (Formal_Type) then
7043                   Error_Msg_N
7044                     ("`NOT NULL` allowed only for an access type", Param_Spec);
7045
7046                else
7047                   if Can_Never_Be_Null (Formal_Type)
7048                     and then Comes_From_Source (Related_Nod)
7049                   then
7050                      Error_Msg_NE
7051                        ("`NOT NULL` not allowed (& already excludes null)",
7052                         Param_Spec,
7053                         Formal_Type);
7054                   end if;
7055
7056                   Formal_Type :=
7057                     Create_Null_Excluding_Itype
7058                       (T           => Formal_Type,
7059                        Related_Nod => Related_Nod,
7060                        Scope_Id    => Scope (Current_Scope));
7061
7062                   --  If the designated type of the itype is an itype we
7063                   --  decorate it with the Has_Delayed_Freeze attribute to
7064                   --  avoid problems with the backend.
7065
7066                   --  Example:
7067                   --     type T is access procedure;
7068                   --     procedure Op (O : not null T);
7069
7070                   if Is_Itype (Directly_Designated_Type (Formal_Type)) then
7071                      Set_Has_Delayed_Freeze (Formal_Type);
7072                   end if;
7073                end if;
7074             end if;
7075
7076          --  An access formal type
7077
7078          else
7079             Formal_Type :=
7080               Access_Definition (Related_Nod, Parameter_Type (Param_Spec));
7081
7082             --  No need to continue if we already notified errors
7083
7084             if not Present (Formal_Type) then
7085                return;
7086             end if;
7087
7088             --  Ada 2005 (AI-254)
7089
7090             declare
7091                AD : constant Node_Id :=
7092                       Access_To_Subprogram_Definition
7093                         (Parameter_Type (Param_Spec));
7094             begin
7095                if Present (AD) and then Protected_Present (AD) then
7096                   Formal_Type :=
7097                     Replace_Anonymous_Access_To_Protected_Subprogram
7098                       (Param_Spec);
7099                end if;
7100             end;
7101          end if;
7102
7103          Set_Etype (Formal, Formal_Type);
7104          Default := Expression (Param_Spec);
7105
7106          if Present (Default) then
7107             if Out_Present (Param_Spec) then
7108                Error_Msg_N
7109                  ("default initialization only allowed for IN parameters",
7110                   Param_Spec);
7111             end if;
7112
7113             --  Do the special preanalysis of the expression (see section on
7114             --  "Handling of Default Expressions" in the spec of package Sem).
7115
7116             Preanalyze_Spec_Expression (Default, Formal_Type);
7117
7118             --  An access to constant cannot be the default for
7119             --  an access parameter that is an access to variable.
7120
7121             if Ekind (Formal_Type) = E_Anonymous_Access_Type
7122               and then not Is_Access_Constant (Formal_Type)
7123               and then Is_Access_Type (Etype (Default))
7124               and then Is_Access_Constant (Etype (Default))
7125             then
7126                Error_Msg_N
7127                  ("formal that is access to variable cannot be initialized " &
7128                     "with an access-to-constant expression", Default);
7129             end if;
7130
7131             --  Check that the designated type of an access parameter's default
7132             --  is not a class-wide type unless the parameter's designated type
7133             --  is also class-wide.
7134
7135             if Ekind (Formal_Type) = E_Anonymous_Access_Type
7136               and then not From_With_Type (Formal_Type)
7137               and then Is_Class_Wide_Default (Default)
7138               and then not Is_Class_Wide_Type (Designated_Type (Formal_Type))
7139             then
7140                Error_Msg_N
7141                  ("access to class-wide expression not allowed here", Default);
7142             end if;
7143          end if;
7144
7145          --  Ada 2005 (AI-231): Static checks
7146
7147          if Ada_Version >= Ada_05
7148            and then Is_Access_Type (Etype (Formal))
7149            and then Can_Never_Be_Null (Etype (Formal))
7150          then
7151             Null_Exclusion_Static_Checks (Param_Spec);
7152          end if;
7153
7154       <<Continue>>
7155          Next (Param_Spec);
7156       end loop;
7157
7158       --  If this is the formal part of a function specification, analyze the
7159       --  subtype mark in the context where the formals are visible but not
7160       --  yet usable, and may hide outer homographs.
7161
7162       if Nkind (Related_Nod) = N_Function_Specification then
7163          Analyze_Return_Type (Related_Nod);
7164       end if;
7165
7166       --  Now set the kind (mode) of each formal
7167
7168       Param_Spec := First (T);
7169
7170       while Present (Param_Spec) loop
7171          Formal := Defining_Identifier (Param_Spec);
7172          Set_Formal_Mode (Formal);
7173
7174          if Ekind (Formal) = E_In_Parameter then
7175             Set_Default_Value (Formal, Expression (Param_Spec));
7176
7177             if Present (Expression (Param_Spec)) then
7178                Default :=  Expression (Param_Spec);
7179
7180                if Is_Scalar_Type (Etype (Default)) then
7181                   if Nkind
7182                        (Parameter_Type (Param_Spec)) /= N_Access_Definition
7183                   then
7184                      Formal_Type := Entity (Parameter_Type (Param_Spec));
7185
7186                   else
7187                      Formal_Type := Access_Definition
7188                        (Related_Nod, Parameter_Type (Param_Spec));
7189                   end if;
7190
7191                   Apply_Scalar_Range_Check (Default, Formal_Type);
7192                end if;
7193             end if;
7194
7195          elsif Ekind (Formal) = E_Out_Parameter then
7196             Num_Out_Params := Num_Out_Params + 1;
7197
7198             if Num_Out_Params = 1 then
7199                First_Out_Param := Formal;
7200             end if;
7201
7202          elsif Ekind (Formal) = E_In_Out_Parameter then
7203             Num_Out_Params := Num_Out_Params + 1;
7204          end if;
7205
7206          Next (Param_Spec);
7207       end loop;
7208
7209       if Present (First_Out_Param) and then Num_Out_Params = 1 then
7210          Set_Is_Only_Out_Parameter (First_Out_Param);
7211       end if;
7212    end Process_Formals;
7213
7214    ------------------
7215    -- Process_PPCs --
7216    ------------------
7217
7218    procedure Process_PPCs
7219      (N       : Node_Id;
7220       Spec_Id : Entity_Id;
7221       Body_Id : Entity_Id)
7222    is
7223       Loc   : constant Source_Ptr := Sloc (N);
7224       Prag  : Node_Id;
7225       Plist : List_Id := No_List;
7226       Subp  : Entity_Id;
7227       Parms : List_Id;
7228
7229       function Grab_PPC (Nam : Name_Id) return Node_Id;
7230       --  Prag contains an analyzed precondition or postcondition pragma.
7231       --  This function copies the pragma, changes it to the corresponding
7232       --  Check pragma and returns the Check pragma as the result. The
7233       --  argument Nam is either Name_Precondition or Name_Postcondition.
7234
7235       --------------
7236       -- Grab_PPC --
7237       --------------
7238
7239       function Grab_PPC (Nam : Name_Id) return Node_Id is
7240          CP : constant Node_Id := New_Copy_Tree (Prag);
7241
7242       begin
7243          --  Set Analyzed to false, since we want to reanalyze the check
7244          --  procedure. Note that it is only at the outer level that we
7245          --  do this fiddling, for the spec cases, the already preanalyzed
7246          --  parameters are not affected.
7247
7248          Set_Analyzed (CP, False);
7249
7250          --  Change pragma into corresponding pragma Check
7251
7252          Prepend_To (Pragma_Argument_Associations (CP),
7253            Make_Pragma_Argument_Association (Sloc (Prag),
7254              Expression =>
7255                Make_Identifier (Loc,
7256                  Chars => Nam)));
7257          Set_Pragma_Identifier (CP,
7258            Make_Identifier (Sloc (Prag),
7259              Chars => Name_Check));
7260
7261          return CP;
7262       end Grab_PPC;
7263
7264    --  Start of processing for Process_PPCs
7265
7266    begin
7267       --  Grab preconditions from spec
7268
7269       if Present (Spec_Id) then
7270
7271          --  Loop through PPC pragmas from spec. Note that preconditions from
7272          --  the body will be analyzed and converted when we scan the body
7273          --  declarations below.
7274
7275          Prag := Spec_PPC_List (Spec_Id);
7276          while Present (Prag) loop
7277             if Pragma_Name (Prag) = Name_Precondition
7278               and then PPC_Enabled (Prag)
7279             then
7280                --  Add pragma Check at the start of the declarations of N.
7281                --  Note that this processing reverses the order of the list,
7282                --  which is what we want since new entries were chained to
7283                --  the head of the list.
7284
7285                Prepend (Grab_PPC (Name_Precondition), Declarations (N));
7286             end if;
7287
7288             Prag := Next_Pragma (Prag);
7289          end loop;
7290       end if;
7291
7292       --  Build postconditions procedure if needed and prepend the following
7293       --  declaration to the start of the declarations for the subprogram.
7294
7295       --     procedure _postconditions [(_Result : resulttype)] is
7296       --     begin
7297       --        pragma Check (Postcondition, condition [,message]);
7298       --        pragma Check (Postcondition, condition [,message]);
7299       --        ...
7300       --     end;
7301
7302       --  First we deal with the postconditions in the body
7303
7304       if Is_Non_Empty_List (Declarations (N)) then
7305
7306          --  Loop through declarations
7307
7308          Prag := First (Declarations (N));
7309          while Present (Prag) loop
7310             if Nkind (Prag) = N_Pragma then
7311
7312                --  If pragma, capture if enabled postcondition, else ignore
7313
7314                if Pragma_Name (Prag) = Name_Postcondition
7315                  and then Check_Enabled (Name_Postcondition)
7316                then
7317                   if Plist = No_List then
7318                      Plist := Empty_List;
7319                   end if;
7320
7321                   Analyze (Prag);
7322                   Append (Grab_PPC (Name_Postcondition), Plist);
7323                end if;
7324
7325                Next (Prag);
7326
7327                --  Not a pragma, if comes from source, then end scan
7328
7329             elsif Comes_From_Source (Prag) then
7330                exit;
7331
7332                --  Skip stuff not coming from source
7333
7334             else
7335                Next (Prag);
7336             end if;
7337          end loop;
7338       end if;
7339
7340       --  Now deal with any postconditions from the spec
7341
7342       if Present (Spec_Id) then
7343
7344          --  Loop through PPC pragmas from spec
7345
7346          Prag := Spec_PPC_List (Spec_Id);
7347          while Present (Prag) loop
7348             if Pragma_Name (Prag) = Name_Postcondition
7349               and then PPC_Enabled (Prag)
7350             then
7351                if Plist = No_List then
7352                   Plist := Empty_List;
7353                end if;
7354
7355                Append (Grab_PPC (Name_Postcondition), Plist);
7356             end if;
7357
7358             Prag := Next_Pragma (Prag);
7359          end loop;
7360       end if;
7361
7362       --  If we had any postconditions, build the procedure
7363
7364       if Present (Plist) then
7365          Subp := Defining_Entity (N);
7366
7367          if Etype (Subp) /= Standard_Void_Type then
7368             Parms := New_List (
7369               Make_Parameter_Specification (Loc,
7370                 Defining_Identifier =>
7371                   Make_Defining_Identifier (Loc,
7372                     Chars => Name_uResult),
7373                 Parameter_Type => New_Occurrence_Of (Etype (Subp), Loc)));
7374          else
7375             Parms := No_List;
7376          end if;
7377
7378          Prepend_To (Declarations (N),
7379            Make_Subprogram_Body (Loc,
7380              Specification =>
7381                Make_Procedure_Specification (Loc,
7382                  Defining_Unit_Name =>
7383                    Make_Defining_Identifier (Loc,
7384                      Chars => Name_uPostconditions),
7385                  Parameter_Specifications => Parms),
7386
7387              Declarations => Empty_List,
7388
7389              Handled_Statement_Sequence =>
7390                Make_Handled_Sequence_Of_Statements (Loc,
7391                  Statements => Plist)));
7392
7393          if Present (Spec_Id) then
7394             Set_Has_Postconditions (Spec_Id);
7395          else
7396             Set_Has_Postconditions (Body_Id);
7397          end if;
7398       end if;
7399    end Process_PPCs;
7400
7401    ----------------------------
7402    -- Reference_Body_Formals --
7403    ----------------------------
7404
7405    procedure Reference_Body_Formals (Spec : Entity_Id; Bod : Entity_Id) is
7406       Fs : Entity_Id;
7407       Fb : Entity_Id;
7408
7409    begin
7410       if Error_Posted (Spec) then
7411          return;
7412       end if;
7413
7414       --  Iterate over both lists. They may be of different lengths if the two
7415       --  specs are not conformant.
7416
7417       Fs := First_Formal (Spec);
7418       Fb := First_Formal (Bod);
7419       while Present (Fs) and then Present (Fb) loop
7420          Generate_Reference (Fs, Fb, 'b');
7421
7422          if Style_Check then
7423             Style.Check_Identifier (Fb, Fs);
7424          end if;
7425
7426          Set_Spec_Entity (Fb, Fs);
7427          Set_Referenced (Fs, False);
7428          Next_Formal (Fs);
7429          Next_Formal (Fb);
7430       end loop;
7431    end Reference_Body_Formals;
7432
7433    -------------------------
7434    -- Set_Actual_Subtypes --
7435    -------------------------
7436
7437    procedure Set_Actual_Subtypes (N : Node_Id; Subp : Entity_Id) is
7438       Loc            : constant Source_Ptr := Sloc (N);
7439       Decl           : Node_Id;
7440       Formal         : Entity_Id;
7441       T              : Entity_Id;
7442       First_Stmt     : Node_Id := Empty;
7443       AS_Needed      : Boolean;
7444
7445    begin
7446       --  If this is an empty initialization procedure, no need to create
7447       --  actual subtypes (small optimization).
7448
7449       if Ekind (Subp) = E_Procedure
7450         and then Is_Null_Init_Proc (Subp)
7451       then
7452          return;
7453       end if;
7454
7455       Formal := First_Formal (Subp);
7456       while Present (Formal) loop
7457          T := Etype (Formal);
7458
7459          --  We never need an actual subtype for a constrained formal
7460
7461          if Is_Constrained (T) then
7462             AS_Needed := False;
7463
7464          --  If we have unknown discriminants, then we do not need an actual
7465          --  subtype, or more accurately we cannot figure it out! Note that
7466          --  all class-wide types have unknown discriminants.
7467
7468          elsif Has_Unknown_Discriminants (T) then
7469             AS_Needed := False;
7470
7471          --  At this stage we have an unconstrained type that may need an
7472          --  actual subtype. For sure the actual subtype is needed if we have
7473          --  an unconstrained array type.
7474
7475          elsif Is_Array_Type (T) then
7476             AS_Needed := True;
7477
7478          --  The only other case needing an actual subtype is an unconstrained
7479          --  record type which is an IN parameter (we cannot generate actual
7480          --  subtypes for the OUT or IN OUT case, since an assignment can
7481          --  change the discriminant values. However we exclude the case of
7482          --  initialization procedures, since discriminants are handled very
7483          --  specially in this context, see the section entitled "Handling of
7484          --  Discriminants" in Einfo.
7485
7486          --  We also exclude the case of Discrim_SO_Functions (functions used
7487          --  in front end layout mode for size/offset values), since in such
7488          --  functions only discriminants are referenced, and not only are such
7489          --  subtypes not needed, but they cannot always be generated, because
7490          --  of order of elaboration issues.
7491
7492          elsif Is_Record_Type (T)
7493            and then Ekind (Formal) = E_In_Parameter
7494            and then Chars (Formal) /= Name_uInit
7495            and then not Is_Unchecked_Union (T)
7496            and then not Is_Discrim_SO_Function (Subp)
7497          then
7498             AS_Needed := True;
7499
7500          --  All other cases do not need an actual subtype
7501
7502          else
7503             AS_Needed := False;
7504          end if;
7505
7506          --  Generate actual subtypes for unconstrained arrays and
7507          --  unconstrained discriminated records.
7508
7509          if AS_Needed then
7510             if Nkind (N) = N_Accept_Statement then
7511
7512                --  If expansion is active, The formal is replaced by a local
7513                --  variable that renames the corresponding entry of the
7514                --  parameter block, and it is this local variable that may
7515                --  require an actual subtype.
7516
7517                if Expander_Active then
7518                   Decl := Build_Actual_Subtype (T, Renamed_Object (Formal));
7519                else
7520                   Decl := Build_Actual_Subtype (T, Formal);
7521                end if;
7522
7523                if Present (Handled_Statement_Sequence (N)) then
7524                   First_Stmt :=
7525                     First (Statements (Handled_Statement_Sequence (N)));
7526                   Prepend (Decl, Statements (Handled_Statement_Sequence (N)));
7527                   Mark_Rewrite_Insertion (Decl);
7528                else
7529                   --  If the accept statement has no body, there will be no
7530                   --  reference to the actuals, so no need to compute actual
7531                   --  subtypes.
7532
7533                   return;
7534                end if;
7535
7536             else
7537                Decl := Build_Actual_Subtype (T, Formal);
7538                Prepend (Decl, Declarations (N));
7539                Mark_Rewrite_Insertion (Decl);
7540             end if;
7541
7542             --  The declaration uses the bounds of an existing object, and
7543             --  therefore needs no constraint checks.
7544
7545             Analyze (Decl, Suppress => All_Checks);
7546
7547             --  We need to freeze manually the generated type when it is
7548             --  inserted anywhere else than in a declarative part.
7549
7550             if Present (First_Stmt) then
7551                Insert_List_Before_And_Analyze (First_Stmt,
7552                  Freeze_Entity (Defining_Identifier (Decl), Loc));
7553             end if;
7554
7555             if Nkind (N) = N_Accept_Statement
7556               and then Expander_Active
7557             then
7558                Set_Actual_Subtype (Renamed_Object (Formal),
7559                  Defining_Identifier (Decl));
7560             else
7561                Set_Actual_Subtype (Formal, Defining_Identifier (Decl));
7562             end if;
7563          end if;
7564
7565          Next_Formal (Formal);
7566       end loop;
7567    end Set_Actual_Subtypes;
7568
7569    ---------------------
7570    -- Set_Formal_Mode --
7571    ---------------------
7572
7573    procedure Set_Formal_Mode (Formal_Id : Entity_Id) is
7574       Spec : constant Node_Id := Parent (Formal_Id);
7575
7576    begin
7577       --  Note: we set Is_Known_Valid for IN parameters and IN OUT parameters
7578       --  since we ensure that corresponding actuals are always valid at the
7579       --  point of the call.
7580
7581       if Out_Present (Spec) then
7582          if Ekind (Scope (Formal_Id)) = E_Function
7583            or else Ekind (Scope (Formal_Id)) = E_Generic_Function
7584          then
7585             Error_Msg_N ("functions can only have IN parameters", Spec);
7586             Set_Ekind (Formal_Id, E_In_Parameter);
7587
7588          elsif In_Present (Spec) then
7589             Set_Ekind (Formal_Id, E_In_Out_Parameter);
7590
7591          else
7592             Set_Ekind               (Formal_Id, E_Out_Parameter);
7593             Set_Never_Set_In_Source (Formal_Id, True);
7594             Set_Is_True_Constant    (Formal_Id, False);
7595             Set_Current_Value       (Formal_Id, Empty);
7596          end if;
7597
7598       else
7599          Set_Ekind (Formal_Id, E_In_Parameter);
7600       end if;
7601
7602       --  Set Is_Known_Non_Null for access parameters since the language
7603       --  guarantees that access parameters are always non-null. We also set
7604       --  Can_Never_Be_Null, since there is no way to change the value.
7605
7606       if Nkind (Parameter_Type (Spec)) = N_Access_Definition then
7607
7608          --  Ada 2005 (AI-231): In Ada95, access parameters are always non-
7609          --  null; In Ada 2005, only if then null_exclusion is explicit.
7610
7611          if Ada_Version < Ada_05
7612            or else Can_Never_Be_Null (Etype (Formal_Id))
7613          then
7614             Set_Is_Known_Non_Null (Formal_Id);
7615             Set_Can_Never_Be_Null (Formal_Id);
7616          end if;
7617
7618       --  Ada 2005 (AI-231): Null-exclusion access subtype
7619
7620       elsif Is_Access_Type (Etype (Formal_Id))
7621         and then Can_Never_Be_Null (Etype (Formal_Id))
7622       then
7623          Set_Is_Known_Non_Null (Formal_Id);
7624       end if;
7625
7626       Set_Mechanism (Formal_Id, Default_Mechanism);
7627       Set_Formal_Validity (Formal_Id);
7628    end Set_Formal_Mode;
7629
7630    -------------------------
7631    -- Set_Formal_Validity --
7632    -------------------------
7633
7634    procedure Set_Formal_Validity (Formal_Id : Entity_Id) is
7635    begin
7636       --  If no validity checking, then we cannot assume anything about the
7637       --  validity of parameters, since we do not know there is any checking
7638       --  of the validity on the call side.
7639
7640       if not Validity_Checks_On then
7641          return;
7642
7643       --  If validity checking for parameters is enabled, this means we are
7644       --  not supposed to make any assumptions about argument values.
7645
7646       elsif Validity_Check_Parameters then
7647          return;
7648
7649       --  If we are checking in parameters, we will assume that the caller is
7650       --  also checking parameters, so we can assume the parameter is valid.
7651
7652       elsif Ekind (Formal_Id) = E_In_Parameter
7653         and then Validity_Check_In_Params
7654       then
7655          Set_Is_Known_Valid (Formal_Id, True);
7656
7657       --  Similar treatment for IN OUT parameters
7658
7659       elsif Ekind (Formal_Id) = E_In_Out_Parameter
7660         and then Validity_Check_In_Out_Params
7661       then
7662          Set_Is_Known_Valid (Formal_Id, True);
7663       end if;
7664    end Set_Formal_Validity;
7665
7666    ------------------------
7667    -- Subtype_Conformant --
7668    ------------------------
7669
7670    function Subtype_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
7671       Result : Boolean;
7672    begin
7673       Check_Conformance (New_Id, Old_Id, Subtype_Conformant, False, Result);
7674       return Result;
7675    end Subtype_Conformant;
7676
7677    ---------------------
7678    -- Type_Conformant --
7679    ---------------------
7680
7681    function Type_Conformant
7682      (New_Id                   : Entity_Id;
7683       Old_Id                   : Entity_Id;
7684       Skip_Controlling_Formals : Boolean := False) return Boolean
7685    is
7686       Result : Boolean;
7687    begin
7688       May_Hide_Profile := False;
7689
7690       Check_Conformance
7691         (New_Id, Old_Id, Type_Conformant, False, Result,
7692          Skip_Controlling_Formals => Skip_Controlling_Formals);
7693       return Result;
7694    end Type_Conformant;
7695
7696    -------------------------------
7697    -- Valid_Operator_Definition --
7698    -------------------------------
7699
7700    procedure Valid_Operator_Definition (Designator : Entity_Id) is
7701       N    : Integer := 0;
7702       F    : Entity_Id;
7703       Id   : constant Name_Id := Chars (Designator);
7704       N_OK : Boolean;
7705
7706    begin
7707       F := First_Formal (Designator);
7708       while Present (F) loop
7709          N := N + 1;
7710
7711          if Present (Default_Value (F)) then
7712             Error_Msg_N
7713               ("default values not allowed for operator parameters",
7714                Parent (F));
7715          end if;
7716
7717          Next_Formal (F);
7718       end loop;
7719
7720       --  Verify that user-defined operators have proper number of arguments
7721       --  First case of operators which can only be unary
7722
7723       if Id = Name_Op_Not
7724         or else Id = Name_Op_Abs
7725       then
7726          N_OK := (N = 1);
7727
7728       --  Case of operators which can be unary or binary
7729
7730       elsif Id = Name_Op_Add
7731         or Id = Name_Op_Subtract
7732       then
7733          N_OK := (N in 1 .. 2);
7734
7735       --  All other operators can only be binary
7736
7737       else
7738          N_OK := (N = 2);
7739       end if;
7740
7741       if not N_OK then
7742          Error_Msg_N
7743            ("incorrect number of arguments for operator", Designator);
7744       end if;
7745
7746       if Id = Name_Op_Ne
7747         and then Base_Type (Etype (Designator)) = Standard_Boolean
7748         and then not Is_Intrinsic_Subprogram (Designator)
7749       then
7750          Error_Msg_N
7751             ("explicit definition of inequality not allowed", Designator);
7752       end if;
7753    end Valid_Operator_Definition;
7754
7755 end Sem_Ch6;