OSDN Git Service

2007-09-10 Robert Dewar <dewar@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-2007, 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 Fname;    use Fname;
45 with Freeze;   use Freeze;
46 with Inline;   use Inline;
47 with Lib;      use Lib;
48 with Namet;    use Namet;
49 with Nlists;   use Nlists;
50 with Nmake;    use Nmake;
51 with Opt;      use Opt;
52 with Restrict; use Restrict;
53 with Rident;   use Rident;
54 with Rtsfind;  use Rtsfind;
55 with Sem;      use Sem;
56 with Sem_Ch6;  use Sem_Ch6;
57 with Sem_Ch8;  use Sem_Ch8;
58 with Sem_Ch12; use Sem_Ch12;
59 with Sem_Ch13; use Sem_Ch13;
60 with Sem_Eval; use Sem_Eval;
61 with Sem_Disp; use Sem_Disp;
62 with Sem_Dist; use Sem_Dist;
63 with Sem_Mech; use Sem_Mech;
64 with Sem_Res;  use Sem_Res;
65 with Sem_Util; use Sem_Util;
66 with Sinfo;    use Sinfo;
67 with Snames;   use Snames;
68 with Stand;    use Stand;
69 with Targparm; use Targparm;
70 with Tbuild;   use Tbuild;
71 with Uintp;    use Uintp;
72 with Validsw;  use Validsw;
73
74 package body Exp_Ch6 is
75
76    -----------------------
77    -- Local Subprograms --
78    -----------------------
79
80    procedure Add_Access_Actual_To_Build_In_Place_Call
81      (Function_Call : Node_Id;
82       Function_Id   : Entity_Id;
83       Return_Object : Node_Id;
84       Is_Access     : Boolean := False);
85    --  Ada 2005 (AI-318-02): Apply the Unrestricted_Access attribute to the
86    --  object name given by Return_Object and add the attribute to the end of
87    --  the actual parameter list associated with the build-in-place function
88    --  call denoted by Function_Call. However, if Is_Access is True, then
89    --  Return_Object is already an access expression, in which case it's passed
90    --  along directly to the build-in-place function. Finally, if Return_Object
91    --  is empty, then pass a null literal as the actual.
92
93    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
94      (Function_Call  : Node_Id;
95       Function_Id    : Entity_Id;
96       Alloc_Form     : BIP_Allocation_Form := Unspecified;
97       Alloc_Form_Exp : Node_Id             := Empty);
98    --  Ada 2005 (AI-318-02): Add an actual indicating the form of allocation,
99    --  if any, to be done by a build-in-place function. If Alloc_Form_Exp is
100    --  present, then use it, otherwise pass a literal corresponding to the
101    --  Alloc_Form parameter (which must not be Unspecified in that case).
102
103    procedure Add_Extra_Actual_To_Call
104      (Subprogram_Call : Node_Id;
105       Extra_Formal    : Entity_Id;
106       Extra_Actual    : Node_Id);
107    --  Adds Extra_Actual as a named parameter association for the formal
108    --  Extra_Formal in Subprogram_Call.
109
110    procedure Add_Final_List_Actual_To_Build_In_Place_Call
111      (Function_Call : Node_Id;
112       Function_Id   : Entity_Id;
113       Acc_Type      : Entity_Id);
114    --  Ada 2005 (AI-318-02): For a build-in-place call, if the result type has
115    --  controlled parts, add an actual parameter that is a pointer to
116    --  appropriate finalization list. The finalization list is that of the
117    --  current scope, except for "new Acc'(F(...))" in which case it's the
118    --  finalization list of the access type returned by the allocator. Acc_Type
119    --  is that type in the allocator case; Empty otherwise.
120
121    procedure Add_Task_Actuals_To_Build_In_Place_Call
122      (Function_Call : Node_Id;
123       Function_Id   : Entity_Id;
124       Master_Actual : Node_Id);
125    --  Ada 2005 (AI-318-02): For a build-in-place call, if the result type
126    --  contains tasks, add two actual parameters: the master, and a pointer to
127    --  the caller's activation chain. Master_Actual is the actual parameter
128    --  expression to pass for the master. In most cases, this is the current
129    --  master (_master). The two exceptions are: If the function call is the
130    --  initialization expression for an allocator, we pass the master of the
131    --  access type. If the function call is the initialization expression for
132    --  a return object, we pass along the master passed in by the caller. The
133    --  activation chain to pass is always the local one.
134
135    procedure Check_Overriding_Operation (Subp : Entity_Id);
136    --  Subp is a dispatching operation. Check whether it may override an
137    --  inherited private operation, in which case its DT entry is that of
138    --  the hidden operation, not the one it may have received earlier.
139    --  This must be done before emitting the code to set the corresponding
140    --  DT to the address of the subprogram. The actual placement of Subp in
141    --  the proper place in the list of primitive operations is done in
142    --  Declare_Inherited_Private_Subprograms, which also has to deal with
143    --  implicit operations. This duplication is unavoidable for now???
144
145    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
146    --  This procedure is called only if the subprogram body N, whose spec
147    --  has the given entity Spec, contains a parameterless recursive call.
148    --  It attempts to generate runtime code to detect if this a case of
149    --  infinite recursion.
150    --
151    --  The body is scanned to determine dependencies. If the only external
152    --  dependencies are on a small set of scalar variables, then the values
153    --  of these variables are captured on entry to the subprogram, and if
154    --  the values are not changed for the call, we know immediately that
155    --  we have an infinite recursion.
156
157    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id);
158    --  For each actual of an in-out or out parameter which is a numeric
159    --  (view) conversion of the form T (A), where A denotes a variable,
160    --  we insert the declaration:
161    --
162    --    Temp : T[ := T (A)];
163    --
164    --  prior to the call. Then we replace the actual with a reference to Temp,
165    --  and append the assignment:
166    --
167    --    A := TypeA (Temp);
168    --
169    --  after the call. Here TypeA is the actual type of variable A.
170    --  For out parameters, the initial declaration has no expression.
171    --  If A is not an entity name, we generate instead:
172    --
173    --    Var  : TypeA renames A;
174    --    Temp : T := Var;       --  omitting expression for out parameter.
175    --    ...
176    --    Var := TypeA (Temp);
177    --
178    --  For other in-out parameters, we emit the required constraint checks
179    --  before and/or after the call.
180    --
181    --  For all parameter modes, actuals that denote components and slices
182    --  of packed arrays are expanded into suitable temporaries.
183    --
184    --  For non-scalar objects that are possibly unaligned, add call by copy
185    --  code (copy in for IN and IN OUT, copy out for OUT and IN OUT).
186
187    procedure Expand_Inlined_Call
188     (N         : Node_Id;
189      Subp      : Entity_Id;
190      Orig_Subp : Entity_Id);
191    --  If called subprogram can be inlined by the front-end, retrieve the
192    --  analyzed body, replace formals with actuals and expand call in place.
193    --  Generate thunks for actuals that are expressions, and insert the
194    --  corresponding constant declarations before the call. If the original
195    --  call is to a derived operation, the return type is the one of the
196    --  derived operation, but the body is that of the original, so return
197    --  expressions in the body must be converted to the desired type (which
198    --  is simply not noted in the tree without inline expansion).
199
200    function Expand_Protected_Object_Reference
201      (N    : Node_Id;
202       Scop : Entity_Id) return Node_Id;
203
204    procedure Expand_Protected_Subprogram_Call
205      (N    : Node_Id;
206       Subp : Entity_Id;
207       Scop : Entity_Id);
208    --  A call to a protected subprogram within the protected object may appear
209    --  as a regular call. The list of actuals must be expanded to contain a
210    --  reference to the object itself, and the call becomes a call to the
211    --  corresponding protected subprogram.
212
213    ----------------------------------------------
214    -- Add_Access_Actual_To_Build_In_Place_Call --
215    ----------------------------------------------
216
217    procedure Add_Access_Actual_To_Build_In_Place_Call
218      (Function_Call : Node_Id;
219       Function_Id   : Entity_Id;
220       Return_Object : Node_Id;
221       Is_Access     : Boolean := False)
222    is
223       Loc            : constant Source_Ptr := Sloc (Function_Call);
224       Obj_Address    : Node_Id;
225       Obj_Acc_Formal : Entity_Id;
226
227    begin
228       --  Locate the implicit access parameter in the called function
229
230       Obj_Acc_Formal := Build_In_Place_Formal (Function_Id, BIP_Object_Access);
231
232       --  If no return object is provided, then pass null
233
234       if not Present (Return_Object) then
235          Obj_Address := Make_Null (Loc);
236          Set_Parent (Obj_Address, Function_Call);
237
238       --  If Return_Object is already an expression of an access type, then use
239       --  it directly, since it must be an access value denoting the return
240       --  object, and couldn't possibly be the return object itself.
241
242       elsif Is_Access then
243          Obj_Address := Return_Object;
244          Set_Parent (Obj_Address, Function_Call);
245
246       --  Apply Unrestricted_Access to caller's return object
247
248       else
249          Obj_Address :=
250             Make_Attribute_Reference (Loc,
251               Prefix         => Return_Object,
252               Attribute_Name => Name_Unrestricted_Access);
253
254          Set_Parent (Return_Object, Obj_Address);
255          Set_Parent (Obj_Address, Function_Call);
256       end if;
257
258       Analyze_And_Resolve (Obj_Address, Etype (Obj_Acc_Formal));
259
260       --  Build the parameter association for the new actual and add it to the
261       --  end of the function's actuals.
262
263       Add_Extra_Actual_To_Call (Function_Call, Obj_Acc_Formal, Obj_Address);
264    end Add_Access_Actual_To_Build_In_Place_Call;
265
266    --------------------------------------------------
267    -- Add_Alloc_Form_Actual_To_Build_In_Place_Call --
268    --------------------------------------------------
269
270    procedure Add_Alloc_Form_Actual_To_Build_In_Place_Call
271      (Function_Call  : Node_Id;
272       Function_Id    : Entity_Id;
273       Alloc_Form     : BIP_Allocation_Form := Unspecified;
274       Alloc_Form_Exp : Node_Id             := Empty)
275    is
276       Loc               : constant Source_Ptr := Sloc (Function_Call);
277       Alloc_Form_Actual : Node_Id;
278       Alloc_Form_Formal : Node_Id;
279
280    begin
281       --  The allocation form generally doesn't need to be passed in the case
282       --  of a constrained result subtype, since normally the caller performs
283       --  the allocation in that case. However this formal is still needed in
284       --  the case where the function has a tagged result, because generally
285       --  such functions can be called in a dispatching context and such calls
286       --  must be handled like calls to class-wide functions.
287
288       if Is_Constrained (Underlying_Type (Etype (Function_Id)))
289         and then not Is_Tagged_Type (Underlying_Type (Etype (Function_Id)))
290       then
291          return;
292       end if;
293
294       --  Locate the implicit allocation form parameter in the called function.
295       --  Maybe it would be better for each implicit formal of a build-in-place
296       --  function to have a flag or a Uint attribute to identify it. ???
297
298       Alloc_Form_Formal := Build_In_Place_Formal (Function_Id, BIP_Alloc_Form);
299
300       if Present (Alloc_Form_Exp) then
301          pragma Assert (Alloc_Form = Unspecified);
302
303          Alloc_Form_Actual := Alloc_Form_Exp;
304
305       else
306          pragma Assert (Alloc_Form /= Unspecified);
307
308          Alloc_Form_Actual :=
309            Make_Integer_Literal (Loc,
310              Intval => UI_From_Int (BIP_Allocation_Form'Pos (Alloc_Form)));
311       end if;
312
313       Analyze_And_Resolve (Alloc_Form_Actual, Etype (Alloc_Form_Formal));
314
315       --  Build the parameter association for the new actual and add it to the
316       --  end of the function's actuals.
317
318       Add_Extra_Actual_To_Call
319         (Function_Call, Alloc_Form_Formal, Alloc_Form_Actual);
320    end Add_Alloc_Form_Actual_To_Build_In_Place_Call;
321
322    ------------------------------
323    -- Add_Extra_Actual_To_Call --
324    ------------------------------
325
326    procedure Add_Extra_Actual_To_Call
327      (Subprogram_Call : Node_Id;
328       Extra_Formal    : Entity_Id;
329       Extra_Actual    : Node_Id)
330    is
331       Loc         : constant Source_Ptr := Sloc (Subprogram_Call);
332       Param_Assoc : Node_Id;
333
334    begin
335       Param_Assoc :=
336         Make_Parameter_Association (Loc,
337           Selector_Name             => New_Occurrence_Of (Extra_Formal, Loc),
338           Explicit_Actual_Parameter => Extra_Actual);
339
340       Set_Parent (Param_Assoc, Subprogram_Call);
341       Set_Parent (Extra_Actual, Param_Assoc);
342
343       if Present (Parameter_Associations (Subprogram_Call)) then
344          if Nkind (Last (Parameter_Associations (Subprogram_Call))) =
345               N_Parameter_Association
346          then
347
348             --  Find last named actual, and append
349
350             declare
351                L : Node_Id;
352             begin
353                L := First_Actual (Subprogram_Call);
354                while Present (L) loop
355                   if No (Next_Actual (L)) then
356                      Set_Next_Named_Actual (Parent (L), Extra_Actual);
357                      exit;
358                   end if;
359                   Next_Actual (L);
360                end loop;
361             end;
362
363          else
364             Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
365          end if;
366
367          Append (Param_Assoc, To => Parameter_Associations (Subprogram_Call));
368
369       else
370          Set_Parameter_Associations (Subprogram_Call, New_List (Param_Assoc));
371          Set_First_Named_Actual (Subprogram_Call, Extra_Actual);
372       end if;
373    end Add_Extra_Actual_To_Call;
374
375    --------------------------------------------------
376    -- Add_Final_List_Actual_To_Build_In_Place_Call --
377    --------------------------------------------------
378
379    procedure Add_Final_List_Actual_To_Build_In_Place_Call
380      (Function_Call : Node_Id;
381       Function_Id   : Entity_Id;
382       Acc_Type      : Entity_Id)
383    is
384       Loc               : constant Source_Ptr := Sloc (Function_Call);
385       Final_List        : Node_Id;
386       Final_List_Actual : Node_Id;
387       Final_List_Formal : Node_Id;
388
389    begin
390       --  No such extra parameter is needed if there are no controlled parts.
391       --  The test for Controlled_Type accounts for class-wide results (which
392       --  potentially have controlled parts, even if the root type doesn't),
393       --  and the test for a tagged result type is needed because calls to
394       --  such a function can in general occur in dispatching contexts, which
395       --  must be treated the same as a call to class-wide functions. Both of
396       --  these situations require that a finalization list be passed.
397
398       if not Controlled_Type (Underlying_Type (Etype (Function_Id)))
399         and then not Is_Tagged_Type (Underlying_Type (Etype (Function_Id)))
400       then
401          return;
402       end if;
403
404       --  Locate implicit finalization list parameter in the called function
405
406       Final_List_Formal := Build_In_Place_Formal (Function_Id, BIP_Final_List);
407
408       --  Create the actual which is a pointer to the appropriate finalization
409       --  list. Acc_Type is present if and only if this call is the
410       --  initialization of an allocator. Use the Current_Scope or the Acc_Type
411       --  as appropriate.
412
413       if Present (Acc_Type)
414         and then (Ekind (Acc_Type) = E_Anonymous_Access_Type
415                    or else
416                      Present (Associated_Final_Chain (Base_Type (Acc_Type))))
417       then
418          Final_List := Find_Final_List (Acc_Type);
419       else
420          Final_List := Find_Final_List (Current_Scope);
421       end if;
422
423       Final_List_Actual :=
424         Make_Attribute_Reference (Loc,
425           Prefix         => Final_List,
426           Attribute_Name => Name_Unrestricted_Access);
427
428       Analyze_And_Resolve (Final_List_Actual, Etype (Final_List_Formal));
429
430       --  Build the parameter association for the new actual and add it to the
431       --  end of the function's actuals.
432
433       Add_Extra_Actual_To_Call
434         (Function_Call, Final_List_Formal, Final_List_Actual);
435    end Add_Final_List_Actual_To_Build_In_Place_Call;
436
437    ---------------------------------------------
438    -- Add_Task_Actuals_To_Build_In_Place_Call --
439    ---------------------------------------------
440
441    procedure Add_Task_Actuals_To_Build_In_Place_Call
442      (Function_Call : Node_Id;
443       Function_Id   : Entity_Id;
444       Master_Actual : Node_Id)
445       --  Note: Master_Actual can be Empty, but only if there are no tasks
446    is
447       Loc               : constant Source_Ptr := Sloc (Function_Call);
448
449    begin
450       --  No such extra parameters are needed if there are no tasks
451
452       if not Has_Task (Etype (Function_Id)) then
453          return;
454       end if;
455
456       --  The master
457
458       declare
459          Master_Formal : Node_Id;
460       begin
461          --  Locate implicit master parameter in the called function
462
463          Master_Formal := Build_In_Place_Formal (Function_Id, BIP_Master);
464
465          Analyze_And_Resolve (Master_Actual, Etype (Master_Formal));
466
467          --  Build the parameter association for the new actual and add it to
468          --  the end of the function's actuals.
469
470          Add_Extra_Actual_To_Call
471            (Function_Call, Master_Formal, Master_Actual);
472       end;
473
474       --  The activation chain
475
476       declare
477          Activation_Chain_Actual : Node_Id;
478          Activation_Chain_Formal : Node_Id;
479       begin
480          --  Locate implicit activation chain parameter in the called function
481
482          Activation_Chain_Formal := Build_In_Place_Formal
483            (Function_Id, BIP_Activation_Chain);
484
485          --  Create the actual which is a pointer to the current activation
486          --  chain
487
488          Activation_Chain_Actual :=
489            Make_Attribute_Reference (Loc,
490              Prefix         => Make_Identifier (Loc, Name_uChain),
491              Attribute_Name => Name_Unrestricted_Access);
492
493          Analyze_And_Resolve
494            (Activation_Chain_Actual, Etype (Activation_Chain_Formal));
495
496          --  Build the parameter association for the new actual and add it to
497          --  the end of the function's actuals.
498
499          Add_Extra_Actual_To_Call
500            (Function_Call, Activation_Chain_Formal, Activation_Chain_Actual);
501       end;
502    end Add_Task_Actuals_To_Build_In_Place_Call;
503
504    -----------------------
505    -- BIP_Formal_Suffix --
506    -----------------------
507
508    function BIP_Formal_Suffix (Kind : BIP_Formal_Kind) return String is
509    begin
510       case Kind is
511          when BIP_Alloc_Form       =>
512             return "BIPalloc";
513          when BIP_Final_List       =>
514             return "BIPfinallist";
515          when BIP_Master           =>
516             return "BIPmaster";
517          when BIP_Activation_Chain =>
518             return "BIPactivationchain";
519          when BIP_Object_Access    =>
520             return "BIPaccess";
521       end case;
522    end BIP_Formal_Suffix;
523
524    ---------------------------
525    -- Build_In_Place_Formal --
526    ---------------------------
527
528    function Build_In_Place_Formal
529      (Func : Entity_Id;
530       Kind : BIP_Formal_Kind) return Entity_Id
531    is
532       Extra_Formal : Entity_Id := Extra_Formals (Func);
533
534    begin
535       --  Maybe it would be better for each implicit formal of a build-in-place
536       --  function to have a flag or a Uint attribute to identify it. ???
537
538       loop
539          pragma Assert (Present (Extra_Formal));
540          exit when
541            Chars (Extra_Formal) =
542              New_External_Name (Chars (Func), BIP_Formal_Suffix (Kind));
543          Next_Formal_With_Extras (Extra_Formal);
544       end loop;
545
546       return Extra_Formal;
547    end Build_In_Place_Formal;
548
549    --------------------------------
550    -- Check_Overriding_Operation --
551    --------------------------------
552
553    procedure Check_Overriding_Operation (Subp : Entity_Id) is
554       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
555       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
556       Op_Elmt : Elmt_Id;
557       Prim_Op : Entity_Id;
558       Par_Op  : Entity_Id;
559
560    begin
561       if Is_Derived_Type (Typ)
562         and then not Is_Private_Type (Typ)
563         and then In_Open_Scopes (Scope (Etype (Typ)))
564         and then Typ = Base_Type (Typ)
565       then
566          --  Subp overrides an inherited private operation if there is an
567          --  inherited operation with a different name than Subp (see
568          --  Derive_Subprogram) whose Alias is a hidden subprogram with the
569          --  same name as Subp.
570
571          Op_Elmt := First_Elmt (Op_List);
572          while Present (Op_Elmt) loop
573             Prim_Op := Node (Op_Elmt);
574             Par_Op  := Alias (Prim_Op);
575
576             if Present (Par_Op)
577               and then not Comes_From_Source (Prim_Op)
578               and then Chars (Prim_Op) /= Chars (Par_Op)
579               and then Chars (Par_Op) = Chars (Subp)
580               and then Is_Hidden (Par_Op)
581               and then Type_Conformant (Prim_Op, Subp)
582             then
583                Set_DT_Position (Subp, DT_Position (Prim_Op));
584             end if;
585
586             Next_Elmt (Op_Elmt);
587          end loop;
588       end if;
589    end Check_Overriding_Operation;
590
591    -------------------------------
592    -- Detect_Infinite_Recursion --
593    -------------------------------
594
595    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
596       Loc : constant Source_Ptr := Sloc (N);
597
598       Var_List : constant Elist_Id := New_Elmt_List;
599       --  List of globals referenced by body of procedure
600
601       Call_List : constant Elist_Id := New_Elmt_List;
602       --  List of recursive calls in body of procedure
603
604       Shad_List : constant Elist_Id := New_Elmt_List;
605       --  List of entity id's for entities created to capture the value of
606       --  referenced globals on entry to the procedure.
607
608       Scop : constant Uint := Scope_Depth (Spec);
609       --  This is used to record the scope depth of the current procedure, so
610       --  that we can identify global references.
611
612       Max_Vars : constant := 4;
613       --  Do not test more than four global variables
614
615       Count_Vars : Natural := 0;
616       --  Count variables found so far
617
618       Var  : Entity_Id;
619       Elm  : Elmt_Id;
620       Ent  : Entity_Id;
621       Call : Elmt_Id;
622       Decl : Node_Id;
623       Test : Node_Id;
624       Elm1 : Elmt_Id;
625       Elm2 : Elmt_Id;
626       Last : Node_Id;
627
628       function Process (Nod : Node_Id) return Traverse_Result;
629       --  Function to traverse the subprogram body (using Traverse_Func)
630
631       -------------
632       -- Process --
633       -------------
634
635       function Process (Nod : Node_Id) return Traverse_Result is
636       begin
637          --  Procedure call
638
639          if Nkind (Nod) = N_Procedure_Call_Statement then
640
641             --  Case of one of the detected recursive calls
642
643             if Is_Entity_Name (Name (Nod))
644               and then Has_Recursive_Call (Entity (Name (Nod)))
645               and then Entity (Name (Nod)) = Spec
646             then
647                Append_Elmt (Nod, Call_List);
648                return Skip;
649
650             --  Any other procedure call may have side effects
651
652             else
653                return Abandon;
654             end if;
655
656          --  A call to a pure function can always be ignored
657
658          elsif Nkind (Nod) = N_Function_Call
659            and then Is_Entity_Name (Name (Nod))
660            and then Is_Pure (Entity (Name (Nod)))
661          then
662             return Skip;
663
664          --  Case of an identifier reference
665
666          elsif Nkind (Nod) = N_Identifier then
667             Ent := Entity (Nod);
668
669             --  If no entity, then ignore the reference
670
671             --  Not clear why this can happen. To investigate, remove this
672             --  test and look at the crash that occurs here in 3401-004 ???
673
674             if No (Ent) then
675                return Skip;
676
677             --  Ignore entities with no Scope, again not clear how this
678             --  can happen, to investigate, look at 4108-008 ???
679
680             elsif No (Scope (Ent)) then
681                return Skip;
682
683             --  Ignore the reference if not to a more global object
684
685             elsif Scope_Depth (Scope (Ent)) >= Scop then
686                return Skip;
687
688             --  References to types, exceptions and constants are always OK
689
690             elsif Is_Type (Ent)
691               or else Ekind (Ent) = E_Exception
692               or else Ekind (Ent) = E_Constant
693             then
694                return Skip;
695
696             --  If other than a non-volatile scalar variable, we have some
697             --  kind of global reference (e.g. to a function) that we cannot
698             --  deal with so we forget the attempt.
699
700             elsif Ekind (Ent) /= E_Variable
701               or else not Is_Scalar_Type (Etype (Ent))
702               or else Treat_As_Volatile (Ent)
703             then
704                return Abandon;
705
706             --  Otherwise we have a reference to a global scalar
707
708             else
709                --  Loop through global entities already detected
710
711                Elm := First_Elmt (Var_List);
712                loop
713                   --  If not detected before, record this new global reference
714
715                   if No (Elm) then
716                      Count_Vars := Count_Vars + 1;
717
718                      if Count_Vars <= Max_Vars then
719                         Append_Elmt (Entity (Nod), Var_List);
720                      else
721                         return Abandon;
722                      end if;
723
724                      exit;
725
726                   --  If recorded before, ignore
727
728                   elsif Node (Elm) = Entity (Nod) then
729                      return Skip;
730
731                   --  Otherwise keep looking
732
733                   else
734                      Next_Elmt (Elm);
735                   end if;
736                end loop;
737
738                return Skip;
739             end if;
740
741          --  For all other node kinds, recursively visit syntactic children
742
743          else
744             return OK;
745          end if;
746       end Process;
747
748       function Traverse_Body is new Traverse_Func (Process);
749
750    --  Start of processing for Detect_Infinite_Recursion
751
752    begin
753       --  Do not attempt detection in No_Implicit_Conditional mode, since we
754       --  won't be able to generate the code to handle the recursion in any
755       --  case.
756
757       if Restriction_Active (No_Implicit_Conditionals) then
758          return;
759       end if;
760
761       --  Otherwise do traversal and quit if we get abandon signal
762
763       if Traverse_Body (N) = Abandon then
764          return;
765
766       --  We must have a call, since Has_Recursive_Call was set. If not just
767       --  ignore (this is only an error check, so if we have a funny situation,
768       --  due to bugs or errors, we do not want to bomb!)
769
770       elsif Is_Empty_Elmt_List (Call_List) then
771          return;
772       end if;
773
774       --  Here is the case where we detect recursion at compile time
775
776       --  Push our current scope for analyzing the declarations and code that
777       --  we will insert for the checking.
778
779       Push_Scope (Spec);
780
781       --  This loop builds temporary variables for each of the referenced
782       --  globals, so that at the end of the loop the list Shad_List contains
783       --  these temporaries in one-to-one correspondence with the elements in
784       --  Var_List.
785
786       Last := Empty;
787       Elm := First_Elmt (Var_List);
788       while Present (Elm) loop
789          Var := Node (Elm);
790          Ent :=
791            Make_Defining_Identifier (Loc,
792              Chars => New_Internal_Name ('S'));
793          Append_Elmt (Ent, Shad_List);
794
795          --  Insert a declaration for this temporary at the start of the
796          --  declarations for the procedure. The temporaries are declared as
797          --  constant objects initialized to the current values of the
798          --  corresponding temporaries.
799
800          Decl :=
801            Make_Object_Declaration (Loc,
802              Defining_Identifier => Ent,
803              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
804              Constant_Present    => True,
805              Expression          => New_Occurrence_Of (Var, Loc));
806
807          if No (Last) then
808             Prepend (Decl, Declarations (N));
809          else
810             Insert_After (Last, Decl);
811          end if;
812
813          Last := Decl;
814          Analyze (Decl);
815          Next_Elmt (Elm);
816       end loop;
817
818       --  Loop through calls
819
820       Call := First_Elmt (Call_List);
821       while Present (Call) loop
822
823          --  Build a predicate expression of the form
824
825          --    True
826          --      and then global1 = temp1
827          --      and then global2 = temp2
828          --      ...
829
830          --  This predicate determines if any of the global values
831          --  referenced by the procedure have changed since the
832          --  current call, if not an infinite recursion is assured.
833
834          Test := New_Occurrence_Of (Standard_True, Loc);
835
836          Elm1 := First_Elmt (Var_List);
837          Elm2 := First_Elmt (Shad_List);
838          while Present (Elm1) loop
839             Test :=
840               Make_And_Then (Loc,
841                 Left_Opnd  => Test,
842                 Right_Opnd =>
843                   Make_Op_Eq (Loc,
844                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
845                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
846
847             Next_Elmt (Elm1);
848             Next_Elmt (Elm2);
849          end loop;
850
851          --  Now we replace the call with the sequence
852
853          --    if no-changes (see above) then
854          --       raise Storage_Error;
855          --    else
856          --       original-call
857          --    end if;
858
859          Rewrite (Node (Call),
860            Make_If_Statement (Loc,
861              Condition       => Test,
862              Then_Statements => New_List (
863                Make_Raise_Storage_Error (Loc,
864                  Reason => SE_Infinite_Recursion)),
865
866              Else_Statements => New_List (
867                Relocate_Node (Node (Call)))));
868
869          Analyze (Node (Call));
870
871          Next_Elmt (Call);
872       end loop;
873
874       --  Remove temporary scope stack entry used for analysis
875
876       Pop_Scope;
877    end Detect_Infinite_Recursion;
878
879    --------------------
880    -- Expand_Actuals --
881    --------------------
882
883    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
884       Loc       : constant Source_Ptr := Sloc (N);
885       Actual    : Node_Id;
886       Formal    : Entity_Id;
887       N_Node    : Node_Id;
888       Post_Call : List_Id;
889       E_Formal  : Entity_Id;
890
891       procedure Add_Call_By_Copy_Code;
892       --  For cases where the parameter must be passed by copy, this routine
893       --  generates a temporary variable into which the actual is copied and
894       --  then passes this as the parameter. For an OUT or IN OUT parameter,
895       --  an assignment is also generated to copy the result back. The call
896       --  also takes care of any constraint checks required for the type
897       --  conversion case (on both the way in and the way out).
898
899       procedure Add_Simple_Call_By_Copy_Code;
900       --  This is similar to the above, but is used in cases where we know
901       --  that all that is needed is to simply create a temporary and copy
902       --  the value in and out of the temporary.
903
904       procedure Check_Fortran_Logical;
905       --  A value of type Logical that is passed through a formal parameter
906       --  must be normalized because .TRUE. usually does not have the same
907       --  representation as True. We assume that .FALSE. = False = 0.
908       --  What about functions that return a logical type ???
909
910       function Is_Legal_Copy return Boolean;
911       --  Check that an actual can be copied before generating the temporary
912       --  to be used in the call. If the actual is of a by_reference type then
913       --  the program is illegal (this can only happen in the presence of
914       --  rep. clauses that force an incorrect alignment). If the formal is
915       --  a by_reference parameter imposed by a DEC pragma, emit a warning to
916       --  the effect that this might lead to unaligned arguments.
917
918       function Make_Var (Actual : Node_Id) return Entity_Id;
919       --  Returns an entity that refers to the given actual parameter,
920       --  Actual (not including any type conversion). If Actual is an
921       --  entity name, then this entity is returned unchanged, otherwise
922       --  a renaming is created to provide an entity for the actual.
923
924       procedure Reset_Packed_Prefix;
925       --  The expansion of a packed array component reference is delayed in
926       --  the context of a call. Now we need to complete the expansion, so we
927       --  unmark the analyzed bits in all prefixes.
928
929       ---------------------------
930       -- Add_Call_By_Copy_Code --
931       ---------------------------
932
933       procedure Add_Call_By_Copy_Code is
934          Expr  : Node_Id;
935          Init  : Node_Id;
936          Temp  : Entity_Id;
937          Indic : Node_Id;
938          Var   : Entity_Id;
939          F_Typ : constant Entity_Id := Etype (Formal);
940          V_Typ : Entity_Id;
941          Crep  : Boolean;
942
943       begin
944          if not Is_Legal_Copy then
945             return;
946          end if;
947
948          Temp :=
949            Make_Defining_Identifier (Loc,
950              Chars => New_Internal_Name ('T'));
951
952          --  Use formal type for temp, unless formal type is an unconstrained
953          --  array, in which case we don't have to worry about bounds checks,
954          --  and we use the actual type, since that has appropriate bounds.
955
956          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
957             Indic := New_Occurrence_Of (Etype (Actual), Loc);
958          else
959             Indic := New_Occurrence_Of (Etype (Formal), Loc);
960          end if;
961
962          if Nkind (Actual) = N_Type_Conversion then
963             V_Typ := Etype (Expression (Actual));
964
965             --  If the formal is an (in-)out parameter, capture the name
966             --  of the variable in order to build the post-call assignment.
967
968             Var := Make_Var (Expression (Actual));
969
970             Crep := not Same_Representation
971                           (F_Typ, Etype (Expression (Actual)));
972
973          else
974             V_Typ := Etype (Actual);
975             Var   := Make_Var (Actual);
976             Crep  := False;
977          end if;
978
979          --  Setup initialization for case of in out parameter, or an out
980          --  parameter where the formal is an unconstrained array (in the
981          --  latter case, we have to pass in an object with bounds).
982
983          --  If this is an out parameter, the initial copy is wasteful, so as
984          --  an optimization for the one-dimensional case we extract the
985          --  bounds of the actual and build an uninitialized temporary of the
986          --  right size.
987
988          if Ekind (Formal) = E_In_Out_Parameter
989            or else (Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ))
990          then
991             if Nkind (Actual) = N_Type_Conversion then
992                if Conversion_OK (Actual) then
993                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
994                else
995                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
996                end if;
997
998             elsif Ekind (Formal) = E_Out_Parameter
999               and then Is_Array_Type (F_Typ)
1000               and then Number_Dimensions (F_Typ) = 1
1001               and then not Has_Non_Null_Base_Init_Proc (F_Typ)
1002             then
1003                --  Actual is a one-dimensional array or slice, and the type
1004                --  requires no initialization. Create a temporary of the
1005                --  right size, but do not copy actual into it (optimization).
1006
1007                Init := Empty;
1008                Indic :=
1009                  Make_Subtype_Indication (Loc,
1010                    Subtype_Mark =>
1011                      New_Occurrence_Of (F_Typ, Loc),
1012                    Constraint   =>
1013                      Make_Index_Or_Discriminant_Constraint (Loc,
1014                        Constraints => New_List (
1015                          Make_Range (Loc,
1016                            Low_Bound  =>
1017                              Make_Attribute_Reference (Loc,
1018                                Prefix => New_Occurrence_Of (Var, Loc),
1019                                Attribute_name => Name_First),
1020                            High_Bound =>
1021                              Make_Attribute_Reference (Loc,
1022                                Prefix => New_Occurrence_Of (Var, Loc),
1023                                Attribute_Name => Name_Last)))));
1024
1025             else
1026                Init := New_Occurrence_Of (Var, Loc);
1027             end if;
1028
1029          --  An initialization is created for packed conversions as
1030          --  actuals for out parameters to enable Make_Object_Declaration
1031          --  to determine the proper subtype for N_Node. Note that this
1032          --  is wasteful because the extra copying on the call side is
1033          --  not required for such out parameters. ???
1034
1035          elsif Ekind (Formal) = E_Out_Parameter
1036            and then Nkind (Actual) = N_Type_Conversion
1037            and then (Is_Bit_Packed_Array (F_Typ)
1038                        or else
1039                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
1040          then
1041             if Conversion_OK (Actual) then
1042                Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1043             else
1044                Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1045             end if;
1046
1047          elsif Ekind (Formal) = E_In_Parameter then
1048
1049             --  Handle the case in which the actual is a type conversion
1050
1051             if Nkind (Actual) = N_Type_Conversion then
1052                if Conversion_OK (Actual) then
1053                   Init := OK_Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1054                else
1055                   Init := Convert_To (F_Typ, New_Occurrence_Of (Var, Loc));
1056                end if;
1057             else
1058                Init := New_Occurrence_Of (Var, Loc);
1059             end if;
1060
1061          else
1062             Init := Empty;
1063          end if;
1064
1065          N_Node :=
1066            Make_Object_Declaration (Loc,
1067              Defining_Identifier => Temp,
1068              Object_Definition   => Indic,
1069              Expression          => Init);
1070          Set_Assignment_OK (N_Node);
1071          Insert_Action (N, N_Node);
1072
1073          --  Now, normally the deal here is that we use the defining
1074          --  identifier created by that object declaration. There is
1075          --  one exception to this. In the change of representation case
1076          --  the above declaration will end up looking like:
1077
1078          --    temp : type := identifier;
1079
1080          --  And in this case we might as well use the identifier directly
1081          --  and eliminate the temporary. Note that the analysis of the
1082          --  declaration was not a waste of time in that case, since it is
1083          --  what generated the necessary change of representation code. If
1084          --  the change of representation introduced additional code, as in
1085          --  a fixed-integer conversion, the expression is not an identifier
1086          --  and must be kept.
1087
1088          if Crep
1089            and then Present (Expression (N_Node))
1090            and then Is_Entity_Name (Expression (N_Node))
1091          then
1092             Temp := Entity (Expression (N_Node));
1093             Rewrite (N_Node, Make_Null_Statement (Loc));
1094          end if;
1095
1096          --  For IN parameter, all we do is to replace the actual
1097
1098          if Ekind (Formal) = E_In_Parameter then
1099             Rewrite (Actual, New_Reference_To (Temp, Loc));
1100             Analyze (Actual);
1101
1102          --  Processing for OUT or IN OUT parameter
1103
1104          else
1105             --  Kill current value indications for the temporary variable we
1106             --  created, since we just passed it as an OUT parameter.
1107
1108             Kill_Current_Values (Temp);
1109
1110             --  If type conversion, use reverse conversion on exit
1111
1112             if Nkind (Actual) = N_Type_Conversion then
1113                if Conversion_OK (Actual) then
1114                   Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1115                else
1116                   Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
1117                end if;
1118             else
1119                Expr := New_Occurrence_Of (Temp, Loc);
1120             end if;
1121
1122             Rewrite (Actual, New_Reference_To (Temp, Loc));
1123             Analyze (Actual);
1124
1125             --  If the actual is a conversion of a packed reference, it may
1126             --  already have been expanded by Remove_Side_Effects, and the
1127             --  resulting variable is a temporary which does not designate
1128             --  the proper out-parameter, which may not be addressable. In
1129             --  that case, generate an assignment to the original expression
1130             --  (before expansion of the  packed reference) so that the proper
1131             --  expansion of assignment to a packed component can take place.
1132
1133             declare
1134                Obj : Node_Id;
1135                Lhs : Node_Id;
1136
1137             begin
1138                if Is_Renaming_Of_Object (Var)
1139                  and then Nkind (Renamed_Object (Var)) = N_Selected_Component
1140                  and then Is_Entity_Name (Prefix (Renamed_Object (Var)))
1141                  and then Nkind (Original_Node (Prefix (Renamed_Object (Var))))
1142                    = N_Indexed_Component
1143                  and then
1144                    Has_Non_Standard_Rep (Etype (Prefix (Renamed_Object (Var))))
1145                then
1146                   Obj := Renamed_Object (Var);
1147                   Lhs :=
1148                     Make_Selected_Component (Loc,
1149                       Prefix        =>
1150                         New_Copy_Tree (Original_Node (Prefix (Obj))),
1151                       Selector_Name => New_Copy (Selector_Name (Obj)));
1152                   Reset_Analyzed_Flags (Lhs);
1153
1154                else
1155                   Lhs :=  New_Occurrence_Of (Var, Loc);
1156                end if;
1157
1158                Set_Assignment_OK (Lhs);
1159
1160                Append_To (Post_Call,
1161                  Make_Assignment_Statement (Loc,
1162                    Name       => Lhs,
1163                    Expression => Expr));
1164             end;
1165          end if;
1166
1167       end Add_Call_By_Copy_Code;
1168
1169       ----------------------------------
1170       -- Add_Simple_Call_By_Copy_Code --
1171       ----------------------------------
1172
1173       procedure Add_Simple_Call_By_Copy_Code is
1174          Temp   : Entity_Id;
1175          Decl   : Node_Id;
1176          Incod  : Node_Id;
1177          Outcod : Node_Id;
1178          Lhs    : Node_Id;
1179          Rhs    : Node_Id;
1180          Indic  : Node_Id;
1181          F_Typ  : constant Entity_Id := Etype (Formal);
1182
1183       begin
1184          if not Is_Legal_Copy then
1185             return;
1186          end if;
1187
1188          --  Use formal type for temp, unless formal type is an unconstrained
1189          --  array, in which case we don't have to worry about bounds checks,
1190          --  and we use the actual type, since that has appropriate bounds.
1191
1192          if Is_Array_Type (F_Typ) and then not Is_Constrained (F_Typ) then
1193             Indic := New_Occurrence_Of (Etype (Actual), Loc);
1194          else
1195             Indic := New_Occurrence_Of (Etype (Formal), Loc);
1196          end if;
1197
1198          --  Prepare to generate code
1199
1200          Reset_Packed_Prefix;
1201
1202          Temp :=
1203            Make_Defining_Identifier (Loc,
1204              Chars => New_Internal_Name ('T'));
1205          Incod  := Relocate_Node (Actual);
1206          Outcod := New_Copy_Tree (Incod);
1207
1208          --  Generate declaration of temporary variable, initializing it
1209          --  with the input parameter unless we have an OUT formal or
1210          --  this is an initialization call.
1211
1212          --  If the formal is an out parameter with discriminants, the
1213          --  discriminants must be captured even if the rest of the object
1214          --  is in principle uninitialized, because the discriminants may
1215          --  be read by the called subprogram.
1216
1217          if Ekind (Formal) = E_Out_Parameter then
1218             Incod := Empty;
1219
1220             if Has_Discriminants (Etype (Formal)) then
1221                Indic := New_Occurrence_Of (Etype (Actual), Loc);
1222             end if;
1223
1224          elsif Inside_Init_Proc then
1225
1226             --  Could use a comment here to match comment below ???
1227
1228             if Nkind (Actual) /= N_Selected_Component
1229               or else
1230                 not Has_Discriminant_Dependent_Constraint
1231                   (Entity (Selector_Name (Actual)))
1232             then
1233                Incod := Empty;
1234
1235             --  Otherwise, keep the component in order to generate the proper
1236             --  actual subtype, that depends on enclosing discriminants.
1237
1238             else
1239                null;
1240             end if;
1241          end if;
1242
1243          Decl :=
1244            Make_Object_Declaration (Loc,
1245              Defining_Identifier => Temp,
1246              Object_Definition   => Indic,
1247              Expression          => Incod);
1248
1249          if Inside_Init_Proc
1250            and then No (Incod)
1251          then
1252             --  If the call is to initialize a component of a composite type,
1253             --  and the component does not depend on discriminants, use the
1254             --  actual type of the component. This is required in case the
1255             --  component is constrained, because in general the formal of the
1256             --  initialization procedure will be unconstrained. Note that if
1257             --  the component being initialized is constrained by an enclosing
1258             --  discriminant, the presence of the initialization in the
1259             --  declaration will generate an expression for the actual subtype.
1260
1261             Set_No_Initialization (Decl);
1262             Set_Object_Definition (Decl,
1263               New_Occurrence_Of (Etype (Actual), Loc));
1264          end if;
1265
1266          Insert_Action (N, Decl);
1267
1268          --  The actual is simply a reference to the temporary
1269
1270          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
1271
1272          --  Generate copy out if OUT or IN OUT parameter
1273
1274          if Ekind (Formal) /= E_In_Parameter then
1275             Lhs := Outcod;
1276             Rhs := New_Occurrence_Of (Temp, Loc);
1277
1278             --  Deal with conversion
1279
1280             if Nkind (Lhs) = N_Type_Conversion then
1281                Lhs := Expression (Lhs);
1282                Rhs := Convert_To (Etype (Actual), Rhs);
1283             end if;
1284
1285             Append_To (Post_Call,
1286               Make_Assignment_Statement (Loc,
1287                 Name       => Lhs,
1288                 Expression => Rhs));
1289             Set_Assignment_OK (Name (Last (Post_Call)));
1290          end if;
1291       end Add_Simple_Call_By_Copy_Code;
1292
1293       ---------------------------
1294       -- Check_Fortran_Logical --
1295       ---------------------------
1296
1297       procedure Check_Fortran_Logical is
1298          Logical : constant Entity_Id := Etype (Formal);
1299          Var     : Entity_Id;
1300
1301       --  Note: this is very incomplete, e.g. it does not handle arrays
1302       --  of logical values. This is really not the right approach at all???)
1303
1304       begin
1305          if Convention (Subp) = Convention_Fortran
1306            and then Root_Type (Etype (Formal)) = Standard_Boolean
1307            and then Ekind (Formal) /= E_In_Parameter
1308          then
1309             Var := Make_Var (Actual);
1310             Append_To (Post_Call,
1311               Make_Assignment_Statement (Loc,
1312                 Name => New_Occurrence_Of (Var, Loc),
1313                 Expression =>
1314                   Unchecked_Convert_To (
1315                     Logical,
1316                     Make_Op_Ne (Loc,
1317                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
1318                       Right_Opnd =>
1319                         Unchecked_Convert_To (
1320                           Logical,
1321                           New_Occurrence_Of (Standard_False, Loc))))));
1322          end if;
1323       end Check_Fortran_Logical;
1324
1325       -------------------
1326       -- Is_Legal_Copy --
1327       -------------------
1328
1329       function Is_Legal_Copy return Boolean is
1330       begin
1331          --  An attempt to copy a value of such a type can only occur if
1332          --  representation clauses give the actual a misaligned address.
1333
1334          if Is_By_Reference_Type (Etype (Formal)) then
1335             Error_Msg_N
1336               ("misaligned actual cannot be passed by reference", Actual);
1337             return False;
1338
1339          --  For users of Starlet, we assume that the specification of by-
1340          --  reference mechanism is mandatory. This may lead to unaligned
1341          --  objects but at least for DEC legacy code it is known to work.
1342          --  The warning will alert users of this code that a problem may
1343          --  be lurking.
1344
1345          elsif Mechanism (Formal) = By_Reference
1346            and then Is_Valued_Procedure (Scope (Formal))
1347          then
1348             Error_Msg_N
1349               ("by_reference actual may be misaligned?", Actual);
1350             return False;
1351
1352          else
1353             return True;
1354          end if;
1355       end Is_Legal_Copy;
1356
1357       --------------
1358       -- Make_Var --
1359       --------------
1360
1361       function Make_Var (Actual : Node_Id) return Entity_Id is
1362          Var : Entity_Id;
1363
1364       begin
1365          if Is_Entity_Name (Actual) then
1366             return Entity (Actual);
1367
1368          else
1369             Var :=
1370               Make_Defining_Identifier (Loc,
1371                 Chars => New_Internal_Name ('T'));
1372
1373             N_Node :=
1374               Make_Object_Renaming_Declaration (Loc,
1375                 Defining_Identifier => Var,
1376                 Subtype_Mark        =>
1377                   New_Occurrence_Of (Etype (Actual), Loc),
1378                 Name                => Relocate_Node (Actual));
1379
1380             Insert_Action (N, N_Node);
1381             return Var;
1382          end if;
1383       end Make_Var;
1384
1385       -------------------------
1386       -- Reset_Packed_Prefix --
1387       -------------------------
1388
1389       procedure Reset_Packed_Prefix is
1390          Pfx : Node_Id := Actual;
1391       begin
1392          loop
1393             Set_Analyzed (Pfx, False);
1394             exit when Nkind (Pfx) /= N_Selected_Component
1395               and then Nkind (Pfx) /= N_Indexed_Component;
1396             Pfx := Prefix (Pfx);
1397          end loop;
1398       end Reset_Packed_Prefix;
1399
1400    --  Start of processing for Expand_Actuals
1401
1402    begin
1403       Post_Call := New_List;
1404
1405       Formal := First_Formal (Subp);
1406       Actual := First_Actual (N);
1407       while Present (Formal) loop
1408          E_Formal := Etype (Formal);
1409
1410          if Is_Scalar_Type (E_Formal)
1411            or else Nkind (Actual) = N_Slice
1412          then
1413             Check_Fortran_Logical;
1414
1415          --  RM 6.4.1 (11)
1416
1417          elsif Ekind (Formal) /= E_Out_Parameter then
1418
1419             --  The unusual case of the current instance of a protected type
1420             --  requires special handling. This can only occur in the context
1421             --  of a call within the body of a protected operation.
1422
1423             if Is_Entity_Name (Actual)
1424               and then Ekind (Entity (Actual)) = E_Protected_Type
1425               and then In_Open_Scopes (Entity (Actual))
1426             then
1427                if Scope (Subp) /= Entity (Actual) then
1428                   Error_Msg_N ("operation outside protected type may not "
1429                     & "call back its protected operations?", Actual);
1430                end if;
1431
1432                Rewrite (Actual,
1433                  Expand_Protected_Object_Reference (N, Entity (Actual)));
1434             end if;
1435
1436             --  Ada 2005 (AI-318-02): If the actual parameter is a call to a
1437             --  build-in-place function, then a temporary return object needs
1438             --  to be created and access to it must be passed to the function.
1439             --  Currently we limit such functions to those with inherently
1440             --  limited result subtypes, but eventually we plan to expand the
1441             --  functions that are treated as build-in-place to include other
1442             --  composite result types.
1443
1444             if Ada_Version >= Ada_05
1445               and then Is_Build_In_Place_Function_Call (Actual)
1446             then
1447                Make_Build_In_Place_Call_In_Anonymous_Context (Actual);
1448             end if;
1449
1450             Apply_Constraint_Check (Actual, E_Formal);
1451
1452          --  Out parameter case. No constraint checks on access type
1453          --  RM 6.4.1 (13)
1454
1455          elsif Is_Access_Type (E_Formal) then
1456             null;
1457
1458          --  RM 6.4.1 (14)
1459
1460          elsif Has_Discriminants (Base_Type (E_Formal))
1461            or else Has_Non_Null_Base_Init_Proc (E_Formal)
1462          then
1463             Apply_Constraint_Check (Actual, E_Formal);
1464
1465          --  RM 6.4.1 (15)
1466
1467          else
1468             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
1469          end if;
1470
1471          --  Processing for IN-OUT and OUT parameters
1472
1473          if Ekind (Formal) /= E_In_Parameter then
1474
1475             --  For type conversions of arrays, apply length/range checks
1476
1477             if Is_Array_Type (E_Formal)
1478               and then Nkind (Actual) = N_Type_Conversion
1479             then
1480                if Is_Constrained (E_Formal) then
1481                   Apply_Length_Check (Expression (Actual), E_Formal);
1482                else
1483                   Apply_Range_Check (Expression (Actual), E_Formal);
1484                end if;
1485             end if;
1486
1487             --  If argument is a type conversion for a type that is passed
1488             --  by copy, then we must pass the parameter by copy.
1489
1490             if Nkind (Actual) = N_Type_Conversion
1491               and then
1492                 (Is_Numeric_Type (E_Formal)
1493                   or else Is_Access_Type (E_Formal)
1494                   or else Is_Enumeration_Type (E_Formal)
1495                   or else Is_Bit_Packed_Array (Etype (Formal))
1496                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
1497
1498                   --  Also pass by copy if change of representation
1499
1500                   or else not Same_Representation
1501                                (Etype (Formal),
1502                                 Etype (Expression (Actual))))
1503             then
1504                Add_Call_By_Copy_Code;
1505
1506             --  References to components of bit packed arrays are expanded
1507             --  at this point, rather than at the point of analysis of the
1508             --  actuals, to handle the expansion of the assignment to
1509             --  [in] out parameters.
1510
1511             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1512                Add_Simple_Call_By_Copy_Code;
1513
1514             --  If a non-scalar actual is possibly bit-aligned, we need a copy
1515             --  because the back-end cannot cope with such objects. In other
1516             --  cases where alignment forces a copy, the back-end generates
1517             --  it properly. It should not be generated unconditionally in the
1518             --  front-end because it does not know precisely the alignment
1519             --  requirements of the target, and makes too conservative an
1520             --  estimate, leading to superfluous copies or spurious errors
1521             --  on by-reference parameters.
1522
1523             elsif Nkind (Actual) = N_Selected_Component
1524               and then
1525                 Component_May_Be_Bit_Aligned (Entity (Selector_Name (Actual)))
1526               and then not Represented_As_Scalar (Etype (Formal))
1527             then
1528                Add_Simple_Call_By_Copy_Code;
1529
1530             --  References to slices of bit packed arrays are expanded
1531
1532             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1533                Add_Call_By_Copy_Code;
1534
1535             --  References to possibly unaligned slices of arrays are expanded
1536
1537             elsif Is_Possibly_Unaligned_Slice (Actual) then
1538                Add_Call_By_Copy_Code;
1539
1540             --  Deal with access types where the actual subtype and the
1541             --  formal subtype are not the same, requiring a check.
1542
1543             --  It is necessary to exclude tagged types because of "downward
1544             --  conversion" errors and a strange assertion error in namet
1545             --  from gnatf in bug 1215-001 ???
1546
1547             elsif Is_Access_Type (E_Formal)
1548               and then not Same_Type (E_Formal, Etype (Actual))
1549               and then not Is_Tagged_Type (Designated_Type (E_Formal))
1550             then
1551                Add_Call_By_Copy_Code;
1552
1553             --  If the actual is not a scalar and is marked for volatile
1554             --  treatment, whereas the formal is not volatile, then pass
1555             --  by copy unless it is a by-reference type.
1556
1557             elsif Is_Entity_Name (Actual)
1558               and then Treat_As_Volatile (Entity (Actual))
1559               and then not Is_By_Reference_Type (Etype (Actual))
1560               and then not Is_Scalar_Type (Etype (Entity (Actual)))
1561               and then not Treat_As_Volatile (E_Formal)
1562             then
1563                Add_Call_By_Copy_Code;
1564
1565             elsif Nkind (Actual) = N_Indexed_Component
1566               and then Is_Entity_Name (Prefix (Actual))
1567               and then Has_Volatile_Components (Entity (Prefix (Actual)))
1568             then
1569                Add_Call_By_Copy_Code;
1570             end if;
1571
1572          --  Processing for IN parameters
1573
1574          else
1575             --  For IN parameters is in the packed array case, we expand an
1576             --  indexed component (the circuit in Exp_Ch4 deliberately left
1577             --  indexed components appearing as actuals untouched, so that
1578             --  the special processing above for the OUT and IN OUT cases
1579             --  could be performed. We could make the test in Exp_Ch4 more
1580             --  complex and have it detect the parameter mode, but it is
1581             --  easier simply to handle all cases here.)
1582
1583             if Nkind (Actual) = N_Indexed_Component
1584               and then Is_Packed (Etype (Prefix (Actual)))
1585             then
1586                Reset_Packed_Prefix;
1587                Expand_Packed_Element_Reference (Actual);
1588
1589             --  If we have a reference to a bit packed array, we copy it,
1590             --  since the actual must be byte aligned.
1591
1592             --  Is this really necessary in all cases???
1593
1594             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
1595                Add_Simple_Call_By_Copy_Code;
1596
1597             --  If a non-scalar actual is possibly unaligned, we need a copy
1598
1599             elsif Is_Possibly_Unaligned_Object (Actual)
1600               and then not Represented_As_Scalar (Etype (Formal))
1601             then
1602                Add_Simple_Call_By_Copy_Code;
1603
1604             --  Similarly, we have to expand slices of packed arrays here
1605             --  because the result must be byte aligned.
1606
1607             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
1608                Add_Call_By_Copy_Code;
1609
1610             --  Only processing remaining is to pass by copy if this is a
1611             --  reference to a possibly unaligned slice, since the caller
1612             --  expects an appropriately aligned argument.
1613
1614             elsif Is_Possibly_Unaligned_Slice (Actual) then
1615                Add_Call_By_Copy_Code;
1616             end if;
1617          end if;
1618
1619          Next_Formal (Formal);
1620          Next_Actual (Actual);
1621       end loop;
1622
1623       --  Find right place to put post call stuff if it is present
1624
1625       if not Is_Empty_List (Post_Call) then
1626
1627          --  If call is not a list member, it must be the triggering statement
1628          --  of a triggering alternative or an entry call alternative, and we
1629          --  can add the post call stuff to the corresponding statement list.
1630
1631          if not Is_List_Member (N) then
1632             declare
1633                P : constant Node_Id := Parent (N);
1634
1635             begin
1636                pragma Assert (Nkind (P) = N_Triggering_Alternative
1637                  or else Nkind (P) = N_Entry_Call_Alternative);
1638
1639                if Is_Non_Empty_List (Statements (P)) then
1640                   Insert_List_Before_And_Analyze
1641                     (First (Statements (P)), Post_Call);
1642                else
1643                   Set_Statements (P, Post_Call);
1644                end if;
1645             end;
1646
1647          --  Otherwise, normal case where N is in a statement sequence,
1648          --  just put the post-call stuff after the call statement.
1649
1650          else
1651             Insert_Actions_After (N, Post_Call);
1652          end if;
1653       end if;
1654
1655       --  The call node itself is re-analyzed in Expand_Call
1656
1657    end Expand_Actuals;
1658
1659    -----------------
1660    -- Expand_Call --
1661    -----------------
1662
1663    --  This procedure handles expansion of function calls and procedure call
1664    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1665    --  Expand_N_Procedure_Call_Statement. Processing for calls includes:
1666
1667    --    Replace call to Raise_Exception by Raise_Exception always if possible
1668    --    Provide values of actuals for all formals in Extra_Formals list
1669    --    Replace "call" to enumeration literal function by literal itself
1670    --    Rewrite call to predefined operator as operator
1671    --    Replace actuals to in-out parameters that are numeric conversions,
1672    --     with explicit assignment to temporaries before and after the call.
1673    --    Remove optional actuals if First_Optional_Parameter specified.
1674
1675    --   Note that the list of actuals has been filled with default expressions
1676    --   during semantic analysis of the call. Only the extra actuals required
1677    --   for the 'Constrained attribute and for accessibility checks are added
1678    --   at this point.
1679
1680    procedure Expand_Call (N : Node_Id) is
1681       Loc           : constant Source_Ptr := Sloc (N);
1682       Remote        : constant Boolean    := Is_Remote_Call (N);
1683       Subp          : Entity_Id;
1684       Orig_Subp     : Entity_Id := Empty;
1685       Parent_Subp   : Entity_Id;
1686       Parent_Formal : Entity_Id;
1687       Actual        : Node_Id;
1688       Formal        : Entity_Id;
1689       Prev          : Node_Id := Empty;
1690
1691       Prev_Orig : Node_Id;
1692       --  Original node for an actual, which may have been rewritten. If the
1693       --  actual is a function call that has been transformed from a selected
1694       --  component, the original node is unanalyzed. Otherwise, it carries
1695       --  semantic information used to generate additional actuals.
1696
1697       Scop          : Entity_Id;
1698       Extra_Actuals : List_Id := No_List;
1699
1700       CW_Interface_Formals_Present : Boolean := False;
1701
1702       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1703       --  Adds one entry to the end of the actual parameter list. Used for
1704       --  default parameters and for extra actuals (for Extra_Formals). The
1705       --  argument is an N_Parameter_Association node.
1706
1707       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1708       --  Adds an extra actual to the list of extra actuals. Expr is the
1709       --  expression for the value of the actual, EF is the entity for the
1710       --  extra formal.
1711
1712       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1713       --  Within an instance, a type derived from a non-tagged formal derived
1714       --  type inherits from the original parent, not from the actual. This is
1715       --  tested in 4723-003. The current derivation mechanism has the derived
1716       --  type inherit from the actual, which is only correct outside of the
1717       --  instance. If the subprogram is inherited, we test for this particular
1718       --  case through a convoluted tree traversal before setting the proper
1719       --  subprogram to be called.
1720
1721       --------------------------
1722       -- Add_Actual_Parameter --
1723       --------------------------
1724
1725       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1726          Actual_Expr : constant Node_Id :=
1727                          Explicit_Actual_Parameter (Insert_Param);
1728
1729       begin
1730          --  Case of insertion is first named actual
1731
1732          if No (Prev) or else
1733             Nkind (Parent (Prev)) /= N_Parameter_Association
1734          then
1735             Set_Next_Named_Actual (Insert_Param, First_Named_Actual (N));
1736             Set_First_Named_Actual (N, Actual_Expr);
1737
1738             if No (Prev) then
1739                if No (Parameter_Associations (N)) then
1740                   Set_Parameter_Associations (N, New_List);
1741                   Append (Insert_Param, Parameter_Associations (N));
1742                end if;
1743             else
1744                Insert_After (Prev, Insert_Param);
1745             end if;
1746
1747          --  Case of insertion is not first named actual
1748
1749          else
1750             Set_Next_Named_Actual
1751               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1752             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1753             Append (Insert_Param, Parameter_Associations (N));
1754          end if;
1755
1756          Prev := Actual_Expr;
1757       end Add_Actual_Parameter;
1758
1759       ----------------------
1760       -- Add_Extra_Actual --
1761       ----------------------
1762
1763       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1764          Loc : constant Source_Ptr := Sloc (Expr);
1765
1766       begin
1767          if Extra_Actuals = No_List then
1768             Extra_Actuals := New_List;
1769             Set_Parent (Extra_Actuals, N);
1770          end if;
1771
1772          Append_To (Extra_Actuals,
1773            Make_Parameter_Association (Loc,
1774              Explicit_Actual_Parameter => Expr,
1775              Selector_Name =>
1776                Make_Identifier (Loc, Chars (EF))));
1777
1778          Analyze_And_Resolve (Expr, Etype (EF));
1779       end Add_Extra_Actual;
1780
1781       ---------------------------
1782       -- Inherited_From_Formal --
1783       ---------------------------
1784
1785       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1786          Par      : Entity_Id;
1787          Gen_Par  : Entity_Id;
1788          Gen_Prim : Elist_Id;
1789          Elmt     : Elmt_Id;
1790          Indic    : Node_Id;
1791
1792       begin
1793          --  If the operation is inherited, it is attached to the corresponding
1794          --  type derivation. If the parent in the derivation is a generic
1795          --  actual, it is a subtype of the actual, and we have to recover the
1796          --  original derived type declaration to find the proper parent.
1797
1798          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1799            or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1800            or else Nkind (Type_Definition (Original_Node (Parent (S)))) /=
1801                                                    N_Derived_Type_Definition
1802            or else not In_Instance
1803          then
1804             return Empty;
1805
1806          else
1807             Indic :=
1808               (Subtype_Indication
1809                 (Type_Definition (Original_Node (Parent (S)))));
1810
1811             if Nkind (Indic) = N_Subtype_Indication then
1812                Par := Entity (Subtype_Mark (Indic));
1813             else
1814                Par := Entity (Indic);
1815             end if;
1816          end if;
1817
1818          if not Is_Generic_Actual_Type (Par)
1819            or else Is_Tagged_Type (Par)
1820            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1821            or else not In_Open_Scopes (Scope (Par))
1822          then
1823             return Empty;
1824
1825          else
1826             Gen_Par := Generic_Parent_Type (Parent (Par));
1827          end if;
1828
1829          --  If the actual has no generic parent type, the formal is not
1830          --  a formal derived type, so nothing to inherit.
1831
1832          if No (Gen_Par) then
1833             return Empty;
1834          end if;
1835
1836          --  If the generic parent type is still the generic type, this is a
1837          --  private formal, not a derived formal, and there are no operations
1838          --  inherited from the formal.
1839
1840          if Nkind (Parent (Gen_Par)) = N_Formal_Type_Declaration then
1841             return Empty;
1842          end if;
1843
1844          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1845
1846          Elmt := First_Elmt (Gen_Prim);
1847          while Present (Elmt) loop
1848             if Chars (Node (Elmt)) = Chars (S) then
1849                declare
1850                   F1 : Entity_Id;
1851                   F2 : Entity_Id;
1852
1853                begin
1854                   F1 := First_Formal (S);
1855                   F2 := First_Formal (Node (Elmt));
1856                   while Present (F1)
1857                     and then Present (F2)
1858                   loop
1859                      if Etype (F1) = Etype (F2)
1860                        or else Etype (F2) = Gen_Par
1861                      then
1862                         Next_Formal (F1);
1863                         Next_Formal (F2);
1864                      else
1865                         Next_Elmt (Elmt);
1866                         exit;   --  not the right subprogram
1867                      end if;
1868
1869                      return Node (Elmt);
1870                   end loop;
1871                end;
1872
1873             else
1874                Next_Elmt (Elmt);
1875             end if;
1876          end loop;
1877
1878          raise Program_Error;
1879       end Inherited_From_Formal;
1880
1881    --  Start of processing for Expand_Call
1882
1883    begin
1884       --  Ignore if previous error
1885
1886       if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then
1887          return;
1888       end if;
1889
1890       --  Call using access to subprogram with explicit dereference
1891
1892       if Nkind (Name (N)) = N_Explicit_Dereference then
1893          Subp        := Etype (Name (N));
1894          Parent_Subp := Empty;
1895
1896       --  Case of call to simple entry, where the Name is a selected component
1897       --  whose prefix is the task, and whose selector name is the entry name
1898
1899       elsif Nkind (Name (N)) = N_Selected_Component then
1900          Subp        := Entity (Selector_Name (Name (N)));
1901          Parent_Subp := Empty;
1902
1903       --  Case of call to member of entry family, where Name is an indexed
1904       --  component, with the prefix being a selected component giving the
1905       --  task and entry family name, and the index being the entry index.
1906
1907       elsif Nkind (Name (N)) = N_Indexed_Component then
1908          Subp        := Entity (Selector_Name (Prefix (Name (N))));
1909          Parent_Subp := Empty;
1910
1911       --  Normal case
1912
1913       else
1914          Subp        := Entity (Name (N));
1915          Parent_Subp := Alias (Subp);
1916
1917          --  Replace call to Raise_Exception by call to Raise_Exception_Always
1918          --  if we can tell that the first parameter cannot possibly be null.
1919          --  This helps optimization and also generation of warnings.
1920
1921          --  We do not do this if Raise_Exception_Always does not exist, which
1922          --  can happen in configurable run time profiles which provide only a
1923          --  Raise_Exception, which is in fact an unconditional raise anyway.
1924
1925          if Is_RTE (Subp, RE_Raise_Exception)
1926            and then RTE_Available (RE_Raise_Exception_Always)
1927          then
1928             declare
1929                FA : constant Node_Id := Original_Node (First_Actual (N));
1930
1931             begin
1932                --  The case we catch is where the first argument is obtained
1933                --  using the Identity attribute (which must always be
1934                --  non-null).
1935
1936                if Nkind (FA) = N_Attribute_Reference
1937                  and then Attribute_Name (FA) = Name_Identity
1938                then
1939                   Subp := RTE (RE_Raise_Exception_Always);
1940                   Set_Name (N, New_Occurrence_Of (Subp, Loc));
1941                end if;
1942             end;
1943          end if;
1944
1945          if Ekind (Subp) = E_Entry then
1946             Parent_Subp := Empty;
1947          end if;
1948       end if;
1949
1950       --  Ada 2005 (AI-345): We have a procedure call as a triggering
1951       --  alternative in an asynchronous select or as an entry call in
1952       --  a conditional or timed select. Check whether the procedure call
1953       --  is a renaming of an entry and rewrite it as an entry call.
1954
1955       if Ada_Version >= Ada_05
1956         and then Nkind (N) = N_Procedure_Call_Statement
1957         and then
1958            ((Nkind (Parent (N)) = N_Triggering_Alternative
1959                and then Triggering_Statement (Parent (N)) = N)
1960           or else
1961             (Nkind (Parent (N)) = N_Entry_Call_Alternative
1962                and then Entry_Call_Statement (Parent (N)) = N))
1963       then
1964          declare
1965             Ren_Decl : Node_Id;
1966             Ren_Root : Entity_Id := Subp;
1967
1968          begin
1969             --  This may be a chain of renamings, find the root
1970
1971             if Present (Alias (Ren_Root)) then
1972                Ren_Root := Alias (Ren_Root);
1973             end if;
1974
1975             if Present (Original_Node (Parent (Parent (Ren_Root)))) then
1976                Ren_Decl := Original_Node (Parent (Parent (Ren_Root)));
1977
1978                if Nkind (Ren_Decl) = N_Subprogram_Renaming_Declaration then
1979                   Rewrite (N,
1980                     Make_Entry_Call_Statement (Loc,
1981                       Name =>
1982                         New_Copy_Tree (Name (Ren_Decl)),
1983                       Parameter_Associations =>
1984                         New_Copy_List_Tree (Parameter_Associations (N))));
1985
1986                   return;
1987                end if;
1988             end if;
1989          end;
1990       end if;
1991
1992       --  First step, compute extra actuals, corresponding to any
1993       --  Extra_Formals present. Note that we do not access Extra_Formals
1994       --  directly, instead we simply note the presence of the extra
1995       --  formals as we process the regular formals and collect the
1996       --  corresponding actuals in Extra_Actuals.
1997
1998       --  We also generate any required range checks for actuals as we go
1999       --  through the loop, since this is a convenient place to do this.
2000
2001       Formal := First_Formal (Subp);
2002       Actual := First_Actual (N);
2003       while Present (Formal) loop
2004
2005          --  Generate range check if required (not activated yet ???)
2006
2007 --         if Do_Range_Check (Actual) then
2008 --            Set_Do_Range_Check (Actual, False);
2009 --            Generate_Range_Check
2010 --              (Actual, Etype (Formal), CE_Range_Check_Failed);
2011 --         end if;
2012
2013          --  Prepare to examine current entry
2014
2015          Prev := Actual;
2016          Prev_Orig := Original_Node (Prev);
2017
2018          --  The original actual may have been a call written in prefix
2019          --  form, and rewritten before analysis.
2020
2021          if not Analyzed (Prev_Orig)
2022            and then
2023              (Nkind (Actual) = N_Function_Call
2024                 or else
2025               Nkind (Actual) = N_Identifier)
2026          then
2027             Prev_Orig := Prev;
2028          end if;
2029
2030          --  Ada 2005 (AI-251): Check if any formal is a class-wide interface
2031          --  to expand it in a further round.
2032
2033          CW_Interface_Formals_Present :=
2034            CW_Interface_Formals_Present
2035              or else
2036                (Ekind (Etype (Formal)) = E_Class_Wide_Type
2037                   and then Is_Interface (Etype (Etype (Formal))))
2038              or else
2039                (Ekind (Etype (Formal)) = E_Anonymous_Access_Type
2040                  and then Is_Interface (Directly_Designated_Type
2041                                          (Etype (Etype (Formal)))));
2042
2043          --  Create possible extra actual for constrained case. Usually, the
2044          --  extra actual is of the form actual'constrained, but since this
2045          --  attribute is only available for unconstrained records, TRUE is
2046          --  expanded if the type of the formal happens to be constrained (for
2047          --  instance when this procedure is inherited from an unconstrained
2048          --  record to a constrained one) or if the actual has no discriminant
2049          --  (its type is constrained). An exception to this is the case of a
2050          --  private type without discriminants. In this case we pass FALSE
2051          --  because the object has underlying discriminants with defaults.
2052
2053          if Present (Extra_Constrained (Formal)) then
2054             if Ekind (Etype (Prev)) in Private_Kind
2055               and then not Has_Discriminants (Base_Type (Etype (Prev)))
2056             then
2057                Add_Extra_Actual (
2058                  New_Occurrence_Of (Standard_False, Loc),
2059                  Extra_Constrained (Formal));
2060
2061             elsif Is_Constrained (Etype (Formal))
2062               or else not Has_Discriminants (Etype (Prev))
2063             then
2064                Add_Extra_Actual (
2065                  New_Occurrence_Of (Standard_True, Loc),
2066                  Extra_Constrained (Formal));
2067
2068             --  Do not produce extra actuals for Unchecked_Union parameters.
2069             --  Jump directly to the end of the loop.
2070
2071             elsif Is_Unchecked_Union (Base_Type (Etype (Actual))) then
2072                goto Skip_Extra_Actual_Generation;
2073
2074             else
2075                --  If the actual is a type conversion, then the constrained
2076                --  test applies to the actual, not the target type.
2077
2078                declare
2079                   Act_Prev : Node_Id;
2080
2081                begin
2082                   --  Test for unchecked conversions as well, which can occur
2083                   --  as out parameter actuals on calls to stream procedures.
2084
2085                   Act_Prev := Prev;
2086                   while Nkind (Act_Prev) = N_Type_Conversion
2087                     or else Nkind (Act_Prev) = N_Unchecked_Type_Conversion
2088                   loop
2089                      Act_Prev := Expression (Act_Prev);
2090                   end loop;
2091
2092                   --  If the expression is a conversion of a dereference,
2093                   --  this is internally generated code that manipulates
2094                   --  addresses, e.g. when building interface tables. No
2095                   --  check should occur in this case, and the discriminated
2096                   --  object is not directly a hand.
2097
2098                   if not Comes_From_Source (Actual)
2099                     and then Nkind (Actual) = N_Unchecked_Type_Conversion
2100                     and then Nkind (Act_Prev) = N_Explicit_Dereference
2101                   then
2102                      Add_Extra_Actual
2103                        (New_Occurrence_Of (Standard_False, Loc),
2104                         Extra_Constrained (Formal));
2105
2106                   else
2107                      Add_Extra_Actual
2108                        (Make_Attribute_Reference (Sloc (Prev),
2109                         Prefix =>
2110                           Duplicate_Subexpr_No_Checks
2111                             (Act_Prev, Name_Req => True),
2112                         Attribute_Name => Name_Constrained),
2113                         Extra_Constrained (Formal));
2114                   end if;
2115                end;
2116             end if;
2117          end if;
2118
2119          --  Create possible extra actual for accessibility level
2120
2121          if Present (Extra_Accessibility (Formal)) then
2122
2123             --  Ada 2005 (AI-252): If the actual was rewritten as an Access
2124             --  attribute, then the original actual may be an aliased object
2125             --  occurring as the prefix in a call using "Object.Operation"
2126             --  notation. In that case we must pass the level of the object,
2127             --  so Prev_Orig is reset to Prev and the attribute will be
2128             --  processed by the code for Access attributes further below.
2129
2130             if Prev_Orig /= Prev
2131               and then Nkind (Prev) = N_Attribute_Reference
2132               and then
2133                 Get_Attribute_Id (Attribute_Name (Prev)) = Attribute_Access
2134               and then Is_Aliased_View (Prev_Orig)
2135             then
2136                Prev_Orig := Prev;
2137             end if;
2138
2139             if Is_Entity_Name (Prev_Orig) then
2140
2141                --  When passing an access parameter, or a renaming of an access
2142                --  parameter, as the actual to another access parameter we need
2143                --  to pass along the actual's own access level parameter. This
2144                --  is done if we are within the scope of the formal access
2145                --  parameter (if this is an inlined body the extra formal is
2146                --  irrelevant).
2147
2148                if (Is_Formal (Entity (Prev_Orig))
2149                     or else
2150                       (Present (Renamed_Object (Entity (Prev_Orig)))
2151                         and then
2152                           Is_Entity_Name (Renamed_Object (Entity (Prev_Orig)))
2153                         and then
2154                           Is_Formal
2155                             (Entity (Renamed_Object (Entity (Prev_Orig))))))
2156                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
2157                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
2158                then
2159                   declare
2160                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
2161
2162                   begin
2163                      pragma Assert (Present (Parm_Ent));
2164
2165                      if Present (Extra_Accessibility (Parm_Ent)) then
2166                         Add_Extra_Actual
2167                           (New_Occurrence_Of
2168                              (Extra_Accessibility (Parm_Ent), Loc),
2169                            Extra_Accessibility (Formal));
2170
2171                      --  If the actual access parameter does not have an
2172                      --  associated extra formal providing its scope level,
2173                      --  then treat the actual as having library-level
2174                      --  accessibility.
2175
2176                      else
2177                         Add_Extra_Actual
2178                           (Make_Integer_Literal (Loc,
2179                            Intval => Scope_Depth (Standard_Standard)),
2180                            Extra_Accessibility (Formal));
2181                      end if;
2182                   end;
2183
2184                --  The actual is a normal access value, so just pass the level
2185                --  of the actual's access type.
2186
2187                else
2188                   Add_Extra_Actual
2189                     (Make_Integer_Literal (Loc,
2190                      Intval => Type_Access_Level (Etype (Prev_Orig))),
2191                      Extra_Accessibility (Formal));
2192                end if;
2193
2194             else
2195                case Nkind (Prev_Orig) is
2196
2197                   when N_Attribute_Reference =>
2198
2199                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
2200
2201                         --  For X'Access, pass on the level of the prefix X
2202
2203                         when Attribute_Access =>
2204                            Add_Extra_Actual (
2205                              Make_Integer_Literal (Loc,
2206                                Intval =>
2207                                  Object_Access_Level (Prefix (Prev_Orig))),
2208                              Extra_Accessibility (Formal));
2209
2210                         --  Treat the unchecked attributes as library-level
2211
2212                         when Attribute_Unchecked_Access |
2213                            Attribute_Unrestricted_Access =>
2214                            Add_Extra_Actual (
2215                              Make_Integer_Literal (Loc,
2216                                Intval => Scope_Depth (Standard_Standard)),
2217                              Extra_Accessibility (Formal));
2218
2219                         --  No other cases of attributes returning access
2220                         --  values that can be passed to access parameters
2221
2222                         when others =>
2223                            raise Program_Error;
2224
2225                      end case;
2226
2227                   --  For allocators we pass the level of the execution of
2228                   --  the called subprogram, which is one greater than the
2229                   --  current scope level.
2230
2231                   when N_Allocator =>
2232                      Add_Extra_Actual (
2233                        Make_Integer_Literal (Loc,
2234                         Scope_Depth (Current_Scope) + 1),
2235                        Extra_Accessibility (Formal));
2236
2237                   --  For other cases we simply pass the level of the
2238                   --  actual's access type.
2239
2240                   when others =>
2241                      Add_Extra_Actual (
2242                        Make_Integer_Literal (Loc,
2243                          Intval => Type_Access_Level (Etype (Prev_Orig))),
2244                        Extra_Accessibility (Formal));
2245
2246                end case;
2247             end if;
2248          end if;
2249
2250          --  Perform the check of 4.6(49) that prevents a null value from being
2251          --  passed as an actual to an access parameter. Note that the check is
2252          --  elided in the common cases of passing an access attribute or
2253          --  access parameter as an actual. Also, we currently don't enforce
2254          --  this check for expander-generated actuals and when -gnatdj is set.
2255
2256          if Ada_Version >= Ada_05 then
2257
2258             --  Ada 2005 (AI-231): Check null-excluding access types
2259
2260             if Is_Access_Type (Etype (Formal))
2261               and then Can_Never_Be_Null (Etype (Formal))
2262               and then Nkind (Prev) /= N_Raise_Constraint_Error
2263               and then (Known_Null (Prev)
2264                           or else not Can_Never_Be_Null (Etype (Prev)))
2265             then
2266                Install_Null_Excluding_Check (Prev);
2267             end if;
2268
2269          --  Ada_Version < Ada_05
2270
2271          else
2272             if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
2273               or else Access_Checks_Suppressed (Subp)
2274             then
2275                null;
2276
2277             elsif Debug_Flag_J then
2278                null;
2279
2280             elsif not Comes_From_Source (Prev) then
2281                null;
2282
2283             elsif Is_Entity_Name (Prev)
2284               and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
2285             then
2286                null;
2287
2288             elsif Nkind (Prev) = N_Allocator
2289               or else Nkind (Prev) = N_Attribute_Reference
2290             then
2291                null;
2292
2293             --  Suppress null checks when passing to access parameters of Java
2294             --  and CIL subprograms. (Should this be done for other foreign
2295             --  conventions as well ???)
2296
2297             elsif Convention (Subp) = Convention_Java
2298               or else Convention (Subp) = Convention_CIL
2299             then
2300                null;
2301
2302             else
2303                Install_Null_Excluding_Check (Prev);
2304             end if;
2305          end if;
2306
2307          --  Perform appropriate validity checks on parameters that
2308          --  are entities.
2309
2310          if Validity_Checks_On then
2311             if  (Ekind (Formal) = E_In_Parameter
2312                    and then Validity_Check_In_Params)
2313               or else
2314                 (Ekind (Formal) = E_In_Out_Parameter
2315                    and then Validity_Check_In_Out_Params)
2316             then
2317                --  If the actual is an indexed component of a packed type (or
2318                --  is an indexed or selected component whose prefix recursively
2319                --  meets this condition), it has not been expanded yet. It will
2320                --  be copied in the validity code that follows, and has to be
2321                --  expanded appropriately, so reanalyze it.
2322
2323                --  What we do is just to unset analyzed bits on prefixes till
2324                --  we reach something that does not have a prefix.
2325
2326                declare
2327                   Nod : Node_Id;
2328
2329                begin
2330                   Nod := Actual;
2331                   while Nkind (Nod) = N_Indexed_Component
2332                           or else
2333                         Nkind (Nod) = N_Selected_Component
2334                   loop
2335                      Set_Analyzed (Nod, False);
2336                      Nod := Prefix (Nod);
2337                   end loop;
2338                end;
2339
2340                Ensure_Valid (Actual);
2341             end if;
2342          end if;
2343
2344          --  For IN OUT and OUT parameters, ensure that subscripts are valid
2345          --  since this is a left side reference. We only do this for calls
2346          --  from the source program since we assume that compiler generated
2347          --  calls explicitly generate any required checks. We also need it
2348          --  only if we are doing standard validity checks, since clearly it
2349          --  is not needed if validity checks are off, and in subscript
2350          --  validity checking mode, all indexed components are checked with
2351          --  a call directly from Expand_N_Indexed_Component.
2352
2353          if Comes_From_Source (N)
2354            and then Ekind (Formal) /= E_In_Parameter
2355            and then Validity_Checks_On
2356            and then Validity_Check_Default
2357            and then not Validity_Check_Subscripts
2358          then
2359             Check_Valid_Lvalue_Subscripts (Actual);
2360          end if;
2361
2362          --  Mark any scalar OUT parameter that is a simple variable as no
2363          --  longer known to be valid (unless the type is always valid). This
2364          --  reflects the fact that if an OUT parameter is never set in a
2365          --  procedure, then it can become invalid on the procedure return.
2366
2367          if Ekind (Formal) = E_Out_Parameter
2368            and then Is_Entity_Name (Actual)
2369            and then Ekind (Entity (Actual)) = E_Variable
2370            and then not Is_Known_Valid (Etype (Actual))
2371          then
2372             Set_Is_Known_Valid (Entity (Actual), False);
2373          end if;
2374
2375          --  For an OUT or IN OUT parameter, if the actual is an entity, then
2376          --  clear current values, since they can be clobbered. We are probably
2377          --  doing this in more places than we need to, but better safe than
2378          --  sorry when it comes to retaining bad current values!
2379
2380          if Ekind (Formal) /= E_In_Parameter
2381            and then Is_Entity_Name (Actual)
2382          then
2383             Kill_Current_Values (Entity (Actual));
2384          end if;
2385
2386          --  If the formal is class wide and the actual is an aggregate, force
2387          --  evaluation so that the back end who does not know about class-wide
2388          --  type, does not generate a temporary of the wrong size.
2389
2390          if not Is_Class_Wide_Type (Etype (Formal)) then
2391             null;
2392
2393          elsif Nkind (Actual) = N_Aggregate
2394            or else (Nkind (Actual) = N_Qualified_Expression
2395                      and then Nkind (Expression (Actual)) = N_Aggregate)
2396          then
2397             Force_Evaluation (Actual);
2398          end if;
2399
2400          --  In a remote call, if the formal is of a class-wide type, check
2401          --  that the actual meets the requirements described in E.4(18).
2402
2403          if Remote and then Is_Class_Wide_Type (Etype (Formal)) then
2404             Insert_Action (Actual,
2405               Make_Transportable_Check (Loc,
2406                 Duplicate_Subexpr_Move_Checks (Actual)));
2407          end if;
2408
2409          --  This label is required when skipping extra actual generation for
2410          --  Unchecked_Union parameters.
2411
2412          <<Skip_Extra_Actual_Generation>>
2413
2414          Next_Actual (Actual);
2415          Next_Formal (Formal);
2416       end loop;
2417
2418       --  If we are expanding a rhs of an assignment we need to check if tag
2419       --  propagation is needed. You might expect this processing to be in
2420       --  Analyze_Assignment but has to be done earlier (bottom-up) because the
2421       --  assignment might be transformed to a declaration for an unconstrained
2422       --  value if the expression is classwide.
2423
2424       if Nkind (N) = N_Function_Call
2425         and then Is_Tag_Indeterminate (N)
2426         and then Is_Entity_Name (Name (N))
2427       then
2428          declare
2429             Ass : Node_Id := Empty;
2430
2431          begin
2432             if Nkind (Parent (N)) = N_Assignment_Statement then
2433                Ass := Parent (N);
2434
2435             elsif Nkind (Parent (N)) = N_Qualified_Expression
2436               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2437             then
2438                Ass := Parent (Parent (N));
2439
2440             elsif Nkind (Parent (N)) = N_Explicit_Dereference
2441               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2442             then
2443                Ass := Parent (Parent (N));
2444             end if;
2445
2446             if Present (Ass)
2447               and then Is_Class_Wide_Type (Etype (Name (Ass)))
2448             then
2449                if Is_Access_Type (Etype (N)) then
2450                   if Designated_Type (Etype (N)) /=
2451                     Root_Type (Etype (Name (Ass)))
2452                   then
2453                      Error_Msg_NE
2454                        ("tag-indeterminate expression "
2455                          & " must have designated type& (RM 5.2 (6))",
2456                            N, Root_Type (Etype (Name (Ass))));
2457                   else
2458                      Propagate_Tag (Name (Ass), N);
2459                   end if;
2460
2461                elsif Etype (N) /= Root_Type (Etype (Name (Ass))) then
2462                   Error_Msg_NE
2463                     ("tag-indeterminate expression must have type&"
2464                      & "(RM 5.2 (6))", N, Root_Type (Etype (Name (Ass))));
2465
2466                else
2467                   Propagate_Tag (Name (Ass), N);
2468                end if;
2469
2470                --  The call will be rewritten as a dispatching call, and
2471                --  expanded as such.
2472
2473                return;
2474             end if;
2475          end;
2476       end if;
2477
2478       --  Ada 2005 (AI-251): If some formal is a class-wide interface, expand
2479       --  it to point to the correct secondary virtual table
2480
2481       if (Nkind (N) = N_Function_Call
2482            or else Nkind (N) = N_Procedure_Call_Statement)
2483         and then CW_Interface_Formals_Present
2484       then
2485          Expand_Interface_Actuals (N);
2486       end if;
2487
2488       --  Deals with Dispatch_Call if we still have a call, before expanding
2489       --  extra actuals since this will be done on the re-analysis of the
2490       --  dispatching call. Note that we do not try to shorten the actual
2491       --  list for a dispatching call, it would not make sense to do so.
2492       --  Expansion of dispatching calls is suppressed when VM_Target, because
2493       --  the VM back-ends directly handle the generation of dispatching
2494       --  calls and would have to undo any expansion to an indirect call.
2495
2496       if (Nkind (N) = N_Function_Call
2497            or else Nkind (N) =  N_Procedure_Call_Statement)
2498         and then Present (Controlling_Argument (N))
2499         and then VM_Target = No_VM
2500       then
2501          Expand_Dispatching_Call (N);
2502
2503          --  The following return is worrisome. Is it really OK to
2504          --  skip all remaining processing in this procedure ???
2505
2506          return;
2507
2508       --  Similarly, expand calls to RCI subprograms on which pragma
2509       --  All_Calls_Remote applies. The rewriting will be reanalyzed
2510       --  later. Do this only when the call comes from source since we do
2511       --  not want such a rewritting to occur in expanded code.
2512
2513       elsif Is_All_Remote_Call (N) then
2514          Expand_All_Calls_Remote_Subprogram_Call (N);
2515
2516       --  Similarly, do not add extra actuals for an entry call whose entity
2517       --  is a protected procedure, or for an internal protected subprogram
2518       --  call, because it will be rewritten as a protected subprogram call
2519       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
2520
2521       elsif Is_Protected_Type (Scope (Subp))
2522          and then (Ekind (Subp) = E_Procedure
2523                     or else Ekind (Subp) = E_Function)
2524       then
2525          null;
2526
2527       --  During that loop we gathered the extra actuals (the ones that
2528       --  correspond to Extra_Formals), so now they can be appended.
2529
2530       else
2531          while Is_Non_Empty_List (Extra_Actuals) loop
2532             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
2533          end loop;
2534       end if;
2535
2536       --  At this point we have all the actuals, so this is the point at
2537       --  which the various expansion activities for actuals is carried out.
2538
2539       Expand_Actuals (N, Subp);
2540
2541       --  If the subprogram is a renaming, or if it is inherited, replace it
2542       --  in the call with the name of the actual subprogram being called.
2543       --  If this is a dispatching call, the run-time decides what to call.
2544       --  The Alias attribute does not apply to entries.
2545
2546       if Nkind (N) /= N_Entry_Call_Statement
2547         and then No (Controlling_Argument (N))
2548         and then Present (Parent_Subp)
2549       then
2550          if Present (Inherited_From_Formal (Subp)) then
2551             Parent_Subp := Inherited_From_Formal (Subp);
2552          else
2553             while Present (Alias (Parent_Subp)) loop
2554                Parent_Subp := Alias (Parent_Subp);
2555             end loop;
2556          end if;
2557
2558          --  The below setting of Entity is suspect, see F109-018 discussion???
2559
2560          Set_Entity (Name (N), Parent_Subp);
2561
2562          if Is_Abstract_Subprogram (Parent_Subp)
2563            and then not In_Instance
2564          then
2565             Error_Msg_NE
2566               ("cannot call abstract subprogram &!", Name (N), Parent_Subp);
2567          end if;
2568
2569          --  Add an explicit conversion for parameter of the derived type.
2570          --  This is only done for scalar and access in-parameters. Others
2571          --  have been expanded in expand_actuals.
2572
2573          Formal := First_Formal (Subp);
2574          Parent_Formal := First_Formal (Parent_Subp);
2575          Actual := First_Actual (N);
2576
2577          --  It is not clear that conversion is needed for intrinsic
2578          --  subprograms, but it certainly is for those that are user-
2579          --  defined, and that can be inherited on derivation, namely
2580          --  unchecked conversion and deallocation.
2581          --  General case needs study ???
2582
2583          if not Is_Intrinsic_Subprogram (Parent_Subp)
2584            or else Is_Generic_Instance (Parent_Subp)
2585          then
2586             while Present (Formal) loop
2587                if Etype (Formal) /= Etype (Parent_Formal)
2588                  and then Is_Scalar_Type (Etype (Formal))
2589                  and then Ekind (Formal) = E_In_Parameter
2590                  and then
2591                    not Subtypes_Statically_Match
2592                          (Etype (Parent_Formal), Etype (Actual))
2593                  and then not Raises_Constraint_Error (Actual)
2594                then
2595                   Rewrite (Actual,
2596                     OK_Convert_To (Etype (Parent_Formal),
2597                       Relocate_Node (Actual)));
2598
2599                   Analyze (Actual);
2600                   Resolve (Actual, Etype (Parent_Formal));
2601                   Enable_Range_Check (Actual);
2602
2603                elsif Is_Access_Type (Etype (Formal))
2604                  and then Base_Type (Etype (Parent_Formal)) /=
2605                           Base_Type (Etype (Actual))
2606                then
2607                   if Ekind (Formal) /= E_In_Parameter then
2608                      Rewrite (Actual,
2609                        Convert_To (Etype (Parent_Formal),
2610                          Relocate_Node (Actual)));
2611
2612                      Analyze (Actual);
2613                      Resolve (Actual, Etype (Parent_Formal));
2614
2615                   elsif
2616                     Ekind (Etype (Parent_Formal)) = E_Anonymous_Access_Type
2617                       and then Designated_Type (Etype (Parent_Formal))
2618                                  /=
2619                                Designated_Type (Etype (Actual))
2620                       and then not Is_Controlling_Formal (Formal)
2621                   then
2622                      --  This unchecked conversion is not necessary unless
2623                      --  inlining is enabled, because in that case the type
2624                      --  mismatch may become visible in the body about to be
2625                      --  inlined.
2626
2627                      Rewrite (Actual,
2628                        Unchecked_Convert_To (Etype (Parent_Formal),
2629                          Relocate_Node (Actual)));
2630
2631                      Analyze (Actual);
2632                      Resolve (Actual, Etype (Parent_Formal));
2633                   end if;
2634                end if;
2635
2636                Next_Formal (Formal);
2637                Next_Formal (Parent_Formal);
2638                Next_Actual (Actual);
2639             end loop;
2640          end if;
2641
2642          Orig_Subp := Subp;
2643          Subp := Parent_Subp;
2644       end if;
2645
2646       --  Check for violation of No_Abort_Statements
2647
2648       if Is_RTE (Subp, RE_Abort_Task) then
2649          Check_Restriction (No_Abort_Statements, N);
2650
2651       --  Check for violation of No_Dynamic_Attachment
2652
2653       elsif RTU_Loaded (Ada_Interrupts)
2654         and then (Is_RTE (Subp, RE_Is_Reserved)      or else
2655                   Is_RTE (Subp, RE_Is_Attached)      or else
2656                   Is_RTE (Subp, RE_Current_Handler)  or else
2657                   Is_RTE (Subp, RE_Attach_Handler)   or else
2658                   Is_RTE (Subp, RE_Exchange_Handler) or else
2659                   Is_RTE (Subp, RE_Detach_Handler)   or else
2660                   Is_RTE (Subp, RE_Reference))
2661       then
2662          Check_Restriction (No_Dynamic_Attachment, N);
2663       end if;
2664
2665       --  Deal with case where call is an explicit dereference
2666
2667       if Nkind (Name (N)) = N_Explicit_Dereference then
2668
2669       --  Handle case of access to protected subprogram type
2670
2671          if Is_Access_Protected_Subprogram_Type
2672             (Base_Type (Etype (Prefix (Name (N)))))
2673          then
2674             --  If this is a call through an access to protected operation,
2675             --  the prefix has the form (object'address, operation'access).
2676             --  Rewrite as a for other protected calls: the object is the
2677             --  first parameter of the list of actuals.
2678
2679             declare
2680                Call : Node_Id;
2681                Parm : List_Id;
2682                Nam  : Node_Id;
2683                Obj  : Node_Id;
2684                Ptr  : constant Node_Id := Prefix (Name (N));
2685
2686                T : constant Entity_Id :=
2687                      Equivalent_Type (Base_Type (Etype (Ptr)));
2688
2689                D_T : constant Entity_Id :=
2690                        Designated_Type (Base_Type (Etype (Ptr)));
2691
2692             begin
2693                Obj :=
2694                  Make_Selected_Component (Loc,
2695                    Prefix        => Unchecked_Convert_To (T, Ptr),
2696                    Selector_Name =>
2697                      New_Occurrence_Of (First_Entity (T), Loc));
2698
2699                Nam :=
2700                  Make_Selected_Component (Loc,
2701                    Prefix        => Unchecked_Convert_To (T, Ptr),
2702                    Selector_Name =>
2703                      New_Occurrence_Of (Next_Entity (First_Entity (T)), Loc));
2704
2705                Nam :=
2706                  Make_Explicit_Dereference (Loc,
2707                    Prefix => Nam);
2708
2709                if Present (Parameter_Associations (N))  then
2710                   Parm := Parameter_Associations (N);
2711                else
2712                   Parm := New_List;
2713                end if;
2714
2715                Prepend (Obj, Parm);
2716
2717                if Etype (D_T) = Standard_Void_Type then
2718                   Call :=
2719                     Make_Procedure_Call_Statement (Loc,
2720                       Name                   => Nam,
2721                       Parameter_Associations => Parm);
2722                else
2723                   Call :=
2724                     Make_Function_Call (Loc,
2725                       Name                   => Nam,
2726                       Parameter_Associations => Parm);
2727                end if;
2728
2729                Set_First_Named_Actual (Call, First_Named_Actual (N));
2730                Set_Etype (Call, Etype (D_T));
2731
2732                --  We do not re-analyze the call to avoid infinite recursion.
2733                --  We analyze separately the prefix and the object, and set
2734                --  the checks on the prefix that would otherwise be emitted
2735                --  when resolving a call.
2736
2737                Rewrite (N, Call);
2738                Analyze (Nam);
2739                Apply_Access_Check (Nam);
2740                Analyze (Obj);
2741                return;
2742             end;
2743          end if;
2744       end if;
2745
2746       --  If this is a call to an intrinsic subprogram, then perform the
2747       --  appropriate expansion to the corresponding tree node and we
2748       --  are all done (since after that the call is gone!)
2749
2750       --  In the case where the intrinsic is to be processed by the back end,
2751       --  the call to Expand_Intrinsic_Call will do nothing, which is fine,
2752       --  since the idea in this case is to pass the call unchanged.
2753       --  If the intrinsic is an inherited unchecked conversion, and the
2754       --  derived type is the target type of the conversion, we must retain
2755       --  it as the return type of the expression. Otherwise the expansion
2756       --  below, which uses the parent operation, will yield the wrong type.
2757
2758       if Is_Intrinsic_Subprogram (Subp) then
2759          Expand_Intrinsic_Call (N, Subp);
2760
2761          if Nkind (N) = N_Unchecked_Type_Conversion
2762            and then Parent_Subp /= Orig_Subp
2763            and then Etype (Parent_Subp) /= Etype (Orig_Subp)
2764          then
2765             Set_Etype (N, Etype (Orig_Subp));
2766          end if;
2767
2768          return;
2769       end if;
2770
2771       if Ekind (Subp) = E_Function
2772         or else Ekind (Subp) = E_Procedure
2773       then
2774          if Is_Inlined (Subp) then
2775
2776             Inlined_Subprogram : declare
2777                Bod         : Node_Id;
2778                Must_Inline : Boolean := False;
2779                Spec        : constant Node_Id := Unit_Declaration_Node (Subp);
2780                Scop        : constant Entity_Id := Scope (Subp);
2781
2782                function In_Unfrozen_Instance return Boolean;
2783                --  If the subprogram comes from an instance in the same
2784                --  unit, and the instance is not yet frozen, inlining might
2785                --  trigger order-of-elaboration problems in gigi.
2786
2787                --------------------------
2788                -- In_Unfrozen_Instance --
2789                --------------------------
2790
2791                function In_Unfrozen_Instance return Boolean is
2792                   S : Entity_Id;
2793
2794                begin
2795                   S := Scop;
2796                   while Present (S)
2797                     and then S /= Standard_Standard
2798                   loop
2799                      if Is_Generic_Instance (S)
2800                        and then Present (Freeze_Node (S))
2801                        and then not Analyzed (Freeze_Node (S))
2802                      then
2803                         return True;
2804                      end if;
2805
2806                      S := Scope (S);
2807                   end loop;
2808
2809                   return False;
2810                end In_Unfrozen_Instance;
2811
2812             --  Start of processing for Inlined_Subprogram
2813
2814             begin
2815                --  Verify that the body to inline has already been seen, and
2816                --  that if the body is in the current unit the inlining does
2817                --  not occur earlier. This avoids order-of-elaboration problems
2818                --  in the back end.
2819
2820                --  This should be documented in sinfo/einfo ???
2821
2822                if No (Spec)
2823                  or else Nkind (Spec) /= N_Subprogram_Declaration
2824                  or else No (Body_To_Inline (Spec))
2825                then
2826                   Must_Inline := False;
2827
2828                --  If this an inherited function that returns a private
2829                --  type, do not inline if the full view is an unconstrained
2830                --  array, because such calls cannot be inlined.
2831
2832                elsif Present (Orig_Subp)
2833                  and then Is_Array_Type (Etype (Orig_Subp))
2834                  and then not Is_Constrained (Etype (Orig_Subp))
2835                then
2836                   Must_Inline := False;
2837
2838                elsif In_Unfrozen_Instance then
2839                   Must_Inline := False;
2840
2841                else
2842                   Bod := Body_To_Inline (Spec);
2843
2844                   if (In_Extended_Main_Code_Unit (N)
2845                         or else In_Extended_Main_Code_Unit (Parent (N))
2846                         or else Is_Always_Inlined (Subp))
2847                     and then (not In_Same_Extended_Unit (Sloc (Bod), Loc)
2848                                or else
2849                                  Earlier_In_Extended_Unit (Sloc (Bod), Loc))
2850                   then
2851                      Must_Inline := True;
2852
2853                   --  If we are compiling a package body that is not the main
2854                   --  unit, it must be for inlining/instantiation purposes,
2855                   --  in which case we inline the call to insure that the same
2856                   --  temporaries are generated when compiling the body by
2857                   --  itself. Otherwise link errors can occur.
2858
2859                   --  If the function being called is itself in the main unit,
2860                   --  we cannot inline, because there is a risk of double
2861                   --  elaboration and/or circularity: the inlining can make
2862                   --  visible a private entity in the body of the main unit,
2863                   --  that gigi will see before its sees its proper definition.
2864
2865                   elsif not (In_Extended_Main_Code_Unit (N))
2866                     and then In_Package_Body
2867                   then
2868                      Must_Inline := not In_Extended_Main_Source_Unit (Subp);
2869                   end if;
2870                end if;
2871
2872                if Must_Inline then
2873                   Expand_Inlined_Call (N, Subp, Orig_Subp);
2874
2875                else
2876                   --  Let the back end handle it
2877
2878                   Add_Inlined_Body (Subp);
2879
2880                   if Front_End_Inlining
2881                     and then Nkind (Spec) = N_Subprogram_Declaration
2882                     and then (In_Extended_Main_Code_Unit (N))
2883                     and then No (Body_To_Inline (Spec))
2884                     and then not Has_Completion (Subp)
2885                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
2886                   then
2887                      Cannot_Inline
2888                       ("cannot inline& (body not seen yet)?",
2889                        N, Subp);
2890                   end if;
2891                end if;
2892             end Inlined_Subprogram;
2893          end if;
2894       end if;
2895
2896       --  Check for a protected subprogram. This is either an intra-object
2897       --  call, or a protected function call. Protected procedure calls are
2898       --  rewritten as entry calls and handled accordingly.
2899
2900       --  In Ada 2005, this may be an indirect call to an access parameter
2901       --  that is an access_to_subprogram. In that case the anonymous type
2902       --  has a scope that is a protected operation, but the call is a
2903       --  regular one.
2904
2905       Scop := Scope (Subp);
2906
2907       if Nkind (N) /= N_Entry_Call_Statement
2908         and then Is_Protected_Type (Scop)
2909         and then Ekind (Subp) /= E_Subprogram_Type
2910       then
2911          --  If the call is an internal one, it is rewritten as a call to
2912          --  to the corresponding unprotected subprogram.
2913
2914          Expand_Protected_Subprogram_Call (N, Subp, Scop);
2915       end if;
2916
2917       --  Functions returning controlled objects need special attention
2918       --  If the return type is limited the context is an initialization
2919       --  and different processing applies.
2920
2921       if Controlled_Type (Etype (Subp))
2922         and then not Is_Inherently_Limited_Type (Etype (Subp))
2923         and then not Is_Limited_Interface (Etype (Subp))
2924       then
2925          Expand_Ctrl_Function_Call (N);
2926       end if;
2927
2928       --  Test for First_Optional_Parameter, and if so, truncate parameter
2929       --  list if there are optional parameters at the trailing end.
2930       --  Note we never delete procedures for call via a pointer.
2931
2932       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
2933         and then Present (First_Optional_Parameter (Subp))
2934       then
2935          declare
2936             Last_Keep_Arg : Node_Id;
2937
2938          begin
2939             --  Last_Keep_Arg will hold the last actual that should be
2940             --  retained. If it remains empty at the end, it means that
2941             --  all parameters are optional.
2942
2943             Last_Keep_Arg := Empty;
2944
2945             --  Find first optional parameter, must be present since we
2946             --  checked the validity of the parameter before setting it.
2947
2948             Formal := First_Formal (Subp);
2949             Actual := First_Actual (N);
2950             while Formal /= First_Optional_Parameter (Subp) loop
2951                Last_Keep_Arg := Actual;
2952                Next_Formal (Formal);
2953                Next_Actual (Actual);
2954             end loop;
2955
2956             --  We have Formal and Actual pointing to the first potentially
2957             --  droppable argument. We can drop all the trailing arguments
2958             --  whose actual matches the default. Note that we know that all
2959             --  remaining formals have defaults, because we checked that this
2960             --  requirement was met before setting First_Optional_Parameter.
2961
2962             --  We use Fully_Conformant_Expressions to check for identity
2963             --  between formals and actuals, which may miss some cases, but
2964             --  on the other hand, this is only an optimization (if we fail
2965             --  to truncate a parameter it does not affect functionality).
2966             --  So if the default is 3 and the actual is 1+2, we consider
2967             --  them unequal, which hardly seems worrisome.
2968
2969             while Present (Formal) loop
2970                if not Fully_Conformant_Expressions
2971                     (Actual, Default_Value (Formal))
2972                then
2973                   Last_Keep_Arg := Actual;
2974                end if;
2975
2976                Next_Formal (Formal);
2977                Next_Actual (Actual);
2978             end loop;
2979
2980             --  If no arguments, delete entire list, this is the easy case
2981
2982             if No (Last_Keep_Arg) then
2983                while Is_Non_Empty_List (Parameter_Associations (N)) loop
2984                   Delete_Tree (Remove_Head (Parameter_Associations (N)));
2985                end loop;
2986
2987                Set_Parameter_Associations (N, No_List);
2988                Set_First_Named_Actual (N, Empty);
2989
2990             --  Case where at the last retained argument is positional. This
2991             --  is also an easy case, since the retained arguments are already
2992             --  in the right form, and we don't need to worry about the order
2993             --  of arguments that get eliminated.
2994
2995             elsif Is_List_Member (Last_Keep_Arg) then
2996                while Present (Next (Last_Keep_Arg)) loop
2997                   Delete_Tree (Remove_Next (Last_Keep_Arg));
2998                end loop;
2999
3000                Set_First_Named_Actual (N, Empty);
3001
3002             --  This is the annoying case where the last retained argument
3003             --  is a named parameter. Since the original arguments are not
3004             --  in declaration order, we may have to delete some fairly
3005             --  random collection of arguments.
3006
3007             else
3008                declare
3009                   Temp   : Node_Id;
3010                   Passoc : Node_Id;
3011
3012                begin
3013                   --  First step, remove all the named parameters from the
3014                   --  list (they are still chained using First_Named_Actual
3015                   --  and Next_Named_Actual, so we have not lost them!)
3016
3017                   Temp := First (Parameter_Associations (N));
3018
3019                   --  Case of all parameters named, remove them all
3020
3021                   if Nkind (Temp) = N_Parameter_Association then
3022                      while Is_Non_Empty_List (Parameter_Associations (N)) loop
3023                         Temp := Remove_Head (Parameter_Associations (N));
3024                      end loop;
3025
3026                   --  Case of mixed positional/named, remove named parameters
3027
3028                   else
3029                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
3030                         Next (Temp);
3031                      end loop;
3032
3033                      while Present (Next (Temp)) loop
3034                         Remove (Next (Temp));
3035                      end loop;
3036                   end if;
3037
3038                   --  Now we loop through the named parameters, till we get
3039                   --  to the last one to be retained, adding them to the list.
3040                   --  Note that the Next_Named_Actual list does not need to be
3041                   --  touched since we are only reordering them on the actual
3042                   --  parameter association list.
3043
3044                   Passoc := Parent (First_Named_Actual (N));
3045                   loop
3046                      Temp := Relocate_Node (Passoc);
3047                      Append_To
3048                        (Parameter_Associations (N), Temp);
3049                      exit when
3050                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
3051                      Passoc := Parent (Next_Named_Actual (Passoc));
3052                   end loop;
3053
3054                   Set_Next_Named_Actual (Temp, Empty);
3055
3056                   loop
3057                      Temp := Next_Named_Actual (Passoc);
3058                      exit when No (Temp);
3059                      Set_Next_Named_Actual
3060                        (Passoc, Next_Named_Actual (Parent (Temp)));
3061                      Delete_Tree (Temp);
3062                   end loop;
3063                end;
3064             end if;
3065          end;
3066       end if;
3067
3068       --  Special processing for Ada 2005 AI-329, which requires a call to
3069       --  Raise_Exception to raise Constraint_Error if the Exception_Id is
3070       --  null. Note that we never need to do this in GNAT mode, or if the
3071       --  parameter to Raise_Exception is a use of Identity, since in these
3072       --  cases we know that the parameter is never null.
3073
3074       --  Note: We must check that the node has not been inlined. This is
3075       --  required because under zfp the Raise_Exception subprogram has the
3076       --  pragma inline_always (and hence the call has been expanded above
3077       --  into a block containing the code of the subprogram).
3078
3079       if Ada_Version >= Ada_05
3080         and then not GNAT_Mode
3081         and then Is_RTE (Subp, RE_Raise_Exception)
3082         and then Nkind (N) = N_Procedure_Call_Statement
3083         and then (Nkind (First_Actual (N)) /= N_Attribute_Reference
3084                    or else Attribute_Name (First_Actual (N)) /= Name_Identity)
3085       then
3086          declare
3087             RCE : constant Node_Id :=
3088                     Make_Raise_Constraint_Error (Loc,
3089                       Reason => CE_Null_Exception_Id);
3090          begin
3091             Insert_After (N, RCE);
3092             Analyze (RCE);
3093          end;
3094       end if;
3095    end Expand_Call;
3096
3097    --------------------------
3098    -- Expand_Inlined_Call --
3099    --------------------------
3100
3101    procedure Expand_Inlined_Call
3102     (N         : Node_Id;
3103      Subp      : Entity_Id;
3104      Orig_Subp : Entity_Id)
3105    is
3106       Loc       : constant Source_Ptr := Sloc (N);
3107       Is_Predef : constant Boolean :=
3108                    Is_Predefined_File_Name
3109                      (Unit_File_Name (Get_Source_Unit (Subp)));
3110       Orig_Bod  : constant Node_Id :=
3111                     Body_To_Inline (Unit_Declaration_Node (Subp));
3112
3113       Blk      : Node_Id;
3114       Bod      : Node_Id;
3115       Decl     : Node_Id;
3116       Decls    : constant List_Id := New_List;
3117       Exit_Lab : Entity_Id := Empty;
3118       F        : Entity_Id;
3119       A        : Node_Id;
3120       Lab_Decl : Node_Id;
3121       Lab_Id   : Node_Id;
3122       New_A    : Node_Id;
3123       Num_Ret  : Int := 0;
3124       Ret_Type : Entity_Id;
3125       Targ     : Node_Id;
3126       Targ1    : Node_Id;
3127       Temp     : Entity_Id;
3128       Temp_Typ : Entity_Id;
3129
3130       Is_Unc : constant Boolean :=
3131                     Is_Array_Type (Etype (Subp))
3132                       and then not Is_Constrained (Etype (Subp));
3133       --  If the type returned by the function is unconstrained and the
3134       --  call can be inlined, special processing is required.
3135
3136       function Is_Null_Procedure return Boolean;
3137       --  Predicate to recognize stubbed procedures and null procedures, for
3138       --  which there is no need for the full inlining mechanism.
3139
3140       procedure Make_Exit_Label;
3141       --  Build declaration for exit label to be used in Return statements
3142
3143       function Process_Formals (N : Node_Id) return Traverse_Result;
3144       --  Replace occurrence of a formal with the corresponding actual, or
3145       --  the thunk generated for it.
3146
3147       function Process_Sloc (Nod : Node_Id) return Traverse_Result;
3148       --  If the call being expanded is that of an internal subprogram,
3149       --  set the sloc of the generated block to that of the call itself,
3150       --  so that the expansion is skipped by the -next- command in gdb.
3151       --  Same processing for a subprogram in a predefined file, e.g.
3152       --  Ada.Tags. If Debug_Generated_Code is true, suppress this change
3153       --  to simplify our own development.
3154
3155       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
3156       --  If the function body is a single expression, replace call with
3157       --  expression, else insert block appropriately.
3158
3159       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
3160       --  If procedure body has no local variables, inline body without
3161       --  creating block, otherwise rewrite call with block.
3162
3163       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean;
3164       --  Determine whether a formal parameter is used only once in Orig_Bod
3165
3166       -----------------------
3167       -- Is_Null_Procedure --
3168       -----------------------
3169
3170       function Is_Null_Procedure return Boolean is
3171          Decl : constant Node_Id := Unit_Declaration_Node (Subp);
3172
3173       begin
3174          if Ekind (Subp) /= E_Procedure then
3175             return False;
3176
3177          elsif Nkind (Orig_Bod) /= N_Subprogram_Body then
3178             return False;
3179
3180          --  Check if this is an Ada 2005 null procedure
3181
3182          elsif Nkind (Decl) = N_Subprogram_Declaration
3183            and then Null_Present (Specification (Decl))
3184          then
3185             return True;
3186
3187          --  Check if the body contains only a null statement, followed by the
3188          --  return statement added during expansion.
3189
3190          else
3191             declare
3192                Stat : constant Node_Id :=
3193                         First
3194                           (Statements (Handled_Statement_Sequence (Orig_Bod)));
3195
3196                Stat2 : constant Node_Id := Next (Stat);
3197
3198             begin
3199                return
3200                  Nkind (Stat) = N_Null_Statement
3201                    and then
3202                      (No (Stat2)
3203                        or else
3204                          (Nkind (Stat2) = N_Simple_Return_Statement
3205                            and then No (Next (Stat2))));
3206             end;
3207          end if;
3208       end Is_Null_Procedure;
3209
3210       ---------------------
3211       -- Make_Exit_Label --
3212       ---------------------
3213
3214       procedure Make_Exit_Label is
3215       begin
3216          --  Create exit label for subprogram if one does not exist yet
3217
3218          if No (Exit_Lab) then
3219             Lab_Id :=
3220               Make_Identifier (Loc,
3221                 Chars => New_Internal_Name ('L'));
3222             Set_Entity (Lab_Id,
3223               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
3224             Exit_Lab := Make_Label (Loc, Lab_Id);
3225
3226             Lab_Decl :=
3227               Make_Implicit_Label_Declaration (Loc,
3228                 Defining_Identifier  => Entity (Lab_Id),
3229                 Label_Construct      => Exit_Lab);
3230          end if;
3231       end Make_Exit_Label;
3232
3233       ---------------------
3234       -- Process_Formals --
3235       ---------------------
3236
3237       function Process_Formals (N : Node_Id) return Traverse_Result is
3238          A   : Entity_Id;
3239          E   : Entity_Id;
3240          Ret : Node_Id;
3241
3242       begin
3243          if Is_Entity_Name (N)
3244            and then Present (Entity (N))
3245          then
3246             E := Entity (N);
3247
3248             if Is_Formal (E)
3249               and then Scope (E) = Subp
3250             then
3251                A := Renamed_Object (E);
3252
3253                --  Rewrite the occurrence of the formal into an occurrence of
3254                --  the actual. Also establish visibility on the proper view of
3255                --  the actual's subtype for the body's context (if the actual's
3256                --  subtype is private at the call point but its full view is
3257                --  visible to the body, then the inlined tree here must be
3258                --  analyzed with the full view).
3259
3260                if Is_Entity_Name (A) then
3261                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
3262                   Check_Private_View (N);
3263
3264                elsif Nkind (A) = N_Defining_Identifier then
3265                   Rewrite (N, New_Occurrence_Of (A, Loc));
3266                   Check_Private_View (N);
3267
3268                --  Numeric literal
3269
3270                else
3271                   Rewrite (N, New_Copy (A));
3272                end if;
3273             end if;
3274
3275             return Skip;
3276
3277          elsif Nkind (N) = N_Simple_Return_Statement then
3278             if No (Expression (N)) then
3279                Make_Exit_Label;
3280                Rewrite (N,
3281                  Make_Goto_Statement (Loc,
3282                    Name => New_Copy (Lab_Id)));
3283
3284             else
3285                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
3286                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
3287                then
3288                   --  Function body is a single expression. No need for
3289                   --  exit label.
3290
3291                   null;
3292
3293                else
3294                   Num_Ret := Num_Ret + 1;
3295                   Make_Exit_Label;
3296                end if;
3297
3298                --  Because of the presence of private types, the views of the
3299                --  expression and the context may be different, so place an
3300                --  unchecked conversion to the context type to avoid spurious
3301                --  errors, eg. when the expression is a numeric literal and
3302                --  the context is private. If the expression is an aggregate,
3303                --  use a qualified expression, because an aggregate is not a
3304                --  legal argument of a conversion.
3305
3306                if Nkind (Expression (N)) = N_Aggregate
3307                  or else Nkind (Expression (N)) = N_Null
3308                then
3309                   Ret :=
3310                     Make_Qualified_Expression (Sloc (N),
3311                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
3312                        Expression => Relocate_Node (Expression (N)));
3313                else
3314                   Ret :=
3315                     Unchecked_Convert_To
3316                       (Ret_Type, Relocate_Node (Expression (N)));
3317                end if;
3318
3319                if Nkind (Targ) = N_Defining_Identifier then
3320                   Rewrite (N,
3321                     Make_Assignment_Statement (Loc,
3322                       Name => New_Occurrence_Of (Targ, Loc),
3323                       Expression => Ret));
3324                else
3325                   Rewrite (N,
3326                     Make_Assignment_Statement (Loc,
3327                       Name => New_Copy (Targ),
3328                       Expression => Ret));
3329                end if;
3330
3331                Set_Assignment_OK (Name (N));
3332
3333                if Present (Exit_Lab) then
3334                   Insert_After (N,
3335                     Make_Goto_Statement (Loc,
3336                       Name => New_Copy (Lab_Id)));
3337                end if;
3338             end if;
3339
3340             return OK;
3341
3342          --  Remove pragma Unreferenced since it may refer to formals that
3343          --  are not visible in the inlined body, and in any case we will
3344          --  not be posting warnings on the inlined body so it is unneeded.
3345
3346          elsif Nkind (N) = N_Pragma
3347            and then Chars (N) = Name_Unreferenced
3348          then
3349             Rewrite (N, Make_Null_Statement (Sloc (N)));
3350             return OK;
3351
3352          else
3353             return OK;
3354          end if;
3355       end Process_Formals;
3356
3357       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
3358
3359       ------------------
3360       -- Process_Sloc --
3361       ------------------
3362
3363       function Process_Sloc (Nod : Node_Id) return Traverse_Result is
3364       begin
3365          if not Debug_Generated_Code then
3366             Set_Sloc (Nod, Sloc (N));
3367             Set_Comes_From_Source (Nod, False);
3368          end if;
3369
3370          return OK;
3371       end Process_Sloc;
3372
3373       procedure Reset_Slocs is new Traverse_Proc (Process_Sloc);
3374
3375       ---------------------------
3376       -- Rewrite_Function_Call --
3377       ---------------------------
3378
3379       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
3380          HSS : constant Node_Id := Handled_Statement_Sequence (Blk);
3381          Fst : constant Node_Id := First (Statements (HSS));
3382
3383       begin
3384          --  Optimize simple case: function body is a single return statement,
3385          --  which has been expanded into an assignment.
3386
3387          if Is_Empty_List (Declarations (Blk))
3388            and then Nkind (Fst) = N_Assignment_Statement
3389            and then No (Next (Fst))
3390          then
3391
3392             --  The function call may have been rewritten as the temporary
3393             --  that holds the result of the call, in which case remove the
3394             --  now useless declaration.
3395
3396             if Nkind (N) = N_Identifier
3397               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3398             then
3399                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
3400             end if;
3401
3402             Rewrite (N, Expression (Fst));
3403
3404          elsif Nkind (N) = N_Identifier
3405            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
3406          then
3407             --  The block assigns the result of the call to the temporary
3408
3409             Insert_After (Parent (Entity (N)), Blk);
3410
3411          elsif Nkind (Parent (N)) = N_Assignment_Statement
3412            and then
3413             (Is_Entity_Name (Name (Parent (N)))
3414                or else
3415                   (Nkind (Name (Parent (N))) = N_Explicit_Dereference
3416                     and then Is_Entity_Name (Prefix (Name (Parent (N))))))
3417          then
3418             --  Replace assignment with the block
3419
3420             declare
3421                Original_Assignment : constant Node_Id := Parent (N);
3422
3423             begin
3424                --  Preserve the original assignment node to keep the complete
3425                --  assignment subtree consistent enough for Analyze_Assignment
3426                --  to proceed (specifically, the original Lhs node must still
3427                --  have an assignment statement as its parent).
3428
3429                --  We cannot rely on Original_Node to go back from the block
3430                --  node to the assignment node, because the assignment might
3431                --  already be a rewrite substitution.
3432
3433                Discard_Node (Relocate_Node (Original_Assignment));
3434                Rewrite (Original_Assignment, Blk);
3435             end;
3436
3437          elsif Nkind (Parent (N)) = N_Object_Declaration then
3438             Set_Expression (Parent (N), Empty);
3439             Insert_After (Parent (N), Blk);
3440
3441          elsif Is_Unc then
3442             Insert_Before (Parent (N), Blk);
3443          end if;
3444       end Rewrite_Function_Call;
3445
3446       ----------------------------
3447       -- Rewrite_Procedure_Call --
3448       ----------------------------
3449
3450       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
3451          HSS  : constant Node_Id := Handled_Statement_Sequence (Blk);
3452       begin
3453          --  If there is a transient scope for N, this will be the scope of the
3454          --  actions for N, and the statements in Blk need to be within this
3455          --  scope. For example, they need to have visibility on the constant
3456          --  declarations created for the formals.
3457
3458          --  If N needs no transient scope, and if there are no declarations in
3459          --  the inlined body, we can do a little optimization and insert the
3460          --  statements for the body directly after N, and rewrite N to a
3461          --  null statement, instead of rewriting N into a full-blown block
3462          --  statement.
3463
3464          if not Scope_Is_Transient
3465            and then Is_Empty_List (Declarations (Blk))
3466          then
3467             Insert_List_After (N, Statements (HSS));
3468             Rewrite (N, Make_Null_Statement (Loc));
3469          else
3470             Rewrite (N, Blk);
3471          end if;
3472       end Rewrite_Procedure_Call;
3473
3474       -------------------------
3475       -- Formal_Is_Used_Once --
3476       -------------------------
3477
3478       function Formal_Is_Used_Once (Formal : Entity_Id) return Boolean is
3479          Use_Counter : Int := 0;
3480
3481          function Count_Uses (N : Node_Id) return Traverse_Result;
3482          --  Traverse the tree and count the uses of the formal parameter.
3483          --  In this case, for optimization purposes, we do not need to
3484          --  continue the traversal once more than one use is encountered.
3485
3486          ----------------
3487          -- Count_Uses --
3488          ----------------
3489
3490          function Count_Uses (N : Node_Id) return Traverse_Result is
3491          begin
3492             --  The original node is an identifier
3493
3494             if Nkind (N) = N_Identifier
3495               and then Present (Entity (N))
3496
3497                --  Original node's entity points to the one in the copied body
3498
3499               and then Nkind (Entity (N)) = N_Identifier
3500               and then Present (Entity (Entity (N)))
3501
3502                --  The entity of the copied node is the formal parameter
3503
3504               and then Entity (Entity (N)) = Formal
3505             then
3506                Use_Counter := Use_Counter + 1;
3507
3508                if Use_Counter > 1 then
3509
3510                   --  Denote more than one use and abandon the traversal
3511
3512                   Use_Counter := 2;
3513                   return Abandon;
3514
3515                end if;
3516             end if;
3517
3518             return OK;
3519          end Count_Uses;
3520
3521          procedure Count_Formal_Uses is new Traverse_Proc (Count_Uses);
3522
3523       --  Start of processing for Formal_Is_Used_Once
3524
3525       begin
3526          Count_Formal_Uses (Orig_Bod);
3527          return Use_Counter = 1;
3528       end Formal_Is_Used_Once;
3529
3530    --  Start of processing for Expand_Inlined_Call
3531
3532    begin
3533       --  Check for special case of To_Address call, and if so, just do an
3534       --  unchecked conversion instead of expanding the call. Not only is this
3535       --  more efficient, but it also avoids problem with order of elaboration
3536       --  when address clauses are inlined (address expression elaborated at
3537       --  wrong point).
3538
3539       if Subp = RTE (RE_To_Address) then
3540          Rewrite (N,
3541            Unchecked_Convert_To
3542             (RTE (RE_Address),
3543              Relocate_Node (First_Actual (N))));
3544          return;
3545
3546       elsif Is_Null_Procedure  then
3547          Rewrite (N, Make_Null_Statement (Loc));
3548          return;
3549       end if;
3550
3551       --  Check for an illegal attempt to inline a recursive procedure. If the
3552       --  subprogram has parameters this is detected when trying to supply a
3553       --  binding for parameters that already have one. For parameterless
3554       --  subprograms this must be done explicitly.
3555
3556       if In_Open_Scopes (Subp) then
3557          Error_Msg_N ("call to recursive subprogram cannot be inlined?", N);
3558          Set_Is_Inlined (Subp, False);
3559          return;
3560       end if;
3561
3562       if Nkind (Orig_Bod) = N_Defining_Identifier
3563         or else Nkind (Orig_Bod) = N_Defining_Operator_Symbol
3564       then
3565          --  Subprogram is a renaming_as_body. Calls appearing after the
3566          --  renaming can be replaced with calls to the renamed entity
3567          --  directly, because the subprograms are subtype conformant. If
3568          --  the renamed subprogram is an inherited operation, we must redo
3569          --  the expansion because implicit conversions may be needed.
3570
3571          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
3572
3573          if Present (Alias (Orig_Bod)) then
3574             Expand_Call (N);
3575          end if;
3576
3577          return;
3578       end if;
3579
3580       --  Use generic machinery to copy body of inlined subprogram, as if it
3581       --  were an instantiation, resetting source locations appropriately, so
3582       --  that nested inlined calls appear in the main unit.
3583
3584       Save_Env (Subp, Empty);
3585       Set_Copied_Sloc_For_Inlined_Body (N, Defining_Entity (Orig_Bod));
3586
3587       Bod := Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
3588       Blk :=
3589         Make_Block_Statement (Loc,
3590           Declarations => Declarations (Bod),
3591           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
3592
3593       if No (Declarations (Bod)) then
3594          Set_Declarations (Blk, New_List);
3595       end if;
3596
3597       --  For the unconstrained case, capture the name of the local
3598       --  variable that holds the result. This must be the first declaration
3599       --  in the block, because its bounds cannot depend on local variables.
3600       --  Otherwise there is no way to declare the result outside of the
3601       --  block. Needless to say, in general the bounds will depend on the
3602       --  actuals in the call.
3603
3604       if Is_Unc then
3605          Targ1 := Defining_Identifier (First (Declarations (Blk)));
3606       end if;
3607
3608       --  If this is a derived function, establish the proper return type
3609
3610       if Present (Orig_Subp)
3611         and then Orig_Subp /= Subp
3612       then
3613          Ret_Type := Etype (Orig_Subp);
3614       else
3615          Ret_Type := Etype (Subp);
3616       end if;
3617
3618       --  Create temporaries for the actuals that are expressions, or that
3619       --  are scalars and require copying to preserve semantics.
3620
3621       F := First_Formal (Subp);
3622       A := First_Actual (N);
3623       while Present (F) loop
3624          if Present (Renamed_Object (F)) then
3625             Error_Msg_N ("cannot inline call to recursive subprogram", N);
3626             return;
3627          end if;
3628
3629          --  If the argument may be a controlling argument in a call within
3630          --  the inlined body, we must preserve its classwide nature to insure
3631          --  that dynamic dispatching take place subsequently. If the formal
3632          --  has a constraint it must be preserved to retain the semantics of
3633          --  the body.
3634
3635          if Is_Class_Wide_Type (Etype (F))
3636            or else (Is_Access_Type (Etype (F))
3637                       and then
3638                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
3639          then
3640             Temp_Typ := Etype (F);
3641
3642          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
3643            and then Etype (F) /= Base_Type (Etype (F))
3644          then
3645             Temp_Typ := Etype (F);
3646
3647          else
3648             Temp_Typ := Etype (A);
3649          end if;
3650
3651          --  If the actual is a simple name or a literal, no need to
3652          --  create a temporary, object can be used directly.
3653
3654          --  If the actual is a literal and the formal has its address taken,
3655          --  we cannot pass the literal itself as an argument, so its value
3656          --  must be captured in a temporary.
3657
3658          if (Is_Entity_Name (A)
3659               and then
3660                (not Is_Scalar_Type (Etype (A))
3661                  or else Ekind (Entity (A)) = E_Enumeration_Literal))
3662
3663          --  When the actual is an identifier and the corresponding formal
3664          --  is used only once in the original body, the formal can be
3665          --  substituted directly with the actual parameter.
3666
3667            or else (Nkind (A) = N_Identifier
3668              and then Formal_Is_Used_Once (F))
3669
3670            or else
3671              ((Nkind (A) = N_Real_Literal    or else
3672                Nkind (A) = N_Integer_Literal or else
3673                Nkind (A) = N_Character_Literal)
3674               and then not Address_Taken (F))
3675          then
3676             if Etype (F) /= Etype (A) then
3677                Set_Renamed_Object
3678                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
3679             else
3680                Set_Renamed_Object (F, A);
3681             end if;
3682
3683          else
3684             Temp :=
3685               Make_Defining_Identifier (Loc,
3686                 Chars => New_Internal_Name ('C'));
3687
3688             --  If the actual for an in/in-out parameter is a view conversion,
3689             --  make it into an unchecked conversion, given that an untagged
3690             --  type conversion is not a proper object for a renaming.
3691
3692             --  In-out conversions that involve real conversions have already
3693             --  been transformed in Expand_Actuals.
3694
3695             if Nkind (A) = N_Type_Conversion
3696               and then Ekind (F) /= E_In_Parameter
3697             then
3698                New_A :=
3699                  Make_Unchecked_Type_Conversion (Loc,
3700                    Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
3701                    Expression   => Relocate_Node (Expression (A)));
3702
3703             elsif Etype (F) /= Etype (A) then
3704                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
3705                Temp_Typ := Etype (F);
3706
3707             else
3708                New_A := Relocate_Node (A);
3709             end if;
3710
3711             Set_Sloc (New_A, Sloc (N));
3712
3713             --  If the actual has a by-reference type, it cannot be copied, so
3714             --  its value is captured in a renaming declaration. Otherwise
3715             --  declare a local constant initialized with the actual.
3716
3717             if Ekind (F) = E_In_Parameter
3718               and then not Is_Limited_Type (Etype (A))
3719               and then not Is_Tagged_Type  (Etype (A))
3720             then
3721                Decl :=
3722                  Make_Object_Declaration (Loc,
3723                    Defining_Identifier => Temp,
3724                    Constant_Present => True,
3725                    Object_Definition => New_Occurrence_Of (Temp_Typ, Loc),
3726                    Expression => New_A);
3727             else
3728                Decl :=
3729                  Make_Object_Renaming_Declaration (Loc,
3730                    Defining_Identifier => Temp,
3731                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
3732                    Name                => New_A);
3733             end if;
3734
3735             Append (Decl, Decls);
3736             Set_Renamed_Object (F, Temp);
3737          end if;
3738
3739          Next_Formal (F);
3740          Next_Actual (A);
3741       end loop;
3742
3743       --  Establish target of function call. If context is not assignment or
3744       --  declaration, create a temporary as a target. The declaration for
3745       --  the temporary may be subsequently optimized away if the body is a
3746       --  single expression, or if the left-hand side of the assignment is
3747       --  simple enough, i.e. an entity or an explicit dereference of one.
3748
3749       if Ekind (Subp) = E_Function then
3750          if Nkind (Parent (N)) = N_Assignment_Statement
3751            and then Is_Entity_Name (Name (Parent (N)))
3752          then
3753             Targ := Name (Parent (N));
3754
3755          elsif Nkind (Parent (N)) = N_Assignment_Statement
3756            and then Nkind (Name (Parent (N))) = N_Explicit_Dereference
3757            and then Is_Entity_Name (Prefix (Name (Parent (N))))
3758          then
3759             Targ := Name (Parent (N));
3760
3761          else
3762             --  Replace call with temporary and create its declaration
3763
3764             Temp :=
3765               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
3766             Set_Is_Internal (Temp);
3767
3768             --  For the unconstrained case. the generated temporary has the
3769             --  same constrained declaration as the result variable.
3770             --  It may eventually be possible to remove that temporary and
3771             --  use the result variable directly.
3772
3773             if Is_Unc then
3774                Decl :=
3775                  Make_Object_Declaration (Loc,
3776                    Defining_Identifier => Temp,
3777                    Object_Definition =>
3778                      New_Copy_Tree (Object_Definition (Parent (Targ1))));
3779
3780                Replace_Formals (Decl);
3781
3782             else
3783                Decl :=
3784                  Make_Object_Declaration (Loc,
3785                    Defining_Identifier => Temp,
3786                    Object_Definition =>
3787                      New_Occurrence_Of (Ret_Type, Loc));
3788
3789                Set_Etype (Temp, Ret_Type);
3790             end if;
3791
3792             Set_No_Initialization (Decl);
3793             Append (Decl, Decls);
3794             Rewrite (N, New_Occurrence_Of (Temp, Loc));
3795             Targ := Temp;
3796          end if;
3797       end if;
3798
3799       Insert_Actions (N, Decls);
3800
3801       --  Traverse the tree and replace formals with actuals or their thunks.
3802       --  Attach block to tree before analysis and rewriting.
3803
3804       Replace_Formals (Blk);
3805       Set_Parent (Blk, N);
3806
3807       if not Comes_From_Source (Subp)
3808         or else Is_Predef
3809       then
3810          Reset_Slocs (Blk);
3811       end if;
3812
3813       if Present (Exit_Lab) then
3814
3815          --  If the body was a single expression, the single return statement
3816          --  and the corresponding label are useless.
3817
3818          if Num_Ret = 1
3819            and then
3820              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
3821                N_Goto_Statement
3822          then
3823             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
3824          else
3825             Append (Lab_Decl, (Declarations (Blk)));
3826             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
3827          end if;
3828       end if;
3829
3830       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
3831       --  conflicting private views that Gigi would ignore. If this is
3832       --  predefined unit, analyze with checks off, as is done in the non-
3833       --  inlined run-time units.
3834
3835       declare
3836          I_Flag : constant Boolean := In_Inlined_Body;
3837
3838       begin
3839          In_Inlined_Body := True;
3840
3841          if Is_Predef then
3842             declare
3843                Style : constant Boolean := Style_Check;
3844             begin
3845                Style_Check := False;
3846                Analyze (Blk, Suppress => All_Checks);
3847                Style_Check := Style;
3848             end;
3849
3850          else
3851             Analyze (Blk);
3852          end if;
3853
3854          In_Inlined_Body := I_Flag;
3855       end;
3856
3857       if Ekind (Subp) = E_Procedure then
3858          Rewrite_Procedure_Call (N, Blk);
3859       else
3860          Rewrite_Function_Call (N, Blk);
3861
3862          --  For the unconstrained case, the replacement of the call has been
3863          --  made prior to the complete analysis of the generated declarations.
3864          --  Propagate the proper type now.
3865
3866          if Is_Unc then
3867             if Nkind (N) = N_Identifier then
3868                Set_Etype (N, Etype (Entity (N)));
3869             else
3870                Set_Etype (N, Etype (Targ1));
3871             end if;
3872          end if;
3873       end if;
3874
3875       Restore_Env;
3876
3877       --  Cleanup mapping between formals and actuals for other expansions
3878
3879       F := First_Formal (Subp);
3880       while Present (F) loop
3881          Set_Renamed_Object (F, Empty);
3882          Next_Formal (F);
3883       end loop;
3884    end Expand_Inlined_Call;
3885
3886    ----------------------------
3887    -- Expand_N_Function_Call --
3888    ----------------------------
3889
3890    procedure Expand_N_Function_Call (N : Node_Id) is
3891       Typ   : constant Entity_Id := Etype (N);
3892
3893       function Returned_By_Reference return Boolean;
3894       --  If the return type is returned through the secondary stack; that is
3895       --  by reference, we don't want to create a temp to force stack checking.
3896       --  ???"sec stack" is not right -- Ada 95 return-by-reference object are
3897       --  returned wherever they are.
3898       --  Shouldn't this function be moved to exp_util???
3899
3900       function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean;
3901       --  If the call is the right side of an assignment or the expression in
3902       --  an object declaration, we don't need to create a temp as the left
3903       --  side will already trigger stack checking if necessary.
3904       --
3905       --  If the call is a component in an extension aggregate, it will be
3906       --  expanded into assignments as well, so no temporary is needed. This
3907       --  also solves the problem of functions returning types with unknown
3908       --  discriminants, where it is not possible to declare an object of the
3909       --  type altogether.
3910
3911       ---------------------------
3912       -- Returned_By_Reference --
3913       ---------------------------
3914
3915       function Returned_By_Reference return Boolean is
3916          S : Entity_Id;
3917
3918       begin
3919          if Is_Inherently_Limited_Type (Typ) then
3920             return True;
3921
3922          elsif Nkind (Parent (N)) /= N_Simple_Return_Statement then
3923             return False;
3924
3925          elsif Requires_Transient_Scope (Typ) then
3926
3927             --  Verify that the return type of the enclosing function has the
3928             --  same constrained status as that of the expression.
3929
3930             S := Current_Scope;
3931             while Ekind (S) /= E_Function loop
3932                S := Scope (S);
3933             end loop;
3934
3935             return Is_Constrained (Typ) = Is_Constrained (Etype (S));
3936          else
3937             return False;
3938          end if;
3939       end Returned_By_Reference;
3940
3941       ---------------------------
3942       -- Rhs_Of_Assign_Or_Decl --
3943       ---------------------------
3944
3945       function Rhs_Of_Assign_Or_Decl (N : Node_Id) return Boolean is
3946       begin
3947          if (Nkind (Parent (N)) = N_Assignment_Statement
3948                and then Expression (Parent (N)) = N)
3949            or else
3950              (Nkind (Parent (N)) = N_Qualified_Expression
3951                 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
3952                   and then Expression (Parent (Parent (N))) = Parent (N))
3953            or else
3954              (Nkind (Parent (N)) = N_Object_Declaration
3955                 and then Expression (Parent (N)) = N)
3956            or else
3957              (Nkind (Parent (N)) = N_Component_Association
3958                 and then Expression (Parent (N)) = N
3959                   and then Nkind (Parent (Parent (N))) = N_Aggregate
3960                     and then Rhs_Of_Assign_Or_Decl (Parent (Parent (N))))
3961            or else
3962              (Nkind (Parent (N)) = N_Extension_Aggregate
3963                and then Is_Private_Type (Etype (Typ)))
3964          then
3965             return True;
3966          else
3967             return False;
3968          end if;
3969       end Rhs_Of_Assign_Or_Decl;
3970
3971    --  Start of processing for Expand_N_Function_Call
3972
3973    begin
3974       --  A special check. If stack checking is enabled, and the return type
3975       --  might generate a large temporary, and the call is not the right side
3976       --  of an assignment, then generate an explicit temporary. We do this
3977       --  because otherwise gigi may generate a large temporary on the fly and
3978       --  this can cause trouble with stack checking.
3979
3980       --  This is unnecessary if the call is the expression in an object
3981       --  declaration, or if it appears outside of any library unit. This can
3982       --  only happen if it appears as an actual in a library-level instance,
3983       --  in which case a temporary will be generated for it once the instance
3984       --  itself is installed.
3985
3986       if May_Generate_Large_Temp (Typ)
3987         and then not Rhs_Of_Assign_Or_Decl (N)
3988         and then not Returned_By_Reference
3989         and then Current_Scope /= Standard_Standard
3990       then
3991          if Stack_Checking_Enabled then
3992
3993             --  Note: it might be thought that it would be OK to use a call to
3994             --  Force_Evaluation here, but that's not good enough, because
3995             --  that can results in a 'Reference construct that may still need
3996             --  a temporary.
3997
3998             declare
3999                Loc      : constant Source_Ptr := Sloc (N);
4000                Temp_Obj : constant Entity_Id :=
4001                             Make_Defining_Identifier (Loc,
4002                               Chars => New_Internal_Name ('F'));
4003                Temp_Typ : Entity_Id := Typ;
4004                Decl     : Node_Id;
4005                A        : Node_Id;
4006                F        : Entity_Id;
4007                Proc     : Entity_Id;
4008
4009             begin
4010                if Is_Tagged_Type (Typ)
4011                  and then Present (Controlling_Argument (N))
4012                then
4013                   if Nkind (Parent (N)) /= N_Procedure_Call_Statement
4014                     and then Nkind (Parent (N)) /= N_Function_Call
4015                   then
4016                      --  If this is a tag-indeterminate call, the object must
4017                      --  be classwide.
4018
4019                      if Is_Tag_Indeterminate (N) then
4020                         Temp_Typ := Class_Wide_Type (Typ);
4021                      end if;
4022
4023                   else
4024                      --  If this is a dispatching call that is itself the
4025                      --  controlling argument of an enclosing call, the
4026                      --  nominal subtype of the object that replaces it must
4027                      --  be classwide, so that dispatching will take place
4028                      --  properly. If it is not a controlling argument, the
4029                      --  object is not classwide.
4030
4031                      Proc := Entity (Name (Parent (N)));
4032
4033                      F := First_Formal (Proc);
4034                      A := First_Actual (Parent (N));
4035                      while A /= N loop
4036                         Next_Formal (F);
4037                         Next_Actual (A);
4038                      end loop;
4039
4040                      if Is_Controlling_Formal (F) then
4041                         Temp_Typ := Class_Wide_Type (Typ);
4042                      end if;
4043                   end if;
4044                end if;
4045
4046                Decl :=
4047                  Make_Object_Declaration (Loc,
4048                    Defining_Identifier => Temp_Obj,
4049                    Object_Definition   => New_Occurrence_Of (Temp_Typ, Loc),
4050                    Constant_Present    => True,
4051                    Expression          => Relocate_Node (N));
4052                Set_Assignment_OK (Decl);
4053
4054                Insert_Actions (N, New_List (Decl));
4055                Rewrite (N, New_Occurrence_Of (Temp_Obj, Loc));
4056             end;
4057
4058          else
4059             --  If stack-checking is not enabled, increment serial number
4060             --  for internal names, so that subsequent symbols are consistent
4061             --  with and without stack-checking.
4062
4063             Synchronize_Serial_Number;
4064
4065             --  Now we can expand the call with consistent symbol names
4066
4067             Expand_Call (N);
4068          end if;
4069
4070       --  Normal case, expand the call
4071
4072       else
4073          Expand_Call (N);
4074       end if;
4075    end Expand_N_Function_Call;
4076
4077    ---------------------------------------
4078    -- Expand_N_Procedure_Call_Statement --
4079    ---------------------------------------
4080
4081    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
4082    begin
4083       Expand_Call (N);
4084    end Expand_N_Procedure_Call_Statement;
4085
4086    ------------------------------
4087    -- Expand_N_Subprogram_Body --
4088    ------------------------------
4089
4090    --  Add poll call if ATC polling is enabled, unless the body will be
4091    --  inlined by the back-end.
4092
4093    --  Add dummy push/pop label nodes at start and end to clear any local
4094    --  exception indications if local-exception-to-goto optimization active.
4095
4096    --  Add return statement if last statement in body is not a return statement
4097    --  (this makes things easier on Gigi which does not want to have to handle
4098    --  a missing return).
4099
4100    --  Add call to Activate_Tasks if body is a task activator
4101
4102    --  Deal with possible detection of infinite recursion
4103
4104    --  Eliminate body completely if convention stubbed
4105
4106    --  Encode entity names within body, since we will not need to reference
4107    --  these entities any longer in the front end.
4108
4109    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
4110
4111    --  Reset Pure indication if any parameter has root type System.Address
4112
4113    --  Wrap thread body
4114
4115    procedure Expand_N_Subprogram_Body (N : Node_Id) is
4116       Loc      : constant Source_Ptr := Sloc (N);
4117       H        : constant Node_Id    := Handled_Statement_Sequence (N);
4118       Body_Id  : Entity_Id;
4119       Spec_Id  : Entity_Id;
4120       Except_H : Node_Id;
4121       Scop     : Entity_Id;
4122       Dec      : Node_Id;
4123       Next_Op  : Node_Id;
4124       L        : List_Id;
4125
4126       procedure Add_Return (S : List_Id);
4127       --  Append a return statement to the statement sequence S if the last
4128       --  statement is not already a return or a goto statement. Note that
4129       --  the latter test is not critical, it does not matter if we add a
4130       --  few extra returns, since they get eliminated anyway later on.
4131
4132       ----------------
4133       -- Add_Return --
4134       ----------------
4135
4136       procedure Add_Return (S : List_Id) is
4137          Last_Stm : Node_Id;
4138          Loc      : Source_Ptr;
4139
4140       begin
4141          --  Get last statement, ignoring any Pop_xxx_Label nodes, which are
4142          --  not relevant in this context since they are not executable.
4143
4144          Last_Stm := Last (S);
4145          while Nkind (Last_Stm) in N_Pop_xxx_Label loop
4146             Prev (Last_Stm);
4147          end loop;
4148
4149          --  Now insert return unless last statement is a transfer
4150
4151          if not Is_Transfer (Last_Stm) then
4152
4153             --  The source location for the return is the end label of the
4154             --  procedure if present. Otherwise use the sloc of the last
4155             --  statement in the list. If the list comes from a generated
4156             --  exception handler and we are not debugging generated code,
4157             --  all the statements within the handler are made invisible
4158             --  to the debugger.
4159
4160             if Nkind (Parent (S)) = N_Exception_Handler
4161               and then not Comes_From_Source (Parent (S))
4162             then
4163                Loc := Sloc (Last_Stm);
4164
4165             elsif Present (End_Label (H)) then
4166                Loc := Sloc (End_Label (H));
4167
4168             else
4169                Loc := Sloc (Last_Stm);
4170             end if;
4171
4172             Append_To (S, Make_Simple_Return_Statement (Loc));
4173          end if;
4174       end Add_Return;
4175
4176    --  Start of processing for Expand_N_Subprogram_Body
4177
4178    begin
4179       --  Set L to either the list of declarations if present, or
4180       --  to the list of statements if no declarations are present.
4181       --  This is used to insert new stuff at the start.
4182
4183       if Is_Non_Empty_List (Declarations (N)) then
4184          L := Declarations (N);
4185       else
4186          L := Statements (H);
4187       end if;
4188
4189       --  If local-exception-to-goto optimization active, insert dummy push
4190       --  statements at start, and dummy pop statements at end.
4191
4192       if (Debug_Flag_Dot_G
4193            or else Restriction_Active (No_Exception_Propagation))
4194         and then Is_Non_Empty_List (L)
4195       then
4196          declare
4197             FS  : constant Node_Id    := First (L);
4198             FL  : constant Source_Ptr := Sloc (FS);
4199             LS  : Node_Id;
4200             LL  : Source_Ptr;
4201
4202          begin
4203             --  LS points to either last statement, if statements are present
4204             --  or to the last declaration if there are no statements present.
4205             --  It is the node after which the pop's are generated.
4206
4207             if Is_Non_Empty_List (Statements (H)) then
4208                LS := Last (Statements (H));
4209             else
4210                LS := Last (L);
4211             end if;
4212
4213             LL := Sloc (LS);
4214
4215             Insert_List_Before_And_Analyze (FS, New_List (
4216               Make_Push_Constraint_Error_Label (FL),
4217               Make_Push_Program_Error_Label    (FL),
4218               Make_Push_Storage_Error_Label    (FL)));
4219
4220             Insert_List_After_And_Analyze (LS, New_List (
4221               Make_Pop_Constraint_Error_Label  (LL),
4222               Make_Pop_Program_Error_Label     (LL),
4223               Make_Pop_Storage_Error_Label     (LL)));
4224          end;
4225       end if;
4226
4227       --  Find entity for subprogram
4228
4229       Body_Id := Defining_Entity (N);
4230
4231       if Present (Corresponding_Spec (N)) then
4232          Spec_Id := Corresponding_Spec (N);
4233       else
4234          Spec_Id := Body_Id;
4235       end if;
4236
4237       --  Need poll on entry to subprogram if polling enabled. We only do this
4238       --  for non-empty subprograms, since it does not seem necessary to poll
4239       --  for a dummy null subprogram. Do not add polling point if calls to
4240       --  this subprogram will be inlined by the back-end, to avoid repeated
4241       --  polling points in nested inlinings.
4242
4243       if Is_Non_Empty_List (L) then
4244          if Is_Inlined (Spec_Id)
4245            and then Front_End_Inlining
4246            and then Optimization_Level > 1
4247          then
4248             null;
4249          else
4250             Generate_Poll_Call (First (L));
4251          end if;
4252       end if;
4253
4254       --  If this is a Pure function which has any parameters whose root
4255       --  type is System.Address, reset the Pure indication, since it will
4256       --  likely cause incorrect code to be generated as the parameter is
4257       --  probably a pointer, and the fact that the same pointer is passed
4258       --  does not mean that the same value is being referenced.
4259
4260       --  Note that if the programmer gave an explicit Pure_Function pragma,
4261       --  then we believe the programmer, and leave the subprogram Pure.
4262
4263       --  This code should probably be at the freeze point, so that it
4264       --  happens even on a -gnatc (or more importantly -gnatt) compile
4265       --  so that the semantic tree has Is_Pure set properly ???
4266
4267       if Is_Pure (Spec_Id)
4268         and then Is_Subprogram (Spec_Id)
4269         and then not Has_Pragma_Pure_Function (Spec_Id)
4270       then
4271          declare
4272             F : Entity_Id;
4273
4274          begin
4275             F := First_Formal (Spec_Id);
4276             while Present (F) loop
4277                if Is_Descendent_Of_Address (Etype (F)) then
4278                   Set_Is_Pure (Spec_Id, False);
4279
4280                   if Spec_Id /= Body_Id then
4281                      Set_Is_Pure (Body_Id, False);
4282                   end if;
4283
4284                   exit;
4285                end if;
4286
4287                Next_Formal (F);
4288             end loop;
4289          end;
4290       end if;
4291
4292       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
4293
4294       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
4295          declare
4296             F : Entity_Id;
4297
4298          begin
4299             --  Loop through formals
4300
4301             F := First_Formal (Spec_Id);
4302             while Present (F) loop
4303                if Is_Scalar_Type (Etype (F))
4304                  and then Ekind (F) = E_Out_Parameter
4305                then
4306                   --  Insert the initialization. We turn off validity checks
4307                   --  for this assignment, since we do not want any check on
4308                   --  the initial value itself (which may well be invalid).
4309
4310                   Insert_Before_And_Analyze (First (L),
4311                     Make_Assignment_Statement (Loc,
4312                       Name       => New_Occurrence_Of (F, Loc),
4313                       Expression => Get_Simple_Init_Val (Etype (F), Loc)),
4314                     Suppress => Validity_Check);
4315                end if;
4316
4317                Next_Formal (F);
4318             end loop;
4319          end;
4320       end if;
4321
4322       Scop := Scope (Spec_Id);
4323
4324       --  Add discriminal renamings to protected subprograms. Install new
4325       --  discriminals for expansion of the next subprogram of this protected
4326       --  type, if any.
4327
4328       if Is_List_Member (N)
4329         and then Present (Parent (List_Containing (N)))
4330         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
4331       then
4332          Add_Discriminal_Declarations
4333            (Declarations (N), Scop, Name_uObject, Loc);
4334          Add_Private_Declarations
4335            (Declarations (N), Scop, Name_uObject, Loc);
4336
4337          --  Associate privals and discriminals with the next protected
4338          --  operation body to be expanded. These are used to expand references
4339          --  to private data objects and discriminants, respectively.
4340
4341          Next_Op := Next_Protected_Operation (N);
4342
4343          if Present (Next_Op) then
4344             Dec := Parent (Base_Type (Scop));
4345             Set_Privals (Dec, Next_Op, Loc);
4346             Set_Discriminals (Dec);
4347          end if;
4348       end if;
4349
4350       --  Clear out statement list for stubbed procedure
4351
4352       if Present (Corresponding_Spec (N)) then
4353          Set_Elaboration_Flag (N, Spec_Id);
4354
4355          if Convention (Spec_Id) = Convention_Stubbed
4356            or else Is_Eliminated (Spec_Id)
4357          then
4358             Set_Declarations (N, Empty_List);
4359             Set_Handled_Statement_Sequence (N,
4360               Make_Handled_Sequence_Of_Statements (Loc,
4361                 Statements => New_List (
4362                   Make_Null_Statement (Loc))));
4363             return;
4364          end if;
4365       end if;
4366
4367       --  Returns_By_Ref flag is normally set when the subprogram is frozen
4368       --  but subprograms with no specs are not frozen.
4369
4370       declare
4371          Typ  : constant Entity_Id := Etype (Spec_Id);
4372          Utyp : constant Entity_Id := Underlying_Type (Typ);
4373
4374       begin
4375          if not Acts_As_Spec (N)
4376            and then Nkind (Parent (Parent (Spec_Id))) /=
4377              N_Subprogram_Body_Stub
4378          then
4379             null;
4380
4381          elsif Is_Inherently_Limited_Type (Typ) then
4382             Set_Returns_By_Ref (Spec_Id);
4383
4384          elsif Present (Utyp) and then CW_Or_Controlled_Type (Utyp) then
4385             Set_Returns_By_Ref (Spec_Id);
4386          end if;
4387       end;
4388
4389       --  For a procedure, we add a return for all possible syntactic ends
4390       --  of the subprogram. Note that reanalysis is not necessary in this
4391       --  case since it would require a lot of work and accomplish nothing.
4392
4393       if Ekind (Spec_Id) = E_Procedure
4394         or else Ekind (Spec_Id) = E_Generic_Procedure
4395       then
4396          Add_Return (Statements (H));
4397
4398          if Present (Exception_Handlers (H)) then
4399             Except_H := First_Non_Pragma (Exception_Handlers (H));
4400             while Present (Except_H) loop
4401                Add_Return (Statements (Except_H));
4402                Next_Non_Pragma (Except_H);
4403             end loop;
4404          end if;
4405
4406       --  For a function, we must deal with the case where there is at least
4407       --  one missing return. What we do is to wrap the entire body of the
4408       --  function in a block:
4409
4410       --    begin
4411       --      ...
4412       --    end;
4413
4414       --  becomes
4415
4416       --    begin
4417       --       begin
4418       --          ...
4419       --       end;
4420
4421       --       raise Program_Error;
4422       --    end;
4423
4424       --  This approach is necessary because the raise must be signalled
4425       --  to the caller, not handled by any local handler (RM 6.4(11)).
4426
4427       --  Note: we do not need to analyze the constructed sequence here,
4428       --  since it has no handler, and an attempt to analyze the handled
4429       --  statement sequence twice is risky in various ways (e.g. the
4430       --  issue of expanding cleanup actions twice).
4431
4432       elsif Has_Missing_Return (Spec_Id) then
4433          declare
4434             Hloc : constant Source_Ptr := Sloc (H);
4435             Blok : constant Node_Id    :=
4436                      Make_Block_Statement (Hloc,
4437                        Handled_Statement_Sequence => H);
4438             Rais : constant Node_Id    :=
4439                      Make_Raise_Program_Error (Hloc,
4440                        Reason => PE_Missing_Return);
4441
4442          begin
4443             Set_Handled_Statement_Sequence (N,
4444               Make_Handled_Sequence_Of_Statements (Hloc,
4445                 Statements => New_List (Blok, Rais)));
4446
4447             Push_Scope (Spec_Id);
4448             Analyze (Blok);
4449             Analyze (Rais);
4450             Pop_Scope;
4451          end;
4452       end if;
4453
4454       --  If subprogram contains a parameterless recursive call, then we may
4455       --  have an infinite recursion, so see if we can generate code to check
4456       --  for this possibility if storage checks are not suppressed.
4457
4458       if Ekind (Spec_Id) = E_Procedure
4459         and then Has_Recursive_Call (Spec_Id)
4460         and then not Storage_Checks_Suppressed (Spec_Id)
4461       then
4462          Detect_Infinite_Recursion (N, Spec_Id);
4463       end if;
4464
4465       --  Finally, if we are in Normalize_Scalars mode, then any scalar out
4466       --  parameters must be initialized to the appropriate default value.
4467
4468       if Ekind (Spec_Id) = E_Procedure and then Normalize_Scalars then
4469          declare
4470             Floc   : Source_Ptr;
4471             Formal : Entity_Id;
4472             Stm    : Node_Id;
4473
4474          begin
4475             Formal := First_Formal (Spec_Id);
4476             while Present (Formal) loop
4477                Floc := Sloc (Formal);
4478
4479                if Ekind (Formal) = E_Out_Parameter
4480                  and then Is_Scalar_Type (Etype (Formal))
4481                then
4482                   Stm :=
4483                     Make_Assignment_Statement (Floc,
4484                       Name => New_Occurrence_Of (Formal, Floc),
4485                       Expression =>
4486                         Get_Simple_Init_Val (Etype (Formal), Floc));
4487                   Prepend (Stm, Declarations (N));
4488                   Analyze (Stm);
4489                end if;
4490
4491                Next_Formal (Formal);
4492             end loop;
4493          end;
4494       end if;
4495
4496       --  Set to encode entity names in package body before gigi is called
4497
4498       Qualify_Entity_Names (N);
4499    end Expand_N_Subprogram_Body;
4500
4501    -----------------------------------
4502    -- Expand_N_Subprogram_Body_Stub --
4503    -----------------------------------
4504
4505    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
4506    begin
4507       if Present (Corresponding_Body (N)) then
4508          Expand_N_Subprogram_Body (
4509            Unit_Declaration_Node (Corresponding_Body (N)));
4510       end if;
4511    end Expand_N_Subprogram_Body_Stub;
4512
4513    -------------------------------------
4514    -- Expand_N_Subprogram_Declaration --
4515    -------------------------------------
4516
4517    --  If the declaration appears within a protected body, it is a private
4518    --  operation of the protected type. We must create the corresponding
4519    --  protected subprogram an associated formals. For a normal protected
4520    --  operation, this is done when expanding the protected type declaration.
4521
4522    --  If the declaration is for a null procedure, emit null body
4523
4524    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
4525       Loc       : constant Source_Ptr := Sloc (N);
4526       Subp      : constant Entity_Id  := Defining_Entity (N);
4527       Scop      : constant Entity_Id  := Scope (Subp);
4528       Prot_Decl : Node_Id;
4529       Prot_Bod  : Node_Id;
4530       Prot_Id   : Entity_Id;
4531
4532    begin
4533       --  Deal with case of protected subprogram. Do not generate protected
4534       --  operation if operation is flagged as eliminated.
4535
4536       if Is_List_Member (N)
4537         and then Present (Parent (List_Containing (N)))
4538         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
4539         and then Is_Protected_Type (Scop)
4540       then
4541          if No (Protected_Body_Subprogram (Subp))
4542            and then not Is_Eliminated (Subp)
4543          then
4544             Prot_Decl :=
4545               Make_Subprogram_Declaration (Loc,
4546                 Specification =>
4547                   Build_Protected_Sub_Specification
4548                     (N, Scop, Unprotected_Mode));
4549
4550             --  The protected subprogram is declared outside of the protected
4551             --  body. Given that the body has frozen all entities so far, we
4552             --  analyze the subprogram and perform freezing actions explicitly.
4553             --  including the generation of an explicit freeze node, to ensure
4554             --  that gigi has the proper order of elaboration.
4555             --  If the body is a subunit, the insertion point is before the
4556             --  stub in the parent.
4557
4558             Prot_Bod := Parent (List_Containing (N));
4559
4560             if Nkind (Parent (Prot_Bod)) = N_Subunit then
4561                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
4562             end if;
4563
4564             Insert_Before (Prot_Bod, Prot_Decl);
4565             Prot_Id := Defining_Unit_Name (Specification (Prot_Decl));
4566             Set_Has_Delayed_Freeze (Prot_Id);
4567
4568             Push_Scope (Scope (Scop));
4569             Analyze (Prot_Decl);
4570             Insert_Actions (N, Freeze_Entity (Prot_Id, Loc));
4571             Set_Protected_Body_Subprogram (Subp, Prot_Id);
4572             Pop_Scope;
4573          end if;
4574
4575       --  Ada 2005 (AI-348): Generation of the null body
4576
4577       elsif Nkind (Specification (N)) = N_Procedure_Specification
4578         and then Null_Present (Specification (N))
4579       then
4580          declare
4581             Bod : constant Node_Id :=
4582                     Make_Subprogram_Body (Loc,
4583                       Specification =>
4584                         New_Copy_Tree (Specification (N)),
4585                       Declarations => New_List,
4586                      Handled_Statement_Sequence =>
4587                         Make_Handled_Sequence_Of_Statements (Loc,
4588                           Statements => New_List (Make_Null_Statement (Loc))));
4589          begin
4590             Set_Body_To_Inline (N, Bod);
4591             Insert_After (N, Bod);
4592             Analyze (Bod);
4593
4594             --  Corresponding_Spec isn't being set by Analyze_Subprogram_Body,
4595             --  evidently because Set_Has_Completion is called earlier for null
4596             --  procedures in Analyze_Subprogram_Declaration, so we force its
4597             --  setting here. If the setting of Has_Completion is not set
4598             --  earlier, then it can result in missing body errors if other
4599             --  errors were already reported (since expansion is turned off).
4600
4601             --  Should creation of the empty body be moved to the analyzer???
4602
4603             Set_Corresponding_Spec (Bod, Defining_Entity (Specification (N)));
4604          end;
4605       end if;
4606    end Expand_N_Subprogram_Declaration;
4607
4608    ---------------------------------------
4609    -- Expand_Protected_Object_Reference --
4610    ---------------------------------------
4611
4612    function Expand_Protected_Object_Reference
4613      (N    : Node_Id;
4614       Scop : Entity_Id) return Node_Id
4615    is
4616       Loc   : constant Source_Ptr := Sloc (N);
4617       Corr  : Entity_Id;
4618       Rec   : Node_Id;
4619       Param : Entity_Id;
4620       Proc  : Entity_Id;
4621
4622    begin
4623       Rec :=
4624         Make_Identifier (Loc,
4625           Chars => Name_uObject);
4626       Set_Etype (Rec, Corresponding_Record_Type (Scop));
4627
4628       --  Find enclosing protected operation, and retrieve its first parameter,
4629       --  which denotes the enclosing protected object. If the enclosing
4630       --  operation is an entry, we are immediately within the protected body,
4631       --  and we can retrieve the object from the service entries procedure. A
4632       --  barrier function has has the same signature as an entry. A barrier
4633       --  function is compiled within the protected object, but unlike
4634       --  protected operations its never needs locks, so that its protected
4635       --  body subprogram points to itself.
4636
4637       Proc := Current_Scope;
4638       while Present (Proc)
4639         and then Scope (Proc) /= Scop
4640       loop
4641          Proc := Scope (Proc);
4642       end loop;
4643
4644       Corr := Protected_Body_Subprogram (Proc);
4645
4646       if No (Corr) then
4647
4648          --  Previous error left expansion incomplete.
4649          --  Nothing to do on this call.
4650
4651          return Empty;
4652       end if;
4653
4654       Param :=
4655         Defining_Identifier
4656           (First (Parameter_Specifications (Parent (Corr))));
4657
4658       if Is_Subprogram (Proc)
4659         and then Proc /= Corr
4660       then
4661          --  Protected function or procedure
4662
4663          Set_Entity (Rec, Param);
4664
4665          --  Rec is a reference to an entity which will not be in scope when
4666          --  the call is reanalyzed, and needs no further analysis.
4667
4668          Set_Analyzed (Rec);
4669
4670       else
4671          --  Entry or barrier function for entry body. The first parameter of
4672          --  the entry body procedure is pointer to the object. We create a
4673          --  local variable of the proper type, duplicating what is done to
4674          --  define _object later on.
4675
4676          declare
4677             Decls : List_Id;
4678             Obj_Ptr : constant Entity_Id :=  Make_Defining_Identifier (Loc,
4679                                                Chars =>
4680                                                  New_Internal_Name ('T'));
4681
4682          begin
4683             Decls := New_List (
4684               Make_Full_Type_Declaration (Loc,
4685                 Defining_Identifier => Obj_Ptr,
4686                   Type_Definition =>
4687                      Make_Access_To_Object_Definition (Loc,
4688                        Subtype_Indication =>
4689                          New_Reference_To
4690                       (Corresponding_Record_Type (Scop), Loc))));
4691
4692             Insert_Actions (N, Decls);
4693             Insert_Actions (N, Freeze_Entity (Obj_Ptr, Sloc (N)));
4694
4695             Rec :=
4696               Make_Explicit_Dereference (Loc,
4697                 Unchecked_Convert_To (Obj_Ptr,
4698                   New_Occurrence_Of (Param, Loc)));
4699
4700             --  Analyze new actual. Other actuals in calls are already analyzed
4701             --  and the list of actuals is not reanalyzed after rewriting.
4702
4703             Set_Parent (Rec, N);
4704             Analyze (Rec);
4705          end;
4706       end if;
4707
4708       return Rec;
4709    end Expand_Protected_Object_Reference;
4710
4711    --------------------------------------
4712    -- Expand_Protected_Subprogram_Call --
4713    --------------------------------------
4714
4715    procedure Expand_Protected_Subprogram_Call
4716      (N    : Node_Id;
4717       Subp : Entity_Id;
4718       Scop : Entity_Id)
4719    is
4720       Rec   : Node_Id;
4721
4722    begin
4723       --  If the protected object is not an enclosing scope, this is
4724       --  an inter-object function call. Inter-object procedure
4725       --  calls are expanded by Exp_Ch9.Build_Simple_Entry_Call.
4726       --  The call is intra-object only if the subprogram being
4727       --  called is in the protected body being compiled, and if the
4728       --  protected object in the call is statically the enclosing type.
4729       --  The object may be an component of some other data structure,
4730       --  in which case this must be handled as an inter-object call.
4731
4732       if not In_Open_Scopes (Scop)
4733         or else not Is_Entity_Name (Name (N))
4734       then
4735          if Nkind (Name (N)) = N_Selected_Component then
4736             Rec := Prefix (Name (N));
4737
4738          else
4739             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
4740             Rec := Prefix (Prefix (Name (N)));
4741          end if;
4742
4743          Build_Protected_Subprogram_Call (N,
4744            Name => New_Occurrence_Of (Subp, Sloc (N)),
4745            Rec =>  Convert_Concurrent (Rec, Etype (Rec)),
4746            External => True);
4747
4748       else
4749          Rec := Expand_Protected_Object_Reference (N, Scop);
4750
4751          if No (Rec) then
4752             return;
4753          end if;
4754
4755          Build_Protected_Subprogram_Call (N,
4756            Name     => Name (N),
4757            Rec      => Rec,
4758            External => False);
4759
4760       end if;
4761
4762       Analyze (N);
4763
4764       --  If it is a function call it can appear in elaboration code and
4765       --  the called entity must be frozen here.
4766
4767       if Ekind (Subp) = E_Function then
4768          Freeze_Expression (Name (N));
4769       end if;
4770    end Expand_Protected_Subprogram_Call;
4771
4772    --------------------------------
4773    -- Is_Build_In_Place_Function --
4774    --------------------------------
4775
4776    function Is_Build_In_Place_Function (E : Entity_Id) return Boolean is
4777    begin
4778       --  For now we test whether E denotes a function or access-to-function
4779       --  type whose result subtype is inherently limited. Later this test may
4780       --  be revised to allow composite nonlimited types. Functions with a
4781       --  foreign convention or whose result type has a foreign convention
4782       --  never qualify.
4783
4784       if Ekind (E) = E_Function
4785         or else Ekind (E) = E_Generic_Function
4786         or else (Ekind (E) = E_Subprogram_Type
4787                   and then Etype (E) /= Standard_Void_Type)
4788       then
4789          --  Note: If you have Convention (C) on an inherently limited type,
4790          --  you're on your own. That is, the C code will have to be carefully
4791          --  written to know about the Ada conventions.
4792
4793          if Has_Foreign_Convention (E)
4794            or else Has_Foreign_Convention (Etype (E))
4795          then
4796             return False;
4797
4798          --  If the return type is a limited interface it has to be treated
4799          --  as a return in place, even if the actual object is some non-
4800          --  limited descendant.
4801
4802          elsif Is_Limited_Interface (Etype (E)) then
4803             return True;
4804
4805          else
4806             return Is_Inherently_Limited_Type (Etype (E))
4807               and then Ada_Version >= Ada_05
4808               and then not Debug_Flag_Dot_L;
4809          end if;
4810
4811       else
4812          return False;
4813       end if;
4814    end Is_Build_In_Place_Function;
4815
4816    -------------------------------------
4817    -- Is_Build_In_Place_Function_Call --
4818    -------------------------------------
4819
4820    function Is_Build_In_Place_Function_Call (N : Node_Id) return Boolean is
4821       Exp_Node    : Node_Id := N;
4822       Function_Id : Entity_Id;
4823
4824    begin
4825       --  Step past qualification or unchecked conversion (the latter can occur
4826       --  in cases of calls to 'Input).
4827
4828       if Nkind (Exp_Node) = N_Qualified_Expression
4829         or else Nkind (Exp_Node) = N_Unchecked_Type_Conversion
4830       then
4831          Exp_Node := Expression (N);
4832       end if;
4833
4834       if Nkind (Exp_Node) /= N_Function_Call then
4835          return False;
4836
4837       else
4838          if Is_Entity_Name (Name (Exp_Node)) then
4839             Function_Id := Entity (Name (Exp_Node));
4840
4841          elsif Nkind (Name (Exp_Node)) = N_Explicit_Dereference then
4842             Function_Id := Etype (Name (Exp_Node));
4843          end if;
4844
4845          return Is_Build_In_Place_Function (Function_Id);
4846       end if;
4847    end Is_Build_In_Place_Function_Call;
4848
4849    ---------------------------------------
4850    -- Is_Build_In_Place_Function_Return --
4851    ---------------------------------------
4852
4853    function Is_Build_In_Place_Function_Return (N : Node_Id) return Boolean is
4854    begin
4855       if Nkind (N) = N_Simple_Return_Statement
4856         or else Nkind (N) = N_Extended_Return_Statement
4857       then
4858          return Is_Build_In_Place_Function
4859                   (Return_Applies_To (Return_Statement_Entity (N)));
4860       else
4861          return False;
4862       end if;
4863    end Is_Build_In_Place_Function_Return;
4864
4865    -----------------------
4866    -- Freeze_Subprogram --
4867    -----------------------
4868
4869    procedure Freeze_Subprogram (N : Node_Id) is
4870       Loc : constant Source_Ptr := Sloc (N);
4871
4872       procedure Register_Predefined_DT_Entry (Prim : Entity_Id);
4873       --  (Ada 2005): Register a predefined primitive in all the secondary
4874       --  dispatch tables of its primitive type.
4875
4876       ----------------------------------
4877       -- Register_Predefined_DT_Entry --
4878       ----------------------------------
4879
4880       procedure Register_Predefined_DT_Entry (Prim : Entity_Id) is
4881          Iface_DT_Ptr : Elmt_Id;
4882          Tagged_Typ   : Entity_Id;
4883          Thunk_Id     : Entity_Id;
4884          Thunk_Code   : Node_Id;
4885
4886       begin
4887          Tagged_Typ := Find_Dispatching_Type (Prim);
4888
4889          if No (Access_Disp_Table (Tagged_Typ))
4890            or else not Has_Abstract_Interfaces (Tagged_Typ)
4891            or else not RTE_Available (RE_Interface_Tag)
4892            or else Restriction_Active (No_Dispatching_Calls)
4893          then
4894             return;
4895          end if;
4896
4897          --  Skip the first access-to-dispatch-table pointer since it leads
4898          --  to the primary dispatch table. We are only concerned with the
4899          --  secondary dispatch table pointers. Note that the access-to-
4900          --  dispatch-table pointer corresponds to the first implemented
4901          --  interface retrieved below.
4902
4903          Iface_DT_Ptr :=
4904            Next_Elmt (First_Elmt (Access_Disp_Table (Tagged_Typ)));
4905
4906          while Present (Iface_DT_Ptr)
4907             and then Ekind (Node (Iface_DT_Ptr)) = E_Constant
4908          loop
4909             Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code);
4910
4911             if Present (Thunk_Code) then
4912                Insert_Actions (N, New_List (
4913                  Thunk_Code,
4914
4915                  Build_Set_Predefined_Prim_Op_Address (Loc,
4916                    Tag_Node => New_Reference_To (Node (Iface_DT_Ptr), Loc),
4917                    Position => DT_Position (Prim),
4918                    Address_Node =>
4919                      Make_Attribute_Reference (Loc,
4920                        Prefix         => New_Reference_To (Thunk_Id, Loc),
4921                        Attribute_Name => Name_Address))));
4922             end if;
4923
4924             Next_Elmt (Iface_DT_Ptr);
4925          end loop;
4926       end Register_Predefined_DT_Entry;
4927
4928       --  Local variables
4929
4930       Subp : constant Entity_Id := Entity (N);
4931
4932    begin
4933       --  We suppress the initialization of the dispatch table entry when
4934       --  VM_Target because the dispatching mechanism is handled internally
4935       --  by the VM.
4936
4937       if Is_Dispatching_Operation (Subp)
4938         and then not Is_Abstract_Subprogram (Subp)
4939         and then Present (DTC_Entity (Subp))
4940         and then Present (Scope (DTC_Entity (Subp)))
4941         and then VM_Target = No_VM
4942         and then not Restriction_Active (No_Dispatching_Calls)
4943         and then RTE_Available (RE_Tag)
4944       then
4945          declare
4946             Typ : constant Entity_Id := Scope (DTC_Entity (Subp));
4947
4948          begin
4949             --  Handle private overriden primitives
4950
4951             if not Is_CPP_Class (Typ) then
4952                Check_Overriding_Operation (Subp);
4953             end if;
4954
4955             --  We assume that imported CPP primitives correspond with objects
4956             --  whose constructor is in the CPP side; therefore we don't need
4957             --  to generate code to register them in the dispatch table.
4958
4959             if Is_CPP_Class (Typ) then
4960                null;
4961
4962             --  Handle CPP primitives found in derivations of CPP_Class types.
4963             --  These primitives must have been inherited from some parent, and
4964             --  there is no need to register them in the dispatch table because
4965             --  Build_Inherit_Prims takes care of the initialization of these
4966             --  slots.
4967
4968             elsif Is_Imported (Subp)
4969                     and then (Convention (Subp) = Convention_CPP
4970                                 or else Convention (Subp) = Convention_C)
4971             then
4972                null;
4973
4974             --  Generate code to register the primitive in non statically
4975             --  allocated dispatch tables
4976
4977             elsif not Static_Dispatch_Tables
4978               or else not
4979                 Is_Library_Level_Tagged_Type (Scope (DTC_Entity (Subp)))
4980             then
4981                --  When a primitive is frozen, enter its name in its dispatch
4982                --  table slot.
4983
4984                if not Is_Interface (Typ)
4985                  or else Present (Abstract_Interface_Alias (Subp))
4986                then
4987                   if Is_Predefined_Dispatching_Operation (Subp) then
4988                      Register_Predefined_DT_Entry (Subp);
4989                   end if;
4990
4991                   Register_Primitive (Loc,
4992                     Prim    => Subp,
4993                     Ins_Nod => N);
4994                end if;
4995             end if;
4996          end;
4997       end if;
4998
4999       --  Mark functions that return by reference. Note that it cannot be part
5000       --  of the normal semantic analysis of the spec since the underlying
5001       --  returned type may not be known yet (for private types).
5002
5003       declare
5004          Typ  : constant Entity_Id := Etype (Subp);
5005          Utyp : constant Entity_Id := Underlying_Type (Typ);
5006       begin
5007          if Is_Inherently_Limited_Type (Typ) then
5008             Set_Returns_By_Ref (Subp);
5009          elsif Present (Utyp) and then CW_Or_Controlled_Type (Utyp) then
5010             Set_Returns_By_Ref (Subp);
5011          end if;
5012       end;
5013    end Freeze_Subprogram;
5014
5015    -------------------------------------------
5016    -- Make_Build_In_Place_Call_In_Allocator --
5017    -------------------------------------------
5018
5019    procedure Make_Build_In_Place_Call_In_Allocator
5020      (Allocator     : Node_Id;
5021       Function_Call : Node_Id)
5022    is
5023       Loc               : Source_Ptr;
5024       Func_Call         : Node_Id := Function_Call;
5025       Function_Id       : Entity_Id;
5026       Result_Subt       : Entity_Id;
5027       Acc_Type          : constant Entity_Id := Etype (Allocator);
5028       New_Allocator     : Node_Id;
5029       Return_Obj_Access : Entity_Id;
5030
5031    begin
5032       --  Step past qualification or unchecked conversion (the latter can occur
5033       --  in cases of calls to 'Input).
5034
5035       if Nkind (Func_Call) = N_Qualified_Expression
5036         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5037       then
5038          Func_Call := Expression (Func_Call);
5039       end if;
5040
5041       Loc := Sloc (Function_Call);
5042
5043       if Is_Entity_Name (Name (Func_Call)) then
5044          Function_Id := Entity (Name (Func_Call));
5045
5046       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5047          Function_Id := Etype (Name (Func_Call));
5048
5049       else
5050          raise Program_Error;
5051       end if;
5052
5053       Result_Subt := Etype (Function_Id);
5054
5055       --  When the result subtype is constrained, the return object must be
5056       --  allocated on the caller side, and access to it is passed to the
5057       --  function.
5058
5059       --  Here and in related routines, we must examine the full view of the
5060       --  type, because the view at the point of call may differ from that
5061       --  that in the function body, and the expansion mechanism depends on
5062       --  the characteristics of the full view.
5063
5064       if Is_Constrained (Underlying_Type (Result_Subt)) then
5065
5066          --  Replace the initialized allocator of form "new T'(Func (...))"
5067          --  with an uninitialized allocator of form "new T", where T is the
5068          --  result subtype of the called function. The call to the function
5069          --  is handled separately further below.
5070
5071          New_Allocator :=
5072            Make_Allocator (Loc, New_Reference_To (Result_Subt, Loc));
5073
5074          Set_Storage_Pool      (New_Allocator, Storage_Pool (Allocator));
5075          Set_Procedure_To_Call (New_Allocator, Procedure_To_Call (Allocator));
5076          Set_No_Initialization (New_Allocator);
5077
5078          Rewrite (Allocator, New_Allocator);
5079
5080          --  Create a new access object and initialize it to the result of the
5081          --  new uninitialized allocator.
5082
5083          Return_Obj_Access :=
5084            Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
5085          Set_Etype (Return_Obj_Access, Acc_Type);
5086
5087          Insert_Action (Allocator,
5088            Make_Object_Declaration (Loc,
5089              Defining_Identifier => Return_Obj_Access,
5090              Object_Definition   => New_Reference_To (Acc_Type, Loc),
5091              Expression          => Relocate_Node (Allocator)));
5092
5093          --  When the function has a controlling result, an allocation-form
5094          --  parameter must be passed indicating that the caller is allocating
5095          --  the result object. This is needed because such a function can be
5096          --  called as a dispatching operation and must be treated similarly
5097          --  to functions with unconstrained result subtypes.
5098
5099          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5100            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5101
5102          Add_Final_List_Actual_To_Build_In_Place_Call
5103            (Func_Call, Function_Id, Acc_Type);
5104
5105          Add_Task_Actuals_To_Build_In_Place_Call
5106            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
5107
5108          --  Add an implicit actual to the function call that provides access
5109          --  to the allocated object. An unchecked conversion to the (specific)
5110          --  result subtype of the function is inserted to handle cases where
5111          --  the access type of the allocator has a class-wide designated type.
5112
5113          Add_Access_Actual_To_Build_In_Place_Call
5114            (Func_Call,
5115             Function_Id,
5116             Make_Unchecked_Type_Conversion (Loc,
5117               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5118               Expression   =>
5119                 Make_Explicit_Dereference (Loc,
5120                   Prefix => New_Reference_To (Return_Obj_Access, Loc))));
5121
5122       --  When the result subtype is unconstrained, the function itself must
5123       --  perform the allocation of the return object, so we pass parameters
5124       --  indicating that. We don't yet handle the case where the allocation
5125       --  must be done in a user-defined storage pool, which will require
5126       --  passing another actual or two to provide allocation/deallocation
5127       --  operations. ???
5128
5129       else
5130
5131          --  Pass an allocation parameter indicating that the function should
5132          --  allocate its result on the heap.
5133
5134          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5135            (Func_Call, Function_Id, Alloc_Form => Global_Heap);
5136
5137          Add_Final_List_Actual_To_Build_In_Place_Call
5138            (Func_Call, Function_Id, Acc_Type);
5139
5140          Add_Task_Actuals_To_Build_In_Place_Call
5141            (Func_Call, Function_Id, Master_Actual => Master_Id (Acc_Type));
5142
5143          --  The caller does not provide the return object in this case, so we
5144          --  have to pass null for the object access actual.
5145
5146          Add_Access_Actual_To_Build_In_Place_Call
5147            (Func_Call, Function_Id, Return_Object => Empty);
5148       end if;
5149
5150       --  Finally, replace the allocator node with a reference to the result
5151       --  of the function call itself (which will effectively be an access
5152       --  to the object created by the allocator).
5153
5154       Rewrite (Allocator, Make_Reference (Loc, Relocate_Node (Function_Call)));
5155       Analyze_And_Resolve (Allocator, Acc_Type);
5156    end Make_Build_In_Place_Call_In_Allocator;
5157
5158    ---------------------------------------------------
5159    -- Make_Build_In_Place_Call_In_Anonymous_Context --
5160    ---------------------------------------------------
5161
5162    procedure Make_Build_In_Place_Call_In_Anonymous_Context
5163      (Function_Call : Node_Id)
5164    is
5165       Loc             : Source_Ptr;
5166       Func_Call       : Node_Id := Function_Call;
5167       Function_Id     : Entity_Id;
5168       Result_Subt     : Entity_Id;
5169       Return_Obj_Id   : Entity_Id;
5170       Return_Obj_Decl : Entity_Id;
5171
5172    begin
5173       --  Step past qualification or unchecked conversion (the latter can occur
5174       --  in cases of calls to 'Input).
5175
5176       if Nkind (Func_Call) = N_Qualified_Expression
5177         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5178       then
5179          Func_Call := Expression (Func_Call);
5180       end if;
5181
5182       Loc := Sloc (Function_Call);
5183
5184       if Is_Entity_Name (Name (Func_Call)) then
5185          Function_Id := Entity (Name (Func_Call));
5186
5187       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5188          Function_Id := Etype (Name (Func_Call));
5189
5190       else
5191          raise Program_Error;
5192       end if;
5193
5194       Result_Subt := Etype (Function_Id);
5195
5196       --  When the result subtype is constrained, an object of the subtype is
5197       --  declared and an access value designating it is passed as an actual.
5198
5199       if Is_Constrained (Underlying_Type (Result_Subt)) then
5200
5201          --  Create a temporary object to hold the function result
5202
5203          Return_Obj_Id :=
5204            Make_Defining_Identifier (Loc,
5205              Chars => New_Internal_Name ('R'));
5206          Set_Etype (Return_Obj_Id, Result_Subt);
5207
5208          Return_Obj_Decl :=
5209            Make_Object_Declaration (Loc,
5210              Defining_Identifier => Return_Obj_Id,
5211              Aliased_Present     => True,
5212              Object_Definition   => New_Reference_To (Result_Subt, Loc));
5213
5214          Set_No_Initialization (Return_Obj_Decl);
5215
5216          Insert_Action (Func_Call, Return_Obj_Decl);
5217
5218          --  When the function has a controlling result, an allocation-form
5219          --  parameter must be passed indicating that the caller is allocating
5220          --  the result object. This is needed because such a function can be
5221          --  called as a dispatching operation and must be treated similarly
5222          --  to functions with unconstrained result subtypes.
5223
5224          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5225            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5226
5227          Add_Final_List_Actual_To_Build_In_Place_Call
5228            (Func_Call, Function_Id, Acc_Type => Empty);
5229
5230          Add_Task_Actuals_To_Build_In_Place_Call
5231            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5232
5233          --  Add an implicit actual to the function call that provides access
5234          --  to the caller's return object.
5235
5236          Add_Access_Actual_To_Build_In_Place_Call
5237            (Func_Call, Function_Id, New_Reference_To (Return_Obj_Id, Loc));
5238
5239       --  When the result subtype is unconstrained, the function must allocate
5240       --  the return object in the secondary stack, so appropriate implicit
5241       --  parameters are added to the call to indicate that. A transient
5242       --  scope is established to ensure eventual cleanup of the result.
5243
5244       else
5245
5246          --  Pass an allocation parameter indicating that the function should
5247          --  allocate its result on the secondary stack.
5248
5249          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5250            (Func_Call, Function_Id, Alloc_Form => Secondary_Stack);
5251
5252          Add_Final_List_Actual_To_Build_In_Place_Call
5253            (Func_Call, Function_Id, Acc_Type => Empty);
5254
5255          Add_Task_Actuals_To_Build_In_Place_Call
5256            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5257
5258          --  Pass a null value to the function since no return object is
5259          --  available on the caller side.
5260
5261          Add_Access_Actual_To_Build_In_Place_Call
5262            (Func_Call, Function_Id, Empty);
5263
5264          Establish_Transient_Scope (Func_Call, Sec_Stack => True);
5265       end if;
5266    end Make_Build_In_Place_Call_In_Anonymous_Context;
5267
5268    ---------------------------------------------------
5269    -- Make_Build_In_Place_Call_In_Assignment --
5270    ---------------------------------------------------
5271
5272    procedure Make_Build_In_Place_Call_In_Assignment
5273      (Assign        : Node_Id;
5274       Function_Call : Node_Id)
5275    is
5276       Lhs             : constant Node_Id := Name (Assign);
5277       Loc             : Source_Ptr;
5278       Func_Call       : Node_Id := Function_Call;
5279       Function_Id     : Entity_Id;
5280       Result_Subt     : Entity_Id;
5281       Ref_Type        : Entity_Id;
5282       Ptr_Typ_Decl    : Node_Id;
5283       Def_Id          : Entity_Id;
5284       New_Expr        : Node_Id;
5285
5286    begin
5287       --  Step past qualification or unchecked conversion (the latter can occur
5288       --  in cases of calls to 'Input).
5289
5290       if Nkind (Func_Call) = N_Qualified_Expression
5291         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5292       then
5293          Func_Call := Expression (Func_Call);
5294       end if;
5295
5296       Loc := Sloc (Function_Call);
5297
5298       if Is_Entity_Name (Name (Func_Call)) then
5299          Function_Id := Entity (Name (Func_Call));
5300
5301       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5302          Function_Id := Etype (Name (Func_Call));
5303
5304       else
5305          raise Program_Error;
5306       end if;
5307
5308       Result_Subt := Etype (Function_Id);
5309
5310       --  When the result subtype is unconstrained, an additional actual must
5311       --  be passed to indicate that the caller is providing the return object.
5312       --  This parameter must also be passed when the called function has a
5313       --  controlling result, because dispatching calls to the function needs
5314       --  to be treated effectively the same as calls to class-wide functions.
5315
5316       Add_Alloc_Form_Actual_To_Build_In_Place_Call
5317         (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5318
5319       Add_Final_List_Actual_To_Build_In_Place_Call
5320         (Func_Call, Function_Id, Acc_Type => Empty);
5321
5322       Add_Task_Actuals_To_Build_In_Place_Call
5323         (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5324
5325       --  Add an implicit actual to the function call that provides access to
5326       --  the caller's return object.
5327
5328       Add_Access_Actual_To_Build_In_Place_Call
5329         (Func_Call,
5330          Function_Id,
5331          Make_Unchecked_Type_Conversion (Loc,
5332            Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5333            Expression   => Relocate_Node (Lhs)));
5334
5335       --  Create an access type designating the function's result subtype
5336
5337       Ref_Type :=
5338         Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5339
5340       Ptr_Typ_Decl :=
5341         Make_Full_Type_Declaration (Loc,
5342           Defining_Identifier => Ref_Type,
5343           Type_Definition =>
5344             Make_Access_To_Object_Definition (Loc,
5345               All_Present => True,
5346               Subtype_Indication =>
5347                 New_Reference_To (Result_Subt, Loc)));
5348
5349       Insert_After_And_Analyze (Assign, Ptr_Typ_Decl);
5350
5351       --  Finally, create an access object initialized to a reference to the
5352       --  function call.
5353
5354       Def_Id :=
5355         Make_Defining_Identifier (Loc,
5356           Chars => New_Internal_Name ('R'));
5357       Set_Etype (Def_Id, Ref_Type);
5358
5359       New_Expr :=
5360         Make_Reference (Loc,
5361           Prefix => Relocate_Node (Func_Call));
5362
5363       Insert_After_And_Analyze (Ptr_Typ_Decl,
5364         Make_Object_Declaration (Loc,
5365           Defining_Identifier => Def_Id,
5366           Object_Definition   => New_Reference_To (Ref_Type, Loc),
5367           Expression          => New_Expr));
5368
5369       Rewrite (Assign, Make_Null_Statement (Loc));
5370    end Make_Build_In_Place_Call_In_Assignment;
5371
5372    ----------------------------------------------------
5373    -- Make_Build_In_Place_Call_In_Object_Declaration --
5374    ----------------------------------------------------
5375
5376    procedure Make_Build_In_Place_Call_In_Object_Declaration
5377      (Object_Decl   : Node_Id;
5378       Function_Call : Node_Id)
5379    is
5380       Loc             : Source_Ptr;
5381       Obj_Def_Id      : constant Entity_Id :=
5382                           Defining_Identifier (Object_Decl);
5383
5384       Func_Call       : Node_Id := Function_Call;
5385       Function_Id     : Entity_Id;
5386       Result_Subt     : Entity_Id;
5387       Caller_Object   : Node_Id;
5388       Call_Deref      : Node_Id;
5389       Ref_Type        : Entity_Id;
5390       Ptr_Typ_Decl    : Node_Id;
5391       Def_Id          : Entity_Id;
5392       New_Expr        : Node_Id;
5393       Enclosing_Func  : Entity_Id;
5394       Pass_Caller_Acc : Boolean := False;
5395
5396    begin
5397       --  Step past qualification or unchecked conversion (the latter can occur
5398       --  in cases of calls to 'Input).
5399
5400       if Nkind (Func_Call) = N_Qualified_Expression
5401         or else Nkind (Func_Call) = N_Unchecked_Type_Conversion
5402       then
5403          Func_Call := Expression (Func_Call);
5404       end if;
5405
5406       Loc := Sloc (Function_Call);
5407
5408       if Is_Entity_Name (Name (Func_Call)) then
5409          Function_Id := Entity (Name (Func_Call));
5410
5411       elsif Nkind (Name (Func_Call)) = N_Explicit_Dereference then
5412          Function_Id := Etype (Name (Func_Call));
5413
5414       else
5415          raise Program_Error;
5416       end if;
5417
5418       Result_Subt := Etype (Function_Id);
5419
5420       --  In the constrained case, add an implicit actual to the function call
5421       --  that provides access to the declared object. An unchecked conversion
5422       --  to the (specific) result type of the function is inserted to handle
5423       --  the case where the object is declared with a class-wide type.
5424
5425       if Is_Constrained (Underlying_Type (Result_Subt)) then
5426          Caller_Object :=
5427             Make_Unchecked_Type_Conversion (Loc,
5428               Subtype_Mark => New_Reference_To (Result_Subt, Loc),
5429               Expression   => New_Reference_To (Obj_Def_Id, Loc));
5430
5431          --  When the function has a controlling result, an allocation-form
5432          --  parameter must be passed indicating that the caller is allocating
5433          --  the result object. This is needed because such a function can be
5434          --  called as a dispatching operation and must be treated similarly
5435          --  to functions with unconstrained result subtypes.
5436
5437          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5438            (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5439
5440       --  If the function's result subtype is unconstrained and the object is
5441       --  a return object of an enclosing build-in-place function, then the
5442       --  implicit build-in-place parameters of the enclosing function must be
5443       --  passed along to the called function.
5444
5445       elsif Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement then
5446          Pass_Caller_Acc := True;
5447
5448          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
5449
5450          --  If the enclosing function has a constrained result type, then
5451          --  caller allocation will be used.
5452
5453          if Is_Constrained (Etype (Enclosing_Func)) then
5454             Add_Alloc_Form_Actual_To_Build_In_Place_Call
5455               (Func_Call, Function_Id, Alloc_Form => Caller_Allocation);
5456
5457          --  Otherwise, when the enclosing function has an unconstrained result
5458          --  type, the BIP_Alloc_Form formal of the enclosing function must be
5459          --  passed along to the callee.
5460
5461          else
5462             Add_Alloc_Form_Actual_To_Build_In_Place_Call
5463               (Func_Call,
5464                Function_Id,
5465                Alloc_Form_Exp =>
5466                  New_Reference_To
5467                    (Build_In_Place_Formal (Enclosing_Func, BIP_Alloc_Form),
5468                     Loc));
5469          end if;
5470
5471          --  Retrieve the BIPacc formal from the enclosing function and convert
5472          --  it to the access type of the callee's BIP_Object_Access formal.
5473
5474          Caller_Object :=
5475             Make_Unchecked_Type_Conversion (Loc,
5476               Subtype_Mark =>
5477                 New_Reference_To
5478                   (Etype
5479                      (Build_In_Place_Formal (Function_Id, BIP_Object_Access)),
5480                    Loc),
5481               Expression   =>
5482                 New_Reference_To
5483                   (Build_In_Place_Formal (Enclosing_Func, BIP_Object_Access),
5484                    Loc));
5485
5486       --  In other unconstrained cases, pass an indication to do the allocation
5487       --  on the secondary stack and set Caller_Object to Empty so that a null
5488       --  value will be passed for the caller's object address. A transient
5489       --  scope is established to ensure eventual cleanup of the result.
5490
5491       else
5492          Add_Alloc_Form_Actual_To_Build_In_Place_Call
5493            (Func_Call,
5494             Function_Id,
5495             Alloc_Form => Secondary_Stack);
5496          Caller_Object := Empty;
5497
5498          Establish_Transient_Scope (Object_Decl, Sec_Stack => True);
5499       end if;
5500
5501       Add_Final_List_Actual_To_Build_In_Place_Call
5502         (Func_Call, Function_Id, Acc_Type => Empty);
5503
5504       if Nkind (Parent (Object_Decl)) = N_Extended_Return_Statement
5505         and then Has_Task (Result_Subt)
5506       then
5507          Enclosing_Func := Enclosing_Subprogram (Obj_Def_Id);
5508
5509          --  Here we're passing along the master that was passed in to this
5510          --  function.
5511
5512          Add_Task_Actuals_To_Build_In_Place_Call
5513            (Func_Call, Function_Id,
5514             Master_Actual =>
5515               New_Reference_To
5516                 (Build_In_Place_Formal (Enclosing_Func, BIP_Master), Loc));
5517
5518       else
5519          Add_Task_Actuals_To_Build_In_Place_Call
5520            (Func_Call, Function_Id, Make_Identifier (Loc, Name_uMaster));
5521       end if;
5522
5523       Add_Access_Actual_To_Build_In_Place_Call
5524         (Func_Call, Function_Id, Caller_Object, Is_Access => Pass_Caller_Acc);
5525
5526       --  Create an access type designating the function's result subtype
5527
5528       Ref_Type :=
5529         Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
5530
5531       Ptr_Typ_Decl :=
5532         Make_Full_Type_Declaration (Loc,
5533           Defining_Identifier => Ref_Type,
5534           Type_Definition =>
5535             Make_Access_To_Object_Definition (Loc,
5536               All_Present => True,
5537               Subtype_Indication =>
5538                 New_Reference_To (Result_Subt, Loc)));
5539
5540       --  The access type and its accompanying object must be inserted after
5541       --  the object declaration in the constrained case, so that the function
5542       --  call can be passed access to the object. In the unconstrained case,
5543       --  the access type and object must be inserted before the object, since
5544       --  the object declaration is rewritten to be a renaming of a dereference
5545       --  of the access object.
5546
5547       if Is_Constrained (Underlying_Type (Result_Subt)) then
5548          Insert_After_And_Analyze (Object_Decl, Ptr_Typ_Decl);
5549       else
5550          Insert_Before_And_Analyze (Object_Decl, Ptr_Typ_Decl);
5551       end if;
5552
5553       --  Finally, create an access object initialized to a reference to the
5554       --  function call.
5555
5556       Def_Id :=
5557         Make_Defining_Identifier (Loc,
5558           Chars => New_Internal_Name ('R'));
5559       Set_Etype (Def_Id, Ref_Type);
5560
5561       New_Expr :=
5562         Make_Reference (Loc,
5563           Prefix => Relocate_Node (Func_Call));
5564
5565       Insert_After_And_Analyze (Ptr_Typ_Decl,
5566         Make_Object_Declaration (Loc,
5567           Defining_Identifier => Def_Id,
5568           Object_Definition   => New_Reference_To (Ref_Type, Loc),
5569           Expression          => New_Expr));
5570
5571       if Is_Constrained (Underlying_Type (Result_Subt)) then
5572          Set_Expression (Object_Decl, Empty);
5573          Set_No_Initialization (Object_Decl);
5574
5575       --  In case of an unconstrained result subtype, rewrite the object
5576       --  declaration as an object renaming where the renamed object is a
5577       --  dereference of <function_Call>'reference:
5578       --
5579       --      Obj : Subt renames <function_call>'Ref.all;
5580
5581       else
5582          Call_Deref :=
5583            Make_Explicit_Dereference (Loc,
5584              Prefix => New_Reference_To (Def_Id, Loc));
5585
5586          Rewrite (Object_Decl,
5587            Make_Object_Renaming_Declaration (Loc,
5588              Defining_Identifier => Make_Defining_Identifier (Loc,
5589                                       New_Internal_Name ('D')),
5590              Access_Definition   => Empty,
5591              Subtype_Mark        => New_Occurrence_Of (Result_Subt, Loc),
5592              Name                => Call_Deref));
5593
5594          Set_Renamed_Object (Defining_Identifier (Object_Decl), Call_Deref);
5595
5596          Analyze (Object_Decl);
5597
5598          --  Replace the internal identifier of the renaming declaration's
5599          --  entity with identifier of the original object entity. We also have
5600          --  to exchange the entities containing their defining identifiers to
5601          --  ensure the correct replacement of the object declaration by the
5602          --  object renaming declaration to avoid homograph conflicts (since
5603          --  the object declaration's defining identifier was already entered
5604          --  in current scope).
5605
5606          Set_Chars (Defining_Identifier (Object_Decl), Chars (Obj_Def_Id));
5607          Exchange_Entities (Defining_Identifier (Object_Decl), Obj_Def_Id);
5608       end if;
5609
5610       --  If the object entity has a class-wide Etype, then we need to change
5611       --  it to the result subtype of the function call, because otherwise the
5612       --  object will be class-wide without an explicit intialization and won't
5613       --  be allocated properly by the back end. It seems unclean to make such
5614       --  a revision to the type at this point, and we should try to improve
5615       --  this treatment when build-in-place functions with class-wide results
5616       --  are implemented. ???
5617
5618       if Is_Class_Wide_Type (Etype (Defining_Identifier (Object_Decl))) then
5619          Set_Etype (Defining_Identifier (Object_Decl), Result_Subt);
5620       end if;
5621    end Make_Build_In_Place_Call_In_Object_Declaration;
5622
5623 end Exp_Ch6;