OSDN Git Service

2011-09-05 Gary Dismukes <dismukes@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch6.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ 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 Errout;   use Errout;
31 with Elists;   use Elists;
32 with Exp_Atag; use Exp_Atag;
33 with Exp_Ch2;  use Exp_Ch2;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch7;  use Exp_Ch7;
36 with Exp_Ch9;  use Exp_Ch9;
37 with Exp_Dbug; use Exp_Dbug;
38 with Exp_Disp; use Exp_Disp;
39 with Exp_Dist; use Exp_Dist;
40 with Exp_Intr; use Exp_Intr;
41 with Exp_Pakd; use Exp_Pakd;
42 with Exp_Tss;  use Exp_Tss;
43 with Exp_Util; use Exp_Util;
44 with Exp_VFpt; use Exp_VFpt;
45 with Fname;    use Fname;
46 with Freeze;   use Freeze;
47 with Inline;   use Inline;
48 with Lib;      use Lib;
49 with Namet;    use Namet;
50 with Nlists;   use Nlists;
51 with Nmake;    use Nmake;
52 with Opt;      use Opt;
53 with Restrict; use Restrict;
54 with Rident;   use Rident;
55 with Rtsfind;  use Rtsfind;
56 with Sem;      use Sem;
57 with Sem_Aux;  use Sem_Aux;
58 with Sem_Ch6;  use Sem_Ch6;
59 with Sem_Ch8;  use Sem_Ch8;
60 with Sem_Ch12; use Sem_Ch12;
61 with Sem_Ch13; use Sem_Ch13;
62 with Sem_Eval; use Sem_Eval;
63 with Sem_Disp; use Sem_Disp;
64 with Sem_Dist; use Sem_Dist;
65 with Sem_Mech; use Sem_Mech;
66 with Sem_Res;  use Sem_Res;
67 with Sem_SCIL; use Sem_SCIL;
68 with Sem_Util; use Sem_Util;
69 with Sinfo;    use Sinfo;
70 with Snames;   use Snames;
71 with Stand;    use Stand;
72 with Targparm; use Targparm;
73 with Tbuild;   use Tbuild;
74 with Uintp;    use Uintp;
75 with Validsw;  use Validsw;
76
77 package body Exp_Ch6 is
78
79    -----------------------
80    -- Local Subprograms --
81    -----------------------
82
83    procedure Add_Access_Actual_To_Build_In_Place_Call
84      (Function_Call : Node_Id;
85       Function_Id   : Entity_Id;
86       Return_Object : Node_Id;
87       Is_Access     : Boolean := False);
88    --  Ada 2005 (AI-318-02): Apply the Unrestricted_Access attribute to the
89    --  object name given by Return_Object and add the attribute to the end of
90    --  the actual parameter list associated with the build-in-place function
91    --  call denoted by Function_Call. However, if Is_Access is True, then
92    --  Return_Object is already an access expression, in which case it's passed
93    --  along directly to the build-in-place function. Finally, if Return_Object
94    --  is empty, then pass a null literal as the actual.
95
96    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
97      (Function_Call  : Node_Id;
98       Function_Id    : Entity_Id;
99       Alloc_Form     : BIP_Allocation_Form := Unspecified;
100       Alloc_Form_Exp : Node_Id             := Empty);
101    --  Ada 2005 (AI-318-02): Add an actual indicating the form of allocation,
102    --  if any, to be done by a build-in-place function. If Alloc_Form_Exp is
103    --  present, then use it, otherwise pass a literal corresponding to the
104    --  Alloc_Form parameter (which must not be Unspecified in that case).
105
106    procedure Add_Extra_Actual_To_Call
107      (Subprogram_Call : Node_Id;
108       Extra_Formal    : Entity_Id;
109       Extra_Actual    : Node_Id);
110    --  Adds Extra_Actual as a named parameter association for the formal
111    --  Extra_Formal in Subprogram_Call.
112
113    procedure Add_Finalization_Master_Actual_To_Build_In_Place_Call
114      (Func_Call  : Node_Id;
115       Func_Id    : Entity_Id;
116       Ptr_Typ    : Entity_Id := Empty;
117       Master_Exp : Node_Id   := Empty);
118    --  Ada 2005 (AI-318-02): If the result type of a build-in-place call needs
119    --  finalization actions, add an actual parameter which is a pointer to the
120    --  finalization master of the caller. If Master_Exp is not Empty, then that
121    --  will be passed as the actual. Otherwise, if Ptr_Typ is left Empty, this
122    --  will result in an automatic "null" value for the actual.
123
124    procedure Add_Task_Actuals_To_Build_In_Place_Call
125      (Function_Call : Node_Id;
126       Function_Id   : Entity_Id;
127       Master_Actual : Node_Id);
128    --  Ada 2005 (AI-318-02): For a build-in-place call, if the result type
129    --  contains tasks, add two actual parameters: the master, and a pointer to
130    --  the caller's activation chain. Master_Actual is the actual parameter
131    --  expression to pass for the master. In most cases, this is the current
132    --  master (_master). The two exceptions are: If the function call is the
133    --  initialization expression for an allocator, we pass the master of the
134    --  access type. If the function call is the initialization expression for a
135    --  return object, we pass along the master passed in by the caller. The
136    --  activation chain to pass is always the local one. Note: Master_Actual
137    --  can be Empty, but only if there are no tasks.
138
139    procedure Check_Overriding_Operation (Subp : Entity_Id);
140    --  Subp is a dispatching operation. Check whether it may override an
141    --  inherited private operation, in which case its DT entry is that of
142    --  the hidden operation, not the one it may have received earlier.
143    --  This must be done before emitting the code to set the corresponding
144    --  DT to the address of the subprogram. The actual placement of Subp in
145    --  the proper place in the list of primitive operations is done in
146    --  Declare_Inherited_Private_Subprograms, which also has to deal with
147    --  implicit operations. This duplication is unavoidable for now???
148
149    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
150    --  This procedure is called only if the subprogram body N, whose spec
151    --  has the given entity Spec, contains a parameterless recursive call.
152    --  It attempts to generate runtime code to detect if this a case of
153    --  infinite recursion.
154    --
155    --  The body is scanned to determine dependencies. If the only external
156    --  dependencies are on a small set of scalar variables, then the values
157    --  of these variables are captured on entry to the subprogram, and if
158    --  the values are not changed for the call, we know immediately that
159    --  we have an infinite recursion.
160
161    procedure Expand_Ctrl_Function_Call (N : Node_Id);
162    --  N is a function call which returns a controlled object. Transform the
163    --  call into a temporary which retrieves the returned object from the
164    --  secondary stack using 'reference.
165
166    procedure Expand_Inlined_Call
167     (N         : Node_Id;
168      Subp      : Entity_Id;
169      Orig_Subp : Entity_Id);
170    --  If called subprogram can be inlined by the front-end, retrieve the
171    --  analyzed body, replace formals with actuals and expand call in place.
172    --  Generate thunks for actuals that are expressions, and insert the
173    --  corresponding constant declarations before the call. If the original
174    --  call is to a derived operation, the return type is the one of the
175    --  derived operation, but the body is that of the original, so return
176    --  expressions in the body must be converted to the desired type (which
177    --  is simply not noted in the tree without inline expansion).
178
179    procedure Expand_Non_Function_Return (N : Node_Id);
180    --  Called by Expand_N_Simple_Return_Statement in case we're returning from
181    --  a procedure body, entry body, accept statement, or extended return
182    --  statement.  Note that all non-function returns are simple return
183    --  statements.
184
185    function Expand_Protected_Object_Reference
186      (N    : Node_Id;
187       Scop : Entity_Id) return Node_Id;
188
189    procedure Expand_Protected_Subprogram_Call
190      (N    : Node_Id;
191       Subp : Entity_Id;
192       Scop : Entity_Id);
193    --  A call to a protected subprogram within the protected object may appear
194    --  as a regular call. The list of actuals must be expanded to contain a
195    --  reference to the object itself, and the call becomes a call to the
196    --  corresponding protected subprogram.
197
198    procedure Expand_Simple_Function_Return (N : Node_Id);
199    --  Expand simple return from function. In the case where we are returning
200    --  from a function body this is called by Expand_N_Simple_Return_Statement.
201
202    ----------------------------------------------
203    -- Add_Access_Actual_To_Build_In_Place_Call --
204    ----------------------------------------------
205
206    procedure Add_Access_Actual_To_Build_In_Place_Call
207      (Function_Call : Node_Id;
208       Function_Id   : Entity_Id;
209       Return_Object : Node_Id;
210       Is_Access     : Boolean := False)
211    is
212       Loc            : constant Source_Ptr := Sloc (Function_Call);
213       Obj_Address    : Node_Id;
214       Obj_Acc_Formal : Entity_Id;
215
216    begin
217       --  Locate the implicit access parameter in the called function
218
219       Obj_Acc_Formal := Build_In_Place_Formal (Function_Id, BIP_Object_Access);
220
221       --  If no return object is provided, then pass null
222
223       if not Present (Return_Object) then
224          Obj_Address := Make_Null (Loc);
225          Set_Parent (Obj_Address, Function_Call);
226
227       --  If Return_Object is already an expression of an access type, then use
228       --  it directly, since it must be an access value denoting the return
229       --  object, and couldn't possibly be the return object itself.
230
231       elsif Is_Access then
232          Obj_Address := Return_Object;
233          Set_Parent (Obj_Address, Function_Call);
234
235       --  Apply Unrestricted_Access to caller's return object
236
237       else
238          Obj_Address :=
239             Make_Attribute_Reference (Loc,
240               Prefix         => Return_Object,
241               Attribute_Name => Name_Unrestricted_Access);
242
243          Set_Parent (Return_Object, Obj_Address);
244          Set_Parent (Obj_Address, Function_Call);
245       end if;
246
247       Analyze_And_Resolve (Obj_Address, Etype (Obj_Acc_Formal));
248
249       --  Build the parameter association for the new actual and add it to the
250       --  end of the function's actuals.
251
252       Add_Extra_Actual_To_Call (Function_Call, Obj_Acc_Formal, Obj_Address);
253    end Add_Access_Actual_To_Build_In_Place_Call;
254
255    --------------------------------------------------
256    -- Add_Alloc_Form_Actual_To_Build_In_Place_Call --
257    --------------------------------------------------
258
259    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
260      (Function_Call  : Node_Id;
261       Function_Id    : Entity_Id;
262       Alloc_Form     : BIP_Allocation_Form := Unspecified;
263       Alloc_Form_Exp : Node_Id             := Empty)
264    is
265       Loc               : constant Source_Ptr := Sloc (Function_Call);
266       Alloc_Form_Actual : Node_Id;
267       Alloc_Form_Formal : Node_Id;
268
269    begin
270       --  The allocation form generally doesn't need to be passed in the case
271       --  of a constrained result subtype, since normally the caller performs
272       --  the allocation in that case. However this formal is still needed in
273       --  the case where the function has a tagged result, because generally
274       --  such functions can be called in a dispatching context and such calls
275       --  must be handled like calls to class-wide functions.
276
277       if Is_Constrained (Underlying_Type (Etype (Function_Id)))
278         and then not Is_Tagged_Type (Underlying_Type (Etype (Function_Id)))
279       then
280          return;
281       end if;
282
283       --  Locate the implicit allocation form parameter in the called function.
284       --  Maybe it would be better for each implicit formal of a build-in-place
285       --  function to have a flag or a Uint attribute to identify it. ???
286
287       Alloc_Form_Formal := Build_In_Place_Formal (Function_Id, BIP_Alloc_Form);
288
289       if Present (Alloc_Form_Exp) then
290          pragma Assert (Alloc_Form = Unspecified);
291
292          Alloc_Form_Actual := Alloc_Form_Exp;
293
294       else
295          pragma Assert (Alloc_Form /= Unspecified);
296
297          Alloc_Form_Actual :=
298            Make_Integer_Literal (Loc,
299              Intval => UI_From_Int (BIP_Allocation_Form'Pos (Alloc_Form)));
300       end if;
301
302       Analyze_And_Resolve (Alloc_Form_Actual, Etype (Alloc_Form_Formal));
303
304       --  Build the parameter association for the new actual and add it to the
305       --  end of the function's actuals.
306
307       Add_Extra_Actual_To_Call
308         (Function_Call, Alloc_Form_Formal, Alloc_Form_Actual);
309    end Add_Alloc_Form_Actual_To_Build_In_Place_Call;
310
311    -----------------------------------------------------------
312    -- Add_Finalization_Master_Actual_To_Build_In_Place_Call --
313    -----------------------------------------------------------
314
315    procedure Add_Finalization_Master_Actual_To_Build_In_Place_Call
316      (Func_Call  : Node_Id;
317       Func_Id    : Entity_Id;
318       Ptr_Typ    : Entity_Id := Empty;
319       Master_Exp : Node_Id   := Empty)
320    is
321    begin
322       if not Needs_BIP_Finalization_Master (Func_Id) then
323          return;
324       end if;
325
326       declare
327          Formal : constant Entity_Id :=
328                     Build_In_Place_Formal (Func_Id, BIP_Finalization_Master);
329          Loc    : constant Source_Ptr := Sloc (Func_Call);
330
331          Actual    : Node_Id;
332          Desig_Typ : Entity_Id;
333
334       begin
335          --  If there is a finalization master actual, such as the implicit
336          --  finalization master of an enclosing build-in-place function,
337          --  then this must be added as an extra actual of the call.
338
339          if Present (Master_Exp) then
340             Actual := Master_Exp;
341
342          --  Case where the context does not require an actual master
343
344          elsif No (Ptr_Typ) then
345             Actual := Make_Null (Loc);
346
347          else
348             Desig_Typ := Directly_Designated_Type (Ptr_Typ);
349
350             --  Check for a library-level access type whose designated type has
351             --  supressed finalization. Such an access types lack a master.
352             --  Pass a null actual to the callee in order to signal a missing
353             --  master.
354
355             if Is_Library_Level_Entity (Ptr_Typ)
356               and then Finalize_Storage_Only (Desig_Typ)
357             then
358                Actual := Make_Null (Loc);
359
360             --  Types in need of finalization actions
361
362             elsif Needs_Finalization (Desig_Typ) then
363
364                --  The general mechanism of creating finalization masters for
365                --  anonymous access types is disabled by default, otherwise
366                --  finalization masters will pop all over the place. Such types
367                --  use context-specific masters.
368
369                if Ekind (Ptr_Typ) = E_Anonymous_Access_Type
370                  and then No (Finalization_Master (Ptr_Typ))
371                then
372                   Build_Finalization_Master
373                     (Typ        => Ptr_Typ,
374                      Ins_Node   => Associated_Node_For_Itype (Ptr_Typ),
375                      Encl_Scope => Scope (Ptr_Typ));
376                end if;
377
378                --  Access-to-controlled types should always have a master
379
380                pragma Assert (Present (Finalization_Master (Ptr_Typ)));
381
382                Actual :=
383                  Make_Attribute_Reference (Loc,
384                    Prefix =>
385                      New_Reference_To (Finalization_Master (Ptr_Typ), Loc),
386                    Attribute_Name => Name_Unrestricted_Access);
387
388             --  Tagged types
389
390             else
391                Actual := Make_Null (Loc);
392             end if;
393          end if;
394
395          Analyze_And_Resolve (Actual, Etype (Formal));
396
397          --  Build the parameter association for the new actual and add it to
398          --  the end of the function's actuals.
399
400          Add_Extra_Actual_To_Call (Func_Call, Formal, Actual);
401       end;
402    end Add_Finalization_Master_Actual_To_Build_In_Place_Call;
403
404    ------------------------------
405    -- Add_Extra_Actual_To_Call --
406    ------------------------------
407
408    procedure Add_Extra_Actual_To_Call
409      (Subprogram_Call : Node_Id;
410       Extra_Formal    : Entity_Id;
411       Extra_Actual    : Node_Id)
412    is
413       Loc         : constant Source_Ptr := Sloc (Subprogram_Call);
414       Param_Assoc : Node_Id;
415
416    begin
417       Param_Assoc :=
418         Make_Parameter_Association (Loc,
419           Selector_Name             => New_Occurrence_Of (Extra_Formal, Loc),
420           Explicit_Actual_Parameter => Extra_Actual);
421
422       Set_Parent (Param_Assoc, Subprogram_Call);
423       Set_Parent (Extra_Actual, Param_Assoc);
424
425       if Present (Parameter_Associations (Subprogram_Call)) then
426          if Nkind (Last (Parameter_Associations (Subprogram_Call))) =
427               N_Parameter_Association
428          then
429
430             --  Find last named actual, and append
431
432             declare
433                L : Node_Id;
434             begin
435                L := First_Actual (Subprogram_Call);
436                while Present (L) loop
437                   if No (Next_Actual (L)) then
438                      Set_Next_Named_Actual (Parent (L), Extra_Actual);
439                      exit;
440                   end if;
441                   Next_Actual (L);
442                end loop;
443             end;
444
445          else
446             Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
447          end if;
448
449          Append (Param_Assoc, To => Parameter_Associations (Subprogram_Call));
450
451       else
452          Set_Parameter_Associations (Subprogram_Call, New_List (Param_Assoc));
453          Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
454       end if;
455    end Add_Extra_Actual_To_Call;
456
457    ---------------------------------------------
458    -- Add_Task_Actuals_To_Build_In_Place_Call --
459    ---------------------------------------------
460
461    procedure Add_Task_Actuals_To_Build_In_Place_Call
462      (Function_Call : Node_Id;
463       Function_Id   : Entity_Id;
464       Master_Actual : Node_Id)
465    is
466       Loc    : constant Source_Ptr := Sloc (Function_Call);
467       Actual : Node_Id := Master_Actual;
468
469    begin
470       --  No such extra parameters are needed if there are no tasks
471
472       if not Has_Task (Etype (Function_Id)) then
473          return;
474       end if;
475
476       --  Use a dummy _master actual in case of No_Task_Hierarchy
477
478       if Restriction_Active (No_Task_Hierarchy) then
479          Actual := New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc);
480       end if;
481
482       --  The master
483
484       declare
485          Master_Formal : Node_Id;
486       begin
487          --  Locate implicit master parameter in the called function
488
489          Master_Formal := Build_In_Place_Formal (Function_Id, BIP_Master);
490
491          Analyze_And_Resolve (Actual, Etype (Master_Formal));
492
493          --  Build the parameter association for the new actual and add it to
494          --  the end of the function's actuals.
495
496          Add_Extra_Actual_To_Call
497            (Function_Call, Master_Formal, Actual);
498       end;
499
500       --  The activation chain
501
502       declare
503          Activation_Chain_Actual : Node_Id;
504          Activation_Chain_Formal : Node_Id;
505
506       begin
507          --  Locate implicit activation chain parameter in the called function
508
509          Activation_Chain_Formal := Build_In_Place_Formal
510            (Function_Id, BIP_Activation_Chain);
511
512          --  Create the actual which is a pointer to the current activation
513          --  chain
514
515          Activation_Chain_Actual :=
516            Make_Attribute_Reference (Loc,
517              Prefix         => Make_Identifier (Loc, Name_uChain),
518              Attribute_Name => Name_Unrestricted_Access);
519
520          Analyze_And_Resolve
521            (Activation_Chain_Actual, Etype (Activation_Chain_Formal));
522
523          --  Build the parameter association for the new actual and add it to
524          --  the end of the function's actuals.
525
526          Add_Extra_Actual_To_Call
527            (Function_Call, Activation_Chain_Formal, Activation_Chain_Actual);
528       end;
529    end Add_Task_Actuals_To_Build_In_Place_Call;
530
531    -----------------------
532    -- BIP_Formal_Suffix --
533    -----------------------
534
535    function BIP_Formal_Suffix (Kind : BIP_Formal_Kind) return String is
536    begin
537       case Kind is
538          when BIP_Alloc_Form          =>
539             return "BIPalloc";
540          when BIP_Finalization_Master =>
541             return "BIPfinalizationmaster";
542          when BIP_Master              =>
543             return "BIPmaster";
544          when BIP_Activation_Chain    =>
545             return "BIPactivationchain";
546          when BIP_Object_Access       =>
547             return "BIPaccess";
548       end case;
549    end BIP_Formal_Suffix;
550
551    ---------------------------
552    -- Build_In_Place_Formal --
553    ---------------------------
554
555    function Build_In_Place_Formal
556      (Func : Entity_Id;
557       Kind : BIP_Formal_Kind) return Entity_Id
558    is
559       Extra_Formal : Entity_Id := Extra_Formals (Func);
560
561    begin
562       --  Maybe it would be better for each implicit formal of a build-in-place
563       --  function to have a flag or a Uint attribute to identify it. ???
564
565       --  The return type in the function declaration may have been a limited
566       --  view, and the extra formals for the function were not generated at
567       --  that point.  At the point of call the full view must be available and
568       --  the extra formals can be created.
569
570       if No (Extra_Formal) then
571          Create_Extra_Formals (Func);
572          Extra_Formal := Extra_Formals (Func);
573       end if;
574
575       loop
576          pragma Assert (Present (Extra_Formal));
577          exit when
578            Chars (Extra_Formal) =
579              New_External_Name (Chars (Func), BIP_Formal_Suffix (Kind));
580          Next_Formal_With_Extras (Extra_Formal);
581       end loop;
582
583       return Extra_Formal;
584    end Build_In_Place_Formal;
585
586    --------------------------------
587    -- Check_Overriding_Operation --
588    --------------------------------
589
590    procedure Check_Overriding_Operation (Subp : Entity_Id) is
591       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
592       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
593       Op_Elmt : Elmt_Id;
594       Prim_Op : Entity_Id;
595       Par_Op  : Entity_Id;
596
597    begin
598       if Is_Derived_Type (Typ)
599         and then not Is_Private_Type (Typ)
600         and then In_Open_Scopes (Scope (Etype (Typ)))
601         and then Is_Base_Type (Typ)
602       then
603          --  Subp overrides an inherited private operation if there is an
604          --  inherited operation with a different name than Subp (see
605          --  Derive_Subprogram) whose Alias is a hidden subprogram with the
606          --  same name as Subp.
607
608          Op_Elmt := First_Elmt (Op_List);
609          while Present (Op_Elmt) loop
610             Prim_Op := Node (Op_Elmt);
611             Par_Op  := Alias (Prim_Op);
612
613             if Present (Par_Op)
614               and then not Comes_From_Source (Prim_Op)
615               and then Chars (Prim_Op) /= Chars (Par_Op)
616               and then Chars (Par_Op) = Chars (Subp)
617               and then Is_Hidden (Par_Op)
618               and then Type_Conformant (Prim_Op, Subp)
619             then
620                Set_DT_Position (Subp, DT_Position (Prim_Op));
621             end if;
622
623             Next_Elmt (Op_Elmt);
624          end loop;
625       end if;
626    end Check_Overriding_Operation;
627
628    -------------------------------
629    -- Detect_Infinite_Recursion --
630    -------------------------------
631
632    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
633       Loc : constant Source_Ptr := Sloc (N);
634
635       Var_List : constant Elist_Id := New_Elmt_List;
636       --  List of globals referenced by body of procedure
637
638       Call_List : constant Elist_Id := New_Elmt_List;
639       --  List of recursive calls in body of procedure
640
641       Shad_List : constant Elist_Id := New_Elmt_List;
642       --  List of entity id's for entities created to capture the value of
643       --  referenced globals on entry to the procedure.
644
645       Scop : constant Uint := Scope_Depth (Spec);
646       --  This is used to record the scope depth of the current procedure, so
647       --  that we can identify global references.
648
649       Max_Vars : constant := 4;
650       --  Do not test more than four global variables
651
652       Count_Vars : Natural := 0;
653       --  Count variables found so far
654
655       Var  : Entity_Id;
656       Elm  : Elmt_Id;
657       Ent  : Entity_Id;
658       Call : Elmt_Id;
659       Decl : Node_Id;
660       Test : Node_Id;
661       Elm1 : Elmt_Id;
662       Elm2 : Elmt_Id;
663       Last : Node_Id;
664
665       function Process (Nod : Node_Id) return Traverse_Result;
666       --  Function to traverse the subprogram body (using Traverse_Func)
667
668       -------------
669       -- Process --
670       -------------
671
672       function Process (Nod : Node_Id) return Traverse_Result is
673       begin
674          --  Procedure call
675
676          if Nkind (Nod) = N_Procedure_Call_Statement then
677
678             --  Case of one of the detected recursive calls
679
680             if Is_Entity_Name (Name (Nod))
681               and then Has_Recursive_Call (Entity (Name (Nod)))
682               and then Entity (Name (Nod)) = Spec
683             then
684                Append_Elmt (Nod, Call_List);
685                return Skip;
686
687             --  Any other procedure call may have side effects
688
689             else
690                return Abandon;
691             end if;
692
693          --  A call to a pure function can always be ignored
694
695          elsif Nkind (Nod) = N_Function_Call
696            and then Is_Entity_Name (Name (Nod))
697            and then Is_Pure (Entity (Name (Nod)))
698          then
699             return Skip;
700
701          --  Case of an identifier reference
702
703          elsif Nkind (Nod) = N_Identifier then
704             Ent := Entity (Nod);
705
706             --  If no entity, then ignore the reference
707
708             --  Not clear why this can happen. To investigate, remove this
709             --  test and look at the crash that occurs here in 3401-004 ???
710
711             if No (Ent) then
712                return Skip;
713
714             --  Ignore entities with no Scope, again not clear how this
715             --  can happen, to investigate, look at 4108-008 ???
716
717             elsif No (Scope (Ent)) then
718                return Skip;
719
720             --  Ignore the reference if not to a more global object
721
722             elsif Scope_Depth (Scope (Ent)) >= Scop then
723                return Skip;
724
725             --  References to types, exceptions and constants are always OK
726
727             elsif Is_Type (Ent)
728               or else Ekind (Ent) = E_Exception
729               or else Ekind (Ent) = E_Constant
730             then
731                return Skip;
732
733             --  If other than a non-volatile scalar variable, we have some
734             --  kind of global reference (e.g. to a function) that we cannot
735             --  deal with so we forget the attempt.
736
737             elsif Ekind (Ent) /= E_Variable
738               or else not Is_Scalar_Type (Etype (Ent))
739               or else Treat_As_Volatile (Ent)
740             then
741                return Abandon;
742
743             --  Otherwise we have a reference to a global scalar
744
745             else
746                --  Loop through global entities already detected
747
748                Elm := First_Elmt (Var_List);
749                loop
750                   --  If not detected before, record this new global reference
751
752                   if No (Elm) then
753                      Count_Vars := Count_Vars + 1;
754
755                      if Count_Vars <= Max_Vars then
756                         Append_Elmt (Entity (Nod), Var_List);
757                      else
758                         return Abandon;
759                      end if;
760
761                      exit;
762
763                   --  If recorded before, ignore
764
765                   elsif Node (Elm) = Entity (Nod) then
766                      return Skip;
767
768                   --  Otherwise keep looking
769
770                   else
771                      Next_Elmt (Elm);
772                   end if;
773                end loop;
774
775                return Skip;
776             end if;
777
778          --  For all other node kinds, recursively visit syntactic children
779
780          else
781             return OK;
782          end if;
783       end Process;
784
785       function Traverse_Body is new Traverse_Func (Process);
786
787    --  Start of processing for Detect_Infinite_Recursion
788
789    begin
790       --  Do not attempt detection in No_Implicit_Conditional mode, since we
791       --  won't be able to generate the code to handle the recursion in any
792       --  case.
793
794       if Restriction_Active (No_Implicit_Conditionals) then
795          return;
796       end if;
797
798       --  Otherwise do traversal and quit if we get abandon signal
799
800       if Traverse_Body (N) = Abandon then
801          return;
802
803       --  We must have a call, since Has_Recursive_Call was set. If not just
804       --  ignore (this is only an error check, so if we have a funny situation,
805       --  due to bugs or errors, we do not want to bomb!)
806
807       elsif Is_Empty_Elmt_List (Call_List) then
808          return;
809       end if;
810
811       --  Here is the case where we detect recursion at compile time
812
813       --  Push our current scope for analyzing the declarations and code that
814       --  we will insert for the checking.
815
816       Push_Scope (Spec);
817
818       --  This loop builds temporary variables for each of the referenced
819       --  globals, so that at the end of the loop the list Shad_List contains
820       --  these temporaries in one-to-one correspondence with the elements in
821       --  Var_List.
822
823       Last := Empty;
824       Elm := First_Elmt (Var_List);
825       while Present (Elm) loop
826          Var := Node (Elm);
827          Ent := Make_Temporary (Loc, 'S');
828          Append_Elmt (Ent, Shad_List);
829
830          --  Insert a declaration for this temporary at the start of the
831          --  declarations for the procedure. The temporaries are declared as
832          --  constant objects initialized to the current values of the
833          --  corresponding temporaries.
834
835          Decl :=
836            Make_Object_Declaration (Loc,
837              Defining_Identifier => Ent,
838              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
839              Constant_Present    => True,
840              Expression          => New_Occurrence_Of (Var, Loc));
841
842          if No (Last) then
843             Prepend (Decl, Declarations (N));
844          else
845             Insert_After (Last, Decl);
846          end if;
847
848          Last := Decl;
849          Analyze (Decl);
850          Next_Elmt (Elm);
851       end loop;
852
853       --  Loop through calls
854
855       Call := First_Elmt (Call_List);
856       while Present (Call) loop
857
858          --  Build a predicate expression of the form
859
860          --    True
861          --      and then global1 = temp1
862          --      and then global2 = temp2
863          --      ...
864
865          --  This predicate determines if any of the global values
866          --  referenced by the procedure have changed since the
867          --  current call, if not an infinite recursion is assured.
868
869          Test := New_Occurrence_Of (Standard_True, Loc);
870
871          Elm1 := First_Elmt (Var_List);
872          Elm2 := First_Elmt (Shad_List);
873          while Present (Elm1) loop
874             Test :=
875               Make_And_Then (Loc,
876                 Left_Opnd  => Test,
877                 Right_Opnd =>
878                   Make_Op_Eq (Loc,
879                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
880                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
881
882             Next_Elmt (Elm1);
883             Next_Elmt (Elm2);
884          end loop;
885
886          --  Now we replace the call with the sequence
887
888          --    if no-changes (see above) then
889          --       raise Storage_Error;
890          --    else
891          --       original-call
892          --    end if;
893
894          Rewrite (Node (Call),
895            Make_If_Statement (Loc,
896              Condition       => Test,
897              Then_Statements => New_List (
898                Make_Raise_Storage_Error (Loc,
899                  Reason => SE_Infinite_Recursion)),
900
901              Else_Statements => New_List (
902                Relocate_Node (Node (Call)))));
903
904          Analyze (Node (Call));
905
906          Next_Elmt (Call);
907       end loop;
908
909       --  Remove temporary scope stack entry used for analysis
910
911       Pop_Scope;
912    end Detect_Infinite_Recursion;
913
914    --------------------
915    -- Expand_Actuals --
916    --------------------
917
918    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
919       Loc       : constant Source_Ptr := Sloc (N);
920       Actual    : Node_Id;
921       Formal    : Entity_Id;
922       N_Node    : Node_Id;
923       Post_Call : List_Id;
924       E_Formal  : Entity_Id;
925
926       procedure Add_Call_By_Copy_Code;
927       --  For cases where the parameter must be passed by copy, this routine
928       --  generates a temporary variable into which the actual is copied and
929       --  then passes this as the parameter. For an OUT or IN OUT parameter,
930       --  an assignment is also generated to copy the result back. The call
931       --  also takes care of any constraint checks required for the type
932       --  conversion case (on both the way in and the way out).
933
934       procedure Add_Simple_Call_By_Copy_Code;
935       --  This is similar to the above, but is used in cases where we know
936       --  that all that is needed is to simply create a temporary and copy
937       --  the value in and out of the temporary.
938
939       procedure Check_Fortran_Logical;
940       --  A value of type Logical that is passed through a formal parameter
941       --  must be normalized because .TRUE. usually does not have the same
942       --  representation as True. We assume that .FALSE. = False = 0.
943       --  What about functions that return a logical type ???
944
945       function Is_Legal_Copy return Boolean;
946       --  Check that an actual can be copied before generating the temporary
947       --  to be used in the call. If the actual is of a by_reference type then
948       --  the program is illegal (this can only happen in the presence of
949       --  rep. clauses that force an incorrect alignment). If the formal is
950       --  a by_reference parameter imposed by a DEC pragma, emit a warning to
951       --  the effect that this might lead to unaligned arguments.
952
953       function Make_Var (Actual : Node_Id) return Entity_Id;
954       --  Returns an entity that refers to the given actual parameter,
955       --  Actual (not including any type conversion). If Actual is an
956       --  entity name, then this entity is returned unchanged, otherwise
957       --  a renaming is created to provide an entity for the actual.
958
959       procedure Reset_Packed_Prefix;
960       --  The expansion of a packed array component reference is delayed in
961       --  the context of a call. Now we need to complete the expansion, so we
962       --  unmark the analyzed bits in all prefixes.
963
964       ---------------------------
965       -- Add_Call_By_Copy_Code --
966       ---------------------------
967
968       procedure Add_Call_By_Copy_Code is
969          Expr  : Node_Id;
970          Init  : Node_Id;
971          Temp  : Entity_Id;
972          Indic : Node_Id;
973          Var   : Entity_Id;
974          F_Typ : constant Entity_Id := Etype (Formal);
975          V_Typ : Entity_Id;
976          Crep  : Boolean;
977
978       begin
979          if not Is_Legal_Copy then
980             return;
981          end if;
982
983          Temp := Make_Temporary (Loc, 'T', Actual);
984
985          --  Use formal type for temp, unless formal type is an unconstrained
986          --  array, in which case we don't have to worry about bounds checks,
987          --  and we use the actual type, since that has appropriate bounds.
988
989          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
990             Indic := New_Occurrence_Of (Etype (Actual), Loc);
991          else
992             Indic := New_Occurrence_Of (Etype (Formal), Loc);
993          end if;
994
995          if Nkind (Actual) = N_Type_Conversion then
996             V_Typ := Etype (Expression (Actual));
997
998             --  If the formal is an (in-)out parameter, capture the name
999             --  of the variable in order to build the post-call assignment.
1000
1001             Var := Make_Var (Expression (Actual));
1002
1003             Crep := not Same_Representation
1004                           (F_Typ, Etype (Expression (Actual)));
1005
1006          else
1007             V_Typ := Etype (Actual);
1008             Var   := Make_Var (Actual);
1009             Crep  := False;
1010          end if;
1011
1012          --  Setup initialization for case of in out parameter, or an out
1013          --  parameter where the formal is an unconstrained array (in the
1014          --  latter case, we have to pass in an object with bounds).
1015
1016          --  If this is an out parameter, the initial copy is wasteful, so as
1017          --  an optimization for the one-dimensional case we extract the
1018          --  bounds of the actual and build an uninitialized temporary of the
1019          --  right size.
1020
1021          if Ekind (Formal) = E_In_Out_Parameter
1022            or else (Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ))
1023          then
1024             if Nkind (Actual) = N_Type_Conversion then
1025                if Conversion_OK (Actual) then
1026                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1027                else
1028                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1029                end if;
1030
1031             elsif Ekind (Formal) = E_Out_Parameter
1032               and then Is_Array_Type (F_Typ)
1033               and then Number_Dimensions (F_Typ) = 1
1034               and then not Has_Non_Null_Base_Init_Proc (F_Typ)
1035             then
1036                --  Actual is a one-dimensional array or slice, and the type
1037                --  requires no initialization. Create a temporary of the
1038                --  right size, but do not copy actual into it (optimization).
1039
1040                Init := Empty;
1041                Indic :=
1042                  Make_Subtype_Indication (Loc,
1043                    Subtype_Mark =>
1044                      New_Occurrence_Of (F_Typ, Loc),
1045                    Constraint   =>
1046                      Make_Index_Or_Discriminant_Constraint (Loc,
1047                        Constraints => New_List (
1048                          Make_Range (Loc,
1049                            Low_Bound  =>
1050                              Make_Attribute_Reference (Loc,
1051                                Prefix => New_Occurrence_Of (Var, Loc),
1052                                Attribute_Name => Name_First),
1053                            High_Bound =>
1054                              Make_Attribute_Reference (Loc,
1055                                Prefix => New_Occurrence_Of (Var, Loc),
1056                                Attribute_Name => Name_Last)))));
1057
1058             else
1059                Init := New_Occurrence_Of (Var, Loc);
1060             end if;
1061
1062          --  An initialization is created for packed conversions as
1063          --  actuals for out parameters to enable Make_Object_Declaration
1064          --  to determine the proper subtype for N_Node. Note that this
1065          --  is wasteful because the extra copying on the call side is
1066          --  not required for such out parameters. ???
1067
1068          elsif Ekind (Formal) = E_Out_Parameter
1069            and then Nkind (Actual) = N_Type_Conversion
1070            and then (Is_Bit_Packed_Array (F_Typ)
1071                        or else
1072                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
1073          then
1074             if Conversion_OK (Actual) then
1075                Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1076             else
1077                Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1078             end if;
1079
1080          elsif Ekind (Formal) = E_In_Parameter then
1081
1082             --  Handle the case in which the actual is a type conversion
1083
1084             if Nkind (Actual) = N_Type_Conversion then
1085                if Conversion_OK (Actual) then
1086                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1087                else
1088                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1089                end if;
1090             else
1091                Init := New_Occurrence_Of (Var, Loc);
1092             end if;
1093
1094          else
1095             Init := Empty;
1096          end if;
1097
1098          N_Node :=
1099            Make_Object_Declaration (Loc,
1100              Defining_Identifier => Temp,
1101              Object_Definition   => Indic,
1102              Expression          => Init);
1103          Set_Assignment_OK (N_Node);
1104          Insert_Action (N, N_Node);
1105
1106          --  Now, normally the deal here is that we use the defining
1107          --  identifier created by that object declaration. There is
1108          --  one exception to this. In the change of representation case
1109          --  the above declaration will end up looking like:
1110
1111          --    temp : type := identifier;
1112
1113          --  And in this case we might as well use the identifier directly
1114          --  and eliminate the temporary. Note that the analysis of the
1115          --  declaration was not a waste of time in that case, since it is
1116          --  what generated the necessary change of representation code. If
1117          --  the change of representation introduced additional code, as in
1118          --  a fixed-integer conversion, the expression is not an identifier
1119          --  and must be kept.
1120
1121          if Crep
1122            and then Present (Expression (N_Node))
1123            and then Is_Entity_Name (Expression (N_Node))
1124          then
1125             Temp := Entity (Expression (N_Node));
1126             Rewrite (N_Node, Make_Null_Statement (Loc));
1127          end if;
1128
1129          --  For IN parameter, all we do is to replace the actual
1130
1131          if Ekind (Formal) = E_In_Parameter then
1132             Rewrite (Actual, New_Reference_To (Temp, Loc));
1133             Analyze (Actual);
1134
1135          --  Processing for OUT or IN OUT parameter
1136
1137          else
1138             --  Kill current value indications for the temporary variable we
1139             --  created, since we just passed it as an OUT parameter.
1140
1141             Kill_Current_Values (Temp);
1142             Set_Is_Known_Valid (Temp, False);
1143
1144             --  If type conversion, use reverse conversion on exit
1145
1146             if Nkind (Actual) = N_Type_Conversion then
1147                if Conversion_OK (Actual) then
1148                   Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1149                else
1150                   Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1151                end if;
1152             else
1153                Expr := New_Occurrence_Of (Temp, Loc);
1154             end if;
1155
1156             Rewrite (Actual, New_Reference_To (Temp, Loc));
1157             Analyze (Actual);
1158
1159             --  If the actual is a conversion of a packed reference, it may
1160             --  already have been expanded by Remove_Side_Effects, and the
1161             --  resulting variable is a temporary which does not designate
1162             --  the proper out-parameter, which may not be addressable. In
1163             --  that case, generate an assignment to the original expression
1164             --  (before expansion of the packed reference) so that the proper
1165             --  expansion of assignment to a packed component can take place.
1166
1167             declare
1168                Obj : Node_Id;
1169                Lhs : Node_Id;
1170
1171             begin
1172                if Is_Renaming_Of_Object (Var)
1173                  and then Nkind (Renamed_Object (Var)) = N_Selected_Component
1174                  and then Is_Entity_Name (Prefix (Renamed_Object (Var)))
1175                  and then Nkind (Original_Node (Prefix (Renamed_Object (Var))))
1176                    = N_Indexed_Component
1177                  and then
1178                    Has_Non_Standard_Rep (Etype (Prefix (Renamed_Object (Var))))
1179                then
1180                   Obj := Renamed_Object (Var);
1181                   Lhs :=
1182                     Make_Selected_Component (Loc,
1183                       Prefix        =>
1184                         New_Copy_Tree (Original_Node (Prefix (Obj))),
1185                       Selector_Name => New_Copy (Selector_Name (Obj)));
1186                   Reset_Analyzed_Flags (Lhs);
1187
1188                else
1189                   Lhs :=  New_Occurrence_Of (Var, Loc);
1190                end if;
1191
1192                Set_Assignment_OK (Lhs);
1193
1194                if Is_Access_Type (E_Formal)
1195                  and then Is_Entity_Name (Lhs)
1196                  and then
1197                    Present (Effective_Extra_Accessibility (Entity (Lhs)))
1198                then
1199                   --  Copyback target is an Ada 2012 stand-alone object
1200                   --  of an anonymous access type
1201
1202                   pragma Assert (Ada_Version >= Ada_2012);
1203
1204                   if Type_Access_Level (E_Formal) >
1205                      Object_Access_Level (Lhs)
1206                   then
1207                      Append_To (Post_Call,
1208                        Make_Raise_Program_Error (Loc,
1209                          Reason => PE_Accessibility_Check_Failed));
1210                   end if;
1211
1212                   Append_To (Post_Call,
1213                     Make_Assignment_Statement (Loc,
1214                       Name       => Lhs,
1215                       Expression => Expr));
1216
1217                   --  We would like to somehow suppress generation of the
1218                   --  extra_accessibility assignment generated by the expansion
1219                   --  of the above assignment statement. It's not a correctness
1220                   --  issue because the following assignment renders it dead,
1221                   --  but generating back-to-back assignments to the same
1222                   --  target is undesirable. ???
1223
1224                   Append_To (Post_Call,
1225                     Make_Assignment_Statement (Loc,
1226                       Name       => New_Occurrence_Of (
1227                         Effective_Extra_Accessibility (Entity (Lhs)), Loc),
1228                       Expression => Make_Integer_Literal (Loc,
1229                         Type_Access_Level (E_Formal))));
1230
1231                else
1232                   Append_To (Post_Call,
1233                     Make_Assignment_Statement (Loc,
1234                       Name       => Lhs,
1235                       Expression => Expr));
1236                end if;
1237             end;
1238          end if;
1239       end Add_Call_By_Copy_Code;
1240
1241       ----------------------------------
1242       -- Add_Simple_Call_By_Copy_Code --
1243       ----------------------------------
1244
1245       procedure Add_Simple_Call_By_Copy_Code is
1246          Temp   : Entity_Id;
1247          Decl   : Node_Id;
1248          Incod  : Node_Id;
1249          Outcod : Node_Id;
1250          Lhs    : Node_Id;
1251          Rhs    : Node_Id;
1252          Indic  : Node_Id;
1253          F_Typ  : constant Entity_Id := Etype (Formal);
1254
1255       begin
1256          if not Is_Legal_Copy then
1257             return;
1258          end if;
1259
1260          --  Use formal type for temp, unless formal type is an unconstrained
1261          --  array, in which case we don't have to worry about bounds checks,
1262          --  and we use the actual type, since that has appropriate bounds.
1263
1264          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
1265             Indic := New_Occurrence_Of (Etype (Actual), Loc);
1266          else
1267             Indic := New_Occurrence_Of (Etype (Formal), Loc);
1268          end if;
1269
1270          --  Prepare to generate code
1271
1272          Reset_Packed_Prefix;
1273
1274          Temp := Make_Temporary (Loc, 'T', Actual);
1275          Incod  := Relocate_Node (Actual);
1276          Outcod := New_Copy_Tree (Incod);
1277
1278          --  Generate declaration of temporary variable, initializing it
1279          --  with the input parameter unless we have an OUT formal or
1280          --  this is an initialization call.
1281
1282          --  If the formal is an out parameter with discriminants, the
1283          --  discriminants must be captured even if the rest of the object
1284          --  is in principle uninitialized, because the discriminants may
1285          --  be read by the called subprogram.
1286
1287          if Ekind (Formal) = E_Out_Parameter then
1288             Incod := Empty;
1289
1290             if Has_Discriminants (Etype (Formal)) then
1291                Indic := New_Occurrence_Of (Etype (Actual), Loc);
1292             end if;
1293
1294          elsif Inside_Init_Proc then
1295
1296             --  Could use a comment here to match comment below ???
1297
1298             if Nkind (Actual) /= N_Selected_Component
1299               or else
1300                 not Has_Discriminant_Dependent_Constraint
1301                   (Entity (Selector_Name (Actual)))
1302             then
1303                Incod := Empty;
1304
1305             --  Otherwise, keep the component in order to generate the proper
1306             --  actual subtype, that depends on enclosing discriminants.
1307
1308             else
1309                null;
1310             end if;
1311          end if;
1312
1313          Decl :=
1314            Make_Object_Declaration (Loc,
1315              Defining_Identifier => Temp,
1316              Object_Definition   => Indic,
1317              Expression          => Incod);
1318
1319          if Inside_Init_Proc
1320            and then No (Incod)
1321          then
1322             --  If the call is to initialize a component of a composite type,
1323             --  and the component does not depend on discriminants, use the
1324             --  actual type of the component. This is required in case the
1325             --  component is constrained, because in general the formal of the
1326             --  initialization procedure will be unconstrained. Note that if
1327             --  the component being initialized is constrained by an enclosing
1328             --  discriminant, the presence of the initialization in the
1329             --  declaration will generate an expression for the actual subtype.
1330
1331             Set_No_Initialization (Decl);
1332             Set_Object_Definition (Decl,
1333               New_Occurrence_Of (Etype (Actual), Loc));
1334          end if;
1335
1336          Insert_Action (N, Decl);
1337
1338          --  The actual is simply a reference to the temporary
1339
1340          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
1341
1342          --  Generate copy out if OUT or IN OUT parameter
1343
1344          if Ekind (Formal) /= E_In_Parameter then
1345             Lhs := Outcod;
1346             Rhs := New_Occurrence_Of (Temp, Loc);
1347
1348             --  Deal with conversion
1349
1350             if Nkind (Lhs) = N_Type_Conversion then
1351                Lhs := Expression (Lhs);
1352                Rhs := Convert_To (Etype (Actual), Rhs);
1353             end if;
1354
1355             Append_To (Post_Call,
1356               Make_Assignment_Statement (Loc,
1357                 Name       => Lhs,
1358                 Expression => Rhs));
1359             Set_Assignment_OK (Name (Last (Post_Call)));
1360          end if;
1361       end Add_Simple_Call_By_Copy_Code;
1362
1363       ---------------------------
1364       -- Check_Fortran_Logical --
1365       ---------------------------
1366
1367       procedure Check_Fortran_Logical is
1368          Logical : constant Entity_Id := Etype (Formal);
1369          Var     : Entity_Id;
1370
1371       --  Note: this is very incomplete, e.g. it does not handle arrays
1372       --  of logical values. This is really not the right approach at all???)
1373
1374       begin
1375          if Convention (Subp) = Convention_Fortran
1376            and then Root_Type (Etype (Formal)) = Standard_Boolean
1377            and then Ekind (Formal) /= E_In_Parameter
1378          then
1379             Var := Make_Var (Actual);
1380             Append_To (Post_Call,
1381               Make_Assignment_Statement (Loc,
1382                 Name => New_Occurrence_Of (Var, Loc),
1383                 Expression =>
1384                   Unchecked_Convert_To (
1385                     Logical,
1386                     Make_Op_Ne (Loc,
1387                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
1388                       Right_Opnd =>
1389                         Unchecked_Convert_To (
1390                           Logical,
1391                           New_Occurrence_Of (Standard_False, Loc))))));
1392          end if;
1393       end Check_Fortran_Logical;
1394
1395       -------------------
1396       -- Is_Legal_Copy --
1397       -------------------
1398
1399       function Is_Legal_Copy return Boolean is
1400       begin
1401          --  An attempt to copy a value of such a type can only occur if
1402          --  representation clauses give the actual a misaligned address.
1403
1404          if Is_By_Reference_Type (Etype (Formal)) then
1405             Error_Msg_N
1406               ("misaligned actual cannot be passed by reference", Actual);
1407             return False;
1408
1409          --  For users of Starlet, we assume that the specification of by-
1410          --  reference mechanism is mandatory. This may lead to unaligned
1411          --  objects but at least for DEC legacy code it is known to work.
1412          --  The warning will alert users of this code that a problem may
1413          --  be lurking.
1414
1415          elsif Mechanism (Formal) = By_Reference
1416            and then Is_Valued_Procedure (Scope (Formal))
1417          then
1418             Error_Msg_N
1419               ("by_reference actual may be misaligned?", Actual);
1420             return False;
1421
1422          else
1423             return True;
1424          end if;
1425       end Is_Legal_Copy;
1426
1427       --------------
1428       -- Make_Var --
1429       --------------
1430
1431       function Make_Var (Actual : Node_Id) return Entity_Id is
1432          Var : Entity_Id;
1433
1434       begin
1435          if Is_Entity_Name (Actual) then
1436             return Entity (Actual);
1437
1438          else
1439             Var := Make_Temporary (Loc, 'T', Actual);
1440
1441             N_Node :=
1442               Make_Object_Renaming_Declaration (Loc,
1443                 Defining_Identifier => Var,
1444                 Subtype_Mark        =>
1445                   New_Occurrence_Of (Etype (Actual), Loc),
1446                 Name                => Relocate_Node (Actual));
1447
1448             Insert_Action (N, N_Node);
1449             return Var;
1450          end if;
1451       end Make_Var;
1452
1453       -------------------------
1454       -- Reset_Packed_Prefix --
1455       -------------------------
1456
1457       procedure Reset_Packed_Prefix is
1458          Pfx : Node_Id := Actual;
1459       begin
1460          loop
1461             Set_Analyzed (Pfx, False);
1462             exit when
1463               not Nkind_In (Pfx, N_Selected_Component, N_Indexed_Component);
1464             Pfx := Prefix (Pfx);
1465          end loop;
1466       end Reset_Packed_Prefix;
1467
1468    --  Start of processing for Expand_Actuals
1469
1470    begin
1471       Post_Call := New_List;
1472
1473       Formal := First_Formal (Subp);
1474       Actual := First_Actual (N);
1475       while Present (Formal) loop
1476          E_Formal := Etype (Formal);
1477
1478          if Is_Scalar_Type (E_Formal)
1479            or else Nkind (Actual) = N_Slice
1480          then
1481             Check_Fortran_Logical;
1482
1483          --  RM 6.4.1 (11)
1484
1485          elsif Ekind (Formal) /= E_Out_Parameter then
1486
1487             --  The unusual case of the current instance of a protected type
1488             --  requires special handling. This can only occur in the context
1489             --  of a call within the body of a protected operation.
1490
1491             if Is_Entity_Name (Actual)
1492               and then Ekind (Entity (Actual)) = E_Protected_Type
1493               and then In_Open_Scopes (Entity (Actual))
1494             then
1495                if Scope (Subp) /= Entity (Actual) then
1496                   Error_Msg_N ("operation outside protected type may not "
1497                     & "call back its protected operations?", Actual);
1498                end if;
1499
1500                Rewrite (Actual,
1501                  Expand_Protected_Object_Reference (N, Entity (Actual)));
1502             end if;
1503
1504             --  Ada 2005 (AI-318-02): If the actual parameter is a call to a
1505             --  build-in-place function, then a temporary return object needs
1506             --  to be created and access to it must be passed to the function.
1507             --  Currently we limit such functions to those with inherently
1508             --  limited result subtypes, but eventually we plan to expand the
1509             --  functions that are treated as build-in-place to include other
1510             --  composite result types.
1511
1512             if Is_Build_In_Place_Function_Call (Actual) then
1513                Make_Build_In_Place_Call_In_Anonymous_Context (Actual);
1514             end if;
1515
1516             Apply_Constraint_Check (Actual, E_Formal);
1517
1518          --  Out parameter case. No constraint checks on access type
1519          --  RM 6.4.1 (13)
1520
1521          elsif Is_Access_Type (E_Formal) then
1522             null;
1523
1524          --  RM 6.4.1 (14)
1525
1526          elsif Has_Discriminants (Base_Type (E_Formal))
1527            or else Has_Non_Null_Base_Init_Proc (E_Formal)
1528          then
1529             Apply_Constraint_Check (Actual, E_Formal);
1530
1531          --  RM 6.4.1 (15)
1532
1533          else
1534             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
1535          end if;
1536
1537          --  Processing for IN-OUT and OUT parameters
1538
1539          if Ekind (Formal) /= E_In_Parameter then
1540
1541             --  For type conversions of arrays, apply length/range checks
1542
1543             if Is_Array_Type (E_Formal)
1544               and then Nkind (Actual) = N_Type_Conversion
1545             then
1546                if Is_Constrained (E_Formal) then
1547                   Apply_Length_Check (Expression (Actual), E_Formal);
1548                else
1549                   Apply_Range_Check (Expression (Actual), E_Formal);
1550                end if;
1551             end if;
1552
1553             --  If argument is a type conversion for a type that is passed
1554             --  by copy, then we must pass the parameter by copy.
1555
1556             if Nkind (Actual) = N_Type_Conversion
1557               and then
1558                 (Is_Numeric_Type (E_Formal)
1559                   or else Is_Access_Type (E_Formal)
1560                   or else Is_Enumeration_Type (E_Formal)
1561                   or else Is_Bit_Packed_Array (Etype (Formal))
1562                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
1563
1564                   --  Also pass by copy if change of representation
1565
1566                   or else not Same_Representation
1567                                (Etype (Formal),
1568                                 Etype (Expression (Actual))))
1569             then
1570                Add_Call_By_Copy_Code;
1571
1572             --  References to components of bit packed arrays are expanded
1573             --  at this point, rather than at the point of analysis of the
1574             --  actuals, to handle the expansion of the assignment to
1575             --  [in] out parameters.
1576
1577             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1578                Add_Simple_Call_By_Copy_Code;
1579
1580             --  If a non-scalar actual is possibly bit-aligned, we need a copy
1581             --  because the back-end cannot cope with such objects. In other
1582             --  cases where alignment forces a copy, the back-end generates
1583             --  it properly. It should not be generated unconditionally in the
1584             --  front-end because it does not know precisely the alignment
1585             --  requirements of the target, and makes too conservative an
1586             --  estimate, leading to superfluous copies or spurious errors
1587             --  on by-reference parameters.
1588
1589             elsif Nkind (Actual) = N_Selected_Component
1590               and then
1591                 Component_May_Be_Bit_Aligned (Entity (Selector_Name (Actual)))
1592               and then not Represented_As_Scalar (Etype (Formal))
1593             then
1594                Add_Simple_Call_By_Copy_Code;
1595
1596             --  References to slices of bit packed arrays are expanded
1597
1598             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1599                Add_Call_By_Copy_Code;
1600
1601             --  References to possibly unaligned slices of arrays are expanded
1602
1603             elsif Is_Possibly_Unaligned_Slice (Actual) then
1604                Add_Call_By_Copy_Code;
1605
1606             --  Deal with access types where the actual subtype and the
1607             --  formal subtype are not the same, requiring a check.
1608
1609             --  It is necessary to exclude tagged types because of "downward
1610             --  conversion" errors.
1611
1612             elsif Is_Access_Type (E_Formal)
1613               and then not Same_Type (E_Formal, Etype (Actual))
1614               and then not Is_Tagged_Type (Designated_Type (E_Formal))
1615             then
1616                Add_Call_By_Copy_Code;
1617
1618             --  If the actual is not a scalar and is marked for volatile
1619             --  treatment, whereas the formal is not volatile, then pass
1620             --  by copy unless it is a by-reference type.
1621
1622             --  Note: we use Is_Volatile here rather than Treat_As_Volatile,
1623             --  because this is the enforcement of a language rule that applies
1624             --  only to "real" volatile variables, not e.g. to the address
1625             --  clause overlay case.
1626
1627             elsif Is_Entity_Name (Actual)
1628               and then Is_Volatile (Entity (Actual))
1629               and then not Is_By_Reference_Type (Etype (Actual))
1630               and then not Is_Scalar_Type (Etype (Entity (Actual)))
1631               and then not Is_Volatile (E_Formal)
1632             then
1633                Add_Call_By_Copy_Code;
1634
1635             elsif Nkind (Actual) = N_Indexed_Component
1636               and then Is_Entity_Name (Prefix (Actual))
1637               and then Has_Volatile_Components (Entity (Prefix (Actual)))
1638             then
1639                Add_Call_By_Copy_Code;
1640
1641             --  Add call-by-copy code for the case of scalar out parameters
1642             --  when it is not known at compile time that the subtype of the
1643             --  formal is a subrange of the subtype of the actual (or vice
1644             --  versa for in out parameters), in order to get range checks
1645             --  on such actuals. (Maybe this case should be handled earlier
1646             --  in the if statement???)
1647
1648             elsif Is_Scalar_Type (E_Formal)
1649               and then
1650                 (not In_Subrange_Of (E_Formal, Etype (Actual))
1651                   or else
1652                     (Ekind (Formal) = E_In_Out_Parameter
1653                       and then not In_Subrange_Of (Etype (Actual), E_Formal)))
1654             then
1655                --  Perhaps the setting back to False should be done within
1656                --  Add_Call_By_Copy_Code, since it could get set on other
1657                --  cases occurring above???
1658
1659                if Do_Range_Check (Actual) then
1660                   Set_Do_Range_Check (Actual, False);
1661                end if;
1662
1663                Add_Call_By_Copy_Code;
1664             end if;
1665
1666          --  Processing for IN parameters
1667
1668          else
1669             --  For IN parameters is in the packed array case, we expand an
1670             --  indexed component (the circuit in Exp_Ch4 deliberately left
1671             --  indexed components appearing as actuals untouched, so that
1672             --  the special processing above for the OUT and IN OUT cases
1673             --  could be performed. We could make the test in Exp_Ch4 more
1674             --  complex and have it detect the parameter mode, but it is
1675             --  easier simply to handle all cases here.)
1676
1677             if Nkind (Actual) = N_Indexed_Component
1678               and then Is_Packed (Etype (Prefix (Actual)))
1679             then
1680                Reset_Packed_Prefix;
1681                Expand_Packed_Element_Reference (Actual);
1682
1683             --  If we have a reference to a bit packed array, we copy it, since
1684             --  the actual must be byte aligned.
1685
1686             --  Is this really necessary in all cases???
1687
1688             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1689                Add_Simple_Call_By_Copy_Code;
1690
1691             --  If a non-scalar actual is possibly unaligned, we need a copy
1692
1693             elsif Is_Possibly_Unaligned_Object (Actual)
1694               and then not Represented_As_Scalar (Etype (Formal))
1695             then
1696                Add_Simple_Call_By_Copy_Code;
1697
1698             --  Similarly, we have to expand slices of packed arrays here
1699             --  because the result must be byte aligned.
1700
1701             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1702                Add_Call_By_Copy_Code;
1703
1704             --  Only processing remaining is to pass by copy if this is a
1705             --  reference to a possibly unaligned slice, since the caller
1706             --  expects an appropriately aligned argument.
1707
1708             elsif Is_Possibly_Unaligned_Slice (Actual) then
1709                Add_Call_By_Copy_Code;
1710
1711             --  An unusual case: a current instance of an enclosing task can be
1712             --  an actual, and must be replaced by a reference to self.
1713
1714             elsif Is_Entity_Name (Actual)
1715               and then Is_Task_Type (Entity (Actual))
1716             then
1717                if In_Open_Scopes (Entity (Actual)) then
1718                   Rewrite (Actual,
1719                     (Make_Function_Call (Loc,
1720                      Name => New_Reference_To (RTE (RE_Self), Loc))));
1721                   Analyze (Actual);
1722
1723                --  A task type cannot otherwise appear as an actual
1724
1725                else
1726                   raise Program_Error;
1727                end if;
1728             end if;
1729          end if;
1730
1731          Next_Formal (Formal);
1732          Next_Actual (Actual);
1733       end loop;
1734
1735       --  Find right place to put post call stuff if it is present
1736
1737       if not Is_Empty_List (Post_Call) then
1738
1739          --  If call is not a list member, it must be the triggering statement
1740          --  of a triggering alternative or an entry call alternative, and we
1741          --  can add the post call stuff to the corresponding statement list.
1742
1743          if not Is_List_Member (N) then
1744             declare
1745                P : constant Node_Id := Parent (N);
1746
1747             begin
1748                pragma Assert (Nkind_In (P, N_Triggering_Alternative,
1749                                            N_Entry_Call_Alternative));
1750
1751                if Is_Non_Empty_List (Statements (P)) then
1752                   Insert_List_Before_And_Analyze
1753                     (First (Statements (P)), Post_Call);
1754                else
1755                   Set_Statements (P, Post_Call);
1756                end if;
1757             end;
1758
1759          --  Otherwise, normal case where N is in a statement sequence,
1760          --  just put the post-call stuff after the call statement.
1761
1762          else
1763             Insert_Actions_After (N, Post_Call);
1764          end if;
1765       end if;
1766
1767       --  The call node itself is re-analyzed in Expand_Call
1768
1769    end Expand_Actuals;
1770
1771    -----------------
1772    -- Expand_Call --
1773    -----------------
1774
1775    --  This procedure handles expansion of function calls and procedure call
1776    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1777    --  Expand_N_Procedure_Call_Statement). Processing for calls includes:
1778
1779    --    Replace call to Raise_Exception by Raise_Exception_Always if possible
1780    --    Provide values of actuals for all formals in Extra_Formals list
1781    --    Replace "call" to enumeration literal function by literal itself
1782    --    Rewrite call to predefined operator as operator
1783    --    Replace actuals to in-out parameters that are numeric conversions,
1784    --     with explicit assignment to temporaries before and after the call.
1785    --    Remove optional actuals if First_Optional_Parameter specified.
1786
1787    --   Note that the list of actuals has been filled with default expressions
1788    --   during semantic analysis of the call. Only the extra actuals required
1789    --   for the 'Constrained attribute and for accessibility checks are added
1790    --   at this point.
1791
1792    procedure Expand_Call (N : Node_Id) is
1793       Loc           : constant Source_Ptr := Sloc (N);
1794       Call_Node     : Node_Id := N;
1795       Extra_Actuals : List_Id := No_List;
1796       Prev          : Node_Id := Empty;
1797
1798       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1799       --  Adds one entry to the end of the actual parameter list. Used for
1800       --  default parameters and for extra actuals (for Extra_Formals). The
1801       --  argument is an N_Parameter_Association node.
1802
1803       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1804       --  Adds an extra actual to the list of extra actuals. Expr is the
1805       --  expression for the value of the actual, EF is the entity for the
1806       --  extra formal.
1807
1808       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1809       --  Within an instance, a type derived from a non-tagged formal derived
1810       --  type inherits from the original parent, not from the actual. The
1811       --  current derivation mechanism has the derived type inherit from the
1812       --  actual, which is only correct outside of the instance. If the
1813       --  subprogram is inherited, we test for this particular case through a
1814       --  convoluted tree traversal before setting the proper subprogram to be
1815       --  called.
1816
1817       function Is_Direct_Deep_Call (Subp : Entity_Id) return Boolean;
1818       --  Determine if Subp denotes a non-dispatching call to a Deep routine
1819
1820       function New_Value (From : Node_Id) return Node_Id;
1821       --  From is the original Expression. New_Value is equivalent to a call
1822       --  to Duplicate_Subexpr with an explicit dereference when From is an
1823       --  access parameter.
1824
1825       --------------------------
1826       -- Add_Actual_Parameter --
1827       --------------------------
1828
1829       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1830          Actual_Expr : constant Node_Id :=
1831                          Explicit_Actual_Parameter (Insert_Param);
1832
1833       begin
1834          --  Case of insertion is first named actual
1835
1836          if No (Prev) or else
1837             Nkind (Parent (Prev)) /= N_Parameter_Association
1838          then
1839             Set_Next_Named_Actual
1840               (Insert_Param, First_Named_Actual (Call_Node));
1841             Set_First_Named_Actual (Call_Node, Actual_Expr);
1842
1843             if No (Prev) then
1844                if No (Parameter_Associations (Call_Node)) then
1845                   Set_Parameter_Associations (Call_Node, New_List);
1846                   Append (Insert_Param, Parameter_Associations (Call_Node));
1847                end if;
1848             else
1849                Insert_After (Prev, Insert_Param);
1850             end if;
1851
1852          --  Case of insertion is not first named actual
1853
1854          else
1855             Set_Next_Named_Actual
1856               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1857             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1858             Append (Insert_Param, Parameter_Associations (Call_Node));
1859          end if;
1860
1861          Prev := Actual_Expr;
1862       end Add_Actual_Parameter;
1863
1864       ----------------------
1865       -- Add_Extra_Actual --
1866       ----------------------
1867
1868       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1869          Loc : constant Source_Ptr := Sloc (Expr);
1870
1871       begin
1872          if Extra_Actuals = No_List then
1873             Extra_Actuals := New_List;
1874             Set_Parent (Extra_Actuals, Call_Node);
1875          end if;
1876
1877          Append_To (Extra_Actuals,
1878            Make_Parameter_Association (Loc,
1879              Selector_Name             => Make_Identifier (Loc, Chars (EF)),
1880              Explicit_Actual_Parameter => Expr));
1881
1882          Analyze_And_Resolve (Expr, Etype (EF));
1883
1884          if Nkind (Call_Node) = N_Function_Call then
1885             Set_Is_Accessibility_Actual (Parent (Expr));
1886          end if;
1887       end Add_Extra_Actual;
1888
1889       ---------------------------
1890       -- Inherited_From_Formal --
1891       ---------------------------
1892
1893       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1894          Par      : Entity_Id;
1895          Gen_Par  : Entity_Id;
1896          Gen_Prim : Elist_Id;
1897          Elmt     : Elmt_Id;
1898          Indic    : Node_Id;
1899
1900       begin
1901          --  If the operation is inherited, it is attached to the corresponding
1902          --  type derivation. If the parent in the derivation is a generic
1903          --  actual, it is a subtype of the actual, and we have to recover the
1904          --  original derived type declaration to find the proper parent.
1905
1906          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1907            or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1908            or else Nkind (Type_Definition (Original_Node (Parent (S)))) /=
1909                                                    N_Derived_Type_Definition
1910            or else not In_Instance
1911          then
1912             return Empty;
1913
1914          else
1915             Indic :=
1916               Subtype_Indication
1917                 (Type_Definition (Original_Node (Parent (S))));
1918
1919             if Nkind (Indic) = N_Subtype_Indication then
1920                Par := Entity (Subtype_Mark (Indic));
1921             else
1922                Par := Entity (Indic);
1923             end if;
1924          end if;
1925
1926          if not Is_Generic_Actual_Type (Par)
1927            or else Is_Tagged_Type (Par)
1928            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1929            or else not In_Open_Scopes (Scope (Par))
1930          then
1931             return Empty;
1932          else
1933             Gen_Par := Generic_Parent_Type (Parent (Par));
1934          end if;
1935
1936          --  If the actual has no generic parent type, the formal is not
1937          --  a formal derived type, so nothing to inherit.
1938
1939          if No (Gen_Par) then
1940             return Empty;
1941          end if;
1942
1943          --  If the generic parent type is still the generic type, this is a
1944          --  private formal, not a derived formal, and there are no operations
1945          --  inherited from the formal.
1946
1947          if Nkind (Parent (Gen_Par)) = N_Formal_Type_Declaration then
1948             return Empty;
1949          end if;
1950
1951          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1952
1953          Elmt := First_Elmt (Gen_Prim);
1954          while Present (Elmt) loop
1955             if Chars (Node (Elmt)) = Chars (S) then
1956                declare
1957                   F1 : Entity_Id;
1958                   F2 : Entity_Id;
1959
1960                begin
1961                   F1 := First_Formal (S);
1962                   F2 := First_Formal (Node (Elmt));
1963                   while Present (F1)
1964                     and then Present (F2)
1965                   loop
1966                      if Etype (F1) = Etype (F2)
1967                        or else Etype (F2) = Gen_Par
1968                      then
1969                         Next_Formal (F1);
1970                         Next_Formal (F2);
1971                      else
1972                         Next_Elmt (Elmt);
1973                         exit;   --  not the right subprogram
1974                      end if;
1975
1976                      return Node (Elmt);
1977                   end loop;
1978                end;
1979
1980             else
1981                Next_Elmt (Elmt);
1982             end if;
1983          end loop;
1984
1985          raise Program_Error;
1986       end Inherited_From_Formal;
1987
1988       -------------------------
1989       -- Is_Direct_Deep_Call --
1990       -------------------------
1991
1992       function Is_Direct_Deep_Call (Subp : Entity_Id) return Boolean is
1993       begin
1994          if Is_TSS (Subp, TSS_Deep_Adjust)
1995            or else Is_TSS (Subp, TSS_Deep_Finalize)
1996            or else Is_TSS (Subp, TSS_Deep_Initialize)
1997          then
1998             declare
1999                Actual : Node_Id;
2000                Formal : Node_Id;
2001
2002             begin
2003                Actual := First (Parameter_Associations (N));
2004                Formal := First_Formal (Subp);
2005                while Present (Actual)
2006                  and then Present (Formal)
2007                loop
2008                   if Nkind (Actual) = N_Identifier
2009                     and then Is_Controlling_Actual (Actual)
2010                     and then Etype (Actual) = Etype (Formal)
2011                   then
2012                      return True;
2013                   end if;
2014
2015                   Next (Actual);
2016                   Next_Formal (Formal);
2017                end loop;
2018             end;
2019          end if;
2020
2021          return False;
2022       end Is_Direct_Deep_Call;
2023
2024       ---------------
2025       -- New_Value --
2026       ---------------
2027
2028       function New_Value (From : Node_Id) return Node_Id is
2029          Res : constant Node_Id := Duplicate_Subexpr (From);
2030       begin
2031          if Is_Access_Type (Etype (From)) then
2032             return
2033               Make_Explicit_Dereference (Sloc (From),
2034                 Prefix => Res);
2035          else
2036             return Res;
2037          end if;
2038       end New_Value;
2039
2040       --  Local variables
2041
2042       Curr_S        : constant Entity_Id := Current_Scope;
2043       Remote        : constant Boolean   := Is_Remote_Call (Call_Node);
2044       Actual        : Node_Id;
2045       Formal        : Entity_Id;
2046       Orig_Subp     : Entity_Id := Empty;
2047       Param_Count   : Natural := 0;
2048       Parent_Formal : Entity_Id;
2049       Parent_Subp   : Entity_Id;
2050       Scop          : Entity_Id;
2051       Subp          : Entity_Id;
2052
2053       Prev_Orig : Node_Id;
2054       --  Original node for an actual, which may have been rewritten. If the
2055       --  actual is a function call that has been transformed from a selected
2056       --  component, the original node is unanalyzed. Otherwise, it carries
2057       --  semantic information used to generate additional actuals.
2058
2059       CW_Interface_Formals_Present : Boolean := False;
2060
2061    --  Start of processing for Expand_Call
2062
2063    begin
2064       --  Ignore if previous error
2065
2066       if Nkind (Call_Node) in N_Has_Etype
2067         and then Etype (Call_Node) = Any_Type
2068       then
2069          return;
2070       end if;
2071
2072       --  Call using access to subprogram with explicit dereference
2073
2074       if Nkind (Name (Call_Node)) = N_Explicit_Dereference then
2075          Subp        := Etype (Name (Call_Node));
2076          Parent_Subp := Empty;
2077
2078       --  Case of call to simple entry, where the Name is a selected component
2079       --  whose prefix is the task, and whose selector name is the entry name
2080
2081       elsif Nkind (Name (Call_Node)) = N_Selected_Component then
2082          Subp        := Entity (Selector_Name (Name (Call_Node)));
2083          Parent_Subp := Empty;
2084
2085       --  Case of call to member of entry family, where Name is an indexed
2086       --  component, with the prefix being a selected component giving the
2087       --  task and entry family name, and the index being the entry index.
2088
2089       elsif Nkind (Name (Call_Node)) = N_Indexed_Component then
2090          Subp        := Entity (Selector_Name (Prefix (Name (Call_Node))));
2091          Parent_Subp := Empty;
2092
2093       --  Normal case
2094
2095       else
2096          Subp        := Entity (Name (Call_Node));
2097          Parent_Subp := Alias (Subp);
2098
2099          --  Replace call to Raise_Exception by call to Raise_Exception_Always
2100          --  if we can tell that the first parameter cannot possibly be null.
2101          --  This improves efficiency by avoiding a run-time test.
2102
2103          --  We do not do this if Raise_Exception_Always does not exist, which
2104          --  can happen in configurable run time profiles which provide only a
2105          --  Raise_Exception.
2106
2107          if Is_RTE (Subp, RE_Raise_Exception)
2108            and then RTE_Available (RE_Raise_Exception_Always)
2109          then
2110             declare
2111                FA : constant Node_Id :=
2112                       Original_Node (First_Actual (Call_Node));
2113
2114             begin
2115                --  The case we catch is where the first argument is obtained
2116                --  using the Identity attribute (which must always be
2117                --  non-null).
2118
2119                if Nkind (FA) = N_Attribute_Reference
2120                  and then Attribute_Name (FA) = Name_Identity
2121                then
2122                   Subp := RTE (RE_Raise_Exception_Always);
2123                   Set_Name (Call_Node, New_Occurrence_Of (Subp, Loc));
2124                end if;
2125             end;
2126          end if;
2127
2128          if Ekind (Subp) = E_Entry then
2129             Parent_Subp := Empty;
2130          end if;
2131       end if;
2132
2133       --  Detect the following code in System.Finalization_Masters only on
2134       --  .NET/JVM targets:
2135       --
2136       --    procedure Finalize (Master : in out Finalization_Master) is
2137       --    begin
2138       --       . . .
2139       --       begin
2140       --          Finalize (Curr_Ptr.all);
2141       --
2142       --  Since .NET/JVM compilers lack address arithmetic and Deep_Finalize
2143       --  cannot be named in library or user code, the compiler has to install
2144       --  a kludge and transform the call to Finalize into Deep_Finalize.
2145
2146       if VM_Target /= No_VM
2147         and then Chars (Subp) = Name_Finalize
2148         and then Ekind (Curr_S) = E_Block
2149         and then Ekind (Scope (Curr_S)) = E_Procedure
2150         and then Chars (Scope (Curr_S)) = Name_Finalize
2151         and then Etype (First_Formal (Scope (Curr_S))) =
2152                    RTE (RE_Finalization_Master)
2153       then
2154          declare
2155             Deep_Fin : constant Entity_Id :=
2156                          Find_Prim_Op (RTE (RE_Root_Controlled),
2157                                        TSS_Deep_Finalize);
2158          begin
2159             --  Since Root_Controlled is a tagged type, the compiler should
2160             --  always generate Deep_Finalize for it.
2161
2162             pragma Assert (Present (Deep_Fin));
2163
2164             --  Generate:
2165             --    Deep_Finalize (Curr_Ptr.all);
2166
2167             Rewrite (N,
2168               Make_Procedure_Call_Statement (Loc,
2169                 Name =>
2170                   New_Reference_To (Deep_Fin, Loc),
2171                 Parameter_Associations =>
2172                   New_Copy_List_Tree (Parameter_Associations (N))));
2173
2174             Analyze (N);
2175             return;
2176          end;
2177       end if;
2178
2179       --  Ada 2005 (AI-345): We have a procedure call as a triggering
2180       --  alternative in an asynchronous select or as an entry call in
2181       --  a conditional or timed select. Check whether the procedure call
2182       --  is a renaming of an entry and rewrite it as an entry call.
2183
2184       if Ada_Version >= Ada_2005
2185         and then Nkind (Call_Node) = N_Procedure_Call_Statement
2186         and then
2187            ((Nkind (Parent (Call_Node)) = N_Triggering_Alternative
2188               and then Triggering_Statement (Parent (Call_Node)) = Call_Node)
2189           or else
2190             (Nkind (Parent (Call_Node)) = N_Entry_Call_Alternative
2191               and then Entry_Call_Statement (Parent (Call_Node)) = Call_Node))
2192       then
2193          declare
2194             Ren_Decl : Node_Id;
2195             Ren_Root : Entity_Id := Subp;
2196
2197          begin
2198             --  This may be a chain of renamings, find the root
2199
2200             if Present (Alias (Ren_Root)) then
2201                Ren_Root := Alias (Ren_Root);
2202             end if;
2203
2204             if Present (Original_Node (Parent (Parent (Ren_Root)))) then
2205                Ren_Decl := Original_Node (Parent (Parent (Ren_Root)));
2206
2207                if Nkind (Ren_Decl) = N_Subprogram_Renaming_Declaration then
2208                   Rewrite (Call_Node,
2209                     Make_Entry_Call_Statement (Loc,
2210                       Name =>
2211                         New_Copy_Tree (Name (Ren_Decl)),
2212                       Parameter_Associations =>
2213                         New_Copy_List_Tree
2214                           (Parameter_Associations (Call_Node))));
2215
2216                   return;
2217                end if;
2218             end if;
2219          end;
2220       end if;
2221
2222       --  First step, compute extra actuals, corresponding to any Extra_Formals
2223       --  present. Note that we do not access Extra_Formals directly, instead
2224       --  we simply note the presence of the extra formals as we process the
2225       --  regular formals collecting corresponding actuals in Extra_Actuals.
2226
2227       --  We also generate any required range checks for actuals for in formals
2228       --  as we go through the loop, since this is a convenient place to do it.
2229       --  (Though it seems that this would be better done in Expand_Actuals???)
2230
2231       Formal := First_Formal (Subp);
2232       Actual := First_Actual (Call_Node);
2233       Param_Count := 1;
2234       while Present (Formal) loop
2235
2236          --  Generate range check if required
2237
2238          if Do_Range_Check (Actual)
2239            and then Ekind (Formal) = E_In_Parameter
2240          then
2241             Set_Do_Range_Check (Actual, False);
2242             Generate_Range_Check
2243               (Actual, Etype (Formal), CE_Range_Check_Failed);
2244          end if;
2245
2246          --  Prepare to examine current entry
2247
2248          Prev := Actual;
2249          Prev_Orig := Original_Node (Prev);
2250
2251          --  Ada 2005 (AI-251): Check if any formal is a class-wide interface
2252          --  to expand it in a further round.
2253
2254          CW_Interface_Formals_Present :=
2255            CW_Interface_Formals_Present
2256              or else
2257                (Ekind (Etype (Formal)) = E_Class_Wide_Type
2258                  and then Is_Interface (Etype (Etype (Formal))))
2259              or else
2260                (Ekind (Etype (Formal)) = E_Anonymous_Access_Type
2261                  and then Is_Interface (Directly_Designated_Type
2262                                          (Etype (Etype (Formal)))));
2263
2264          --  Create possible extra actual for constrained case. Usually, the
2265          --  extra actual is of the form actual'constrained, but since this
2266          --  attribute is only available for unconstrained records, TRUE is
2267          --  expanded if the type of the formal happens to be constrained (for
2268          --  instance when this procedure is inherited from an unconstrained
2269          --  record to a constrained one) or if the actual has no discriminant
2270          --  (its type is constrained). An exception to this is the case of a
2271          --  private type without discriminants. In this case we pass FALSE
2272          --  because the object has underlying discriminants with defaults.
2273
2274          if Present (Extra_Constrained (Formal)) then
2275             if Ekind (Etype (Prev)) in Private_Kind
2276               and then not Has_Discriminants (Base_Type (Etype (Prev)))
2277             then
2278                Add_Extra_Actual
2279                  (New_Occurrence_Of (Standard_False, Loc),
2280                   Extra_Constrained (Formal));
2281
2282             elsif Is_Constrained (Etype (Formal))
2283               or else not Has_Discriminants (Etype (Prev))
2284             then
2285                Add_Extra_Actual
2286                  (New_Occurrence_Of (Standard_True, Loc),
2287                   Extra_Constrained (Formal));
2288
2289             --  Do not produce extra actuals for Unchecked_Union parameters.
2290             --  Jump directly to the end of the loop.
2291
2292             elsif Is_Unchecked_Union (Base_Type (Etype (Actual))) then
2293                goto Skip_Extra_Actual_Generation;
2294
2295             else
2296                --  If the actual is a type conversion, then the constrained
2297                --  test applies to the actual, not the target type.
2298
2299                declare
2300                   Act_Prev : Node_Id;
2301
2302                begin
2303                   --  Test for unchecked conversions as well, which can occur
2304                   --  as out parameter actuals on calls to stream procedures.
2305
2306                   Act_Prev := Prev;
2307                   while Nkind_In (Act_Prev, N_Type_Conversion,
2308                                             N_Unchecked_Type_Conversion)
2309                   loop
2310                      Act_Prev := Expression (Act_Prev);
2311                   end loop;
2312
2313                   --  If the expression is a conversion of a dereference, this
2314                   --  is internally generated code that manipulates addresses,
2315                   --  e.g. when building interface tables. No check should
2316                   --  occur in this case, and the discriminated object is not
2317                   --  directly a hand.
2318
2319                   if not Comes_From_Source (Actual)
2320                     and then Nkind (Actual) = N_Unchecked_Type_Conversion
2321                     and then Nkind (Act_Prev) = N_Explicit_Dereference
2322                   then
2323                      Add_Extra_Actual
2324                        (New_Occurrence_Of (Standard_False, Loc),
2325                         Extra_Constrained (Formal));
2326
2327                   else
2328                      Add_Extra_Actual
2329                        (Make_Attribute_Reference (Sloc (Prev),
2330                         Prefix =>
2331                           Duplicate_Subexpr_No_Checks
2332                             (Act_Prev, Name_Req => True),
2333                         Attribute_Name => Name_Constrained),
2334                         Extra_Constrained (Formal));
2335                   end if;
2336                end;
2337             end if;
2338          end if;
2339
2340          --  Create possible extra actual for accessibility level
2341
2342          if Present (Extra_Accessibility (Formal)) then
2343
2344             --  Ada 2005 (AI-252): If the actual was rewritten as an Access
2345             --  attribute, then the original actual may be an aliased object
2346             --  occurring as the prefix in a call using "Object.Operation"
2347             --  notation. In that case we must pass the level of the object,
2348             --  so Prev_Orig is reset to Prev and the attribute will be
2349             --  processed by the code for Access attributes further below.
2350
2351             if Prev_Orig /= Prev
2352               and then Nkind (Prev) = N_Attribute_Reference
2353               and then
2354                 Get_Attribute_Id (Attribute_Name (Prev)) = Attribute_Access
2355               and then Is_Aliased_View (Prev_Orig)
2356             then
2357                Prev_Orig := Prev;
2358             end if;
2359
2360             --  Ada 2005 (AI-251): Thunks must propagate the extra actuals of
2361             --  accessibility levels.
2362
2363             if Ekind (Current_Scope) in Subprogram_Kind
2364               and then Is_Thunk (Current_Scope)
2365             then
2366                declare
2367                   Parm_Ent : Entity_Id;
2368
2369                begin
2370                   if Is_Controlling_Actual (Actual) then
2371
2372                      --  Find the corresponding actual of the thunk
2373
2374                      Parm_Ent := First_Entity (Current_Scope);
2375                      for J in 2 .. Param_Count loop
2376                         Next_Entity (Parm_Ent);
2377                      end loop;
2378
2379                   else pragma Assert (Is_Entity_Name (Actual));
2380                      Parm_Ent := Entity (Actual);
2381                   end if;
2382
2383                   Add_Extra_Actual
2384                     (New_Occurrence_Of (Extra_Accessibility (Parm_Ent), Loc),
2385                      Extra_Accessibility (Formal));
2386                end;
2387
2388             elsif Is_Entity_Name (Prev_Orig) then
2389
2390                --  When passing an access parameter, or a renaming of an access
2391                --  parameter, as the actual to another access parameter we need
2392                --  to pass along the actual's own access level parameter. This
2393                --  is done if we are within the scope of the formal access
2394                --  parameter (if this is an inlined body the extra formal is
2395                --  irrelevant).
2396
2397                if (Is_Formal (Entity (Prev_Orig))
2398                     or else
2399                       (Present (Renamed_Object (Entity (Prev_Orig)))
2400                         and then
2401                           Is_Entity_Name (Renamed_Object (Entity (Prev_Orig)))
2402                         and then
2403                           Is_Formal
2404                             (Entity (Renamed_Object (Entity (Prev_Orig))))))
2405                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
2406                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
2407                then
2408                   declare
2409                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
2410
2411                   begin
2412                      pragma Assert (Present (Parm_Ent));
2413
2414                      if Present (Extra_Accessibility (Parm_Ent)) then
2415                         Add_Extra_Actual
2416                           (New_Occurrence_Of
2417                              (Extra_Accessibility (Parm_Ent), Loc),
2418                            Extra_Accessibility (Formal));
2419
2420                      --  If the actual access parameter does not have an
2421                      --  associated extra formal providing its scope level,
2422                      --  then treat the actual as having library-level
2423                      --  accessibility.
2424
2425                      else
2426                         Add_Extra_Actual
2427                           (Make_Integer_Literal (Loc,
2428                              Intval => Scope_Depth (Standard_Standard)),
2429                            Extra_Accessibility (Formal));
2430                      end if;
2431                   end;
2432
2433                --  The actual is a normal access value, so just pass the level
2434                --  of the actual's access type.
2435
2436                else
2437                   Add_Extra_Actual
2438                     (Dynamic_Accessibility_Level (Prev_Orig),
2439                      Extra_Accessibility (Formal));
2440                end if;
2441
2442             --  If the actual is an access discriminant, then pass the level
2443             --  of the enclosing object (RM05-3.10.2(12.4/2)).
2444
2445             elsif Nkind (Prev_Orig) = N_Selected_Component
2446               and then Ekind (Entity (Selector_Name (Prev_Orig))) =
2447                                                        E_Discriminant
2448               and then Ekind (Etype (Entity (Selector_Name (Prev_Orig)))) =
2449                                                        E_Anonymous_Access_Type
2450             then
2451                Add_Extra_Actual
2452                  (Make_Integer_Literal (Loc,
2453                     Intval => Object_Access_Level (Prefix (Prev_Orig))),
2454                   Extra_Accessibility (Formal));
2455
2456             --  All other cases
2457
2458             else
2459                case Nkind (Prev_Orig) is
2460
2461                   when N_Attribute_Reference =>
2462                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
2463
2464                         --  For X'Access, pass on the level of the prefix X
2465
2466                         when Attribute_Access =>
2467
2468                            --  If this is an Access attribute applied to the
2469                            --  the current instance object passed to a type
2470                            --  initialization procedure, then use the level
2471                            --  of the type itself. This is not really correct,
2472                            --  as there should be an extra level parameter
2473                            --  passed in with _init formals (only in the case
2474                            --  where the type is immutably limited), but we
2475                            --  don't have an easy way currently to create such
2476                            --  an extra formal (init procs aren't ever frozen).
2477                            --  For now we just use the level of the type,
2478                            --  which may be too shallow, but that works better
2479                            --  than passing Object_Access_Level of the type,
2480                            --  which can be one level too deep in some cases.
2481                            --  ???
2482
2483                            if Is_Entity_Name (Prefix (Prev_Orig))
2484                              and then Is_Type (Entity (Prefix (Prev_Orig)))
2485                            then
2486                               Add_Extra_Actual
2487                                 (Make_Integer_Literal (Loc,
2488                                    Intval =>
2489                                      Type_Access_Level
2490                                        (Entity (Prefix (Prev_Orig)))),
2491                                  Extra_Accessibility (Formal));
2492
2493                            else
2494                               Add_Extra_Actual
2495                                 (Make_Integer_Literal (Loc,
2496                                    Intval =>
2497                                      Object_Access_Level
2498                                        (Prefix (Prev_Orig))),
2499                                  Extra_Accessibility (Formal));
2500                            end if;
2501
2502                         --  Treat the unchecked attributes as library-level
2503
2504                         when Attribute_Unchecked_Access |
2505                            Attribute_Unrestricted_Access =>
2506                            Add_Extra_Actual
2507                              (Make_Integer_Literal (Loc,
2508                                 Intval => Scope_Depth (Standard_Standard)),
2509                               Extra_Accessibility (Formal));
2510
2511                         --  No other cases of attributes returning access
2512                         --  values that can be passed to access parameters.
2513
2514                         when others =>
2515                            raise Program_Error;
2516
2517                      end case;
2518
2519                   --  For allocators we pass the level of the execution of the
2520                   --  called subprogram, which is one greater than the current
2521                   --  scope level.
2522
2523                   when N_Allocator =>
2524                      Add_Extra_Actual
2525                        (Make_Integer_Literal (Loc,
2526                           Intval => Scope_Depth (Current_Scope) + 1),
2527                         Extra_Accessibility (Formal));
2528
2529                   --  For most other cases we simply pass the level of the
2530                   --  actual's access type. The type is retrieved from
2531                   --  Prev rather than Prev_Orig, because in some cases
2532                   --  Prev_Orig denotes an original expression that has
2533                   --  not been analyzed.
2534
2535                   when others =>
2536                      Add_Extra_Actual
2537                        (Dynamic_Accessibility_Level (Prev),
2538                         Extra_Accessibility (Formal));
2539                end case;
2540             end if;
2541          end if;
2542
2543          --  Perform the check of 4.6(49) that prevents a null value from being
2544          --  passed as an actual to an access parameter. Note that the check
2545          --  is elided in the common cases of passing an access attribute or
2546          --  access parameter as an actual. Also, we currently don't enforce
2547          --  this check for expander-generated actuals and when -gnatdj is set.
2548
2549          if Ada_Version >= Ada_2005 then
2550
2551             --  Ada 2005 (AI-231): Check null-excluding access types. Note that
2552             --  the intent of 6.4.1(13) is that null-exclusion checks should
2553             --  not be done for 'out' parameters, even though it refers only
2554             --  to constraint checks, and a null_exclusion is not a constraint.
2555             --  Note that AI05-0196-1 corrects this mistake in the RM.
2556
2557             if Is_Access_Type (Etype (Formal))
2558               and then Can_Never_Be_Null (Etype (Formal))
2559               and then Ekind (Formal) /= E_Out_Parameter
2560               and then Nkind (Prev) /= N_Raise_Constraint_Error
2561               and then (Known_Null (Prev)
2562                          or else not Can_Never_Be_Null (Etype (Prev)))
2563             then
2564                Install_Null_Excluding_Check (Prev);
2565             end if;
2566
2567          --  Ada_Version < Ada_2005
2568
2569          else
2570             if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
2571               or else Access_Checks_Suppressed (Subp)
2572             then
2573                null;
2574
2575             elsif Debug_Flag_J then
2576                null;
2577
2578             elsif not Comes_From_Source (Prev) then
2579                null;
2580
2581             elsif Is_Entity_Name (Prev)
2582               and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
2583             then
2584                null;
2585
2586             elsif Nkind_In (Prev, N_Allocator, N_Attribute_Reference) then
2587                null;
2588
2589             --  Suppress null checks when passing to access parameters of Java
2590             --  and CIL subprograms. (Should this be done for other foreign
2591             --  conventions as well ???)
2592
2593             elsif Convention (Subp) = Convention_Java
2594               or else Convention (Subp) = Convention_CIL
2595             then
2596                null;
2597
2598             else
2599                Install_Null_Excluding_Check (Prev);
2600             end if;
2601          end if;
2602
2603          --  Perform appropriate validity checks on parameters that
2604          --  are entities.
2605
2606          if Validity_Checks_On then
2607             if  (Ekind (Formal) = E_In_Parameter
2608                   and then Validity_Check_In_Params)
2609               or else
2610                 (Ekind (Formal) = E_In_Out_Parameter
2611                   and then Validity_Check_In_Out_Params)
2612             then
2613                --  If the actual is an indexed component of a packed type (or
2614                --  is an indexed or selected component whose prefix recursively
2615                --  meets this condition), it has not been expanded yet. It will
2616                --  be copied in the validity code that follows, and has to be
2617                --  expanded appropriately, so reanalyze it.
2618
2619                --  What we do is just to unset analyzed bits on prefixes till
2620                --  we reach something that does not have a prefix.
2621
2622                declare
2623                   Nod : Node_Id;
2624
2625                begin
2626                   Nod := Actual;
2627                   while Nkind_In (Nod, N_Indexed_Component,
2628                                        N_Selected_Component)
2629                   loop
2630                      Set_Analyzed (Nod, False);
2631                      Nod := Prefix (Nod);
2632                   end loop;
2633                end;
2634
2635                Ensure_Valid (Actual);
2636             end if;
2637          end if;
2638
2639          --  For Ada 2012, if a parameter is aliased, the actual must be an
2640          --  aliased object.
2641
2642          if Is_Aliased (Formal) and then not Is_Aliased_View (Actual) then
2643             Error_Msg_NE
2644               ("actual for aliased formal& must be aliased object",
2645                Actual, Formal);
2646          end if;
2647
2648          --  For IN OUT and OUT parameters, ensure that subscripts are valid
2649          --  since this is a left side reference. We only do this for calls
2650          --  from the source program since we assume that compiler generated
2651          --  calls explicitly generate any required checks. We also need it
2652          --  only if we are doing standard validity checks, since clearly it is
2653          --  not needed if validity checks are off, and in subscript validity
2654          --  checking mode, all indexed components are checked with a call
2655          --  directly from Expand_N_Indexed_Component.
2656
2657          if Comes_From_Source (Call_Node)
2658            and then Ekind (Formal) /= E_In_Parameter
2659            and then Validity_Checks_On
2660            and then Validity_Check_Default
2661            and then not Validity_Check_Subscripts
2662          then
2663             Check_Valid_Lvalue_Subscripts (Actual);
2664          end if;
2665
2666          --  Mark any scalar OUT parameter that is a simple variable as no
2667          --  longer known to be valid (unless the type is always valid). This
2668          --  reflects the fact that if an OUT parameter is never set in a
2669          --  procedure, then it can become invalid on the procedure return.
2670
2671          if Ekind (Formal) = E_Out_Parameter
2672            and then Is_Entity_Name (Actual)
2673            and then Ekind (Entity (Actual)) = E_Variable
2674            and then not Is_Known_Valid (Etype (Actual))
2675          then
2676             Set_Is_Known_Valid (Entity (Actual), False);
2677          end if;
2678
2679          --  For an OUT or IN OUT parameter, if the actual is an entity, then
2680          --  clear current values, since they can be clobbered. We are probably
2681          --  doing this in more places than we need to, but better safe than
2682          --  sorry when it comes to retaining bad current values!
2683
2684          if Ekind (Formal) /= E_In_Parameter
2685            and then Is_Entity_Name (Actual)
2686            and then Present (Entity (Actual))
2687          then
2688             declare
2689                Ent : constant Entity_Id := Entity (Actual);
2690                Sav : Node_Id;
2691
2692             begin
2693                --  For an OUT or IN OUT parameter that is an assignable entity,
2694                --  we do not want to clobber the Last_Assignment field, since
2695                --  if it is set, it was precisely because it is indeed an OUT
2696                --  or IN OUT parameter! We do reset the Is_Known_Valid flag
2697                --  since the subprogram could have returned in invalid value.
2698
2699                if Ekind_In (Formal, E_Out_Parameter, E_In_Out_Parameter)
2700                  and then Is_Assignable (Ent)
2701                then
2702                   Sav := Last_Assignment (Ent);
2703                   Kill_Current_Values (Ent);
2704                   Set_Last_Assignment (Ent, Sav);
2705                   Set_Is_Known_Valid (Ent, False);
2706
2707                   --  For all other cases, just kill the current values
2708
2709                else
2710                   Kill_Current_Values (Ent);
2711                end if;
2712             end;
2713          end if;
2714
2715          --  If the formal is class wide and the actual is an aggregate, force
2716          --  evaluation so that the back end who does not know about class-wide
2717          --  type, does not generate a temporary of the wrong size.
2718
2719          if not Is_Class_Wide_Type (Etype (Formal)) then
2720             null;
2721
2722          elsif Nkind (Actual) = N_Aggregate
2723            or else (Nkind (Actual) = N_Qualified_Expression
2724                      and then Nkind (Expression (Actual)) = N_Aggregate)
2725          then
2726             Force_Evaluation (Actual);
2727          end if;
2728
2729          --  In a remote call, if the formal is of a class-wide type, check
2730          --  that the actual meets the requirements described in E.4(18).
2731
2732          if Remote and then Is_Class_Wide_Type (Etype (Formal)) then
2733             Insert_Action (Actual,
2734               Make_Transportable_Check (Loc,
2735                 Duplicate_Subexpr_Move_Checks (Actual)));
2736          end if;
2737
2738          --  This label is required when skipping extra actual generation for
2739          --  Unchecked_Union parameters.
2740
2741          <<Skip_Extra_Actual_Generation>>
2742
2743          Param_Count := Param_Count + 1;
2744          Next_Actual (Actual);
2745          Next_Formal (Formal);
2746       end loop;
2747
2748       --  If we are expanding a rhs of an assignment we need to check if tag
2749       --  propagation is needed. You might expect this processing to be in
2750       --  Analyze_Assignment but has to be done earlier (bottom-up) because the
2751       --  assignment might be transformed to a declaration for an unconstrained
2752       --  value if the expression is classwide.
2753
2754       if Nkind (Call_Node) = N_Function_Call
2755         and then Is_Tag_Indeterminate (Call_Node)
2756         and then Is_Entity_Name (Name (Call_Node))
2757       then
2758          declare
2759             Ass : Node_Id := Empty;
2760
2761          begin
2762             if Nkind (Parent (Call_Node)) = N_Assignment_Statement then
2763                Ass := Parent (Call_Node);
2764
2765             elsif Nkind (Parent (Call_Node)) = N_Qualified_Expression
2766               and then Nkind (Parent (Parent (Call_Node))) =
2767                                                   N_Assignment_Statement
2768             then
2769                Ass := Parent (Parent (Call_Node));
2770
2771             elsif Nkind (Parent (Call_Node)) = N_Explicit_Dereference
2772               and then Nkind (Parent (Parent (Call_Node))) =
2773                                                   N_Assignment_Statement
2774             then
2775                Ass := Parent (Parent (Call_Node));
2776             end if;
2777
2778             if Present (Ass)
2779               and then Is_Class_Wide_Type (Etype (Name (Ass)))
2780             then
2781                if Is_Access_Type (Etype (Call_Node)) then
2782                   if Designated_Type (Etype (Call_Node)) /=
2783                     Root_Type (Etype (Name (Ass)))
2784                   then
2785                      Error_Msg_NE
2786                        ("tag-indeterminate expression "
2787                          & " must have designated type& (RM 5.2 (6))",
2788                          Call_Node, Root_Type (Etype (Name (Ass))));
2789                   else
2790                      Propagate_Tag (Name (Ass), Call_Node);
2791                   end if;
2792
2793                elsif Etype (Call_Node) /= Root_Type (Etype (Name (Ass))) then
2794                   Error_Msg_NE
2795                     ("tag-indeterminate expression must have type&"
2796                      & "(RM 5.2 (6))",
2797                      Call_Node, Root_Type (Etype (Name (Ass))));
2798
2799                else
2800                   Propagate_Tag (Name (Ass), Call_Node);
2801                end if;
2802
2803                --  The call will be rewritten as a dispatching call, and
2804                --  expanded as such.
2805
2806                return;
2807             end if;
2808          end;
2809       end if;
2810
2811       --  Ada 2005 (AI-251): If some formal is a class-wide interface, expand
2812       --  it to point to the correct secondary virtual table
2813
2814       if Nkind_In (Call_Node, N_Function_Call, N_Procedure_Call_Statement)
2815         and then CW_Interface_Formals_Present
2816       then
2817          Expand_Interface_Actuals (Call_Node);
2818       end if;
2819
2820       --  Deals with Dispatch_Call if we still have a call, before expanding
2821       --  extra actuals since this will be done on the re-analysis of the
2822       --  dispatching call. Note that we do not try to shorten the actual list
2823       --  for a dispatching call, it would not make sense to do so. Expansion
2824       --  of dispatching calls is suppressed when VM_Target, because the VM
2825       --  back-ends directly handle the generation of dispatching calls and
2826       --  would have to undo any expansion to an indirect call.
2827
2828       if Nkind_In (Call_Node, N_Function_Call, N_Procedure_Call_Statement)
2829         and then Present (Controlling_Argument (Call_Node))
2830       then
2831          declare
2832             Call_Typ   : constant Entity_Id := Etype (Call_Node);
2833             Typ        : constant Entity_Id := Find_Dispatching_Type (Subp);
2834             Eq_Prim_Op : Entity_Id := Empty;
2835             New_Call   : Node_Id;
2836             Param      : Node_Id;
2837             Prev_Call  : Node_Id;
2838
2839          begin
2840             if not Is_Limited_Type (Typ) then
2841                Eq_Prim_Op := Find_Prim_Op (Typ, Name_Op_Eq);
2842             end if;
2843
2844             if Tagged_Type_Expansion then
2845                Expand_Dispatching_Call (Call_Node);
2846
2847                --  The following return is worrisome. Is it really OK to skip
2848                --  all remaining processing in this procedure ???
2849
2850                return;
2851
2852             --  VM targets
2853
2854             else
2855                Apply_Tag_Checks (Call_Node);
2856
2857                --  If this is a dispatching "=", we must first compare the
2858                --  tags so we generate: x.tag = y.tag and then x = y
2859
2860                if Subp = Eq_Prim_Op then
2861
2862                   --  Mark the node as analyzed to avoid reanalizing this
2863                   --  dispatching call (which would cause a never-ending loop)
2864
2865                   Prev_Call := Relocate_Node (Call_Node);
2866                   Set_Analyzed (Prev_Call);
2867
2868                   Param := First_Actual (Call_Node);
2869                   New_Call :=
2870                     Make_And_Then (Loc,
2871                       Left_Opnd =>
2872                            Make_Op_Eq (Loc,
2873                              Left_Opnd =>
2874                                Make_Selected_Component (Loc,
2875                                  Prefix        => New_Value (Param),
2876                                  Selector_Name =>
2877                                    New_Reference_To (First_Tag_Component (Typ),
2878                                                      Loc)),
2879
2880                              Right_Opnd =>
2881                                Make_Selected_Component (Loc,
2882                                  Prefix        =>
2883                                    Unchecked_Convert_To (Typ,
2884                                      New_Value (Next_Actual (Param))),
2885                                  Selector_Name =>
2886                                    New_Reference_To
2887                                      (First_Tag_Component (Typ), Loc))),
2888                       Right_Opnd => Prev_Call);
2889
2890                   Rewrite (Call_Node, New_Call);
2891
2892                   Analyze_And_Resolve
2893                     (Call_Node, Call_Typ, Suppress => All_Checks);
2894                end if;
2895
2896                --  Expansion of a dispatching call results in an indirect call,
2897                --  which in turn causes current values to be killed (see
2898                --  Resolve_Call), so on VM targets we do the call here to
2899                --  ensure consistent warnings between VM and non-VM targets.
2900
2901                Kill_Current_Values;
2902             end if;
2903
2904             --  If this is a dispatching "=" then we must update the reference
2905             --  to the call node because we generated:
2906             --     x.tag = y.tag and then x = y
2907
2908             if Subp = Eq_Prim_Op then
2909                Call_Node := Right_Opnd (Call_Node);
2910             end if;
2911          end;
2912       end if;
2913
2914       --  Similarly, expand calls to RCI subprograms on which pragma
2915       --  All_Calls_Remote applies. The rewriting will be reanalyzed
2916       --  later. Do this only when the call comes from source since we
2917       --  do not want such a rewriting to occur in expanded code.
2918
2919       if Is_All_Remote_Call (Call_Node) then
2920          Expand_All_Calls_Remote_Subprogram_Call (Call_Node);
2921
2922       --  Similarly, do not add extra actuals for an entry call whose entity
2923       --  is a protected procedure, or for an internal protected subprogram
2924       --  call, because it will be rewritten as a protected subprogram call
2925       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
2926
2927       elsif Is_Protected_Type (Scope (Subp))
2928          and then (Ekind (Subp) = E_Procedure
2929                     or else Ekind (Subp) = E_Function)
2930       then
2931          null;
2932
2933       --  During that loop we gathered the extra actuals (the ones that
2934       --  correspond to Extra_Formals), so now they can be appended.
2935
2936       else
2937          while Is_Non_Empty_List (Extra_Actuals) loop
2938             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
2939          end loop;
2940       end if;
2941
2942       --  At this point we have all the actuals, so this is the point at which
2943       --  the various expansion activities for actuals is carried out.
2944
2945       Expand_Actuals (Call_Node, Subp);
2946
2947       --  If the subprogram is a renaming, or if it is inherited, replace it in
2948       --  the call with the name of the actual subprogram being called. If this
2949       --  is a dispatching call, the run-time decides what to call. The Alias
2950       --  attribute does not apply to entries.
2951
2952       if Nkind (Call_Node) /= N_Entry_Call_Statement
2953         and then No (Controlling_Argument (Call_Node))
2954         and then Present (Parent_Subp)
2955         and then not Is_Direct_Deep_Call (Subp)
2956       then
2957          if Present (Inherited_From_Formal (Subp)) then
2958             Parent_Subp := Inherited_From_Formal (Subp);
2959          else
2960             Parent_Subp := Ultimate_Alias (Parent_Subp);
2961          end if;
2962
2963          --  The below setting of Entity is suspect, see F109-018 discussion???
2964
2965          Set_Entity (Name (Call_Node), Parent_Subp);
2966
2967          if Is_Abstract_Subprogram (Parent_Subp)
2968            and then not In_Instance
2969          then
2970             Error_Msg_NE
2971               ("cannot call abstract subprogram &!",
2972                Name (Call_Node), Parent_Subp);
2973          end if;
2974
2975          --  Inspect all formals of derived subprogram Subp. Compare parameter
2976          --  types with the parent subprogram and check whether an actual may
2977          --  need a type conversion to the corresponding formal of the parent
2978          --  subprogram.
2979
2980          --  Not clear whether intrinsic subprograms need such conversions. ???
2981
2982          if not Is_Intrinsic_Subprogram (Parent_Subp)
2983            or else Is_Generic_Instance (Parent_Subp)
2984          then
2985             declare
2986                procedure Convert (Act : Node_Id; Typ : Entity_Id);
2987                --  Rewrite node Act as a type conversion of Act to Typ. Analyze
2988                --  and resolve the newly generated construct.
2989
2990                -------------
2991                -- Convert --
2992                -------------
2993
2994                procedure Convert (Act : Node_Id; Typ : Entity_Id) is
2995                begin
2996                   Rewrite (Act, OK_Convert_To (Typ, Relocate_Node (Act)));
2997                   Analyze (Act);
2998                   Resolve (Act, Typ);
2999                end Convert;
3000
3001                --  Local variables
3002
3003                Actual_Typ : Entity_Id;
3004                Formal_Typ : Entity_Id;
3005                Parent_Typ : Entity_Id;
3006
3007             begin
3008                Actual := First_Actual (Call_Node);
3009                Formal := First_Formal (Subp);
3010                Parent_Formal := First_Formal (Parent_Subp);
3011                while Present (Formal) loop
3012                   Actual_Typ := Etype (Actual);
3013                   Formal_Typ := Etype (Formal);
3014                   Parent_Typ := Etype (Parent_Formal);
3015
3016                   --  For an IN parameter of a scalar type, the parent formal
3017                   --  type and derived formal type differ or the parent formal
3018                   --  type and actual type do not match statically.
3019
3020                   if Is_Scalar_Type (Formal_Typ)
3021                     and then Ekind (Formal) = E_In_Parameter
3022                     and then Formal_Typ /= Parent_Typ
3023                     and then
3024                       not Subtypes_Statically_Match (Parent_Typ, Actual_Typ)
3025                     and then not Raises_Constraint_Error (Actual)
3026                   then
3027                      Convert (Actual, Parent_Typ);
3028                      Enable_Range_Check (Actual);
3029
3030                      --  If the actual has been marked as requiring a range
3031                      --  check, then generate it here.
3032
3033                      if Do_Range_Check (Actual) then
3034                         Set_Do_Range_Check (Actual, False);
3035                         Generate_Range_Check
3036                           (Actual, Etype (Formal), CE_Range_Check_Failed);
3037                      end if;
3038
3039                   --  For access types, the parent formal type and actual type
3040                   --  differ.
3041
3042                   elsif Is_Access_Type (Formal_Typ)
3043                     and then Base_Type (Parent_Typ) /= Base_Type (Actual_Typ)
3044                   then
3045                      if Ekind (Formal) /= E_In_Parameter then
3046                         Convert (Actual, Parent_Typ);
3047
3048                      elsif Ekind (Parent_Typ) = E_Anonymous_Access_Type
3049                        and then Designated_Type (Parent_Typ) /=
3050                                 Designated_Type (Actual_Typ)
3051                        and then not Is_Controlling_Formal (Formal)
3052                      then
3053                         --  This unchecked conversion is not necessary unless
3054                         --  inlining is enabled, because in that case the type
3055                         --  mismatch may become visible in the body about to be
3056                         --  inlined.
3057
3058                         Rewrite (Actual,
3059                           Unchecked_Convert_To (Parent_Typ,
3060                             Relocate_Node (Actual)));
3061                         Analyze (Actual);
3062                         Resolve (Actual, Parent_Typ);
3063                      end if;
3064
3065                   --  For array and record types, the parent formal type and
3066                   --  derived formal type have different sizes or pragma Pack
3067                   --  status.
3068
3069                   elsif ((Is_Array_Type (Formal_Typ)
3070                             and then Is_Array_Type (Parent_Typ))
3071                        or else
3072                          (Is_Record_Type (Formal_Typ)
3073                             and then Is_Record_Type (Parent_Typ)))
3074                     and then
3075                       (Esize (Formal_Typ) /= Esize (Parent_Typ)
3076                          or else Has_Pragma_Pack (Formal_Typ) /=
3077                                  Has_Pragma_Pack (Parent_Typ))
3078                   then
3079                      Convert (Actual, Parent_Typ);
3080                   end if;
3081
3082                   Next_Actual (Actual);
3083                   Next_Formal (Formal);
3084                   Next_Formal (Parent_Formal);
3085                end loop;
3086             end;
3087          end if;
3088
3089          Orig_Subp := Subp;
3090          Subp := Parent_Subp;
3091       end if;
3092
3093       --  Check for violation of No_Abort_Statements
3094
3095       if Restriction_Check_Required (No_Abort_Statements)
3096         and then Is_RTE (Subp, RE_Abort_Task)
3097       then
3098          Check_Restriction (No_Abort_Statements, Call_Node);
3099
3100       --  Check for violation of No_Dynamic_Attachment
3101
3102       elsif Restriction_Check_Required (No_Dynamic_Attachment)
3103         and then RTU_Loaded (Ada_Interrupts)
3104         and then (Is_RTE (Subp, RE_Is_Reserved)      or else
3105                   Is_RTE (Subp, RE_Is_Attached)      or else
3106                   Is_RTE (Subp, RE_Current_Handler)  or else
3107                   Is_RTE (Subp, RE_Attach_Handler)   or else
3108                   Is_RTE (Subp, RE_Exchange_Handler) or else
3109                   Is_RTE (Subp, RE_Detach_Handler)   or else
3110                   Is_RTE (Subp, RE_Reference))
3111       then
3112          Check_Restriction (No_Dynamic_Attachment, Call_Node);
3113       end if;
3114
3115       --  Deal with case where call is an explicit dereference
3116
3117       if Nkind (Name (Call_Node)) = N_Explicit_Dereference then
3118
3119       --  Handle case of access to protected subprogram type
3120
3121          if Is_Access_Protected_Subprogram_Type
3122               (Base_Type (Etype (Prefix (Name (Call_Node)))))
3123          then
3124             --  If this is a call through an access to protected operation, the
3125             --  prefix has the form (object'address, operation'access). Rewrite
3126             --  as a for other protected calls: the object is the 1st parameter
3127             --  of the list of actuals.
3128
3129             declare
3130                Call : Node_Id;
3131                Parm : List_Id;
3132                Nam  : Node_Id;
3133                Obj  : Node_Id;
3134                Ptr  : constant Node_Id := Prefix (Name (Call_Node));
3135
3136                T : constant Entity_Id :=
3137                      Equivalent_Type (Base_Type (Etype (Ptr)));
3138
3139                D_T : constant Entity_Id :=
3140                        Designated_Type (Base_Type (Etype (Ptr)));
3141
3142             begin
3143                Obj :=
3144                  Make_Selected_Component (Loc,
3145                    Prefix        => Unchecked_Convert_To (T, Ptr),
3146                    Selector_Name =>
3147                      New_Occurrence_Of (First_Entity (T), Loc));
3148
3149                Nam :=
3150                  Make_Selected_Component (Loc,
3151                    Prefix        => Unchecked_Convert_To (T, Ptr),
3152                    Selector_Name =>
3153                      New_Occurrence_Of (Next_Entity (First_Entity (T)), Loc));
3154
3155                Nam :=
3156                  Make_Explicit_Dereference (Loc,
3157                    Prefix => Nam);
3158
3159                if Present (Parameter_Associations (Call_Node))  then
3160                   Parm := Parameter_Associations (Call_Node);
3161                else
3162                   Parm := New_List;
3163                end if;
3164
3165                Prepend (Obj, Parm);
3166
3167                if Etype (D_T) = Standard_Void_Type then
3168                   Call :=
3169                     Make_Procedure_Call_Statement (Loc,
3170                       Name                   => Nam,
3171                       Parameter_Associations => Parm);
3172                else
3173                   Call :=
3174                     Make_Function_Call (Loc,
3175                       Name                   => Nam,
3176                       Parameter_Associations => Parm);
3177                end if;
3178
3179                Set_First_Named_Actual (Call, First_Named_Actual (Call_Node));
3180                Set_Etype (Call, Etype (D_T));
3181
3182                --  We do not re-analyze the call to avoid infinite recursion.
3183                --  We analyze separately the prefix and the object, and set
3184                --  the checks on the prefix that would otherwise be emitted
3185                --  when resolving a call.
3186
3187                Rewrite (Call_Node, Call);
3188                Analyze (Nam);
3189                Apply_Access_Check (Nam);
3190                Analyze (Obj);
3191                return;
3192             end;
3193          end if;
3194       end if;
3195
3196       --  If this is a call to an intrinsic subprogram, then perform the
3197       --  appropriate expansion to the corresponding tree node and we
3198       --  are all done (since after that the call is gone!)
3199
3200       --  In the case where the intrinsic is to be processed by the back end,
3201       --  the call to Expand_Intrinsic_Call will do nothing, which is fine,
3202       --  since the idea in this case is to pass the call unchanged. If the
3203       --  intrinsic is an inherited unchecked conversion, and the derived type
3204       --  is the target type of the conversion, we must retain it as the return
3205       --  type of the expression. Otherwise the expansion below, which uses the
3206       --  parent operation, will yield the wrong type.
3207
3208       if Is_Intrinsic_Subprogram (Subp) then
3209          Expand_Intrinsic_Call (Call_Node, Subp);
3210
3211          if Nkind (Call_Node) = N_Unchecked_Type_Conversion
3212            and then Parent_Subp /= Orig_Subp
3213            and then Etype (Parent_Subp) /= Etype (Orig_Subp)
3214          then
3215             Set_Etype (Call_Node, Etype (Orig_Subp));
3216          end if;
3217
3218          return;
3219       end if;
3220
3221       if Ekind_In (Subp, E_Function, E_Procedure) then
3222
3223          --  We perform two simple optimization on calls:
3224
3225          --  a) replace calls to null procedures unconditionally;
3226
3227          --  b) for To_Address, just do an unchecked conversion. Not only is
3228          --  this efficient, but it also avoids order of elaboration problems
3229          --  when address clauses are inlined (address expression elaborated
3230          --  at the wrong point).
3231
3232          --  We perform these optimization regardless of whether we are in the
3233          --  main unit or in a unit in the context of the main unit, to ensure
3234          --  that tree generated is the same in both cases, for Inspector use.
3235
3236          if Is_RTE (Subp, RE_To_Address) then
3237             Rewrite (Call_Node,
3238               Unchecked_Convert_To
3239                 (RTE (RE_Address), Relocate_Node (First_Actual (Call_Node))));
3240             return;
3241
3242          elsif Is_Null_Procedure (Subp)  then
3243             Rewrite (Call_Node, Make_Null_Statement (Loc));
3244             return;
3245          end if;
3246
3247          if Is_Inlined (Subp) then
3248
3249             Inlined_Subprogram : declare
3250                Bod         : Node_Id;
3251                Must_Inline : Boolean := False;
3252                Spec        : constant Node_Id := Unit_Declaration_Node (Subp);
3253                Scop        : constant Entity_Id := Scope (Subp);
3254
3255                function In_Unfrozen_Instance return Boolean;
3256                --  If the subprogram comes from an instance in the same unit,
3257                --  and the instance is not yet frozen, inlining might trigger
3258                --  order-of-elaboration problems in gigi.
3259
3260                --------------------------
3261                -- In_Unfrozen_Instance --
3262                --------------------------
3263
3264                function In_Unfrozen_Instance return Boolean is
3265                   S : Entity_Id;
3266
3267                begin
3268                   S := Scop;
3269                   while Present (S)
3270                     and then S /= Standard_Standard
3271                   loop
3272                      if Is_Generic_Instance (S)
3273                        and then Present (Freeze_Node (S))
3274                        and then not Analyzed (Freeze_Node (S))
3275                      then
3276                         return True;
3277                      end if;
3278
3279                      S := Scope (S);
3280                   end loop;
3281
3282                   return False;
3283                end In_Unfrozen_Instance;
3284
3285             --  Start of processing for Inlined_Subprogram
3286
3287             begin
3288                --  Verify that the body to inline has already been seen, and
3289                --  that if the body is in the current unit the inlining does
3290                --  not occur earlier. This avoids order-of-elaboration problems
3291                --  in the back end.
3292
3293                --  This should be documented in sinfo/einfo ???
3294
3295                if No (Spec)
3296                  or else Nkind (Spec) /= N_Subprogram_Declaration
3297                  or else No (Body_To_Inline (Spec))
3298                then
3299                   Must_Inline := False;
3300
3301                --  If this an inherited function that returns a private type,
3302                --  do not inline if the full view is an unconstrained array,
3303                --  because such calls cannot be inlined.
3304
3305                elsif Present (Orig_Subp)
3306                  and then Is_Array_Type (Etype (Orig_Subp))
3307                  and then not Is_Constrained (Etype (Orig_Subp))
3308                then
3309                   Must_Inline := False;
3310
3311                elsif In_Unfrozen_Instance then
3312                   Must_Inline := False;
3313
3314                else
3315                   Bod := Body_To_Inline (Spec);
3316
3317                   if (In_Extended_Main_Code_Unit (Call_Node)
3318                         or else In_Extended_Main_Code_Unit (Parent (Call_Node))
3319                         or else Has_Pragma_Inline_Always (Subp))
3320                     and then (not In_Same_Extended_Unit (Sloc (Bod), Loc)
3321                                or else
3322                                  Earlier_In_Extended_Unit (Sloc (Bod), Loc))
3323                   then
3324                      Must_Inline := True;
3325
3326                   --  If we are compiling a package body that is not the main
3327                   --  unit, it must be for inlining/instantiation purposes,
3328                   --  in which case we inline the call to insure that the same
3329                   --  temporaries are generated when compiling the body by
3330                   --  itself. Otherwise link errors can occur.
3331
3332                   --  If the function being called is itself in the main unit,
3333                   --  we cannot inline, because there is a risk of double
3334                   --  elaboration and/or circularity: the inlining can make
3335                   --  visible a private entity in the body of the main unit,
3336                   --  that gigi will see before its sees its proper definition.
3337
3338                   elsif not (In_Extended_Main_Code_Unit (Call_Node))
3339                     and then In_Package_Body
3340                   then
3341                      Must_Inline := not In_Extended_Main_Source_Unit (Subp);
3342                   end if;
3343                end if;
3344
3345                if Must_Inline then
3346                   Expand_Inlined_Call (Call_Node, Subp, Orig_Subp);
3347
3348                else
3349                   --  Let the back end handle it
3350
3351                   Add_Inlined_Body (Subp);
3352
3353                   if Front_End_Inlining
3354                     and then Nkind (Spec) = N_Subprogram_Declaration
3355                     and then (In_Extended_Main_Code_Unit (Call_Node))
3356                     and then No (Body_To_Inline (Spec))
3357                     and then not Has_Completion (Subp)
3358                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
3359                   then
3360                      Cannot_Inline
3361                       ("cannot inline& (body not seen yet)?", Call_Node, Subp);
3362                   end if;
3363                end if;
3364             end Inlined_Subprogram;
3365          end if;
3366       end if;
3367
3368       --  Check for protected subprogram. This is either an intra-object call,
3369       --  or a protected function call. Protected procedure calls are rewritten
3370       --  as entry calls and handled accordingly.
3371
3372       --  In Ada 2005, this may be an indirect call to an access parameter that
3373       --  is an access_to_subprogram. In that case the anonymous type has a
3374       --  scope that is a protected operation, but the call is a regular one.
3375       --  In either case do not expand call if subprogram is eliminated.
3376
3377       Scop := Scope (Subp);
3378
3379       if Nkind (Call_Node) /= N_Entry_Call_Statement
3380         and then Is_Protected_Type (Scop)
3381         and then Ekind (Subp) /= E_Subprogram_Type
3382         and then not Is_Eliminated (Subp)
3383       then
3384          --  If the call is an internal one, it is rewritten as a call to the
3385          --  corresponding unprotected subprogram.
3386
3387          Expand_Protected_Subprogram_Call (Call_Node, Subp, Scop);
3388       end if;
3389
3390       --  Functions returning controlled objects need special attention. If
3391       --  the return type is limited, then the context is initialization and
3392       --  different processing applies. If the call is to a protected function,
3393       --  the expansion above will call Expand_Call recursively. Otherwise the
3394       --  function call is transformed into a temporary which obtains the
3395       --  result from the secondary stack.
3396
3397       if Needs_Finalization (Etype (Subp)) then
3398          if not Is_Immutably_Limited_Type (Etype (Subp))
3399            and then
3400              (No (First_Formal (Subp))
3401                 or else
3402                   not Is_Concurrent_Record_Type (Etype (First_Formal (Subp))))
3403          then
3404             Expand_Ctrl_Function_Call (Call_Node);
3405
3406          --  Build-in-place function calls which appear in anonymous contexts
3407          --  need a transient scope to ensure the proper finalization of the
3408          --  intermediate result after its use.
3409
3410          elsif Is_Build_In_Place_Function_Call (Call_Node)
3411            and then Nkind_In (Parent (Call_Node), N_Attribute_Reference,
3412                                           N_Function_Call,
3413                                           N_Indexed_Component,
3414                                           N_Object_Renaming_Declaration,
3415                                           N_Procedure_Call_Statement,
3416                                           N_Selected_Component,
3417                                           N_Slice)
3418          then
3419             Establish_Transient_Scope (Call_Node, Sec_Stack => True);
3420          end if;
3421       end if;
3422
3423       --  Test for First_Optional_Parameter, and if so, truncate parameter list
3424       --  if there are optional parameters at the trailing end.
3425       --  Note: we never delete procedures for call via a pointer.
3426
3427       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
3428         and then Present (First_Optional_Parameter (Subp))
3429       then
3430          declare
3431             Last_Keep_Arg : Node_Id;
3432
3433          begin
3434             --  Last_Keep_Arg will hold the last actual that should be kept.
3435             --  If it remains empty at the end, it means that all parameters
3436             --  are optional.
3437
3438             Last_Keep_Arg := Empty;
3439
3440             --  Find first optional parameter, must be present since we checked
3441             --  the validity of the parameter before setting it.
3442
3443             Formal := First_Formal (Subp);
3444             Actual := First_Actual (Call_Node);
3445             while Formal /= First_Optional_Parameter (Subp) loop
3446                Last_Keep_Arg := Actual;
3447                Next_Formal (Formal);
3448                Next_Actual (Actual);
3449             end loop;
3450
3451             --  We have Formal and Actual pointing to the first potentially
3452             --  droppable argument. We can drop all the trailing arguments
3453             --  whose actual matches the default. Note that we know that all
3454             --  remaining formals have defaults, because we checked that this
3455             --  requirement was met before setting First_Optional_Parameter.
3456
3457             --  We use Fully_Conformant_Expressions to check for identity
3458             --  between formals and actuals, which may miss some cases, but
3459             --  on the other hand, this is only an optimization (if we fail
3460             --  to truncate a parameter it does not affect functionality).
3461             --  So if the default is 3 and the actual is 1+2, we consider
3462             --  them unequal, which hardly seems worrisome.
3463
3464             while Present (Formal) loop
3465                if not Fully_Conformant_Expressions
3466                     (Actual, Default_Value (Formal))
3467                then
3468                   Last_Keep_Arg := Actual;
3469                end if;
3470
3471                Next_Formal (Formal);
3472                Next_Actual (Actual);
3473             end loop;
3474
3475             --  If no arguments, delete entire list, this is the easy case
3476
3477             if No (Last_Keep_Arg) then
3478                Set_Parameter_Associations (Call_Node, No_List);
3479                Set_First_Named_Actual (Call_Node, Empty);
3480
3481             --  Case where at the last retained argument is positional. This
3482             --  is also an easy case, since the retained arguments are already
3483             --  in the right form, and we don't need to worry about the order
3484             --  of arguments that get eliminated.
3485
3486             elsif Is_List_Member (Last_Keep_Arg) then
3487                while Present (Next (Last_Keep_Arg)) loop
3488                   Discard_Node (Remove_Next (Last_Keep_Arg));
3489                end loop;
3490
3491                Set_First_Named_Actual (Call_Node, Empty);
3492
3493             --  This is the annoying case where the last retained argument
3494             --  is a named parameter. Since the original arguments are not
3495             --  in declaration order, we may have to delete some fairly
3496             --  random collection of arguments.
3497
3498             else
3499                declare
3500                   Temp   : Node_Id;
3501                   Passoc : Node_Id;
3502
3503                begin
3504                   --  First step, remove all the named parameters from the
3505                   --  list (they are still chained using First_Named_Actual
3506                   --  and Next_Named_Actual, so we have not lost them!)
3507
3508                   Temp := First (Parameter_Associations (Call_Node));
3509
3510                   --  Case of all parameters named, remove them all
3511
3512                   if Nkind (Temp) = N_Parameter_Association then
3513                      --  Suppress warnings to avoid warning on possible
3514                      --  infinite loop (because Call_Node is not modified).
3515
3516                      pragma Warnings (Off);
3517                      while Is_Non_Empty_List
3518                              (Parameter_Associations (Call_Node))
3519                      loop
3520                         Temp :=
3521                           Remove_Head (Parameter_Associations (Call_Node));
3522                      end loop;
3523                      pragma Warnings (On);
3524
3525                   --  Case of mixed positional/named, remove named parameters
3526
3527                   else
3528                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
3529                         Next (Temp);
3530                      end loop;
3531
3532                      while Present (Next (Temp)) loop
3533                         Remove (Next (Temp));
3534                      end loop;
3535                   end if;
3536
3537                   --  Now we loop through the named parameters, till we get
3538                   --  to the last one to be retained, adding them to the list.
3539                   --  Note that the Next_Named_Actual list does not need to be
3540                   --  touched since we are only reordering them on the actual
3541                   --  parameter association list.
3542
3543                   Passoc := Parent (First_Named_Actual (Call_Node));
3544                   loop
3545                      Temp := Relocate_Node (Passoc);
3546                      Append_To
3547                        (Parameter_Associations (Call_Node), Temp);
3548                      exit when
3549                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
3550                      Passoc := Parent (Next_Named_Actual (Passoc));
3551                   end loop;
3552
3553                   Set_Next_Named_Actual (Temp, Empty);
3554
3555                   loop
3556                      Temp := Next_Named_Actual (Passoc);
3557                      exit when No (Temp);
3558                      Set_Next_Named_Actual
3559                        (Passoc, Next_Named_Actual (Parent (Temp)));
3560                   end loop;
3561                end;
3562
3563             end if;
3564          end;
3565       end if;
3566    end Expand_Call;
3567
3568    -------------------------------
3569    -- Expand_Ctrl_Function_Call --
3570    -------------------------------
3571
3572    procedure Expand_Ctrl_Function_Call (N : Node_Id) is
3573    begin
3574       --  Optimization, if the returned value (which is on the sec-stack) is
3575       --  returned again, no need to copy/readjust/finalize, we can just pass
3576       --  the value thru (see Expand_N_Simple_Return_Statement), and thus no
3577       --  attachment is needed
3578
3579       if Nkind (Parent (N)) = N_Simple_Return_Statement then
3580          return;
3581       end if;
3582
3583       --  Resolution is now finished, make sure we don't start analysis again
3584       --  because of the duplication.
3585
3586       Set_Analyzed (N);
3587
3588       --  A function which returns a controlled object uses the secondary
3589       --  stack. Rewrite the call into a temporary which obtains the result of
3590       --  the function using 'reference.
3591
3592       Remove_Side_Effects (N);
3593    end Expand_Ctrl_Function_Call;
3594
3595    --------------------------
3596    -- Expand_Inlined_Call --
3597    --------------------------
3598
3599    procedure Expand_Inlined_Call
3600     (N         : Node_Id;
3601      Subp      : Entity_Id;
3602      Orig_Subp : Entity_Id)
3603    is
3604       Loc       : constant Source_Ptr := Sloc (N);
3605       Is_Predef : constant Boolean :=
3606                    Is_Predefined_File_Name
3607                      (Unit_File_Name (Get_Source_Unit (Subp)));
3608       Orig_Bod  : constant Node_Id :=
3609                     Body_To_Inline (Unit_Declaration_Node (Subp));
3610
3611       Blk      : Node_Id;
3612       Bod      : Node_Id;
3613       Decl     : Node_Id;
3614       Decls    : constant List_Id := New_List;
3615       Exit_Lab : Entity_Id := Empty;
3616       F        : Entity_Id;
3617       A        : Node_Id;
3618       Lab_Decl : Node_Id;
3619       Lab_Id   : Node_Id;
3620       New_A    : Node_Id;
3621       Num_Ret  : Int := 0;
3622       Ret_Type : Entity_Id;
3623       Targ     : Node_Id;
3624       Targ1    : Node_Id;
3625       Temp     : Entity_Id;
3626       Temp_Typ : Entity_Id;
3627
3628       Return_Object : Entity_Id := Empty;
3629       --  Entity in declaration in an extended_return_statement
3630
3631       Is_Unc : constant Boolean :=
3632                     Is_Array_Type (Etype (Subp))
3633                       and then not Is_Constrained (Etype (Subp));
3634       --  If the type returned by the function is unconstrained and the call
3635       --  can be inlined, special processing is required.
3636
3637       procedure Make_Exit_Label;
3638       --  Build declaration for exit label to be used in Return statements,
3639       --  sets Exit_Lab (the label node) and Lab_Decl (corresponding implicit
3640       --  declaration). Does nothing if Exit_Lab already set.
3641
3642       function Process_Formals (N : Node_Id) return Traverse_Result;
3643       --  Replace occurrence of a formal with the corresponding actual, or the
3644       --  thunk generated for it.
3645
3646       function Process_Sloc (Nod : Node_Id) return Traverse_Result;
3647       --  If the call being expanded is that of an internal subprogram, set the
3648       --  sloc of the generated block to that of the call itself, so that the
3649       --  expansion is skipped by the "next" command in gdb.
3650       --  Same processing for a subprogram in a predefined file, e.g.
3651       --  Ada.Tags. If Debug_Generated_Code is true, suppress this change to
3652       --  simplify our own development.
3653
3654       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
3655       --  If the function body is a single expression, replace call with
3656       --  expression, else insert block appropriately.
3657
3658       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
3659       --  If procedure body has no local variables, inline body without
3660       --  creating block, otherwise rewrite call with block.
3661
3662       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean;
3663       --  Determine whether a formal parameter is used only once in Orig_Bod
3664
3665       ---------------------
3666       -- Make_Exit_Label --
3667       ---------------------
3668
3669       procedure Make_Exit_Label is
3670          Lab_Ent : Entity_Id;
3671       begin
3672          if No (Exit_Lab) then
3673             Lab_Ent := Make_Temporary (Loc, 'L');
3674             Lab_Id  := New_Reference_To (Lab_Ent, Loc);
3675             Exit_Lab := Make_Label (Loc, Lab_Id);
3676             Lab_Decl :=
3677               Make_Implicit_Label_Declaration (Loc,
3678                 Defining_Identifier  => Lab_Ent,
3679                 Label_Construct      => Exit_Lab);
3680          end if;
3681       end Make_Exit_Label;
3682
3683       ---------------------
3684       -- Process_Formals --
3685       ---------------------
3686
3687       function Process_Formals (N : Node_Id) return Traverse_Result is
3688          A   : Entity_Id;
3689          E   : Entity_Id;
3690          Ret : Node_Id;
3691
3692       begin
3693          if Is_Entity_Name (N)
3694            and then Present (Entity (N))
3695          then
3696             E := Entity (N);
3697
3698             if Is_Formal (E)
3699               and then Scope (E) = Subp
3700             then
3701                A := Renamed_Object (E);
3702
3703                --  Rewrite the occurrence of the formal into an occurrence of
3704                --  the actual. Also establish visibility on the proper view of
3705                --  the actual's subtype for the body's context (if the actual's
3706                --  subtype is private at the call point but its full view is
3707                --  visible to the body, then the inlined tree here must be
3708                --  analyzed with the full view).
3709
3710                if Is_Entity_Name (A) then
3711                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
3712                   Check_Private_View (N);
3713
3714                elsif Nkind (A) = N_Defining_Identifier then
3715                   Rewrite (N, New_Occurrence_Of (A, Loc));
3716                   Check_Private_View (N);
3717
3718                --  Numeric literal
3719
3720                else
3721                   Rewrite (N, New_Copy (A));
3722                end if;
3723             end if;
3724             return Skip;
3725
3726          elsif Is_Entity_Name (N)
3727            and then Present (Return_Object)
3728            and then Chars (N) = Chars (Return_Object)
3729          then
3730             --  Occurrence within an extended return statement. The return
3731             --  object is local to the body been inlined, and thus the generic
3732             --  copy is not analyzed yet, so we match by name, and replace it
3733             --  with target of call.
3734
3735             if Nkind (Targ) = N_Defining_Identifier then
3736                Rewrite (N, New_Occurrence_Of (Targ, Loc));
3737             else
3738                Rewrite (N, New_Copy_Tree (Targ));
3739             end if;
3740
3741             return Skip;
3742
3743          elsif Nkind (N) = N_Simple_Return_Statement then
3744             if No (Expression (N)) then
3745                Make_Exit_Label;
3746                Rewrite (N,
3747                  Make_Goto_Statement (Loc, Name => New_Copy (Lab_Id)));
3748
3749             else
3750                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
3751                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
3752                then
3753                   --  Function body is a single expression. No need for
3754                   --  exit label.
3755
3756                   null;
3757
3758                else
3759                   Num_Ret := Num_Ret + 1;
3760                   Make_Exit_Label;
3761                end if;
3762
3763                --  Because of the presence of private types, the views of the
3764                --  expression and the context may be different, so place an
3765                --  unchecked conversion to the context type to avoid spurious
3766                --  errors, e.g. when the expression is a numeric literal and
3767                --  the context is private. If the expression is an aggregate,
3768                --  use a qualified expression, because an aggregate is not a
3769                --  legal argument of a conversion.
3770
3771                if Nkind_In (Expression (N), N_Aggregate, N_Null) then
3772                   Ret :=
3773                     Make_Qualified_Expression (Sloc (N),
3774                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
3775                        Expression => Relocate_Node (Expression (N)));
3776                else
3777                   Ret :=
3778                     Unchecked_Convert_To
3779                       (Ret_Type, Relocate_Node (Expression (N)));
3780                end if;
3781
3782                if Nkind (Targ) = N_Defining_Identifier then
3783                   Rewrite (N,
3784                     Make_Assignment_Statement (Loc,
3785                       Name => New_Occurrence_Of (Targ, Loc),
3786                       Expression => Ret));
3787                else
3788                   Rewrite (N,
3789                     Make_Assignment_Statement (Loc,
3790                       Name => New_Copy (Targ),
3791                       Expression => Ret));
3792                end if;
3793
3794                Set_Assignment_OK (Name (N));
3795
3796                if Present (Exit_Lab) then
3797                   Insert_After (N,
3798                     Make_Goto_Statement (Loc,
3799                       Name => New_Copy (Lab_Id)));
3800                end if;
3801             end if;
3802
3803             return OK;
3804
3805          elsif Nkind (N) = N_Extended_Return_Statement then
3806
3807             --  An extended return becomes a block whose first statement is
3808             --  the assignment of the initial expression of the return object
3809             --  to the target of the call itself.
3810
3811             declare
3812                Return_Decl : constant Entity_Id :=
3813                                First (Return_Object_Declarations (N));
3814                Assign      : Node_Id;
3815
3816             begin
3817                Return_Object := Defining_Identifier (Return_Decl);
3818
3819                if Present (Expression (Return_Decl)) then
3820                   if Nkind (Targ) = N_Defining_Identifier then
3821                      Assign :=
3822                        Make_Assignment_Statement (Loc,
3823                          Name => New_Occurrence_Of (Targ, Loc),
3824                          Expression => Expression (Return_Decl));
3825                   else
3826                      Assign :=
3827                        Make_Assignment_Statement (Loc,
3828                          Name => New_Copy (Targ),
3829                          Expression => Expression (Return_Decl));
3830                   end if;
3831
3832                   Set_Assignment_OK (Name (Assign));
3833                   Prepend (Assign,
3834                     Statements (Handled_Statement_Sequence (N)));
3835                end if;
3836
3837                Rewrite (N,
3838                  Make_Block_Statement (Loc,
3839                     Handled_Statement_Sequence =>
3840                       Handled_Statement_Sequence (N)));
3841
3842                return OK;
3843             end;
3844
3845          --  Remove pragma Unreferenced since it may refer to formals that
3846          --  are not visible in the inlined body, and in any case we will
3847          --  not be posting warnings on the inlined body so it is unneeded.
3848
3849          elsif Nkind (N) = N_Pragma
3850            and then Pragma_Name (N) = Name_Unreferenced
3851          then
3852             Rewrite (N, Make_Null_Statement (Sloc (N)));
3853             return OK;
3854
3855          else
3856             return OK;
3857          end if;
3858       end Process_Formals;
3859
3860       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
3861
3862       ------------------
3863       -- Process_Sloc --
3864       ------------------
3865
3866       function Process_Sloc (Nod : Node_Id) return Traverse_Result is
3867       begin
3868          if not Debug_Generated_Code then
3869             Set_Sloc (Nod, Sloc (N));
3870             Set_Comes_From_Source (Nod, False);
3871          end if;
3872
3873          return OK;
3874       end Process_Sloc;
3875
3876       procedure Reset_Slocs is new Traverse_Proc (Process_Sloc);
3877
3878       ---------------------------
3879       -- Rewrite_Function_Call --
3880       ---------------------------
3881
3882       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
3883          HSS : constant Node_Id := Handled_Statement_Sequence (Blk);
3884          Fst : constant Node_Id := First (Statements (HSS));
3885
3886       begin
3887          --  Optimize simple case: function body is a single return statement,
3888          --  which has been expanded into an assignment.
3889
3890          if Is_Empty_List (Declarations (Blk))
3891            and then Nkind (Fst) = N_Assignment_Statement
3892            and then No (Next (Fst))
3893          then
3894
3895             --  The function call may have been rewritten as the temporary
3896             --  that holds the result of the call, in which case remove the
3897             --  now useless declaration.
3898
3899             if Nkind (N) = N_Identifier
3900               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3901             then
3902                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
3903             end if;
3904
3905             Rewrite (N, Expression (Fst));
3906
3907          elsif Nkind (N) = N_Identifier
3908            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3909          then
3910             --  The block assigns the result of the call to the temporary
3911
3912             Insert_After (Parent (Entity (N)), Blk);
3913
3914          elsif Nkind (Parent (N)) = N_Assignment_Statement
3915            and then
3916             (Is_Entity_Name (Name (Parent (N)))
3917                or else
3918                   (Nkind (Name (Parent (N))) = N_Explicit_Dereference
3919                     and then Is_Entity_Name (Prefix (Name (Parent (N))))))
3920          then
3921             --  Replace assignment with the block
3922
3923             declare
3924                Original_Assignment : constant Node_Id := Parent (N);
3925
3926             begin
3927                --  Preserve the original assignment node to keep the complete
3928                --  assignment subtree consistent enough for Analyze_Assignment
3929                --  to proceed (specifically, the original Lhs node must still
3930                --  have an assignment statement as its parent).
3931
3932                --  We cannot rely on Original_Node to go back from the block
3933                --  node to the assignment node, because the assignment might
3934                --  already be a rewrite substitution.
3935
3936                Discard_Node (Relocate_Node (Original_Assignment));
3937                Rewrite (Original_Assignment, Blk);
3938             end;
3939
3940          elsif Nkind (Parent (N)) = N_Object_Declaration then
3941             Set_Expression (Parent (N), Empty);
3942             Insert_After (Parent (N), Blk);
3943
3944          elsif Is_Unc then
3945             Insert_Before (Parent (N), Blk);
3946          end if;
3947       end Rewrite_Function_Call;
3948
3949       ----------------------------
3950       -- Rewrite_Procedure_Call --
3951       ----------------------------
3952
3953       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
3954          HSS  : constant Node_Id := Handled_Statement_Sequence (Blk);
3955       begin
3956          --  If there is a transient scope for N, this will be the scope of the
3957          --  actions for N, and the statements in Blk need to be within this
3958          --  scope. For example, they need to have visibility on the constant
3959          --  declarations created for the formals.
3960
3961          --  If N needs no transient scope, and if there are no declarations in
3962          --  the inlined body, we can do a little optimization and insert the
3963          --  statements for the body directly after N, and rewrite N to a
3964          --  null statement, instead of rewriting N into a full-blown block
3965          --  statement.
3966
3967          if not Scope_Is_Transient
3968            and then Is_Empty_List (Declarations (Blk))
3969          then
3970             Insert_List_After (N, Statements (HSS));
3971             Rewrite (N, Make_Null_Statement (Loc));
3972          else
3973             Rewrite (N, Blk);
3974          end if;
3975       end Rewrite_Procedure_Call;
3976
3977       -------------------------
3978       -- Formal_Is_Used_Once --
3979       -------------------------
3980
3981       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean is
3982          Use_Counter : Int := 0;
3983
3984          function Count_Uses (N : Node_Id) return Traverse_Result;
3985          --  Traverse the tree and count the uses of the formal parameter.
3986          --  In this case, for optimization purposes, we do not need to
3987          --  continue the traversal once more than one use is encountered.
3988
3989          ----------------
3990          -- Count_Uses --
3991          ----------------
3992
3993          function Count_Uses (N : Node_Id) return Traverse_Result is
3994          begin
3995             --  The original node is an identifier
3996
3997             if Nkind (N) = N_Identifier
3998               and then Present (Entity (N))
3999
4000                --  Original node's entity points to the one in the copied body
4001
4002               and then Nkind (Entity (N)) = N_Identifier
4003               and then Present (Entity (Entity (N)))
4004
4005                --  The entity of the copied node is the formal parameter
4006
4007               and then Entity (Entity (N)) = Formal
4008             then
4009                Use_Counter := Use_Counter + 1;
4010
4011                if Use_Counter > 1 then
4012
4013                   --  Denote more than one use and abandon the traversal
4014
4015                   Use_Counter := 2;
4016                   return Abandon;
4017
4018                end if;
4019             end if;
4020
4021             return OK;
4022          end Count_Uses;
4023
4024          procedure Count_Formal_Uses is new Traverse_Proc (Count_Uses);
4025
4026       --  Start of processing for Formal_Is_Used_Once
4027
4028       begin
4029          Count_Formal_Uses (Orig_Bod);
4030          return Use_Counter = 1;
4031       end Formal_Is_Used_Once;
4032
4033    --  Start of processing for Expand_Inlined_Call
4034
4035    begin
4036
4037       --  Check for an illegal attempt to inline a recursive procedure. If the
4038       --  subprogram has parameters this is detected when trying to supply a
4039       --  binding for parameters that already have one. For parameterless
4040       --  subprograms this must be done explicitly.
4041
4042       if In_Open_Scopes (Subp) then
4043          Error_Msg_N ("call to recursive subprogram cannot be inlined?", N);
4044          Set_Is_Inlined (Subp, False);
4045          return;
4046       end if;
4047
4048       if Nkind (Orig_Bod) = N_Defining_Identifier
4049         or else Nkind (Orig_Bod) = N_Defining_Operator_Symbol
4050       then
4051          --  Subprogram is renaming_as_body. Calls occurring after the renaming
4052          --  can be replaced with calls to the renamed entity directly, because
4053          --  the subprograms are subtype conformant. If the renamed subprogram
4054          --  is an inherited operation, we must redo the expansion because
4055          --  implicit conversions may be needed. Similarly, if the renamed
4056          --  entity is inlined, expand the call for further optimizations.
4057
4058          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
4059
4060          if Present (Alias (Orig_Bod)) or else Is_Inlined (Orig_Bod) then
4061             Expand_Call (N);
4062          end if;
4063
4064          return;
4065       end if;
4066
4067       --  Use generic machinery to copy body of inlined subprogram, as if it
4068       --  were an instantiation, resetting source locations appropriately, so
4069       --  that nested inlined calls appear in the main unit.
4070
4071       Save_Env (Subp, Empty);
4072       Set_Copied_Sloc_For_Inlined_Body (N, Defining_Entity (Orig_Bod));
4073
4074       Bod := Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
4075       Blk :=
4076         Make_Block_Statement (Loc,
4077           Declarations => Declarations (Bod),
4078           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
4079
4080       if No (Declarations (Bod)) then
4081          Set_Declarations (Blk, New_List);
4082       end if;
4083
4084       --  For the unconstrained case, capture the name of the local
4085       --  variable that holds the result. This must be the first declaration
4086       --  in the block, because its bounds cannot depend on local variables.
4087       --  Otherwise there is no way to declare the result outside of the
4088       --  block. Needless to say, in general the bounds will depend on the
4089       --  actuals in the call.
4090
4091       if Is_Unc then
4092          Targ1 := Defining_Identifier (First (Declarations (Blk)));
4093       end if;
4094
4095       --  If this is a derived function, establish the proper return type
4096
4097       if Present (Orig_Subp)
4098         and then Orig_Subp /= Subp
4099       then
4100          Ret_Type := Etype (Orig_Subp);
4101       else
4102          Ret_Type := Etype (Subp);
4103       end if;
4104
4105       --  Create temporaries for the actuals that are expressions, or that
4106       --  are scalars and require copying to preserve semantics.
4107
4108       F := First_Formal (Subp);
4109       A := First_Actual (N);
4110       while Present (F) loop
4111          if Present (Renamed_Object (F)) then
4112             Error_Msg_N ("cannot inline call to recursive subprogram", N);
4113             return;
4114          end if;
4115
4116          --  If the argument may be a controlling argument in a call within
4117          --  the inlined body, we must preserve its classwide nature to insure
4118          --  that dynamic dispatching take place subsequently. If the formal
4119          --  has a constraint it must be preserved to retain the semantics of
4120          --  the body.
4121
4122          if Is_Class_Wide_Type (Etype (F))
4123            or else (Is_Access_Type (Etype (F))
4124                       and then
4125                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
4126          then
4127             Temp_Typ := Etype (F);
4128
4129          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
4130            and then Etype (F) /= Base_Type (Etype (F))
4131          then
4132             Temp_Typ := Etype (F);
4133
4134          else
4135             Temp_Typ := Etype (A);
4136          end if;
4137
4138          --  If the actual is a simple name or a literal, no need to
4139          --  create a temporary, object can be used directly.
4140
4141          --  If the actual is a literal and the formal has its address taken,
4142          --  we cannot pass the literal itself as an argument, so its value
4143          --  must be captured in a temporary.
4144
4145          if (Is_Entity_Name (A)
4146               and then
4147                (not Is_Scalar_Type (Etype (A))
4148                  or else Ekind (Entity (A)) = E_Enumeration_Literal))
4149
4150          --  When the actual is an identifier and the corresponding formal
4151          --  is used only once in the original body, the formal can be
4152          --  substituted directly with the actual parameter.
4153
4154            or else (Nkind (A) = N_Identifier
4155              and then Formal_Is_Used_Once (F))
4156
4157            or else
4158              (Nkind_In (A, N_Real_Literal,
4159                             N_Integer_Literal,
4160                             N_Character_Literal)
4161                 and then not Address_Taken (F))
4162          then
4163             if Etype (F) /= Etype (A) then
4164                Set_Renamed_Object
4165                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
4166             else
4167                Set_Renamed_Object (F, A);
4168             end if;
4169
4170          else
4171             Temp := Make_Temporary (Loc, 'C');
4172
4173             --  If the actual for an in/in-out parameter is a view conversion,
4174             --  make it into an unchecked conversion, given that an untagged
4175             --  type conversion is not a proper object for a renaming.
4176
4177             --  In-out conversions that involve real conversions have already
4178             --  been transformed in Expand_Actuals.
4179
4180             if Nkind (A) = N_Type_Conversion
4181               and then Ekind (F) /= E_In_Parameter
4182             then
4183                New_A :=
4184                  Make_Unchecked_Type_Conversion (Loc,
4185                    Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
4186                    Expression   => Relocate_Node (Expression (A)));
4187
4188             elsif Etype (F) /= Etype (A) then
4189                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
4190                Temp_Typ := Etype (F);
4191
4192             else
4193                New_A := Relocate_Node (A);
4194             end if;
4195
4196             Set_Sloc (New_A, Sloc (N));
4197
4198             --  If the actual has a by-reference type, it cannot be copied, so
4199             --  its value is captured in a renaming declaration. Otherwise
4200             --  declare a local constant initialized with the actual.
4201
4202             --  We also use a renaming declaration for expressions of an array
4203             --  type that is not bit-packed, both for efficiency reasons and to
4204             --  respect the semantics of the call: in most cases the original
4205             --  call will pass the parameter by reference, and thus the inlined
4206             --  code will have the same semantics.
4207
4208             if Ekind (F) = E_In_Parameter
4209               and then not Is_By_Reference_Type (Etype (A))
4210               and then
4211                (not Is_Array_Type (Etype (A))
4212                  or else not Is_Object_Reference (A)
4213                  or else Is_Bit_Packed_Array (Etype (A)))
4214             then
4215                Decl :=
4216                  Make_Object_Declaration (Loc,
4217                    Defining_Identifier => Temp,
4218                    Constant_Present    => True,
4219                    Object_Definition   => New_Occurrence_Of (Temp_Typ, Loc),
4220                    Expression          => New_A);
4221             else
4222                Decl :=
4223                  Make_Object_Renaming_Declaration (Loc,
4224                    Defining_Identifier => Temp,
4225                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
4226                    Name                => New_A);
4227             end if;
4228
4229             Append (Decl, Decls);
4230             Set_Renamed_Object (F, Temp);
4231          end if;
4232
4233          Next_Formal (F);
4234          Next_Actual (A);
4235       end loop;
4236
4237       --  Establish target of function call. If context is not assignment or
4238       --  declaration, create a temporary as a target. The declaration for the
4239       --  temporary may be subsequently optimized away if the body is a single
4240       --  expression, or if the left-hand side of the assignment is simple
4241       --  enough, i.e. an entity or an explicit dereference of one.
4242
4243       if Ekind (Subp) = E_Function then
4244          if Nkind (Parent (N)) = N_Assignment_Statement
4245            and then Is_Entity_Name (Name (Parent (N)))
4246          then
4247             Targ := Name (Parent (N));
4248
4249          elsif Nkind (Parent (N)) = N_Assignment_Statement
4250            and then Nkind (Name (Parent (N))) = N_Explicit_Dereference
4251            and then Is_Entity_Name (Prefix (Name (Parent (N))))
4252          then
4253             Targ := Name (Parent (N));
4254
4255          elsif Nkind (Parent (N)) = N_Object_Declaration
4256            and then Is_Limited_Type (Etype (Subp))
4257          then
4258             Targ := Defining_Identifier (Parent (N));
4259
4260          else
4261             --  Replace call with temporary and create its declaration
4262
4263             Temp := Make_Temporary (Loc, 'C');
4264             Set_Is_Internal (Temp);
4265
4266             --  For the unconstrained case, the generated temporary has the
4267             --  same constrained declaration as the result variable. It may
4268             --  eventually be possible to remove that temporary and use the
4269             --  result variable directly.
4270
4271             if Is_Unc then
4272                Decl :=
4273                  Make_Object_Declaration (Loc,
4274                    Defining_Identifier => Temp,
4275                    Object_Definition =>
4276                      New_Copy_Tree (Object_Definition (Parent (Targ1))));
4277
4278                Replace_Formals (Decl);
4279
4280             else
4281                Decl :=
4282                  Make_Object_Declaration (Loc,
4283                    Defining_Identifier => Temp,
4284                    Object_Definition =>
4285                      New_Occurrence_Of (Ret_Type, Loc));
4286
4287                Set_Etype (Temp, Ret_Type);
4288             end if;
4289
4290             Set_No_Initialization (Decl);
4291             Append (Decl, Decls);
4292             Rewrite (N, New_Occurrence_Of (Temp, Loc));
4293             Targ := Temp;
4294          end if;
4295       end if;
4296
4297       Insert_Actions (N, Decls);
4298
4299       --  Traverse the tree and replace formals with actuals or their thunks.
4300       --  Attach block to tree before analysis and rewriting.
4301
4302       Replace_Formals (Blk);
4303       Set_Parent (Blk, N);
4304
4305       if not Comes_From_Source (Subp)
4306         or else Is_Predef
4307       then
4308          Reset_Slocs (Blk);
4309       end if;
4310
4311       if Present (Exit_Lab) then
4312
4313          --  If the body was a single expression, the single return statement
4314          --  and the corresponding label are useless.
4315
4316          if Num_Ret = 1
4317            and then
4318              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
4319                N_Goto_Statement
4320          then
4321             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
4322          else
4323             Append (Lab_Decl, (Declarations (Blk)));
4324             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
4325          end if;
4326       end if;
4327
4328       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
4329       --  conflicting private views that Gigi would ignore. If this is a
4330       --  predefined unit, analyze with checks off, as is done in the non-
4331       --  inlined run-time units.
4332
4333       declare
4334          I_Flag : constant Boolean := In_Inlined_Body;
4335
4336       begin
4337          In_Inlined_Body := True;
4338
4339          if Is_Predef then
4340             declare
4341                Style : constant Boolean := Style_Check;
4342             begin
4343                Style_Check := False;
4344                Analyze (Blk, Suppress => All_Checks);
4345                Style_Check := Style;
4346             end;
4347
4348          else
4349             Analyze (Blk);
4350          end if;
4351
4352          In_Inlined_Body := I_Flag;
4353       end;
4354
4355       if Ekind (Subp) = E_Procedure then
4356          Rewrite_Procedure_Call (N, Blk);
4357       else
4358          Rewrite_Function_Call (N, Blk);
4359
4360          --  For the unconstrained case, the replacement of the call has been
4361          --  made prior to the complete analysis of the generated declarations.
4362          --  Propagate the proper type now.
4363
4364          if Is_Unc then
4365             if Nkind (N) = N_Identifier then
4366                Set_Etype (N, Etype (Entity (N)));
4367             else
4368                Set_Etype (N, Etype (Targ1));
4369             end if;
4370          end if;
4371       end if;
4372
4373       Restore_Env;
4374
4375       --  Cleanup mapping between formals and actuals for other expansions
4376
4377       F := First_Formal (Subp);
4378       while Present (F) loop
4379          Set_Renamed_Object (F, Empty);
4380          Next_Formal (F);
4381       end loop;
4382    end Expand_Inlined_Call;
4383
4384    ----------------------------------------
4385    -- Expand_N_Extended_Return_Statement --
4386    ----------------------------------------
4387
4388    --  If there is a Handled_Statement_Sequence, we rewrite this:
4389
4390    --     return Result : T := <expression> do
4391    --        <handled_seq_of_stms>
4392    --     end return;
4393
4394    --  to be:
4395
4396    --     declare
4397    --        Result : T := <expression>;
4398    --     begin
4399    --        <handled_seq_of_stms>
4400    --        return Result;
4401    --     end;
4402
4403    --  Otherwise (no Handled_Statement_Sequence), we rewrite this:
4404
4405    --     return Result : T := <expression>;
4406
4407    --  to be:
4408
4409    --     return <expression>;
4410
4411    --  unless it's build-in-place or there's no <expression>, in which case
4412    --  we generate:
4413
4414    --     declare
4415    --        Result : T := <expression>;
4416    --     begin
4417    --        return Result;
4418    --     end;
4419
4420    --  Note that this case could have been written by the user as an extended
4421    --  return statement, or could have been transformed to this from a simple
4422    --  return statement.
4423
4424    --  That is, we need to have a reified return object if there are statements
4425    --  (which might refer to it) or if we're doing build-in-place (so we can
4426    --  set its address to the final resting place or if there is no expression
4427    --  (in which case default initial values might need to be set).
4428
4429    procedure Expand_N_Extended_Return_Statement (N : Node_Id) is
4430       Loc : constant Source_Ptr := Sloc (N);
4431
4432       Par_Func     : constant Entity_Id :=
4433                        Return_Applies_To (Return_Statement_Entity (N));
4434       Ret_Obj_Id   : constant Entity_Id :=
4435                        First_Entity (Return_Statement_Entity (N));
4436       Ret_Obj_Decl : constant Node_Id := Parent (Ret_Obj_Id);
4437
4438       Is_Build_In_Place : constant Boolean :=
4439                             Is_Build_In_Place_Function (Par_Func);
4440
4441       Exp         : Node_Id;
4442       HSS         : Node_Id;
4443       Result      : Node_Id;
4444       Return_Stmt : Node_Id;
4445       Stmts       : List_Id;
4446
4447       function Build_Heap_Allocator
4448         (Temp_Id    : Entity_Id;
4449          Temp_Typ   : Entity_Id;
4450          Func_Id    : Entity_Id;
4451          Ret_Typ    : Entity_Id;
4452          Alloc_Expr : Node_Id) return Node_Id;
4453       --  Create the statements necessary to allocate a return object on the
4454       --  caller's master. The master is available through implicit parameter
4455       --  BIPfinalizationmaster.
4456       --
4457       --    if BIPfinalizationmaster /= null then
4458       --       declare
4459       --          type Ptr_Typ is access Ret_Typ;
4460       --          for Ptr_Typ'Storage_Pool use
4461       --                Base_Pool (BIPfinalizationmaster.all).all;
4462       --          Local : Ptr_Typ;
4463       --
4464       --       begin
4465       --          procedure Allocate (...) is
4466       --          begin
4467       --             System.Storage_Pools.Subpools.Allocate_Any (...);
4468       --          end Allocate;
4469       --
4470       --          Local := <Alloc_Expr>;
4471       --          Temp_Id := Temp_Typ (Local);
4472       --       end;
4473       --    end if;
4474       --
4475       --  Temp_Id is the temporary which is used to reference the internally
4476       --  created object in all allocation forms. Temp_Typ is the type of the
4477       --  temporary. Func_Id is the enclosing function. Ret_Typ is the return
4478       --  type of Func_Id. Alloc_Expr is the actual allocator.
4479
4480       function Move_Activation_Chain return Node_Id;
4481       --  Construct a call to System.Tasking.Stages.Move_Activation_Chain
4482       --  with parameters:
4483       --    From         current activation chain
4484       --    To           activation chain passed in by the caller
4485       --    New_Master   master passed in by the caller
4486
4487       --------------------------
4488       -- Build_Heap_Allocator --
4489       --------------------------
4490
4491       function Build_Heap_Allocator
4492         (Temp_Id    : Entity_Id;
4493          Temp_Typ   : Entity_Id;
4494          Func_Id    : Entity_Id;
4495          Ret_Typ    : Entity_Id;
4496          Alloc_Expr : Node_Id) return Node_Id
4497       is
4498       begin
4499          --  Processing for build-in-place object allocation. This is disabled
4500          --  on .NET/JVM because the targets do not support pools.
4501
4502          if VM_Target = No_VM
4503            and then Is_Build_In_Place_Function (Func_Id)
4504            and then Needs_Finalization (Ret_Typ)
4505          then
4506             declare
4507                Decls      : constant List_Id := New_List;
4508                Fin_Mas_Id : constant Entity_Id :=
4509                               Build_In_Place_Formal
4510                                 (Func_Id, BIP_Finalization_Master);
4511                Stmts      : constant List_Id := New_List;
4512
4513                Local_Id : Entity_Id;
4514                Pool_Id  : Entity_Id;
4515                Ptr_Typ  : Entity_Id;
4516
4517             begin
4518                --  Generate:
4519                --    Pool_Id renames Base_Pool (BIPfinalizationmaster.all).all;
4520
4521                Pool_Id := Make_Temporary (Loc, 'P');
4522
4523                Append_To (Decls,
4524                  Make_Object_Renaming_Declaration (Loc,
4525                    Defining_Identifier => Pool_Id,
4526                    Subtype_Mark        =>
4527                      New_Reference_To (RTE (RE_Root_Storage_Pool), Loc),
4528                    Name                =>
4529                      Make_Explicit_Dereference (Loc,
4530                        Prefix =>
4531                          Make_Function_Call (Loc,
4532                            Name                   =>
4533                              New_Reference_To (RTE (RE_Base_Pool), Loc),
4534                            Parameter_Associations => New_List (
4535                              Make_Explicit_Dereference (Loc,
4536                                Prefix =>
4537                                  New_Reference_To (Fin_Mas_Id, Loc)))))));
4538
4539                --  Create an access type which uses the storage pool of the
4540                --  caller's master. This additional type is necessary because
4541                --  the finalization master cannot be associated with the type
4542                --  of the temporary. Otherwise the secondary stack allocation
4543                --  will fail.
4544
4545                --  Generate:
4546                --    type Ptr_Typ is access Ret_Typ;
4547
4548                Ptr_Typ := Make_Temporary (Loc, 'P');
4549
4550                Append_To (Decls,
4551                  Make_Full_Type_Declaration (Loc,
4552                    Defining_Identifier => Ptr_Typ,
4553                    Type_Definition     =>
4554                      Make_Access_To_Object_Definition (Loc,
4555                        Subtype_Indication =>
4556                          New_Reference_To (Ret_Typ, Loc))));
4557
4558                --  Perform minor decoration in order to set the master and the
4559                --  storage pool attributes.
4560
4561                Set_Ekind (Ptr_Typ, E_Access_Type);
4562                Set_Finalization_Master     (Ptr_Typ, Fin_Mas_Id);
4563                Set_Associated_Storage_Pool (Ptr_Typ, Pool_Id);
4564
4565                --  Create the temporary, generate:
4566                --
4567                --    Local_Id : Ptr_Typ;
4568
4569                Local_Id := Make_Temporary (Loc, 'T');
4570
4571                Append_To (Decls,
4572                  Make_Object_Declaration (Loc,
4573                    Defining_Identifier => Local_Id,
4574                    Object_Definition   =>
4575                      New_Reference_To (Ptr_Typ, Loc)));
4576
4577                --  Allocate the object, generate:
4578                --
4579                --    Local_Id := <Alloc_Expr>;
4580
4581                Append_To (Stmts,
4582                  Make_Assignment_Statement (Loc,
4583                    Name       => New_Reference_To (Local_Id, Loc),
4584                    Expression => Alloc_Expr));
4585
4586                --  Generate:
4587                --    Temp_Id := Temp_Typ (Local_Id);
4588
4589                Append_To (Stmts,
4590                  Make_Assignment_Statement (Loc,
4591                    Name       => New_Reference_To (Temp_Id, Loc),
4592                    Expression =>
4593                      Unchecked_Convert_To (Temp_Typ,
4594                        New_Reference_To (Local_Id, Loc))));
4595
4596                --  Wrap the allocation in a block. This is further conditioned
4597                --  by checking the caller finalization master at runtime. A
4598                --  null value indicates a non-existent master, most likely due
4599                --  to a Finalize_Storage_Only allocation.
4600
4601                --  Generate:
4602                --    if BIPfinalizationmaster /= null then
4603                --       declare
4604                --          <Decls>
4605                --       begin
4606                --          <Stmts>
4607                --       end;
4608                --    end if;
4609
4610                return
4611                  Make_If_Statement (Loc,
4612                    Condition       =>
4613                      Make_Op_Ne (Loc,
4614                        Left_Opnd  => New_Reference_To (Fin_Mas_Id, Loc),
4615                        Right_Opnd => Make_Null (Loc)),
4616
4617                    Then_Statements => New_List (
4618                      Make_Block_Statement (Loc,
4619                        Declarations               => Decls,
4620                        Handled_Statement_Sequence =>
4621                          Make_Handled_Sequence_Of_Statements (Loc,
4622                            Statements => Stmts))));
4623             end;
4624
4625          --  For all other cases, generate:
4626          --
4627          --    Temp_Id := <Alloc_Expr>;
4628
4629          else
4630             return
4631               Make_Assignment_Statement (Loc,
4632                 Name       => New_Reference_To (Temp_Id, Loc),
4633                 Expression => Alloc_Expr);
4634          end if;
4635       end Build_Heap_Allocator;
4636
4637       ---------------------------
4638       -- Move_Activation_Chain --
4639       ---------------------------
4640
4641       function Move_Activation_Chain return Node_Id is
4642          Chain_Formal  : constant Entity_Id :=
4643                            Build_In_Place_Formal
4644                             (Par_Func, BIP_Activation_Chain);
4645          To            : constant Node_Id :=
4646                            New_Reference_To (Chain_Formal, Loc);
4647          Master_Formal : constant Entity_Id :=
4648                            Build_In_Place_Formal (Par_Func, BIP_Master);
4649          New_Master    : constant Node_Id :=
4650                            New_Reference_To (Master_Formal, Loc);
4651
4652          Chain_Id : Entity_Id;
4653          From     : Node_Id;
4654
4655       begin
4656          Chain_Id := First_Entity (Return_Statement_Entity (N));
4657          while Chars (Chain_Id) /= Name_uChain loop
4658             Chain_Id := Next_Entity (Chain_Id);
4659          end loop;
4660
4661          From :=
4662            Make_Attribute_Reference (Loc,
4663              Prefix =>
4664                New_Reference_To (Chain_Id, Loc),
4665              Attribute_Name => Name_Unrestricted_Access);
4666          --  ??? Not clear why "Make_Identifier (Loc, Name_uChain)" doesn't
4667          --  work, instead of "New_Reference_To (Chain_Id, Loc)" above.
4668
4669          return
4670            Make_Procedure_Call_Statement (Loc,
4671              Name                   =>
4672                New_Reference_To (RTE (RE_Move_Activation_Chain), Loc),
4673              Parameter_Associations => New_List (From, To, New_Master));
4674       end Move_Activation_Chain;
4675
4676    --  Start of processing for Expand_N_Extended_Return_Statement
4677
4678    begin
4679       if Nkind (Ret_Obj_Decl) = N_Object_Declaration then
4680          Exp := Expression (Ret_Obj_Decl);
4681       else
4682          Exp := Empty;
4683       end if;
4684
4685       HSS := Handled_Statement_Sequence (N);
4686
4687       --  If the returned object needs finalization actions, the function must
4688       --  perform the appropriate cleanup should it fail to return. The state
4689       --  of the function itself is tracked through a flag which is coupled
4690       --  with the scope finalizer. There is one flag per each return object
4691       --  in case of multiple returns.
4692
4693       if Is_Build_In_Place
4694         and then Needs_Finalization (Etype (Ret_Obj_Id))
4695       then
4696          declare
4697             Flag_Decl : Node_Id;
4698             Flag_Id   : Entity_Id;
4699             Func_Bod  : Node_Id;
4700
4701          begin
4702             --  Recover the function body
4703
4704             Func_Bod := Unit_Declaration_Node (Par_Func);
4705             if Nkind (Func_Bod) = N_Subprogram_Declaration then
4706                Func_Bod := Parent (Parent (Corresponding_Body (Func_Bod)));
4707             end if;
4708
4709             --  Create a flag to track the function state
4710
4711             Flag_Id := Make_Temporary (Loc, 'F');
4712             Set_Return_Flag_Or_Transient_Decl (Ret_Obj_Id, Flag_Id);
4713
4714             --  Insert the flag at the beginning of the function declarations,
4715             --  generate:
4716             --    Fnn : Boolean := False;
4717
4718             Flag_Decl :=
4719               Make_Object_Declaration (Loc,
4720                 Defining_Identifier => Flag_Id,
4721                   Object_Definition =>
4722                     New_Reference_To (Standard_Boolean, Loc),
4723                   Expression        => New_Reference_To (Standard_False, Loc));
4724
4725             Prepend_To (Declarations (Func_Bod), Flag_Decl);
4726             Analyze (Flag_Decl);
4727          end;
4728       end if;
4729
4730       --  Build a simple_return_statement that returns the return object when
4731       --  there is a statement sequence, or no expression, or the result will
4732       --  be built in place. Note however that we currently do this for all
4733       --  composite cases, even though nonlimited composite results are not yet
4734       --  built in place (though we plan to do so eventually).
4735
4736       if Present (HSS)
4737         or else Is_Composite_Type (Etype (Par_Func))
4738         or else No (Exp)
4739       then
4740          if No (HSS) then
4741             Stmts := New_List;
4742
4743          --  If the extended return has a handled statement sequence, then wrap
4744          --  it in a block and use the block as the first statement.
4745
4746          else
4747             Stmts := New_List (
4748               Make_Block_Statement (Loc,
4749                 Declarations               => New_List,
4750                 Handled_Statement_Sequence => HSS));
4751          end if;
4752
4753          --  If the result type contains tasks, we call Move_Activation_Chain.
4754          --  Later, the cleanup code will call Complete_Master, which will
4755          --  terminate any unactivated tasks belonging to the return statement
4756          --  master. But Move_Activation_Chain updates their master to be that
4757          --  of the caller, so they will not be terminated unless the return
4758          --  statement completes unsuccessfully due to exception, abort, goto,
4759          --  or exit. As a formality, we test whether the function requires the
4760          --  result to be built in place, though that's necessarily true for
4761          --  the case of result types with task parts.
4762
4763          if Is_Build_In_Place
4764            and then Has_Task (Etype (Par_Func))
4765          then
4766             Append_To (Stmts, Move_Activation_Chain);
4767          end if;
4768
4769          --  Update the state of the function right before the object is
4770          --  returned.
4771
4772          if Is_Build_In_Place
4773            and then Needs_Finalization (Etype (Ret_Obj_Id))
4774          then
4775             declare
4776                Flag_Id : constant Entity_Id :=
4777                            Return_Flag_Or_Transient_Decl (Ret_Obj_Id);
4778
4779             begin
4780                --  Generate:
4781                --    Fnn := True;
4782
4783                Append_To (Stmts,
4784                  Make_Assignment_Statement (Loc,
4785                    Name       => New_Reference_To (Flag_Id, Loc),
4786                    Expression => New_Reference_To (Standard_True, Loc)));
4787             end;
4788          end if;
4789
4790          --  Build a simple_return_statement that returns the return object
4791
4792          Return_Stmt :=
4793            Make_Simple_Return_Statement (Loc,
4794              Expression => New_Occurrence_Of (Ret_Obj_Id, Loc));
4795          Append_To (Stmts, Return_Stmt);
4796
4797          HSS := Make_Handled_Sequence_Of_Statements (Loc, Stmts);
4798       end if;
4799
4800       --  Case where we build a return statement block
4801
4802       if Present (HSS) then
4803          Result :=
4804            Make_Block_Statement (Loc,
4805              Declarations               => Return_Object_Declarations (N),
4806              Handled_Statement_Sequence => HSS);
4807
4808          --  We set the entity of the new block statement to be that of the
4809          --  return statement. This is necessary so that various fields, such
4810          --  as Finalization_Chain_Entity carry over from the return statement
4811          --  to the block. Note that this block is unusual, in that its entity
4812          --  is an E_Return_Statement rather than an E_Block.
4813
4814          Set_Identifier
4815            (Result, New_Occurrence_Of (Return_Statement_Entity (N), Loc));
4816
4817          --  If the object decl was already rewritten as a renaming, then
4818          --  we don't want to do the object allocation and transformation of
4819          --  of the return object declaration to a renaming. This case occurs
4820          --  when the return object is initialized by a call to another
4821          --  build-in-place function, and that function is responsible for the
4822          --  allocation of the return object.
4823
4824          if Is_Build_In_Place
4825            and then Nkind (Ret_Obj_Decl) = N_Object_Renaming_Declaration
4826          then
4827             pragma Assert
4828               (Nkind (Original_Node (Ret_Obj_Decl)) = N_Object_Declaration
4829                 and then Is_Build_In_Place_Function_Call
4830                            (Expression (Original_Node (Ret_Obj_Decl))));
4831
4832             --  Return the build-in-place result by reference
4833
4834             Set_By_Ref (Return_Stmt);
4835
4836          elsif Is_Build_In_Place then
4837
4838             --  Locate the implicit access parameter associated with the
4839             --  caller-supplied return object and convert the return
4840             --  statement's return object declaration to a renaming of a
4841             --  dereference of the access parameter. If the return object's
4842             --  declaration includes an expression that has not already been
4843             --  expanded as separate assignments, then add an assignment
4844             --  statement to ensure the return object gets initialized.
4845
4846             --    declare
4847             --       Result : T [:= <expression>];
4848             --    begin
4849             --       ...
4850
4851             --  is converted to
4852
4853             --    declare
4854             --       Result : T renames FuncRA.all;
4855             --       [Result := <expression;]
4856             --    begin
4857             --       ...
4858
4859             declare
4860                Return_Obj_Id    : constant Entity_Id :=
4861                                     Defining_Identifier (Ret_Obj_Decl);
4862                Return_Obj_Typ   : constant Entity_Id := Etype (Return_Obj_Id);
4863                Return_Obj_Expr  : constant Node_Id :=
4864                                     Expression (Ret_Obj_Decl);
4865                Result_Subt      : constant Entity_Id := Etype (Par_Func);
4866                Constr_Result    : constant Boolean :=
4867                                     Is_Constrained (Result_Subt);
4868                Obj_Alloc_Formal : Entity_Id;
4869                Object_Access    : Entity_Id;
4870                Obj_Acc_Deref    : Node_Id;
4871                Init_Assignment  : Node_Id := Empty;
4872
4873             begin
4874                --  Build-in-place results must be returned by reference
4875
4876                Set_By_Ref (Return_Stmt);
4877
4878                --  Retrieve the implicit access parameter passed by the caller
4879
4880                Object_Access :=
4881                  Build_In_Place_Formal (Par_Func, BIP_Object_Access);
4882
4883                --  If the return object's declaration includes an expression
4884                --  and the declaration isn't marked as No_Initialization, then
4885                --  we need to generate an assignment to the object and insert
4886                --  it after the declaration before rewriting it as a renaming
4887                --  (otherwise we'll lose the initialization). The case where
4888                --  the result type is an interface (or class-wide interface)
4889                --  is also excluded because the context of the function call
4890                --  must be unconstrained, so the initialization will always
4891                --  be done as part of an allocator evaluation (storage pool
4892                --  or secondary stack), never to a constrained target object
4893                --  passed in by the caller. Besides the assignment being
4894                --  unneeded in this case, it avoids problems with trying to
4895                --  generate a dispatching assignment when the return expression
4896                --  is a nonlimited descendant of a limited interface (the
4897                --  interface has no assignment operation).
4898
4899                if Present (Return_Obj_Expr)
4900                  and then not No_Initialization (Ret_Obj_Decl)
4901                  and then not Is_Interface (Return_Obj_Typ)
4902                then
4903                   Init_Assignment :=
4904                     Make_Assignment_Statement (Loc,
4905                       Name       => New_Reference_To (Return_Obj_Id, Loc),
4906                       Expression => Relocate_Node (Return_Obj_Expr));
4907
4908                   Set_Etype (Name (Init_Assignment), Etype (Return_Obj_Id));
4909                   Set_Assignment_OK (Name (Init_Assignment));
4910                   Set_No_Ctrl_Actions (Init_Assignment);
4911
4912                   Set_Parent (Name (Init_Assignment), Init_Assignment);
4913                   Set_Parent (Expression (Init_Assignment), Init_Assignment);
4914
4915                   Set_Expression (Ret_Obj_Decl, Empty);
4916
4917                   if Is_Class_Wide_Type (Etype (Return_Obj_Id))
4918                     and then not Is_Class_Wide_Type
4919                                    (Etype (Expression (Init_Assignment)))
4920                   then
4921                      Rewrite (Expression (Init_Assignment),
4922                        Make_Type_Conversion (Loc,
4923                          Subtype_Mark =>
4924                            New_Occurrence_Of (Etype (Return_Obj_Id), Loc),
4925                          Expression   =>
4926                            Relocate_Node (Expression (Init_Assignment))));
4927                   end if;
4928
4929                   --  In the case of functions where the calling context can
4930                   --  determine the form of allocation needed, initialization
4931                   --  is done with each part of the if statement that handles
4932                   --  the different forms of allocation (this is true for
4933                   --  unconstrained and tagged result subtypes).
4934
4935                   if Constr_Result
4936                     and then not Is_Tagged_Type (Underlying_Type (Result_Subt))
4937                   then
4938                      Insert_After (Ret_Obj_Decl, Init_Assignment);
4939                   end if;
4940                end if;
4941
4942                --  When the function's subtype is unconstrained, a run-time
4943                --  test is needed to determine the form of allocation to use
4944                --  for the return object. The function has an implicit formal
4945                --  parameter indicating this. If the BIP_Alloc_Form formal has
4946                --  the value one, then the caller has passed access to an
4947                --  existing object for use as the return object. If the value
4948                --  is two, then the return object must be allocated on the
4949                --  secondary stack. Otherwise, the object must be allocated in
4950                --  a storage pool (currently only supported for the global
4951                --  heap, user-defined storage pools TBD ???). We generate an
4952                --  if statement to test the implicit allocation formal and
4953                --  initialize a local access value appropriately, creating
4954                --  allocators in the secondary stack and global heap cases.
4955                --  The special formal also exists and must be tested when the
4956                --  function has a tagged result, even when the result subtype
4957                --  is constrained, because in general such functions can be
4958                --  called in dispatching contexts and must be handled similarly
4959                --  to functions with a class-wide result.
4960
4961                if not Constr_Result
4962                  or else Is_Tagged_Type (Underlying_Type (Result_Subt))
4963                then
4964                   Obj_Alloc_Formal :=
4965                     Build_In_Place_Formal (Par_Func, BIP_Alloc_Form);
4966
4967                   declare
4968                      Ref_Type       : Entity_Id;
4969                      Ptr_Type_Decl  : Node_Id;
4970                      Alloc_Obj_Id   : Entity_Id;
4971                      Alloc_Obj_Decl : Node_Id;
4972                      Alloc_If_Stmt  : Node_Id;
4973                      Heap_Allocator : Node_Id;
4974                      SS_Allocator   : Node_Id;
4975
4976                   begin
4977                      --  Reuse the itype created for the function's implicit
4978                      --  access formal. This avoids the need to create a new
4979                      --  access type here, plus it allows assigning the access
4980                      --  formal directly without applying a conversion.
4981
4982                      --    Ref_Type := Etype (Object_Access);
4983
4984                      --  Create an access type designating the function's
4985                      --  result subtype.
4986
4987                      Ref_Type := Make_Temporary (Loc, 'A');
4988
4989                      Ptr_Type_Decl :=
4990                        Make_Full_Type_Declaration (Loc,
4991                          Defining_Identifier => Ref_Type,
4992                          Type_Definition     =>
4993                            Make_Access_To_Object_Definition (Loc,
4994                              All_Present        => True,
4995                              Subtype_Indication =>
4996                                New_Reference_To (Return_Obj_Typ, Loc)));
4997
4998                      Insert_Before (Ret_Obj_Decl, Ptr_Type_Decl);
4999
5000                      --  Create an access object that will be initialized to an
5001                      --  access value denoting the return object, either coming
5002                      --  from an implicit access value passed in by the caller
5003                      --  or from the result of an allocator.
5004
5005                      Alloc_Obj_Id := Make_Temporary (Loc, 'R');
5006                      Set_Etype (Alloc_Obj_Id, Ref_Type);
5007
5008                      Alloc_Obj_Decl :=
5009                        Make_Object_Declaration (Loc,
5010                          Defining_Identifier => Alloc_Obj_Id,
5011                          Object_Definition   =>
5012                            New_Reference_To (Ref_Type, Loc));
5013
5014                      Insert_Before (Ret_Obj_Decl, Alloc_Obj_Decl);
5015
5016                      --  Create allocators for both the secondary stack and
5017                      --  global heap. If there's an initialization expression,
5018                      --  then create these as initialized allocators.
5019
5020                      if Present (Return_Obj_Expr)
5021                        and then not No_Initialization (Ret_Obj_Decl)
5022                      then
5023                         --  Always use the type of the expression for the
5024                         --  qualified expression, rather than the result type.
5025                         --  In general we cannot always use the result type
5026                         --  for the allocator, because the expression might be
5027                         --  of a specific type, such as in the case of an
5028                         --  aggregate or even a nonlimited object when the
5029                         --  result type is a limited class-wide interface type.
5030
5031                         Heap_Allocator :=
5032                           Make_Allocator (Loc,
5033                             Expression =>
5034                               Make_Qualified_Expression (Loc,
5035                                 Subtype_Mark =>
5036                                   New_Reference_To
5037                                     (Etype (Return_Obj_Expr), Loc),
5038                                 Expression   =>
5039                                   New_Copy_Tree (Return_Obj_Expr)));
5040
5041                      else
5042                         --  If the function returns a class-wide type we cannot
5043                         --  use the return type for the allocator. Instead we
5044                         --  use the type of the expression, which must be an
5045                         --  aggregate of a definite type.
5046
5047                         if Is_Class_Wide_Type (Return_Obj_Typ) then
5048                            Heap_Allocator :=
5049                              Make_Allocator (Loc,
5050                                Expression =>
5051                                  New_Reference_To
5052                                    (Etype (Return_Obj_Expr), Loc));
5053                         else
5054                            Heap_Allocator :=
5055                              Make_Allocator (Loc,
5056                                Expression =>
5057                                  New_Reference_To (Return_Obj_Typ, Loc));
5058                         end if;
5059
5060                         --  If the object requires default initialization then
5061                         --  that will happen later following the elaboration of
5062                         --  the object renaming. If we don't turn it off here
5063                         --  then the object will be default initialized twice.
5064
5065                         Set_No_Initialization (Heap_Allocator);
5066                      end if;
5067
5068                      --  If the No_Allocators restriction is active, then only
5069                      --  an allocator for secondary stack allocation is needed.
5070                      --  It's OK for such allocators to have Comes_From_Source
5071                      --  set to False, because gigi knows not to flag them as
5072                      --  being a violation of No_Implicit_Heap_Allocations.
5073
5074                      if Restriction_Active (No_Allocators) then
5075                         SS_Allocator   := Heap_Allocator;
5076                         Heap_Allocator := Make_Null (Loc);
5077
5078                      --  Otherwise the heap allocator may be needed, so we make
5079                      --  another allocator for secondary stack allocation.
5080
5081                      else
5082                         SS_Allocator := New_Copy_Tree (Heap_Allocator);
5083
5084                         --  The heap allocator is marked Comes_From_Source
5085                         --  since it corresponds to an explicit user-written
5086                         --  allocator (that is, it will only be executed on
5087                         --  behalf of callers that call the function as
5088                         --  initialization for such an allocator). This
5089                         --  prevents errors when No_Implicit_Heap_Allocations
5090                         --  is in force.
5091
5092                         Set_Comes_From_Source (Heap_Allocator, True);
5093                      end if;
5094
5095                      --  The allocator is returned on the secondary stack. We
5096                      --  don't do this on VM targets, since the SS is not used.
5097
5098                      if VM_Target = No_VM then
5099                         Set_Storage_Pool (SS_Allocator, RTE (RE_SS_Pool));
5100                         Set_Procedure_To_Call
5101                           (SS_Allocator, RTE (RE_SS_Allocate));
5102
5103                         --  The allocator is returned on the secondary stack,
5104                         --  so indicate that the function return, as well as
5105                         --  the block that encloses the allocator, must not
5106                         --  release it. The flags must be set now because the
5107                         --  decision to use the secondary stack is done very
5108                         --  late in the course of expanding the return
5109                         --  statement, past the point where these flags are
5110                         --  normally set.
5111
5112                         Set_Sec_Stack_Needed_For_Return (Par_Func);
5113                         Set_Sec_Stack_Needed_For_Return
5114                           (Return_Statement_Entity (N));
5115                         Set_Uses_Sec_Stack (Par_Func);
5116                         Set_Uses_Sec_Stack (Return_Statement_Entity (N));
5117                      end if;
5118
5119                      --  Create an if statement to test the BIP_Alloc_Form
5120                      --  formal and initialize the access object to either the
5121                      --  BIP_Object_Access formal (BIP_Alloc_Form = 0), the
5122                      --  result of allocating the object in the secondary stack
5123                      --  (BIP_Alloc_Form = 1), or else an allocator to create
5124                      --  the return object in the heap (BIP_Alloc_Form = 2).
5125
5126                      --  ??? An unchecked type conversion must be made in the
5127                      --  case of assigning the access object formal to the
5128                      --  local access object, because a normal conversion would
5129                      --  be illegal in some cases (such as converting access-
5130                      --  to-unconstrained to access-to-constrained), but the
5131                      --  the unchecked conversion will presumably fail to work
5132                      --  right in just such cases. It's not clear at all how to
5133                      --  handle this. ???
5134
5135                      Alloc_If_Stmt :=
5136                        Make_If_Statement (Loc,
5137                          Condition =>
5138                            Make_Op_Eq (Loc,
5139                              Left_Opnd  =>
5140                                New_Reference_To (Obj_Alloc_Formal, Loc),
5141                              Right_Opnd =>
5142                                Make_Integer_Literal (Loc,
5143                                  UI_From_Int (BIP_Allocation_Form'Pos
5144                                                 (Caller_Allocation)))),
5145
5146                          Then_Statements => New_List (
5147                            Make_Assignment_Statement (Loc,
5148                              Name       =>
5149                                New_Reference_To (Alloc_Obj_Id, Loc),
5150                              Expression =>
5151                                Make_Unchecked_Type_Conversion (Loc,
5152                                  Subtype_Mark =>
5153                                    New_Reference_To (Ref_Type, Loc),
5154                                  Expression   =>
5155                                    New_Reference_To (Object_Access, Loc)))),
5156
5157                          Elsif_Parts => New_List (
5158                            Make_Elsif_Part (Loc,
5159                              Condition =>
5160                                Make_Op_Eq (Loc,
5161                                  Left_Opnd  =>
5162                                    New_Reference_To (Obj_Alloc_Formal, Loc),
5163                                  Right_Opnd =>
5164                                    Make_Integer_Literal (Loc,
5165                                      UI_From_Int (BIP_Allocation_Form'Pos
5166                                                     (Secondary_Stack)))),
5167
5168                              Then_Statements => New_List (
5169                                Make_Assignment_Statement (Loc,
5170                                  Name       =>
5171                                    New_Reference_To (Alloc_Obj_Id, Loc),
5172                                  Expression => SS_Allocator)))),
5173
5174                          Else_Statements => New_List (
5175                            Build_Heap_Allocator
5176                              (Temp_Id    => Alloc_Obj_Id,
5177                               Temp_Typ   => Ref_Type,
5178                               Func_Id    => Par_Func,
5179                               Ret_Typ    => Return_Obj_Typ,
5180                               Alloc_Expr => Heap_Allocator)));
5181
5182                      --  If a separate initialization assignment was created
5183                      --  earlier, append that following the assignment of the
5184                      --  implicit access formal to the access object, to ensure
5185                      --  that the return object is initialized in that case.
5186                      --  In this situation, the target of the assignment must
5187                      --  be rewritten to denote a dereference of the access to
5188                      --  the return object passed in by the caller.
5189
5190                      if Present (Init_Assignment) then
5191                         Rewrite (Name (Init_Assignment),
5192                           Make_Explicit_Dereference (Loc,
5193                             Prefix => New_Reference_To (Alloc_Obj_Id, Loc)));
5194
5195                         Set_Etype
5196                           (Name (Init_Assignment), Etype (Return_Obj_Id));
5197
5198                         Append_To
5199                           (Then_Statements (Alloc_If_Stmt), Init_Assignment);
5200                      end if;
5201
5202                      Insert_Before (Ret_Obj_Decl, Alloc_If_Stmt);
5203
5204                      --  Remember the local access object for use in the
5205                      --  dereference of the renaming created below.
5206
5207                      Object_Access := Alloc_Obj_Id;
5208                   end;
5209                end if;
5210
5211                --  Replace the return object declaration with a renaming of a
5212                --  dereference of the access value designating the return
5213                --  object.
5214
5215                Obj_Acc_Deref :=
5216                  Make_Explicit_Dereference (Loc,
5217                    Prefix => New_Reference_To (Object_Access, Loc));
5218
5219                Rewrite (Ret_Obj_Decl,
5220                  Make_Object_Renaming_Declaration (Loc,
5221                    Defining_Identifier => Return_Obj_Id,
5222                    Access_Definition   => Empty,
5223                    Subtype_Mark        =>
5224                      New_Occurrence_Of (Return_Obj_Typ, Loc),
5225                    Name                => Obj_Acc_Deref));
5226
5227                Set_Renamed_Object (Return_Obj_Id, Obj_Acc_Deref);
5228             end;
5229          end if;
5230
5231       --  Case where we do not build a block
5232
5233       else
5234          --  We're about to drop Return_Object_Declarations on the floor, so
5235          --  we need to insert it, in case it got expanded into useful code.
5236          --  Remove side effects from expression, which may be duplicated in
5237          --  subsequent checks (see Expand_Simple_Function_Return).
5238
5239          Insert_List_Before (N, Return_Object_Declarations (N));
5240          Remove_Side_Effects (Exp);
5241
5242          --  Build simple_return_statement that returns the expression directly
5243
5244          Return_Stmt := Make_Simple_Return_Statement (Loc, Expression => Exp);
5245          Result := Return_Stmt;
5246       end if;
5247
5248       --  Set the flag to prevent infinite recursion
5249
5250       Set_Comes_From_Extended_Return_Statement (Return_Stmt);
5251
5252       Rewrite (N, Result);
5253       Analyze (N);
5254    end Expand_N_Extended_Return_Statement;
5255
5256    ----------------------------
5257    -- Expand_N_Function_Call --
5258    ----------------------------
5259
5260    procedure Expand_N_Function_Call (N : Node_Id) is
5261    begin
5262       Expand_Call (N);
5263
5264       --  If the return value of a foreign compiled function is VAX Float, then
5265       --  expand the return (adjusts the location of the return value on
5266       --  Alpha/VMS, no-op everywhere else).
5267       --  Comes_From_Source intercepts recursive expansion.
5268
5269       if Vax_Float (Etype (N))
5270         and then Nkind (N) = N_Function_Call
5271         and then Present (Name (N))
5272         and then Present (Entity (Name (N)))
5273         and then Has_Foreign_Convention (Entity (Name (N)))
5274         and then Comes_From_Source (Parent (N))
5275       then
5276          Expand_Vax_Foreign_Return (N);
5277       end if;
5278    end Expand_N_Function_Call;
5279
5280    ---------------------------------------
5281    -- Expand_N_Procedure_Call_Statement --
5282    ---------------------------------------
5283
5284    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
5285    begin
5286       Expand_Call (N);
5287    end Expand_N_Procedure_Call_Statement;
5288
5289    --------------------------------------
5290    -- Expand_N_Simple_Return_Statement --
5291    --------------------------------------
5292
5293    procedure Expand_N_Simple_Return_Statement (N : Node_Id) is
5294    begin
5295       --  Defend against previous errors (i.e. the return statement calls a
5296       --  function that is not available in configurable runtime).
5297
5298       if Present (Expression (N))
5299         and then Nkind (Expression (N)) = N_Empty
5300       then
5301          return;
5302       end if;
5303
5304       --  Distinguish the function and non-function cases:
5305
5306       case Ekind (Return_Applies_To (Return_Statement_Entity (N))) is
5307
5308          when E_Function          |
5309               E_Generic_Function  =>
5310             Expand_Simple_Function_Return (N);
5311
5312          when E_Procedure         |
5313               E_Generic_Procedure |
5314               E_Entry             |
5315               E_Entry_Family      |
5316               E_Return_Statement =>
5317             Expand_Non_Function_Return (N);
5318
5319          when others =>
5320             raise Program_Error;
5321       end case;
5322
5323    exception
5324       when RE_Not_Available =>
5325          return;
5326    end Expand_N_Simple_Return_Statement;
5327
5328    ------------------------------
5329    -- Expand_N_Subprogram_Body --
5330    ------------------------------
5331
5332    --  Add poll call if ATC polling is enabled, unless the body will be inlined
5333    --  by the back-end.
5334
5335    --  Add dummy push/pop label nodes at start and end to clear any local
5336    --  exception indications if local-exception-to-goto optimization is active.
5337
5338    --  Add return statement if last statement in body is not a return statement
5339    --  (this makes things easier on Gigi which does not want to have to handle
5340    --  a missing return).
5341
5342    --  Add call to Activate_Tasks if body is a task activator
5343
5344    --  Deal with possible detection of infinite recursion
5345
5346    --  Eliminate body completely if convention stubbed
5347
5348    --  Encode entity names within body, since we will not need to reference
5349    --  these entities any longer in the front end.
5350
5351    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
5352
5353    --  Reset Pure indication if any parameter has root type System.Address
5354    --  or has any parameters of limited types, where limited means that the
5355    --  run-time view is limited (i.e. the full type is limited).
5356
5357    --  Wrap thread body
5358
5359    procedure Expand_N_Subprogram_Body (N : Node_Id) is
5360       Loc      : constant Source_Ptr := Sloc (N);
5361       H        : constant Node_Id    := Handled_Statement_Sequence (N);
5362       Body_Id  : Entity_Id;
5363       Except_H : Node_Id;
5364       L        : List_Id;
5365       Spec_Id  : Entity_Id;
5366
5367       procedure Add_Return (S : List_Id);
5368       --  Append a return statement to the statement sequence S if the last
5369       --  statement is not already a return or a goto statement. Note that
5370       --  the latter test is not critical, it does not matter if we add a few
5371       --  extra returns, since they get eliminated anyway later on.
5372
5373       ----------------
5374       -- Add_Return --
5375       ----------------
5376
5377       procedure Add_Return (S : List_Id) is
5378          Last_Stm : Node_Id;
5379          Loc      : Source_Ptr;
5380
5381       begin
5382          --  Get last statement, ignoring any Pop_xxx_Label nodes, which are
5383          --  not relevant in this context since they are not executable.
5384
5385          Last_Stm := Last (S);
5386          while Nkind (Last_Stm) in N_Pop_xxx_Label loop
5387             Prev (Last_Stm);
5388          end loop;
5389
5390          --  Now insert return unless last statement is a transfer
5391
5392          if not Is_Transfer (Last_Stm) then
5393
5394             --  The source location for the return is the end label of the
5395             --  procedure if present. Otherwise use the sloc of the last
5396             --  statement in the list. If the list comes from a generated
5397             --  exception handler and we are not debugging generated code,
5398             --  all the statements within the handler are made invisible
5399             --  to the debugger.
5400
5401             if Nkind (Parent (S)) = N_Exception_Handler
5402               and then not Comes_From_Source (Parent (S))
5403             then
5404                Loc := Sloc (Last_Stm);
5405             elsif Present (End_Label (H)) then
5406                Loc := Sloc (End_Label (H));
5407             else
5408                Loc := Sloc (Last_Stm);
5409             end if;
5410
5411             declare
5412                Rtn : constant Node_Id := Make_Simple_Return_Statement (Loc);
5413
5414             begin
5415                --  Append return statement, and set analyzed manually. We can't
5416                --  call Analyze on this return since the scope is wrong.
5417
5418                --  Note: it almost works to push the scope and then do the
5419                --  Analyze call, but something goes wrong in some weird cases
5420                --  and it is not worth worrying about ???
5421
5422                Append_To (S, Rtn);
5423                Set_Analyzed (Rtn);
5424
5425                --  Call _Postconditions procedure if appropriate. We need to
5426                --  do this explicitly because we did not analyze the generated
5427                --  return statement above, so the call did not get inserted.
5428
5429                if Ekind (Spec_Id) = E_Procedure
5430                  and then Has_Postconditions (Spec_Id)
5431                then
5432                   pragma Assert (Present (Postcondition_Proc (Spec_Id)));
5433                   Insert_Action (Rtn,
5434                     Make_Procedure_Call_Statement (Loc,
5435                       Name =>
5436                         New_Reference_To (Postcondition_Proc (Spec_Id), Loc)));
5437                end if;
5438             end;
5439          end if;
5440       end Add_Return;
5441
5442    --  Start of processing for Expand_N_Subprogram_Body
5443
5444    begin
5445       --  Set L to either the list of declarations if present, or to the list
5446       --  of statements if no declarations are present. This is used to insert
5447       --  new stuff at the start.
5448
5449       if Is_Non_Empty_List (Declarations (N)) then
5450          L := Declarations (N);
5451       else
5452          L := Statements (H);
5453       end if;
5454
5455       --  If local-exception-to-goto optimization active, insert dummy push
5456       --  statements at start, and dummy pop statements at end.
5457
5458       if (Debug_Flag_Dot_G
5459            or else Restriction_Active (No_Exception_Propagation))
5460         and then Is_Non_Empty_List (L)
5461       then
5462          declare
5463             FS  : constant Node_Id    := First (L);
5464             FL  : constant Source_Ptr := Sloc (FS);
5465             LS  : Node_Id;
5466             LL  : Source_Ptr;
5467
5468          begin
5469             --  LS points to either last statement, if statements are present
5470             --  or to the last declaration if there are no statements present.
5471             --  It is the node after which the pop's are generated.
5472
5473             if Is_Non_Empty_List (Statements (H)) then
5474                LS := Last (Statements (H));
5475             else
5476                LS := Last (L);
5477             end if;
5478
5479             LL := Sloc (LS);
5480
5481             Insert_List_Before_And_Analyze (FS, New_List (
5482               Make_Push_Constraint_Error_Label (FL),
5483               Make_Push_Program_Error_Label    (FL),
5484               Make_Push_Storage_Error_Label    (FL)));
5485
5486             Insert_List_After_And_Analyze (LS, New_List (
5487               Make_Pop_Constraint_Error_Label  (LL),
5488               Make_Pop_Program_Error_Label     (LL),
5489               Make_Pop_Storage_Error_Label     (LL)));
5490          end;
5491       end if;
5492
5493       --  Find entity for subprogram
5494
5495       Body_Id := Defining_Entity (N);
5496
5497       if Present (Corresponding_Spec (N)) then
5498          Spec_Id := Corresponding_Spec (N);
5499       else
5500          Spec_Id := Body_Id;
5501       end if;
5502
5503       --  Need poll on entry to subprogram if polling enabled. We only do this
5504       --  for non-empty subprograms, since it does not seem necessary to poll
5505       --  for a dummy null subprogram.
5506
5507       if Is_Non_Empty_List (L) then
5508
5509          --  Do not add a polling call if the subprogram is to be inlined by
5510          --  the back-end, to avoid repeated calls with multiple inlinings.
5511
5512          if Is_Inlined (Spec_Id)
5513            and then Front_End_Inlining
5514            and then Optimization_Level > 1
5515          then
5516             null;
5517          else
5518             Generate_Poll_Call (First (L));
5519          end if;
5520       end if;
5521
5522       --  If this is a Pure function which has any parameters whose root type
5523       --  is System.Address, reset the Pure indication, since it will likely
5524       --  cause incorrect code to be generated as the parameter is probably
5525       --  a pointer, and the fact that the same pointer is passed does not mean
5526       --  that the same value is being referenced.
5527
5528       --  Note that if the programmer gave an explicit Pure_Function pragma,
5529       --  then we believe the programmer, and leave the subprogram Pure.
5530
5531       --  This code should probably be at the freeze point, so that it happens
5532       --  even on a -gnatc (or more importantly -gnatt) compile, so that the
5533       --  semantic tree has Is_Pure set properly ???
5534
5535       if Is_Pure (Spec_Id)
5536         and then Is_Subprogram (Spec_Id)
5537         and then not Has_Pragma_Pure_Function (Spec_Id)
5538       then
5539          declare
5540             F : Entity_Id;
5541
5542          begin
5543             F := First_Formal (Spec_Id);
5544             while Present (F) loop
5545                if Is_Descendent_Of_Address (Etype (F))
5546
5547                  --  Note that this test is being made in the body of the
5548                  --  subprogram, not the spec, so we are testing the full
5549                  --  type for being limited here, as required.
5550
5551                  or else Is_Limited_Type (Etype (F))
5552                then
5553                   Set_Is_Pure (Spec_Id, False);
5554
5555                   if Spec_Id /= Body_Id then
5556                      Set_Is_Pure (Body_Id, False);
5557                   end if;
5558
5559                   exit;
5560                end if;
5561
5562                Next_Formal (F);
5563             end loop;
5564          end;
5565       end if;
5566
5567       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
5568
5569       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
5570          declare
5571             F : Entity_Id;
5572
5573          begin
5574             --  Loop through formals
5575
5576             F := First_Formal (Spec_Id);
5577             while Present (F) loop
5578                if Is_Scalar_Type (Etype (F))
5579                  and then Ekind (F) = E_Out_Parameter
5580                then
5581                   Check_Restriction (No_Default_Initialization, F);
5582
5583                   --  Insert the initialization. We turn off validity checks
5584                   --  for this assignment, since we do not want any check on
5585                   --  the initial value itself (which may well be invalid).
5586
5587                   Insert_Before_And_Analyze (First (L),
5588                     Make_Assignment_Statement (Loc,
5589                       Name       => New_Occurrence_Of (F, Loc),
5590                       Expression => Get_Simple_Init_Val (Etype (F), N)),
5591                     Suppress => Validity_Check);
5592                end if;
5593
5594                Next_Formal (F);
5595             end loop;
5596          end;
5597       end if;
5598
5599       --  Clear out statement list for stubbed procedure
5600
5601       if Present (Corresponding_Spec (N)) then
5602          Set_Elaboration_Flag (N, Spec_Id);
5603
5604          if Convention (Spec_Id) = Convention_Stubbed
5605            or else Is_Eliminated (Spec_Id)
5606          then
5607             Set_Declarations (N, Empty_List);
5608             Set_Handled_Statement_Sequence (N,
5609               Make_Handled_Sequence_Of_Statements (Loc,
5610                 Statements => New_List (Make_Null_Statement (Loc))));
5611             return;
5612          end if;
5613       end if;
5614
5615       --  Create a set of discriminals for the next protected subprogram body
5616
5617       if Is_List_Member (N)
5618         and then Present (Parent (List_Containing (N)))
5619         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
5620         and then Present (Next_Protected_Operation (N))
5621       then
5622          Set_Discriminals (Parent (Base_Type (Scope (Spec_Id))));
5623       end if;
5624
5625       --  Returns_By_Ref flag is normally set when the subprogram is frozen but
5626       --  subprograms with no specs are not frozen.
5627
5628       declare
5629          Typ  : constant Entity_Id := Etype (Spec_Id);
5630          Utyp : constant Entity_Id := Underlying_Type (Typ);
5631
5632       begin
5633          if not Acts_As_Spec (N)
5634            and then Nkind (Parent (Parent (Spec_Id))) /=
5635              N_Subprogram_Body_Stub
5636          then
5637             null;
5638
5639          elsif Is_Immutably_Limited_Type (Typ) then
5640             Set_Returns_By_Ref (Spec_Id);
5641
5642          elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
5643             Set_Returns_By_Ref (Spec_Id);
5644          end if;
5645       end;
5646
5647       --  For a procedure, we add a return for all possible syntactic ends of
5648       --  the subprogram.
5649
5650       if Ekind_In (Spec_Id, E_Procedure, E_Generic_Procedure) then
5651          Add_Return (Statements (H));
5652
5653          if Present (Exception_Handlers (H)) then
5654             Except_H := First_Non_Pragma (Exception_Handlers (H));
5655             while Present (Except_H) loop
5656                Add_Return (Statements (Except_H));
5657                Next_Non_Pragma (Except_H);
5658             end loop;
5659          end if;
5660
5661       --  For a function, we must deal with the case where there is at least
5662       --  one missing return. What we do is to wrap the entire body of the
5663       --  function in a block:
5664
5665       --    begin
5666       --      ...
5667       --    end;
5668
5669       --  becomes
5670
5671       --    begin
5672       --       begin
5673       --          ...
5674       --       end;
5675
5676       --       raise Program_Error;
5677       --    end;
5678
5679       --  This approach is necessary because the raise must be signalled to the
5680       --  caller, not handled by any local handler (RM 6.4(11)).
5681
5682       --  Note: we do not need to analyze the constructed sequence here, since
5683       --  it has no handler, and an attempt to analyze the handled statement
5684       --  sequence twice is risky in various ways (e.g. the issue of expanding
5685       --  cleanup actions twice).
5686
5687       elsif Has_Missing_Return (Spec_Id) then
5688          declare
5689             Hloc : constant Source_Ptr := Sloc (H);
5690             Blok : constant Node_Id    :=
5691                      Make_Block_Statement (Hloc,
5692                        Handled_Statement_Sequence => H);
5693             Rais : constant Node_Id    :=
5694                      Make_Raise_Program_Error (Hloc,
5695                        Reason => PE_Missing_Return);
5696
5697          begin
5698             Set_Handled_Statement_Sequence (N,
5699               Make_Handled_Sequence_Of_Statements (Hloc,
5700                 Statements => New_List (Blok, Rais)));
5701
5702             Push_Scope (Spec_Id);
5703             Analyze (Blok);
5704             Analyze (Rais);
5705             Pop_Scope;
5706          end;
5707       end if;
5708
5709       --  If subprogram contains a parameterless recursive call, then we may
5710       --  have an infinite recursion, so see if we can generate code to check
5711       --  for this possibility if storage checks are not suppressed.
5712
5713       if Ekind (Spec_Id) = E_Procedure
5714         and then Has_Recursive_Call (Spec_Id)
5715         and then not Storage_Checks_Suppressed (Spec_Id)
5716       then
5717          Detect_Infinite_Recursion (N, Spec_Id);
5718       end if;
5719
5720       --  Set to encode entity names in package body before gigi is called
5721
5722       Qualify_Entity_Names (N);
5723    end Expand_N_Subprogram_Body;
5724
5725    -----------------------------------
5726    -- Expand_N_Subprogram_Body_Stub --
5727    -----------------------------------
5728
5729    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
5730    begin
5731       if Present (Corresponding_Body (N)) then
5732          Expand_N_Subprogram_Body (
5733            Unit_Declaration_Node (Corresponding_Body (N)));
5734       end if;
5735    end Expand_N_Subprogram_Body_Stub;
5736
5737    -------------------------------------
5738    -- Expand_N_Subprogram_Declaration --
5739    -------------------------------------
5740
5741    --  If the declaration appears within a protected body, it is a private
5742    --  operation of the protected type. We must create the corresponding
5743    --  protected subprogram an associated formals. For a normal protected
5744    --  operation, this is done when expanding the protected type declaration.
5745
5746    --  If the declaration is for a null procedure, emit null body
5747
5748    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
5749       Loc       : constant Source_Ptr := Sloc (N);
5750       Subp      : constant Entity_Id  := Defining_Entity (N);
5751       Scop      : constant Entity_Id  := Scope (Subp);
5752       Prot_Decl : Node_Id;
5753       Prot_Bod  : Node_Id;
5754       Prot_Id   : Entity_Id;
5755
5756    begin
5757       --  In SPARK, subprogram declarations are only allowed in package
5758       --  specifications.
5759
5760       if Nkind (Parent (N)) /= N_Package_Specification then
5761          if Nkind (Parent (N)) = N_Compilation_Unit then
5762             Check_SPARK_Restriction
5763               ("subprogram declaration is not a library item", N);
5764
5765          elsif Present (Next (N))
5766            and then Nkind (Next (N)) = N_Pragma
5767            and then Get_Pragma_Id (Pragma_Name (Next (N))) = Pragma_Import
5768          then
5769             --  In SPARK, subprogram declarations are also permitted in
5770             --  declarative parts when immediately followed by a corresponding
5771             --  pragma Import. We only check here that there is some pragma
5772             --  Import.
5773
5774             null;
5775          else
5776             Check_SPARK_Restriction
5777               ("subprogram declaration is not allowed here", N);
5778          end if;
5779       end if;
5780
5781       --  Deal with case of protected subprogram. Do not generate protected
5782       --  operation if operation is flagged as eliminated.
5783
5784       if Is_List_Member (N)
5785         and then Present (Parent (List_Containing (N)))
5786         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
5787         and then Is_Protected_Type (Scop)
5788       then
5789          if No (Protected_Body_Subprogram (Subp))
5790            and then not Is_Eliminated (Subp)
5791          then
5792             Prot_Decl :=
5793               Make_Subprogram_Declaration (Loc,
5794                 Specification =>
5795                   Build_Protected_Sub_Specification
5796                     (N, Scop, Unprotected_Mode));
5797
5798             --  The protected subprogram is declared outside of the protected
5799             --  body. Given that the body has frozen all entities so far, we
5800             --  analyze the subprogram and perform freezing actions explicitly.
5801             --  including the generation of an explicit freeze node, to ensure
5802             --  that gigi has the proper order of elaboration.
5803             --  If the body is a subunit, the insertion point is before the
5804             --  stub in the parent.
5805
5806             Prot_Bod := Parent (List_Containing (N));
5807
5808             if Nkind (Parent (Prot_Bod)) = N_Subunit then
5809                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
5810             end if;
5811
5812             Insert_Before (Prot_Bod, Prot_Decl);
5813             Prot_Id := Defining_Unit_Name (Specification (Prot_Decl));
5814             Set_Has_Delayed_Freeze (Prot_Id);
5815
5816             Push_Scope (Scope (Scop));
5817             Analyze (Prot_Decl);
5818             Freeze_Before (N, Prot_Id);
5819             Set_Protected_Body_Subprogram (Subp, Prot_Id);
5820
5821             --  Create protected operation as well. Even though the operation
5822             --  is only accessible within the body, it is possible to make it
5823             --  available outside of the protected object by using 'Access to
5824             --  provide a callback, so build protected version in all cases.
5825
5826             Prot_Decl :=
5827               Make_Subprogram_Declaration (Loc,
5828                 Specification =>
5829                   Build_Protected_Sub_Specification (N, Scop, Protected_Mode));
5830             Insert_Before (Prot_Bod, Prot_Decl);
5831             Analyze (Prot_Decl);
5832
5833             Pop_Scope;
5834          end if;
5835
5836       --  Ada 2005 (AI-348): Generate body for a null procedure.
5837       --  In most cases this is superfluous because calls to it
5838       --  will be automatically inlined, but we definitely need
5839       --  the body if preconditions for the procedure are present.
5840
5841       elsif Nkind (Specification (N)) = N_Procedure_Specification
5842         and then Null_Present (Specification (N))
5843       then
5844          declare
5845             Bod : constant Node_Id := Body_To_Inline (N);
5846
5847          begin
5848             Set_Has_Completion (Subp, False);
5849             Append_Freeze_Action (Subp, Bod);
5850
5851             --  The body now contains raise statements, so calls to it will
5852             --  not be inlined.
5853
5854             Set_Is_Inlined (Subp, False);
5855          end;
5856       end if;
5857    end Expand_N_Subprogram_Declaration;
5858
5859    --------------------------------
5860    -- Expand_Non_Function_Return --
5861    --------------------------------
5862
5863    procedure Expand_Non_Function_Return (N : Node_Id) is
5864       pragma Assert (No (Expression (N)));
5865
5866       Loc         : constant Source_Ptr := Sloc (N);
5867       Scope_Id    : Entity_Id :=
5868                       Return_Applies_To (Return_Statement_Entity (N));
5869       Kind        : constant Entity_Kind := Ekind (Scope_Id);
5870       Call        : Node_Id;
5871       Acc_Stat    : Node_Id;
5872       Goto_Stat   : Node_Id;
5873       Lab_Node    : Node_Id;
5874
5875    begin
5876       --  Call _Postconditions procedure if procedure with active
5877       --  postconditions. Here, we use the Postcondition_Proc attribute, which
5878       --  is needed for implicitly-generated returns. Functions never
5879       --  have implicitly-generated returns, and there's no room for
5880       --  Postcondition_Proc in E_Function, so we look up the identifier
5881       --  Name_uPostconditions for function returns (see
5882       --  Expand_Simple_Function_Return).
5883
5884       if Ekind (Scope_Id) = E_Procedure
5885         and then Has_Postconditions (Scope_Id)
5886       then
5887          pragma Assert (Present (Postcondition_Proc (Scope_Id)));
5888          Insert_Action (N,
5889            Make_Procedure_Call_Statement (Loc,
5890              Name => New_Reference_To (Postcondition_Proc (Scope_Id), Loc)));
5891       end if;
5892
5893       --  If it is a return from a procedure do no extra steps
5894
5895       if Kind = E_Procedure or else Kind = E_Generic_Procedure then
5896          return;
5897
5898       --  If it is a nested return within an extended one, replace it with a
5899       --  return of the previously declared return object.
5900
5901       elsif Kind = E_Return_Statement then
5902          Rewrite (N,
5903            Make_Simple_Return_Statement (Loc,
5904              Expression =>
5905                New_Occurrence_Of (First_Entity (Scope_Id), Loc)));
5906          Set_Comes_From_Extended_Return_Statement (N);
5907          Set_Return_Statement_Entity (N, Scope_Id);
5908          Expand_Simple_Function_Return (N);
5909          return;
5910       end if;
5911
5912       pragma Assert (Is_Entry (Scope_Id));
5913
5914       --  Look at the enclosing block to see whether the return is from an
5915       --  accept statement or an entry body.
5916
5917       for J in reverse 0 .. Scope_Stack.Last loop
5918          Scope_Id := Scope_Stack.Table (J).Entity;
5919          exit when Is_Concurrent_Type (Scope_Id);
5920       end loop;
5921
5922       --  If it is a return from accept statement it is expanded as call to
5923       --  RTS Complete_Rendezvous and a goto to the end of the accept body.
5924
5925       --  (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
5926       --  Expand_N_Accept_Alternative in exp_ch9.adb)
5927
5928       if Is_Task_Type (Scope_Id) then
5929
5930          Call :=
5931            Make_Procedure_Call_Statement (Loc,
5932              Name => New_Reference_To (RTE (RE_Complete_Rendezvous), Loc));
5933          Insert_Before (N, Call);
5934          --  why not insert actions here???
5935          Analyze (Call);
5936
5937          Acc_Stat := Parent (N);
5938          while Nkind (Acc_Stat) /= N_Accept_Statement loop
5939             Acc_Stat := Parent (Acc_Stat);
5940          end loop;
5941
5942          Lab_Node := Last (Statements
5943            (Handled_Statement_Sequence (Acc_Stat)));
5944
5945          Goto_Stat := Make_Goto_Statement (Loc,
5946            Name => New_Occurrence_Of
5947              (Entity (Identifier (Lab_Node)), Loc));
5948
5949          Set_Analyzed (Goto_Stat);
5950
5951          Rewrite (N, Goto_Stat);
5952          Analyze (N);
5953
5954       --  If it is a return from an entry body, put a Complete_Entry_Body call
5955       --  in front of the return.
5956
5957       elsif Is_Protected_Type (Scope_Id) then
5958          Call :=
5959            Make_Procedure_Call_Statement (Loc,
5960              Name =>
5961                New_Reference_To (RTE (RE_Complete_Entry_Body), Loc),
5962              Parameter_Associations => New_List (
5963                Make_Attribute_Reference (Loc,
5964                  Prefix         =>
5965                    New_Reference_To
5966                      (Find_Protection_Object (Current_Scope), Loc),
5967                  Attribute_Name => Name_Unchecked_Access)));
5968
5969          Insert_Before (N, Call);
5970          Analyze (Call);
5971       end if;
5972    end Expand_Non_Function_Return;
5973
5974    ---------------------------------------
5975    -- Expand_Protected_Object_Reference --
5976    ---------------------------------------
5977
5978    function Expand_Protected_Object_Reference
5979      (N    : Node_Id;
5980       Scop : Entity_Id) return Node_Id
5981    is
5982       Loc   : constant Source_Ptr := Sloc (N);
5983       Corr  : Entity_Id;
5984       Rec   : Node_Id;
5985       Param : Entity_Id;
5986       Proc  : Entity_Id;
5987
5988    begin
5989       Rec := Make_Identifier (Loc, Name_uObject);
5990       Set_Etype (Rec, Corresponding_Record_Type (Scop));
5991
5992       --  Find enclosing protected operation, and retrieve its first parameter,
5993       --  which denotes the enclosing protected object. If the enclosing
5994       --  operation is an entry, we are immediately within the protected body,
5995       --  and we can retrieve the object from the service entries procedure. A
5996       --  barrier function has the same signature as an entry. A barrier
5997       --  function is compiled within the protected object, but unlike
5998       --  protected operations its never needs locks, so that its protected
5999       --  body subprogram points to itself.
6000
6001       Proc := Current_Scope;
6002       while Present (Proc)
6003         and then Scope (Proc) /= Scop
6004       loop
6005          Proc := Scope (Proc);
6006       end loop;
6007
6008       Corr := Protected_Body_Subprogram (Proc);
6009
6010       if No (Corr) then
6011
6012          --  Previous error left expansion incomplete.
6013          --  Nothing to do on this call.
6014
6015          return Empty;
6016       end if;
6017
6018       Param :=
6019         Defining_Identifier
6020           (First (Parameter_Specifications (Parent (Corr))));
6021
6022       if Is_Subprogram (Proc)
6023         and then Proc /= Corr
6024       then
6025          --  Protected function or procedure
6026
6027          Set_Entity (Rec, Param);
6028
6029          --  Rec is a reference to an entity which will not be in scope when
6030          --  the call is reanalyzed, and needs no further analysis.
6031
6032          Set_Analyzed (Rec);
6033
6034       else
6035          --  Entry or barrier function for entry body. The first parameter of
6036          --  the entry body procedure is pointer to the object. We create a
6037          --  local variable of the proper type, duplicating what is done to
6038          --  define _object later on.
6039
6040          declare
6041             Decls   : List_Id;
6042             Obj_Ptr : constant Entity_Id :=  Make_Temporary (Loc, 'T');
6043
6044          begin
6045             Decls := New_List (
6046               Make_Full_Type_Declaration (Loc,
6047                 Defining_Identifier => Obj_Ptr,
6048                   Type_Definition   =>
6049                      Make_Access_To_Object_Definition (Loc,
6050                        Subtype_Indication =>
6051                          New_Reference_To
6052                            (Corresponding_Record_Type (Scop), Loc))));
6053
6054             Insert_Actions (N, Decls);
6055             Freeze_Before (N, Obj_Ptr);
6056
6057             Rec :=
6058               Make_Explicit_Dereference (Loc,
6059                 Prefix =>
6060                   Unchecked_Convert_To (Obj_Ptr,
6061                     New_Occurrence_Of (Param, Loc)));
6062
6063             --  Analyze new actual. Other actuals in calls are already analyzed
6064             --  and the list of actuals is not reanalyzed after rewriting.
6065
6066             Set_Parent (Rec, N);
6067             Analyze (Rec);
6068          end;
6069       end if;
6070
6071       return Rec;
6072    end Expand_Protected_Object_Reference;
6073
6074    --------------------------------------
6075    -- Expand_Protected_Subprogram_Call --
6076    --------------------------------------
6077
6078    procedure Expand_Protected_Subprogram_Call
6079      (N    : Node_Id;
6080       Subp : Entity_Id;
6081       Scop : Entity_Id)
6082    is
6083       Rec   : Node_Id;
6084
6085    begin
6086       --  If the protected object is not an enclosing scope, this is an
6087       --  inter-object function call. Inter-object procedure calls are expanded
6088       --  by Exp_Ch9.Build_Simple_Entry_Call. The call is intra-object only if
6089       --  the subprogram being called is in the protected body being compiled,
6090       --  and if the protected object in the call is statically the enclosing
6091       --  type. The object may be an component of some other data structure, in
6092       --  which case this must be handled as an inter-object call.
6093
6094       if not In_Open_Scopes (Scop)
6095         or else not Is_Entity_Name (Name (N))
6096       then
6097          if Nkind (Name (N)) = N_Selected_Component then
6098             Rec := Prefix (Name (N));
6099
6100          else
6101             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
6102             Rec := Prefix (Prefix (Name (N)));
6103          end if;
6104
6105          Build_Protected_Subprogram_Call (N,
6106            Name     => New_Occurrence_Of (Subp, Sloc (N)),
6107            Rec      => Convert_Concurrent (Rec, Etype (Rec)),
6108            External => True);
6109
6110       else
6111          Rec := Expand_Protected_Object_Reference (N, Scop);
6112
6113          if No (Rec) then
6114             return;
6115          end if;
6116
6117          Build_Protected_Subprogram_Call (N,
6118            Name     => Name (N),
6119            Rec      => Rec,
6120            External => False);
6121
6122       end if;
6123
6124       --  If it is a function call it can appear in elaboration code and
6125       --  the called entity must be frozen here.
6126
6127       if Ekind (Subp) = E_Function then
6128          Freeze_Expression (Name (N));
6129       end if;
6130
6131       --  Analyze and resolve the new call. The actuals have already been
6132       --  resolved, but expansion of a function call will add extra actuals
6133       --  if needed. Analysis of a procedure call already includes resolution.
6134
6135       Analyze (N);
6136
6137       if Ekind (Subp) = E_Function then
6138          Resolve (N, Etype (Subp));
6139       end if;
6140    end Expand_Protected_Subprogram_Call;
6141
6142    -----------------------------------
6143    -- Expand_Simple_Function_Return --
6144    -----------------------------------
6145
6146    --  The "simple" comes from the syntax rule simple_return_statement.
6147    --  The semantics are not at all simple!
6148
6149    procedure Expand_Simple_Function_Return (N : Node_Id) is
6150       Loc : constant Source_Ptr := Sloc (N);
6151
6152       Scope_Id : constant Entity_Id :=
6153                    Return_Applies_To (Return_Statement_Entity (N));
6154       --  The function we are returning from
6155
6156       R_Type : constant Entity_Id := Etype (Scope_Id);
6157       --  The result type of the function
6158
6159       Utyp : constant Entity_Id := Underlying_Type (R_Type);
6160
6161       Exp : constant Node_Id := Expression (N);
6162       pragma Assert (Present (Exp));
6163
6164       Exptyp : constant Entity_Id := Etype (Exp);
6165       --  The type of the expression (not necessarily the same as R_Type)
6166
6167       Subtype_Ind : Node_Id;
6168       --  If the result type of the function is class-wide and the
6169       --  expression has a specific type, then we use the expression's
6170       --  type as the type of the return object. In cases where the
6171       --  expression is an aggregate that is built in place, this avoids
6172       --  the need for an expensive conversion of the return object to
6173       --  the specific type on assignments to the individual components.
6174
6175    begin
6176       if Is_Class_Wide_Type (R_Type)
6177         and then not Is_Class_Wide_Type (Etype (Exp))
6178       then
6179          Subtype_Ind := New_Occurrence_Of (Etype (Exp), Loc);
6180       else
6181          Subtype_Ind := New_Occurrence_Of (R_Type, Loc);
6182       end if;
6183
6184       --  For the case of a simple return that does not come from an extended
6185       --  return, in the case of Ada 2005 where we are returning a limited
6186       --  type, we rewrite "return <expression>;" to be:
6187
6188       --    return _anon_ : <return_subtype> := <expression>
6189
6190       --  The expansion produced by Expand_N_Extended_Return_Statement will
6191       --  contain simple return statements (for example, a block containing
6192       --  simple return of the return object), which brings us back here with
6193       --  Comes_From_Extended_Return_Statement set. The reason for the barrier
6194       --  checking for a simple return that does not come from an extended
6195       --  return is to avoid this infinite recursion.
6196
6197       --  The reason for this design is that for Ada 2005 limited returns, we
6198       --  need to reify the return object, so we can build it "in place", and
6199       --  we need a block statement to hang finalization and tasking stuff.
6200
6201       --  ??? In order to avoid disruption, we avoid translating to extended
6202       --  return except in the cases where we really need to (Ada 2005 for
6203       --  inherently limited). We might prefer to do this translation in all
6204       --  cases (except perhaps for the case of Ada 95 inherently limited),
6205       --  in order to fully exercise the Expand_N_Extended_Return_Statement
6206       --  code. This would also allow us to do the build-in-place optimization
6207       --  for efficiency even in cases where it is semantically not required.
6208
6209       --  As before, we check the type of the return expression rather than the
6210       --  return type of the function, because the latter may be a limited
6211       --  class-wide interface type, which is not a limited type, even though
6212       --  the type of the expression may be.
6213
6214       if not Comes_From_Extended_Return_Statement (N)
6215         and then Is_Immutably_Limited_Type (Etype (Expression (N)))
6216         and then Ada_Version >= Ada_2005
6217         and then not Debug_Flag_Dot_L
6218       then
6219          declare
6220             Return_Object_Entity : constant Entity_Id :=
6221                                      Make_Temporary (Loc, 'R', Exp);
6222             Obj_Decl : constant Node_Id :=
6223                          Make_Object_Declaration (Loc,
6224                            Defining_Identifier => Return_Object_Entity,
6225                            Object_Definition   => Subtype_Ind,
6226                            Expression          => Exp);
6227
6228             Ext : constant Node_Id := Make_Extended_Return_Statement (Loc,
6229                     Return_Object_Declarations => New_List (Obj_Decl));
6230             --  Do not perform this high-level optimization if the result type
6231             --  is an interface because the "this" pointer must be displaced.
6232
6233          begin
6234             Rewrite (N, Ext);
6235             Analyze (N);
6236             return;
6237          end;
6238       end if;
6239
6240       --  Here we have a simple return statement that is part of the expansion
6241       --  of an extended return statement (either written by the user, or
6242       --  generated by the above code).
6243
6244       --  Always normalize C/Fortran boolean result. This is not always needed,
6245       --  but it seems a good idea to minimize the passing around of non-
6246       --  normalized values, and in any case this handles the processing of
6247       --  barrier functions for protected types, which turn the condition into
6248       --  a return statement.
6249
6250       if Is_Boolean_Type (Exptyp)
6251         and then Nonzero_Is_True (Exptyp)
6252       then
6253          Adjust_Condition (Exp);
6254          Adjust_Result_Type (Exp, Exptyp);
6255       end if;
6256
6257       --  Do validity check if enabled for returns
6258
6259       if Validity_Checks_On
6260         and then Validity_Check_Returns
6261       then
6262          Ensure_Valid (Exp);
6263       end if;
6264
6265       --  Check the result expression of a scalar function against the subtype
6266       --  of the function by inserting a conversion. This conversion must
6267       --  eventually be performed for other classes of types, but for now it's
6268       --  only done for scalars.
6269       --  ???
6270
6271       if Is_Scalar_Type (Exptyp) then
6272          Rewrite (Exp, Convert_To (R_Type, Exp));
6273
6274          --  The expression is resolved to ensure that the conversion gets
6275          --  expanded to generate a possible constraint check.
6276
6277          Analyze_And_Resolve (Exp, R_Type);
6278       end if;
6279
6280       --  Deal with returning variable length objects and controlled types
6281
6282       --  Nothing to do if we are returning by reference, or this is not a
6283       --  type that requires special processing (indicated by the fact that
6284       --  it requires a cleanup scope for the secondary stack case).
6285
6286       if Is_Immutably_Limited_Type (Exptyp)
6287         or else Is_Limited_Interface (Exptyp)
6288       then
6289          null;
6290
6291       elsif not Requires_Transient_Scope (R_Type) then
6292
6293          --  Mutable records with no variable length components are not
6294          --  returned on the sec-stack, so we need to make sure that the
6295          --  backend will only copy back the size of the actual value, and not
6296          --  the maximum size. We create an actual subtype for this purpose.
6297
6298          declare
6299             Ubt  : constant Entity_Id := Underlying_Type (Base_Type (Exptyp));
6300             Decl : Node_Id;
6301             Ent  : Entity_Id;
6302          begin
6303             if Has_Discriminants (Ubt)
6304               and then not Is_Constrained (Ubt)
6305               and then not Has_Unchecked_Union (Ubt)
6306             then
6307                Decl := Build_Actual_Subtype (Ubt, Exp);
6308                Ent := Defining_Identifier (Decl);
6309                Insert_Action (Exp, Decl);
6310                Rewrite (Exp, Unchecked_Convert_To (Ent, Exp));
6311                Analyze_And_Resolve (Exp);
6312             end if;
6313          end;
6314
6315       --  Here if secondary stack is used
6316
6317       else
6318          --  Make sure that no surrounding block will reclaim the secondary
6319          --  stack on which we are going to put the result. Not only may this
6320          --  introduce secondary stack leaks but worse, if the reclamation is
6321          --  done too early, then the result we are returning may get
6322          --  clobbered.
6323
6324          declare
6325             S : Entity_Id;
6326          begin
6327             S := Current_Scope;
6328             while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
6329                Set_Sec_Stack_Needed_For_Return (S, True);
6330                S := Enclosing_Dynamic_Scope (S);
6331             end loop;
6332          end;
6333
6334          --  Optimize the case where the result is a function call. In this
6335          --  case either the result is already on the secondary stack, or is
6336          --  already being returned with the stack pointer depressed and no
6337          --  further processing is required except to set the By_Ref flag to
6338          --  ensure that gigi does not attempt an extra unnecessary copy.
6339          --  (actually not just unnecessary but harmfully wrong in the case
6340          --  of a controlled type, where gigi does not know how to do a copy).
6341          --  To make up for a gcc 2.8.1 deficiency (???), we perform
6342          --  the copy for array types if the constrained status of the
6343          --  target type is different from that of the expression.
6344
6345          if Requires_Transient_Scope (Exptyp)
6346            and then
6347               (not Is_Array_Type (Exptyp)
6348                 or else Is_Constrained (Exptyp) = Is_Constrained (R_Type)
6349                 or else CW_Or_Has_Controlled_Part (Utyp))
6350            and then Nkind (Exp) = N_Function_Call
6351          then
6352             Set_By_Ref (N);
6353
6354             --  Remove side effects from the expression now so that other parts
6355             --  of the expander do not have to reanalyze this node without this
6356             --  optimization
6357
6358             Rewrite (Exp, Duplicate_Subexpr_No_Checks (Exp));
6359
6360          --  For controlled types, do the allocation on the secondary stack
6361          --  manually in order to call adjust at the right time:
6362
6363          --    type Anon1 is access R_Type;
6364          --    for Anon1'Storage_pool use ss_pool;
6365          --    Anon2 : anon1 := new R_Type'(expr);
6366          --    return Anon2.all;
6367
6368          --  We do the same for classwide types that are not potentially
6369          --  controlled (by the virtue of restriction No_Finalization) because
6370          --  gigi is not able to properly allocate class-wide types.
6371
6372          elsif CW_Or_Has_Controlled_Part (Utyp) then
6373             declare
6374                Loc        : constant Source_Ptr := Sloc (N);
6375                Acc_Typ    : constant Entity_Id := Make_Temporary (Loc, 'A');
6376                Alloc_Node : Node_Id;
6377                Temp       : Entity_Id;
6378
6379             begin
6380                Set_Ekind (Acc_Typ, E_Access_Type);
6381
6382                Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
6383
6384                --  This is an allocator for the secondary stack, and it's fine
6385                --  to have Comes_From_Source set False on it, as gigi knows not
6386                --  to flag it as a violation of No_Implicit_Heap_Allocations.
6387
6388                Alloc_Node :=
6389                  Make_Allocator (Loc,
6390                    Expression =>
6391                      Make_Qualified_Expression (Loc,
6392                        Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
6393                        Expression   => Relocate_Node (Exp)));
6394
6395                --  We do not want discriminant checks on the declaration,
6396                --  given that it gets its value from the allocator.
6397
6398                Set_No_Initialization (Alloc_Node);
6399
6400                Temp := Make_Temporary (Loc, 'R', Alloc_Node);
6401
6402                Insert_List_Before_And_Analyze (N, New_List (
6403                  Make_Full_Type_Declaration (Loc,
6404                    Defining_Identifier => Acc_Typ,
6405                    Type_Definition     =>
6406                      Make_Access_To_Object_Definition (Loc,
6407                        Subtype_Indication => Subtype_Ind)),
6408
6409                  Make_Object_Declaration (Loc,
6410                    Defining_Identifier => Temp,
6411                    Object_Definition   => New_Reference_To (Acc_Typ, Loc),
6412                    Expression          => Alloc_Node)));
6413
6414                Rewrite (Exp,
6415                  Make_Explicit_Dereference (Loc,
6416                  Prefix => New_Reference_To (Temp, Loc)));
6417
6418                Analyze_And_Resolve (Exp, R_Type);
6419             end;
6420
6421          --  Otherwise use the gigi mechanism to allocate result on the
6422          --  secondary stack.
6423
6424          else
6425             Check_Restriction (No_Secondary_Stack, N);
6426             Set_Storage_Pool (N, RTE (RE_SS_Pool));
6427
6428             --  If we are generating code for the VM do not use
6429             --  SS_Allocate since everything is heap-allocated anyway.
6430
6431             if VM_Target = No_VM then
6432                Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
6433             end if;
6434          end if;
6435       end if;
6436
6437       --  Implement the rules of 6.5(8-10), which require a tag check in the
6438       --  case of a limited tagged return type, and tag reassignment for
6439       --  nonlimited tagged results. These actions are needed when the return
6440       --  type is a specific tagged type and the result expression is a
6441       --  conversion or a formal parameter, because in that case the tag of the
6442       --  expression might differ from the tag of the specific result type.
6443
6444       if Is_Tagged_Type (Utyp)
6445         and then not Is_Class_Wide_Type (Utyp)
6446         and then (Nkind_In (Exp, N_Type_Conversion,
6447                                  N_Unchecked_Type_Conversion)
6448                     or else (Is_Entity_Name (Exp)
6449                                and then Ekind (Entity (Exp)) in Formal_Kind))
6450       then
6451          --  When the return type is limited, perform a check that the
6452          --  tag of the result is the same as the tag of the return type.
6453
6454          if Is_Limited_Type (R_Type) then
6455             Insert_Action (Exp,
6456               Make_Raise_Constraint_Error (Loc,
6457                 Condition =>
6458                   Make_Op_Ne (Loc,
6459                     Left_Opnd  =>
6460                       Make_Selected_Component (Loc,
6461                         Prefix        => Duplicate_Subexpr (Exp),
6462                         Selector_Name => Make_Identifier (Loc, Name_uTag)),
6463                     Right_Opnd =>
6464                       Make_Attribute_Reference (Loc,
6465                         Prefix         =>
6466                           New_Occurrence_Of (Base_Type (Utyp), Loc),
6467                         Attribute_Name => Name_Tag)),
6468                 Reason    => CE_Tag_Check_Failed));
6469
6470          --  If the result type is a specific nonlimited tagged type, then we
6471          --  have to ensure that the tag of the result is that of the result
6472          --  type. This is handled by making a copy of the expression in the
6473          --  case where it might have a different tag, namely when the
6474          --  expression is a conversion or a formal parameter. We create a new
6475          --  object of the result type and initialize it from the expression,
6476          --  which will implicitly force the tag to be set appropriately.
6477
6478          else
6479             declare
6480                ExpR       : constant Node_Id   := Relocate_Node (Exp);
6481                Result_Id  : constant Entity_Id :=
6482                               Make_Temporary (Loc, 'R', ExpR);
6483                Result_Exp : constant Node_Id   :=
6484                               New_Reference_To (Result_Id, Loc);
6485                Result_Obj : constant Node_Id   :=
6486                               Make_Object_Declaration (Loc,
6487                                 Defining_Identifier => Result_Id,
6488                                 Object_Definition   =>
6489                                   New_Reference_To (R_Type, Loc),
6490                                 Constant_Present    => True,
6491                                 Expression          => ExpR);
6492
6493             begin
6494                Set_Assignment_OK (Result_Obj);
6495                Insert_Action (Exp, Result_Obj);
6496
6497                Rewrite (Exp, Result_Exp);
6498                Analyze_And_Resolve (Exp, R_Type);
6499             end;
6500          end if;
6501
6502       --  Ada 2005 (AI-344): If the result type is class-wide, then insert
6503       --  a check that the level of the return expression's underlying type
6504       --  is not deeper than the level of the master enclosing the function.
6505       --  Always generate the check when the type of the return expression
6506       --  is class-wide, when it's a type conversion, or when it's a formal
6507       --  parameter. Otherwise, suppress the check in the case where the
6508       --  return expression has a specific type whose level is known not to
6509       --  be statically deeper than the function's result type.
6510
6511       --  Note: accessibility check is skipped in the VM case, since there
6512       --  does not seem to be any practical way to implement this check.
6513
6514       elsif Ada_Version >= Ada_2005
6515         and then Tagged_Type_Expansion
6516         and then Is_Class_Wide_Type (R_Type)
6517         and then not Scope_Suppress (Accessibility_Check)
6518         and then
6519           (Is_Class_Wide_Type (Etype (Exp))
6520             or else Nkind_In (Exp, N_Type_Conversion,
6521                                    N_Unchecked_Type_Conversion)
6522             or else (Is_Entity_Name (Exp)
6523                       and then Ekind (Entity (Exp)) in Formal_Kind)
6524             or else Scope_Depth (Enclosing_Dynamic_Scope (Etype (Exp))) >
6525                       Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))
6526       then
6527          declare
6528             Tag_Node : Node_Id;
6529
6530          begin
6531             --  Ada 2005 (AI-251): In class-wide interface objects we displace
6532             --  "this" to reference the base of the object. This is required to
6533             --  get access to the TSD of the object.
6534
6535             if Is_Class_Wide_Type (Etype (Exp))
6536               and then Is_Interface (Etype (Exp))
6537               and then Nkind (Exp) = N_Explicit_Dereference
6538             then
6539                Tag_Node :=
6540                  Make_Explicit_Dereference (Loc,
6541                    Prefix =>
6542                      Unchecked_Convert_To (RTE (RE_Tag_Ptr),
6543                        Make_Function_Call (Loc,
6544                          Name                   =>
6545                            New_Reference_To (RTE (RE_Base_Address), Loc),
6546                          Parameter_Associations => New_List (
6547                            Unchecked_Convert_To (RTE (RE_Address),
6548                              Duplicate_Subexpr (Prefix (Exp)))))));
6549             else
6550                Tag_Node :=
6551                  Make_Attribute_Reference (Loc,
6552                    Prefix         => Duplicate_Subexpr (Exp),
6553                    Attribute_Name => Name_Tag);
6554             end if;
6555
6556             Insert_Action (Exp,
6557               Make_Raise_Program_Error (Loc,
6558                 Condition =>
6559                   Make_Op_Gt (Loc,
6560                     Left_Opnd  => Build_Get_Access_Level (Loc, Tag_Node),
6561                     Right_Opnd =>
6562                       Make_Integer_Literal (Loc,
6563                         Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))),
6564                 Reason => PE_Accessibility_Check_Failed));
6565          end;
6566
6567       --  AI05-0073: If function has a controlling access result, check that
6568       --  the tag of the return value, if it is not null, matches designated
6569       --  type of return type.
6570       --  The return expression is referenced twice in the code below, so
6571       --  it must be made free of side effects. Given that different compilers
6572       --  may evaluate these parameters in different order, both occurrences
6573       --  perform a copy.
6574
6575       elsif Ekind (R_Type) = E_Anonymous_Access_Type
6576         and then Has_Controlling_Result (Scope_Id)
6577       then
6578          Insert_Action (N,
6579            Make_Raise_Constraint_Error (Loc,
6580              Condition =>
6581                Make_And_Then (Loc,
6582                  Left_Opnd  =>
6583                    Make_Op_Ne (Loc,
6584                      Left_Opnd  => Duplicate_Subexpr (Exp),
6585                      Right_Opnd => Make_Null (Loc)),
6586                  Right_Opnd => Make_Op_Ne (Loc,
6587                    Left_Opnd  =>
6588                      Make_Selected_Component (Loc,
6589                        Prefix        => Duplicate_Subexpr (Exp),
6590                        Selector_Name => Make_Identifier (Loc, Name_uTag)),
6591                    Right_Opnd =>
6592                      Make_Attribute_Reference (Loc,
6593                        Prefix         =>
6594                          New_Occurrence_Of (Designated_Type (R_Type), Loc),
6595                        Attribute_Name => Name_Tag))),
6596              Reason    => CE_Tag_Check_Failed),
6597              Suppress  => All_Checks);
6598       end if;
6599
6600       --  If we are returning an object that may not be bit-aligned, then copy
6601       --  the value into a temporary first. This copy may need to expand to a
6602       --  loop of component operations.
6603
6604       if Is_Possibly_Unaligned_Slice (Exp)
6605         or else Is_Possibly_Unaligned_Object (Exp)
6606       then
6607          declare
6608             ExpR : constant Node_Id   := Relocate_Node (Exp);
6609             Tnn  : constant Entity_Id := Make_Temporary (Loc, 'T', ExpR);
6610          begin
6611             Insert_Action (Exp,
6612               Make_Object_Declaration (Loc,
6613                 Defining_Identifier => Tnn,
6614                 Constant_Present    => True,
6615                 Object_Definition   => New_Occurrence_Of (R_Type, Loc),
6616                 Expression          => ExpR),
6617               Suppress => All_Checks);
6618             Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6619          end;
6620       end if;
6621
6622       --  Generate call to postcondition checks if they are present
6623
6624       if Ekind (Scope_Id) = E_Function
6625         and then Has_Postconditions (Scope_Id)
6626       then
6627          --  We are going to reference the returned value twice in this case,
6628          --  once in the call to _Postconditions, and once in the actual return
6629          --  statement, but we can't have side effects happening twice, and in
6630          --  any case for efficiency we don't want to do the computation twice.
6631
6632          --  If the returned expression is an entity name, we don't need to
6633          --  worry since it is efficient and safe to reference it twice, that's
6634          --  also true for literals other than string literals, and for the
6635          --  case of X.all where X is an entity name.
6636
6637          if Is_Entity_Name (Exp)
6638            or else Nkind_In (Exp, N_Character_Literal,
6639                                   N_Integer_Literal,
6640                                   N_Real_Literal)
6641            or else (Nkind (Exp) = N_Explicit_Dereference
6642                      and then Is_Entity_Name (Prefix (Exp)))
6643          then
6644             null;
6645
6646          --  Otherwise we are going to need a temporary to capture the value
6647
6648          else
6649             declare
6650                ExpR : constant Node_Id   := Relocate_Node (Exp);
6651                Tnn  : constant Entity_Id := Make_Temporary (Loc, 'T', ExpR);
6652
6653             begin
6654                --  For a complex expression of an elementary type, capture
6655                --  value in the temporary and use it as the reference.
6656
6657                if Is_Elementary_Type (R_Type) then
6658                   Insert_Action (Exp,
6659                     Make_Object_Declaration (Loc,
6660                       Defining_Identifier => Tnn,
6661                       Constant_Present    => True,
6662                       Object_Definition   => New_Occurrence_Of (R_Type, Loc),
6663                       Expression          => ExpR),
6664                     Suppress => All_Checks);
6665
6666                   Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6667
6668                --  If we have something we can rename, generate a renaming of
6669                --  the object and replace the expression with a reference
6670
6671                elsif Is_Object_Reference (Exp) then
6672                   Insert_Action (Exp,
6673                     Make_Object_Renaming_Declaration (Loc,
6674                       Defining_Identifier => Tnn,
6675                       Subtype_Mark        => New_Occurrence_Of (R_Type, Loc),
6676                       Name                => ExpR),
6677                     Suppress => All_Checks);
6678
6679                   Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6680
6681                --  Otherwise we have something like a string literal or an
6682                --  aggregate. We could copy the value, but that would be
6683                --  inefficient. Instead we make a reference to the value and
6684                --  capture this reference with a renaming, the expression is
6685                --  then replaced by a dereference of this renaming.
6686
6687                else
6688                   --  For now, copy the value, since the code below does not
6689                   --  seem to work correctly ???
6690
6691                   Insert_Action (Exp,
6692                     Make_Object_Declaration (Loc,
6693                       Defining_Identifier => Tnn,
6694                       Constant_Present    => True,
6695                       Object_Definition   => New_Occurrence_Of (R_Type, Loc),
6696                       Expression          => Relocate_Node (Exp)),
6697                     Suppress => All_Checks);
6698
6699                   Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
6700
6701                   --  Insert_Action (Exp,
6702                   --    Make_Object_Renaming_Declaration (Loc,
6703                   --      Defining_Identifier => Tnn,
6704                   --      Access_Definition =>
6705                   --        Make_Access_Definition (Loc,
6706                   --          All_Present  => True,
6707                   --          Subtype_Mark => New_Occurrence_Of (R_Type, Loc)),
6708                   --      Name =>
6709                   --        Make_Reference (Loc,
6710                   --          Prefix => Relocate_Node (Exp))),
6711                   --    Suppress => All_Checks);
6712
6713                   --  Rewrite (Exp,
6714                   --    Make_Explicit_Dereference (Loc,
6715                   --      Prefix => New_Occurrence_Of (Tnn, Loc)));
6716                end if;
6717             end;
6718          end if;
6719
6720          --  Generate call to _postconditions
6721
6722          Insert_Action (Exp,
6723            Make_Procedure_Call_Statement (Loc,
6724              Name => Make_Identifier (Loc, Name_uPostconditions),
6725              Parameter_Associations => New_List (Duplicate_Subexpr (Exp))));
6726       end if;
6727
6728       --  Ada 2005 (AI-251): If this return statement corresponds with an
6729       --  simple return statement associated with an extended return statement
6730       --  and the type of the returned object is an interface then generate an
6731       --  implicit conversion to force displacement of the "this" pointer.
6732
6733       if Ada_Version >= Ada_2005
6734         and then Comes_From_Extended_Return_Statement (N)
6735         and then Nkind (Expression (N)) = N_Identifier
6736         and then Is_Interface (Utyp)
6737         and then Utyp /= Underlying_Type (Exptyp)
6738       then
6739          Rewrite (Exp, Convert_To (Utyp, Relocate_Node (Exp)));
6740          Analyze_And_Resolve (Exp);
6741       end if;
6742    end Expand_Simple_Function_Return;
6743
6744    --------------------------------
6745    -- Is_Build_In_Place_Function --
6746    --------------------------------
6747
6748    function Is_Build_In_Place_Function (E : Entity_Id) return Boolean is
6749    begin
6750       --  This function is called from Expand_Subtype_From_Expr during
6751       --  semantic analysis, even when expansion is off. In those cases
6752       --  the build_in_place expansion will not take place.
6753
6754       if not Expander_Active then
6755          return False;
6756       end if;
6757
6758       --  For now we test whether E denotes a function or access-to-function
6759       --  type whose result subtype is inherently limited. Later this test may
6760       --  be revised to allow composite nonlimited types. Functions with a
6761       --  foreign convention or whose result type has a foreign convention
6762       --  never qualify.
6763
6764       if Ekind_In (E, E_Function, E_Generic_Function)
6765         or else (Ekind (E) = E_Subprogram_Type
6766                   and then Etype (E) /= Standard_Void_Type)
6767       then
6768          --  Note: If you have Convention (C) on an inherently limited type,
6769          --  you're on your own. That is, the C code will have to be carefully
6770          --  written to know about the Ada conventions.
6771
6772          if Has_Foreign_Convention (E)
6773            or else Has_Foreign_Convention (Etype (E))
6774          then
6775             return False;
6776
6777          --  In Ada 2005 all functions with an inherently limited return type
6778          --  must be handled using a build-in-place profile, including the case
6779          --  of a function with a limited interface result, where the function
6780          --  may return objects of nonlimited descendants.
6781
6782          else
6783             return Is_Immutably_Limited_Type (Etype (E))
6784               and then Ada_Version >= Ada_2005
6785               and then not Debug_Flag_Dot_L;
6786          end if;
6787
6788       else
6789          return False;
6790       end if;
6791    end Is_Build_In_Place_Function;
6792
6793    -------------------------------------
6794    -- Is_Build_In_Place_Function_Call --
6795    -------------------------------------
6796
6797    function Is_Build_In_Place_Function_Call (N : Node_Id) return Boolean is
6798       Exp_Node    : Node_Id := N;
6799       Function_Id : Entity_Id;
6800
6801    begin
6802       --  Return False when the expander is inactive, since awareness of
6803       --  build-in-place treatment is only relevant during expansion. Note that
6804       --  Is_Build_In_Place_Function, which is called as part of this function,
6805       --  is also conditioned this way, but we need to check here as well to
6806       --  avoid blowing up on processing protected calls when expansion is
6807       --  disabled (such as with -gnatc) since those would trip over the raise
6808       --  of Program_Error below.
6809
6810       if not Expander_Active then
6811          return False;
6812       end if;
6813
6814       --  Step past qualification or unchecked conversion (the latter can occur
6815       --  in cases of calls to 'Input).
6816
6817       if Nkind_In
6818            (Exp_Node, N_Qualified_Expression, N_Unchecked_Type_Conversion)
6819       then
6820          Exp_Node := Expression (N);
6821       end if;
6822
6823       if Nkind (Exp_Node) /= N_Function_Call then
6824          return False;
6825
6826       else
6827          if Is_Entity_Name (Name (Exp_Node)) then
6828             Function_Id := Entity (Name (Exp_Node));
6829
6830          elsif Nkind (Name (Exp_Node)) = N_Explicit_Dereference then
6831             Function_Id := Etype (Name (Exp_Node));
6832
6833          --  In Alfa mode, protected subprogram calls are not expanded, so that
6834          --  we may end up with a call that is neither resolved to an entity,
6835          --  nor an indirect call.
6836
6837          elsif Alfa_Mode then
6838             return False;
6839
6840          else
6841             raise Program_Error;
6842          end if;
6843
6844          return Is_Build_In_Place_Function (Function_Id);
6845       end if;
6846    end Is_Build_In_Place_Function_Call;
6847
6848    -----------------------
6849    -- Freeze_Subprogram --
6850    -----------------------
6851
6852    procedure Freeze_Subprogram (N : Node_Id) is
6853       Loc : constant Source_Ptr := Sloc (N);
6854
6855       procedure Register_Predefined_DT_Entry (Prim : Entity_Id);
6856       --  (Ada 2005): Register a predefined primitive in all the secondary
6857       --  dispatch tables of its primitive type.
6858
6859       ----------------------------------
6860       -- Register_Predefined_DT_Entry --
6861       ----------------------------------
6862
6863       procedure Register_Predefined_DT_Entry (Prim : Entity_Id) is
6864          Iface_DT_Ptr : Elmt_Id;
6865          Tagged_Typ   : Entity_Id;
6866          Thunk_Id     : Entity_Id;
6867          Thunk_Code   : Node_Id;
6868
6869       begin
6870          Tagged_Typ := Find_Dispatching_Type (Prim);
6871
6872          if No (Access_Disp_Table (Tagged_Typ))
6873            or else not Has_Interfaces (Tagged_Typ)
6874            or else not RTE_Available (RE_Interface_Tag)
6875            or else Restriction_Active (No_Dispatching_Calls)
6876          then
6877             return;
6878          end if;
6879
6880          --  Skip the first two access-to-dispatch-table pointers since they
6881          --  leads to the primary dispatch table (predefined DT and user
6882          --  defined DT). We are only concerned with the secondary dispatch
6883          --  table pointers. Note that the access-to- dispatch-table pointer
6884          --  corresponds to the first implemented interface retrieved below.
6885
6886          Iface_DT_Ptr :=
6887            Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Tagged_Typ))));
6888
6889          while Present (Iface_DT_Ptr)
6890            and then Ekind (Node (Iface_DT_Ptr)) = E_Constant
6891          loop
6892             pragma Assert (Has_Thunks (Node (Iface_DT_Ptr)));
6893             Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code);
6894
6895             if Present (Thunk_Code) then
6896                Insert_Actions_After (N, New_List (
6897                  Thunk_Code,
6898
6899                  Build_Set_Predefined_Prim_Op_Address (Loc,
6900                    Tag_Node =>
6901                      New_Reference_To (Node (Next_Elmt (Iface_DT_Ptr)), Loc),
6902                    Position => DT_Position (Prim),
6903                    Address_Node =>
6904                      Unchecked_Convert_To (RTE (RE_Prim_Ptr),
6905                        Make_Attribute_Reference (Loc,
6906                          Prefix         => New_Reference_To (Thunk_Id, Loc),
6907                          Attribute_Name => Name_Unrestricted_Access))),
6908
6909                  Build_Set_Predefined_Prim_Op_Address (Loc,
6910                    Tag_Node =>
6911                      New_Reference_To
6912                       (Node (Next_Elmt (Next_Elmt (Next_Elmt (Iface_DT_Ptr)))),
6913                        Loc),
6914                    Position => DT_Position (Prim),
6915                    Address_Node =>
6916                      Unchecked_Convert_To (RTE (RE_Prim_Ptr),
6917                        Make_Attribute_Reference (Loc,
6918                          Prefix         => New_Reference_To (Prim, Loc),
6919                          Attribute_Name => Name_Unrestricted_Access)))));
6920             end if;
6921
6922             --  Skip the tag of the predefined primitives dispatch table
6923
6924             Next_Elmt (Iface_DT_Ptr);
6925             pragma Assert (Has_Thunks (Node (Iface_DT_Ptr)));
6926
6927             --  Skip the tag of the no-thunks dispatch table
6928
6929             Next_Elmt (Iface_DT_Ptr);
6930             pragma Assert (not Has_Thunks (Node (Iface_DT_Ptr)));
6931
6932             --  Skip the tag of the predefined primitives no-thunks dispatch
6933             --  table.
6934
6935             Next_Elmt (Iface_DT_Ptr);
6936             pragma Assert (not Has_Thunks (Node (Iface_DT_Ptr)));
6937
6938             Next_Elmt (Iface_DT_Ptr);
6939          end loop;
6940       end Register_Predefined_DT_Entry;
6941
6942       --  Local variables
6943
6944       Subp : constant Entity_Id  := Entity (N);
6945
6946    --  Start of processing for Freeze_Subprogram
6947
6948    begin
6949       --  We suppress the initialization of the dispatch table entry when
6950       --  VM_Target because the dispatching mechanism is handled internally
6951       --  by the VM.
6952
6953       if Is_Dispatching_Operation (Subp)
6954         and then not Is_Abstract_Subprogram (Subp)
6955         and then Present (DTC_Entity (Subp))
6956         and then Present (Scope (DTC_Entity (Subp)))
6957         and then Tagged_Type_Expansion
6958         and then not Restriction_Active (No_Dispatching_Calls)
6959         and then RTE_Available (RE_Tag)
6960       then
6961          declare
6962             Typ : constant Entity_Id := Scope (DTC_Entity (Subp));
6963
6964          begin
6965             --  Handle private overridden primitives
6966
6967             if not Is_CPP_Class (Typ) then
6968                Check_Overriding_Operation (Subp);
6969             end if;
6970
6971             --  We assume that imported CPP primitives correspond with objects
6972             --  whose constructor is in the CPP side; therefore we don't need
6973             --  to generate code to register them in the dispatch table.
6974
6975             if Is_CPP_Class (Typ) then
6976                null;
6977
6978             --  Handle CPP primitives found in derivations of CPP_Class types.
6979             --  These primitives must have been inherited from some parent, and
6980             --  there is no need to register them in the dispatch table because
6981             --  Build_Inherit_Prims takes care of the initialization of these
6982             --  slots.
6983
6984             elsif Is_Imported (Subp)
6985                     and then (Convention (Subp) = Convention_CPP
6986                                 or else Convention (Subp) = Convention_C)
6987             then
6988                null;
6989
6990             --  Generate code to register the primitive in non statically
6991             --  allocated dispatch tables
6992
6993             elsif not Building_Static_DT (Scope (DTC_Entity (Subp))) then
6994
6995                --  When a primitive is frozen, enter its name in its dispatch
6996                --  table slot.
6997
6998                if not Is_Interface (Typ)
6999                  or else Present (Interface_Alias (Subp))
7000                then
7001                   if Is_Predefined_Dispatching_Operation (Subp) then
7002                      Register_Predefined_DT_Entry (Subp);
7003                   end if;
7004
7005                   Insert_Actions_After (N,
7006                     Register_Primitive (Loc, Prim => Subp));
7007                end if;
7008             end if;
7009          end;
7010       end if;
7011
7012       --  Mark functions that return by reference. Note that it cannot be part
7013       --  of the normal semantic analysis of the spec since the underlying
7014       --  returned type may not be known yet (for private types).
7015
7016       declare
7017          Typ  : constant Entity_Id := Etype (Subp);
7018          Utyp : constant Entity_Id := Underlying_Type (Typ);
7019       begin
7020          if Is_Immutably_Limited_Type (Typ) then
7021             Set_Returns_By_Ref (Subp);
7022          elsif Present (Utyp) and then CW_Or_Has_Controlled_Part (Utyp) then
7023             Set_Returns_By_Ref (Subp);
7024          end if;
7025       end;
7026    end Freeze_Subprogram;
7027
7028    -----------------------
7029    -- Is_Null_Procedure --
7030    -----------------------
7031
7032    function Is_Null_Procedure (Subp : Entity_Id) return Boolean is
7033       Decl : constant Node_Id := Unit_Declaration_Node (Subp);
7034
7035    begin
7036       if Ekind (Subp) /= E_Procedure then
7037          return False;
7038
7039       --  Check if this is a declared null procedure
7040
7041       elsif Nkind (Decl) = N_Subprogram_Declaration then
7042          if not Null_Present (Specification (Decl)) then
7043             return False;
7044
7045          elsif No (Body_To_Inline (Decl)) then
7046             return False;
7047
7048          --  Check if the body contains only a null statement, followed by
7049          --  the return statement added during expansion.
7050
7051          else
7052             declare
7053                Orig_Bod : constant Node_Id := Body_To_Inline (Decl);
7054
7055                Stat  : Node_Id;
7056                Stat2 : Node_Id;
7057
7058             begin
7059                if Nkind (Orig_Bod) /= N_Subprogram_Body then
7060                   return False;
7061                else
7062                   --  We must skip SCIL nodes because they are currently
7063                   --  implemented as special N_Null_Statement nodes.
7064
7065                   Stat :=
7066                      First_Non_SCIL_Node
7067                        (Statements (Handled_Statement_Sequence (Orig_Bod)));
7068                   Stat2 := Next_Non_SCIL_Node (Stat);
7069
7070                   return
7071                      Is_Empty_List (Declarations (Orig_Bod))
7072                        and then Nkind (Stat) = N_Null_Statement
7073                        and then
7074                         (No (Stat2)
7075                           or else
7076                             (Nkind (Stat2) = N_Simple_Return_Statement
7077                               and then No (Next (Stat2))));
7078                end if;
7079             end;
7080          end if;
7081
7082       else
7083          return False;
7084       end if;
7085    end Is_Null_Procedure;
7086
7087    -------------------------------------------
7088    -- Make_Build_In_Place_Call_In_Allocator --
7089    -------------------------------------------
7090
7091    procedure Make_Build_In_Place_Call_In_Allocator
7092      (Allocator     : Node_Id;
7093       Function_Call : Node_Id)
7094    is
7095       Loc               : Source_Ptr;
7096       Func_Call         : Node_Id := Function_Call;
7097       Function_Id       : Entity_Id;
7098       Result_Subt       : Entity_Id;
7099       Acc_Type          : constant Entity_Id := Etype (Allocator);
7100       New_Allocator     : Node_Id;
7101       Return_Obj_Access : Entity_Id;
7102
7103    begin
7104       --  Step past qualification or unchecked conversion (the latter can occur
7105       --  in cases of calls to 'Input).
7106
7107       if Nkind_In (Func_Call,
7108                    N_Qualified_Expression,
7109                    N_Unchecked_Type_Conversion)
7110       then
7111          Func_Call := Expression (Func_Call);
7112       end if;
7113
7114       --  If the call has already been processed to add build-in-place actuals
7115       --  then return. This should not normally occur in an allocator context,
7116       --  but we add the protection as a defensive measure.
7117
7118       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7119          return;
7120       end if;
7121
7122       --  Mark the call as processed as a build-in-place call
7123
7124       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7125
7126       Loc := Sloc (Function_Call);
7127
7128       if Is_Entity_Name (Name (Func_Call)) then
7129          Function_Id := Entity (Name (Func_Call));
7130
7131       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7132          Function_Id := Etype (Name (Func_Call));
7133
7134       else
7135          raise Program_Error;
7136       end if;
7137
7138       Result_Subt := Etype (Function_Id);
7139
7140       --  Check whether return type includes tasks. This may not have been done
7141       --  previously, if the type was a limited view.
7142
7143       if Has_Task (Result_Subt) then
7144          Build_Activation_Chain_Entity (Allocator);
7145       end if;
7146
7147       --  When the result subtype is constrained, the return object must be
7148       --  allocated on the caller side, and access to it is passed to the
7149       --  function.
7150
7151       --  Here and in related routines, we must examine the full view of the
7152       --  type, because the view at the point of call may differ from that
7153       --  that in the function body, and the expansion mechanism depends on
7154       --  the characteristics of the full view.
7155
7156       if Is_Constrained (Underlying_Type (Result_Subt)) then
7157
7158          --  Replace the initialized allocator of form "new T'(Func (...))"
7159          --  with an uninitialized allocator of form "new T", where T is the
7160          --  result subtype of the called function. The call to the function
7161          --  is handled separately further below.
7162
7163          New_Allocator :=
7164            Make_Allocator (Loc,
7165              Expression => New_Reference_To (Result_Subt, Loc));
7166          Set_No_Initialization (New_Allocator);
7167
7168          --  Copy attributes to new allocator. Note that the new allocator
7169          --  logically comes from source if the original one did, so copy the
7170          --  relevant flag. This ensures proper treatment of the restriction
7171          --  No_Implicit_Heap_Allocations in this case.
7172
7173          Set_Storage_Pool      (New_Allocator, Storage_Pool      (Allocator));
7174          Set_Procedure_To_Call (New_Allocator, Procedure_To_Call (Allocator));
7175          Set_Comes_From_Source (New_Allocator, Comes_From_Source (Allocator));
7176
7177          Rewrite (Allocator, New_Allocator);
7178
7179          --  Create a new access object and initialize it to the result of the
7180          --  new uninitialized allocator. Note: we do not use Allocator as the
7181          --  Related_Node of Return_Obj_Access in call to Make_Temporary below
7182          --  as this would create a sort of infinite "recursion".
7183
7184          Return_Obj_Access := Make_Temporary (Loc, 'R');
7185          Set_Etype (Return_Obj_Access, Acc_Type);
7186
7187          Insert_Action (Allocator,
7188            Make_Object_Declaration (Loc,
7189              Defining_Identifier => Return_Obj_Access,
7190              Object_Definition   => New_Reference_To (Acc_Type, Loc),
7191              Expression          => Relocate_Node (Allocator)));
7192
7193          --  When the function has a controlling result, an allocation-form
7194          --  parameter must be passed indicating that the caller is allocating
7195          --  the result object. This is needed because such a function can be
7196          --  called as a dispatching operation and must be treated similarly
7197          --  to functions with unconstrained result subtypes.
7198
7199          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7200            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7201
7202          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7203            (Func_Call, Function_Id, Acc_Type);
7204
7205          Add_Task_Actuals_To_Build_In_Place_Call
7206            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
7207
7208          --  Add an implicit actual to the function call that provides access
7209          --  to the allocated object. An unchecked conversion to the (specific)
7210          --  result subtype of the function is inserted to handle cases where
7211          --  the access type of the allocator has a class-wide designated type.
7212
7213          Add_Access_Actual_To_Build_In_Place_Call
7214            (Func_Call,
7215             Function_Id,
7216             Make_Unchecked_Type_Conversion (Loc,
7217               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
7218               Expression   =>
7219                 Make_Explicit_Dereference (Loc,
7220                   Prefix => New_Reference_To (Return_Obj_Access, Loc))));
7221
7222       --  When the result subtype is unconstrained, the function itself must
7223       --  perform the allocation of the return object, so we pass parameters
7224       --  indicating that. We don't yet handle the case where the allocation
7225       --  must be done in a user-defined storage pool, which will require
7226       --  passing another actual or two to provide allocation/deallocation
7227       --  operations. ???
7228
7229       else
7230          --  Pass an allocation parameter indicating that the function should
7231          --  allocate its result on the heap.
7232
7233          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7234            (Func_Call, Function_Id, Alloc_Form => Global_Heap);
7235
7236          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7237            (Func_Call, Function_Id, Acc_Type);
7238
7239          --  If access type has a master entity, pass a reference to it
7240
7241          if Present (Master_Id (Acc_Type)) then
7242             Add_Task_Actuals_To_Build_In_Place_Call
7243               (Func_Call, Function_Id,
7244                Master_Actual =>
7245                  New_Occurrence_Of (Master_Id (Acc_Type), Loc));
7246          else
7247             Add_Task_Actuals_To_Build_In_Place_Call
7248               (Func_Call, Function_Id, Empty);
7249          end if;
7250
7251          --  The caller does not provide the return object in this case, so we
7252          --  have to pass null for the object access actual.
7253
7254          Add_Access_Actual_To_Build_In_Place_Call
7255            (Func_Call, Function_Id, Return_Object => Empty);
7256       end if;
7257
7258       --  If the build-in-place function call returns a controlled object,
7259       --  the finalization master will require a reference to routine
7260       --  Finalize_Address of the designated type. Setting this attribute
7261       --  is done in the same manner to expansion of allocators.
7262
7263       if Needs_Finalization (Result_Subt) then
7264
7265          --  Controlled types with supressed finalization do not need to
7266          --  associate the address of their Finalize_Address primitives with
7267          --  a master since they do not need a master to begin with.
7268
7269          if Is_Library_Level_Entity (Acc_Type)
7270            and then Finalize_Storage_Only (Result_Subt)
7271          then
7272             null;
7273
7274          --  Do not generate the call to Set_Finalize_Address in Alfa mode
7275          --  because it is not necessary and results in unwanted expansion.
7276          --  This expansion is also not carried out in CodePeer mode because
7277          --  Finalize_Address is never built.
7278
7279          elsif not Alfa_Mode
7280            and then not CodePeer_Mode
7281          then
7282             Insert_Action (Allocator,
7283               Make_Set_Finalize_Address_Call (Loc,
7284                 Typ     => Etype (Function_Id),
7285                 Ptr_Typ => Acc_Type));
7286          end if;
7287       end if;
7288
7289       --  Finally, replace the allocator node with a reference to the result
7290       --  of the function call itself (which will effectively be an access
7291       --  to the object created by the allocator).
7292
7293       Rewrite (Allocator, Make_Reference (Loc, Relocate_Node (Function_Call)));
7294       Analyze_And_Resolve (Allocator, Acc_Type);
7295    end Make_Build_In_Place_Call_In_Allocator;
7296
7297    ---------------------------------------------------
7298    -- Make_Build_In_Place_Call_In_Anonymous_Context --
7299    ---------------------------------------------------
7300
7301    procedure Make_Build_In_Place_Call_In_Anonymous_Context
7302      (Function_Call : Node_Id)
7303    is
7304       Loc             : Source_Ptr;
7305       Func_Call       : Node_Id := Function_Call;
7306       Function_Id     : Entity_Id;
7307       Result_Subt     : Entity_Id;
7308       Return_Obj_Id   : Entity_Id;
7309       Return_Obj_Decl : Entity_Id;
7310
7311    begin
7312       --  Step past qualification or unchecked conversion (the latter can occur
7313       --  in cases of calls to 'Input).
7314
7315       if Nkind_In (Func_Call, N_Qualified_Expression,
7316                               N_Unchecked_Type_Conversion)
7317       then
7318          Func_Call := Expression (Func_Call);
7319       end if;
7320
7321       --  If the call has already been processed to add build-in-place actuals
7322       --  then return. One place this can occur is for calls to build-in-place
7323       --  functions that occur within a call to a protected operation, where
7324       --  due to rewriting and expansion of the protected call there can be
7325       --  more than one call to Expand_Actuals for the same set of actuals.
7326
7327       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7328          return;
7329       end if;
7330
7331       --  Mark the call as processed as a build-in-place call
7332
7333       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7334
7335       Loc := Sloc (Function_Call);
7336
7337       if Is_Entity_Name (Name (Func_Call)) then
7338          Function_Id := Entity (Name (Func_Call));
7339
7340       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7341          Function_Id := Etype (Name (Func_Call));
7342
7343       else
7344          raise Program_Error;
7345       end if;
7346
7347       Result_Subt := Etype (Function_Id);
7348
7349       --  If the build-in-place function returns a controlled object, then the
7350       --  object needs to be finalized immediately after the context. Since
7351       --  this case produces a transient scope, the servicing finalizer needs
7352       --  to name the returned object. Create a temporary which is initialized
7353       --  with the function call:
7354       --
7355       --    Temp_Id : Func_Type := BIP_Func_Call;
7356       --
7357       --  The initialization expression of the temporary will be rewritten by
7358       --  the expander using the appropriate mechanism in Make_Build_In_Place_
7359       --  Call_In_Object_Declaration.
7360
7361       if Needs_Finalization (Result_Subt) then
7362          declare
7363             Temp_Id   : constant Entity_Id := Make_Temporary (Loc, 'R');
7364             Temp_Decl : Node_Id;
7365
7366          begin
7367             --  Reset the guard on the function call since the following does
7368             --  not perform actual call expansion.
7369
7370             Set_Is_Expanded_Build_In_Place_Call (Func_Call, False);
7371
7372             Temp_Decl :=
7373               Make_Object_Declaration (Loc,
7374                 Defining_Identifier => Temp_Id,
7375                 Object_Definition =>
7376                   New_Reference_To (Result_Subt, Loc),
7377                 Expression =>
7378                   New_Copy_Tree (Function_Call));
7379
7380             Insert_Action (Function_Call, Temp_Decl);
7381
7382             Rewrite (Function_Call, New_Reference_To (Temp_Id, Loc));
7383             Analyze (Function_Call);
7384          end;
7385
7386       --  When the result subtype is constrained, an object of the subtype is
7387       --  declared and an access value designating it is passed as an actual.
7388
7389       elsif Is_Constrained (Underlying_Type (Result_Subt)) then
7390
7391          --  Create a temporary object to hold the function result
7392
7393          Return_Obj_Id := Make_Temporary (Loc, 'R');
7394          Set_Etype (Return_Obj_Id, Result_Subt);
7395
7396          Return_Obj_Decl :=
7397            Make_Object_Declaration (Loc,
7398              Defining_Identifier => Return_Obj_Id,
7399              Aliased_Present     => True,
7400              Object_Definition   => New_Reference_To (Result_Subt, Loc));
7401
7402          Set_No_Initialization (Return_Obj_Decl);
7403
7404          Insert_Action (Func_Call, Return_Obj_Decl);
7405
7406          --  When the function has a controlling result, an allocation-form
7407          --  parameter must be passed indicating that the caller is allocating
7408          --  the result object. This is needed because such a function can be
7409          --  called as a dispatching operation and must be treated similarly
7410          --  to functions with unconstrained result subtypes.
7411
7412          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7413            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7414
7415          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7416            (Func_Call, Function_Id);
7417
7418          Add_Task_Actuals_To_Build_In_Place_Call
7419            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
7420
7421          --  Add an implicit actual to the function call that provides access
7422          --  to the caller's return object.
7423
7424          Add_Access_Actual_To_Build_In_Place_Call
7425            (Func_Call, Function_Id, New_Reference_To (Return_Obj_Id, Loc));
7426
7427       --  When the result subtype is unconstrained, the function must allocate
7428       --  the return object in the secondary stack, so appropriate implicit
7429       --  parameters are added to the call to indicate that. A transient
7430       --  scope is established to ensure eventual cleanup of the result.
7431
7432       else
7433          --  Pass an allocation parameter indicating that the function should
7434          --  allocate its result on the secondary stack.
7435
7436          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7437            (Func_Call, Function_Id, Alloc_Form => Secondary_Stack);
7438
7439          Add_Finalization_Master_Actual_To_Build_In_Place_Call
7440            (Func_Call, Function_Id);
7441
7442          Add_Task_Actuals_To_Build_In_Place_Call
7443            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
7444
7445          --  Pass a null value to the function since no return object is
7446          --  available on the caller side.
7447
7448          Add_Access_Actual_To_Build_In_Place_Call
7449            (Func_Call, Function_Id, Empty);
7450       end if;
7451    end Make_Build_In_Place_Call_In_Anonymous_Context;
7452
7453    --------------------------------------------
7454    -- Make_Build_In_Place_Call_In_Assignment --
7455    --------------------------------------------
7456
7457    procedure Make_Build_In_Place_Call_In_Assignment
7458      (Assign        : Node_Id;
7459       Function_Call : Node_Id)
7460    is
7461       Lhs          : constant Node_Id := Name (Assign);
7462       Func_Call    : Node_Id := Function_Call;
7463       Func_Id      : Entity_Id;
7464       Loc          : Source_Ptr;
7465       Obj_Decl     : Node_Id;
7466       Obj_Id       : Entity_Id;
7467       Ptr_Typ      : Entity_Id;
7468       Ptr_Typ_Decl : Node_Id;
7469       Result_Subt  : Entity_Id;
7470       Target       : Node_Id;
7471
7472    begin
7473       --  Step past qualification or unchecked conversion (the latter can occur
7474       --  in cases of calls to 'Input).
7475
7476       if Nkind_In (Func_Call, N_Qualified_Expression,
7477                               N_Unchecked_Type_Conversion)
7478       then
7479          Func_Call := Expression (Func_Call);
7480       end if;
7481
7482       --  If the call has already been processed to add build-in-place actuals
7483       --  then return. This should not normally occur in an assignment context,
7484       --  but we add the protection as a defensive measure.
7485
7486       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7487          return;
7488       end if;
7489
7490       --  Mark the call as processed as a build-in-place call
7491
7492       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7493
7494       Loc := Sloc (Function_Call);
7495
7496       if Is_Entity_Name (Name (Func_Call)) then
7497          Func_Id := Entity (Name (Func_Call));
7498
7499       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7500          Func_Id := Etype (Name (Func_Call));
7501
7502       else
7503          raise Program_Error;
7504       end if;
7505
7506       Result_Subt := Etype (Func_Id);
7507
7508       --  When the result subtype is unconstrained, an additional actual must
7509       --  be passed to indicate that the caller is providing the return object.
7510       --  This parameter must also be passed when the called function has a
7511       --  controlling result, because dispatching calls to the function needs
7512       --  to be treated effectively the same as calls to class-wide functions.
7513
7514       Add_Alloc_Form_Actual_To_Build_In_Place_Call
7515         (Func_Call, Func_Id, Alloc_Form => Caller_Allocation);
7516
7517       Add_Finalization_Master_Actual_To_Build_In_Place_Call
7518         (Func_Call, Func_Id);
7519
7520       Add_Task_Actuals_To_Build_In_Place_Call
7521         (Func_Call, Func_Id, Make_Identifier (Loc, Name_uMaster));
7522
7523       --  Add an implicit actual to the function call that provides access to
7524       --  the caller's return object.
7525
7526       Add_Access_Actual_To_Build_In_Place_Call
7527         (Func_Call,
7528          Func_Id,
7529          Make_Unchecked_Type_Conversion (Loc,
7530            Subtype_Mark => New_Reference_To (Result_Subt, Loc),
7531            Expression   => Relocate_Node (Lhs)));
7532
7533       --  Create an access type designating the function's result subtype
7534
7535       Ptr_Typ := Make_Temporary (Loc, 'A');
7536
7537       Ptr_Typ_Decl :=
7538         Make_Full_Type_Declaration (Loc,
7539           Defining_Identifier => Ptr_Typ,
7540           Type_Definition     =>
7541             Make_Access_To_Object_Definition (Loc,
7542               All_Present        => True,
7543               Subtype_Indication =>
7544                 New_Reference_To (Result_Subt, Loc)));
7545       Insert_After_And_Analyze (Assign, Ptr_Typ_Decl);
7546
7547       --  Finally, create an access object initialized to a reference to the
7548       --  function call.
7549
7550       Obj_Id := Make_Temporary (Loc, 'R');
7551       Set_Etype (Obj_Id, Ptr_Typ);
7552
7553       Obj_Decl :=
7554         Make_Object_Declaration (Loc,
7555           Defining_Identifier => Obj_Id,
7556           Object_Definition   => New_Reference_To (Ptr_Typ, Loc),
7557           Expression => Make_Reference (Loc, Relocate_Node (Func_Call)));
7558       Insert_After_And_Analyze (Ptr_Typ_Decl, Obj_Decl);
7559
7560       Rewrite (Assign, Make_Null_Statement (Loc));
7561
7562       --  Retrieve the target of the assignment
7563
7564       if Nkind (Lhs) = N_Selected_Component then
7565          Target := Selector_Name (Lhs);
7566       elsif Nkind (Lhs) = N_Type_Conversion then
7567          Target := Expression (Lhs);
7568       else
7569          Target := Lhs;
7570       end if;
7571
7572       --  If we are assigning to a return object or this is an expression of
7573       --  an extension aggregate, the target should either be an identifier
7574       --  or a simple expression. All other cases imply a different scenario.
7575
7576       if Nkind (Target) in N_Has_Entity then
7577          Target := Entity (Target);
7578       else
7579          return;
7580       end if;
7581    end Make_Build_In_Place_Call_In_Assignment;
7582
7583    ----------------------------------------------------
7584    -- Make_Build_In_Place_Call_In_Object_Declaration --
7585    ----------------------------------------------------
7586
7587    procedure Make_Build_In_Place_Call_In_Object_Declaration
7588      (Object_Decl   : Node_Id;
7589       Function_Call : Node_Id)
7590    is
7591       Loc             : Source_Ptr;
7592       Obj_Def_Id      : constant Entity_Id :=
7593                           Defining_Identifier (Object_Decl);
7594
7595       Func_Call       : Node_Id := Function_Call;
7596       Function_Id     : Entity_Id;
7597       Result_Subt     : Entity_Id;
7598       Caller_Object   : Node_Id;
7599       Call_Deref      : Node_Id;
7600       Ref_Type        : Entity_Id;
7601       Ptr_Typ_Decl    : Node_Id;
7602       Def_Id          : Entity_Id;
7603       New_Expr        : Node_Id;
7604       Enclosing_Func  : constant Entity_Id :=
7605                           Enclosing_Subprogram (Obj_Def_Id);
7606       Fmaster_Actual  : Node_Id := Empty;
7607       Pass_Caller_Acc : Boolean := False;
7608
7609    begin
7610       --  Step past qualification or unchecked conversion (the latter can occur
7611       --  in cases of calls to 'Input).
7612
7613       if Nkind_In (Func_Call, N_Qualified_Expression,
7614                               N_Unchecked_Type_Conversion)
7615       then
7616          Func_Call := Expression (Func_Call);
7617       end if;
7618
7619       --  If the call has already been processed to add build-in-place actuals
7620       --  then return. This should not normally occur in an object declaration,
7621       --  but we add the protection as a defensive measure.
7622
7623       if Is_Expanded_Build_In_Place_Call (Func_Call) then
7624          return;
7625       end if;
7626
7627       --  Mark the call as processed as a build-in-place call
7628
7629       Set_Is_Expanded_Build_In_Place_Call (Func_Call);
7630
7631       Loc := Sloc (Function_Call);
7632
7633       if Is_Entity_Name (Name (Func_Call)) then
7634          Function_Id := Entity (Name (Func_Call));
7635
7636       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
7637          Function_Id := Etype (Name (Func_Call));
7638
7639       else
7640          raise Program_Error;
7641       end if;
7642
7643       Result_Subt := Etype (Function_Id);
7644
7645       --  If the the object is a return object of an enclosing build-in-place
7646       --  function, then the implicit build-in-place parameters of the
7647       --  enclosing function are simply passed along to the called function.
7648       --  (Unfortunately, this won't cover the case of extension aggregates
7649       --  where the ancestor part is a build-in-place unconstrained function
7650       --  call that should be passed along the caller's parameters. Currently
7651       --  those get mishandled by reassigning the result of the call to the
7652       --  aggregate return object, when the call result should really be
7653       --  directly built in place in the aggregate and not in a temporary. ???)
7654
7655       if Is_Return_Object (Defining_Identifier (Object_Decl)) then
7656          Pass_Caller_Acc := True;
7657
7658          --  When the enclosing function has a BIP_Alloc_Form formal then we
7659          --  pass it along to the callee (such as when the enclosing function
7660          --  has an unconstrained or tagged result type).
7661
7662          if Needs_BIP_Alloc_Form (Enclosing_Func) then
7663             Add_Alloc_Form_Actual_To_Build_In_Place_Call
7664               (Func_Call,
7665                Function_Id,
7666                Alloc_Form_Exp =>
7667                  New_Reference_To
7668                    (Build_In_Place_Formal (Enclosing_Func, BIP_Alloc_Form),
7669                     Loc));
7670
7671          --  Otherwise, if enclosing function has a constrained result subtype,
7672          --  then caller allocation will be used.
7673
7674          else
7675             Add_Alloc_Form_Actual_To_Build_In_Place_Call
7676               (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7677          end if;
7678
7679          if Needs_BIP_Finalization_Master (Enclosing_Func) then
7680             Fmaster_Actual :=
7681               New_Reference_To
7682                 (Build_In_Place_Formal
7683                    (Enclosing_Func, BIP_Finalization_Master), Loc);
7684          end if;
7685
7686          --  Retrieve the BIPacc formal from the enclosing function and convert
7687          --  it to the access type of the callee's BIP_Object_Access formal.
7688
7689          Caller_Object :=
7690             Make_Unchecked_Type_Conversion (Loc,
7691               Subtype_Mark =>
7692                 New_Reference_To
7693                   (Etype
7694                      (Build_In_Place_Formal (Function_Id, BIP_Object_Access)),
7695                    Loc),
7696               Expression   =>
7697                 New_Reference_To
7698                   (Build_In_Place_Formal (Enclosing_Func, BIP_Object_Access),
7699                    Loc));
7700
7701       --  In the constrained case, add an implicit actual to the function call
7702       --  that provides access to the declared object. An unchecked conversion
7703       --  to the (specific) result type of the function is inserted to handle
7704       --  the case where the object is declared with a class-wide type.
7705
7706       elsif Is_Constrained (Underlying_Type (Result_Subt)) then
7707          Caller_Object :=
7708             Make_Unchecked_Type_Conversion (Loc,
7709               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
7710               Expression   => New_Reference_To (Obj_Def_Id, Loc));
7711
7712          --  When the function has a controlling result, an allocation-form
7713          --  parameter must be passed indicating that the caller is allocating
7714          --  the result object. This is needed because such a function can be
7715          --  called as a dispatching operation and must be treated similarly
7716          --  to functions with unconstrained result subtypes.
7717
7718          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7719            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
7720
7721       --  In other unconstrained cases, pass an indication to do the allocation
7722       --  on the secondary stack and set Caller_Object to Empty so that a null
7723       --  value will be passed for the caller's object address. A transient
7724       --  scope is established to ensure eventual cleanup of the result.
7725
7726       else
7727          Add_Alloc_Form_Actual_To_Build_In_Place_Call
7728            (Func_Call,
7729             Function_Id,
7730             Alloc_Form => Secondary_Stack);
7731          Caller_Object := Empty;
7732
7733          Establish_Transient_Scope (Object_Decl, Sec_Stack => True);
7734       end if;
7735
7736       --  Pass along any finalization master actual, which is needed in the
7737       --  case where the called function initializes a return object of an
7738       --  enclosing build-in-place function.
7739
7740       Add_Finalization_Master_Actual_To_Build_In_Place_Call
7741         (Func_Call  => Func_Call,
7742          Func_Id    => Function_Id,
7743          Master_Exp => Fmaster_Actual);
7744
7745       if Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement
7746         and then Has_Task (Result_Subt)
7747       then
7748          --  Here we're passing along the master that was passed in to this
7749          --  function.
7750
7751          Add_Task_Actuals_To_Build_In_Place_Call
7752            (Func_Call, Function_Id,
7753             Master_Actual =>
7754               New_Reference_To
7755                 (Build_In_Place_Formal (Enclosing_Func, BIP_Master), Loc));
7756
7757       else
7758          Add_Task_Actuals_To_Build_In_Place_Call
7759            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
7760       end if;
7761
7762       Add_Access_Actual_To_Build_In_Place_Call
7763         (Func_Call, Function_Id, Caller_Object, Is_Access => Pass_Caller_Acc);
7764
7765       --  Create an access type designating the function's result subtype. We
7766       --  use the type of the original expression because it may be a call to
7767       --  an inherited operation, which the expansion has replaced with the
7768       --  parent operation that yields the parent type.
7769
7770       Ref_Type := Make_Temporary (Loc, 'A');
7771
7772       Ptr_Typ_Decl :=
7773         Make_Full_Type_Declaration (Loc,
7774           Defining_Identifier => Ref_Type,
7775           Type_Definition     =>
7776             Make_Access_To_Object_Definition (Loc,
7777               All_Present        => True,
7778               Subtype_Indication =>
7779                 New_Reference_To (Etype (Function_Call), Loc)));
7780
7781       --  The access type and its accompanying object must be inserted after
7782       --  the object declaration in the constrained case, so that the function
7783       --  call can be passed access to the object. In the unconstrained case,
7784       --  or if the object declaration is for a return object, the access type
7785       --  and object must be inserted before the object, since the object
7786       --  declaration is rewritten to be a renaming of a dereference of the
7787       --  access object.
7788
7789       if Is_Constrained (Underlying_Type (Result_Subt))
7790         and then not Is_Return_Object (Defining_Identifier (Object_Decl))
7791       then
7792          Insert_After_And_Analyze (Object_Decl, Ptr_Typ_Decl);
7793       else
7794          Insert_Action (Object_Decl, Ptr_Typ_Decl);
7795       end if;
7796
7797       --  Finally, create an access object initialized to a reference to the
7798       --  function call.
7799
7800       New_Expr := Make_Reference (Loc, Relocate_Node (Func_Call));
7801
7802       Def_Id := Make_Temporary (Loc, 'R', New_Expr);
7803       Set_Etype (Def_Id, Ref_Type);
7804
7805       Insert_After_And_Analyze (Ptr_Typ_Decl,
7806         Make_Object_Declaration (Loc,
7807           Defining_Identifier => Def_Id,
7808           Object_Definition   => New_Reference_To (Ref_Type, Loc),
7809           Expression          => New_Expr));
7810
7811       --  If the result subtype of the called function is constrained and
7812       --  is not itself the return expression of an enclosing BIP function,
7813       --  then mark the object as having no initialization.
7814
7815       if Is_Constrained (Underlying_Type (Result_Subt))
7816         and then not Is_Return_Object (Defining_Identifier (Object_Decl))
7817       then
7818          Set_Expression (Object_Decl, Empty);
7819          Set_No_Initialization (Object_Decl);
7820
7821       --  In case of an unconstrained result subtype, or if the call is the
7822       --  return expression of an enclosing BIP function, rewrite the object
7823       --  declaration as an object renaming where the renamed object is a
7824       --  dereference of <function_Call>'reference:
7825       --
7826       --      Obj : Subt renames <function_call>'Ref.all;
7827
7828       else
7829          Call_Deref :=
7830            Make_Explicit_Dereference (Loc,
7831              Prefix => New_Reference_To (Def_Id, Loc));
7832
7833          Loc := Sloc (Object_Decl);
7834          Rewrite (Object_Decl,
7835            Make_Object_Renaming_Declaration (Loc,
7836              Defining_Identifier => Make_Temporary (Loc, 'D'),
7837              Access_Definition   => Empty,
7838              Subtype_Mark        => New_Occurrence_Of (Result_Subt, Loc),
7839              Name                => Call_Deref));
7840
7841          Set_Renamed_Object (Defining_Identifier (Object_Decl), Call_Deref);
7842
7843          Analyze (Object_Decl);
7844
7845          --  Replace the internal identifier of the renaming declaration's
7846          --  entity with identifier of the original object entity. We also have
7847          --  to exchange the entities containing their defining identifiers to
7848          --  ensure the correct replacement of the object declaration by the
7849          --  object renaming declaration to avoid homograph conflicts (since
7850          --  the object declaration's defining identifier was already entered
7851          --  in current scope). The Next_Entity links of the two entities also
7852          --  have to be swapped since the entities are part of the return
7853          --  scope's entity list and the list structure would otherwise be
7854          --  corrupted. Finally, the homonym chain must be preserved as well.
7855
7856          declare
7857             Renaming_Def_Id  : constant Entity_Id :=
7858                                  Defining_Identifier (Object_Decl);
7859             Next_Entity_Temp : constant Entity_Id :=
7860                                  Next_Entity (Renaming_Def_Id);
7861          begin
7862             Set_Chars (Renaming_Def_Id, Chars (Obj_Def_Id));
7863
7864             --  Swap next entity links in preparation for exchanging entities
7865
7866             Set_Next_Entity (Renaming_Def_Id, Next_Entity (Obj_Def_Id));
7867             Set_Next_Entity (Obj_Def_Id, Next_Entity_Temp);
7868             Set_Homonym     (Renaming_Def_Id, Homonym (Obj_Def_Id));
7869
7870             Exchange_Entities (Renaming_Def_Id, Obj_Def_Id);
7871
7872             --  Preserve source indication of original declaration, so that
7873             --  xref information is properly generated for the right entity.
7874
7875             Preserve_Comes_From_Source
7876               (Object_Decl, Original_Node (Object_Decl));
7877
7878             Preserve_Comes_From_Source
7879               (Obj_Def_Id, Original_Node (Object_Decl));
7880
7881             Set_Comes_From_Source (Renaming_Def_Id, False);
7882          end;
7883       end if;
7884
7885       --  If the object entity has a class-wide Etype, then we need to change
7886       --  it to the result subtype of the function call, because otherwise the
7887       --  object will be class-wide without an explicit initialization and
7888       --  won't be allocated properly by the back end. It seems unclean to make
7889       --  such a revision to the type at this point, and we should try to
7890       --  improve this treatment when build-in-place functions with class-wide
7891       --  results are implemented. ???
7892
7893       if Is_Class_Wide_Type (Etype (Defining_Identifier (Object_Decl))) then
7894          Set_Etype (Defining_Identifier (Object_Decl), Result_Subt);
7895       end if;
7896    end Make_Build_In_Place_Call_In_Object_Declaration;
7897
7898    -----------------------------------
7899    -- Needs_BIP_Finalization_Master --
7900    -----------------------------------
7901
7902    function Needs_BIP_Finalization_Master
7903      (Func_Id : Entity_Id) return Boolean
7904    is
7905       pragma Assert (Is_Build_In_Place_Function (Func_Id));
7906       Func_Typ : constant Entity_Id := Underlying_Type (Etype (Func_Id));
7907
7908    begin
7909       return
7910         not Restriction_Active (No_Finalization)
7911           and then Needs_Finalization (Func_Typ);
7912    end Needs_BIP_Finalization_Master;
7913
7914    --------------------------
7915    -- Needs_BIP_Alloc_Form --
7916    --------------------------
7917
7918    function Needs_BIP_Alloc_Form (Func_Id : Entity_Id) return Boolean is
7919       pragma Assert (Is_Build_In_Place_Function (Func_Id));
7920       Func_Typ : constant Entity_Id := Underlying_Type (Etype (Func_Id));
7921    begin
7922       return not Is_Constrained (Func_Typ) or else Is_Tagged_Type (Func_Typ);
7923    end Needs_BIP_Alloc_Form;
7924
7925 end Exp_Ch6;