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