OSDN Git Service

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