OSDN Git Service

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