OSDN Git Service

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