OSDN Git Service

PR c++/40373
[pf3gnuchains/gcc-fork.git] / gcc / ada / sem_ch6.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              S E M _ C H 6                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2009, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Expander; use Expander;
33 with Exp_Ch6;  use Exp_Ch6;
34 with Exp_Ch7;  use Exp_Ch7;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Disp; use Exp_Disp;
37 with Exp_Tss;  use Exp_Tss;
38 with Exp_Util; use Exp_Util;
39 with Fname;    use Fname;
40 with Freeze;   use Freeze;
41 with Itypes;   use Itypes;
42 with Lib.Xref; use Lib.Xref;
43 with Layout;   use Layout;
44 with Namet;    use Namet;
45 with Lib;      use Lib;
46 with Nlists;   use Nlists;
47 with Nmake;    use Nmake;
48 with Opt;      use Opt;
49 with Output;   use Output;
50 with Restrict; use Restrict;
51 with Rident;   use Rident;
52 with Rtsfind;  use Rtsfind;
53 with Sem;      use Sem;
54 with Sem_Aux;  use Sem_Aux;
55 with Sem_Cat;  use Sem_Cat;
56 with Sem_Ch3;  use Sem_Ch3;
57 with Sem_Ch4;  use Sem_Ch4;
58 with Sem_Ch5;  use Sem_Ch5;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Ch10; use Sem_Ch10;
61 with Sem_Ch12; use Sem_Ch12;
62 with Sem_Disp; use Sem_Disp;
63 with Sem_Dist; use Sem_Dist;
64 with Sem_Elim; use Sem_Elim;
65 with Sem_Eval; use Sem_Eval;
66 with Sem_Mech; use Sem_Mech;
67 with Sem_Prag; use Sem_Prag;
68 with Sem_Res;  use Sem_Res;
69 with Sem_Util; use Sem_Util;
70 with Sem_Type; use Sem_Type;
71 with Sem_Warn; use Sem_Warn;
72 with Sinput;   use Sinput;
73 with Stand;    use Stand;
74 with Sinfo;    use Sinfo;
75 with Sinfo.CN; use Sinfo.CN;
76 with Snames;   use Snames;
77 with Stringt;  use Stringt;
78 with Style;
79 with Stylesw;  use Stylesw;
80 with Tbuild;   use Tbuild;
81 with Uintp;    use Uintp;
82 with Urealp;   use Urealp;
83 with Validsw;  use Validsw;
84
85 package body Sem_Ch6 is
86
87    May_Hide_Profile : Boolean := False;
88    --  This flag is used to indicate that two formals in two subprograms being
89    --  checked for conformance differ only in that one is an access parameter
90    --  while the other is of a general access type with the same designated
91    --  type. In this case, if the rest of the signatures match, a call to
92    --  either subprogram may be ambiguous, which is worth a warning. The flag
93    --  is set in Compatible_Types, and the warning emitted in
94    --  New_Overloaded_Entity.
95
96    -----------------------
97    -- Local Subprograms --
98    -----------------------
99
100    procedure Analyze_Return_Statement (N : Node_Id);
101    --  Common processing for simple_ and extended_return_statements
102
103    procedure Analyze_Function_Return (N : Node_Id);
104    --  Subsidiary to Analyze_Return_Statement. Called when the return statement
105    --  applies to a [generic] function.
106
107    procedure Analyze_Return_Type (N : Node_Id);
108    --  Subsidiary to Process_Formals: analyze subtype mark in function
109    --  specification, in a context where the formals are visible and hide
110    --  outer homographs.
111
112    procedure Analyze_Subprogram_Body_Helper (N : Node_Id);
113    --  Does all the real work of Analyze_Subprogram_Body
114
115    procedure Analyze_Generic_Subprogram_Body (N : Node_Id; Gen_Id : Entity_Id);
116    --  Analyze a generic subprogram body. N is the body to be analyzed, and
117    --  Gen_Id is the defining entity Id for the corresponding spec.
118
119    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id);
120    --  If a subprogram has pragma Inline and inlining is active, use generic
121    --  machinery to build an unexpanded body for the subprogram. This body is
122    --  subsequently used for inline expansions at call sites. If subprogram can
123    --  be inlined (depending on size and nature of local declarations) this
124    --  function returns true. Otherwise subprogram body is treated normally.
125    --  If proper warnings are enabled and the subprogram contains a construct
126    --  that cannot be inlined, the offending construct is flagged accordingly.
127
128    procedure Check_Conformance
129      (New_Id                   : Entity_Id;
130       Old_Id                   : Entity_Id;
131       Ctype                    : Conformance_Type;
132       Errmsg                   : Boolean;
133       Conforms                 : out Boolean;
134       Err_Loc                  : Node_Id := Empty;
135       Get_Inst                 : Boolean := False;
136       Skip_Controlling_Formals : Boolean := False);
137    --  Given two entities, this procedure checks that the profiles associated
138    --  with these entities meet the conformance criterion given by the third
139    --  parameter. If they conform, Conforms is set True and control returns
140    --  to the caller. If they do not conform, Conforms is set to False, and
141    --  in addition, if Errmsg is True on the call, proper messages are output
142    --  to complain about the conformance failure. If Err_Loc is non_Empty
143    --  the error messages are placed on Err_Loc, if Err_Loc is empty, then
144    --  error messages are placed on the appropriate part of the construct
145    --  denoted by New_Id. If Get_Inst is true, then this is a mode conformance
146    --  against a formal access-to-subprogram type so Get_Instance_Of must
147    --  be called.
148
149    procedure Check_Subprogram_Order (N : Node_Id);
150    --  N is the N_Subprogram_Body node for a subprogram. This routine applies
151    --  the alpha ordering rule for N if this ordering requirement applicable.
152
153    procedure Check_Returns
154      (HSS  : Node_Id;
155       Mode : Character;
156       Err  : out Boolean;
157       Proc : Entity_Id := Empty);
158    --  Called to check for missing return statements in a function body, or for
159    --  returns present in a procedure body which has No_Return set. HSS is the
160    --  handled statement sequence for the subprogram body. This procedure
161    --  checks all flow paths to make sure they either have return (Mode = 'F',
162    --  used for functions) or do not have a return (Mode = 'P', used for
163    --  No_Return procedures). The flag Err is set if there are any control
164    --  paths not explicitly terminated by a return in the function case, and is
165    --  True otherwise. Proc is the entity for the procedure case and is used
166    --  in posting the warning message.
167
168    procedure Enter_Overloaded_Entity (S : Entity_Id);
169    --  This procedure makes S, a new overloaded entity, into the first visible
170    --  entity with that name.
171
172    procedure Install_Entity (E : Entity_Id);
173    --  Make single entity visible. Used for generic formals as well
174
175    function Is_Non_Overriding_Operation
176      (Prev_E : Entity_Id;
177       New_E  : Entity_Id) return Boolean;
178    --  Enforce the rule given in 12.3(18): a private operation in an instance
179    --  overrides an inherited operation only if the corresponding operation
180    --  was overriding in the generic. This can happen for primitive operations
181    --  of types derived (in the generic unit) from formal private or formal
182    --  derived types.
183
184    procedure Make_Inequality_Operator (S : Entity_Id);
185    --  Create the declaration for an inequality operator that is implicitly
186    --  created by a user-defined equality operator that yields a boolean.
187
188    procedure May_Need_Actuals (Fun : Entity_Id);
189    --  Flag functions that can be called without parameters, i.e. those that
190    --  have no parameters, or those for which defaults exist for all parameters
191
192    procedure Process_PPCs
193      (N       : Node_Id;
194       Spec_Id : Entity_Id;
195       Body_Id : Entity_Id);
196    --  Called from Analyze[_Generic]_Subprogram_Body to deal with scanning post
197    --  conditions for the body and assembling and inserting the _postconditions
198    --  procedure. N is the node for the subprogram body and Body_Id/Spec_Id are
199    --  the entities for the body and separate spec (if there is no separate
200    --  spec, Spec_Id is Empty).
201
202    procedure Set_Formal_Validity (Formal_Id : Entity_Id);
203    --  Formal_Id is an formal parameter entity. This procedure deals with
204    --  setting the proper validity status for this entity, which depends on
205    --  the kind of parameter and the validity checking mode.
206
207    ------------------------------
208    -- Analyze_Return_Statement --
209    ------------------------------
210
211    procedure Analyze_Return_Statement (N : Node_Id) is
212
213       pragma Assert (Nkind_In (N, N_Simple_Return_Statement,
214                                   N_Extended_Return_Statement));
215
216       Returns_Object : constant Boolean :=
217                          Nkind (N) = N_Extended_Return_Statement
218                            or else
219                             (Nkind (N) = N_Simple_Return_Statement
220                               and then Present (Expression (N)));
221       --  True if we're returning something; that is, "return <expression>;"
222       --  or "return Result : T [:= ...]". False for "return;". Used for error
223       --  checking: If Returns_Object is True, N should apply to a function
224       --  body; otherwise N should apply to a procedure body, entry body,
225       --  accept statement, or extended return statement.
226
227       function Find_What_It_Applies_To return Entity_Id;
228       --  Find the entity representing the innermost enclosing body, accept
229       --  statement, or extended return statement. If the result is a callable
230       --  construct or extended return statement, then this will be the value
231       --  of the Return_Applies_To attribute. Otherwise, the program is
232       --  illegal. See RM-6.5(4/2).
233
234       -----------------------------
235       -- Find_What_It_Applies_To --
236       -----------------------------
237
238       function Find_What_It_Applies_To return Entity_Id is
239          Result : Entity_Id := Empty;
240
241       begin
242          --  Loop outward through the Scope_Stack, skipping blocks and loops
243
244          for J in reverse 0 .. Scope_Stack.Last loop
245             Result := Scope_Stack.Table (J).Entity;
246             exit when Ekind (Result) /= E_Block and then
247                       Ekind (Result) /= E_Loop;
248          end loop;
249
250          pragma Assert (Present (Result));
251          return Result;
252       end Find_What_It_Applies_To;
253
254       --  Local declarations
255
256       Scope_Id   : constant Entity_Id   := Find_What_It_Applies_To;
257       Kind       : constant Entity_Kind := Ekind (Scope_Id);
258       Loc        : constant Source_Ptr  := Sloc (N);
259       Stm_Entity : constant Entity_Id   :=
260                      New_Internal_Entity
261                        (E_Return_Statement, Current_Scope, Loc, 'R');
262
263    --  Start of processing for Analyze_Return_Statement
264
265    begin
266       Set_Return_Statement_Entity (N, Stm_Entity);
267
268       Set_Etype (Stm_Entity, Standard_Void_Type);
269       Set_Return_Applies_To (Stm_Entity, Scope_Id);
270
271       --  Place Return entity on scope stack, to simplify enforcement of 6.5
272       --  (4/2): an inner return statement will apply to this extended return.
273
274       if Nkind (N) = N_Extended_Return_Statement then
275          Push_Scope (Stm_Entity);
276       end if;
277
278       --  Check that pragma No_Return is obeyed. Don't complain about the
279       --  implicitly-generated return that is placed at the end.
280
281       if No_Return (Scope_Id) and then Comes_From_Source (N) then
282          Error_Msg_N ("RETURN statement not allowed (No_Return)", N);
283       end if;
284
285       --  Warn on any unassigned OUT parameters if in procedure
286
287       if Ekind (Scope_Id) = E_Procedure then
288          Warn_On_Unassigned_Out_Parameter (N, Scope_Id);
289       end if;
290
291       --  Check that functions return objects, and other things do not
292
293       if Kind = E_Function or else Kind = E_Generic_Function then
294          if not Returns_Object then
295             Error_Msg_N ("missing expression in return from function", N);
296          end if;
297
298       elsif Kind = E_Procedure or else Kind = E_Generic_Procedure then
299          if Returns_Object then
300             Error_Msg_N ("procedure cannot return value (use function)", N);
301          end if;
302
303       elsif Kind = E_Entry or else Kind = E_Entry_Family then
304          if Returns_Object then
305             if Is_Protected_Type (Scope (Scope_Id)) then
306                Error_Msg_N ("entry body cannot return value", N);
307             else
308                Error_Msg_N ("accept statement cannot return value", N);
309             end if;
310          end if;
311
312       elsif Kind = E_Return_Statement then
313
314          --  We are nested within another return statement, which must be an
315          --  extended_return_statement.
316
317          if Returns_Object then
318             Error_Msg_N
319               ("extended_return_statement cannot return value; " &
320                "use `""RETURN;""`", N);
321          end if;
322
323       else
324          Error_Msg_N ("illegal context for return statement", N);
325       end if;
326
327       if Kind = E_Function or else Kind = E_Generic_Function then
328          Analyze_Function_Return (N);
329       end if;
330
331       if Nkind (N) = N_Extended_Return_Statement then
332          End_Scope;
333       end if;
334
335       Kill_Current_Values (Last_Assignment_Only => True);
336       Check_Unreachable_Code (N);
337    end Analyze_Return_Statement;
338
339    ---------------------------------------------
340    -- Analyze_Abstract_Subprogram_Declaration --
341    ---------------------------------------------
342
343    procedure Analyze_Abstract_Subprogram_Declaration (N : Node_Id) is
344       Designator : constant Entity_Id :=
345                      Analyze_Subprogram_Specification (Specification (N));
346       Scop       : constant Entity_Id := Current_Scope;
347
348    begin
349       Generate_Definition (Designator);
350       Set_Is_Abstract_Subprogram (Designator);
351       New_Overloaded_Entity (Designator);
352       Check_Delayed_Subprogram (Designator);
353
354       Set_Categorization_From_Scope (Designator, Scop);
355
356       if Ekind (Scope (Designator)) = E_Protected_Type then
357          Error_Msg_N
358            ("abstract subprogram not allowed in protected type", N);
359
360       --  Issue a warning if the abstract subprogram is neither a dispatching
361       --  operation nor an operation that overrides an inherited subprogram or
362       --  predefined operator, since this most likely indicates a mistake.
363
364       elsif Warn_On_Redundant_Constructs
365         and then not Is_Dispatching_Operation (Designator)
366         and then not Is_Overriding_Operation (Designator)
367         and then (not Is_Operator_Symbol_Name (Chars (Designator))
368                    or else Scop /= Scope (Etype (First_Formal (Designator))))
369       then
370          Error_Msg_N
371            ("?abstract subprogram is not dispatching or overriding", N);
372       end if;
373
374       Generate_Reference_To_Formals (Designator);
375       Check_Eliminated (Designator);
376    end Analyze_Abstract_Subprogram_Declaration;
377
378    ----------------------------------------
379    -- Analyze_Extended_Return_Statement  --
380    ----------------------------------------
381
382    procedure Analyze_Extended_Return_Statement (N : Node_Id) is
383    begin
384       Analyze_Return_Statement (N);
385    end Analyze_Extended_Return_Statement;
386
387    ----------------------------
388    -- Analyze_Function_Call  --
389    ----------------------------
390
391    procedure Analyze_Function_Call (N : Node_Id) is
392       P      : constant Node_Id := Name (N);
393       L      : constant List_Id := Parameter_Associations (N);
394       Actual : Node_Id;
395
396    begin
397       Analyze (P);
398
399       --  A call of the form A.B (X) may be an Ada05 call, which is rewritten
400       --  as B (A, X). If the rewriting is successful, the call has been
401       --  analyzed and we just return.
402
403       if Nkind (P) = N_Selected_Component
404         and then Name (N) /= P
405         and then Is_Rewrite_Substitution (N)
406         and then Present (Etype (N))
407       then
408          return;
409       end if;
410
411       --  If error analyzing name, then set Any_Type as result type and return
412
413       if Etype (P) = Any_Type then
414          Set_Etype (N, Any_Type);
415          return;
416       end if;
417
418       --  Otherwise analyze the parameters
419
420       if Present (L) then
421          Actual := First (L);
422          while Present (Actual) loop
423             Analyze (Actual);
424             Check_Parameterless_Call (Actual);
425             Next (Actual);
426          end loop;
427       end if;
428
429       Analyze_Call (N);
430    end Analyze_Function_Call;
431
432    -----------------------------
433    -- Analyze_Function_Return --
434    -----------------------------
435
436    procedure Analyze_Function_Return (N : Node_Id) is
437       Loc        : constant Source_Ptr  := Sloc (N);
438       Stm_Entity : constant Entity_Id   := Return_Statement_Entity (N);
439       Scope_Id   : constant Entity_Id   := Return_Applies_To (Stm_Entity);
440
441       R_Type : constant Entity_Id := Etype (Scope_Id);
442       --  Function result subtype
443
444       procedure Check_Limited_Return (Expr : Node_Id);
445       --  Check the appropriate (Ada 95 or Ada 2005) rules for returning
446       --  limited types. Used only for simple return statements.
447       --  Expr is the expression returned.
448
449       procedure Check_Return_Subtype_Indication (Obj_Decl : Node_Id);
450       --  Check that the return_subtype_indication properly matches the result
451       --  subtype of the function, as required by RM-6.5(5.1/2-5.3/2).
452
453       --------------------------
454       -- Check_Limited_Return --
455       --------------------------
456
457       procedure Check_Limited_Return (Expr : Node_Id) is
458       begin
459          --  Ada 2005 (AI-318-02): Return-by-reference types have been
460          --  removed and replaced by anonymous access results. This is an
461          --  incompatibility with Ada 95. Not clear whether this should be
462          --  enforced yet or perhaps controllable with special switch. ???
463
464          if Is_Limited_Type (R_Type)
465            and then Comes_From_Source (N)
466            and then not In_Instance_Body
467            and then not OK_For_Limited_Init_In_05 (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
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 non
2689       --  generic tagged private type , mark the subprogram as being a private
2690       --  primitive.
2691
2692       if Present (First_Formal (Designator)) then
2693          declare
2694             Formal_Typ : constant Entity_Id :=
2695                            Etype (First_Formal (Designator));
2696          begin
2697             Set_Is_Private_Primitive (Designator,
2698               Is_Tagged_Type (Formal_Typ)
2699                 and then Is_Private_Type (Formal_Typ)
2700                 and then not Is_Generic_Actual_Type (Formal_Typ));
2701          end;
2702       end if;
2703
2704       --  Ada 2005 (AI-251): Abstract interface primitives must be abstract
2705       --  or null.
2706
2707       if Ada_Version >= Ada_05
2708         and then Comes_From_Source (N)
2709         and then Is_Dispatching_Operation (Designator)
2710       then
2711          declare
2712             E    : Entity_Id;
2713             Etyp : Entity_Id;
2714
2715          begin
2716             if Has_Controlling_Result (Designator) then
2717                Etyp := Etype (Designator);
2718
2719             else
2720                E := First_Entity (Designator);
2721                while Present (E)
2722                  and then Is_Formal (E)
2723                  and then not Is_Controlling_Formal (E)
2724                loop
2725                   Next_Entity (E);
2726                end loop;
2727
2728                Etyp := Etype (E);
2729             end if;
2730
2731             if Is_Access_Type (Etyp) then
2732                Etyp := Directly_Designated_Type (Etyp);
2733             end if;
2734
2735             if Is_Interface (Etyp)
2736               and then not Is_Abstract_Subprogram (Designator)
2737               and then not (Ekind (Designator) = E_Procedure
2738                               and then Null_Present (Specification (N)))
2739             then
2740                Error_Msg_Name_1 := Chars (Defining_Entity (N));
2741                Error_Msg_N
2742                  ("(Ada 2005) interface subprogram % must be abstract or null",
2743                   N);
2744             end if;
2745          end;
2746       end if;
2747
2748       --  What is the following code for, it used to be
2749
2750       --  ???   Set_Suppress_Elaboration_Checks
2751       --  ???     (Designator, Elaboration_Checks_Suppressed (Designator));
2752
2753       --  The following seems equivalent, but a bit dubious
2754
2755       if Elaboration_Checks_Suppressed (Designator) then
2756          Set_Kill_Elaboration_Checks (Designator);
2757       end if;
2758
2759       if Scop /= Standard_Standard
2760         and then not Is_Child_Unit (Designator)
2761       then
2762          Set_Categorization_From_Scope (Designator, Scop);
2763       else
2764          --  For a compilation unit, check for library-unit pragmas
2765
2766          Push_Scope (Designator);
2767          Set_Categorization_From_Pragmas (N);
2768          Validate_Categorization_Dependency (N, Designator);
2769          Pop_Scope;
2770       end if;
2771
2772       --  For a compilation unit, set body required. This flag will only be
2773       --  reset if a valid Import or Interface pragma is processed later on.
2774
2775       if Nkind (Parent (N)) = N_Compilation_Unit then
2776          Set_Body_Required (Parent (N), True);
2777
2778          if Ada_Version >= Ada_05
2779            and then Nkind (Specification (N)) = N_Procedure_Specification
2780            and then Null_Present (Specification (N))
2781          then
2782             Error_Msg_N
2783               ("null procedure cannot be declared at library level", N);
2784          end if;
2785       end if;
2786
2787       Generate_Reference_To_Formals (Designator);
2788       Check_Eliminated (Designator);
2789
2790       if Debug_Flag_C then
2791          Outdent;
2792          Write_Str ("<== subprogram spec ");
2793          Write_Name (Chars (Designator));
2794          Write_Str (" from ");
2795          Write_Location (Sloc (N));
2796          Write_Eol;
2797       end if;
2798    end Analyze_Subprogram_Declaration;
2799
2800    --------------------------------------
2801    -- Analyze_Subprogram_Specification --
2802    --------------------------------------
2803
2804    --  Reminder: N here really is a subprogram specification (not a subprogram
2805    --  declaration). This procedure is called to analyze the specification in
2806    --  both subprogram bodies and subprogram declarations (specs).
2807
2808    function Analyze_Subprogram_Specification (N : Node_Id) return Entity_Id is
2809       Designator : constant Entity_Id := Defining_Entity (N);
2810       Formals    : constant List_Id   := Parameter_Specifications (N);
2811
2812    --  Start of processing for Analyze_Subprogram_Specification
2813
2814    begin
2815       Generate_Definition (Designator);
2816
2817       if Nkind (N) = N_Function_Specification then
2818          Set_Ekind (Designator, E_Function);
2819          Set_Mechanism (Designator, Default_Mechanism);
2820
2821       else
2822          Set_Ekind (Designator, E_Procedure);
2823          Set_Etype (Designator, Standard_Void_Type);
2824       end if;
2825
2826       --  Introduce new scope for analysis of the formals and the return type
2827
2828       Set_Scope (Designator, Current_Scope);
2829
2830       if Present (Formals) then
2831          Push_Scope (Designator);
2832          Process_Formals (Formals, N);
2833
2834          --  Ada 2005 (AI-345): If this is an overriding operation of an
2835          --  inherited interface operation, and the controlling type is
2836          --  a synchronized type, replace the type with its corresponding
2837          --  record, to match the proper signature of an overriding operation.
2838          --  Same processing for an access parameter whose designated type is
2839          --  derived from a synchronized interface.
2840
2841          if Ada_Version >= Ada_05 then
2842             declare
2843                Formal     : Entity_Id;
2844                Formal_Typ : Entity_Id;
2845                Rec_Typ    : Entity_Id;
2846                Desig_Typ  : Entity_Id;
2847
2848             begin
2849                Formal := First_Formal (Designator);
2850                while Present (Formal) loop
2851                   Formal_Typ := Etype (Formal);
2852
2853                   if Is_Concurrent_Type (Formal_Typ)
2854                     and then Present (Corresponding_Record_Type (Formal_Typ))
2855                   then
2856                      Rec_Typ := Corresponding_Record_Type (Formal_Typ);
2857
2858                      if Present (Interfaces (Rec_Typ)) then
2859                         Set_Etype (Formal, Rec_Typ);
2860                      end if;
2861
2862                   elsif Ekind (Formal_Typ) = E_Anonymous_Access_Type then
2863                      Desig_Typ := Designated_Type (Formal_Typ);
2864
2865                      if Is_Concurrent_Type (Desig_Typ)
2866                        and then Present (Corresponding_Record_Type (Desig_Typ))
2867                      then
2868                         Rec_Typ := Corresponding_Record_Type (Desig_Typ);
2869
2870                         if Present (Interfaces (Rec_Typ)) then
2871                            Set_Directly_Designated_Type (Formal_Typ, Rec_Typ);
2872                         end if;
2873                      end if;
2874                   end if;
2875
2876                   Next_Formal (Formal);
2877                end loop;
2878             end;
2879          end if;
2880
2881          End_Scope;
2882
2883       --  The subprogram scope is pushed and popped around the processing of
2884       --  the return type for consistency with call above to Process_Formals
2885       --  (which itself can call Analyze_Return_Type), and to ensure that any
2886       --  itype created for the return type will be associated with the proper
2887       --  scope.
2888
2889       elsif Nkind (N) = N_Function_Specification then
2890          Push_Scope (Designator);
2891
2892          Analyze_Return_Type (N);
2893
2894          End_Scope;
2895       end if;
2896
2897       if Nkind (N) = N_Function_Specification then
2898          if Nkind (Designator) = N_Defining_Operator_Symbol then
2899             Valid_Operator_Definition (Designator);
2900          end if;
2901
2902          May_Need_Actuals (Designator);
2903
2904          --  Ada 2005 (AI-251): If the return type is abstract, verify that
2905          --  the subprogram is abstract also. This does not apply to renaming
2906          --  declarations, where abstractness is inherited.
2907          --  In case of primitives associated with abstract interface types
2908          --  the check is applied later (see Analyze_Subprogram_Declaration).
2909
2910          if Is_Abstract_Type (Etype (Designator))
2911            and then not Is_Interface (Etype (Designator))
2912            and then Nkind (Parent (N)) /= N_Subprogram_Renaming_Declaration
2913            and then Nkind (Parent (N)) /=
2914                       N_Abstract_Subprogram_Declaration
2915            and then
2916              (Nkind (Parent (N))) /= N_Formal_Abstract_Subprogram_Declaration
2917          then
2918             Error_Msg_N
2919               ("function that returns abstract type must be abstract", N);
2920          end if;
2921       end if;
2922
2923       return Designator;
2924    end Analyze_Subprogram_Specification;
2925
2926    --------------------------
2927    -- Build_Body_To_Inline --
2928    --------------------------
2929
2930    procedure Build_Body_To_Inline (N : Node_Id; Subp : Entity_Id) is
2931       Decl            : constant Node_Id := Unit_Declaration_Node (Subp);
2932       Original_Body   : Node_Id;
2933       Body_To_Analyze : Node_Id;
2934       Max_Size        : constant := 10;
2935       Stat_Count      : Integer := 0;
2936
2937       function Has_Excluded_Declaration (Decls : List_Id) return Boolean;
2938       --  Check for declarations that make inlining not worthwhile
2939
2940       function Has_Excluded_Statement   (Stats : List_Id) return Boolean;
2941       --  Check for statements that make inlining not worthwhile: any tasking
2942       --  statement, nested at any level. Keep track of total number of
2943       --  elementary statements, as a measure of acceptable size.
2944
2945       function Has_Pending_Instantiation return Boolean;
2946       --  If some enclosing body contains instantiations that appear before the
2947       --  corresponding generic body, the enclosing body has a freeze node so
2948       --  that it can be elaborated after the generic itself. This might
2949       --  conflict with subsequent inlinings, so that it is unsafe to try to
2950       --  inline in such a case.
2951
2952       function Has_Single_Return return Boolean;
2953       --  In general we cannot inline functions that return unconstrained type.
2954       --  However, we can handle such functions if all return statements return
2955       --  a local variable that is the only declaration in the body of the
2956       --  function. In that case the call can be replaced by that local
2957       --  variable as is done for other inlined calls.
2958
2959       procedure Remove_Pragmas;
2960       --  A pragma Unreferenced or pragma Unmodified that mentions a formal
2961       --  parameter has no meaning when the body is inlined and the formals
2962       --  are rewritten. Remove it from body to inline. The analysis of the
2963       --  non-inlined body will handle the pragma properly.
2964
2965       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean;
2966       --  If the body of the subprogram includes a call that returns an
2967       --  unconstrained type, the secondary stack is involved, and it
2968       --  is not worth inlining.
2969
2970       ------------------------------
2971       -- Has_Excluded_Declaration --
2972       ------------------------------
2973
2974       function Has_Excluded_Declaration (Decls : List_Id) return Boolean is
2975          D : Node_Id;
2976
2977          function Is_Unchecked_Conversion (D : Node_Id) return Boolean;
2978          --  Nested subprograms make a given body ineligible for inlining, but
2979          --  we make an exception for instantiations of unchecked conversion.
2980          --  The body has not been analyzed yet, so check the name, and verify
2981          --  that the visible entity with that name is the predefined unit.
2982
2983          -----------------------------
2984          -- Is_Unchecked_Conversion --
2985          -----------------------------
2986
2987          function Is_Unchecked_Conversion (D : Node_Id) return Boolean is
2988             Id   : constant Node_Id := Name (D);
2989             Conv : Entity_Id;
2990
2991          begin
2992             if Nkind (Id) = N_Identifier
2993               and then Chars (Id) = Name_Unchecked_Conversion
2994             then
2995                Conv := Current_Entity (Id);
2996
2997             elsif Nkind_In (Id, N_Selected_Component, N_Expanded_Name)
2998               and then Chars (Selector_Name (Id)) = Name_Unchecked_Conversion
2999             then
3000                Conv := Current_Entity (Selector_Name (Id));
3001             else
3002                return False;
3003             end if;
3004
3005             return Present (Conv)
3006               and then Is_Predefined_File_Name
3007                          (Unit_File_Name (Get_Source_Unit (Conv)))
3008               and then Is_Intrinsic_Subprogram (Conv);
3009          end Is_Unchecked_Conversion;
3010
3011       --  Start of processing for Has_Excluded_Declaration
3012
3013       begin
3014          D := First (Decls);
3015          while Present (D) loop
3016             if (Nkind (D) = N_Function_Instantiation
3017                   and then not Is_Unchecked_Conversion (D))
3018               or else Nkind_In (D, N_Protected_Type_Declaration,
3019                                    N_Package_Declaration,
3020                                    N_Package_Instantiation,
3021                                    N_Subprogram_Body,
3022                                    N_Procedure_Instantiation,
3023                                    N_Task_Type_Declaration)
3024             then
3025                Cannot_Inline
3026                  ("cannot inline & (non-allowed declaration)?", D, Subp);
3027                return True;
3028             end if;
3029
3030             Next (D);
3031          end loop;
3032
3033          return False;
3034       end Has_Excluded_Declaration;
3035
3036       ----------------------------
3037       -- Has_Excluded_Statement --
3038       ----------------------------
3039
3040       function Has_Excluded_Statement (Stats : List_Id) return Boolean is
3041          S : Node_Id;
3042          E : Node_Id;
3043
3044       begin
3045          S := First (Stats);
3046          while Present (S) loop
3047             Stat_Count := Stat_Count + 1;
3048
3049             if Nkind_In (S, N_Abort_Statement,
3050                             N_Asynchronous_Select,
3051                             N_Conditional_Entry_Call,
3052                             N_Delay_Relative_Statement,
3053                             N_Delay_Until_Statement,
3054                             N_Selective_Accept,
3055                             N_Timed_Entry_Call)
3056             then
3057                Cannot_Inline
3058                  ("cannot inline & (non-allowed statement)?", S, Subp);
3059                return True;
3060
3061             elsif Nkind (S) = N_Block_Statement then
3062                if Present (Declarations (S))
3063                  and then Has_Excluded_Declaration (Declarations (S))
3064                then
3065                   return True;
3066
3067                elsif Present (Handled_Statement_Sequence (S))
3068                   and then
3069                     (Present
3070                       (Exception_Handlers (Handled_Statement_Sequence (S)))
3071                      or else
3072                        Has_Excluded_Statement
3073                          (Statements (Handled_Statement_Sequence (S))))
3074                then
3075                   return True;
3076                end if;
3077
3078             elsif Nkind (S) = N_Case_Statement then
3079                E := First (Alternatives (S));
3080                while Present (E) loop
3081                   if Has_Excluded_Statement (Statements (E)) then
3082                      return True;
3083                   end if;
3084
3085                   Next (E);
3086                end loop;
3087
3088             elsif Nkind (S) = N_If_Statement then
3089                if Has_Excluded_Statement (Then_Statements (S)) then
3090                   return True;
3091                end if;
3092
3093                if Present (Elsif_Parts (S)) then
3094                   E := First (Elsif_Parts (S));
3095                   while Present (E) loop
3096                      if Has_Excluded_Statement (Then_Statements (E)) then
3097                         return True;
3098                      end if;
3099                      Next (E);
3100                   end loop;
3101                end if;
3102
3103                if Present (Else_Statements (S))
3104                  and then Has_Excluded_Statement (Else_Statements (S))
3105                then
3106                   return True;
3107                end if;
3108
3109             elsif Nkind (S) = N_Loop_Statement
3110               and then Has_Excluded_Statement (Statements (S))
3111             then
3112                return True;
3113             end if;
3114
3115             Next (S);
3116          end loop;
3117
3118          return False;
3119       end Has_Excluded_Statement;
3120
3121       -------------------------------
3122       -- Has_Pending_Instantiation --
3123       -------------------------------
3124
3125       function Has_Pending_Instantiation return Boolean is
3126          S : Entity_Id;
3127
3128       begin
3129          S := Current_Scope;
3130          while Present (S) loop
3131             if Is_Compilation_Unit (S)
3132               or else Is_Child_Unit (S)
3133             then
3134                return False;
3135             elsif Ekind (S) = E_Package
3136               and then Has_Forward_Instantiation (S)
3137             then
3138                return True;
3139             end if;
3140
3141             S := Scope (S);
3142          end loop;
3143
3144          return False;
3145       end Has_Pending_Instantiation;
3146
3147       ------------------------
3148       --  Has_Single_Return --
3149       ------------------------
3150
3151       function Has_Single_Return return Boolean is
3152          Return_Statement : Node_Id := Empty;
3153
3154          function Check_Return (N : Node_Id) return Traverse_Result;
3155
3156          ------------------
3157          -- Check_Return --
3158          ------------------
3159
3160          function Check_Return (N : Node_Id) return Traverse_Result is
3161          begin
3162             if Nkind (N) = N_Simple_Return_Statement then
3163                if Present (Expression (N))
3164                  and then Is_Entity_Name (Expression (N))
3165                then
3166                   if No (Return_Statement) then
3167                      Return_Statement := N;
3168                      return OK;
3169
3170                   elsif Chars (Expression (N)) =
3171                         Chars (Expression (Return_Statement))
3172                   then
3173                      return OK;
3174
3175                   else
3176                      return Abandon;
3177                   end if;
3178
3179                else
3180                   --  Expression has wrong form
3181
3182                   return Abandon;
3183                end if;
3184
3185             else
3186                return OK;
3187             end if;
3188          end Check_Return;
3189
3190          function Check_All_Returns is new Traverse_Func (Check_Return);
3191
3192       --  Start of processing for Has_Single_Return
3193
3194       begin
3195          return Check_All_Returns (N) = OK
3196            and then Present (Declarations (N))
3197            and then Present (First (Declarations (N)))
3198            and then Chars (Expression (Return_Statement)) =
3199                     Chars (Defining_Identifier (First (Declarations (N))));
3200       end Has_Single_Return;
3201
3202       --------------------
3203       -- Remove_Pragmas --
3204       --------------------
3205
3206       procedure Remove_Pragmas is
3207          Decl : Node_Id;
3208          Nxt  : Node_Id;
3209
3210       begin
3211          Decl := First (Declarations (Body_To_Analyze));
3212          while Present (Decl) loop
3213             Nxt := Next (Decl);
3214
3215             if Nkind (Decl) = N_Pragma
3216               and then (Pragma_Name (Decl) = Name_Unreferenced
3217                           or else
3218                         Pragma_Name (Decl) = Name_Unmodified)
3219             then
3220                Remove (Decl);
3221             end if;
3222
3223             Decl := Nxt;
3224          end loop;
3225       end Remove_Pragmas;
3226
3227       --------------------------
3228       -- Uses_Secondary_Stack --
3229       --------------------------
3230
3231       function Uses_Secondary_Stack (Bod : Node_Id) return Boolean is
3232          function Check_Call (N : Node_Id) return Traverse_Result;
3233          --  Look for function calls that return an unconstrained type
3234
3235          ----------------
3236          -- Check_Call --
3237          ----------------
3238
3239          function Check_Call (N : Node_Id) return Traverse_Result is
3240          begin
3241             if Nkind (N) = N_Function_Call
3242               and then Is_Entity_Name (Name (N))
3243               and then Is_Composite_Type (Etype (Entity (Name (N))))
3244               and then not Is_Constrained (Etype (Entity (Name (N))))
3245             then
3246                Cannot_Inline
3247                  ("cannot inline & (call returns unconstrained type)?",
3248                     N, Subp);
3249                return Abandon;
3250             else
3251                return OK;
3252             end if;
3253          end Check_Call;
3254
3255          function Check_Calls is new Traverse_Func (Check_Call);
3256
3257       begin
3258          return Check_Calls (Bod) = Abandon;
3259       end Uses_Secondary_Stack;
3260
3261    --  Start of processing for Build_Body_To_Inline
3262
3263    begin
3264       --  Return immediately if done already
3265
3266       if Nkind (Decl) = N_Subprogram_Declaration
3267         and then Present (Body_To_Inline (Decl))
3268       then
3269          return;
3270
3271       --  Functions that return unconstrained composite types require
3272       --  secondary stack handling, and cannot currently be inlined, unless
3273       --  all return statements return a local variable that is the first
3274       --  local declaration in the body.
3275
3276       elsif Ekind (Subp) = E_Function
3277         and then not Is_Scalar_Type (Etype (Subp))
3278         and then not Is_Access_Type (Etype (Subp))
3279         and then not Is_Constrained (Etype (Subp))
3280       then
3281          if not Has_Single_Return then
3282             Cannot_Inline
3283               ("cannot inline & (unconstrained return type)?", N, Subp);
3284             return;
3285          end if;
3286
3287       --  Ditto for functions that return controlled types, where controlled
3288       --  actions interfere in complex ways with inlining.
3289
3290       elsif Ekind (Subp) = E_Function
3291         and then Needs_Finalization (Etype (Subp))
3292       then
3293          Cannot_Inline
3294            ("cannot inline & (controlled return type)?", N, Subp);
3295          return;
3296       end if;
3297
3298       if Present (Declarations (N))
3299         and then Has_Excluded_Declaration (Declarations (N))
3300       then
3301          return;
3302       end if;
3303
3304       if Present (Handled_Statement_Sequence (N)) then
3305          if Present (Exception_Handlers (Handled_Statement_Sequence (N))) then
3306             Cannot_Inline
3307               ("cannot inline& (exception handler)?",
3308                First (Exception_Handlers (Handled_Statement_Sequence (N))),
3309                Subp);
3310             return;
3311          elsif
3312            Has_Excluded_Statement
3313              (Statements (Handled_Statement_Sequence (N)))
3314          then
3315             return;
3316          end if;
3317       end if;
3318
3319       --  We do not inline a subprogram  that is too large, unless it is
3320       --  marked Inline_Always. This pragma does not suppress the other
3321       --  checks on inlining (forbidden declarations, handlers, etc).
3322
3323       if Stat_Count > Max_Size
3324         and then not Has_Pragma_Inline_Always (Subp)
3325       then
3326          Cannot_Inline ("cannot inline& (body too large)?", N, Subp);
3327          return;
3328       end if;
3329
3330       if Has_Pending_Instantiation then
3331          Cannot_Inline
3332            ("cannot inline& (forward instance within enclosing body)?",
3333              N, Subp);
3334          return;
3335       end if;
3336
3337       --  Within an instance, the body to inline must be treated as a nested
3338       --  generic, so that the proper global references are preserved.
3339
3340       --  Note that we do not do this at the library level, because it is not
3341       --  needed, and furthermore this causes trouble if front end inlining
3342       --  is activated (-gnatN).
3343
3344       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
3345          Save_Env (Scope (Current_Scope), Scope (Current_Scope));
3346          Original_Body := Copy_Generic_Node (N, Empty, True);
3347       else
3348          Original_Body := Copy_Separate_Tree (N);
3349       end if;
3350
3351       --  We need to capture references to the formals in order to substitute
3352       --  the actuals at the point of inlining, i.e. instantiation. To treat
3353       --  the formals as globals to the body to inline, we nest it within
3354       --  a dummy parameterless subprogram, declared within the real one.
3355       --  To avoid generating an internal name (which is never public, and
3356       --  which affects serial numbers of other generated names), we use
3357       --  an internal symbol that cannot conflict with user declarations.
3358
3359       Set_Parameter_Specifications (Specification (Original_Body), No_List);
3360       Set_Defining_Unit_Name
3361         (Specification (Original_Body),
3362           Make_Defining_Identifier (Sloc (N), Name_uParent));
3363       Set_Corresponding_Spec (Original_Body, Empty);
3364
3365       Body_To_Analyze := Copy_Generic_Node (Original_Body, Empty, False);
3366
3367       --  Set return type of function, which is also global and does not need
3368       --  to be resolved.
3369
3370       if Ekind (Subp) = E_Function then
3371          Set_Result_Definition (Specification (Body_To_Analyze),
3372            New_Occurrence_Of (Etype (Subp), Sloc (N)));
3373       end if;
3374
3375       if No (Declarations (N)) then
3376          Set_Declarations (N, New_List (Body_To_Analyze));
3377       else
3378          Append (Body_To_Analyze, Declarations (N));
3379       end if;
3380
3381       Expander_Mode_Save_And_Set (False);
3382       Remove_Pragmas;
3383
3384       Analyze (Body_To_Analyze);
3385       Push_Scope (Defining_Entity (Body_To_Analyze));
3386       Save_Global_References (Original_Body);
3387       End_Scope;
3388       Remove (Body_To_Analyze);
3389
3390       Expander_Mode_Restore;
3391
3392       --  Restore environment if previously saved
3393
3394       if In_Instance and then Scope (Current_Scope) /= Standard_Standard then
3395          Restore_Env;
3396       end if;
3397
3398       --  If secondary stk used there is no point in inlining. We have
3399       --  already issued the warning in this case, so nothing to do.
3400
3401       if Uses_Secondary_Stack (Body_To_Analyze) then
3402          return;
3403       end if;
3404
3405       Set_Body_To_Inline (Decl, Original_Body);
3406       Set_Ekind (Defining_Entity (Original_Body), Ekind (Subp));
3407       Set_Is_Inlined (Subp);
3408    end Build_Body_To_Inline;
3409
3410    -------------------
3411    -- Cannot_Inline --
3412    -------------------
3413
3414    procedure Cannot_Inline (Msg : String; N : Node_Id; Subp : Entity_Id) is
3415    begin
3416       --  Do not emit warning if this is a predefined unit which is not
3417       --  the main unit. With validity checks enabled, some predefined
3418       --  subprograms may contain nested subprograms and become ineligible
3419       --  for inlining.
3420
3421       if Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Subp)))
3422         and then not In_Extended_Main_Source_Unit (Subp)
3423       then
3424          null;
3425
3426       elsif Has_Pragma_Inline_Always (Subp) then
3427
3428          --  Remove last character (question mark) to make this into an error,
3429          --  because the Inline_Always pragma cannot be obeyed.
3430
3431          Error_Msg_NE (Msg (Msg'First .. Msg'Last - 1), N, Subp);
3432
3433       elsif Ineffective_Inline_Warnings then
3434          Error_Msg_NE (Msg, N, Subp);
3435       end if;
3436    end Cannot_Inline;
3437
3438    -----------------------
3439    -- Check_Conformance --
3440    -----------------------
3441
3442    procedure Check_Conformance
3443      (New_Id                   : Entity_Id;
3444       Old_Id                   : Entity_Id;
3445       Ctype                    : Conformance_Type;
3446       Errmsg                   : Boolean;
3447       Conforms                 : out Boolean;
3448       Err_Loc                  : Node_Id := Empty;
3449       Get_Inst                 : Boolean := False;
3450       Skip_Controlling_Formals : Boolean := False)
3451    is
3452       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id);
3453       --  Sets Conforms to False. If Errmsg is False, then that's all it does.
3454       --  If Errmsg is True, then processing continues to post an error message
3455       --  for conformance error on given node. Two messages are output. The
3456       --  first message points to the previous declaration with a general "no
3457       --  conformance" message. The second is the detailed reason, supplied as
3458       --  Msg. The parameter N provide information for a possible & insertion
3459       --  in the message, and also provides the location for posting the
3460       --  message in the absence of a specified Err_Loc location.
3461
3462       -----------------------
3463       -- Conformance_Error --
3464       -----------------------
3465
3466       procedure Conformance_Error (Msg : String; N : Node_Id := New_Id) is
3467          Enode : Node_Id;
3468
3469       begin
3470          Conforms := False;
3471
3472          if Errmsg then
3473             if No (Err_Loc) then
3474                Enode := N;
3475             else
3476                Enode := Err_Loc;
3477             end if;
3478
3479             Error_Msg_Sloc := Sloc (Old_Id);
3480
3481             case Ctype is
3482                when Type_Conformant =>
3483                   Error_Msg_N -- CODEFIX
3484                     ("not type conformant with declaration#!", Enode);
3485
3486                when Mode_Conformant =>
3487                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3488                      Error_Msg_N -- CODEFIX???
3489                        ("not mode conformant with operation inherited#!",
3490                          Enode);
3491                   else
3492                      Error_Msg_N -- CODEFIX???
3493                        ("not mode conformant with declaration#!", Enode);
3494                   end if;
3495
3496                when Subtype_Conformant =>
3497                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3498                      Error_Msg_N -- CODEFIX???
3499                        ("not subtype conformant with operation inherited#!",
3500                          Enode);
3501                   else
3502                      Error_Msg_N -- CODEFIX???
3503                        ("not subtype conformant with declaration#!", Enode);
3504                   end if;
3505
3506                when Fully_Conformant =>
3507                   if Nkind (Parent (Old_Id)) = N_Full_Type_Declaration then
3508                      Error_Msg_N -- CODEFIX
3509                        ("not fully conformant with operation inherited#!",
3510                          Enode);
3511                   else
3512                      Error_Msg_N -- CODEFIX
3513                        ("not fully conformant with declaration#!", Enode);
3514                   end if;
3515             end case;
3516
3517             Error_Msg_NE (Msg, Enode, N);
3518          end if;
3519       end Conformance_Error;
3520
3521       --  Local Variables
3522
3523       Old_Type           : constant Entity_Id := Etype (Old_Id);
3524       New_Type           : constant Entity_Id := Etype (New_Id);
3525       Old_Formal         : Entity_Id;
3526       New_Formal         : Entity_Id;
3527       Access_Types_Match : Boolean;
3528       Old_Formal_Base    : Entity_Id;
3529       New_Formal_Base    : Entity_Id;
3530
3531    --  Start of processing for Check_Conformance
3532
3533    begin
3534       Conforms := True;
3535
3536       --  We need a special case for operators, since they don't appear
3537       --  explicitly.
3538
3539       if Ctype = Type_Conformant then
3540          if Ekind (New_Id) = E_Operator
3541            and then Operator_Matches_Spec (New_Id, Old_Id)
3542          then
3543             return;
3544          end if;
3545       end if;
3546
3547       --  If both are functions/operators, check return types conform
3548
3549       if Old_Type /= Standard_Void_Type
3550         and then New_Type /= Standard_Void_Type
3551       then
3552
3553          --  If we are checking interface conformance we omit controlling
3554          --  arguments and result, because we are only checking the conformance
3555          --  of the remaining parameters.
3556
3557          if Has_Controlling_Result (Old_Id)
3558            and then Has_Controlling_Result (New_Id)
3559            and then Skip_Controlling_Formals
3560          then
3561             null;
3562
3563          elsif not Conforming_Types (Old_Type, New_Type, Ctype, Get_Inst) then
3564             Conformance_Error ("\return type does not match!", New_Id);
3565             return;
3566          end if;
3567
3568          --  Ada 2005 (AI-231): In case of anonymous access types check the
3569          --  null-exclusion and access-to-constant attributes match.
3570
3571          if Ada_Version >= Ada_05
3572            and then Ekind (Etype (Old_Type)) = E_Anonymous_Access_Type
3573            and then
3574              (Can_Never_Be_Null (Old_Type)
3575                 /= Can_Never_Be_Null (New_Type)
3576               or else Is_Access_Constant (Etype (Old_Type))
3577                         /= Is_Access_Constant (Etype (New_Type)))
3578          then
3579             Conformance_Error ("\return type does not match!", New_Id);
3580             return;
3581          end if;
3582
3583       --  If either is a function/operator and the other isn't, error
3584
3585       elsif Old_Type /= Standard_Void_Type
3586         or else New_Type /= Standard_Void_Type
3587       then
3588          Conformance_Error ("\functions can only match functions!", New_Id);
3589          return;
3590       end if;
3591
3592       --  In subtype conformant case, conventions must match (RM 6.3.1(16)).
3593       --  If this is a renaming as body, refine error message to indicate that
3594       --  the conflict is with the original declaration. If the entity is not
3595       --  frozen, the conventions don't have to match, the one of the renamed
3596       --  entity is inherited.
3597
3598       if Ctype >= Subtype_Conformant then
3599          if Convention (Old_Id) /= Convention (New_Id) then
3600
3601             if not Is_Frozen (New_Id) then
3602                null;
3603
3604             elsif Present (Err_Loc)
3605               and then Nkind (Err_Loc) = N_Subprogram_Renaming_Declaration
3606               and then Present (Corresponding_Spec (Err_Loc))
3607             then
3608                Error_Msg_Name_1 := Chars (New_Id);
3609                Error_Msg_Name_2 :=
3610                  Name_Ada + Convention_Id'Pos (Convention (New_Id));
3611
3612                Conformance_Error ("\prior declaration for% has convention %!");
3613
3614             else
3615                Conformance_Error ("\calling conventions do not match!");
3616             end if;
3617
3618             return;
3619
3620          elsif Is_Formal_Subprogram (Old_Id)
3621            or else Is_Formal_Subprogram (New_Id)
3622          then
3623             Conformance_Error ("\formal subprograms not allowed!");
3624             return;
3625          end if;
3626       end if;
3627
3628       --  Deal with parameters
3629
3630       --  Note: we use the entity information, rather than going directly
3631       --  to the specification in the tree. This is not only simpler, but
3632       --  absolutely necessary for some cases of conformance tests between
3633       --  operators, where the declaration tree simply does not exist!
3634
3635       Old_Formal := First_Formal (Old_Id);
3636       New_Formal := First_Formal (New_Id);
3637       while Present (Old_Formal) and then Present (New_Formal) loop
3638          if Is_Controlling_Formal (Old_Formal)
3639            and then Is_Controlling_Formal (New_Formal)
3640            and then Skip_Controlling_Formals
3641          then
3642             --  The controlling formals will have different types when
3643             --  comparing an interface operation with its match, but both
3644             --  or neither must be access parameters.
3645
3646             if Is_Access_Type (Etype (Old_Formal))
3647                  =
3648                Is_Access_Type (Etype (New_Formal))
3649             then
3650                goto Skip_Controlling_Formal;
3651             else
3652                Conformance_Error
3653                  ("\access parameter does not match!", New_Formal);
3654             end if;
3655          end if;
3656
3657          if Ctype = Fully_Conformant then
3658
3659             --  Names must match. Error message is more accurate if we do
3660             --  this before checking that the types of the formals match.
3661
3662             if Chars (Old_Formal) /= Chars (New_Formal) then
3663                Conformance_Error ("\name & does not match!", New_Formal);
3664
3665                --  Set error posted flag on new formal as well to stop
3666                --  junk cascaded messages in some cases.
3667
3668                Set_Error_Posted (New_Formal);
3669                return;
3670             end if;
3671          end if;
3672
3673          --  Ada 2005 (AI-423): Possible access [sub]type and itype match. This
3674          --  case occurs whenever a subprogram is being renamed and one of its
3675          --  parameters imposes a null exclusion. For example:
3676
3677          --     type T is null record;
3678          --     type Acc_T is access T;
3679          --     subtype Acc_T_Sub is Acc_T;
3680
3681          --     procedure P     (Obj : not null Acc_T_Sub);  --  itype
3682          --     procedure Ren_P (Obj :          Acc_T_Sub)   --  subtype
3683          --       renames P;
3684
3685          Old_Formal_Base := Etype (Old_Formal);
3686          New_Formal_Base := Etype (New_Formal);
3687
3688          if Get_Inst then
3689             Old_Formal_Base := Get_Instance_Of (Old_Formal_Base);
3690             New_Formal_Base := Get_Instance_Of (New_Formal_Base);
3691          end if;
3692
3693          Access_Types_Match := Ada_Version >= Ada_05
3694
3695             --  Ensure that this rule is only applied when New_Id is a
3696             --  renaming of Old_Id.
3697
3698            and then Nkind (Parent (Parent (New_Id))) =
3699                       N_Subprogram_Renaming_Declaration
3700            and then Nkind (Name (Parent (Parent (New_Id)))) in N_Has_Entity
3701            and then Present (Entity (Name (Parent (Parent (New_Id)))))
3702            and then Entity (Name (Parent (Parent (New_Id)))) = Old_Id
3703
3704             --  Now handle the allowed access-type case
3705
3706            and then Is_Access_Type (Old_Formal_Base)
3707            and then Is_Access_Type (New_Formal_Base)
3708
3709             --  The type kinds must match. The only exception occurs with
3710             --  multiple generics of the form:
3711
3712             --   generic                    generic
3713             --     type F is private;         type A is private;
3714             --     type F_Ptr is access F;    type A_Ptr is access A;
3715             --     with proc F_P (X : F_Ptr); with proc A_P (X : A_Ptr);
3716             --   package F_Pack is ...      package A_Pack is
3717             --                                package F_Inst is
3718             --                                  new F_Pack (A, A_Ptr, A_P);
3719
3720             --  When checking for conformance between the parameters of A_P
3721             --  and F_P, the type kinds of F_Ptr and A_Ptr will not match
3722             --  because the compiler has transformed A_Ptr into a subtype of
3723             --  F_Ptr. We catch this case in the code below.
3724
3725            and then (Ekind (Old_Formal_Base) = Ekind (New_Formal_Base)
3726                   or else
3727                     (Is_Generic_Type (Old_Formal_Base)
3728                        and then Is_Generic_Type (New_Formal_Base)
3729                        and then Is_Internal (New_Formal_Base)
3730                        and then Etype (Etype (New_Formal_Base)) =
3731                                   Old_Formal_Base))
3732            and then Directly_Designated_Type (Old_Formal_Base) =
3733                       Directly_Designated_Type (New_Formal_Base)
3734            and then ((Is_Itype (Old_Formal_Base)
3735                        and then Can_Never_Be_Null (Old_Formal_Base))
3736                     or else
3737                      (Is_Itype (New_Formal_Base)
3738                        and then Can_Never_Be_Null (New_Formal_Base)));
3739
3740          --  Types must always match. In the visible part of an instance,
3741          --  usual overloading rules for dispatching operations apply, and
3742          --  we check base types (not the actual subtypes).
3743
3744          if In_Instance_Visible_Part
3745            and then Is_Dispatching_Operation (New_Id)
3746          then
3747             if not Conforming_Types
3748                      (T1       => Base_Type (Etype (Old_Formal)),
3749                       T2       => Base_Type (Etype (New_Formal)),
3750                       Ctype    => Ctype,
3751                       Get_Inst => Get_Inst)
3752                and then not Access_Types_Match
3753             then
3754                Conformance_Error ("\type of & does not match!", New_Formal);
3755                return;
3756             end if;
3757
3758          elsif not Conforming_Types
3759                      (T1       => Old_Formal_Base,
3760                       T2       => New_Formal_Base,
3761                       Ctype    => Ctype,
3762                       Get_Inst => Get_Inst)
3763            and then not Access_Types_Match
3764          then
3765             --  Don't give error message if old type is Any_Type. This test
3766             --  avoids some cascaded errors, e.g. in case of a bad spec.
3767
3768             if Errmsg and then Old_Formal_Base = Any_Type then
3769                Conforms := False;
3770             else
3771                Conformance_Error ("\type of & does not match!", New_Formal);
3772             end if;
3773
3774             return;
3775          end if;
3776
3777          --  For mode conformance, mode must match
3778
3779          if Ctype >= Mode_Conformant then
3780             if Parameter_Mode (Old_Formal) /= Parameter_Mode (New_Formal) then
3781                Conformance_Error ("\mode of & does not match!", New_Formal);
3782                return;
3783
3784             --  Part of mode conformance for access types is having the same
3785             --  constant modifier.
3786
3787             elsif Access_Types_Match
3788               and then Is_Access_Constant (Old_Formal_Base) /=
3789                        Is_Access_Constant (New_Formal_Base)
3790             then
3791                Conformance_Error
3792                  ("\constant modifier does not match!", New_Formal);
3793                return;
3794             end if;
3795          end if;
3796
3797          if Ctype >= Subtype_Conformant then
3798
3799             --  Ada 2005 (AI-231): In case of anonymous access types check
3800             --  the null-exclusion and access-to-constant attributes must
3801             --  match.
3802
3803             if Ada_Version >= Ada_05
3804               and then Ekind (Etype (Old_Formal)) = E_Anonymous_Access_Type
3805               and then Ekind (Etype (New_Formal)) = E_Anonymous_Access_Type
3806               and then
3807                 (Can_Never_Be_Null (Old_Formal) /=
3808                  Can_Never_Be_Null (New_Formal)
3809                    or else
3810                  Is_Access_Constant (Etype (Old_Formal)) /=
3811                  Is_Access_Constant (Etype (New_Formal)))
3812             then
3813                --  It is allowed to omit the null-exclusion in case of stream
3814                --  attribute subprograms. We recognize stream subprograms
3815                --  through their TSS-generated suffix.
3816
3817                declare
3818                   TSS_Name : constant TSS_Name_Type := Get_TSS_Name (New_Id);
3819                begin
3820                   if TSS_Name /= TSS_Stream_Read
3821                     and then TSS_Name /= TSS_Stream_Write
3822                     and then TSS_Name /= TSS_Stream_Input
3823                     and then TSS_Name /= TSS_Stream_Output
3824                   then
3825                      Conformance_Error
3826                        ("\type of & does not match!", New_Formal);
3827                      return;
3828                   end if;
3829                end;
3830             end if;
3831          end if;
3832
3833          --  Full conformance checks
3834
3835          if Ctype = Fully_Conformant then
3836
3837             --  We have checked already that names match
3838
3839             if Parameter_Mode (Old_Formal) = E_In_Parameter then
3840
3841                --  Check default expressions for in parameters
3842
3843                declare
3844                   NewD : constant Boolean :=
3845                            Present (Default_Value (New_Formal));
3846                   OldD : constant Boolean :=
3847                            Present (Default_Value (Old_Formal));
3848                begin
3849                   if NewD or OldD then
3850
3851                      --  The old default value has been analyzed because the
3852                      --  current full declaration will have frozen everything
3853                      --  before. The new default value has not been analyzed,
3854                      --  so analyze it now before we check for conformance.
3855
3856                      if NewD then
3857                         Push_Scope (New_Id);
3858                         Preanalyze_Spec_Expression
3859                           (Default_Value (New_Formal), Etype (New_Formal));
3860                         End_Scope;
3861                      end if;
3862
3863                      if not (NewD and OldD)
3864                        or else not Fully_Conformant_Expressions
3865                                     (Default_Value (Old_Formal),
3866                                      Default_Value (New_Formal))
3867                      then
3868                         Conformance_Error
3869                           ("\default expression for & does not match!",
3870                            New_Formal);
3871                         return;
3872                      end if;
3873                   end if;
3874                end;
3875             end if;
3876          end if;
3877
3878          --  A couple of special checks for Ada 83 mode. These checks are
3879          --  skipped if either entity is an operator in package Standard,
3880          --  or if either old or new instance is not from the source program.
3881
3882          if Ada_Version = Ada_83
3883            and then Sloc (Old_Id) > Standard_Location
3884            and then Sloc (New_Id) > Standard_Location
3885            and then Comes_From_Source (Old_Id)
3886            and then Comes_From_Source (New_Id)
3887          then
3888             declare
3889                Old_Param : constant Node_Id := Declaration_Node (Old_Formal);
3890                New_Param : constant Node_Id := Declaration_Node (New_Formal);
3891
3892             begin
3893                --  Explicit IN must be present or absent in both cases. This
3894                --  test is required only in the full conformance case.
3895
3896                if In_Present (Old_Param) /= In_Present (New_Param)
3897                  and then Ctype = Fully_Conformant
3898                then
3899                   Conformance_Error
3900                     ("\(Ada 83) IN must appear in both declarations",
3901                      New_Formal);
3902                   return;
3903                end if;
3904
3905                --  Grouping (use of comma in param lists) must be the same
3906                --  This is where we catch a misconformance like:
3907
3908                --    A, B : Integer
3909                --    A : Integer; B : Integer
3910
3911                --  which are represented identically in the tree except
3912                --  for the setting of the flags More_Ids and Prev_Ids.
3913
3914                if More_Ids (Old_Param) /= More_Ids (New_Param)
3915                  or else Prev_Ids (Old_Param) /= Prev_Ids (New_Param)
3916                then
3917                   Conformance_Error
3918                     ("\grouping of & does not match!", New_Formal);
3919                   return;
3920                end if;
3921             end;
3922          end if;
3923
3924          --  This label is required when skipping controlling formals
3925
3926          <<Skip_Controlling_Formal>>
3927
3928          Next_Formal (Old_Formal);
3929          Next_Formal (New_Formal);
3930       end loop;
3931
3932       if Present (Old_Formal) then
3933          Conformance_Error ("\too few parameters!");
3934          return;
3935
3936       elsif Present (New_Formal) then
3937          Conformance_Error ("\too many parameters!", New_Formal);
3938          return;
3939       end if;
3940    end Check_Conformance;
3941
3942    -----------------------
3943    -- Check_Conventions --
3944    -----------------------
3945
3946    procedure Check_Conventions (Typ : Entity_Id) is
3947       Ifaces_List : Elist_Id;
3948
3949       procedure Check_Convention (Op : Entity_Id);
3950       --  Verify that the convention of inherited dispatching operation Op is
3951       --  consistent among all subprograms it overrides. In order to minimize
3952       --  the search, Search_From is utilized to designate a specific point in
3953       --  the list rather than iterating over the whole list once more.
3954
3955       ----------------------
3956       -- Check_Convention --
3957       ----------------------
3958
3959       procedure Check_Convention (Op : Entity_Id) is
3960          Iface_Elmt      : Elmt_Id;
3961          Iface_Prim_Elmt : Elmt_Id;
3962          Iface_Prim      : Entity_Id;
3963
3964       begin
3965          Iface_Elmt := First_Elmt (Ifaces_List);
3966          while Present (Iface_Elmt) loop
3967             Iface_Prim_Elmt :=
3968                First_Elmt (Primitive_Operations (Node (Iface_Elmt)));
3969             while Present (Iface_Prim_Elmt) loop
3970                Iface_Prim := Node (Iface_Prim_Elmt);
3971
3972                if Is_Interface_Conformant (Typ, Iface_Prim, Op)
3973                  and then Convention (Iface_Prim) /= Convention (Op)
3974                then
3975                   Error_Msg_N
3976                     ("inconsistent conventions in primitive operations", Typ);
3977
3978                   Error_Msg_Name_1 := Chars (Op);
3979                   Error_Msg_Name_2 := Get_Convention_Name (Convention (Op));
3980                   Error_Msg_Sloc   := Sloc (Op);
3981
3982                   if Comes_From_Source (Op) then
3983                      if not Is_Overriding_Operation (Op) then
3984                         Error_Msg_N ("\\primitive % defined #", Typ);
3985                      else
3986                         Error_Msg_N ("\\overriding operation % with " &
3987                                      "convention % defined #", Typ);
3988                      end if;
3989
3990                   else pragma Assert (Present (Alias (Op)));
3991                      Error_Msg_Sloc := Sloc (Alias (Op));
3992                      Error_Msg_N ("\\inherited operation % with " &
3993                                   "convention % defined #", Typ);
3994                   end if;
3995
3996                   Error_Msg_Name_1 := Chars (Op);
3997                   Error_Msg_Name_2 :=
3998                     Get_Convention_Name (Convention (Iface_Prim));
3999                   Error_Msg_Sloc := Sloc (Iface_Prim);
4000                   Error_Msg_N ("\\overridden operation % with " &
4001                                "convention % defined #", Typ);
4002
4003                   --  Avoid cascading errors
4004
4005                   return;
4006                end if;
4007
4008                Next_Elmt (Iface_Prim_Elmt);
4009             end loop;
4010
4011             Next_Elmt (Iface_Elmt);
4012          end loop;
4013       end Check_Convention;
4014
4015       --  Local variables
4016
4017       Prim_Op      : Entity_Id;
4018       Prim_Op_Elmt : Elmt_Id;
4019
4020    --  Start of processing for Check_Conventions
4021
4022    begin
4023       if not Has_Interfaces (Typ) then
4024          return;
4025       end if;
4026
4027       Collect_Interfaces (Typ, Ifaces_List);
4028
4029       --  The algorithm checks every overriding dispatching operation against
4030       --  all the corresponding overridden dispatching operations, detecting
4031       --  differences in conventions.
4032
4033       Prim_Op_Elmt := First_Elmt (Primitive_Operations (Typ));
4034       while Present (Prim_Op_Elmt) loop
4035          Prim_Op := Node (Prim_Op_Elmt);
4036
4037          --  A small optimization: skip the predefined dispatching operations
4038          --  since they always have the same convention.
4039
4040          if not Is_Predefined_Dispatching_Operation (Prim_Op) then
4041             Check_Convention (Prim_Op);
4042          end if;
4043
4044          Next_Elmt (Prim_Op_Elmt);
4045       end loop;
4046    end Check_Conventions;
4047
4048    ------------------------------
4049    -- Check_Delayed_Subprogram --
4050    ------------------------------
4051
4052    procedure Check_Delayed_Subprogram (Designator : Entity_Id) is
4053       F : Entity_Id;
4054
4055       procedure Possible_Freeze (T : Entity_Id);
4056       --  T is the type of either a formal parameter or of the return type.
4057       --  If T is not yet frozen and needs a delayed freeze, then the
4058       --  subprogram itself must be delayed. If T is the limited view of an
4059       --  incomplete type the subprogram must be frozen as well, because
4060       --  T may depend on local types that have not been frozen yet.
4061
4062       ---------------------
4063       -- Possible_Freeze --
4064       ---------------------
4065
4066       procedure Possible_Freeze (T : Entity_Id) is
4067       begin
4068          if Has_Delayed_Freeze (T) and then not Is_Frozen (T) then
4069             Set_Has_Delayed_Freeze (Designator);
4070
4071          elsif Is_Access_Type (T)
4072            and then Has_Delayed_Freeze (Designated_Type (T))
4073            and then not Is_Frozen (Designated_Type (T))
4074          then
4075             Set_Has_Delayed_Freeze (Designator);
4076
4077          elsif Ekind (T) = E_Incomplete_Type and then From_With_Type (T) then
4078             Set_Has_Delayed_Freeze (Designator);
4079          end if;
4080
4081       end Possible_Freeze;
4082
4083    --  Start of processing for Check_Delayed_Subprogram
4084
4085    begin
4086       --  Never need to freeze abstract subprogram
4087
4088       if Ekind (Designator) /= E_Subprogram_Type
4089         and then Is_Abstract_Subprogram (Designator)
4090       then
4091          null;
4092       else
4093          --  Need delayed freeze if return type itself needs a delayed
4094          --  freeze and is not yet frozen.
4095
4096          Possible_Freeze (Etype (Designator));
4097          Possible_Freeze (Base_Type (Etype (Designator))); -- needed ???
4098
4099          --  Need delayed freeze if any of the formal types themselves need
4100          --  a delayed freeze and are not yet frozen.
4101
4102          F := First_Formal (Designator);
4103          while Present (F) loop
4104             Possible_Freeze (Etype (F));
4105             Possible_Freeze (Base_Type (Etype (F))); -- needed ???
4106             Next_Formal (F);
4107          end loop;
4108       end if;
4109
4110       --  Mark functions that return by reference. Note that it cannot be
4111       --  done for delayed_freeze subprograms because the underlying
4112       --  returned type may not be known yet (for private types)
4113
4114       if not Has_Delayed_Freeze (Designator)
4115         and then Expander_Active
4116       then
4117          declare
4118             Typ  : constant Entity_Id := Etype (Designator);
4119             Utyp : constant Entity_Id := Underlying_Type (Typ);
4120
4121          begin
4122             if Is_Inherently_Limited_Type (Typ) then
4123                Set_Returns_By_Ref (Designator);
4124
4125             elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
4126                Set_Returns_By_Ref (Designator);
4127             end if;
4128          end;
4129       end if;
4130    end Check_Delayed_Subprogram;
4131
4132    ------------------------------------
4133    -- Check_Discriminant_Conformance --
4134    ------------------------------------
4135
4136    procedure Check_Discriminant_Conformance
4137      (N        : Node_Id;
4138       Prev     : Entity_Id;
4139       Prev_Loc : Node_Id)
4140    is
4141       Old_Discr      : Entity_Id := First_Discriminant (Prev);
4142       New_Discr      : Node_Id   := First (Discriminant_Specifications (N));
4143       New_Discr_Id   : Entity_Id;
4144       New_Discr_Type : Entity_Id;
4145
4146       procedure Conformance_Error (Msg : String; N : Node_Id);
4147       --  Post error message for conformance error on given node. Two messages
4148       --  are output. The first points to the previous declaration with a
4149       --  general "no conformance" message. The second is the detailed reason,
4150       --  supplied as Msg. The parameter N provide information for a possible
4151       --  & insertion in the message.
4152
4153       -----------------------
4154       -- Conformance_Error --
4155       -----------------------
4156
4157       procedure Conformance_Error (Msg : String; N : Node_Id) is
4158       begin
4159          Error_Msg_Sloc := Sloc (Prev_Loc);
4160          Error_Msg_N -- CODEFIX
4161            ("not fully conformant with declaration#!", N);
4162          Error_Msg_NE (Msg, N, N);
4163       end Conformance_Error;
4164
4165    --  Start of processing for Check_Discriminant_Conformance
4166
4167    begin
4168       while Present (Old_Discr) and then Present (New_Discr) loop
4169
4170          New_Discr_Id := Defining_Identifier (New_Discr);
4171
4172          --  The subtype mark of the discriminant on the full type has not
4173          --  been analyzed so we do it here. For an access discriminant a new
4174          --  type is created.
4175
4176          if Nkind (Discriminant_Type (New_Discr)) = N_Access_Definition then
4177             New_Discr_Type :=
4178               Access_Definition (N, Discriminant_Type (New_Discr));
4179
4180          else
4181             Analyze (Discriminant_Type (New_Discr));
4182             New_Discr_Type := Etype (Discriminant_Type (New_Discr));
4183
4184             --  Ada 2005: if the discriminant definition carries a null
4185             --  exclusion, create an itype to check properly for consistency
4186             --  with partial declaration.
4187
4188             if Is_Access_Type (New_Discr_Type)
4189                  and then Null_Exclusion_Present (New_Discr)
4190             then
4191                New_Discr_Type :=
4192                  Create_Null_Excluding_Itype
4193                    (T           => New_Discr_Type,
4194                     Related_Nod => New_Discr,
4195                     Scope_Id    => Current_Scope);
4196             end if;
4197          end if;
4198
4199          if not Conforming_Types
4200                   (Etype (Old_Discr), New_Discr_Type, Fully_Conformant)
4201          then
4202             Conformance_Error ("type of & does not match!", New_Discr_Id);
4203             return;
4204          else
4205             --  Treat the new discriminant as an occurrence of the old one,
4206             --  for navigation purposes, and fill in some semantic
4207             --  information, for completeness.
4208
4209             Generate_Reference (Old_Discr, New_Discr_Id, 'r');
4210             Set_Etype (New_Discr_Id, Etype (Old_Discr));
4211             Set_Scope (New_Discr_Id, Scope (Old_Discr));
4212          end if;
4213
4214          --  Names must match
4215
4216          if Chars (Old_Discr) /= Chars (Defining_Identifier (New_Discr)) then
4217             Conformance_Error ("name & does not match!", New_Discr_Id);
4218             return;
4219          end if;
4220
4221          --  Default expressions must match
4222
4223          declare
4224             NewD : constant Boolean :=
4225                      Present (Expression (New_Discr));
4226             OldD : constant Boolean :=
4227                      Present (Expression (Parent (Old_Discr)));
4228
4229          begin
4230             if NewD or OldD then
4231
4232                --  The old default value has been analyzed and expanded,
4233                --  because the current full declaration will have frozen
4234                --  everything before. The new default values have not been
4235                --  expanded, so expand now to check conformance.
4236
4237                if NewD then
4238                   Preanalyze_Spec_Expression
4239                     (Expression (New_Discr), New_Discr_Type);
4240                end if;
4241
4242                if not (NewD and OldD)
4243                  or else not Fully_Conformant_Expressions
4244                               (Expression (Parent (Old_Discr)),
4245                                Expression (New_Discr))
4246
4247                then
4248                   Conformance_Error
4249                     ("default expression for & does not match!",
4250                      New_Discr_Id);
4251                   return;
4252                end if;
4253             end if;
4254          end;
4255
4256          --  In Ada 83 case, grouping must match: (A,B : X) /= (A : X; B : X)
4257
4258          if Ada_Version = Ada_83 then
4259             declare
4260                Old_Disc : constant Node_Id := Declaration_Node (Old_Discr);
4261
4262             begin
4263                --  Grouping (use of comma in param lists) must be the same
4264                --  This is where we catch a misconformance like:
4265
4266                --    A,B : Integer
4267                --    A : Integer; B : Integer
4268
4269                --  which are represented identically in the tree except
4270                --  for the setting of the flags More_Ids and Prev_Ids.
4271
4272                if More_Ids (Old_Disc) /= More_Ids (New_Discr)
4273                  or else Prev_Ids (Old_Disc) /= Prev_Ids (New_Discr)
4274                then
4275                   Conformance_Error
4276                     ("grouping of & does not match!", New_Discr_Id);
4277                   return;
4278                end if;
4279             end;
4280          end if;
4281
4282          Next_Discriminant (Old_Discr);
4283          Next (New_Discr);
4284       end loop;
4285
4286       if Present (Old_Discr) then
4287          Conformance_Error ("too few discriminants!", Defining_Identifier (N));
4288          return;
4289
4290       elsif Present (New_Discr) then
4291          Conformance_Error
4292            ("too many discriminants!", Defining_Identifier (New_Discr));
4293          return;
4294       end if;
4295    end Check_Discriminant_Conformance;
4296
4297    ----------------------------
4298    -- Check_Fully_Conformant --
4299    ----------------------------
4300
4301    procedure Check_Fully_Conformant
4302      (New_Id  : Entity_Id;
4303       Old_Id  : Entity_Id;
4304       Err_Loc : Node_Id := Empty)
4305    is
4306       Result : Boolean;
4307       pragma Warnings (Off, Result);
4308    begin
4309       Check_Conformance
4310         (New_Id, Old_Id, Fully_Conformant, True, Result, Err_Loc);
4311    end Check_Fully_Conformant;
4312
4313    ---------------------------
4314    -- Check_Mode_Conformant --
4315    ---------------------------
4316
4317    procedure Check_Mode_Conformant
4318      (New_Id   : Entity_Id;
4319       Old_Id   : Entity_Id;
4320       Err_Loc  : Node_Id := Empty;
4321       Get_Inst : Boolean := False)
4322    is
4323       Result : Boolean;
4324       pragma Warnings (Off, Result);
4325    begin
4326       Check_Conformance
4327         (New_Id, Old_Id, Mode_Conformant, True, Result, Err_Loc, Get_Inst);
4328    end Check_Mode_Conformant;
4329
4330    --------------------------------
4331    -- Check_Overriding_Indicator --
4332    --------------------------------
4333
4334    procedure Check_Overriding_Indicator
4335      (Subp            : Entity_Id;
4336       Overridden_Subp : Entity_Id;
4337       Is_Primitive    : Boolean)
4338    is
4339       Decl : Node_Id;
4340       Spec : Node_Id;
4341
4342    begin
4343       --  No overriding indicator for literals
4344
4345       if Ekind (Subp) = E_Enumeration_Literal then
4346          return;
4347
4348       elsif Ekind (Subp) = E_Entry then
4349          Decl := Parent (Subp);
4350
4351       else
4352          Decl := Unit_Declaration_Node (Subp);
4353       end if;
4354
4355       if Nkind_In (Decl, N_Subprogram_Body,
4356                          N_Subprogram_Body_Stub,
4357                          N_Subprogram_Declaration,
4358                          N_Abstract_Subprogram_Declaration,
4359                          N_Subprogram_Renaming_Declaration)
4360       then
4361          Spec := Specification (Decl);
4362
4363       elsif Nkind (Decl) = N_Entry_Declaration then
4364          Spec := Decl;
4365
4366       else
4367          return;
4368       end if;
4369
4370       if Present (Overridden_Subp) then
4371          if Must_Not_Override (Spec) then
4372             Error_Msg_Sloc := Sloc (Overridden_Subp);
4373
4374             if Ekind (Subp) = E_Entry then
4375                Error_Msg_NE
4376                  ("entry & overrides inherited operation #", Spec, Subp);
4377             else
4378                Error_Msg_NE
4379                  ("subprogram & overrides inherited operation #", Spec, Subp);
4380             end if;
4381
4382          elsif Is_Subprogram (Subp) then
4383             Set_Is_Overriding_Operation (Subp);
4384          end if;
4385
4386          --  If primitive flag is set or this is a protected operation, then
4387          --  the operation is overriding at the point of its declaration, so
4388          --  warn if necessary. Otherwise it may have been declared before the
4389          --  operation it overrides and no check is required.
4390
4391          if Style_Check
4392            and then not Must_Override (Spec)
4393            and then (Is_Primitive
4394                       or else Ekind (Scope (Subp)) = E_Protected_Type)
4395          then
4396             Style.Missing_Overriding (Decl, Subp);
4397          end if;
4398
4399       --  If Subp is an operator, it may override a predefined operation.
4400       --  In that case overridden_subp is empty because of our implicit
4401       --  representation for predefined operators. We have to check whether the
4402       --  signature of Subp matches that of a predefined operator. Note that
4403       --  first argument provides the name of the operator, and the second
4404       --  argument the signature that may match that of a standard operation.
4405       --  If the indicator is overriding, then the operator must match a
4406       --  predefined signature, because we know already that there is no
4407       --  explicit overridden operation.
4408
4409       elsif Nkind (Subp) = N_Defining_Operator_Symbol then
4410
4411          if Must_Not_Override (Spec) then
4412
4413             --  If this is not a primitive operation or protected subprogram,
4414             --  then "not overriding" is illegal.
4415
4416             if not Is_Primitive
4417               and then Ekind (Scope (Subp)) /= E_Protected_Type
4418             then
4419                Error_Msg_N
4420                  ("overriding indicator only allowed "
4421                     & "if subprogram is primitive", Subp);
4422
4423             elsif Operator_Matches_Spec (Subp, Subp) then
4424                Error_Msg_NE
4425                  ("subprogram & overrides predefined operator ", Spec, Subp);
4426             end if;
4427
4428          elsif Must_Override (Spec) then
4429             if Is_Overriding_Operation (Subp) then
4430                Set_Is_Overriding_Operation (Subp);
4431
4432             elsif not Operator_Matches_Spec (Subp, Subp) then
4433                Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
4434             end if;
4435
4436          elsif not Error_Posted (Subp)
4437            and then Style_Check
4438            and then Operator_Matches_Spec (Subp, Subp)
4439              and then
4440                not Is_Predefined_File_Name
4441                  (Unit_File_Name (Get_Source_Unit (Subp)))
4442          then
4443             Set_Is_Overriding_Operation (Subp);
4444
4445             --  If style checks are enabled, indicate that the indicator is
4446             --  missing. However, at the point of declaration, the type of
4447             --  which this is a primitive operation may be private, in which
4448             --  case the indicator would be premature.
4449
4450             if Has_Private_Declaration (Etype (Subp))
4451               or else Has_Private_Declaration (Etype (First_Formal (Subp)))
4452             then
4453                null;
4454             else
4455                Style.Missing_Overriding (Decl, Subp);
4456             end if;
4457          end if;
4458
4459       elsif Must_Override (Spec) then
4460          if Ekind (Subp) = E_Entry then
4461             Error_Msg_NE ("entry & is not overriding", Spec, Subp);
4462          else
4463             Error_Msg_NE ("subprogram & is not overriding", Spec, Subp);
4464          end if;
4465
4466       --  If the operation is marked "not overriding" and it's not primitive
4467       --  then an error is issued, unless this is an operation of a task or
4468       --  protected type (RM05-8.3.1(3/2-4/2)). Error cases where "overriding"
4469       --  has been specified have already been checked above.
4470
4471       elsif Must_Not_Override (Spec)
4472         and then not Is_Primitive
4473         and then Ekind (Subp) /= E_Entry
4474         and then Ekind (Scope (Subp)) /= E_Protected_Type
4475       then
4476          Error_Msg_N
4477            ("overriding indicator only allowed if subprogram is primitive",
4478             Subp);
4479          return;
4480       end if;
4481    end Check_Overriding_Indicator;
4482
4483    -------------------
4484    -- Check_Returns --
4485    -------------------
4486
4487    --  Note: this procedure needs to know far too much about how the expander
4488    --  messes with exceptions. The use of the flag Exception_Junk and the
4489    --  incorporation of knowledge of Exp_Ch11.Expand_Local_Exception_Handlers
4490    --  works, but is not very clean. It would be better if the expansion
4491    --  routines would leave Original_Node working nicely, and we could use
4492    --  Original_Node here to ignore all the peculiar expander messing ???
4493
4494    procedure Check_Returns
4495      (HSS  : Node_Id;
4496       Mode : Character;
4497       Err  : out Boolean;
4498       Proc : Entity_Id := Empty)
4499    is
4500       Handler : Node_Id;
4501
4502       procedure Check_Statement_Sequence (L : List_Id);
4503       --  Internal recursive procedure to check a list of statements for proper
4504       --  termination by a return statement (or a transfer of control or a
4505       --  compound statement that is itself internally properly terminated).
4506
4507       ------------------------------
4508       -- Check_Statement_Sequence --
4509       ------------------------------
4510
4511       procedure Check_Statement_Sequence (L : List_Id) is
4512          Last_Stm : Node_Id;
4513          Stm      : Node_Id;
4514          Kind     : Node_Kind;
4515
4516          Raise_Exception_Call : Boolean;
4517          --  Set True if statement sequence terminated by Raise_Exception call
4518          --  or a Reraise_Occurrence call.
4519
4520       begin
4521          Raise_Exception_Call := False;
4522
4523          --  Get last real statement
4524
4525          Last_Stm := Last (L);
4526
4527          --  Deal with digging out exception handler statement sequences that
4528          --  have been transformed by the local raise to goto optimization.
4529          --  See Exp_Ch11.Expand_Local_Exception_Handlers for details. If this
4530          --  optimization has occurred, we are looking at something like:
4531
4532          --  begin
4533          --     original stmts in block
4534
4535          --  exception            \
4536          --     when excep1 =>     |
4537          --        goto L1;        | omitted if No_Exception_Propagation
4538          --     when excep2 =>     |
4539          --        goto L2;       /
4540          --  end;
4541
4542          --  goto L3;      -- skip handler when exception not raised
4543
4544          --  <<L1>>        -- target label for local exception
4545          --     begin
4546          --        estmts1
4547          --     end;
4548
4549          --     goto L3;
4550
4551          --  <<L2>>
4552          --     begin
4553          --        estmts2
4554          --     end;
4555
4556          --  <<L3>>
4557
4558          --  and what we have to do is to dig out the estmts1 and estmts2
4559          --  sequences (which were the original sequences of statements in
4560          --  the exception handlers) and check them.
4561
4562          if Nkind (Last_Stm) = N_Label
4563            and then Exception_Junk (Last_Stm)
4564          then
4565             Stm := Last_Stm;
4566             loop
4567                Prev (Stm);
4568                exit when No (Stm);
4569                exit when Nkind (Stm) /= N_Block_Statement;
4570                exit when not Exception_Junk (Stm);
4571                Prev (Stm);
4572                exit when No (Stm);
4573                exit when Nkind (Stm) /= N_Label;
4574                exit when not Exception_Junk (Stm);
4575                Check_Statement_Sequence
4576                  (Statements (Handled_Statement_Sequence (Next (Stm))));
4577
4578                Prev (Stm);
4579                Last_Stm := Stm;
4580                exit when No (Stm);
4581                exit when Nkind (Stm) /= N_Goto_Statement;
4582                exit when not Exception_Junk (Stm);
4583             end loop;
4584          end if;
4585
4586          --  Don't count pragmas
4587
4588          while Nkind (Last_Stm) = N_Pragma
4589
4590          --  Don't count call to SS_Release (can happen after Raise_Exception)
4591
4592            or else
4593              (Nkind (Last_Stm) = N_Procedure_Call_Statement
4594                 and then
4595               Nkind (Name (Last_Stm)) = N_Identifier
4596                 and then
4597               Is_RTE (Entity (Name (Last_Stm)), RE_SS_Release))
4598
4599          --  Don't count exception junk
4600
4601            or else
4602              (Nkind_In (Last_Stm, N_Goto_Statement,
4603                                    N_Label,
4604                                    N_Object_Declaration)
4605                 and then Exception_Junk (Last_Stm))
4606            or else Nkind (Last_Stm) in N_Push_xxx_Label
4607            or else Nkind (Last_Stm) in N_Pop_xxx_Label
4608          loop
4609             Prev (Last_Stm);
4610          end loop;
4611
4612          --  Here we have the "real" last statement
4613
4614          Kind := Nkind (Last_Stm);
4615
4616          --  Transfer of control, OK. Note that in the No_Return procedure
4617          --  case, we already diagnosed any explicit return statements, so
4618          --  we can treat them as OK in this context.
4619
4620          if Is_Transfer (Last_Stm) then
4621             return;
4622
4623          --  Check cases of explicit non-indirect procedure calls
4624
4625          elsif Kind = N_Procedure_Call_Statement
4626            and then Is_Entity_Name (Name (Last_Stm))
4627          then
4628             --  Check call to Raise_Exception procedure which is treated
4629             --  specially, as is a call to Reraise_Occurrence.
4630
4631             --  We suppress the warning in these cases since it is likely that
4632             --  the programmer really does not expect to deal with the case
4633             --  of Null_Occurrence, and thus would find a warning about a
4634             --  missing return curious, and raising Program_Error does not
4635             --  seem such a bad behavior if this does occur.
4636
4637             --  Note that in the Ada 2005 case for Raise_Exception, the actual
4638             --  behavior will be to raise Constraint_Error (see AI-329).
4639
4640             if Is_RTE (Entity (Name (Last_Stm)), RE_Raise_Exception)
4641                  or else
4642                Is_RTE (Entity (Name (Last_Stm)), RE_Reraise_Occurrence)
4643             then
4644                Raise_Exception_Call := True;
4645
4646                --  For Raise_Exception call, test first argument, if it is
4647                --  an attribute reference for a 'Identity call, then we know
4648                --  that the call cannot possibly return.
4649
4650                declare
4651                   Arg : constant Node_Id :=
4652                           Original_Node (First_Actual (Last_Stm));
4653                begin
4654                   if Nkind (Arg) = N_Attribute_Reference
4655                     and then Attribute_Name (Arg) = Name_Identity
4656                   then
4657                      return;
4658                   end if;
4659                end;
4660             end if;
4661
4662          --  If statement, need to look inside if there is an else and check
4663          --  each constituent statement sequence for proper termination.
4664
4665          elsif Kind = N_If_Statement
4666            and then Present (Else_Statements (Last_Stm))
4667          then
4668             Check_Statement_Sequence (Then_Statements (Last_Stm));
4669             Check_Statement_Sequence (Else_Statements (Last_Stm));
4670
4671             if Present (Elsif_Parts (Last_Stm)) then
4672                declare
4673                   Elsif_Part : Node_Id := First (Elsif_Parts (Last_Stm));
4674
4675                begin
4676                   while Present (Elsif_Part) loop
4677                      Check_Statement_Sequence (Then_Statements (Elsif_Part));
4678                      Next (Elsif_Part);
4679                   end loop;
4680                end;
4681             end if;
4682
4683             return;
4684
4685          --  Case statement, check each case for proper termination
4686
4687          elsif Kind = N_Case_Statement then
4688             declare
4689                Case_Alt : Node_Id;
4690             begin
4691                Case_Alt := First_Non_Pragma (Alternatives (Last_Stm));
4692                while Present (Case_Alt) loop
4693                   Check_Statement_Sequence (Statements (Case_Alt));
4694                   Next_Non_Pragma (Case_Alt);
4695                end loop;
4696             end;
4697
4698             return;
4699
4700          --  Block statement, check its handled sequence of statements
4701
4702          elsif Kind = N_Block_Statement then
4703             declare
4704                Err1 : Boolean;
4705
4706             begin
4707                Check_Returns
4708                  (Handled_Statement_Sequence (Last_Stm), Mode, Err1);
4709
4710                if Err1 then
4711                   Err := True;
4712                end if;
4713
4714                return;
4715             end;
4716
4717          --  Loop statement. If there is an iteration scheme, we can definitely
4718          --  fall out of the loop. Similarly if there is an exit statement, we
4719          --  can fall out. In either case we need a following return.
4720
4721          elsif Kind = N_Loop_Statement then
4722             if Present (Iteration_Scheme (Last_Stm))
4723               or else Has_Exit (Entity (Identifier (Last_Stm)))
4724             then
4725                null;
4726
4727             --  A loop with no exit statement or iteration scheme is either
4728             --  an infinite loop, or it has some other exit (raise/return).
4729             --  In either case, no warning is required.
4730
4731             else
4732                return;
4733             end if;
4734
4735          --  Timed entry call, check entry call and delay alternatives
4736
4737          --  Note: in expanded code, the timed entry call has been converted
4738          --  to a set of expanded statements on which the check will work
4739          --  correctly in any case.
4740
4741          elsif Kind = N_Timed_Entry_Call then
4742             declare
4743                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
4744                DCA : constant Node_Id := Delay_Alternative      (Last_Stm);
4745
4746             begin
4747                --  If statement sequence of entry call alternative is missing,
4748                --  then we can definitely fall through, and we post the error
4749                --  message on the entry call alternative itself.
4750
4751                if No (Statements (ECA)) then
4752                   Last_Stm := ECA;
4753
4754                --  If statement sequence of delay alternative is missing, then
4755                --  we can definitely fall through, and we post the error
4756                --  message on the delay alternative itself.
4757
4758                --  Note: if both ECA and DCA are missing the return, then we
4759                --  post only one message, should be enough to fix the bugs.
4760                --  If not we will get a message next time on the DCA when the
4761                --  ECA is fixed!
4762
4763                elsif No (Statements (DCA)) then
4764                   Last_Stm := DCA;
4765
4766                --  Else check both statement sequences
4767
4768                else
4769                   Check_Statement_Sequence (Statements (ECA));
4770                   Check_Statement_Sequence (Statements (DCA));
4771                   return;
4772                end if;
4773             end;
4774
4775          --  Conditional entry call, check entry call and else part
4776
4777          --  Note: in expanded code, the conditional entry call has been
4778          --  converted to a set of expanded statements on which the check
4779          --  will work correctly in any case.
4780
4781          elsif Kind = N_Conditional_Entry_Call then
4782             declare
4783                ECA : constant Node_Id := Entry_Call_Alternative (Last_Stm);
4784
4785             begin
4786                --  If statement sequence of entry call alternative is missing,
4787                --  then we can definitely fall through, and we post the error
4788                --  message on the entry call alternative itself.
4789
4790                if No (Statements (ECA)) then
4791                   Last_Stm := ECA;
4792
4793                --  Else check statement sequence and else part
4794
4795                else
4796                   Check_Statement_Sequence (Statements (ECA));
4797                   Check_Statement_Sequence (Else_Statements (Last_Stm));
4798                   return;
4799                end if;
4800             end;
4801          end if;
4802
4803          --  If we fall through, issue appropriate message
4804
4805          if Mode = 'F' then
4806             if not Raise_Exception_Call then
4807                Error_Msg_N
4808                  ("?RETURN statement missing following this statement!",
4809                   Last_Stm);
4810                Error_Msg_N
4811                  ("\?Program_Error may be raised at run time!",
4812                   Last_Stm);
4813             end if;
4814
4815             --  Note: we set Err even though we have not issued a warning
4816             --  because we still have a case of a missing return. This is
4817             --  an extremely marginal case, probably will never be noticed
4818             --  but we might as well get it right.
4819
4820             Err := True;
4821
4822          --  Otherwise we have the case of a procedure marked No_Return
4823
4824          else
4825             if not Raise_Exception_Call then
4826                Error_Msg_N
4827                  ("?implied return after this statement " &
4828                   "will raise Program_Error",
4829                   Last_Stm);
4830                Error_Msg_NE
4831                  ("\?procedure & is marked as No_Return!",
4832                   Last_Stm, Proc);
4833             end if;
4834
4835             declare
4836                RE : constant Node_Id :=
4837                       Make_Raise_Program_Error (Sloc (Last_Stm),
4838                         Reason => PE_Implicit_Return);
4839             begin
4840                Insert_After (Last_Stm, RE);
4841                Analyze (RE);
4842             end;
4843          end if;
4844       end Check_Statement_Sequence;
4845
4846    --  Start of processing for Check_Returns
4847
4848    begin
4849       Err := False;
4850       Check_Statement_Sequence (Statements (HSS));
4851
4852       if Present (Exception_Handlers (HSS)) then
4853          Handler := First_Non_Pragma (Exception_Handlers (HSS));
4854          while Present (Handler) loop
4855             Check_Statement_Sequence (Statements (Handler));
4856             Next_Non_Pragma (Handler);
4857          end loop;
4858       end if;
4859    end Check_Returns;
4860
4861    ----------------------------
4862    -- Check_Subprogram_Order --
4863    ----------------------------
4864
4865    procedure Check_Subprogram_Order (N : Node_Id) is
4866
4867       function Subprogram_Name_Greater (S1, S2 : String) return Boolean;
4868       --  This is used to check if S1 > S2 in the sense required by this
4869       --  test, for example nameab < namec, but name2 < name10.
4870
4871       -----------------------------
4872       -- Subprogram_Name_Greater --
4873       -----------------------------
4874
4875       function Subprogram_Name_Greater (S1, S2 : String) return Boolean is
4876          L1, L2 : Positive;
4877          N1, N2 : Natural;
4878
4879       begin
4880          --  Remove trailing numeric parts
4881
4882          L1 := S1'Last;
4883          while S1 (L1) in '0' .. '9' loop
4884             L1 := L1 - 1;
4885          end loop;
4886
4887          L2 := S2'Last;
4888          while S2 (L2) in '0' .. '9' loop
4889             L2 := L2 - 1;
4890          end loop;
4891
4892          --  If non-numeric parts non-equal, that's decisive
4893
4894          if S1 (S1'First .. L1) < S2 (S2'First .. L2) then
4895             return False;
4896
4897          elsif S1 (S1'First .. L1) > S2 (S2'First .. L2) then
4898             return True;
4899
4900          --  If non-numeric parts equal, compare suffixed numeric parts. Note
4901          --  that a missing suffix is treated as numeric zero in this test.
4902
4903          else
4904             N1 := 0;
4905             while L1 < S1'Last loop
4906                L1 := L1 + 1;
4907                N1 := N1 * 10 + Character'Pos (S1 (L1)) - Character'Pos ('0');
4908             end loop;
4909
4910             N2 := 0;
4911             while L2 < S2'Last loop
4912                L2 := L2 + 1;
4913                N2 := N2 * 10 + Character'Pos (S2 (L2)) - Character'Pos ('0');
4914             end loop;
4915
4916             return N1 > N2;
4917          end if;
4918       end Subprogram_Name_Greater;
4919
4920    --  Start of processing for Check_Subprogram_Order
4921
4922    begin
4923       --  Check body in alpha order if this is option
4924
4925       if Style_Check
4926         and then Style_Check_Order_Subprograms
4927         and then Nkind (N) = N_Subprogram_Body
4928         and then Comes_From_Source (N)
4929         and then In_Extended_Main_Source_Unit (N)
4930       then
4931          declare
4932             LSN : String_Ptr
4933                     renames Scope_Stack.Table
4934                               (Scope_Stack.Last).Last_Subprogram_Name;
4935
4936             Body_Id : constant Entity_Id :=
4937                         Defining_Entity (Specification (N));
4938
4939          begin
4940             Get_Decoded_Name_String (Chars (Body_Id));
4941
4942             if LSN /= null then
4943                if Subprogram_Name_Greater
4944                     (LSN.all, Name_Buffer (1 .. Name_Len))
4945                then
4946                   Style.Subprogram_Not_In_Alpha_Order (Body_Id);
4947                end if;
4948
4949                Free (LSN);
4950             end if;
4951
4952             LSN := new String'(Name_Buffer (1 .. Name_Len));
4953          end;
4954       end if;
4955    end Check_Subprogram_Order;
4956
4957    ------------------------------
4958    -- Check_Subtype_Conformant --
4959    ------------------------------
4960
4961    procedure Check_Subtype_Conformant
4962      (New_Id                   : Entity_Id;
4963       Old_Id                   : Entity_Id;
4964       Err_Loc                  : Node_Id := Empty;
4965       Skip_Controlling_Formals : Boolean := False)
4966    is
4967       Result : Boolean;
4968       pragma Warnings (Off, Result);
4969    begin
4970       Check_Conformance
4971         (New_Id, Old_Id, Subtype_Conformant, True, Result, Err_Loc,
4972          Skip_Controlling_Formals => Skip_Controlling_Formals);
4973    end Check_Subtype_Conformant;
4974
4975    ---------------------------
4976    -- Check_Type_Conformant --
4977    ---------------------------
4978
4979    procedure Check_Type_Conformant
4980      (New_Id  : Entity_Id;
4981       Old_Id  : Entity_Id;
4982       Err_Loc : Node_Id := Empty)
4983    is
4984       Result : Boolean;
4985       pragma Warnings (Off, Result);
4986    begin
4987       Check_Conformance
4988         (New_Id, Old_Id, Type_Conformant, True, Result, Err_Loc);
4989    end Check_Type_Conformant;
4990
4991    ----------------------
4992    -- Conforming_Types --
4993    ----------------------
4994
4995    function Conforming_Types
4996      (T1       : Entity_Id;
4997       T2       : Entity_Id;
4998       Ctype    : Conformance_Type;
4999       Get_Inst : Boolean := False) return Boolean
5000    is
5001       Type_1 : Entity_Id := T1;
5002       Type_2 : Entity_Id := T2;
5003       Are_Anonymous_Access_To_Subprogram_Types : Boolean := False;
5004
5005       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean;
5006       --  If neither T1 nor T2 are generic actual types, or if they are in
5007       --  different scopes (e.g. parent and child instances), then verify that
5008       --  the base types are equal. Otherwise T1 and T2 must be on the same
5009       --  subtype chain. The whole purpose of this procedure is to prevent
5010       --  spurious ambiguities in an instantiation that may arise if two
5011       --  distinct generic types are instantiated with the same actual.
5012
5013       function Find_Designated_Type (T : Entity_Id) return Entity_Id;
5014       --  An access parameter can designate an incomplete type. If the
5015       --  incomplete type is the limited view of a type from a limited_
5016       --  with_clause, check whether the non-limited view is available. If
5017       --  it is a (non-limited) incomplete type, get the full view.
5018
5019       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean;
5020       --  Returns True if and only if either T1 denotes a limited view of T2
5021       --  or T2 denotes a limited view of T1. This can arise when the limited
5022       --  with view of a type is used in a subprogram declaration and the
5023       --  subprogram body is in the scope of a regular with clause for the
5024       --  same unit. In such a case, the two type entities can be considered
5025       --  identical for purposes of conformance checking.
5026
5027       ----------------------
5028       -- Base_Types_Match --
5029       ----------------------
5030
5031       function Base_Types_Match (T1, T2 : Entity_Id) return Boolean is
5032       begin
5033          if T1 = T2 then
5034             return True;
5035
5036          elsif Base_Type (T1) = Base_Type (T2) then
5037
5038             --  The following is too permissive. A more precise test should
5039             --  check that the generic actual is an ancestor subtype of the
5040             --  other ???.
5041
5042             return not Is_Generic_Actual_Type (T1)
5043               or else not Is_Generic_Actual_Type (T2)
5044               or else Scope (T1) /= Scope (T2);
5045
5046          else
5047             return False;
5048          end if;
5049       end Base_Types_Match;
5050
5051       --------------------------
5052       -- Find_Designated_Type --
5053       --------------------------
5054
5055       function Find_Designated_Type (T : Entity_Id) return Entity_Id is
5056          Desig : Entity_Id;
5057
5058       begin
5059          Desig := Directly_Designated_Type (T);
5060
5061          if Ekind (Desig) = E_Incomplete_Type then
5062
5063             --  If regular incomplete type, get full view if available
5064
5065             if Present (Full_View (Desig)) then
5066                Desig := Full_View (Desig);
5067
5068             --  If limited view of a type, get non-limited view if available,
5069             --  and check again for a regular incomplete type.
5070
5071             elsif Present (Non_Limited_View (Desig)) then
5072                Desig := Get_Full_View (Non_Limited_View (Desig));
5073             end if;
5074          end if;
5075
5076          return Desig;
5077       end Find_Designated_Type;
5078
5079       -------------------------------
5080       -- Matches_Limited_With_View --
5081       -------------------------------
5082
5083       function Matches_Limited_With_View (T1, T2 : Entity_Id) return Boolean is
5084       begin
5085          --  In some cases a type imported through a limited_with clause, and
5086          --  its nonlimited view are both visible, for example in an anonymous
5087          --  access-to-class-wide type in a formal. Both entities designate the
5088          --  same type.
5089
5090          if From_With_Type (T1)
5091            and then T2 = Available_View (T1)
5092          then
5093             return True;
5094
5095          elsif From_With_Type (T2)
5096            and then T1 = Available_View (T2)
5097          then
5098             return True;
5099
5100          else
5101             return False;
5102          end if;
5103       end Matches_Limited_With_View;
5104
5105    --  Start of processing for Conforming_Types
5106
5107    begin
5108       --  The context is an instance association for a formal
5109       --  access-to-subprogram type; the formal parameter types require
5110       --  mapping because they may denote other formal parameters of the
5111       --  generic unit.
5112
5113       if Get_Inst then
5114          Type_1 := Get_Instance_Of (T1);
5115          Type_2 := Get_Instance_Of (T2);
5116       end if;
5117
5118       --  If one of the types is a view of the other introduced by a limited
5119       --  with clause, treat these as conforming for all purposes.
5120
5121       if Matches_Limited_With_View (T1, T2) then
5122          return True;
5123
5124       elsif Base_Types_Match (Type_1, Type_2) then
5125          return Ctype <= Mode_Conformant
5126            or else Subtypes_Statically_Match (Type_1, Type_2);
5127
5128       elsif Is_Incomplete_Or_Private_Type (Type_1)
5129         and then Present (Full_View (Type_1))
5130         and then Base_Types_Match (Full_View (Type_1), Type_2)
5131       then
5132          return Ctype <= Mode_Conformant
5133            or else Subtypes_Statically_Match (Full_View (Type_1), Type_2);
5134
5135       elsif Ekind (Type_2) = E_Incomplete_Type
5136         and then Present (Full_View (Type_2))
5137         and then Base_Types_Match (Type_1, Full_View (Type_2))
5138       then
5139          return Ctype <= Mode_Conformant
5140            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
5141
5142       elsif Is_Private_Type (Type_2)
5143         and then In_Instance
5144         and then Present (Full_View (Type_2))
5145         and then Base_Types_Match (Type_1, Full_View (Type_2))
5146       then
5147          return Ctype <= Mode_Conformant
5148            or else Subtypes_Statically_Match (Type_1, Full_View (Type_2));
5149       end if;
5150
5151       --  Ada 2005 (AI-254): Anonymous access-to-subprogram types must be
5152       --  treated recursively because they carry a signature.
5153
5154       Are_Anonymous_Access_To_Subprogram_Types :=
5155         Ekind (Type_1) = Ekind (Type_2)
5156           and then
5157             (Ekind (Type_1) = E_Anonymous_Access_Subprogram_Type
5158              or else
5159                Ekind (Type_1) = E_Anonymous_Access_Protected_Subprogram_Type);
5160
5161       --  Test anonymous access type case. For this case, static subtype
5162       --  matching is required for mode conformance (RM 6.3.1(15)). We check
5163       --  the base types because we may have built internal subtype entities
5164       --  to handle null-excluding types (see Process_Formals).
5165
5166       if (Ekind (Base_Type (Type_1)) = E_Anonymous_Access_Type
5167             and then
5168           Ekind (Base_Type (Type_2)) = E_Anonymous_Access_Type)
5169         or else Are_Anonymous_Access_To_Subprogram_Types -- Ada 2005 (AI-254)
5170       then
5171          declare
5172             Desig_1 : Entity_Id;
5173             Desig_2 : Entity_Id;
5174
5175          begin
5176             --  In Ada2005, access constant indicators must match for
5177             --  subtype conformance.
5178
5179             if Ada_Version >= Ada_05
5180               and then Ctype >= Subtype_Conformant
5181               and then
5182                 Is_Access_Constant (Type_1) /= Is_Access_Constant (Type_2)
5183             then
5184                return False;
5185             end if;
5186
5187             Desig_1 := Find_Designated_Type (Type_1);
5188
5189             Desig_2 := Find_Designated_Type (Type_2);
5190
5191             --  If the context is an instance association for a formal
5192             --  access-to-subprogram type; formal access parameter designated
5193             --  types require mapping because they may denote other formal
5194             --  parameters of the generic unit.
5195
5196             if Get_Inst then
5197                Desig_1 := Get_Instance_Of (Desig_1);
5198                Desig_2 := Get_Instance_Of (Desig_2);
5199             end if;
5200
5201             --  It is possible for a Class_Wide_Type to be introduced for an
5202             --  incomplete type, in which case there is a separate class_ wide
5203             --  type for the full view. The types conform if their Etypes
5204             --  conform, i.e. one may be the full view of the other. This can
5205             --  only happen in the context of an access parameter, other uses
5206             --  of an incomplete Class_Wide_Type are illegal.
5207
5208             if Is_Class_Wide_Type (Desig_1)
5209               and then Is_Class_Wide_Type (Desig_2)
5210             then
5211                return
5212                  Conforming_Types
5213                    (Etype (Base_Type (Desig_1)),
5214                     Etype (Base_Type (Desig_2)), Ctype);
5215
5216             elsif Are_Anonymous_Access_To_Subprogram_Types then
5217                if Ada_Version < Ada_05 then
5218                   return Ctype = Type_Conformant
5219                     or else
5220                       Subtypes_Statically_Match (Desig_1, Desig_2);
5221
5222                --  We must check the conformance of the signatures themselves
5223
5224                else
5225                   declare
5226                      Conformant : Boolean;
5227                   begin
5228                      Check_Conformance
5229                        (Desig_1, Desig_2, Ctype, False, Conformant);
5230                      return Conformant;
5231                   end;
5232                end if;
5233
5234             else
5235                return Base_Type (Desig_1) = Base_Type (Desig_2)
5236                 and then (Ctype = Type_Conformant
5237                             or else
5238                           Subtypes_Statically_Match (Desig_1, Desig_2));
5239             end if;
5240          end;
5241
5242       --  Otherwise definitely no match
5243
5244       else
5245          if ((Ekind (Type_1) = E_Anonymous_Access_Type
5246                and then Is_Access_Type (Type_2))
5247             or else (Ekind (Type_2) = E_Anonymous_Access_Type
5248                        and then Is_Access_Type (Type_1)))
5249            and then
5250              Conforming_Types
5251                (Designated_Type (Type_1), Designated_Type (Type_2), Ctype)
5252          then
5253             May_Hide_Profile := True;
5254          end if;
5255
5256          return False;
5257       end if;
5258    end Conforming_Types;
5259
5260    --------------------------
5261    -- Create_Extra_Formals --
5262    --------------------------
5263
5264    procedure Create_Extra_Formals (E : Entity_Id) is
5265       Formal      : Entity_Id;
5266       First_Extra : Entity_Id := Empty;
5267       Last_Extra  : Entity_Id;
5268       Formal_Type : Entity_Id;
5269       P_Formal    : Entity_Id := Empty;
5270
5271       function Add_Extra_Formal
5272         (Assoc_Entity : Entity_Id;
5273          Typ          : Entity_Id;
5274          Scope        : Entity_Id;
5275          Suffix       : String) return Entity_Id;
5276       --  Add an extra formal to the current list of formals and extra formals.
5277       --  The extra formal is added to the end of the list of extra formals,
5278       --  and also returned as the result. These formals are always of mode IN.
5279       --  The new formal has the type Typ, is declared in Scope, and its name
5280       --  is given by a concatenation of the name of Assoc_Entity and Suffix.
5281
5282       ----------------------
5283       -- Add_Extra_Formal --
5284       ----------------------
5285
5286       function Add_Extra_Formal
5287         (Assoc_Entity : Entity_Id;
5288          Typ          : Entity_Id;
5289          Scope        : Entity_Id;
5290          Suffix       : String) return Entity_Id
5291       is
5292          EF : constant Entity_Id :=
5293                 Make_Defining_Identifier (Sloc (Assoc_Entity),
5294                   Chars  => New_External_Name (Chars (Assoc_Entity),
5295                                                Suffix => Suffix));
5296
5297       begin
5298          --  A little optimization. Never generate an extra formal for the
5299          --  _init operand of an initialization procedure, since it could
5300          --  never be used.
5301
5302          if Chars (Formal) = Name_uInit then
5303             return Empty;
5304          end if;
5305
5306          Set_Ekind           (EF, E_In_Parameter);
5307          Set_Actual_Subtype  (EF, Typ);
5308          Set_Etype           (EF, Typ);
5309          Set_Scope           (EF, Scope);
5310          Set_Mechanism       (EF, Default_Mechanism);
5311          Set_Formal_Validity (EF);
5312
5313          if No (First_Extra) then
5314             First_Extra := EF;
5315             Set_Extra_Formals (Scope, First_Extra);
5316          end if;
5317
5318          if Present (Last_Extra) then
5319             Set_Extra_Formal (Last_Extra, EF);
5320          end if;
5321
5322          Last_Extra := EF;
5323
5324          return EF;
5325       end Add_Extra_Formal;
5326
5327    --  Start of processing for Create_Extra_Formals
5328
5329    begin
5330       --  We never generate extra formals if expansion is not active
5331       --  because we don't need them unless we are generating code.
5332
5333       if not Expander_Active then
5334          return;
5335       end if;
5336
5337       --  If this is a derived subprogram then the subtypes of the parent
5338       --  subprogram's formal parameters will be used to determine the need
5339       --  for extra formals.
5340
5341       if Is_Overloadable (E) and then Present (Alias (E)) then
5342          P_Formal := First_Formal (Alias (E));
5343       end if;
5344
5345       Last_Extra := Empty;
5346       Formal := First_Formal (E);
5347       while Present (Formal) loop
5348          Last_Extra := Formal;
5349          Next_Formal (Formal);
5350       end loop;
5351
5352       --  If Extra_formals were already created, don't do it again. This
5353       --  situation may arise for subprogram types created as part of
5354       --  dispatching calls (see Expand_Dispatching_Call)
5355
5356       if Present (Last_Extra) and then
5357         Present (Extra_Formal (Last_Extra))
5358       then
5359          return;
5360       end if;
5361
5362       --  If the subprogram is a predefined dispatching subprogram then don't
5363       --  generate any extra constrained or accessibility level formals. In
5364       --  general we suppress these for internal subprograms (by not calling
5365       --  Freeze_Subprogram and Create_Extra_Formals at all), but internally
5366       --  generated stream attributes do get passed through because extra
5367       --  build-in-place formals are needed in some cases (limited 'Input).
5368
5369       if Is_Predefined_Dispatching_Operation (E) then
5370          goto Test_For_BIP_Extras;
5371       end if;
5372
5373       Formal := First_Formal (E);
5374       while Present (Formal) loop
5375
5376          --  Create extra formal for supporting the attribute 'Constrained.
5377          --  The case of a private type view without discriminants also
5378          --  requires the extra formal if the underlying type has defaulted
5379          --  discriminants.
5380
5381          if Ekind (Formal) /= E_In_Parameter then
5382             if Present (P_Formal) then
5383                Formal_Type := Etype (P_Formal);
5384             else
5385                Formal_Type := Etype (Formal);
5386             end if;
5387
5388             --  Do not produce extra formals for Unchecked_Union parameters.
5389             --  Jump directly to the end of the loop.
5390
5391             if Is_Unchecked_Union (Base_Type (Formal_Type)) then
5392                goto Skip_Extra_Formal_Generation;
5393             end if;
5394
5395             if not Has_Discriminants (Formal_Type)
5396               and then Ekind (Formal_Type) in Private_Kind
5397               and then Present (Underlying_Type (Formal_Type))
5398             then
5399                Formal_Type := Underlying_Type (Formal_Type);
5400             end if;
5401
5402             if Has_Discriminants (Formal_Type)
5403               and then not Is_Constrained (Formal_Type)
5404               and then not Is_Indefinite_Subtype (Formal_Type)
5405             then
5406                Set_Extra_Constrained
5407                  (Formal, Add_Extra_Formal (Formal, Standard_Boolean, E, "F"));
5408             end if;
5409          end if;
5410
5411          --  Create extra formal for supporting accessibility checking. This
5412          --  is done for both anonymous access formals and formals of named
5413          --  access types that are marked as controlling formals. The latter
5414          --  case can occur when Expand_Dispatching_Call creates a subprogram
5415          --  type and substitutes the types of access-to-class-wide actuals
5416          --  for the anonymous access-to-specific-type of controlling formals.
5417          --  Base_Type is applied because in cases where there is a null
5418          --  exclusion the formal may have an access subtype.
5419
5420          --  This is suppressed if we specifically suppress accessibility
5421          --  checks at the package level for either the subprogram, or the
5422          --  package in which it resides. However, we do not suppress it
5423          --  simply if the scope has accessibility checks suppressed, since
5424          --  this could cause trouble when clients are compiled with a
5425          --  different suppression setting. The explicit checks at the
5426          --  package level are safe from this point of view.
5427
5428          if (Ekind (Base_Type (Etype (Formal))) = E_Anonymous_Access_Type
5429               or else (Is_Controlling_Formal (Formal)
5430                         and then Is_Access_Type (Base_Type (Etype (Formal)))))
5431            and then not
5432              (Explicit_Suppress (E, Accessibility_Check)
5433                or else
5434               Explicit_Suppress (Scope (E), Accessibility_Check))
5435            and then
5436              (No (P_Formal)
5437                or else Present (Extra_Accessibility (P_Formal)))
5438          then
5439             --  Temporary kludge: for now we avoid creating the extra formal
5440             --  for access parameters of protected operations because of
5441             --  problem with the case of internal protected calls. ???
5442
5443             if Nkind (Parent (Parent (Parent (E)))) /= N_Protected_Definition
5444               and then Nkind (Parent (Parent (Parent (E)))) /= N_Protected_Body
5445             then
5446                Set_Extra_Accessibility
5447                  (Formal, Add_Extra_Formal (Formal, Standard_Natural, E, "F"));
5448             end if;
5449          end if;
5450
5451          --  This label is required when skipping extra formal generation for
5452          --  Unchecked_Union parameters.
5453
5454          <<Skip_Extra_Formal_Generation>>
5455
5456          if Present (P_Formal) then
5457             Next_Formal (P_Formal);
5458          end if;
5459
5460          Next_Formal (Formal);
5461       end loop;
5462
5463       <<Test_For_BIP_Extras>>
5464
5465       --  Ada 2005 (AI-318-02): In the case of build-in-place functions, add
5466       --  appropriate extra formals. See type Exp_Ch6.BIP_Formal_Kind.
5467
5468       if Ada_Version >= Ada_05 and then Is_Build_In_Place_Function (E) then
5469          declare
5470             Result_Subt : constant Entity_Id := Etype (E);
5471
5472             Discard : Entity_Id;
5473             pragma Warnings (Off, Discard);
5474
5475          begin
5476             --  In the case of functions with unconstrained result subtypes,
5477             --  add a 3-state formal indicating whether the return object is
5478             --  allocated by the caller (0), or should be allocated by the
5479             --  callee on the secondary stack (1) or in the global heap (2).
5480             --  For the moment we just use Natural for the type of this formal.
5481             --  Note that this formal isn't usually needed in the case where
5482             --  the result subtype is constrained, but it is needed when the
5483             --  function has a tagged result, because generally such functions
5484             --  can be called in a dispatching context and such calls must be
5485             --  handled like calls to a class-wide function.
5486
5487             if not Is_Constrained (Underlying_Type (Result_Subt))
5488               or else Is_Tagged_Type (Underlying_Type (Result_Subt))
5489             then
5490                Discard :=
5491                  Add_Extra_Formal
5492                    (E, Standard_Natural,
5493                     E, BIP_Formal_Suffix (BIP_Alloc_Form));
5494             end if;
5495
5496             --  In the case of functions whose result type has controlled
5497             --  parts, we have an extra formal of type
5498             --  System.Finalization_Implementation.Finalizable_Ptr_Ptr. That
5499             --  is, we are passing a pointer to a finalization list (which is
5500             --  itself a pointer). This extra formal is then passed along to
5501             --  Move_Final_List in case of successful completion of a return
5502             --  statement. We cannot pass an 'in out' parameter, because we
5503             --  need to update the finalization list during an abort-deferred
5504             --  region, rather than using copy-back after the function
5505             --  returns. This is true even if we are able to get away with
5506             --  having 'in out' parameters, which are normally illegal for
5507             --  functions. This formal is also needed when the function has
5508             --  a tagged result.
5509
5510             if Needs_BIP_Final_List (E) then
5511                Discard :=
5512                  Add_Extra_Formal
5513                    (E, RTE (RE_Finalizable_Ptr_Ptr),
5514                     E, BIP_Formal_Suffix (BIP_Final_List));
5515             end if;
5516
5517             --  If the result type contains tasks, we have two extra formals:
5518             --  the master of the tasks to be created, and the caller's
5519             --  activation chain.
5520
5521             if Has_Task (Result_Subt) then
5522                Discard :=
5523                  Add_Extra_Formal
5524                    (E, RTE (RE_Master_Id),
5525                     E, BIP_Formal_Suffix (BIP_Master));
5526                Discard :=
5527                  Add_Extra_Formal
5528                    (E, RTE (RE_Activation_Chain_Access),
5529                     E, BIP_Formal_Suffix (BIP_Activation_Chain));
5530             end if;
5531
5532             --  All build-in-place functions get an extra formal that will be
5533             --  passed the address of the return object within the caller.
5534
5535             declare
5536                Formal_Type : constant Entity_Id :=
5537                                Create_Itype
5538                                  (E_Anonymous_Access_Type, E,
5539                                   Scope_Id => Scope (E));
5540             begin
5541                Set_Directly_Designated_Type (Formal_Type, Result_Subt);
5542                Set_Etype (Formal_Type, Formal_Type);
5543                Set_Depends_On_Private
5544                  (Formal_Type, Has_Private_Component (Formal_Type));
5545                Set_Is_Public (Formal_Type, Is_Public (Scope (Formal_Type)));
5546                Set_Is_Access_Constant (Formal_Type, False);
5547
5548                --  Ada 2005 (AI-50217): Propagate the attribute that indicates
5549                --  the designated type comes from the limited view (for
5550                --  back-end purposes).
5551
5552                Set_From_With_Type (Formal_Type, From_With_Type (Result_Subt));
5553
5554                Layout_Type (Formal_Type);
5555
5556                Discard :=
5557                  Add_Extra_Formal
5558                    (E, Formal_Type, E, BIP_Formal_Suffix (BIP_Object_Access));
5559             end;
5560          end;
5561       end if;
5562    end Create_Extra_Formals;
5563
5564    -----------------------------
5565    -- Enter_Overloaded_Entity --
5566    -----------------------------
5567
5568    procedure Enter_Overloaded_Entity (S : Entity_Id) is
5569       E   : Entity_Id := Current_Entity_In_Scope (S);
5570       C_E : Entity_Id := Current_Entity (S);
5571
5572    begin
5573       if Present (E) then
5574          Set_Has_Homonym (E);
5575          Set_Has_Homonym (S);
5576       end if;
5577
5578       Set_Is_Immediately_Visible (S);
5579       Set_Scope (S, Current_Scope);
5580
5581       --  Chain new entity if front of homonym in current scope, so that
5582       --  homonyms are contiguous.
5583
5584       if Present (E)
5585         and then E /= C_E
5586       then
5587          while Homonym (C_E) /= E loop
5588             C_E := Homonym (C_E);
5589          end loop;
5590
5591          Set_Homonym (C_E, S);
5592
5593       else
5594          E := C_E;
5595          Set_Current_Entity (S);
5596       end if;
5597
5598       Set_Homonym (S, E);
5599
5600       Append_Entity (S, Current_Scope);
5601       Set_Public_Status (S);
5602
5603       if Debug_Flag_E then
5604          Write_Str ("New overloaded entity chain: ");
5605          Write_Name (Chars (S));
5606
5607          E := S;
5608          while Present (E) loop
5609             Write_Str (" "); Write_Int (Int (E));
5610             E := Homonym (E);
5611          end loop;
5612
5613          Write_Eol;
5614       end if;
5615
5616       --  Generate warning for hiding
5617
5618       if Warn_On_Hiding
5619         and then Comes_From_Source (S)
5620         and then In_Extended_Main_Source_Unit (S)
5621       then
5622          E := S;
5623          loop
5624             E := Homonym (E);
5625             exit when No (E);
5626
5627             --  Warn unless genuine overloading
5628
5629             if (not Is_Overloadable (E) or else Subtype_Conformant (E, S))
5630                   and then (Is_Immediately_Visible (E)
5631                               or else
5632                             Is_Potentially_Use_Visible (S))
5633             then
5634                Error_Msg_Sloc := Sloc (E);
5635                Error_Msg_N ("declaration of & hides one#?", S);
5636             end if;
5637          end loop;
5638       end if;
5639    end Enter_Overloaded_Entity;
5640
5641    -----------------------------
5642    -- Find_Corresponding_Spec --
5643    -----------------------------
5644
5645    function Find_Corresponding_Spec
5646      (N          : Node_Id;
5647       Post_Error : Boolean := True) return Entity_Id
5648    is
5649       Spec       : constant Node_Id   := Specification (N);
5650       Designator : constant Entity_Id := Defining_Entity (Spec);
5651
5652       E : Entity_Id;
5653
5654    begin
5655       E := Current_Entity (Designator);
5656       while Present (E) loop
5657
5658          --  We are looking for a matching spec. It must have the same scope,
5659          --  and the same name, and either be type conformant, or be the case
5660          --  of a library procedure spec and its body (which belong to one
5661          --  another regardless of whether they are type conformant or not).
5662
5663          if Scope (E) = Current_Scope then
5664             if Current_Scope = Standard_Standard
5665               or else (Ekind (E) = Ekind (Designator)
5666                          and then Type_Conformant (E, Designator))
5667             then
5668                --  Within an instantiation, we know that spec and body are
5669                --  subtype conformant, because they were subtype conformant
5670                --  in the generic. We choose the subtype-conformant entity
5671                --  here as well, to resolve spurious ambiguities in the
5672                --  instance that were not present in the generic (i.e. when
5673                --  two different types are given the same actual). If we are
5674                --  looking for a spec to match a body, full conformance is
5675                --  expected.
5676
5677                if In_Instance then
5678                   Set_Convention (Designator, Convention (E));
5679
5680                   if Nkind (N) = N_Subprogram_Body
5681                     and then Present (Homonym (E))
5682                     and then not Fully_Conformant (E, Designator)
5683                   then
5684                      goto Next_Entity;
5685
5686                   elsif not Subtype_Conformant (E, Designator) then
5687                      goto Next_Entity;
5688                   end if;
5689                end if;
5690
5691                if not Has_Completion (E) then
5692                   if Nkind (N) /= N_Subprogram_Body_Stub then
5693                      Set_Corresponding_Spec (N, E);
5694                   end if;
5695
5696                   Set_Has_Completion (E);
5697                   return E;
5698
5699                elsif Nkind (Parent (N)) = N_Subunit then
5700
5701                   --  If this is the proper body of a subunit, the completion
5702                   --  flag is set when analyzing the stub.
5703
5704                   return E;
5705
5706                --  If E is an internal function with a controlling result
5707                --  that was created for an operation inherited by a null
5708                --  extension, it may be overridden by a body without a previous
5709                --  spec (one more reason why these should be shunned). In that
5710                --  case remove the generated body, because the current one is
5711                --  the explicit overriding.
5712
5713                elsif Ekind (E) = E_Function
5714                  and then Ada_Version >= Ada_05
5715                  and then not Comes_From_Source (E)
5716                  and then Has_Controlling_Result (E)
5717                  and then Is_Null_Extension (Etype (E))
5718                  and then Comes_From_Source (Spec)
5719                then
5720                   Set_Has_Completion (E, False);
5721
5722                   if Expander_Active then
5723                      Remove
5724                        (Unit_Declaration_Node
5725                          (Corresponding_Body (Unit_Declaration_Node (E))));
5726                      return E;
5727
5728                   --  If expansion is disabled, the wrapper function has not
5729                   --  been generated, and this is the standard case of a late
5730                   --  body overriding an inherited operation.
5731
5732                   else
5733                      return Empty;
5734                   end if;
5735
5736                --  If the body already exists, then this is an error unless
5737                --  the previous declaration is the implicit declaration of a
5738                --  derived subprogram, or this is a spurious overloading in an
5739                --  instance.
5740
5741                elsif No (Alias (E))
5742                  and then not Is_Intrinsic_Subprogram (E)
5743                  and then not In_Instance
5744                  and then Post_Error
5745                then
5746                   Error_Msg_Sloc := Sloc (E);
5747
5748                   if Is_Imported (E) then
5749                      Error_Msg_NE
5750                       ("body not allowed for imported subprogram & declared#",
5751                         N, E);
5752                   else
5753                      Error_Msg_NE ("duplicate body for & declared#", N, E);
5754                   end if;
5755                end if;
5756
5757             --  Child units cannot be overloaded, so a conformance mismatch
5758             --  between body and a previous spec is an error.
5759
5760             elsif Is_Child_Unit (E)
5761               and then
5762                 Nkind (Unit_Declaration_Node (Designator)) = N_Subprogram_Body
5763               and then
5764                 Nkind (Parent (Unit_Declaration_Node (Designator))) =
5765                   N_Compilation_Unit
5766               and then Post_Error
5767             then
5768                Error_Msg_N
5769                  ("body of child unit does not match previous declaration", N);
5770             end if;
5771          end if;
5772
5773          <<Next_Entity>>
5774             E := Homonym (E);
5775       end loop;
5776
5777       --  On exit, we know that no previous declaration of subprogram exists
5778
5779       return Empty;
5780    end Find_Corresponding_Spec;
5781
5782    ----------------------
5783    -- Fully_Conformant --
5784    ----------------------
5785
5786    function Fully_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
5787       Result : Boolean;
5788    begin
5789       Check_Conformance (New_Id, Old_Id, Fully_Conformant, False, Result);
5790       return Result;
5791    end Fully_Conformant;
5792
5793    ----------------------------------
5794    -- Fully_Conformant_Expressions --
5795    ----------------------------------
5796
5797    function Fully_Conformant_Expressions
5798      (Given_E1 : Node_Id;
5799       Given_E2 : Node_Id) return Boolean
5800    is
5801       E1 : constant Node_Id := Original_Node (Given_E1);
5802       E2 : constant Node_Id := Original_Node (Given_E2);
5803       --  We always test conformance on original nodes, since it is possible
5804       --  for analysis and/or expansion to make things look as though they
5805       --  conform when they do not, e.g. by converting 1+2 into 3.
5806
5807       function FCE (Given_E1, Given_E2 : Node_Id) return Boolean
5808         renames Fully_Conformant_Expressions;
5809
5810       function FCL (L1, L2 : List_Id) return Boolean;
5811       --  Compare elements of two lists for conformance. Elements have to
5812       --  be conformant, and actuals inserted as default parameters do not
5813       --  match explicit actuals with the same value.
5814
5815       function FCO (Op_Node, Call_Node : Node_Id) return Boolean;
5816       --  Compare an operator node with a function call
5817
5818       ---------
5819       -- FCL --
5820       ---------
5821
5822       function FCL (L1, L2 : List_Id) return Boolean is
5823          N1, N2 : Node_Id;
5824
5825       begin
5826          if L1 = No_List then
5827             N1 := Empty;
5828          else
5829             N1 := First (L1);
5830          end if;
5831
5832          if L2 = No_List then
5833             N2 := Empty;
5834          else
5835             N2 := First (L2);
5836          end if;
5837
5838          --  Compare two lists, skipping rewrite insertions (we want to
5839          --  compare the original trees, not the expanded versions!)
5840
5841          loop
5842             if Is_Rewrite_Insertion (N1) then
5843                Next (N1);
5844             elsif Is_Rewrite_Insertion (N2) then
5845                Next (N2);
5846             elsif No (N1) then
5847                return No (N2);
5848             elsif No (N2) then
5849                return False;
5850             elsif not FCE (N1, N2) then
5851                return False;
5852             else
5853                Next (N1);
5854                Next (N2);
5855             end if;
5856          end loop;
5857       end FCL;
5858
5859       ---------
5860       -- FCO --
5861       ---------
5862
5863       function FCO (Op_Node, Call_Node : Node_Id) return Boolean is
5864          Actuals : constant List_Id := Parameter_Associations (Call_Node);
5865          Act     : Node_Id;
5866
5867       begin
5868          if No (Actuals)
5869             or else Entity (Op_Node) /= Entity (Name (Call_Node))
5870          then
5871             return False;
5872
5873          else
5874             Act := First (Actuals);
5875
5876             if Nkind (Op_Node) in N_Binary_Op then
5877                if not FCE (Left_Opnd (Op_Node), Act) then
5878                   return False;
5879                end if;
5880
5881                Next (Act);
5882             end if;
5883
5884             return Present (Act)
5885               and then FCE (Right_Opnd (Op_Node), Act)
5886               and then No (Next (Act));
5887          end if;
5888       end FCO;
5889
5890    --  Start of processing for Fully_Conformant_Expressions
5891
5892    begin
5893       --  Non-conformant if paren count does not match. Note: if some idiot
5894       --  complains that we don't do this right for more than 3 levels of
5895       --  parentheses, they will be treated with the respect they deserve!
5896
5897       if Paren_Count (E1) /= Paren_Count (E2) then
5898          return False;
5899
5900       --  If same entities are referenced, then they are conformant even if
5901       --  they have different forms (RM 8.3.1(19-20)).
5902
5903       elsif Is_Entity_Name (E1) and then Is_Entity_Name (E2) then
5904          if Present (Entity (E1)) then
5905             return Entity (E1) = Entity (E2)
5906               or else (Chars (Entity (E1)) = Chars (Entity (E2))
5907                         and then Ekind (Entity (E1)) = E_Discriminant
5908                         and then Ekind (Entity (E2)) = E_In_Parameter);
5909
5910          elsif Nkind (E1) = N_Expanded_Name
5911            and then Nkind (E2) = N_Expanded_Name
5912            and then Nkind (Selector_Name (E1)) = N_Character_Literal
5913            and then Nkind (Selector_Name (E2)) = N_Character_Literal
5914          then
5915             return Chars (Selector_Name (E1)) = Chars (Selector_Name (E2));
5916
5917          else
5918             --  Identifiers in component associations don't always have
5919             --  entities, but their names must conform.
5920
5921             return Nkind  (E1) = N_Identifier
5922               and then Nkind (E2) = N_Identifier
5923               and then Chars (E1) = Chars (E2);
5924          end if;
5925
5926       elsif Nkind (E1) = N_Character_Literal
5927         and then Nkind (E2) = N_Expanded_Name
5928       then
5929          return Nkind (Selector_Name (E2)) = N_Character_Literal
5930            and then Chars (E1) = Chars (Selector_Name (E2));
5931
5932       elsif Nkind (E2) = N_Character_Literal
5933         and then Nkind (E1) = N_Expanded_Name
5934       then
5935          return Nkind (Selector_Name (E1)) = N_Character_Literal
5936            and then Chars (E2) = Chars (Selector_Name (E1));
5937
5938       elsif Nkind (E1) in N_Op
5939         and then Nkind (E2) = N_Function_Call
5940       then
5941          return FCO (E1, E2);
5942
5943       elsif Nkind (E2) in N_Op
5944         and then Nkind (E1) = N_Function_Call
5945       then
5946          return FCO (E2, E1);
5947
5948       --  Otherwise we must have the same syntactic entity
5949
5950       elsif Nkind (E1) /= Nkind (E2) then
5951          return False;
5952
5953       --  At this point, we specialize by node type
5954
5955       else
5956          case Nkind (E1) is
5957
5958             when N_Aggregate =>
5959                return
5960                  FCL (Expressions (E1), Expressions (E2))
5961                    and then FCL (Component_Associations (E1),
5962                                  Component_Associations (E2));
5963
5964             when N_Allocator =>
5965                if Nkind (Expression (E1)) = N_Qualified_Expression
5966                     or else
5967                   Nkind (Expression (E2)) = N_Qualified_Expression
5968                then
5969                   return FCE (Expression (E1), Expression (E2));
5970
5971                --  Check that the subtype marks and any constraints
5972                --  are conformant
5973
5974                else
5975                   declare
5976                      Indic1 : constant Node_Id := Expression (E1);
5977                      Indic2 : constant Node_Id := Expression (E2);
5978                      Elt1   : Node_Id;
5979                      Elt2   : Node_Id;
5980
5981                   begin
5982                      if Nkind (Indic1) /= N_Subtype_Indication then
5983                         return
5984                           Nkind (Indic2) /= N_Subtype_Indication
5985                             and then Entity (Indic1) = Entity (Indic2);
5986
5987                      elsif Nkind (Indic2) /= N_Subtype_Indication then
5988                         return
5989                           Nkind (Indic1) /= N_Subtype_Indication
5990                             and then Entity (Indic1) = Entity (Indic2);
5991
5992                      else
5993                         if Entity (Subtype_Mark (Indic1)) /=
5994                           Entity (Subtype_Mark (Indic2))
5995                         then
5996                            return False;
5997                         end if;
5998
5999                         Elt1 := First (Constraints (Constraint (Indic1)));
6000                         Elt2 := First (Constraints (Constraint (Indic2)));
6001                         while Present (Elt1) and then Present (Elt2) loop
6002                            if not FCE (Elt1, Elt2) then
6003                               return False;
6004                            end if;
6005
6006                            Next (Elt1);
6007                            Next (Elt2);
6008                         end loop;
6009
6010                         return True;
6011                      end if;
6012                   end;
6013                end if;
6014
6015             when N_Attribute_Reference =>
6016                return
6017                  Attribute_Name (E1) = Attribute_Name (E2)
6018                    and then FCL (Expressions (E1), Expressions (E2));
6019
6020             when N_Binary_Op =>
6021                return
6022                  Entity (E1) = Entity (E2)
6023                    and then FCE (Left_Opnd  (E1), Left_Opnd  (E2))
6024                    and then FCE (Right_Opnd (E1), Right_Opnd (E2));
6025
6026             when N_And_Then | N_Or_Else | N_Membership_Test =>
6027                return
6028                  FCE (Left_Opnd  (E1), Left_Opnd  (E2))
6029                    and then
6030                  FCE (Right_Opnd (E1), Right_Opnd (E2));
6031
6032             when N_Character_Literal =>
6033                return
6034                  Char_Literal_Value (E1) = Char_Literal_Value (E2);
6035
6036             when N_Component_Association =>
6037                return
6038                  FCL (Choices (E1), Choices (E2))
6039                    and then FCE (Expression (E1), Expression (E2));
6040
6041             when N_Conditional_Expression =>
6042                return
6043                  FCL (Expressions (E1), Expressions (E2));
6044
6045             when N_Explicit_Dereference =>
6046                return
6047                  FCE (Prefix (E1), Prefix (E2));
6048
6049             when N_Extension_Aggregate =>
6050                return
6051                  FCL (Expressions (E1), Expressions (E2))
6052                    and then Null_Record_Present (E1) =
6053                             Null_Record_Present (E2)
6054                    and then FCL (Component_Associations (E1),
6055                                Component_Associations (E2));
6056
6057             when N_Function_Call =>
6058                return
6059                  FCE (Name (E1), Name (E2))
6060                    and then FCL (Parameter_Associations (E1),
6061                                  Parameter_Associations (E2));
6062
6063             when N_Indexed_Component =>
6064                return
6065                  FCE (Prefix (E1), Prefix (E2))
6066                    and then FCL (Expressions (E1), Expressions (E2));
6067
6068             when N_Integer_Literal =>
6069                return (Intval (E1) = Intval (E2));
6070
6071             when N_Null =>
6072                return True;
6073
6074             when N_Operator_Symbol =>
6075                return
6076                  Chars (E1) = Chars (E2);
6077
6078             when N_Others_Choice =>
6079                return True;
6080
6081             when N_Parameter_Association =>
6082                return
6083                  Chars (Selector_Name (E1))  = Chars (Selector_Name (E2))
6084                    and then FCE (Explicit_Actual_Parameter (E1),
6085                                  Explicit_Actual_Parameter (E2));
6086
6087             when N_Qualified_Expression =>
6088                return
6089                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6090                    and then FCE (Expression (E1), Expression (E2));
6091
6092             when N_Range =>
6093                return
6094                  FCE (Low_Bound (E1), Low_Bound (E2))
6095                    and then FCE (High_Bound (E1), High_Bound (E2));
6096
6097             when N_Real_Literal =>
6098                return (Realval (E1) = Realval (E2));
6099
6100             when N_Selected_Component =>
6101                return
6102                  FCE (Prefix (E1), Prefix (E2))
6103                    and then FCE (Selector_Name (E1), Selector_Name (E2));
6104
6105             when N_Slice =>
6106                return
6107                  FCE (Prefix (E1), Prefix (E2))
6108                    and then FCE (Discrete_Range (E1), Discrete_Range (E2));
6109
6110             when N_String_Literal =>
6111                declare
6112                   S1 : constant String_Id := Strval (E1);
6113                   S2 : constant String_Id := Strval (E2);
6114                   L1 : constant Nat       := String_Length (S1);
6115                   L2 : constant Nat       := String_Length (S2);
6116
6117                begin
6118                   if L1 /= L2 then
6119                      return False;
6120
6121                   else
6122                      for J in 1 .. L1 loop
6123                         if Get_String_Char (S1, J) /=
6124                            Get_String_Char (S2, J)
6125                         then
6126                            return False;
6127                         end if;
6128                      end loop;
6129
6130                      return True;
6131                   end if;
6132                end;
6133
6134             when N_Type_Conversion =>
6135                return
6136                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6137                    and then FCE (Expression (E1), Expression (E2));
6138
6139             when N_Unary_Op =>
6140                return
6141                  Entity (E1) = Entity (E2)
6142                    and then FCE (Right_Opnd (E1), Right_Opnd (E2));
6143
6144             when N_Unchecked_Type_Conversion =>
6145                return
6146                  FCE (Subtype_Mark (E1), Subtype_Mark (E2))
6147                    and then FCE (Expression (E1), Expression (E2));
6148
6149             --  All other node types cannot appear in this context. Strictly
6150             --  we should raise a fatal internal error. Instead we just ignore
6151             --  the nodes. This means that if anyone makes a mistake in the
6152             --  expander and mucks an expression tree irretrievably, the
6153             --  result will be a failure to detect a (probably very obscure)
6154             --  case of non-conformance, which is better than bombing on some
6155             --  case where two expressions do in fact conform.
6156
6157             when others =>
6158                return True;
6159
6160          end case;
6161       end if;
6162    end Fully_Conformant_Expressions;
6163
6164    ----------------------------------------
6165    -- Fully_Conformant_Discrete_Subtypes --
6166    ----------------------------------------
6167
6168    function Fully_Conformant_Discrete_Subtypes
6169      (Given_S1 : Node_Id;
6170       Given_S2 : Node_Id) return Boolean
6171    is
6172       S1 : constant Node_Id := Original_Node (Given_S1);
6173       S2 : constant Node_Id := Original_Node (Given_S2);
6174
6175       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean;
6176       --  Special-case for a bound given by a discriminant, which in the body
6177       --  is replaced with the discriminal of the enclosing type.
6178
6179       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean;
6180       --  Check both bounds
6181
6182       -----------------------
6183       -- Conforming_Bounds --
6184       -----------------------
6185
6186       function Conforming_Bounds (B1, B2 : Node_Id) return Boolean is
6187       begin
6188          if Is_Entity_Name (B1)
6189            and then Is_Entity_Name (B2)
6190            and then Ekind (Entity (B1)) = E_Discriminant
6191          then
6192             return Chars (B1) = Chars (B2);
6193
6194          else
6195             return Fully_Conformant_Expressions (B1, B2);
6196          end if;
6197       end Conforming_Bounds;
6198
6199       -----------------------
6200       -- Conforming_Ranges --
6201       -----------------------
6202
6203       function Conforming_Ranges (R1, R2 : Node_Id) return Boolean is
6204       begin
6205          return
6206            Conforming_Bounds (Low_Bound (R1), Low_Bound (R2))
6207              and then
6208            Conforming_Bounds (High_Bound (R1), High_Bound (R2));
6209       end Conforming_Ranges;
6210
6211    --  Start of processing for Fully_Conformant_Discrete_Subtypes
6212
6213    begin
6214       if Nkind (S1) /= Nkind (S2) then
6215          return False;
6216
6217       elsif Is_Entity_Name (S1) then
6218          return Entity (S1) = Entity (S2);
6219
6220       elsif Nkind (S1) = N_Range then
6221          return Conforming_Ranges (S1, S2);
6222
6223       elsif Nkind (S1) = N_Subtype_Indication then
6224          return
6225             Entity (Subtype_Mark (S1)) = Entity (Subtype_Mark (S2))
6226               and then
6227             Conforming_Ranges
6228               (Range_Expression (Constraint (S1)),
6229                Range_Expression (Constraint (S2)));
6230       else
6231          return True;
6232       end if;
6233    end Fully_Conformant_Discrete_Subtypes;
6234
6235    --------------------
6236    -- Install_Entity --
6237    --------------------
6238
6239    procedure Install_Entity (E : Entity_Id) is
6240       Prev : constant Entity_Id := Current_Entity (E);
6241    begin
6242       Set_Is_Immediately_Visible (E);
6243       Set_Current_Entity (E);
6244       Set_Homonym (E, Prev);
6245    end Install_Entity;
6246
6247    ---------------------
6248    -- Install_Formals --
6249    ---------------------
6250
6251    procedure Install_Formals (Id : Entity_Id) is
6252       F : Entity_Id;
6253    begin
6254       F := First_Formal (Id);
6255       while Present (F) loop
6256          Install_Entity (F);
6257          Next_Formal (F);
6258       end loop;
6259    end Install_Formals;
6260
6261    -----------------------------
6262    -- Is_Interface_Conformant --
6263    -----------------------------
6264
6265    function Is_Interface_Conformant
6266      (Tagged_Type : Entity_Id;
6267       Iface_Prim  : Entity_Id;
6268       Prim        : Entity_Id) return Boolean
6269    is
6270       Iface : constant Entity_Id := Find_Dispatching_Type (Iface_Prim);
6271       Typ   : constant Entity_Id := Find_Dispatching_Type (Prim);
6272
6273    begin
6274       pragma Assert (Is_Subprogram (Iface_Prim)
6275         and then Is_Subprogram (Prim)
6276         and then Is_Dispatching_Operation (Iface_Prim)
6277         and then Is_Dispatching_Operation (Prim));
6278
6279       pragma Assert (Is_Interface (Iface)
6280         or else (Present (Alias (Iface_Prim))
6281                    and then
6282                      Is_Interface
6283                        (Find_Dispatching_Type (Ultimate_Alias (Iface_Prim)))));
6284
6285       if Prim = Iface_Prim
6286         or else not Is_Subprogram (Prim)
6287         or else Ekind (Prim) /= Ekind (Iface_Prim)
6288         or else not Is_Dispatching_Operation (Prim)
6289         or else Scope (Prim) /= Scope (Tagged_Type)
6290         or else No (Typ)
6291         or else Base_Type (Typ) /= Tagged_Type
6292         or else not Primitive_Names_Match (Iface_Prim, Prim)
6293       then
6294          return False;
6295
6296       --  Case of a procedure, or a function that does not have a controlling
6297       --  result (I or access I).
6298
6299       elsif Ekind (Iface_Prim) = E_Procedure
6300         or else Etype (Prim) = Etype (Iface_Prim)
6301         or else not Has_Controlling_Result (Prim)
6302       then
6303          return Type_Conformant (Prim, Iface_Prim,
6304                   Skip_Controlling_Formals => True);
6305
6306       --  Case of a function returning an interface, or an access to one.
6307       --  Check that the return types correspond.
6308
6309       elsif Implements_Interface (Typ, Iface) then
6310          if (Ekind (Etype (Prim)) = E_Anonymous_Access_Type)
6311               /=
6312             (Ekind (Etype (Iface_Prim)) = E_Anonymous_Access_Type)
6313          then
6314             return False;
6315          else
6316             return
6317               Type_Conformant (Prim, Iface_Prim,
6318                 Skip_Controlling_Formals => True);
6319          end if;
6320
6321       else
6322          return False;
6323       end if;
6324    end Is_Interface_Conformant;
6325
6326    ---------------------------------
6327    -- Is_Non_Overriding_Operation --
6328    ---------------------------------
6329
6330    function Is_Non_Overriding_Operation
6331      (Prev_E : Entity_Id;
6332       New_E  : Entity_Id) return Boolean
6333    is
6334       Formal : Entity_Id;
6335       F_Typ  : Entity_Id;
6336       G_Typ  : Entity_Id := Empty;
6337
6338       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id;
6339       --  If F_Type is a derived type associated with a generic actual subtype,
6340       --  then return its Generic_Parent_Type attribute, else return Empty.
6341
6342       function Types_Correspond
6343         (P_Type : Entity_Id;
6344          N_Type : Entity_Id) return Boolean;
6345       --  Returns true if and only if the types (or designated types in the
6346       --  case of anonymous access types) are the same or N_Type is derived
6347       --  directly or indirectly from P_Type.
6348
6349       -----------------------------
6350       -- Get_Generic_Parent_Type --
6351       -----------------------------
6352
6353       function Get_Generic_Parent_Type (F_Typ : Entity_Id) return Entity_Id is
6354          G_Typ : Entity_Id;
6355          Indic : Node_Id;
6356
6357       begin
6358          if Is_Derived_Type (F_Typ)
6359            and then Nkind (Parent (F_Typ)) = N_Full_Type_Declaration
6360          then
6361             --  The tree must be traversed to determine the parent subtype in
6362             --  the generic unit, which unfortunately isn't always available
6363             --  via semantic attributes. ??? (Note: The use of Original_Node
6364             --  is needed for cases where a full derived type has been
6365             --  rewritten.)
6366
6367             Indic := Subtype_Indication
6368                        (Type_Definition (Original_Node (Parent (F_Typ))));
6369
6370             if Nkind (Indic) = N_Subtype_Indication then
6371                G_Typ := Entity (Subtype_Mark (Indic));
6372             else
6373                G_Typ := Entity (Indic);
6374             end if;
6375
6376             if Nkind (Parent (G_Typ)) = N_Subtype_Declaration
6377               and then Present (Generic_Parent_Type (Parent (G_Typ)))
6378             then
6379                return Generic_Parent_Type (Parent (G_Typ));
6380             end if;
6381          end if;
6382
6383          return Empty;
6384       end Get_Generic_Parent_Type;
6385
6386       ----------------------
6387       -- Types_Correspond --
6388       ----------------------
6389
6390       function Types_Correspond
6391         (P_Type : Entity_Id;
6392          N_Type : Entity_Id) return Boolean
6393       is
6394          Prev_Type : Entity_Id := Base_Type (P_Type);
6395          New_Type  : Entity_Id := Base_Type (N_Type);
6396
6397       begin
6398          if Ekind (Prev_Type) = E_Anonymous_Access_Type then
6399             Prev_Type := Designated_Type (Prev_Type);
6400          end if;
6401
6402          if Ekind (New_Type) = E_Anonymous_Access_Type then
6403             New_Type := Designated_Type (New_Type);
6404          end if;
6405
6406          if Prev_Type = New_Type then
6407             return True;
6408
6409          elsif not Is_Class_Wide_Type (New_Type) then
6410             while Etype (New_Type) /= New_Type loop
6411                New_Type := Etype (New_Type);
6412                if New_Type = Prev_Type then
6413                   return True;
6414                end if;
6415             end loop;
6416          end if;
6417          return False;
6418       end Types_Correspond;
6419
6420    --  Start of processing for Is_Non_Overriding_Operation
6421
6422    begin
6423       --  In the case where both operations are implicit derived subprograms
6424       --  then neither overrides the other. This can only occur in certain
6425       --  obscure cases (e.g., derivation from homographs created in a generic
6426       --  instantiation).
6427
6428       if Present (Alias (Prev_E)) and then Present (Alias (New_E)) then
6429          return True;
6430
6431       elsif Ekind (Current_Scope) = E_Package
6432         and then Is_Generic_Instance (Current_Scope)
6433         and then In_Private_Part (Current_Scope)
6434         and then Comes_From_Source (New_E)
6435       then
6436          --  We examine the formals and result subtype of the inherited
6437          --  operation, to determine whether their type is derived from (the
6438          --  instance of) a generic type.
6439
6440          Formal := First_Formal (Prev_E);
6441
6442          while Present (Formal) loop
6443             F_Typ := Base_Type (Etype (Formal));
6444
6445             if Ekind (F_Typ) = E_Anonymous_Access_Type then
6446                F_Typ := Designated_Type (F_Typ);
6447             end if;
6448
6449             G_Typ := Get_Generic_Parent_Type (F_Typ);
6450
6451             Next_Formal (Formal);
6452          end loop;
6453
6454          if No (G_Typ) and then Ekind (Prev_E) = E_Function then
6455             G_Typ := Get_Generic_Parent_Type (Base_Type (Etype (Prev_E)));
6456          end if;
6457
6458          if No (G_Typ) then
6459             return False;
6460          end if;
6461
6462          --  If the generic type is a private type, then the original operation
6463          --  was not overriding in the generic, because there was no primitive
6464          --  operation to override.
6465
6466          if Nkind (Parent (G_Typ)) = N_Formal_Type_Declaration
6467            and then Nkind (Formal_Type_Definition (Parent (G_Typ))) =
6468                       N_Formal_Private_Type_Definition
6469          then
6470             return True;
6471
6472          --  The generic parent type is the ancestor of a formal derived
6473          --  type declaration. We need to check whether it has a primitive
6474          --  operation that should be overridden by New_E in the generic.
6475
6476          else
6477             declare
6478                P_Formal : Entity_Id;
6479                N_Formal : Entity_Id;
6480                P_Typ    : Entity_Id;
6481                N_Typ    : Entity_Id;
6482                P_Prim   : Entity_Id;
6483                Prim_Elt : Elmt_Id := First_Elmt (Primitive_Operations (G_Typ));
6484
6485             begin
6486                while Present (Prim_Elt) loop
6487                   P_Prim := Node (Prim_Elt);
6488
6489                   if Chars (P_Prim) = Chars (New_E)
6490                     and then Ekind (P_Prim) = Ekind (New_E)
6491                   then
6492                      P_Formal := First_Formal (P_Prim);
6493                      N_Formal := First_Formal (New_E);
6494                      while Present (P_Formal) and then Present (N_Formal) loop
6495                         P_Typ := Etype (P_Formal);
6496                         N_Typ := Etype (N_Formal);
6497
6498                         if not Types_Correspond (P_Typ, N_Typ) then
6499                            exit;
6500                         end if;
6501
6502                         Next_Entity (P_Formal);
6503                         Next_Entity (N_Formal);
6504                      end loop;
6505
6506                      --  Found a matching primitive operation belonging to the
6507                      --  formal ancestor type, so the new subprogram is
6508                      --  overriding.
6509
6510                      if No (P_Formal)
6511                        and then No (N_Formal)
6512                        and then (Ekind (New_E) /= E_Function
6513                                   or else
6514                                  Types_Correspond
6515                                    (Etype (P_Prim), Etype (New_E)))
6516                      then
6517                         return False;
6518                      end if;
6519                   end if;
6520
6521                   Next_Elmt (Prim_Elt);
6522                end loop;
6523
6524                --  If no match found, then the new subprogram does not
6525                --  override in the generic (nor in the instance).
6526
6527                return True;
6528             end;
6529          end if;
6530       else
6531          return False;
6532       end if;
6533    end Is_Non_Overriding_Operation;
6534
6535    ------------------------------
6536    -- Make_Inequality_Operator --
6537    ------------------------------
6538
6539    --  S is the defining identifier of an equality operator. We build a
6540    --  subprogram declaration with the right signature. This operation is
6541    --  intrinsic, because it is always expanded as the negation of the
6542    --  call to the equality function.
6543
6544    procedure Make_Inequality_Operator (S : Entity_Id) is
6545       Loc     : constant Source_Ptr := Sloc (S);
6546       Decl    : Node_Id;
6547       Formals : List_Id;
6548       Op_Name : Entity_Id;
6549
6550       FF : constant Entity_Id := First_Formal (S);
6551       NF : constant Entity_Id := Next_Formal (FF);
6552
6553    begin
6554       --  Check that equality was properly defined, ignore call if not
6555
6556       if No (NF) then
6557          return;
6558       end if;
6559
6560       declare
6561          A : constant Entity_Id :=
6562                Make_Defining_Identifier (Sloc (FF),
6563                  Chars => Chars (FF));
6564
6565          B : constant Entity_Id :=
6566                Make_Defining_Identifier (Sloc (NF),
6567                  Chars => Chars (NF));
6568
6569       begin
6570          Op_Name := Make_Defining_Operator_Symbol (Loc, Name_Op_Ne);
6571
6572          Formals := New_List (
6573            Make_Parameter_Specification (Loc,
6574              Defining_Identifier => A,
6575              Parameter_Type      =>
6576                New_Reference_To (Etype (First_Formal (S)),
6577                  Sloc (Etype (First_Formal (S))))),
6578
6579            Make_Parameter_Specification (Loc,
6580              Defining_Identifier => B,
6581              Parameter_Type      =>
6582                New_Reference_To (Etype (Next_Formal (First_Formal (S))),
6583                  Sloc (Etype (Next_Formal (First_Formal (S)))))));
6584
6585          Decl :=
6586            Make_Subprogram_Declaration (Loc,
6587              Specification =>
6588                Make_Function_Specification (Loc,
6589                  Defining_Unit_Name       => Op_Name,
6590                  Parameter_Specifications => Formals,
6591                  Result_Definition        =>
6592                    New_Reference_To (Standard_Boolean, Loc)));
6593
6594          --  Insert inequality right after equality if it is explicit or after
6595          --  the derived type when implicit. These entities are created only
6596          --  for visibility purposes, and eventually replaced in the course of
6597          --  expansion, so they do not need to be attached to the tree and seen
6598          --  by the back-end. Keeping them internal also avoids spurious
6599          --  freezing problems. The declaration is inserted in the tree for
6600          --  analysis, and removed afterwards. If the equality operator comes
6601          --  from an explicit declaration, attach the inequality immediately
6602          --  after. Else the equality is inherited from a derived type
6603          --  declaration, so insert inequality after that declaration.
6604
6605          if No (Alias (S)) then
6606             Insert_After (Unit_Declaration_Node (S), Decl);
6607          elsif Is_List_Member (Parent (S)) then
6608             Insert_After (Parent (S), Decl);
6609          else
6610             Insert_After (Parent (Etype (First_Formal (S))), Decl);
6611          end if;
6612
6613          Mark_Rewrite_Insertion (Decl);
6614          Set_Is_Intrinsic_Subprogram (Op_Name);
6615          Analyze (Decl);
6616          Remove (Decl);
6617          Set_Has_Completion (Op_Name);
6618          Set_Corresponding_Equality (Op_Name, S);
6619          Set_Is_Abstract_Subprogram (Op_Name, Is_Abstract_Subprogram (S));
6620       end;
6621    end Make_Inequality_Operator;
6622
6623    ----------------------
6624    -- May_Need_Actuals --
6625    ----------------------
6626
6627    procedure May_Need_Actuals (Fun : Entity_Id) is
6628       F : Entity_Id;
6629       B : Boolean;
6630
6631    begin
6632       F := First_Formal (Fun);
6633       B := True;
6634       while Present (F) loop
6635          if No (Default_Value (F)) then
6636             B := False;
6637             exit;
6638          end if;
6639
6640          Next_Formal (F);
6641       end loop;
6642
6643       Set_Needs_No_Actuals (Fun, B);
6644    end May_Need_Actuals;
6645
6646    ---------------------
6647    -- Mode_Conformant --
6648    ---------------------
6649
6650    function Mode_Conformant (New_Id, Old_Id : Entity_Id) return Boolean is
6651       Result : Boolean;
6652    begin
6653       Check_Conformance (New_Id, Old_Id, Mode_Conformant, False, Result);
6654       return Result;
6655    end Mode_Conformant;
6656
6657    ---------------------------
6658    -- New_Overloaded_Entity --
6659    ---------------------------
6660
6661    procedure New_Overloaded_Entity
6662      (S            : Entity_Id;
6663       Derived_Type : Entity_Id := Empty)
6664    is
6665       Overridden_Subp : Entity_Id := Empty;
6666       --  Set if the current scope has an operation that is type-conformant
6667       --  with S, and becomes hidden by S.
6668
6669       Is_Primitive_Subp : Boolean;
6670       --  Set to True if the new subprogram is primitive
6671
6672       E : Entity_Id;
6673       --  Entity that S overrides
6674
6675       Prev_Vis : Entity_Id := Empty;
6676       --  Predecessor of E in Homonym chain
6677
6678       procedure Check_For_Primitive_Subprogram
6679         (Is_Primitive  : out Boolean;
6680          Is_Overriding : Boolean := False);
6681       --  If the subprogram being analyzed is a primitive operation of the type
6682       --  of a formal or result, set the Has_Primitive_Operations flag on the
6683       --  type, and set Is_Primitive to True (otherwise set to False). Set the
6684       --  corresponding flag on the entity itself for later use.
6685
6686       procedure Check_Synchronized_Overriding
6687         (Def_Id          : Entity_Id;
6688          Overridden_Subp : out Entity_Id);
6689       --  First determine if Def_Id is an entry or a subprogram either defined
6690       --  in the scope of a task or protected type, or is a primitive of such
6691       --  a type. Check whether Def_Id overrides a subprogram of an interface
6692       --  implemented by the synchronized type, return the overridden entity
6693       --  or Empty.
6694
6695       function Is_Private_Declaration (E : Entity_Id) return Boolean;
6696       --  Check that E is declared in the private part of the current package,
6697       --  or in the package body, where it may hide a previous declaration.
6698       --  We can't use In_Private_Part by itself because this flag is also
6699       --  set when freezing entities, so we must examine the place of the
6700       --  declaration in the tree, and recognize wrapper packages as well.
6701
6702       function Is_Overriding_Alias
6703         (Old_E : Entity_Id;
6704          New_E : Entity_Id) return Boolean;
6705       --  Check whether new subprogram and old subprogram are both inherited
6706       --  from subprograms that have distinct dispatch table entries. This can
6707       --  occur with derivations from instances with accidental homonyms.
6708       --  The function is conservative given that the converse is only true
6709       --  within instances that contain accidental overloadings.
6710
6711       ------------------------------------
6712       -- Check_For_Primitive_Subprogram --
6713       ------------------------------------
6714
6715       procedure Check_For_Primitive_Subprogram
6716         (Is_Primitive  : out Boolean;
6717          Is_Overriding : Boolean := False)
6718       is
6719          Formal : Entity_Id;
6720          F_Typ  : Entity_Id;
6721          B_Typ  : Entity_Id;
6722
6723          function Visible_Part_Type (T : Entity_Id) return Boolean;
6724          --  Returns true if T is declared in the visible part of the current
6725          --  package scope; otherwise returns false. Assumes that T is declared
6726          --  in a package.
6727
6728          procedure Check_Private_Overriding (T : Entity_Id);
6729          --  Checks that if a primitive abstract subprogram of a visible
6730          --  abstract type is declared in a private part, then it must override
6731          --  an abstract subprogram declared in the visible part. Also checks
6732          --  that if a primitive function with a controlling result is declared
6733          --  in a private part, then it must override a function declared in
6734          --  the visible part.
6735
6736          ------------------------------
6737          -- Check_Private_Overriding --
6738          ------------------------------
6739
6740          procedure Check_Private_Overriding (T : Entity_Id) is
6741          begin
6742             if Is_Package_Or_Generic_Package (Current_Scope)
6743               and then In_Private_Part (Current_Scope)
6744               and then Visible_Part_Type (T)
6745               and then not In_Instance
6746             then
6747                if Is_Abstract_Type (T)
6748                  and then Is_Abstract_Subprogram (S)
6749                  and then (not Is_Overriding
6750                             or else not Is_Abstract_Subprogram (E))
6751                then
6752                   Error_Msg_N ("abstract subprograms must be visible "
6753                                    & "(RM 3.9.3(10))!", S);
6754
6755                elsif Ekind (S) = E_Function
6756                  and then Is_Tagged_Type (T)
6757                  and then T = Base_Type (Etype (S))
6758                  and then not Is_Overriding
6759                then
6760                   Error_Msg_N
6761                     ("private function with tagged result must"
6762                      & " override visible-part function", S);
6763                   Error_Msg_N
6764                     ("\move subprogram to the visible part"
6765                      & " (RM 3.9.3(10))", S);
6766                end if;
6767             end if;
6768          end Check_Private_Overriding;
6769
6770          -----------------------
6771          -- Visible_Part_Type --
6772          -----------------------
6773
6774          function Visible_Part_Type (T : Entity_Id) return Boolean is
6775             P : constant Node_Id := Unit_Declaration_Node (Scope (T));
6776             N : Node_Id;
6777
6778          begin
6779             --  If the entity is a private type, then it must be declared in a
6780             --  visible part.
6781
6782             if Ekind (T) in Private_Kind then
6783                return True;
6784             end if;
6785
6786             --  Otherwise, we traverse the visible part looking for its
6787             --  corresponding declaration. We cannot use the declaration
6788             --  node directly because in the private part the entity of a
6789             --  private type is the one in the full view, which does not
6790             --  indicate that it is the completion of something visible.
6791
6792             N := First (Visible_Declarations (Specification (P)));
6793             while Present (N) loop
6794                if Nkind (N) = N_Full_Type_Declaration
6795                  and then Present (Defining_Identifier (N))
6796                  and then T = Defining_Identifier (N)
6797                then
6798                   return True;
6799
6800                elsif Nkind_In (N, N_Private_Type_Declaration,
6801                                   N_Private_Extension_Declaration)
6802                  and then Present (Defining_Identifier (N))
6803                  and then T = Full_View (Defining_Identifier (N))
6804                then
6805                   return True;
6806                end if;
6807
6808                Next (N);
6809             end loop;
6810
6811             return False;
6812          end Visible_Part_Type;
6813
6814       --  Start of processing for Check_For_Primitive_Subprogram
6815
6816       begin
6817          Is_Primitive := False;
6818
6819          if not Comes_From_Source (S) then
6820             null;
6821
6822          --  If subprogram is at library level, it is not primitive operation
6823
6824          elsif Current_Scope = Standard_Standard then
6825             null;
6826
6827          elsif (Is_Package_Or_Generic_Package (Current_Scope)
6828                  and then not In_Package_Body (Current_Scope))
6829            or else Is_Overriding
6830          then
6831             --  For function, check return type
6832
6833             if Ekind (S) = E_Function then
6834                if Ekind (Etype (S)) = E_Anonymous_Access_Type then
6835                   F_Typ := Designated_Type (Etype (S));
6836                else
6837                   F_Typ := Etype (S);
6838                end if;
6839
6840                B_Typ := Base_Type (F_Typ);
6841
6842                if Scope (B_Typ) = Current_Scope
6843                  and then not Is_Class_Wide_Type (B_Typ)
6844                  and then not Is_Generic_Type (B_Typ)
6845                then
6846                   Is_Primitive := True;
6847                   Set_Has_Primitive_Operations (B_Typ);
6848                   Set_Is_Primitive (S);
6849                   Check_Private_Overriding (B_Typ);
6850                end if;
6851             end if;
6852
6853             --  For all subprograms, check formals
6854
6855             Formal := First_Formal (S);
6856             while Present (Formal) loop
6857                if Ekind (Etype (Formal)) = E_Anonymous_Access_Type then
6858                   F_Typ := Designated_Type (Etype (Formal));
6859                else
6860                   F_Typ := Etype (Formal);
6861                end if;
6862
6863                B_Typ := Base_Type (F_Typ);
6864
6865                if Ekind (B_Typ) = E_Access_Subtype then
6866                   B_Typ := Base_Type (B_Typ);
6867                end if;
6868
6869                if Scope (B_Typ) = Current_Scope
6870                  and then not Is_Class_Wide_Type (B_Typ)
6871                  and then not Is_Generic_Type (B_Typ)
6872                then
6873                   Is_Primitive := True;
6874                   Set_Is_Primitive (S);
6875                   Set_Has_Primitive_Operations (B_Typ);
6876                   Check_Private_Overriding (B_Typ);
6877                end if;
6878
6879                Next_Formal (Formal);
6880             end loop;
6881          end if;
6882       end Check_For_Primitive_Subprogram;
6883
6884       -----------------------------------
6885       -- Check_Synchronized_Overriding --
6886       -----------------------------------
6887
6888       procedure Check_Synchronized_Overriding
6889         (Def_Id          : Entity_Id;
6890          Overridden_Subp : out Entity_Id)
6891       is
6892          Ifaces_List : Elist_Id;
6893          In_Scope    : Boolean;
6894          Typ         : Entity_Id;
6895
6896          function Matches_Prefixed_View_Profile
6897            (Prim_Params  : List_Id;
6898             Iface_Params : List_Id) return Boolean;
6899          --  Determine whether a subprogram's parameter profile Prim_Params
6900          --  matches that of a potentially overridden interface subprogram
6901          --  Iface_Params. Also determine if the type of first parameter of
6902          --  Iface_Params is an implemented interface.
6903
6904          -----------------------------------
6905          -- Matches_Prefixed_View_Profile --
6906          -----------------------------------
6907
6908          function Matches_Prefixed_View_Profile
6909            (Prim_Params  : List_Id;
6910             Iface_Params : List_Id) return Boolean
6911          is
6912             Iface_Id     : Entity_Id;
6913             Iface_Param  : Node_Id;
6914             Iface_Typ    : Entity_Id;
6915             Prim_Id      : Entity_Id;
6916             Prim_Param   : Node_Id;
6917             Prim_Typ     : Entity_Id;
6918
6919             function Is_Implemented
6920               (Ifaces_List : Elist_Id;
6921                Iface       : Entity_Id) return Boolean;
6922             --  Determine if Iface is implemented by the current task or
6923             --  protected type.
6924
6925             --------------------
6926             -- Is_Implemented --
6927             --------------------
6928
6929             function Is_Implemented
6930               (Ifaces_List : Elist_Id;
6931                Iface       : Entity_Id) return Boolean
6932             is
6933                Iface_Elmt : Elmt_Id;
6934
6935             begin
6936                Iface_Elmt := First_Elmt (Ifaces_List);
6937                while Present (Iface_Elmt) loop
6938                   if Node (Iface_Elmt) = Iface then
6939                      return True;
6940                   end if;
6941
6942                   Next_Elmt (Iface_Elmt);
6943                end loop;
6944
6945                return False;
6946             end Is_Implemented;
6947
6948          --  Start of processing for Matches_Prefixed_View_Profile
6949
6950          begin
6951             Iface_Param := First (Iface_Params);
6952             Iface_Typ   := Etype (Defining_Identifier (Iface_Param));
6953
6954             if Is_Access_Type (Iface_Typ) then
6955                Iface_Typ := Designated_Type (Iface_Typ);
6956             end if;
6957
6958             Prim_Param := First (Prim_Params);
6959
6960             --  The first parameter of the potentially overridden subprogram
6961             --  must be an interface implemented by Prim.
6962
6963             if not Is_Interface (Iface_Typ)
6964               or else not Is_Implemented (Ifaces_List, Iface_Typ)
6965             then
6966                return False;
6967             end if;
6968
6969             --  The checks on the object parameters are done, move onto the
6970             --  rest of the parameters.
6971
6972             if not In_Scope then
6973                Prim_Param := Next (Prim_Param);
6974             end if;
6975
6976             Iface_Param := Next (Iface_Param);
6977             while Present (Iface_Param) and then Present (Prim_Param) loop
6978                Iface_Id  := Defining_Identifier (Iface_Param);
6979                Iface_Typ := Find_Parameter_Type (Iface_Param);
6980
6981                Prim_Id  := Defining_Identifier (Prim_Param);
6982                Prim_Typ := Find_Parameter_Type (Prim_Param);
6983
6984                if Ekind (Iface_Typ) = E_Anonymous_Access_Type
6985                  and then Ekind (Prim_Typ) = E_Anonymous_Access_Type
6986                  and then Is_Concurrent_Type (Designated_Type (Prim_Typ))
6987                then
6988                   Iface_Typ := Designated_Type (Iface_Typ);
6989                   Prim_Typ := Designated_Type (Prim_Typ);
6990                end if;
6991
6992                --  Case of multiple interface types inside a parameter profile
6993
6994                --     (Obj_Param : in out Iface; ...; Param : Iface)
6995
6996                --  If the interface type is implemented, then the matching type
6997                --  in the primitive should be the implementing record type.
6998
6999                if Ekind (Iface_Typ) = E_Record_Type
7000                  and then Is_Interface (Iface_Typ)
7001                  and then Is_Implemented (Ifaces_List, Iface_Typ)
7002                then
7003                   if Prim_Typ /= Typ then
7004                      return False;
7005                   end if;
7006
7007                --  The two parameters must be both mode and subtype conformant
7008
7009                elsif Ekind (Iface_Id) /= Ekind (Prim_Id)
7010                  or else not
7011                    Conforming_Types (Iface_Typ, Prim_Typ, Subtype_Conformant)
7012                then
7013                   return False;
7014                end if;
7015
7016                Next (Iface_Param);
7017                Next (Prim_Param);
7018             end loop;
7019
7020             --  One of the two lists contains more parameters than the other
7021
7022             if Present (Iface_Param) or else Present (Prim_Param) then
7023                return False;
7024             end if;
7025
7026             return True;
7027          end Matches_Prefixed_View_Profile;
7028
7029       --  Start of processing for Check_Synchronized_Overriding
7030
7031       begin
7032          Overridden_Subp := Empty;
7033
7034          --  Def_Id must be an entry or a subprogram. We should skip predefined
7035          --  primitives internally generated by the frontend; however at this
7036          --  stage predefined primitives are still not fully decorated. As a
7037          --  minor optimization we skip here internally generated subprograms.
7038
7039          if (Ekind (Def_Id) /= E_Entry
7040               and then Ekind (Def_Id) /= E_Function
7041               and then Ekind (Def_Id) /= E_Procedure)
7042            or else not Comes_From_Source (Def_Id)
7043          then
7044             return;
7045          end if;
7046
7047          --  Search for the concurrent declaration since it contains the list
7048          --  of all implemented interfaces. In this case, the subprogram is
7049          --  declared within the scope of a protected or a task type.
7050
7051          if Present (Scope (Def_Id))
7052            and then Is_Concurrent_Type (Scope (Def_Id))
7053            and then not Is_Generic_Actual_Type (Scope (Def_Id))
7054          then
7055             Typ := Scope (Def_Id);
7056             In_Scope := True;
7057
7058          --  The enclosing scope is not a synchronized type and the subprogram
7059          --  has no formals
7060
7061          elsif No (First_Formal (Def_Id)) then
7062             return;
7063
7064          --  The subprogram has formals and hence it may be a primitive of a
7065          --  concurrent type
7066
7067          else
7068             Typ := Etype (First_Formal (Def_Id));
7069
7070             if Is_Access_Type (Typ) then
7071                Typ := Directly_Designated_Type (Typ);
7072             end if;
7073
7074             if Is_Concurrent_Type (Typ)
7075               and then not Is_Generic_Actual_Type (Typ)
7076             then
7077                In_Scope := False;
7078
7079             --  This case occurs when the concurrent type is declared within
7080             --  a generic unit. As a result the corresponding record has been
7081             --  built and used as the type of the first formal, we just have
7082             --  to retrieve the corresponding concurrent type.
7083
7084             elsif Is_Concurrent_Record_Type (Typ)
7085               and then Present (Corresponding_Concurrent_Type (Typ))
7086             then
7087                Typ := Corresponding_Concurrent_Type (Typ);
7088                In_Scope := False;
7089
7090             else
7091                return;
7092             end if;
7093          end if;
7094
7095          --  There is no overriding to check if is an inherited operation in a
7096          --  type derivation on for a generic actual.
7097
7098          Collect_Interfaces (Typ, Ifaces_List);
7099
7100          if Is_Empty_Elmt_List (Ifaces_List) then
7101             return;
7102          end if;
7103
7104          --  Determine whether entry or subprogram Def_Id overrides a primitive
7105          --  operation that belongs to one of the interfaces in Ifaces_List.
7106
7107          declare
7108             Candidate : Entity_Id := Empty;
7109             Hom       : Entity_Id := Empty;
7110             Iface_Typ : Entity_Id;
7111             Subp      : Entity_Id := Empty;
7112
7113          begin
7114             --  Traverse the homonym chain, looking at a potentially
7115             --  overridden subprogram that belongs to an implemented
7116             --  interface.
7117
7118             Hom := Current_Entity_In_Scope (Def_Id);
7119             while Present (Hom) loop
7120                Subp := Hom;
7121
7122                if Subp = Def_Id
7123                  or else not Is_Overloadable (Subp)
7124                  or else not Is_Primitive (Subp)
7125                  or else not Is_Dispatching_Operation (Subp)
7126                  or else not Is_Interface (Find_Dispatching_Type (Subp))
7127                then
7128                   null;
7129
7130                --  Entries and procedures can override abstract or null
7131                --  interface procedures
7132
7133                elsif (Ekind (Def_Id) = E_Procedure
7134                         or else Ekind (Def_Id) = E_Entry)
7135                  and then Ekind (Subp) = E_Procedure
7136                  and then Matches_Prefixed_View_Profile
7137                             (Parameter_Specifications (Parent (Def_Id)),
7138                              Parameter_Specifications (Parent (Subp)))
7139                then
7140                   Candidate := Subp;
7141
7142                   --  For an overridden subprogram Subp, check whether the mode
7143                   --  of its first parameter is correct depending on the kind
7144                   --  of synchronized type.
7145
7146                   declare
7147                      Formal : constant Node_Id := First_Formal (Candidate);
7148
7149                   begin
7150                      --  In order for an entry or a protected procedure to
7151                      --  override, the first parameter of the overridden
7152                      --  routine must be of mode "out", "in out" or
7153                      --  access-to-variable.
7154
7155                      if (Ekind (Candidate) = E_Entry
7156                          or else Ekind (Candidate) = E_Procedure)
7157                        and then Is_Protected_Type (Typ)
7158                        and then Ekind (Formal) /= E_In_Out_Parameter
7159                        and then Ekind (Formal) /= E_Out_Parameter
7160                        and then Nkind (Parameter_Type (Parent (Formal)))
7161                                   /= N_Access_Definition
7162                      then
7163                         null;
7164
7165                      --  All other cases are OK since a task entry or routine
7166                      --  does not have a restriction on the mode of the first
7167                      --  parameter of the overridden interface routine.
7168
7169                      else
7170                         Overridden_Subp := Candidate;
7171                         return;
7172                      end if;
7173                   end;
7174
7175                --  Functions can override abstract interface functions
7176
7177                elsif Ekind (Def_Id) = E_Function
7178                  and then Ekind (Subp) = E_Function
7179                  and then Matches_Prefixed_View_Profile
7180                             (Parameter_Specifications (Parent (Def_Id)),
7181                              Parameter_Specifications (Parent (Subp)))
7182                  and then Etype (Result_Definition (Parent (Def_Id))) =
7183                           Etype (Result_Definition (Parent (Subp)))
7184                then
7185                   Overridden_Subp := Subp;
7186                   return;
7187                end if;
7188
7189                Hom := Homonym (Hom);
7190             end loop;
7191
7192             --  After examining all candidates for overriding, we are
7193             --  left with the best match which is a mode incompatible
7194             --  interface routine. Do not emit an error if the Expander
7195             --  is active since this error will be detected later on
7196             --  after all concurrent types are expanded and all wrappers
7197             --  are built. This check is meant for spec-only
7198             --  compilations.
7199
7200             if Present (Candidate)
7201               and then not Expander_Active
7202             then
7203                Iface_Typ :=
7204                  Find_Parameter_Type (Parent (First_Formal (Candidate)));
7205
7206                --  Def_Id is primitive of a protected type, declared
7207                --  inside the type, and the candidate is primitive of a
7208                --  limited or synchronized interface.
7209
7210                if In_Scope
7211                  and then Is_Protected_Type (Typ)
7212                  and then
7213                    (Is_Limited_Interface (Iface_Typ)
7214                       or else Is_Protected_Interface (Iface_Typ)
7215                       or else Is_Synchronized_Interface (Iface_Typ)
7216                       or else Is_Task_Interface (Iface_Typ))
7217                then
7218                   --  Must reword this message, comma before to in -gnatj
7219                   --  mode ???
7220
7221                   Error_Msg_NE
7222                     ("first formal of & must be of mode `OUT`, `IN OUT`"
7223                       & " or access-to-variable", Typ, Candidate);
7224                   Error_Msg_N
7225                     ("\to be overridden by protected procedure or entry "
7226                       & "(RM 9.4(11.9/2))", Typ);
7227                end if;
7228             end if;
7229
7230             Overridden_Subp := Candidate;
7231             return;
7232          end;
7233       end Check_Synchronized_Overriding;
7234
7235       ----------------------------
7236       -- Is_Private_Declaration --
7237       ----------------------------
7238
7239       function Is_Private_Declaration (E : Entity_Id) return Boolean is
7240          Priv_Decls : List_Id;
7241          Decl       : constant Node_Id := Unit_Declaration_Node (E);
7242
7243       begin
7244          if Is_Package_Or_Generic_Package (Current_Scope)
7245            and then In_Private_Part (Current_Scope)
7246          then
7247             Priv_Decls :=
7248               Private_Declarations (
7249                 Specification (Unit_Declaration_Node (Current_Scope)));
7250
7251             return In_Package_Body (Current_Scope)
7252               or else
7253                 (Is_List_Member (Decl)
7254                    and then List_Containing (Decl) = Priv_Decls)
7255               or else (Nkind (Parent (Decl)) = N_Package_Specification
7256                          and then not
7257                            Is_Compilation_Unit
7258                              (Defining_Entity (Parent (Decl)))
7259                          and then List_Containing (Parent (Parent (Decl)))
7260                                     = Priv_Decls);
7261          else
7262             return False;
7263          end if;
7264       end Is_Private_Declaration;
7265
7266       --------------------------
7267       -- Is_Overriding_Alias --
7268       --------------------------
7269
7270       function Is_Overriding_Alias
7271         (Old_E : Entity_Id;
7272          New_E : Entity_Id) return Boolean
7273       is
7274          AO : constant Entity_Id := Alias (Old_E);
7275          AN : constant Entity_Id := Alias (New_E);
7276
7277       begin
7278          return Scope (AO) /= Scope (AN)
7279            or else No (DTC_Entity (AO))
7280            or else No (DTC_Entity (AN))
7281            or else DT_Position (AO) = DT_Position (AN);
7282       end Is_Overriding_Alias;
7283
7284    --  Start of processing for New_Overloaded_Entity
7285
7286    begin
7287       --  We need to look for an entity that S may override. This must be a
7288       --  homonym in the current scope, so we look for the first homonym of
7289       --  S in the current scope as the starting point for the search.
7290
7291       E := Current_Entity_In_Scope (S);
7292
7293       --  If there is no homonym then this is definitely not overriding
7294
7295       if No (E) then
7296          Enter_Overloaded_Entity (S);
7297          Check_Dispatching_Operation (S, Empty);
7298          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
7299
7300          --  If subprogram has an explicit declaration, check whether it
7301          --  has an overriding indicator.
7302
7303          if Comes_From_Source (S) then
7304             Check_Synchronized_Overriding (S, Overridden_Subp);
7305             Check_Overriding_Indicator
7306               (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
7307          end if;
7308
7309       --  If there is a homonym that is not overloadable, then we have an
7310       --  error, except for the special cases checked explicitly below.
7311
7312       elsif not Is_Overloadable (E) then
7313
7314          --  Check for spurious conflict produced by a subprogram that has the
7315          --  same name as that of the enclosing generic package. The conflict
7316          --  occurs within an instance, between the subprogram and the renaming
7317          --  declaration for the package. After the subprogram, the package
7318          --  renaming declaration becomes hidden.
7319
7320          if Ekind (E) = E_Package
7321            and then Present (Renamed_Object (E))
7322            and then Renamed_Object (E) = Current_Scope
7323            and then Nkind (Parent (Renamed_Object (E))) =
7324                                                      N_Package_Specification
7325            and then Present (Generic_Parent (Parent (Renamed_Object (E))))
7326          then
7327             Set_Is_Hidden (E);
7328             Set_Is_Immediately_Visible (E, False);
7329             Enter_Overloaded_Entity (S);
7330             Set_Homonym (S, Homonym (E));
7331             Check_Dispatching_Operation (S, Empty);
7332             Check_Overriding_Indicator (S, Empty, Is_Primitive => False);
7333
7334          --  If the subprogram is implicit it is hidden by the previous
7335          --  declaration. However if it is dispatching, it must appear in the
7336          --  dispatch table anyway, because it can be dispatched to even if it
7337          --  cannot be called directly.
7338
7339          elsif Present (Alias (S))
7340            and then not Comes_From_Source (S)
7341          then
7342             Set_Scope (S, Current_Scope);
7343
7344             if Is_Dispatching_Operation (Alias (S)) then
7345                Check_Dispatching_Operation (S, Empty);
7346             end if;
7347
7348             return;
7349
7350          else
7351             Error_Msg_Sloc := Sloc (E);
7352
7353             --  Generate message, with useful additional warning if in generic
7354
7355             if Is_Generic_Unit (E) then
7356                Error_Msg_N ("previous generic unit cannot be overloaded", S);
7357                Error_Msg_N ("\& conflicts with declaration#", S);
7358             else
7359                Error_Msg_N ("& conflicts with declaration#", S);
7360             end if;
7361
7362             return;
7363          end if;
7364
7365       --  E exists and is overloadable
7366
7367       else
7368          --  Ada 2005 (AI-251): Derivation of abstract interface primitives
7369          --  need no check against the homonym chain. They are directly added
7370          --  to the list of primitive operations of Derived_Type.
7371
7372          if Ada_Version >= Ada_05
7373            and then Present (Derived_Type)
7374            and then Is_Dispatching_Operation (Alias (S))
7375            and then Present (Find_Dispatching_Type (Alias (S)))
7376            and then Is_Interface (Find_Dispatching_Type (Alias (S)))
7377          then
7378             goto Add_New_Entity;
7379          end if;
7380
7381          Check_Synchronized_Overriding (S, Overridden_Subp);
7382
7383          --  Loop through E and its homonyms to determine if any of them is
7384          --  the candidate for overriding by S.
7385
7386          while Present (E) loop
7387
7388             --  Definitely not interesting if not in the current scope
7389
7390             if Scope (E) /= Current_Scope then
7391                null;
7392
7393             --  Check if we have type conformance
7394
7395             elsif Type_Conformant (E, S) then
7396
7397                --  If the old and new entities have the same profile and one
7398                --  is not the body of the other, then this is an error, unless
7399                --  one of them is implicitly declared.
7400
7401                --  There are some cases when both can be implicit, for example
7402                --  when both a literal and a function that overrides it are
7403                --  inherited in a derivation, or when an inherited operation
7404                --  of a tagged full type overrides the inherited operation of
7405                --  a private extension. Ada 83 had a special rule for the
7406                --  literal case. In Ada95, the later implicit operation hides
7407                --  the former, and the literal is always the former. In the
7408                --  odd case where both are derived operations declared at the
7409                --  same point, both operations should be declared, and in that
7410                --  case we bypass the following test and proceed to the next
7411                --  part. This can only occur for certain obscure cases in
7412                --  instances, when an operation on a type derived from a formal
7413                --  private type does not override a homograph inherited from
7414                --  the actual. In subsequent derivations of such a type, the
7415                --  DT positions of these operations remain distinct, if they
7416                --  have been set.
7417
7418                if Present (Alias (S))
7419                  and then (No (Alias (E))
7420                             or else Comes_From_Source (E)
7421                             or else Is_Abstract_Subprogram (S)
7422                             or else
7423                               (Is_Dispatching_Operation (E)
7424                                  and then Is_Overriding_Alias (E, S)))
7425                  and then Ekind (E) /= E_Enumeration_Literal
7426                then
7427                   --  When an derived operation is overloaded it may be due to
7428                   --  the fact that the full view of a private extension
7429                   --  re-inherits. It has to be dealt with.
7430
7431                   if Is_Package_Or_Generic_Package (Current_Scope)
7432                     and then In_Private_Part (Current_Scope)
7433                   then
7434                      Check_Operation_From_Private_View (S, E);
7435                   end if;
7436
7437                   --  In any case the implicit operation remains hidden by
7438                   --  the existing declaration, which is overriding.
7439
7440                   Set_Is_Overriding_Operation (E);
7441
7442                   if Comes_From_Source (E) then
7443                      Check_Overriding_Indicator (E, S, Is_Primitive => False);
7444
7445                      --  Indicate that E overrides the operation from which
7446                      --  S is inherited.
7447
7448                      if Present (Alias (S)) then
7449                         Set_Overridden_Operation (E, Alias (S));
7450                      else
7451                         Set_Overridden_Operation (E, S);
7452                      end if;
7453                   end if;
7454
7455                   return;
7456
7457                --  Within an instance, the renaming declarations for actual
7458                --  subprograms may become ambiguous, but they do not hide each
7459                --  other.
7460
7461                elsif Ekind (E) /= E_Entry
7462                  and then not Comes_From_Source (E)
7463                  and then not Is_Generic_Instance (E)
7464                  and then (Present (Alias (E))
7465                             or else Is_Intrinsic_Subprogram (E))
7466                  and then (not In_Instance
7467                             or else No (Parent (E))
7468                             or else Nkind (Unit_Declaration_Node (E)) /=
7469                                       N_Subprogram_Renaming_Declaration)
7470                then
7471                   --  A subprogram child unit is not allowed to override an
7472                   --  inherited subprogram (10.1.1(20)).
7473
7474                   if Is_Child_Unit (S) then
7475                      Error_Msg_N
7476                        ("child unit overrides inherited subprogram in parent",
7477                         S);
7478                      return;
7479                   end if;
7480
7481                   if Is_Non_Overriding_Operation (E, S) then
7482                      Enter_Overloaded_Entity (S);
7483
7484                      if No (Derived_Type)
7485                        or else Is_Tagged_Type (Derived_Type)
7486                      then
7487                         Check_Dispatching_Operation (S, Empty);
7488                      end if;
7489
7490                      return;
7491                   end if;
7492
7493                   --  E is a derived operation or an internal operator which
7494                   --  is being overridden. Remove E from further visibility.
7495                   --  Furthermore, if E is a dispatching operation, it must be
7496                   --  replaced in the list of primitive operations of its type
7497                   --  (see Override_Dispatching_Operation).
7498
7499                   Overridden_Subp := E;
7500
7501                   declare
7502                      Prev : Entity_Id;
7503
7504                   begin
7505                      Prev := First_Entity (Current_Scope);
7506                      while Present (Prev)
7507                        and then Next_Entity (Prev) /= E
7508                      loop
7509                         Next_Entity (Prev);
7510                      end loop;
7511
7512                      --  It is possible for E to be in the current scope and
7513                      --  yet not in the entity chain. This can only occur in a
7514                      --  generic context where E is an implicit concatenation
7515                      --  in the formal part, because in a generic body the
7516                      --  entity chain starts with the formals.
7517
7518                      pragma Assert
7519                        (Present (Prev) or else Chars (E) = Name_Op_Concat);
7520
7521                      --  E must be removed both from the entity_list of the
7522                      --  current scope, and from the visibility chain
7523
7524                      if Debug_Flag_E then
7525                         Write_Str ("Override implicit operation ");
7526                         Write_Int (Int (E));
7527                         Write_Eol;
7528                      end if;
7529
7530                      --  If E is a predefined concatenation, it stands for four
7531                      --  different operations. As a result, a single explicit
7532                      --  declaration does not hide it. In a possible ambiguous
7533                      --  situation, Disambiguate chooses the user-defined op,
7534                      --  so it is correct to retain the previous internal one.
7535
7536                      if Chars (E) /= Name_Op_Concat
7537                        or else Ekind (E) /= E_Operator
7538                      then
7539                         --  For nondispatching derived operations that are
7540                         --  overridden by a subprogram declared in the private
7541                         --  part of a package, we retain the derived subprogram
7542                         --  but mark it as not immediately visible. If the
7543                         --  derived operation was declared in the visible part
7544                         --  then this ensures that it will still be visible
7545                         --  outside the package with the proper signature
7546                         --  (calls from outside must also be directed to this
7547                         --  version rather than the overriding one, unlike the
7548                         --  dispatching case). Calls from inside the package
7549                         --  will still resolve to the overriding subprogram
7550                         --  since the derived one is marked as not visible
7551                         --  within the package.
7552
7553                         --  If the private operation is dispatching, we achieve
7554                         --  the overriding by keeping the implicit operation
7555                         --  but setting its alias to be the overriding one. In
7556                         --  this fashion the proper body is executed in all
7557                         --  cases, but the original signature is used outside
7558                         --  of the package.
7559
7560                         --  If the overriding is not in the private part, we
7561                         --  remove the implicit operation altogether.
7562
7563                         if Is_Private_Declaration (S) then
7564                            if not Is_Dispatching_Operation (E) then
7565                               Set_Is_Immediately_Visible (E, False);
7566                            else
7567                               --  Work done in Override_Dispatching_Operation,
7568                               --  so nothing else need to be done here.
7569
7570                               null;
7571                            end if;
7572
7573                         else
7574                            --  Find predecessor of E in Homonym chain
7575
7576                            if E = Current_Entity (E) then
7577                               Prev_Vis := Empty;
7578                            else
7579                               Prev_Vis := Current_Entity (E);
7580                               while Homonym (Prev_Vis) /= E loop
7581                                  Prev_Vis := Homonym (Prev_Vis);
7582                               end loop;
7583                            end if;
7584
7585                            if Prev_Vis /= Empty then
7586
7587                               --  Skip E in the visibility chain
7588
7589                               Set_Homonym (Prev_Vis, Homonym (E));
7590
7591                            else
7592                               Set_Name_Entity_Id (Chars (E), Homonym (E));
7593                            end if;
7594
7595                            Set_Next_Entity (Prev, Next_Entity (E));
7596
7597                            if No (Next_Entity (Prev)) then
7598                               Set_Last_Entity (Current_Scope, Prev);
7599                            end if;
7600
7601                         end if;
7602                      end if;
7603
7604                      Enter_Overloaded_Entity (S);
7605                      Set_Is_Overriding_Operation (S);
7606                      Check_Overriding_Indicator (S, E, Is_Primitive => True);
7607
7608                      --  Indicate that S overrides the operation from which
7609                      --  E is inherited.
7610
7611                      if Comes_From_Source (S) then
7612                         if Present (Alias (E)) then
7613                            Set_Overridden_Operation (S, Alias (E));
7614                         else
7615                            Set_Overridden_Operation (S, E);
7616                         end if;
7617                      end if;
7618
7619                      if Is_Dispatching_Operation (E) then
7620
7621                         --  An overriding dispatching subprogram inherits the
7622                         --  convention of the overridden subprogram (by
7623                         --  AI-117).
7624
7625                         Set_Convention (S, Convention (E));
7626                         Check_Dispatching_Operation (S, E);
7627
7628                      else
7629                         Check_Dispatching_Operation (S, Empty);
7630                      end if;
7631
7632                      Check_For_Primitive_Subprogram
7633                        (Is_Primitive_Subp, Is_Overriding => True);
7634                      goto Check_Inequality;
7635                   end;
7636
7637                --  Apparent redeclarations in instances can occur when two
7638                --  formal types get the same actual type. The subprograms in
7639                --  in the instance are legal,  even if not callable from the
7640                --  outside. Calls from within are disambiguated elsewhere.
7641                --  For dispatching operations in the visible part, the usual
7642                --  rules apply, and operations with the same profile are not
7643                --  legal (B830001).
7644
7645                elsif (In_Instance_Visible_Part
7646                        and then not Is_Dispatching_Operation (E))
7647                  or else In_Instance_Not_Visible
7648                then
7649                   null;
7650
7651                --  Here we have a real error (identical profile)
7652
7653                else
7654                   Error_Msg_Sloc := Sloc (E);
7655
7656                   --  Avoid cascaded errors if the entity appears in
7657                   --  subsequent calls.
7658
7659                   Set_Scope (S, Current_Scope);
7660
7661                   --  Generate error, with extra useful warning for the case
7662                   --  of a generic instance with no completion.
7663
7664                   if Is_Generic_Instance (S)
7665                     and then not Has_Completion (E)
7666                   then
7667                      Error_Msg_N
7668                        ("instantiation cannot provide body for&", S);
7669                      Error_Msg_N ("\& conflicts with declaration#", S);
7670                   else
7671                      Error_Msg_N ("& conflicts with declaration#", S);
7672                   end if;
7673
7674                   return;
7675                end if;
7676
7677             else
7678                --  If one subprogram has an access parameter and the other
7679                --  a parameter of an access type, calls to either might be
7680                --  ambiguous. Verify that parameters match except for the
7681                --  access parameter.
7682
7683                if May_Hide_Profile then
7684                   declare
7685                      F1 : Entity_Id;
7686                      F2 : Entity_Id;
7687
7688                   begin
7689                      F1 := First_Formal (S);
7690                      F2 := First_Formal (E);
7691                      while Present (F1) and then Present (F2) loop
7692                         if Is_Access_Type (Etype (F1)) then
7693                            if not Is_Access_Type (Etype (F2))
7694                               or else not Conforming_Types
7695                                 (Designated_Type (Etype (F1)),
7696                                  Designated_Type (Etype (F2)),
7697                                  Type_Conformant)
7698                            then
7699                               May_Hide_Profile := False;
7700                            end if;
7701
7702                         elsif
7703                           not Conforming_Types
7704                             (Etype (F1), Etype (F2), Type_Conformant)
7705                         then
7706                            May_Hide_Profile := False;
7707                         end if;
7708
7709                         Next_Formal (F1);
7710                         Next_Formal (F2);
7711                      end loop;
7712
7713                      if May_Hide_Profile
7714                        and then No (F1)
7715                        and then No (F2)
7716                      then
7717                         Error_Msg_NE ("calls to& may be ambiguous?", S, S);
7718                      end if;
7719                   end;
7720                end if;
7721             end if;
7722
7723             E := Homonym (E);
7724          end loop;
7725
7726          <<Add_New_Entity>>
7727
7728          --  On exit, we know that S is a new entity
7729
7730          Enter_Overloaded_Entity (S);
7731          Check_For_Primitive_Subprogram (Is_Primitive_Subp);
7732          Check_Overriding_Indicator
7733            (S, Overridden_Subp, Is_Primitive => Is_Primitive_Subp);
7734
7735          --  If S is a derived operation for an untagged type then by
7736          --  definition it's not a dispatching operation (even if the parent
7737          --  operation was dispatching), so we don't call
7738          --  Check_Dispatching_Operation in that case.
7739
7740          if No (Derived_Type)
7741            or else Is_Tagged_Type (Derived_Type)
7742          then
7743             Check_Dispatching_Operation (S, Empty);
7744          end if;
7745       end if;
7746
7747       --  If this is a user-defined equality operator that is not a derived
7748       --  subprogram, create the corresponding inequality. If the operation is
7749       --  dispatching, the expansion is done elsewhere, and we do not create
7750       --  an explicit inequality operation.
7751
7752       <<Check_Inequality>>
7753          if Chars (S) = Name_Op_Eq
7754            and then Etype (S) = Standard_Boolean
7755            and then Present (Parent (S))
7756            and then not Is_Dispatching_Operation (S)
7757          then
7758             Make_Inequality_Operator (S);
7759          end if;
7760    end New_Overloaded_Entity;
7761
7762    ---------------------
7763    -- Process_Formals --
7764    ---------------------
7765
7766    procedure Process_Formals
7767      (T           : List_Id;
7768       Related_Nod : Node_Id)
7769    is
7770       Param_Spec  : Node_Id;
7771       Formal      : Entity_Id;
7772       Formal_Type : Entity_Id;
7773       Default     : Node_Id;
7774       Ptype       : Entity_Id;
7775
7776       Num_Out_Params  : Nat       := 0;
7777       First_Out_Param : Entity_Id := Empty;
7778       --  Used for setting Is_Only_Out_Parameter
7779
7780       function Is_Class_Wide_Default (D : Node_Id) return Boolean;
7781       --  Check whether the default has a class-wide type. After analysis the
7782       --  default has the type of the formal, so we must also check explicitly
7783       --  for an access attribute.
7784
7785       ---------------------------
7786       -- Is_Class_Wide_Default --
7787       ---------------------------
7788
7789       function Is_Class_Wide_Default (D : Node_Id) return Boolean is
7790       begin
7791          return Is_Class_Wide_Type (Designated_Type (Etype (D)))
7792            or else (Nkind (D) =  N_Attribute_Reference
7793                       and then Attribute_Name (D) = Name_Access
7794                       and then Is_Class_Wide_Type (Etype (Prefix (D))));
7795       end Is_Class_Wide_Default;
7796
7797    --  Start of processing for Process_Formals
7798
7799    begin
7800       --  In order to prevent premature use of the formals in the same formal
7801       --  part, the Ekind is left undefined until all default expressions are
7802       --  analyzed. The Ekind is established in a separate loop at the end.
7803
7804       Param_Spec := First (T);
7805       while Present (Param_Spec) loop
7806          Formal := Defining_Identifier (Param_Spec);
7807          Set_Never_Set_In_Source (Formal, True);
7808          Enter_Name (Formal);
7809
7810          --  Case of ordinary parameters
7811
7812          if Nkind (Parameter_Type (Param_Spec)) /= N_Access_Definition then
7813             Find_Type (Parameter_Type (Param_Spec));
7814             Ptype := Parameter_Type (Param_Spec);
7815
7816             if Ptype = Error then
7817                goto Continue;
7818             end if;
7819
7820             Formal_Type := Entity (Ptype);
7821
7822             if Is_Incomplete_Type (Formal_Type)
7823               or else
7824                (Is_Class_Wide_Type (Formal_Type)
7825                   and then Is_Incomplete_Type (Root_Type (Formal_Type)))
7826             then
7827                --  Ada 2005 (AI-326): Tagged incomplete types allowed in
7828                --  primitive operations, as long as their completion is
7829                --  in the same declarative part. If in the private part
7830                --  this means that the type cannot be a Taft-amendment type.
7831                --  Check is done on package exit. For access to subprograms,
7832                --  the use is legal for Taft-amendment types.
7833
7834                if Is_Tagged_Type (Formal_Type) then
7835                   if Ekind (Scope (Current_Scope)) = E_Package
7836                     and then In_Private_Part (Scope (Current_Scope))
7837                     and then not From_With_Type (Formal_Type)
7838                     and then not Is_Class_Wide_Type (Formal_Type)
7839                   then
7840                      if not Nkind_In
7841                        (Parent (T), N_Access_Function_Definition,
7842                                     N_Access_Procedure_Definition)
7843                      then
7844                         Append_Elmt
7845                           (Current_Scope,
7846                              Private_Dependents (Base_Type (Formal_Type)));
7847                      end if;
7848                   end if;
7849
7850                --  Special handling of Value_Type for CIL case
7851
7852                elsif Is_Value_Type (Formal_Type) then
7853                   null;
7854
7855                elsif not Nkind_In (Parent (T), N_Access_Function_Definition,
7856                                                N_Access_Procedure_Definition)
7857                then
7858                   Error_Msg_NE
7859                     ("invalid use of incomplete type&",
7860                        Param_Spec, Formal_Type);
7861
7862                   --  Further checks on the legality of incomplete types
7863                   --  in formal parts must be delayed until the freeze point
7864                   --  of the enclosing subprogram or access to subprogram.
7865                end if;
7866
7867             elsif Ekind (Formal_Type) = E_Void then
7868                Error_Msg_NE ("premature use of&",
7869                  Parameter_Type (Param_Spec), Formal_Type);
7870             end if;
7871
7872             --  Ada 2005 (AI-231): Create and decorate an internal subtype
7873             --  declaration corresponding to the null-excluding type of the
7874             --  formal in the enclosing scope. Finally, replace the parameter
7875             --  type of the formal with the internal subtype.
7876
7877             if Ada_Version >= Ada_05
7878               and then Null_Exclusion_Present (Param_Spec)
7879             then
7880                if not Is_Access_Type (Formal_Type) then
7881                   Error_Msg_N
7882                     ("`NOT NULL` allowed only for an access type", Param_Spec);
7883
7884                else
7885                   if Can_Never_Be_Null (Formal_Type)
7886                     and then Comes_From_Source (Related_Nod)
7887                   then
7888                      Error_Msg_NE
7889                        ("`NOT NULL` not allowed (& already excludes null)",
7890                         Param_Spec,
7891                         Formal_Type);
7892                   end if;
7893
7894                   Formal_Type :=
7895                     Create_Null_Excluding_Itype
7896                       (T           => Formal_Type,
7897                        Related_Nod => Related_Nod,
7898                        Scope_Id    => Scope (Current_Scope));
7899
7900                   --  If the designated type of the itype is an itype we
7901                   --  decorate it with the Has_Delayed_Freeze attribute to
7902                   --  avoid problems with the backend.
7903
7904                   --  Example:
7905                   --     type T is access procedure;
7906                   --     procedure Op (O : not null T);
7907
7908                   if Is_Itype (Directly_Designated_Type (Formal_Type)) then
7909                      Set_Has_Delayed_Freeze (Formal_Type);
7910                   end if;
7911                end if;
7912             end if;
7913
7914          --  An access formal type
7915
7916          else
7917             Formal_Type :=
7918               Access_Definition (Related_Nod, Parameter_Type (Param_Spec));
7919
7920             --  No need to continue if we already notified errors
7921
7922             if not Present (Formal_Type) then
7923                return;
7924             end if;
7925
7926             --  Ada 2005 (AI-254)
7927
7928             declare
7929                AD : constant Node_Id :=
7930                       Access_To_Subprogram_Definition
7931                         (Parameter_Type (Param_Spec));
7932             begin
7933                if Present (AD) and then Protected_Present (AD) then
7934                   Formal_Type :=
7935                     Replace_Anonymous_Access_To_Protected_Subprogram
7936                       (Param_Spec);
7937                end if;
7938             end;
7939          end if;
7940
7941          Set_Etype (Formal, Formal_Type);
7942          Default := Expression (Param_Spec);
7943
7944          if Present (Default) then
7945             if Out_Present (Param_Spec) then
7946                Error_Msg_N
7947                  ("default initialization only allowed for IN parameters",
7948                   Param_Spec);
7949             end if;
7950
7951             --  Do the special preanalysis of the expression (see section on
7952             --  "Handling of Default Expressions" in the spec of package Sem).
7953
7954             Preanalyze_Spec_Expression (Default, Formal_Type);
7955
7956             --  An access to constant cannot be the default for
7957             --  an access parameter that is an access to variable.
7958
7959             if Ekind (Formal_Type) = E_Anonymous_Access_Type
7960               and then not Is_Access_Constant (Formal_Type)
7961               and then Is_Access_Type (Etype (Default))
7962               and then Is_Access_Constant (Etype (Default))
7963             then
7964                Error_Msg_N
7965                  ("formal that is access to variable cannot be initialized " &
7966                     "with an access-to-constant expression", Default);
7967             end if;
7968
7969             --  Check that the designated type of an access parameter's default
7970             --  is not a class-wide type unless the parameter's designated type
7971             --  is also class-wide.
7972
7973             if Ekind (Formal_Type) = E_Anonymous_Access_Type
7974               and then not From_With_Type (Formal_Type)
7975               and then Is_Class_Wide_Default (Default)
7976               and then not Is_Class_Wide_Type (Designated_Type (Formal_Type))
7977             then
7978                Error_Msg_N
7979                  ("access to class-wide expression not allowed here", Default);
7980             end if;
7981          end if;
7982
7983          --  Ada 2005 (AI-231): Static checks
7984
7985          if Ada_Version >= Ada_05
7986            and then Is_Access_Type (Etype (Formal))
7987            and then Can_Never_Be_Null (Etype (Formal))
7988          then
7989             Null_Exclusion_Static_Checks (Param_Spec);
7990          end if;
7991
7992       <<Continue>>
7993          Next (Param_Spec);
7994       end loop;
7995
7996       --  If this is the formal part of a function specification, analyze the
7997       --  subtype mark in the context where the formals are visible but not
7998       --  yet usable, and may hide outer homographs.
7999
8000       if Nkind (Related_Nod) = N_Function_Specification then
8001          Analyze_Return_Type (Related_Nod);
8002       end if;
8003
8004       --  Now set the kind (mode) of each formal
8005
8006       Param_Spec := First (T);
8007
8008       while Present (Param_Spec) loop
8009          Formal := Defining_Identifier (Param_Spec);
8010          Set_Formal_Mode (Formal);
8011
8012          if Ekind (Formal) = E_In_Parameter then
8013             Set_Default_Value (Formal, Expression (Param_Spec));
8014
8015             if Present (Expression (Param_Spec)) then
8016                Default :=  Expression (Param_Spec);
8017
8018                if Is_Scalar_Type (Etype (Default)) then
8019                   if Nkind
8020                        (Parameter_Type (Param_Spec)) /= N_Access_Definition
8021                   then
8022                      Formal_Type := Entity (Parameter_Type (Param_Spec));
8023
8024                   else
8025                      Formal_Type := Access_Definition
8026                        (Related_Nod, Parameter_Type (Param_Spec));
8027                   end if;
8028
8029                   Apply_Scalar_Range_Check (Default, Formal_Type);
8030                end if;
8031             end if;
8032
8033          elsif Ekind (Formal) = E_Out_Parameter then
8034             Num_Out_Params := Num_Out_Params + 1;
8035
8036             if Num_Out_Params = 1 then
8037                First_Out_Param := Formal;
8038             end if;
8039
8040          elsif Ekind (Formal) = E_In_Out_Parameter then
8041             Num_Out_Params := Num_Out_Params + 1;
8042          end if;
8043
8044          Next (Param_Spec);
8045       end loop;
8046
8047       if Present (First_Out_Param) and then Num_Out_Params = 1 then
8048          Set_Is_Only_Out_Parameter (First_Out_Param);
8049       end if;
8050    end Process_Formals;
8051
8052    ------------------
8053    -- Process_PPCs --
8054    ------------------
8055
8056    procedure Process_PPCs
8057      (N       : Node_Id;
8058       Spec_Id : Entity_Id;
8059       Body_Id : Entity_Id)
8060    is
8061       Loc   : constant Source_Ptr := Sloc (N);
8062       Prag  : Node_Id;
8063       Plist : List_Id := No_List;
8064       Subp  : Entity_Id;
8065       Parms : List_Id;
8066
8067       function Grab_PPC (Nam : Name_Id) return Node_Id;
8068       --  Prag contains an analyzed precondition or postcondition pragma.
8069       --  This function copies the pragma, changes it to the corresponding
8070       --  Check pragma and returns the Check pragma as the result. The
8071       --  argument Nam is either Name_Precondition or Name_Postcondition.
8072
8073       --------------
8074       -- Grab_PPC --
8075       --------------
8076
8077       function Grab_PPC (Nam : Name_Id) return Node_Id is
8078          CP : constant Node_Id := New_Copy_Tree (Prag);
8079
8080       begin
8081          --  Set Analyzed to false, since we want to reanalyze the check
8082          --  procedure. Note that it is only at the outer level that we
8083          --  do this fiddling, for the spec cases, the already preanalyzed
8084          --  parameters are not affected.
8085
8086          --  For a postcondition pragma within a generic, preserve the pragma
8087          --  for later expansion.
8088
8089          Set_Analyzed (CP, False);
8090
8091          if Nam = Name_Postcondition
8092            and then not Expander_Active
8093          then
8094             return CP;
8095          end if;
8096
8097          --  Change pragma into corresponding pragma Check
8098
8099          Prepend_To (Pragma_Argument_Associations (CP),
8100            Make_Pragma_Argument_Association (Sloc (Prag),
8101              Expression =>
8102                Make_Identifier (Loc,
8103                  Chars => Nam)));
8104          Set_Pragma_Identifier (CP,
8105            Make_Identifier (Sloc (Prag),
8106              Chars => Name_Check));
8107
8108          return CP;
8109       end Grab_PPC;
8110
8111    --  Start of processing for Process_PPCs
8112
8113    begin
8114       --  Nothing to do if we are not generating code
8115
8116       if Operating_Mode /= Generate_Code then
8117          return;
8118       end if;
8119
8120       --  Grab preconditions from spec
8121
8122       if Present (Spec_Id) then
8123
8124          --  Loop through PPC pragmas from spec. Note that preconditions from
8125          --  the body will be analyzed and converted when we scan the body
8126          --  declarations below.
8127
8128          Prag := Spec_PPC_List (Spec_Id);
8129          while Present (Prag) loop
8130             if Pragma_Name (Prag) = Name_Precondition
8131               and then PPC_Enabled (Prag)
8132             then
8133                --  Add pragma Check at the start of the declarations of N.
8134                --  Note that this processing reverses the order of the list,
8135                --  which is what we want since new entries were chained to
8136                --  the head of the list.
8137
8138                Prepend (Grab_PPC (Name_Precondition), Declarations (N));
8139             end if;
8140
8141             Prag := Next_Pragma (Prag);
8142          end loop;
8143       end if;
8144
8145       --  Build postconditions procedure if needed and prepend the following
8146       --  declaration to the start of the declarations for the subprogram.
8147
8148       --     procedure _postconditions [(_Result : resulttype)] is
8149       --     begin
8150       --        pragma Check (Postcondition, condition [,message]);
8151       --        pragma Check (Postcondition, condition [,message]);
8152       --        ...
8153       --     end;
8154
8155       --  First we deal with the postconditions in the body
8156
8157       if Is_Non_Empty_List (Declarations (N)) then
8158
8159          --  Loop through declarations
8160
8161          Prag := First (Declarations (N));
8162          while Present (Prag) loop
8163             if Nkind (Prag) = N_Pragma then
8164
8165                --  If pragma, capture if enabled postcondition, else ignore
8166
8167                if Pragma_Name (Prag) = Name_Postcondition
8168                  and then Check_Enabled (Name_Postcondition)
8169                then
8170                   if Plist = No_List then
8171                      Plist := Empty_List;
8172                   end if;
8173
8174                   Analyze (Prag);
8175
8176                   --  If expansion is disabled, as in a generic unit,
8177                   --  save pragma for later expansion.
8178
8179                   if not Expander_Active then
8180                      Prepend (Grab_PPC (Name_Postcondition), Declarations (N));
8181                   else
8182                      Append (Grab_PPC (Name_Postcondition), Plist);
8183                   end if;
8184                end if;
8185
8186                Next (Prag);
8187
8188             --  Not a pragma, if comes from source, then end scan
8189
8190             elsif Comes_From_Source (Prag) then
8191                exit;
8192
8193             --  Skip stuff not coming from source
8194
8195             else
8196                Next (Prag);
8197             end if;
8198          end loop;
8199       end if;
8200
8201       --  Now deal with any postconditions from the spec
8202
8203       if Present (Spec_Id) then
8204
8205          --  Loop through PPC pragmas from spec
8206
8207          Prag := Spec_PPC_List (Spec_Id);
8208          while Present (Prag) loop
8209             if Pragma_Name (Prag) = Name_Postcondition
8210               and then PPC_Enabled (Prag)
8211             then
8212                if Plist = No_List then
8213                   Plist := Empty_List;
8214                end if;
8215
8216                if not Expander_Active then
8217                   Prepend (Grab_PPC (Name_Postcondition), Declarations (N));
8218                else
8219                   Append (Grab_PPC (Name_Postcondition), Plist);
8220                end if;
8221             end if;
8222
8223             Prag := Next_Pragma (Prag);
8224          end loop;
8225       end if;
8226
8227       --  If we had any postconditions and expansion is enabled, build
8228       --  the _Postconditions procedure.
8229
8230       if Present (Plist)
8231         and then Expander_Active
8232       then
8233          Subp := Defining_Entity (N);
8234
8235          if Etype (Subp) /= Standard_Void_Type then
8236             Parms := New_List (
8237               Make_Parameter_Specification (Loc,
8238                 Defining_Identifier =>
8239                   Make_Defining_Identifier (Loc,
8240                     Chars => Name_uResult),
8241                 Parameter_Type => New_Occurrence_Of (Etype (Subp), Loc)));
8242          else
8243             Parms := No_List;
8244          end if;
8245
8246          declare
8247             Post_Proc : constant Entity_Id :=
8248                    Make_Defining_Identifier (Loc,
8249                      Chars => Name_uPostconditions);
8250             --  The entity for the _Postconditions procedure
8251          begin
8252             Prepend_To (Declarations (N),
8253               Make_Subprogram_Body (Loc,
8254                 Specification =>
8255                   Make_Procedure_Specification (Loc,
8256                     Defining_Unit_Name => Post_Proc,
8257                     Parameter_Specifications => Parms),
8258
8259                 Declarations => Empty_List,
8260
8261                 Handled_Statement_Sequence =>
8262                   Make_Handled_Sequence_Of_Statements (Loc,
8263                     Statements => Plist)));
8264
8265             --  If this is a procedure, set the Postcondition_Proc attribute
8266
8267             if Etype (Subp) = Standard_Void_Type then
8268                Set_Postcondition_Proc (Spec_Id, Post_Proc);
8269             end if;
8270          end;
8271
8272          if Present (Spec_Id) then
8273             Set_Has_Postconditions (Spec_Id);
8274          else
8275             Set_Has_Postconditions (Body_Id);
8276          end if;
8277       end if;
8278    end Process_PPCs;
8279
8280    ----------------------------
8281    -- Reference_Body_Formals --
8282    ----------------------------
8283
8284    procedure Reference_Body_Formals (Spec : Entity_Id; Bod : Entity_Id) is
8285       Fs : Entity_Id;
8286       Fb : Entity_Id;
8287
8288    begin
8289       if Error_Posted (Spec) then
8290          return;
8291       end if;
8292
8293       --  Iterate over both lists. They may be of different lengths if the two
8294       --  specs are not conformant.
8295
8296       Fs := First_Formal (Spec);
8297       Fb := First_Formal (Bod);
8298       while Present (Fs) and then Present (Fb) loop
8299          Generate_Reference (Fs, Fb, 'b');
8300
8301          if Style_Check then
8302             Style.Check_Identifier (Fb, Fs);
8303          end if;
8304
8305          Set_Spec_Entity (Fb, Fs);
8306          Set_Referenced (Fs, False);
8307          Next_Formal (Fs);
8308          Next_Formal (Fb);
8309       end loop;
8310    end Reference_Body_Formals;
8311
8312    -------------------------
8313    -- Set_Actual_Subtypes --
8314    -------------------------
8315
8316    procedure Set_Actual_Subtypes (N : Node_Id; Subp : Entity_Id) is
8317       Loc            : constant Source_Ptr := Sloc (N);
8318       Decl           : Node_Id;
8319       Formal         : Entity_Id;
8320       T              : Entity_Id;
8321       First_Stmt     : Node_Id := Empty;
8322       AS_Needed      : Boolean;
8323
8324    begin
8325       --  If this is an empty initialization procedure, no need to create
8326       --  actual subtypes (small optimization).
8327
8328       if Ekind (Subp) = E_Procedure
8329         and then Is_Null_Init_Proc (Subp)
8330       then
8331          return;
8332       end if;
8333
8334       Formal := First_Formal (Subp);
8335       while Present (Formal) loop
8336          T := Etype (Formal);
8337
8338          --  We never need an actual subtype for a constrained formal
8339
8340          if Is_Constrained (T) then
8341             AS_Needed := False;
8342
8343          --  If we have unknown discriminants, then we do not need an actual
8344          --  subtype, or more accurately we cannot figure it out! Note that
8345          --  all class-wide types have unknown discriminants.
8346
8347          elsif Has_Unknown_Discriminants (T) then
8348             AS_Needed := False;
8349
8350          --  At this stage we have an unconstrained type that may need an
8351          --  actual subtype. For sure the actual subtype is needed if we have
8352          --  an unconstrained array type.
8353
8354          elsif Is_Array_Type (T) then
8355             AS_Needed := True;
8356
8357          --  The only other case needing an actual subtype is an unconstrained
8358          --  record type which is an IN parameter (we cannot generate actual
8359          --  subtypes for the OUT or IN OUT case, since an assignment can
8360          --  change the discriminant values. However we exclude the case of
8361          --  initialization procedures, since discriminants are handled very
8362          --  specially in this context, see the section entitled "Handling of
8363          --  Discriminants" in Einfo.
8364
8365          --  We also exclude the case of Discrim_SO_Functions (functions used
8366          --  in front end layout mode for size/offset values), since in such
8367          --  functions only discriminants are referenced, and not only are such
8368          --  subtypes not needed, but they cannot always be generated, because
8369          --  of order of elaboration issues.
8370
8371          elsif Is_Record_Type (T)
8372            and then Ekind (Formal) = E_In_Parameter
8373            and then Chars (Formal) /= Name_uInit
8374            and then not Is_Unchecked_Union (T)
8375            and then not Is_Discrim_SO_Function (Subp)
8376          then
8377             AS_Needed := True;
8378
8379          --  All other cases do not need an actual subtype
8380
8381          else
8382             AS_Needed := False;
8383          end if;
8384
8385          --  Generate actual subtypes for unconstrained arrays and
8386          --  unconstrained discriminated records.
8387
8388          if AS_Needed then
8389             if Nkind (N) = N_Accept_Statement then
8390
8391                --  If expansion is active, The formal is replaced by a local
8392                --  variable that renames the corresponding entry of the
8393                --  parameter block, and it is this local variable that may
8394                --  require an actual subtype.
8395
8396                if Expander_Active then
8397                   Decl := Build_Actual_Subtype (T, Renamed_Object (Formal));
8398                else
8399                   Decl := Build_Actual_Subtype (T, Formal);
8400                end if;
8401
8402                if Present (Handled_Statement_Sequence (N)) then
8403                   First_Stmt :=
8404                     First (Statements (Handled_Statement_Sequence (N)));
8405                   Prepend (Decl, Statements (Handled_Statement_Sequence (N)));
8406                   Mark_Rewrite_Insertion (Decl);
8407                else
8408                   --  If the accept statement has no body, there will be no
8409                   --  reference to the actuals, so no need to compute actual
8410                   --  subtypes.
8411
8412                   return;
8413                end if;
8414
8415             else
8416                Decl := Build_Actual_Subtype (T, Formal);
8417                Prepend (Decl, Declarations (N));
8418                Mark_Rewrite_Insertion (Decl);
8419             end if;
8420
8421             --  The declaration uses the bounds of an existing object, and
8422             --  therefore needs no constraint checks.
8423
8424             Analyze (Decl, Suppress => All_Checks);
8425
8426             --  We need to freeze manually the generated type when it is
8427             --  inserted anywhere else than in a declarative part.
8428
8429             if Present (First_Stmt) then
8430                Insert_List_Before_And_Analyze (First_Stmt,
8431                  Freeze_Entity (Defining_Identifier (Decl), Loc));
8432             end if;
8433
8434             if Nkind (N) = N_Accept_Statement
8435               and then Expander_Active
8436             then
8437                Set_Actual_Subtype (Renamed_Object (Formal),
8438                  Defining_Identifier (Decl));
8439             else
8440                Set_Actual_Subtype (Formal, Defining_Identifier (Decl));
8441             end if;
8442          end if;
8443
8444          Next_Formal (Formal);
8445       end loop;
8446    end Set_Actual_Subtypes;
8447
8448    ---------------------
8449    -- Set_Formal_Mode --
8450    ---------------------
8451
8452    procedure Set_Formal_Mode (Formal_Id : Entity_Id) is
8453       Spec : constant Node_Id := Parent (Formal_Id);
8454
8455    begin
8456       --  Note: we set Is_Known_Valid for IN parameters and IN OUT parameters
8457       --  since we ensure that corresponding actuals are always valid at the
8458       --  point of the call.
8459
8460       if Out_Present (Spec) then
8461          if Ekind (Scope (Formal_Id)) = E_Function
8462            or else Ekind (Scope (Formal_Id)) = E_Generic_Function
8463          then
8464             Error_Msg_N ("functions can only have IN parameters", Spec);
8465             Set_Ekind (Formal_Id, E_In_Parameter);
8466
8467          elsif In_Present (Spec) then
8468             Set_Ekind (Formal_Id, E_In_Out_Parameter);
8469
8470          else
8471             Set_Ekind               (Formal_Id, E_Out_Parameter);
8472             Set_Never_Set_In_Source (Formal_Id, True);
8473             Set_Is_True_Constant    (Formal_Id, False);
8474             Set_Current_Value       (Formal_Id, Empty);
8475          end if;
8476
8477       else
8478          Set_Ekind (Formal_Id, E_In_Parameter);
8479       end if;
8480
8481       --  Set Is_Known_Non_Null for access parameters since the language
8482       --  guarantees that access parameters are always non-null. We also set
8483       --  Can_Never_Be_Null, since there is no way to change the value.
8484
8485       if Nkind (Parameter_Type (Spec)) = N_Access_Definition then
8486
8487          --  Ada 2005 (AI-231): In Ada95, access parameters are always non-
8488          --  null; In Ada 2005, only if then null_exclusion is explicit.
8489
8490          if Ada_Version < Ada_05
8491            or else Can_Never_Be_Null (Etype (Formal_Id))
8492          then
8493             Set_Is_Known_Non_Null (Formal_Id);
8494             Set_Can_Never_Be_Null (Formal_Id);
8495          end if;
8496
8497       --  Ada 2005 (AI-231): Null-exclusion access subtype
8498
8499       elsif Is_Access_Type (Etype (Formal_Id))
8500         and then Can_Never_Be_Null (Etype (Formal_Id))
8501       then
8502          Set_Is_Known_Non_Null (Formal_Id);
8503       end if;
8504
8505       Set_Mechanism (Formal_Id, Default_Mechanism);
8506       Set_Formal_Validity (Formal_Id);
8507    end Set_Formal_Mode;
8508
8509    -------------------------
8510    -- Set_Formal_Validity --
8511    -------------------------
8512
8513    procedure Set_Formal_Validity (Formal_Id : Entity_Id) is
8514    begin
8515       --  If no validity checking, then we cannot assume anything about the
8516       --  validity of parameters, since we do not know there is any checking
8517       --  of the validity on the call side.
8518
8519       if not Validity_Checks_On then
8520          return;
8521
8522       --  If validity checking for parameters is enabled, this means we are
8523       --  not supposed to make any assumptions about argument values.
8524
8525       elsif Validity_Check_Parameters then
8526          return;
8527
8528       --  If we are checking in parameters, we will assume that the caller is
8529       --  also checking parameters, so we can assume the parameter is valid.
8530
8531       elsif Ekind (Formal_Id) = E_In_Parameter
8532         and then Validity_Check_In_Params
8533       then
8534          Set_Is_Known_Valid (Formal_Id, True);
8535
8536       --  Similar treatment for IN OUT parameters
8537
8538       elsif Ekind (Formal_Id) = E_In_Out_Parameter
8539         and then Validity_Check_In_Out_Params
8540       then
8541          Set_Is_Known_Valid (Formal_Id, True);
8542       end if;
8543    end Set_Formal_Validity;
8544
8545    ------------------------
8546    -- Subtype_Conformant --
8547    ------------------------
8548
8549    function Subtype_Conformant
8550      (New_Id                   : Entity_Id;
8551       Old_Id                   : Entity_Id;
8552       Skip_Controlling_Formals : Boolean := False) return Boolean
8553    is
8554       Result : Boolean;
8555    begin
8556       Check_Conformance (New_Id, Old_Id, Subtype_Conformant, False, Result,
8557         Skip_Controlling_Formals => Skip_Controlling_Formals);
8558       return Result;
8559    end Subtype_Conformant;
8560
8561    ---------------------
8562    -- Type_Conformant --
8563    ---------------------
8564
8565    function Type_Conformant
8566      (New_Id                   : Entity_Id;
8567       Old_Id                   : Entity_Id;
8568       Skip_Controlling_Formals : Boolean := False) return Boolean
8569    is
8570       Result : Boolean;
8571    begin
8572       May_Hide_Profile := False;
8573
8574       Check_Conformance
8575         (New_Id, Old_Id, Type_Conformant, False, Result,
8576          Skip_Controlling_Formals => Skip_Controlling_Formals);
8577       return Result;
8578    end Type_Conformant;
8579
8580    -------------------------------
8581    -- Valid_Operator_Definition --
8582    -------------------------------
8583
8584    procedure Valid_Operator_Definition (Designator : Entity_Id) is
8585       N    : Integer := 0;
8586       F    : Entity_Id;
8587       Id   : constant Name_Id := Chars (Designator);
8588       N_OK : Boolean;
8589
8590    begin
8591       F := First_Formal (Designator);
8592       while Present (F) loop
8593          N := N + 1;
8594
8595          if Present (Default_Value (F)) then
8596             Error_Msg_N
8597               ("default values not allowed for operator parameters",
8598                Parent (F));
8599          end if;
8600
8601          Next_Formal (F);
8602       end loop;
8603
8604       --  Verify that user-defined operators have proper number of arguments
8605       --  First case of operators which can only be unary
8606
8607       if Id = Name_Op_Not
8608         or else Id = Name_Op_Abs
8609       then
8610          N_OK := (N = 1);
8611
8612       --  Case of operators which can be unary or binary
8613
8614       elsif Id = Name_Op_Add
8615         or Id = Name_Op_Subtract
8616       then
8617          N_OK := (N in 1 .. 2);
8618
8619       --  All other operators can only be binary
8620
8621       else
8622          N_OK := (N = 2);
8623       end if;
8624
8625       if not N_OK then
8626          Error_Msg_N
8627            ("incorrect number of arguments for operator", Designator);
8628       end if;
8629
8630       if Id = Name_Op_Ne
8631         and then Base_Type (Etype (Designator)) = Standard_Boolean
8632         and then not Is_Intrinsic_Subprogram (Designator)
8633       then
8634          Error_Msg_N
8635             ("explicit definition of inequality not allowed", Designator);
8636       end if;
8637    end Valid_Operator_Definition;
8638
8639 end Sem_Ch6;