OSDN Git Service

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