OSDN Git Service

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