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