OSDN Git Service

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