OSDN Git Service

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