OSDN Git Service

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