OSDN Git Service

New Language: Ada
[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 --                            $Revision: 1.343 $
10 --                                                                          --
11 --          Copyright (C) 1992-2001, Free Software Foundation, Inc.         --
12 --                                                                          --
13 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
14 -- terms of the  GNU General Public License as published  by the Free Soft- --
15 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
16 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
17 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
18 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
19 -- for  more details.  You should have  received  a copy of the GNU General --
20 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
21 -- to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston, --
22 -- MA 02111-1307, USA.                                                      --
23 --                                                                          --
24 -- GNAT was originally developed  by the GNAT team at  New York University. --
25 -- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
26 --                                                                          --
27 ------------------------------------------------------------------------------
28
29 with Atree;    use Atree;
30 with Checks;   use Checks;
31 with Debug;    use Debug;
32 with Einfo;    use Einfo;
33 with Errout;   use Errout;
34 with Elists;   use Elists;
35 with Exp_Ch2;  use Exp_Ch2;
36 with Exp_Ch3;  use Exp_Ch3;
37 with Exp_Ch7;  use Exp_Ch7;
38 with Exp_Ch9;  use Exp_Ch9;
39 with Exp_Ch11; use Exp_Ch11;
40 with Exp_Dbug; use Exp_Dbug;
41 with Exp_Disp; use Exp_Disp;
42 with Exp_Dist; use Exp_Dist;
43 with Exp_Intr; use Exp_Intr;
44 with Exp_Pakd; use Exp_Pakd;
45 with Exp_Tss;  use Exp_Tss;
46 with Exp_Util; use Exp_Util;
47 with Freeze;   use Freeze;
48 with Hostparm; use Hostparm;
49 with Inline;   use Inline;
50 with Lib;      use Lib;
51 with Nlists;   use Nlists;
52 with Nmake;    use Nmake;
53 with Opt;      use Opt;
54 with Restrict; use Restrict;
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_Res;  use Sem_Res;
64 with Sem_Util; use Sem_Util;
65 with Sinfo;    use Sinfo;
66 with Snames;   use Snames;
67 with Stand;    use Stand;
68 with Tbuild;   use Tbuild;
69 with Uintp;    use Uintp;
70 with Validsw;  use Validsw;
71
72 package body Exp_Ch6 is
73
74    -----------------------
75    -- Local Subprograms --
76    -----------------------
77
78    procedure Check_Overriding_Operation (Subp : Entity_Id);
79    --  Subp is a dispatching operation. Check whether it may override an
80    --  inherited private operation, in which case its DT entry is that of
81    --  the hidden operation, not the one it may have received earlier.
82    --  This must be done before emitting the code to set the corresponding
83    --  DT to the address of the subprogram. The actual placement of Subp in
84    --  the proper place in the list of primitive operations is done in
85    --  Declare_Inherited_Private_Subprograms, which also has to deal with
86    --  implicit operations. This duplication is unavoidable for now???
87
88    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id);
89    --  This procedure is called only if the subprogram body N, whose spec
90    --  has the given entity Spec, contains a parameterless recursive call.
91    --  It attempts to generate runtime code to detect if this a case of
92    --  infinite recursion.
93    --
94    --  The body is scanned to determine dependencies. If the only external
95    --  dependencies are on a small set of scalar variables, then the values
96    --  of these variables are captured on entry to the subprogram, and if
97    --  the values are not changed for the call, we know immediately that
98    --  we have an infinite recursion.
99
100    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id);
101    --  For each actual of an in-out parameter which is a numeric conversion
102    --  of the form T(A), where A denotes a variable, we insert the declaration:
103    --
104    --    Temp : T := T(A);
105    --
106    --  prior to the call. Then we replace the actual with a reference to Temp,
107    --  and append the assignment:
108    --
109    --    A := T' (Temp);
110    --
111    --  after the call. Here T' is the actual type of variable A.
112    --  For out parameters, the initial declaration has no expression.
113    --  If A is not an entity name,  we generate instead:
114    --
115    --    Var  : T' renames A;
116    --    Temp : T := Var;       --  omitting expression for out parameter.
117    --    ...
118    --    Var := T' (Temp);
119    --
120    --  For other in-out parameters, we emit the required constraint checks
121    --  before and/or after the call.
122
123    --  For all parameter modes, actuals that denote components and slices
124    --  of packed arrays are expanded into suitable temporaries.
125
126    procedure Expand_Inlined_Call
127     (N         : Node_Id;
128      Subp      : Entity_Id;
129      Orig_Subp : Entity_Id);
130    --  If called subprogram can be inlined by the front-end, retrieve the
131    --  analyzed body, replace formals with actuals and expand call in place.
132    --  Generate thunks for actuals that are expressions, and insert the
133    --  corresponding constant declarations before the call. If the original
134    --  call is to a derived operation, the return type is the one of the
135    --  derived operation, but the body is that of the original, so return
136    --  expressions in the body must be converted to the desired type (which
137    --  is simply not noted in the tree without inline expansion).
138
139    function Expand_Protected_Object_Reference
140      (N    : Node_Id;
141       Scop : Entity_Id)
142       return Node_Id;
143
144    procedure Expand_Protected_Subprogram_Call
145      (N    : Node_Id;
146       Subp : Entity_Id;
147       Scop : Entity_Id);
148    --  A call to a protected subprogram within the protected object may appear
149    --  as a regular call. The list of actuals must be expanded to contain a
150    --  reference to the object itself, and the call becomes a call to the
151    --  corresponding protected subprogram.
152
153    ---------------------------------
154    --  Check_Overriding_Operation --
155    ---------------------------------
156
157    procedure Check_Overriding_Operation (Subp : Entity_Id) is
158       Typ     : constant Entity_Id := Find_Dispatching_Type (Subp);
159       Op_List : constant Elist_Id  := Primitive_Operations (Typ);
160       Op_Elmt : Elmt_Id;
161       Prim_Op : Entity_Id;
162       Par_Op  : Entity_Id;
163
164    begin
165       if Is_Derived_Type (Typ)
166         and then not Is_Private_Type (Typ)
167         and then In_Open_Scopes (Scope (Etype (Typ)))
168         and then Typ = Base_Type (Typ)
169       then
170          --  Subp overrides an inherited private operation if there is
171          --  an inherited operation with a different name than Subp (see
172          --  Derive_Subprogram) whose Alias is a hidden  subprogram with
173          --  the same name as Subp.
174
175          Op_Elmt := First_Elmt (Op_List);
176          while Present (Op_Elmt) loop
177             Prim_Op := Node (Op_Elmt);
178             Par_Op  := Alias (Prim_Op);
179
180             if Present (Par_Op)
181               and then not Comes_From_Source (Prim_Op)
182               and then Chars (Prim_Op) /= Chars (Par_Op)
183               and then Chars (Par_Op) = Chars (Subp)
184               and then Is_Hidden (Par_Op)
185               and then Type_Conformant (Prim_Op, Subp)
186             then
187                Set_DT_Position (Subp, DT_Position (Prim_Op));
188             end if;
189
190             Next_Elmt (Op_Elmt);
191          end loop;
192       end if;
193    end Check_Overriding_Operation;
194
195    -------------------------------
196    -- Detect_Infinite_Recursion --
197    -------------------------------
198
199    procedure Detect_Infinite_Recursion (N : Node_Id; Spec : Entity_Id) is
200       Loc : constant Source_Ptr := Sloc (N);
201
202       Var_List : Elist_Id := New_Elmt_List;
203       --  List of globals referenced by body of procedure
204
205       Call_List : Elist_Id := New_Elmt_List;
206       --  List of recursive calls in body of procedure
207
208       Shad_List : Elist_Id := New_Elmt_List;
209       --  List of entity id's for entities created to capture the
210       --  value of referenced globals on entry to the procedure.
211
212       Scop : constant Uint := Scope_Depth (Spec);
213       --  This is used to record the scope depth of the current
214       --  procedure, so that we can identify global references.
215
216       Max_Vars : constant := 4;
217       --  Do not test more than four global variables
218
219       Count_Vars : Natural := 0;
220       --  Count variables found so far
221
222       Var  : Entity_Id;
223       Elm  : Elmt_Id;
224       Ent  : Entity_Id;
225       Call : Elmt_Id;
226       Decl : Node_Id;
227       Test : Node_Id;
228       Elm1 : Elmt_Id;
229       Elm2 : Elmt_Id;
230       Last : Node_Id;
231
232       function Process (Nod : Node_Id) return Traverse_Result;
233       --  Function to traverse the subprogram body (using Traverse_Func)
234
235       -------------
236       -- Process --
237       -------------
238
239       function Process (Nod : Node_Id) return Traverse_Result is
240       begin
241          --  Procedure call
242
243          if Nkind (Nod) = N_Procedure_Call_Statement then
244
245             --  Case of one of the detected recursive calls
246
247             if Is_Entity_Name (Name (Nod))
248               and then Has_Recursive_Call (Entity (Name (Nod)))
249               and then Entity (Name (Nod)) = Spec
250             then
251                Append_Elmt (Nod, Call_List);
252                return Skip;
253
254             --  Any other procedure call may have side effects
255
256             else
257                return Abandon;
258             end if;
259
260          --  A call to a pure function can always be ignored
261
262          elsif Nkind (Nod) = N_Function_Call
263            and then Is_Entity_Name (Name (Nod))
264            and then Is_Pure (Entity (Name (Nod)))
265          then
266             return Skip;
267
268          --  Case of an identifier reference
269
270          elsif Nkind (Nod) = N_Identifier then
271             Ent := Entity (Nod);
272
273             --  If no entity, then ignore the reference
274
275             --  Not clear why this can happen. To investigate, remove this
276             --  test and look at the crash that occurs here in 3401-004 ???
277
278             if No (Ent) then
279                return Skip;
280
281             --  Ignore entities with no Scope, again not clear how this
282             --  can happen, to investigate, look at 4108-008 ???
283
284             elsif No (Scope (Ent)) then
285                return Skip;
286
287             --  Ignore the reference if not to a more global object
288
289             elsif Scope_Depth (Scope (Ent)) >= Scop then
290                return Skip;
291
292             --  References to types, exceptions and constants are always OK
293
294             elsif Is_Type (Ent)
295               or else Ekind (Ent) = E_Exception
296               or else Ekind (Ent) = E_Constant
297             then
298                return Skip;
299
300             --  If other than a non-volatile scalar variable, we have some
301             --  kind of global reference (e.g. to a function) that we cannot
302             --  deal with so we forget the attempt.
303
304             elsif Ekind (Ent) /= E_Variable
305               or else not Is_Scalar_Type (Etype (Ent))
306               or else Is_Volatile (Ent)
307             then
308                return Abandon;
309
310             --  Otherwise we have a reference to a global scalar
311
312             else
313                --  Loop through global entities already detected
314
315                Elm := First_Elmt (Var_List);
316                loop
317                   --  If not detected before, record this new global reference
318
319                   if No (Elm) then
320                      Count_Vars := Count_Vars + 1;
321
322                      if Count_Vars <= Max_Vars then
323                         Append_Elmt (Entity (Nod), Var_List);
324                      else
325                         return Abandon;
326                      end if;
327
328                      exit;
329
330                   --  If recorded before, ignore
331
332                   elsif Node (Elm) = Entity (Nod) then
333                      return Skip;
334
335                   --  Otherwise keep looking
336
337                   else
338                      Next_Elmt (Elm);
339                   end if;
340                end loop;
341
342                return Skip;
343             end if;
344
345          --  For all other node kinds, recursively visit syntactic children
346
347          else
348             return OK;
349          end if;
350       end Process;
351
352       function Traverse_Body is new Traverse_Func;
353
354    --  Start of processing for Detect_Infinite_Recursion
355
356    begin
357       --  Do not attempt detection in No_Implicit_Conditional mode,
358       --  since we won't be able to generate the code to handle the
359       --  recursion in any case.
360
361       if Restrictions (No_Implicit_Conditionals) then
362          return;
363       end if;
364
365       --  Otherwise do traversal and quit if we get abandon signal
366
367       if Traverse_Body (N) = Abandon then
368          return;
369
370       --  We must have a call, since Has_Recursive_Call was set. If not
371       --  just ignore (this is only an error check, so if we have a funny
372       --  situation, due to bugs or errors, we do not want to bomb!)
373
374       elsif Is_Empty_Elmt_List (Call_List) then
375          return;
376       end if;
377
378       --  Here is the case where we detect recursion at compile time
379
380       --  Push our current scope for analyzing the declarations and
381       --  code that we will insert for the checking.
382
383       New_Scope (Spec);
384
385       --  This loop builds temporary variables for each of the
386       --  referenced globals, so that at the end of the loop the
387       --  list Shad_List contains these temporaries in one-to-one
388       --  correspondence with the elements in Var_List.
389
390       Last := Empty;
391       Elm := First_Elmt (Var_List);
392       while Present (Elm) loop
393          Var := Node (Elm);
394          Ent :=
395            Make_Defining_Identifier (Loc,
396              Chars => New_Internal_Name ('S'));
397          Append_Elmt (Ent, Shad_List);
398
399          --  Insert a declaration for this temporary at the start of
400          --  the declarations for the procedure. The temporaries are
401          --  declared as constant objects initialized to the current
402          --  values of the corresponding temporaries.
403
404          Decl :=
405            Make_Object_Declaration (Loc,
406              Defining_Identifier => Ent,
407              Object_Definition   => New_Occurrence_Of (Etype (Var), Loc),
408              Constant_Present    => True,
409              Expression          => New_Occurrence_Of (Var, Loc));
410
411          if No (Last) then
412             Prepend (Decl, Declarations (N));
413          else
414             Insert_After (Last, Decl);
415          end if;
416
417          Last := Decl;
418          Analyze (Decl);
419          Next_Elmt (Elm);
420       end loop;
421
422       --  Loop through calls
423
424       Call := First_Elmt (Call_List);
425       while Present (Call) loop
426
427          --  Build a predicate expression of the form
428
429          --    True
430          --      and then global1 = temp1
431          --      and then global2 = temp2
432          --      ...
433
434          --  This predicate determines if any of the global values
435          --  referenced by the procedure have changed since the
436          --  current call, if not an infinite recursion is assured.
437
438          Test := New_Occurrence_Of (Standard_True, Loc);
439
440          Elm1 := First_Elmt (Var_List);
441          Elm2 := First_Elmt (Shad_List);
442          while Present (Elm1) loop
443             Test :=
444               Make_And_Then (Loc,
445                 Left_Opnd  => Test,
446                 Right_Opnd =>
447                   Make_Op_Eq (Loc,
448                     Left_Opnd  => New_Occurrence_Of (Node (Elm1), Loc),
449                     Right_Opnd => New_Occurrence_Of (Node (Elm2), Loc)));
450
451             Next_Elmt (Elm1);
452             Next_Elmt (Elm2);
453          end loop;
454
455          --  Now we replace the call with the sequence
456
457          --    if no-changes (see above) then
458          --       raise Storage_Error;
459          --    else
460          --       original-call
461          --    end if;
462
463          Rewrite (Node (Call),
464            Make_If_Statement (Loc,
465              Condition       => Test,
466              Then_Statements => New_List (
467                Make_Raise_Storage_Error (Loc)),
468
469              Else_Statements => New_List (
470                Relocate_Node (Node (Call)))));
471
472          Analyze (Node (Call));
473
474          Next_Elmt (Call);
475       end loop;
476
477       --  Remove temporary scope stack entry used for analysis
478
479       Pop_Scope;
480    end Detect_Infinite_Recursion;
481
482    --------------------
483    -- Expand_Actuals --
484    --------------------
485
486    procedure Expand_Actuals (N : Node_Id; Subp : Entity_Id) is
487       Loc       : constant Source_Ptr := Sloc (N);
488       Actual    : Node_Id;
489       Formal    : Entity_Id;
490       N_Node    : Node_Id;
491       Post_Call : List_Id;
492       E_Formal  : Entity_Id;
493
494       procedure Add_Call_By_Copy_Code;
495       --  For In and In-Out parameters, where the parameter must be passed
496       --  by copy, this routine generates a temporary variable into which
497       --  the actual is copied, and then passes this as the parameter. This
498       --  routine also takes care of any constraint checks required for the
499       --  type conversion case (on both the way in and the way out).
500
501       procedure Add_Packed_Call_By_Copy_Code;
502       --  This is used when the actual involves a reference to an element
503       --  of a packed array, where we can appropriately use a simpler
504       --  approach than the full call by copy code. We just copy the value
505       --  in and out of an apropriate temporary.
506
507       procedure Check_Fortran_Logical;
508       --  A value of type Logical that is passed through a formal parameter
509       --  must be normalized because .TRUE. usually does not have the same
510       --  representation as True. We assume that .FALSE. = False = 0.
511       --  What about functions that return a logical type ???
512
513       function Make_Var (Actual : Node_Id) return Entity_Id;
514       --  Returns an entity that refers to the given actual parameter,
515       --  Actual (not including any type conversion). If Actual is an
516       --  entity name, then this entity is returned unchanged, otherwise
517       --  a renaming is created to provide an entity for the actual.
518
519       procedure Reset_Packed_Prefix;
520       --  The expansion of a packed array component reference is delayed in
521       --  the context of a call. Now we need to complete the expansion, so we
522       --  unmark the analyzed bits in all prefixes.
523
524       ---------------------------
525       -- Add_Call_By_Copy_Code --
526       ---------------------------
527
528       procedure Add_Call_By_Copy_Code is
529          Expr    : Node_Id;
530          Init    : Node_Id;
531          Temp    : Entity_Id;
532          Var     : Entity_Id;
533          V_Typ   : Entity_Id;
534          Crep    : Boolean;
535
536       begin
537          Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
538
539          if Nkind (Actual) = N_Type_Conversion then
540             V_Typ := Etype (Expression (Actual));
541             Var   := Make_Var (Expression (Actual));
542             Crep  := not Same_Representation
543                        (Etype (Formal), Etype (Expression (Actual)));
544          else
545             V_Typ := Etype (Actual);
546             Var   := Make_Var (Actual);
547             Crep  := False;
548          end if;
549
550          --  Setup initialization for case of in out parameter, or an out
551          --  parameter where the formal is an unconstrained array (in the
552          --  latter case, we have to pass in an object with bounds).
553
554          if Ekind (Formal) = E_In_Out_Parameter
555            or else (Is_Array_Type (Etype (Formal))
556                      and then
557                     not Is_Constrained (Etype (Formal)))
558          then
559             if Nkind (Actual) = N_Type_Conversion then
560                if Conversion_OK (Actual) then
561                   Init := OK_Convert_To
562                             (Etype (Formal), New_Occurrence_Of (Var, Loc));
563                else
564                   Init := Convert_To
565                             (Etype (Formal), New_Occurrence_Of (Var, Loc));
566                end if;
567             else
568                Init := New_Occurrence_Of (Var, Loc);
569             end if;
570
571          --  An initialization is created for packed conversions as
572          --  actuals for out parameters to enable Make_Object_Declaration
573          --  to determine the proper subtype for N_Node. Note that this
574          --  is wasteful because the extra copying on the call side is
575          --  not required for such out parameters. ???
576
577          elsif Ekind (Formal) = E_Out_Parameter
578            and then Nkind (Actual) = N_Type_Conversion
579            and then (Is_Bit_Packed_Array (Etype (Formal))
580                        or else
581                      Is_Bit_Packed_Array (Etype (Expression (Actual))))
582          then
583             if Conversion_OK (Actual) then
584                Init :=
585                  OK_Convert_To (Etype (Formal), New_Occurrence_Of (Var, Loc));
586             else
587                Init :=
588                  Convert_To (Etype (Formal), New_Occurrence_Of (Var, Loc));
589             end if;
590          else
591             Init := Empty;
592          end if;
593
594          N_Node :=
595            Make_Object_Declaration (Loc,
596              Defining_Identifier => Temp,
597              Object_Definition   =>
598                New_Occurrence_Of (Etype (Formal), Loc),
599              Expression => Init);
600          Set_Assignment_OK (N_Node);
601          Insert_Action (N, N_Node);
602
603          --  Now, normally the deal here is that we use the defining
604          --  identifier created by that object declaration. There is
605          --  one exception to this. In the change of representation case
606          --  the above declaration will end up looking like:
607
608          --    temp : type := identifier;
609
610          --  And in this case we might as well use the identifier directly
611          --  and eliminate the temporary. Note that the analysis of the
612          --  declaration was not a waste of time in that case, since it is
613          --  what generated the necessary change of representation code. If
614          --  the change of representation introduced additional code, as in
615          --  a fixed-integer conversion, the expression is not an identifier
616          --  and must be kept.
617
618          if Crep
619            and then Present (Expression (N_Node))
620            and then Is_Entity_Name (Expression (N_Node))
621          then
622             Temp := Entity (Expression (N_Node));
623             Rewrite (N_Node, Make_Null_Statement (Loc));
624          end if;
625
626          --  If type conversion, use reverse conversion on exit
627
628          if Nkind (Actual) = N_Type_Conversion then
629             if Conversion_OK (Actual) then
630                Expr := OK_Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
631             else
632                Expr := Convert_To (V_Typ, New_Occurrence_Of (Temp, Loc));
633             end if;
634          else
635             Expr := New_Occurrence_Of (Temp, Loc);
636          end if;
637
638          Rewrite (Actual, New_Reference_To (Temp, Loc));
639          Analyze (Actual);
640
641          Append_To (Post_Call,
642            Make_Assignment_Statement (Loc,
643              Name       => New_Occurrence_Of (Var, Loc),
644              Expression => Expr));
645
646          Set_Assignment_OK (Name (Last (Post_Call)));
647       end Add_Call_By_Copy_Code;
648
649       ----------------------------------
650       -- Add_Packed_Call_By_Copy_Code --
651       ----------------------------------
652
653       procedure Add_Packed_Call_By_Copy_Code is
654          Temp   : Entity_Id;
655          Incod  : Node_Id;
656          Outcod : Node_Id;
657          Lhs    : Node_Id;
658          Rhs    : Node_Id;
659
660       begin
661          Reset_Packed_Prefix;
662
663          --  Prepare to generate code
664
665          Temp := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
666          Incod  := Relocate_Node (Actual);
667          Outcod := New_Copy_Tree (Incod);
668
669          --  Generate declaration of temporary variable, initializing it
670          --  with the input parameter unless we have an OUT variable.
671
672          if Ekind (Formal) = E_Out_Parameter then
673             Incod := Empty;
674          end if;
675
676          Insert_Action (N,
677            Make_Object_Declaration (Loc,
678              Defining_Identifier => Temp,
679              Object_Definition   =>
680                New_Occurrence_Of (Etype (Formal), Loc),
681              Expression => Incod));
682
683          --  The actual is simply a reference to the temporary
684
685          Rewrite (Actual, New_Occurrence_Of (Temp, Loc));
686
687          --  Generate copy out if OUT or IN OUT parameter
688
689          if Ekind (Formal) /= E_In_Parameter then
690             Lhs := Outcod;
691             Rhs := New_Occurrence_Of (Temp, Loc);
692
693             --  Deal with conversion
694
695             if Nkind (Lhs) = N_Type_Conversion then
696                Lhs := Expression (Lhs);
697                Rhs := Convert_To (Etype (Actual), Rhs);
698             end if;
699
700             Append_To (Post_Call,
701               Make_Assignment_Statement (Loc,
702                 Name       => Lhs,
703                 Expression => Rhs));
704          end if;
705       end Add_Packed_Call_By_Copy_Code;
706
707       ---------------------------
708       -- Check_Fortran_Logical --
709       ---------------------------
710
711       procedure Check_Fortran_Logical is
712          Logical : Entity_Id := Etype (Formal);
713          Var     : Entity_Id;
714
715       --  Note: this is very incomplete, e.g. it does not handle arrays
716       --  of logical values. This is really not the right approach at all???)
717
718       begin
719          if Convention (Subp) = Convention_Fortran
720            and then Root_Type (Etype (Formal)) = Standard_Boolean
721            and then Ekind (Formal) /= E_In_Parameter
722          then
723             Var := Make_Var (Actual);
724             Append_To (Post_Call,
725               Make_Assignment_Statement (Loc,
726                 Name => New_Occurrence_Of (Var, Loc),
727                 Expression =>
728                   Unchecked_Convert_To (
729                     Logical,
730                     Make_Op_Ne (Loc,
731                       Left_Opnd  => New_Occurrence_Of (Var, Loc),
732                       Right_Opnd =>
733                         Unchecked_Convert_To (
734                           Logical,
735                           New_Occurrence_Of (Standard_False, Loc))))));
736          end if;
737       end Check_Fortran_Logical;
738
739       --------------
740       -- Make_Var --
741       --------------
742
743       function Make_Var (Actual : Node_Id) return Entity_Id is
744          Var : Entity_Id;
745
746       begin
747          if Is_Entity_Name (Actual) then
748             return Entity (Actual);
749
750          else
751             Var := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
752
753             N_Node :=
754               Make_Object_Renaming_Declaration (Loc,
755                 Defining_Identifier => Var,
756                 Subtype_Mark        =>
757                   New_Occurrence_Of (Etype (Actual), Loc),
758                 Name                => Relocate_Node (Actual));
759
760             Insert_Action (N, N_Node);
761             return Var;
762          end if;
763       end Make_Var;
764
765       -------------------------
766       -- Reset_Packed_Prefix --
767       -------------------------
768
769       procedure Reset_Packed_Prefix is
770          Pfx : Node_Id := Actual;
771
772       begin
773          loop
774             Set_Analyzed (Pfx, False);
775             exit when Nkind (Pfx) /= N_Selected_Component
776               and then Nkind (Pfx) /= N_Indexed_Component;
777             Pfx := Prefix (Pfx);
778          end loop;
779       end Reset_Packed_Prefix;
780
781    --  Start of processing for Expand_Actuals
782
783    begin
784       Formal := First_Formal (Subp);
785       Actual := First_Actual (N);
786
787       Post_Call := New_List;
788
789       while Present (Formal) loop
790          E_Formal := Etype (Formal);
791
792          if Is_Scalar_Type (E_Formal)
793            or else Nkind (Actual) = N_Slice
794          then
795             Check_Fortran_Logical;
796
797          --  RM 6.4.1 (11)
798
799          elsif Ekind (Formal) /= E_Out_Parameter then
800
801             --  The unusual case of the current instance of a protected type
802             --  requires special handling. This can only occur in the context
803             --  of a call within the body of a protected operation.
804
805             if Is_Entity_Name (Actual)
806               and then Ekind (Entity (Actual)) = E_Protected_Type
807               and then In_Open_Scopes (Entity (Actual))
808             then
809                if Scope (Subp) /= Entity (Actual) then
810                   Error_Msg_N ("operation outside protected type may not "
811                     & "call back its protected operations?", Actual);
812                end if;
813
814                Rewrite (Actual,
815                  Expand_Protected_Object_Reference (N, Entity (Actual)));
816             end if;
817
818             Apply_Constraint_Check (Actual, E_Formal);
819
820          --  Out parameter case. No constraint checks on access type
821          --  RM 6.4.1 (13)
822
823          elsif Is_Access_Type (E_Formal) then
824             null;
825
826          --  RM 6.4.1 (14)
827
828          elsif Has_Discriminants (Base_Type (E_Formal))
829            or else Has_Non_Null_Base_Init_Proc (E_Formal)
830          then
831             Apply_Constraint_Check (Actual, E_Formal);
832
833          --  RM 6.4.1 (15)
834
835          else
836             Apply_Constraint_Check (Actual, Base_Type (E_Formal));
837          end if;
838
839          --  Processing for IN-OUT and OUT parameters
840
841          if Ekind (Formal) /= E_In_Parameter then
842
843             --  For type conversions of arrays, apply length/range checks
844
845             if Is_Array_Type (E_Formal)
846               and then Nkind (Actual) = N_Type_Conversion
847             then
848                if Is_Constrained (E_Formal) then
849                   Apply_Length_Check (Expression (Actual), E_Formal);
850                else
851                   Apply_Range_Check (Expression (Actual), E_Formal);
852                end if;
853             end if;
854
855             --  If argument is a type conversion for a type that is passed
856             --  by copy, then we must pass the parameter by copy.
857
858             if Nkind (Actual) = N_Type_Conversion
859               and then
860                 (Is_Numeric_Type (E_Formal)
861                   or else Is_Access_Type (E_Formal)
862                   or else Is_Enumeration_Type (E_Formal)
863                   or else Is_Bit_Packed_Array (Etype (Formal))
864                   or else Is_Bit_Packed_Array (Etype (Expression (Actual)))
865
866                   --  Also pass by copy if change of representation
867
868                   or else not Same_Representation
869                                (Etype (Formal),
870                                 Etype (Expression (Actual))))
871             then
872                Add_Call_By_Copy_Code;
873
874             --  References to components of bit packed arrays are expanded
875             --  at this point, rather than at the point of analysis of the
876             --  actuals, to handle the expansion of the assignment to
877             --  [in] out parameters.
878
879             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
880                Add_Packed_Call_By_Copy_Code;
881
882             --  References to slices of bit packed arrays are expanded
883
884             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
885                Add_Call_By_Copy_Code;
886
887             --  Deal with access types where the actual subtpe and the
888             --  formal subtype are not the same, requiring a check.
889
890             --  It is neccessary to exclude tagged types because of "downward
891             --  conversion" errors and a strange assertion error in namet
892             --  from gnatf in bug 1215-001 ???
893
894             elsif Is_Access_Type (E_Formal)
895               and then not Same_Type (E_Formal, Etype (Actual))
896               and then not Is_Tagged_Type (Designated_Type (E_Formal))
897             then
898                Add_Call_By_Copy_Code;
899
900             elsif Is_Entity_Name (Actual)
901               and then Is_Volatile (Entity (Actual))
902               and then not Is_Scalar_Type (Etype (Entity (Actual)))
903               and then not Is_Volatile (E_Formal)
904             then
905                Add_Call_By_Copy_Code;
906
907             elsif Nkind (Actual) = N_Indexed_Component
908               and then Is_Entity_Name (Prefix (Actual))
909               and then Has_Volatile_Components (Entity (Prefix (Actual)))
910             then
911                Add_Call_By_Copy_Code;
912             end if;
913
914          --  The only processing required for IN parameters is in the packed
915          --  array case, where we expand the indexed component (the circuit
916          --  in Exp_Ch4 deliberately left indexed components appearing as
917          --  actuals untouched, so that the special processing above for
918          --  the OUT and IN OUT cases could be performed. We could make the
919          --  test in Exp_Ch4 more complex and have it detect the parameter
920          --  mode, but it is easier simply to handle all cases here.
921
922          --  Similarly, we have to expand slices of packed arrays here
923
924          else
925             if Nkind (Actual) = N_Indexed_Component
926               and then Is_Packed (Etype (Prefix (Actual)))
927             then
928                Reset_Packed_Prefix;
929                Expand_Packed_Element_Reference (Actual);
930
931             elsif Is_Ref_To_Bit_Packed_Array (Actual) then
932                Add_Packed_Call_By_Copy_Code;
933
934             elsif Is_Ref_To_Bit_Packed_Slice (Actual) then
935                declare
936                   Typ : constant Entity_Id := Etype (Actual);
937
938                   Ent : constant Entity_Id :=
939                           Make_Defining_Identifier (Loc,
940                             Chars => New_Internal_Name ('T'));
941
942                   Decl : constant Node_Id :=
943                            Make_Object_Declaration (Loc,
944                              Defining_Identifier => Ent,
945                              Object_Definition   =>
946                                New_Occurrence_Of (Typ, Loc));
947
948                begin
949                   Set_No_Initialization (Decl);
950
951                   Insert_Actions (N, New_List (
952                     Decl,
953                     Make_Assignment_Statement (Loc,
954                       Name => New_Occurrence_Of (Ent, Loc),
955                       Expression => Relocate_Node (Actual))));
956
957                   Rewrite
958                     (Actual, New_Occurrence_Of (Ent, Loc));
959                   Analyze_And_Resolve (Actual, Typ);
960                end;
961             end if;
962          end if;
963
964          Next_Formal (Formal);
965          Next_Actual (Actual);
966       end loop;
967
968       --  Find right place to put post call stuff if it is present
969
970       if not Is_Empty_List (Post_Call) then
971
972          --  If call is not a list member, it must be the triggering
973          --  statement of a triggering alternative or an entry call
974          --  alternative, and we can add the post call stuff to the
975          --  corresponding statement list.
976
977          if not Is_List_Member (N) then
978             declare
979                P : constant Node_Id := Parent (N);
980
981             begin
982                pragma Assert (Nkind (P) = N_Triggering_Alternative
983                  or else Nkind (P) = N_Entry_Call_Alternative);
984
985                if Is_Non_Empty_List (Statements (P)) then
986                   Insert_List_Before_And_Analyze
987                     (First (Statements (P)), Post_Call);
988                else
989                   Set_Statements (P, Post_Call);
990                end if;
991             end;
992
993          --  Otherwise, normal case where N is in a statement sequence,
994          --  just put the post-call stuff after the call statement.
995
996          else
997             Insert_Actions_After (N, Post_Call);
998          end if;
999       end if;
1000
1001       --  The call node itself is re-analyzed in Expand_Call.
1002
1003    end Expand_Actuals;
1004
1005    -----------------
1006    -- Expand_Call --
1007    -----------------
1008
1009    --  This procedure handles expansion of function calls and procedure call
1010    --  statements (i.e. it serves as the body for Expand_N_Function_Call and
1011    --  Expand_N_Procedure_Call_Statement. Processing for calls includes:
1012
1013    --    Replace call to Raise_Exception by Raise_Exception always if possible
1014    --    Provide values of actuals for all formals in Extra_Formals list
1015    --    Replace "call" to enumeration literal function by literal itself
1016    --    Rewrite call to predefined operator as operator
1017    --    Replace actuals to in-out parameters that are numeric conversions,
1018    --     with explicit assignment to temporaries before and after the call.
1019    --    Remove optional actuals if First_Optional_Parameter specified.
1020
1021    --   Note that the list of actuals has been filled with default expressions
1022    --   during semantic analysis of the call. Only the extra actuals required
1023    --   for the 'Constrained attribute and for accessibility checks are added
1024    --   at this point.
1025
1026    procedure Expand_Call (N : Node_Id) is
1027       Loc           : constant Source_Ptr := Sloc (N);
1028       Remote        : constant Boolean    := Is_Remote_Call (N);
1029       Subp          : Entity_Id;
1030       Orig_Subp     : Entity_Id := Empty;
1031       Parent_Subp   : Entity_Id;
1032       Parent_Formal : Entity_Id;
1033       Actual        : Node_Id;
1034       Formal        : Entity_Id;
1035       Prev          : Node_Id := Empty;
1036       Prev_Orig     : Node_Id;
1037       Scop          : Entity_Id;
1038       Extra_Actuals : List_Id := No_List;
1039       Cond          : Node_Id;
1040
1041       procedure Add_Actual_Parameter (Insert_Param : Node_Id);
1042       --  Adds one entry to the end of the actual parameter list. Used for
1043       --  default parameters and for extra actuals (for Extra_Formals).
1044       --  The argument is an N_Parameter_Association node.
1045
1046       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id);
1047       --  Adds an extra actual to the list of extra actuals. Expr
1048       --  is the expression for the value of the actual, EF is the
1049       --  entity for the extra formal.
1050
1051       function Inherited_From_Formal (S : Entity_Id) return Entity_Id;
1052       --  Within an instance, a type derived from a non-tagged formal derived
1053       --  type inherits from the original parent, not from the actual. This is
1054       --  tested in 4723-003. The current derivation mechanism has the derived
1055       --  type inherit from the actual, which is only correct outside of the
1056       --  instance. If the subprogram is inherited, we test for this particular
1057       --  case through a convoluted tree traversal before setting the proper
1058       --  subprogram to be called.
1059
1060       --------------------------
1061       -- Add_Actual_Parameter --
1062       --------------------------
1063
1064       procedure Add_Actual_Parameter (Insert_Param : Node_Id) is
1065          Actual_Expr : constant Node_Id :=
1066                          Explicit_Actual_Parameter (Insert_Param);
1067
1068       begin
1069          --  Case of insertion is first named actual
1070
1071          if No (Prev) or else
1072             Nkind (Parent (Prev)) /= N_Parameter_Association
1073          then
1074             Set_Next_Named_Actual (Insert_Param, First_Named_Actual (N));
1075             Set_First_Named_Actual (N, Actual_Expr);
1076
1077             if No (Prev) then
1078                if not Present (Parameter_Associations (N)) then
1079                   Set_Parameter_Associations (N, New_List);
1080                   Append (Insert_Param, Parameter_Associations (N));
1081                end if;
1082             else
1083                Insert_After (Prev, Insert_Param);
1084             end if;
1085
1086          --  Case of insertion is not first named actual
1087
1088          else
1089             Set_Next_Named_Actual
1090               (Insert_Param, Next_Named_Actual (Parent (Prev)));
1091             Set_Next_Named_Actual (Parent (Prev), Actual_Expr);
1092             Append (Insert_Param, Parameter_Associations (N));
1093          end if;
1094
1095          Prev := Actual_Expr;
1096       end Add_Actual_Parameter;
1097
1098       ----------------------
1099       -- Add_Extra_Actual --
1100       ----------------------
1101
1102       procedure Add_Extra_Actual (Expr : Node_Id; EF : Entity_Id) is
1103          Loc : constant Source_Ptr := Sloc (Expr);
1104
1105       begin
1106          if Extra_Actuals = No_List then
1107             Extra_Actuals := New_List;
1108             Set_Parent (Extra_Actuals, N);
1109          end if;
1110
1111          Append_To (Extra_Actuals,
1112            Make_Parameter_Association (Loc,
1113              Explicit_Actual_Parameter => Expr,
1114              Selector_Name =>
1115                Make_Identifier (Loc, Chars (EF))));
1116
1117          Analyze_And_Resolve (Expr, Etype (EF));
1118
1119       end Add_Extra_Actual;
1120
1121       ---------------------------
1122       -- Inherited_From_Formal --
1123       ---------------------------
1124
1125       function Inherited_From_Formal (S : Entity_Id) return Entity_Id is
1126          Par      : Entity_Id;
1127          Gen_Par  : Entity_Id;
1128          Gen_Prim : Elist_Id;
1129          Elmt     : Elmt_Id;
1130          Indic    : Node_Id;
1131
1132       begin
1133          --  If the operation is inherited, it is attached to the corresponding
1134          --  type derivation. If the parent in the derivation is a generic
1135          --  actual, it is a subtype of the actual, and we have to recover the
1136          --  original derived type declaration to find the proper parent.
1137
1138          if Nkind (Parent (S)) /= N_Full_Type_Declaration
1139             or else not Is_Derived_Type (Defining_Identifier (Parent (S)))
1140             or else Nkind (Type_Definition (Original_Node (Parent (S))))
1141               /= N_Derived_Type_Definition
1142          then
1143             return Empty;
1144
1145          else
1146             Indic :=
1147               (Subtype_Indication
1148                 (Type_Definition (Original_Node (Parent (S)))));
1149
1150             if Nkind (Indic) = N_Subtype_Indication then
1151                Par := Entity (Subtype_Mark (Indic));
1152             else
1153                Par := Entity (Indic);
1154             end if;
1155          end if;
1156
1157          if not Is_Generic_Actual_Type (Par)
1158            or else Is_Tagged_Type (Par)
1159            or else Nkind (Parent (Par)) /= N_Subtype_Declaration
1160            or else not In_Open_Scopes (Scope (Par))
1161            or else not In_Instance
1162          then
1163             return Empty;
1164
1165          else
1166             Gen_Par := Generic_Parent_Type (Parent (Par));
1167          end if;
1168
1169          Gen_Prim := Collect_Primitive_Operations (Gen_Par);
1170          Elmt := First_Elmt (Gen_Prim);
1171
1172          while Present (Elmt) loop
1173             if Chars (Node (Elmt)) = Chars (S) then
1174                declare
1175                   F1 : Entity_Id;
1176                   F2 : Entity_Id;
1177                begin
1178
1179                   F1 := First_Formal (S);
1180                   F2 := First_Formal (Node (Elmt));
1181
1182                   while Present (F1)
1183                     and then Present (F2)
1184                   loop
1185
1186                      if Etype (F1) = Etype (F2)
1187                        or else Etype (F2) = Gen_Par
1188                      then
1189                         Next_Formal (F1);
1190                         Next_Formal (F2);
1191                      else
1192                         Next_Elmt (Elmt);
1193                         exit;   --  not the right subprogram
1194                      end if;
1195
1196                      return Node (Elmt);
1197                   end loop;
1198                end;
1199
1200             else
1201                Next_Elmt (Elmt);
1202             end if;
1203          end loop;
1204
1205          raise Program_Error;
1206       end Inherited_From_Formal;
1207
1208    --  Start of processing for Expand_Call
1209
1210    begin
1211       --  Call using access to subprogram with explicit dereference
1212
1213       if Nkind (Name (N)) = N_Explicit_Dereference then
1214          Subp        := Etype (Name (N));
1215          Parent_Subp := Empty;
1216
1217       --  Case of call to simple entry, where the Name is a selected component
1218       --  whose prefix is the task, and whose selector name is the entry name
1219
1220       elsif Nkind (Name (N)) = N_Selected_Component then
1221          Subp        := Entity (Selector_Name (Name (N)));
1222          Parent_Subp := Empty;
1223
1224       --  Case of call to member of entry family, where Name is an indexed
1225       --  component, with the prefix being a selected component giving the
1226       --  task and entry family name, and the index being the entry index.
1227
1228       elsif Nkind (Name (N)) = N_Indexed_Component then
1229          Subp        := Entity (Selector_Name (Prefix (Name (N))));
1230          Parent_Subp := Empty;
1231
1232       --  Normal case
1233
1234       else
1235          Subp        := Entity (Name (N));
1236          Parent_Subp := Alias (Subp);
1237
1238          --  Replace call to Raise_Exception by call to Raise_Exception_Always
1239          --  if we can tell that the first parameter cannot possibly be null.
1240
1241          if not Restrictions (No_Exception_Handlers)
1242            and then Is_RTE (Subp, RE_Raise_Exception)
1243          then
1244             declare
1245                FA : constant Node_Id := Original_Node (First_Actual (N));
1246
1247             begin
1248                --  The case we catch is where the first argument is obtained
1249                --  using the Identity attribute (which must always be non-null)
1250
1251                if Nkind (FA) = N_Attribute_Reference
1252                  and then Attribute_Name (FA) = Name_Identity
1253                then
1254                   Subp := RTE (RE_Raise_Exception_Always);
1255                   Set_Entity (Name (N), Subp);
1256                end if;
1257             end;
1258          end if;
1259
1260          if Ekind (Subp) = E_Entry then
1261             Parent_Subp := Empty;
1262          end if;
1263       end if;
1264
1265       --  First step, compute  extra actuals, corresponding to any
1266       --  Extra_Formals present. Note that we do not access Extra_Formals
1267       --  directly, instead we simply  note the presence of the extra
1268       --  formals as we process the regular formals and collect the
1269       --  corresponding actuals in Extra_Actuals.
1270
1271       Formal := First_Formal (Subp);
1272       Actual := First_Actual (N);
1273
1274       while Present (Formal) loop
1275          Prev := Actual;
1276          Prev_Orig := Original_Node (Prev);
1277
1278          --  Create possible extra actual for constrained case. Usually,
1279          --  the extra actual is of the form actual'constrained, but since
1280          --  this attribute is only available for unconstrained records,
1281          --  TRUE is expanded if the type of the formal happens to be
1282          --  constrained (for instance when this procedure is inherited
1283          --  from an unconstrained record to a constrained one) or if the
1284          --  actual has no discriminant (its type is constrained). An
1285          --  exception to this is the case of a private type without
1286          --  discriminants. In this case we pass FALSE because the
1287          --  object has underlying discriminants with defaults.
1288
1289          if Present (Extra_Constrained (Formal)) then
1290             if Ekind (Etype (Prev)) in Private_Kind
1291               and then not Has_Discriminants (Base_Type (Etype (Prev)))
1292             then
1293                Add_Extra_Actual (
1294                  New_Occurrence_Of (Standard_False, Loc),
1295                  Extra_Constrained (Formal));
1296
1297             elsif Is_Constrained (Etype (Formal))
1298               or else not Has_Discriminants (Etype (Prev))
1299             then
1300                Add_Extra_Actual (
1301                  New_Occurrence_Of (Standard_True, Loc),
1302                  Extra_Constrained (Formal));
1303
1304             else
1305                --  If the actual is a type conversion, then the constrained
1306                --  test applies to the actual, not the target type.
1307
1308                declare
1309                   Act_Prev : Node_Id := Prev;
1310
1311                begin
1312                   --  Test for unchecked conversions as well, which can
1313                   --  occur as out parameter actuals on calls to stream
1314                   --  procedures.
1315
1316                   if Nkind (Act_Prev) = N_Type_Conversion
1317                     or else Nkind (Act_Prev) = N_Unchecked_Type_Conversion
1318                   then
1319                      Act_Prev := Expression (Act_Prev);
1320                   end if;
1321
1322                   Add_Extra_Actual (
1323                     Make_Attribute_Reference (Sloc (Prev),
1324                       Prefix => Duplicate_Subexpr (Act_Prev, Name_Req => True),
1325                       Attribute_Name => Name_Constrained),
1326                     Extra_Constrained (Formal));
1327                end;
1328             end if;
1329          end if;
1330
1331          --  Create possible extra actual for accessibility level
1332
1333          if Present (Extra_Accessibility (Formal)) then
1334             if Is_Entity_Name (Prev_Orig) then
1335
1336                --  When passing an access parameter as the actual to another
1337                --  access parameter we need to pass along the actual's own
1338                --  associated access level parameter. This is done is we are
1339                --  in the scope of the formal access parameter (if this is an
1340                --  inlined body the extra formal is irrelevant).
1341
1342                if Ekind (Entity (Prev_Orig)) in Formal_Kind
1343                  and then Ekind (Etype (Prev_Orig)) = E_Anonymous_Access_Type
1344                  and then In_Open_Scopes (Scope (Entity (Prev_Orig)))
1345                then
1346                   declare
1347                      Parm_Ent : constant Entity_Id := Param_Entity (Prev_Orig);
1348
1349                   begin
1350                      pragma Assert (Present (Parm_Ent));
1351
1352                      if Present (Extra_Accessibility (Parm_Ent)) then
1353                         Add_Extra_Actual (
1354                           New_Occurrence_Of
1355                             (Extra_Accessibility (Parm_Ent), Loc),
1356                           Extra_Accessibility (Formal));
1357
1358                      --  If the actual access parameter does not have an
1359                      --  associated extra formal providing its scope level,
1360                      --  then treat the actual as having library-level
1361                      --  accessibility.
1362
1363                      else
1364                         Add_Extra_Actual (
1365                           Make_Integer_Literal (Loc,
1366                             Intval => Scope_Depth (Standard_Standard)),
1367                           Extra_Accessibility (Formal));
1368                      end if;
1369                   end;
1370
1371                --  The actual is a normal access value, so just pass the
1372                --  level of the actual's access type.
1373
1374                else
1375                   Add_Extra_Actual (
1376                     Make_Integer_Literal (Loc,
1377                       Intval => Type_Access_Level (Etype (Prev_Orig))),
1378                     Extra_Accessibility (Formal));
1379                end if;
1380
1381             else
1382                case Nkind (Prev_Orig) is
1383
1384                   when N_Attribute_Reference =>
1385
1386                      case Get_Attribute_Id (Attribute_Name (Prev_Orig)) is
1387
1388                         --  For X'Access, pass on the level of the prefix X
1389
1390                         when Attribute_Access =>
1391                            Add_Extra_Actual (
1392                              Make_Integer_Literal (Loc,
1393                                Intval =>
1394                                  Object_Access_Level (Prefix (Prev_Orig))),
1395                              Extra_Accessibility (Formal));
1396
1397                         --  Treat the unchecked attributes as library-level
1398
1399                         when Attribute_Unchecked_Access |
1400                            Attribute_Unrestricted_Access =>
1401                            Add_Extra_Actual (
1402                              Make_Integer_Literal (Loc,
1403                                Intval => Scope_Depth (Standard_Standard)),
1404                              Extra_Accessibility (Formal));
1405
1406                         --  No other cases of attributes returning access
1407                         --  values that can be passed to access parameters
1408
1409                         when others =>
1410                            raise Program_Error;
1411
1412                      end case;
1413
1414                   --  For allocators we pass the level of the execution of
1415                   --  the called subprogram, which is one greater than the
1416                   --  current scope level.
1417
1418                   when N_Allocator =>
1419                      Add_Extra_Actual (
1420                        Make_Integer_Literal (Loc,
1421                         Scope_Depth (Current_Scope) + 1),
1422                        Extra_Accessibility (Formal));
1423
1424                   --  For other cases we simply pass the level of the
1425                   --  actual's access type.
1426
1427                   when others =>
1428                      Add_Extra_Actual (
1429                        Make_Integer_Literal (Loc,
1430                          Intval => Type_Access_Level (Etype (Prev_Orig))),
1431                        Extra_Accessibility (Formal));
1432
1433                end case;
1434             end if;
1435          end if;
1436
1437          --  Perform the check of 4.6(49) that prevents a null value
1438          --  from being passed as an actual to an access parameter.
1439          --  Note that the check is elided in the common cases of
1440          --  passing an access attribute or access parameter as an
1441          --  actual. Also, we currently don't enforce this check for
1442          --  expander-generated actuals and when -gnatdj is set.
1443
1444          if Ekind (Etype (Formal)) /= E_Anonymous_Access_Type
1445            or else Suppress_Accessibility_Checks (Subp)
1446          then
1447             null;
1448
1449          elsif Debug_Flag_J then
1450             null;
1451
1452          elsif not Comes_From_Source (Prev) then
1453             null;
1454
1455          elsif Is_Entity_Name (Prev)
1456            and then Ekind (Etype (Prev)) = E_Anonymous_Access_Type
1457          then
1458             null;
1459
1460          elsif Nkind (Prev) = N_Allocator
1461            or else Nkind (Prev) = N_Attribute_Reference
1462          then
1463             null;
1464
1465          --  Suppress null checks when passing to access parameters
1466          --  of Java subprograms. (Should this be done for other
1467          --  foreign conventions as well ???)
1468
1469          elsif Convention (Subp) = Convention_Java then
1470             null;
1471
1472          else
1473             Cond :=
1474               Make_Op_Eq (Loc,
1475                 Left_Opnd => Duplicate_Subexpr (Prev),
1476                 Right_Opnd => Make_Null (Loc));
1477             Insert_Action (Prev, Make_Raise_Constraint_Error (Loc, Cond));
1478          end if;
1479
1480          --  Perform apropriate validity checks on parameters
1481
1482          if Validity_Checks_On then
1483
1484             if Ekind (Formal) = E_In_Parameter
1485               and then Validity_Check_In_Params
1486             then
1487                Ensure_Valid (Actual);
1488
1489             elsif Ekind (Formal) = E_In_Out_Parameter
1490               and then Validity_Check_In_Out_Params
1491             then
1492                Ensure_Valid (Actual);
1493             end if;
1494          end if;
1495
1496          --  For IN OUT and OUT parameters, ensure that subscripts are valid
1497          --  since this is a left side reference. We only do this for calls
1498          --  from the source program since we assume that compiler generated
1499          --  calls explicitly generate any required checks. We also need it
1500          --  only if we are doing standard validity checks, since clearly it
1501          --  is not needed if validity checks are off, and in subscript
1502          --  validity checking mode, all indexed components are checked with
1503          --  a call directly from Expand_N_Indexed_Component.
1504
1505          if Comes_From_Source (N)
1506            and then Ekind (Formal) /= E_In_Parameter
1507            and then Validity_Checks_On
1508            and then Validity_Check_Default
1509            and then not Validity_Check_Subscripts
1510          then
1511             Check_Valid_Lvalue_Subscripts (Actual);
1512          end if;
1513
1514          --  If the formal is class wide and the actual is an aggregate, force
1515          --  evaluation so that the back end who does not know about class-wide
1516          --  type, does not generate a temporary of the wrong size.
1517
1518          if not Is_Class_Wide_Type (Etype (Formal)) then
1519             null;
1520
1521          elsif Nkind (Actual) = N_Aggregate
1522            or else (Nkind (Actual) = N_Qualified_Expression
1523                      and then Nkind (Expression (Actual)) = N_Aggregate)
1524          then
1525             Force_Evaluation (Actual);
1526          end if;
1527
1528          --  In a remote call, if the formal is of a class-wide type, check
1529          --  that the actual meets the requirements described in E.4(18).
1530
1531          if Remote
1532            and then Is_Class_Wide_Type (Etype (Formal))
1533          then
1534             Insert_Action (Actual,
1535               Make_Implicit_If_Statement (N,
1536                 Condition       =>
1537                   Make_Op_Not (Loc,
1538                     Get_Remotely_Callable (Duplicate_Subexpr (Actual))),
1539                 Then_Statements => New_List (
1540                   Make_Procedure_Call_Statement (Loc,
1541                     New_Occurrence_Of (RTE
1542                       (RE_Raise_Program_Error_For_E_4_18), Loc)))));
1543          end if;
1544
1545          Next_Actual (Actual);
1546          Next_Formal (Formal);
1547       end loop;
1548
1549       --  If we are expanding a rhs of an assignement we need to check if
1550       --  tag propagation is needed. This code belongs theorically in Analyze
1551       --  Assignment  but has to be done earlier (bottom-up) because the
1552       --  assignment might be transformed into a declaration for an uncons-
1553       --  trained value, if the expression is classwide.
1554
1555       if Nkind (N) = N_Function_Call
1556         and then Is_Tag_Indeterminate (N)
1557         and then Is_Entity_Name (Name (N))
1558       then
1559          declare
1560             Ass : Node_Id := Empty;
1561
1562          begin
1563             if Nkind (Parent (N)) = N_Assignment_Statement then
1564                Ass := Parent (N);
1565
1566             elsif Nkind (Parent (N)) = N_Qualified_Expression
1567               and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
1568             then
1569                Ass := Parent (Parent (N));
1570             end if;
1571
1572             if Present (Ass)
1573               and then Is_Class_Wide_Type (Etype (Name (Ass)))
1574             then
1575                Propagate_Tag (Name (Ass), N);
1576                return;
1577             end if;
1578          end;
1579       end if;
1580
1581       --  Deals with Dispatch_Call if we still have a call, before expanding
1582       --  extra actuals since this will be done on the re-analysis of the
1583       --  dispatching call. Note that we do not try to shorten the actual
1584       --  list for a dispatching call, it would not make sense to do so.
1585       --  Expansion of dispatching calls is suppressed when Java_VM, because
1586       --  the JVM back end directly handles the generation of dispatching
1587       --  calls and would have to undo any expansion to an indirect call.
1588
1589       if (Nkind (N) = N_Function_Call
1590            or else Nkind (N) =  N_Procedure_Call_Statement)
1591         and then Present (Controlling_Argument (N))
1592         and then not Java_VM
1593       then
1594          Expand_Dispatch_Call (N);
1595          return;
1596
1597       --  Similarly, expand calls to RCI subprograms on which pragma
1598       --  All_Calls_Remote applies. The rewriting will be reanalyzed
1599       --  later. Do this only when the call comes from source since we do
1600       --  not want such a rewritting to occur in expanded code.
1601
1602       elsif Is_All_Remote_Call (N) then
1603          Expand_All_Calls_Remote_Subprogram_Call (N);
1604
1605       --  Similarly, do not add extra actuals for an entry call whose entity
1606       --  is a protected procedure, or for an internal protected subprogram
1607       --  call, because it will be rewritten as a protected subprogram call
1608       --  and reanalyzed (see Expand_Protected_Subprogram_Call).
1609
1610       elsif Is_Protected_Type (Scope (Subp))
1611          and then (Ekind (Subp) = E_Procedure
1612                     or else Ekind (Subp) = E_Function)
1613       then
1614          null;
1615
1616       --  During that loop we gathered the extra actuals (the ones that
1617       --  correspond to Extra_Formals), so now they can be appended.
1618
1619       else
1620          while Is_Non_Empty_List (Extra_Actuals) loop
1621             Add_Actual_Parameter (Remove_Head (Extra_Actuals));
1622          end loop;
1623       end if;
1624
1625       if Ekind (Subp) = E_Procedure
1626          or else (Ekind (Subp) = E_Subprogram_Type
1627                    and then Etype (Subp) = Standard_Void_Type)
1628          or else Is_Entry (Subp)
1629       then
1630          Expand_Actuals (N, Subp);
1631       end if;
1632
1633       --  If the subprogram is a renaming, or if it is inherited, replace it
1634       --  in the call with the name of the actual subprogram being called.
1635       --  If this is a dispatching call, the run-time decides what to call.
1636       --  The Alias attribute does not apply to entries.
1637
1638       if Nkind (N) /= N_Entry_Call_Statement
1639         and then No (Controlling_Argument (N))
1640         and then Present (Parent_Subp)
1641       then
1642          if Present (Inherited_From_Formal (Subp)) then
1643             Parent_Subp := Inherited_From_Formal (Subp);
1644          else
1645             while Present (Alias (Parent_Subp)) loop
1646                Parent_Subp := Alias (Parent_Subp);
1647             end loop;
1648          end if;
1649
1650          Set_Entity (Name (N), Parent_Subp);
1651
1652          if Is_Abstract (Parent_Subp)
1653            and then not In_Instance
1654          then
1655             Error_Msg_NE
1656               ("cannot call abstract subprogram &!", Name (N), Parent_Subp);
1657          end if;
1658
1659          --  Add an explicit conversion for parameter of the derived type.
1660          --  This is only done for scalar and access in-parameters. Others
1661          --  have been expanded in expand_actuals.
1662
1663          Formal := First_Formal (Subp);
1664          Parent_Formal := First_Formal (Parent_Subp);
1665          Actual := First_Actual (N);
1666
1667          --  It is not clear that conversion is needed for intrinsic
1668          --  subprograms, but it certainly is for those that are user-
1669          --  defined, and that can be inherited on derivation, namely
1670          --  unchecked conversion and deallocation.
1671          --  General case needs study ???
1672
1673          if not Is_Intrinsic_Subprogram (Parent_Subp)
1674            or else Is_Generic_Instance (Parent_Subp)
1675          then
1676             while Present (Formal) loop
1677
1678                if Etype (Formal) /= Etype (Parent_Formal)
1679                  and then Is_Scalar_Type (Etype (Formal))
1680                  and then Ekind (Formal) = E_In_Parameter
1681                then
1682                   Rewrite (Actual,
1683                     OK_Convert_To (Etype (Parent_Formal),
1684                       Relocate_Node (Actual)));
1685
1686                   Analyze (Actual);
1687                   Resolve (Actual, Etype (Parent_Formal));
1688                   Enable_Range_Check (Actual);
1689
1690                elsif Is_Access_Type (Etype (Formal))
1691                  and then Base_Type (Etype (Parent_Formal))
1692                    /= Base_Type (Etype (Actual))
1693                then
1694                   if Ekind (Formal) /= E_In_Parameter then
1695                      Rewrite (Actual,
1696                        Convert_To (Etype (Parent_Formal),
1697                          Relocate_Node (Actual)));
1698
1699                      Analyze (Actual);
1700                      Resolve (Actual, Etype (Parent_Formal));
1701
1702                   elsif
1703                     Ekind (Etype (Parent_Formal)) = E_Anonymous_Access_Type
1704                       and then
1705                     Designated_Type (Etype (Parent_Formal))
1706                       /= Designated_Type (Etype (Actual))
1707                       and then not Is_Controlling_Formal (Formal)
1708                   then
1709
1710                      --  This unchecked conversion is not necessary unless
1711                      --  inlining is unabled, because in that case the type
1712                      --  mismatch may become visible in the body about to be
1713                      --  inlined.
1714
1715                      Rewrite (Actual,
1716                        Unchecked_Convert_To (Etype (Parent_Formal),
1717                          Relocate_Node (Actual)));
1718
1719                      Analyze (Actual);
1720                      Resolve (Actual, Etype (Parent_Formal));
1721                   end if;
1722                end if;
1723
1724                Next_Formal (Formal);
1725                Next_Formal (Parent_Formal);
1726                Next_Actual (Actual);
1727             end loop;
1728          end if;
1729
1730          Orig_Subp := Subp;
1731          Subp := Parent_Subp;
1732       end if;
1733
1734       --  Some more special cases for cases other than explicit dereference
1735
1736       if Nkind (Name (N)) /= N_Explicit_Dereference then
1737
1738          --  Calls to an enumeration literal are replaced by the literal
1739          --  This case occurs only when we have a call to a function that
1740          --  is a renaming of an enumeration literal. The normal case of
1741          --  a direct reference to an enumeration literal has already been
1742          --  been dealt with by Resolve_Call. If the function is itself
1743          --  inherited (see 7423-001) the literal of the parent type must
1744          --  be explicitly converted to the return type of the function.
1745
1746          if Ekind (Subp) = E_Enumeration_Literal then
1747             if Base_Type (Etype (Subp)) /= Base_Type (Etype (N)) then
1748                Rewrite
1749                  (N, Convert_To (Etype (N), New_Occurrence_Of (Subp, Loc)));
1750             else
1751                Rewrite (N, New_Occurrence_Of (Subp, Loc));
1752                Resolve (N, Etype (N));
1753             end if;
1754          end if;
1755
1756       --  Handle case of access to protected subprogram type
1757
1758       else
1759          if Ekind (Base_Type (Etype (Prefix (Name (N))))) =
1760                                E_Access_Protected_Subprogram_Type
1761          then
1762             --  If this is a call through an access to protected operation,
1763             --  the prefix has the form (object'address, operation'access).
1764             --  Rewrite as a for other protected calls: the object is the
1765             --  first parameter of the list of actuals.
1766
1767             declare
1768                Call : Node_Id;
1769                Parm : List_Id;
1770                Nam  : Node_Id;
1771                Obj  : Node_Id;
1772                Ptr  : Node_Id := Prefix (Name (N));
1773                T    : Entity_Id := Equivalent_Type (Base_Type (Etype (Ptr)));
1774                D_T  : Entity_Id := Designated_Type (Base_Type (Etype (Ptr)));
1775
1776             begin
1777                Obj := Make_Selected_Component (Loc,
1778                  Prefix => Unchecked_Convert_To (T, Ptr),
1779                  Selector_Name => New_Occurrence_Of (First_Entity (T), Loc));
1780
1781                Nam := Make_Selected_Component (Loc,
1782                  Prefix => Unchecked_Convert_To (T, Ptr),
1783                  Selector_Name => New_Occurrence_Of (
1784                    Next_Entity (First_Entity (T)), Loc));
1785
1786                Nam := Make_Explicit_Dereference (Loc, Nam);
1787
1788                if Present (Parameter_Associations (N))  then
1789                   Parm := Parameter_Associations (N);
1790                else
1791                   Parm := New_List;
1792                end if;
1793
1794                Prepend (Obj, Parm);
1795
1796                if Etype (D_T) = Standard_Void_Type then
1797                   Call := Make_Procedure_Call_Statement (Loc,
1798                     Name => Nam,
1799                     Parameter_Associations => Parm);
1800                else
1801                   Call := Make_Function_Call (Loc,
1802                     Name => Nam,
1803                     Parameter_Associations => Parm);
1804                end if;
1805
1806                Set_First_Named_Actual (Call, First_Named_Actual (N));
1807
1808                Set_Etype (Call, Etype (D_T));
1809
1810                --  We do not re-analyze the call to avoid infinite recursion.
1811                --  We analyze separately the prefix and the object, and set
1812                --  the checks on the prefix that would otherwise be emitted
1813                --  when resolving a call.
1814
1815                Rewrite (N, Call);
1816                Analyze (Nam);
1817                Apply_Access_Check (Nam);
1818                Analyze (Obj);
1819                return;
1820             end;
1821          end if;
1822       end if;
1823
1824       --  If this is a call to an intrinsic subprogram, then perform the
1825       --  appropriate expansion to the corresponding tree node and we
1826       --  are all done (since after that the call is gone!)
1827
1828       if Is_Intrinsic_Subprogram (Subp) then
1829          Expand_Intrinsic_Call (N, Subp);
1830          return;
1831       end if;
1832
1833       if Ekind (Subp) = E_Function
1834         or else Ekind (Subp) = E_Procedure
1835       then
1836          if Is_Inlined (Subp) then
1837
1838             declare
1839                Spec : constant Node_Id := Unit_Declaration_Node (Subp);
1840
1841             begin
1842                --  Verify that the body to inline has already been seen,
1843                --  and that if the body is in the current unit the inlining
1844                --  does not occur earlier. This avoids order-of-elaboration
1845                --  problems in gigi.
1846
1847                if Present (Spec)
1848                  and then Nkind (Spec) = N_Subprogram_Declaration
1849                  and then Present (Body_To_Inline (Spec))
1850                  and then (In_Extended_Main_Code_Unit (N)
1851                             or else In_Extended_Main_Code_Unit (Parent (N)))
1852                  and then (not In_Same_Extended_Unit
1853                               (Sloc (Body_To_Inline (Spec)), Loc)
1854                             or else
1855                            Earlier_In_Extended_Unit
1856                               (Sloc (Body_To_Inline (Spec)), Loc))
1857                then
1858                   Expand_Inlined_Call (N, Subp, Orig_Subp);
1859
1860                else
1861                   --  Let the back-end handle it.
1862
1863                   Add_Inlined_Body (Subp);
1864
1865                   if Front_End_Inlining
1866                     and then Nkind (Spec) = N_Subprogram_Declaration
1867                     and then (In_Extended_Main_Code_Unit (N))
1868                     and then No (Body_To_Inline (Spec))
1869                     and then not Has_Completion (Subp)
1870                     and then In_Same_Extended_Unit (Sloc (Spec), Loc)
1871                     and then Ineffective_Inline_Warnings
1872                   then
1873                      Error_Msg_N
1874                       ("call cannot be inlined before body is seen?", N);
1875                   end if;
1876                end if;
1877             end;
1878          end if;
1879       end if;
1880
1881       --  Check for a protected subprogram. This is either an intra-object
1882       --  call, or a protected function call. Protected procedure calls are
1883       --  rewritten as entry calls and handled accordingly.
1884
1885       Scop := Scope (Subp);
1886
1887       if Nkind (N) /= N_Entry_Call_Statement
1888         and then Is_Protected_Type (Scop)
1889       then
1890          --  If the call is an internal one, it is rewritten as a call to
1891          --  to the corresponding unprotected subprogram.
1892
1893          Expand_Protected_Subprogram_Call (N, Subp, Scop);
1894       end if;
1895
1896       --  Functions returning controlled objects need special attention
1897
1898       if Controlled_Type (Etype (Subp))
1899         and then not Is_Return_By_Reference_Type (Etype (Subp))
1900       then
1901          Expand_Ctrl_Function_Call (N);
1902       end if;
1903
1904       --  Test for First_Optional_Parameter, and if so, truncate parameter
1905       --  list if there are optional parameters at the trailing end.
1906       --  Note we never delete procedures for call via a pointer.
1907
1908       if (Ekind (Subp) = E_Procedure or else Ekind (Subp) = E_Function)
1909         and then Present (First_Optional_Parameter (Subp))
1910       then
1911          declare
1912             Last_Keep_Arg : Node_Id;
1913
1914          begin
1915             --  Last_Keep_Arg will hold the last actual that should be
1916             --  retained. If it remains empty at the end, it means that
1917             --  all parameters are optional.
1918
1919             Last_Keep_Arg := Empty;
1920
1921             --  Find first optional parameter, must be present since we
1922             --  checked the validity of the parameter before setting it.
1923
1924             Formal := First_Formal (Subp);
1925             Actual := First_Actual (N);
1926             while Formal /= First_Optional_Parameter (Subp) loop
1927                Last_Keep_Arg := Actual;
1928                Next_Formal (Formal);
1929                Next_Actual (Actual);
1930             end loop;
1931
1932             --  Now we have Formal and Actual pointing to the first
1933             --  potentially droppable argument. We can drop all the
1934             --  trailing arguments whose actual matches the default.
1935             --  Note that we know that all remaining formals have
1936             --  defaults, because we checked that this requirement
1937             --  was met before setting First_Optional_Parameter.
1938
1939             --  We use Fully_Conformant_Expressions to check for identity
1940             --  between formals and actuals, which may miss some cases, but
1941             --  on the other hand, this is only an optimization (if we fail
1942             --  to truncate a parameter it does not affect functionality).
1943             --  So if the default is 3 and the actual is 1+2, we consider
1944             --  them unequal, which hardly seems worrisome.
1945
1946             while Present (Formal) loop
1947                if not Fully_Conformant_Expressions
1948                     (Actual, Default_Value (Formal))
1949                then
1950                   Last_Keep_Arg := Actual;
1951                end if;
1952
1953                Next_Formal (Formal);
1954                Next_Actual (Actual);
1955             end loop;
1956
1957             --  If no arguments, delete entire list, this is the easy case
1958
1959             if No (Last_Keep_Arg) then
1960                while Is_Non_Empty_List (Parameter_Associations (N)) loop
1961                   Delete_Tree (Remove_Head (Parameter_Associations (N)));
1962                end loop;
1963
1964                Set_Parameter_Associations (N, No_List);
1965                Set_First_Named_Actual (N, Empty);
1966
1967             --  Case where at the last retained argument is positional. This
1968             --  is also an easy case, since the retained arguments are already
1969             --  in the right form, and we don't need to worry about the order
1970             --  of arguments that get eliminated.
1971
1972             elsif Is_List_Member (Last_Keep_Arg) then
1973                while Present (Next (Last_Keep_Arg)) loop
1974                   Delete_Tree (Remove_Next (Last_Keep_Arg));
1975                end loop;
1976
1977                Set_First_Named_Actual (N, Empty);
1978
1979             --  This is the annoying case where the last retained argument
1980             --  is a named parameter. Since the original arguments are not
1981             --  in declaration order, we may have to delete some fairly
1982             --  random collection of arguments.
1983
1984             else
1985                declare
1986                   Temp   : Node_Id;
1987                   Passoc : Node_Id;
1988                   Junk   : Node_Id;
1989
1990                begin
1991                   --  First step, remove all the named parameters from the
1992                   --  list (they are still chained using First_Named_Actual
1993                   --  and Next_Named_Actual, so we have not lost them!)
1994
1995                   Temp := First (Parameter_Associations (N));
1996
1997                   --  Case of all parameters named, remove them all
1998
1999                   if Nkind (Temp) = N_Parameter_Association then
2000                      while Is_Non_Empty_List (Parameter_Associations (N)) loop
2001                         Temp := Remove_Head (Parameter_Associations (N));
2002                      end loop;
2003
2004                   --  Case of mixed positional/named, remove named parameters
2005
2006                   else
2007                      while Nkind (Next (Temp)) /= N_Parameter_Association loop
2008                         Next (Temp);
2009                      end loop;
2010
2011                      while Present (Next (Temp)) loop
2012                         Junk := Remove_Next (Temp);
2013                      end loop;
2014                   end if;
2015
2016                   --  Now we loop through the named parameters, till we get
2017                   --  to the last one to be retained, adding them to the list.
2018                   --  Note that the Next_Named_Actual list does not need to be
2019                   --  touched since we are only reordering them on the actual
2020                   --  parameter association list.
2021
2022                   Passoc := Parent (First_Named_Actual (N));
2023                   loop
2024                      Temp := Relocate_Node (Passoc);
2025                      Append_To
2026                        (Parameter_Associations (N), Temp);
2027                      exit when
2028                        Last_Keep_Arg = Explicit_Actual_Parameter (Passoc);
2029                      Passoc := Parent (Next_Named_Actual (Passoc));
2030                   end loop;
2031
2032                   Set_Next_Named_Actual (Temp, Empty);
2033
2034                   loop
2035                      Temp := Next_Named_Actual (Passoc);
2036                      exit when No (Temp);
2037                      Set_Next_Named_Actual
2038                        (Passoc, Next_Named_Actual (Parent (Temp)));
2039                      Delete_Tree (Temp);
2040                   end loop;
2041                end;
2042             end if;
2043          end;
2044       end if;
2045
2046    end Expand_Call;
2047
2048    --------------------------
2049    -- Expand_Inlined_Call --
2050    --------------------------
2051
2052    procedure Expand_Inlined_Call
2053     (N         : Node_Id;
2054      Subp      : Entity_Id;
2055      Orig_Subp : Entity_Id)
2056    is
2057       Loc      : constant Source_Ptr := Sloc (N);
2058       Blk      : Node_Id;
2059       Bod      : Node_Id;
2060       Decl     : Node_Id;
2061       Exit_Lab : Entity_Id := Empty;
2062       F        : Entity_Id;
2063       A        : Node_Id;
2064       Lab_Decl : Node_Id;
2065       Lab_Id   : Node_Id;
2066       New_A    : Node_Id;
2067       Num_Ret  : Int := 0;
2068       Orig_Bod : constant Node_Id :=
2069                    Body_To_Inline (Unit_Declaration_Node (Subp));
2070       Ret_Type : Entity_Id;
2071       Targ     : Node_Id;
2072       Temp     : Entity_Id;
2073       Temp_Typ : Entity_Id;
2074
2075       procedure Make_Exit_Label;
2076       --  Build declaration for exit label to be used in Return statements.
2077
2078       function Process_Formals (N : Node_Id) return Traverse_Result;
2079       --  Replace occurrence of a formal with the corresponding actual, or
2080       --  the thunk generated for it.
2081
2082       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id);
2083       --  If the function body is a single expression, replace call with
2084       --  expression, else insert block appropriately.
2085
2086       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id);
2087       --  If procedure body has no local variables, inline body without
2088       --  creating block,  otherwise rewrite call with block.
2089
2090       ---------------------
2091       -- Make_Exit_Label --
2092       ---------------------
2093
2094       procedure Make_Exit_Label is
2095       begin
2096          --  Create exit label for subprogram, if one doesn't exist yet.
2097
2098          if No (Exit_Lab) then
2099             Lab_Id := Make_Identifier (Loc, New_Internal_Name ('L'));
2100             Set_Entity (Lab_Id,
2101               Make_Defining_Identifier (Loc, Chars (Lab_Id)));
2102             Exit_Lab := Make_Label (Loc, Lab_Id);
2103
2104             Lab_Decl :=
2105               Make_Implicit_Label_Declaration (Loc,
2106                 Defining_Identifier  => Entity (Lab_Id),
2107                 Label_Construct      => Exit_Lab);
2108          end if;
2109       end Make_Exit_Label;
2110
2111       ---------------------
2112       -- Process_Formals --
2113       ---------------------
2114
2115       function Process_Formals (N : Node_Id) return Traverse_Result is
2116          A   : Entity_Id;
2117          E   : Entity_Id;
2118          Ret : Node_Id;
2119
2120       begin
2121          if Is_Entity_Name (N)
2122            and then Present (Entity (N))
2123          then
2124             E := Entity (N);
2125
2126             if Is_Formal (E)
2127               and then Scope (E) = Subp
2128             then
2129                A := Renamed_Object (E);
2130
2131                if Is_Entity_Name (A) then
2132                   Rewrite (N, New_Occurrence_Of (Entity (A), Loc));
2133
2134                elsif Nkind (A) = N_Defining_Identifier then
2135                   Rewrite (N, New_Occurrence_Of (A, Loc));
2136
2137                else   --  numeric literal
2138                   Rewrite (N, New_Copy (A));
2139                end if;
2140             end if;
2141
2142             return Skip;
2143
2144          elsif Nkind (N) = N_Return_Statement then
2145
2146             if No (Expression (N)) then
2147                Make_Exit_Label;
2148                Rewrite (N, Make_Goto_Statement (Loc,
2149                  Name => New_Copy (Lab_Id)));
2150
2151             else
2152                if Nkind (Parent (N)) = N_Handled_Sequence_Of_Statements
2153                  and then Nkind (Parent (Parent (N))) = N_Subprogram_Body
2154                then
2155                   --  function body is a single expression. No need for
2156                   --  exit label.
2157                   null;
2158
2159                else
2160                   Num_Ret := Num_Ret + 1;
2161                   Make_Exit_Label;
2162                end if;
2163
2164                --  Because of the presence of private types, the views of the
2165                --  expression and the context may be different, so place an
2166                --  unchecked conversion to the context type to avoid spurious
2167                --  errors, eg. when the expression is a numeric literal and
2168                --  the context is private. If the expression is an aggregate,
2169                --  use a qualified expression, because an aggregate is not a
2170                --  legal argument of a conversion.
2171
2172                if Nkind (Expression (N)) = N_Aggregate then
2173                   Ret :=
2174                     Make_Qualified_Expression (Sloc (N),
2175                        Subtype_Mark => New_Occurrence_Of (Ret_Type, Sloc (N)),
2176                        Expression => Relocate_Node (Expression (N)));
2177                else
2178                   Ret :=
2179                     Unchecked_Convert_To
2180                       (Ret_Type, Relocate_Node (Expression (N)));
2181                end if;
2182
2183                if Nkind (Targ) = N_Defining_Identifier then
2184                   Rewrite (N,
2185                     Make_Assignment_Statement (Loc,
2186                       Name => New_Occurrence_Of (Targ, Loc),
2187                       Expression => Ret));
2188                else
2189                   Rewrite (N,
2190                     Make_Assignment_Statement (Loc,
2191                       Name => New_Copy (Targ),
2192                       Expression => Ret));
2193                end if;
2194
2195                Set_Assignment_OK (Name (N));
2196
2197                if Present (Exit_Lab) then
2198                   Insert_After (N,
2199                     Make_Goto_Statement (Loc,
2200                       Name => New_Copy (Lab_Id)));
2201                end if;
2202             end if;
2203
2204             return OK;
2205
2206          else
2207             return OK;
2208          end if;
2209       end Process_Formals;
2210
2211       procedure Replace_Formals is new Traverse_Proc (Process_Formals);
2212
2213       ---------------------------
2214       -- Rewrite_Function_Call --
2215       ---------------------------
2216
2217       procedure Rewrite_Function_Call (N : Node_Id; Blk : Node_Id) is
2218          HSS  : Node_Id := Handled_Statement_Sequence (Blk);
2219          Fst  : Node_Id := First (Statements (HSS));
2220
2221       begin
2222
2223          --  Optimize simple case: function body is a single return statement,
2224          --  which has been expanded into an assignment.
2225
2226          if Is_Empty_List (Declarations (Blk))
2227            and then Nkind (Fst) = N_Assignment_Statement
2228            and then No (Next (Fst))
2229          then
2230
2231             --  The function call may have been rewritten as the temporary
2232             --  that holds the result of the call, in which case remove the
2233             --  now useless declaration.
2234
2235             if Nkind (N) = N_Identifier
2236               and then Nkind (Parent (Entity (N))) = N_Object_Declaration
2237             then
2238                Rewrite (Parent (Entity (N)), Make_Null_Statement (Loc));
2239             end if;
2240
2241             Rewrite (N, Expression (Fst));
2242
2243          elsif Nkind (N) = N_Identifier
2244            and then Nkind (Parent (Entity (N))) = N_Object_Declaration
2245          then
2246
2247             --  The block assigns the result of the call to the temporary.
2248
2249             Insert_After (Parent (Entity (N)), Blk);
2250
2251          elsif Nkind (Parent (N)) = N_Assignment_Statement
2252            and then Is_Entity_Name (Name (Parent (N)))
2253          then
2254
2255             --  replace assignment with the block.
2256
2257             Rewrite (Parent (N), Blk);
2258
2259          elsif Nkind (Parent (N)) = N_Object_Declaration then
2260             Set_Expression (Parent (N), Empty);
2261             Insert_After (Parent (N), Blk);
2262          end if;
2263       end Rewrite_Function_Call;
2264
2265       ----------------------------
2266       -- Rewrite_Procedure_Call --
2267       ----------------------------
2268
2269       procedure Rewrite_Procedure_Call (N : Node_Id; Blk : Node_Id) is
2270          HSS  : Node_Id := Handled_Statement_Sequence (Blk);
2271
2272       begin
2273          if Is_Empty_List (Declarations (Blk)) then
2274             Insert_List_After (N, Statements (HSS));
2275             Rewrite (N, Make_Null_Statement (Loc));
2276          else
2277             Rewrite (N, Blk);
2278          end if;
2279       end Rewrite_Procedure_Call;
2280
2281    --  Start of processing for Expand_Inlined_Call
2282
2283    begin
2284       if Nkind (Orig_Bod) = N_Defining_Identifier then
2285
2286          --  Subprogram is a renaming_as_body. Calls appearing after the
2287          --  renaming can be replaced with calls to the renamed entity
2288          --  directly, because the subprograms are subtype conformant.
2289
2290          Set_Name (N, New_Occurrence_Of (Orig_Bod, Loc));
2291          return;
2292       end if;
2293
2294       --  Use generic machinery to copy body of inlined subprogram, as if it
2295       --  were an instantiation, resetting source locations appropriately, so
2296       --  that nested inlined calls appear in the main unit.
2297
2298       Save_Env (Subp, Empty);
2299       Set_Copied_Sloc (N, Defining_Entity (Orig_Bod));
2300
2301       Bod :=
2302        Copy_Generic_Node (Orig_Bod, Empty, Instantiating => True);
2303
2304       Blk :=
2305         Make_Block_Statement (Loc,
2306           Declarations => Declarations (Bod),
2307           Handled_Statement_Sequence => Handled_Statement_Sequence (Bod));
2308
2309       if No (Declarations (Bod)) then
2310          Set_Declarations (Blk, New_List);
2311       end if;
2312
2313       --  If this is a derived function, establish the proper return type.
2314
2315       if Present (Orig_Subp)
2316         and then Orig_Subp /= Subp
2317       then
2318          Ret_Type := Etype (Orig_Subp);
2319       else
2320          Ret_Type := Etype (Subp);
2321       end if;
2322
2323       F := First_Formal (Subp);
2324       A := First_Actual (N);
2325
2326       --  Create temporaries for the actuals that are expressions, or that
2327       --  are scalars and require copying to preserve semantics.
2328
2329       while Present (F) loop
2330
2331          if Present (Renamed_Object (F)) then
2332             Error_Msg_N (" cannot inline call to recursive subprogram", N);
2333             return;
2334          end if;
2335
2336          --  If the argument may be a controlling argument in a call within
2337          --  the inlined body, we must preserve its classwide nature to
2338          --  insure that dynamic dispatching take place subsequently.
2339          --  If the formal has a constraint it must be preserved to retain
2340          --  the semantics of the body.
2341
2342          if Is_Class_Wide_Type (Etype (F))
2343            or else (Is_Access_Type (Etype (F))
2344                       and then
2345                     Is_Class_Wide_Type (Designated_Type (Etype (F))))
2346          then
2347             Temp_Typ := Etype (F);
2348
2349          elsif Base_Type (Etype (F)) = Base_Type (Etype (A))
2350            and then Etype (F) /= Base_Type (Etype (F))
2351          then
2352             Temp_Typ := Etype (F);
2353
2354          else
2355             Temp_Typ := Etype (A);
2356          end if;
2357
2358          if (not Is_Entity_Name (A)
2359              and then Nkind (A) /= N_Integer_Literal
2360              and then Nkind (A) /= N_Real_Literal)
2361
2362            or else Is_Scalar_Type (Etype (A))
2363          then
2364             Temp :=
2365               Make_Defining_Identifier (Loc,
2366                 Chars => New_Internal_Name ('C'));
2367
2368             --  If the actual for an in/in-out parameter is a view conversion,
2369             --  make it into an unchecked conversion, given that an untagged
2370             --  type conversion is not a proper object for a renaming.
2371             --  In-out conversions that involve real conversions have already
2372             --  been transformed in Expand_Actuals.
2373
2374             if Nkind (A) = N_Type_Conversion
2375               and then
2376                 (Ekind (F) = E_In_Out_Parameter
2377                   or else not Is_Tagged_Type (Etype (F)))
2378             then
2379                New_A := Make_Unchecked_Type_Conversion (Loc,
2380                  Subtype_Mark => New_Occurrence_Of (Etype (F), Loc),
2381                  Expression   => Relocate_Node (Expression (A)));
2382
2383             elsif Etype (F) /= Etype (A) then
2384                New_A := Unchecked_Convert_To (Etype (F), Relocate_Node (A));
2385                Temp_Typ := Etype (F);
2386
2387             else
2388                New_A := Relocate_Node (A);
2389             end if;
2390
2391             Set_Sloc (New_A, Sloc (N));
2392
2393             if Ekind (F) = E_In_Parameter
2394               and then not Is_Limited_Type (Etype (A))
2395             then
2396                Decl :=
2397                  Make_Object_Declaration (Loc,
2398                    Defining_Identifier => Temp,
2399                    Constant_Present => True,
2400                    Object_Definition => New_Occurrence_Of (Temp_Typ, Loc),
2401                    Expression => New_A);
2402             else
2403                Decl :=
2404                  Make_Object_Renaming_Declaration (Loc,
2405                    Defining_Identifier => Temp,
2406                    Subtype_Mark        => New_Occurrence_Of (Temp_Typ, Loc),
2407                    Name                => New_A);
2408             end if;
2409
2410             Prepend (Decl, Declarations (Blk));
2411             Set_Renamed_Object (F, Temp);
2412
2413          else
2414             if Etype (F) /= Etype (A) then
2415                Set_Renamed_Object
2416                 (F, Unchecked_Convert_To (Etype (F), Relocate_Node (A)));
2417             else
2418                Set_Renamed_Object (F, A);
2419             end if;
2420          end if;
2421
2422          Next_Formal (F);
2423          Next_Actual (A);
2424       end loop;
2425
2426       --  Establish target of function call. If context is not assignment or
2427       --  declaration, create a temporary as a target. The declaration for
2428       --  the temporary may be subsequently optimized away if the body is a
2429       --  single expression, or if the left-hand side of the assignment is
2430       --  simple enough.
2431
2432       if Ekind (Subp) = E_Function then
2433          if Nkind (Parent (N)) = N_Assignment_Statement
2434            and then Is_Entity_Name (Name (Parent (N)))
2435          then
2436             Targ := Name (Parent (N));
2437
2438          else
2439             --  Replace call with temporary, and create its declaration.
2440
2441             Temp :=
2442               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
2443
2444             Decl :=
2445               Make_Object_Declaration (Loc,
2446                 Defining_Identifier => Temp,
2447                 Object_Definition =>
2448                   New_Occurrence_Of (Ret_Type, Loc));
2449
2450             Set_No_Initialization (Decl);
2451             Insert_Action (N, Decl);
2452             Rewrite (N, New_Occurrence_Of (Temp, Loc));
2453             Targ := Temp;
2454          end if;
2455       end if;
2456
2457       --  Traverse the tree and replace  formals with actuals or their thunks.
2458       --  Attach block to tree before analysis and rewriting.
2459
2460       Replace_Formals (Blk);
2461       Set_Parent (Blk, N);
2462
2463       if Present (Exit_Lab) then
2464
2465          --  If the body was a single expression, the single return statement
2466          --  and the corresponding label are useless.
2467
2468          if Num_Ret = 1
2469            and then
2470              Nkind (Last (Statements (Handled_Statement_Sequence (Blk)))) =
2471                N_Goto_Statement
2472          then
2473             Remove (Last (Statements (Handled_Statement_Sequence (Blk))));
2474          else
2475             Append (Lab_Decl, (Declarations (Blk)));
2476             Append (Exit_Lab, Statements (Handled_Statement_Sequence (Blk)));
2477          end if;
2478       end if;
2479
2480       --  Analyze Blk with In_Inlined_Body set, to avoid spurious errors on
2481       --  conflicting private views that Gigi would ignore.
2482
2483       declare
2484          I_Flag : constant Boolean := In_Inlined_Body;
2485
2486       begin
2487          In_Inlined_Body := True;
2488          Analyze (Blk);
2489          In_Inlined_Body := I_Flag;
2490       end;
2491
2492       if Ekind (Subp) = E_Procedure then
2493          Rewrite_Procedure_Call (N, Blk);
2494       else
2495          Rewrite_Function_Call (N, Blk);
2496       end if;
2497
2498       Restore_Env;
2499
2500       --  Cleanup mapping between formals and actuals, for other expansions.
2501
2502       F := First_Formal (Subp);
2503
2504       while Present (F) loop
2505          Set_Renamed_Object (F, Empty);
2506          Next_Formal (F);
2507       end loop;
2508    end Expand_Inlined_Call;
2509
2510    ----------------------------
2511    -- Expand_N_Function_Call --
2512    ----------------------------
2513
2514    procedure Expand_N_Function_Call (N : Node_Id) is
2515       Typ : constant Entity_Id := Etype (N);
2516
2517       function Returned_By_Reference return Boolean;
2518       --  If the return type is returned through the secondary stack. i.e.
2519       --  by reference, we don't want to create a temporary to force stack
2520       --  checking.
2521
2522       function Returned_By_Reference return Boolean is
2523          S : Entity_Id := Current_Scope;
2524
2525       begin
2526          if Is_Return_By_Reference_Type (Typ) then
2527             return True;
2528
2529          elsif Nkind (Parent (N)) /= N_Return_Statement then
2530             return False;
2531
2532          elsif Requires_Transient_Scope (Typ) then
2533
2534             --  Verify that the return type of the enclosing function has
2535             --  the same constrained status as that of the expression.
2536
2537             while Ekind (S) /= E_Function loop
2538                S := Scope (S);
2539             end loop;
2540
2541             return Is_Constrained (Typ) = Is_Constrained (Etype (S));
2542          else
2543             return False;
2544          end if;
2545       end Returned_By_Reference;
2546
2547    --  Start of processing for Expand_N_Function_Call
2548
2549    begin
2550       --  A special check. If stack checking is enabled, and the return type
2551       --  might generate a large temporary, and the call is not the right
2552       --  side of an assignment, then generate an explicit temporary. We do
2553       --  this because otherwise gigi may generate a large temporary on the
2554       --  fly and this can cause trouble with stack checking.
2555
2556       if May_Generate_Large_Temp (Typ)
2557         and then Nkind (Parent (N)) /= N_Assignment_Statement
2558         and then
2559           (Nkind (Parent (N)) /= N_Object_Declaration
2560              or else Expression (Parent (N)) /= N)
2561         and then not Returned_By_Reference
2562       then
2563          --  Note: it might be thought that it would be OK to use a call to
2564          --  Force_Evaluation here, but that's not good enough, because that
2565          --  results in a 'Reference construct that may still need a temporary.
2566
2567          declare
2568             Loc      : constant Source_Ptr := Sloc (N);
2569             Temp_Obj : constant Entity_Id := Make_Defining_Identifier (Loc,
2570                                           New_Internal_Name ('F'));
2571             Temp_Typ : Entity_Id := Typ;
2572             Decl     : Node_Id;
2573             A        : Node_Id;
2574             F        : Entity_Id;
2575             Proc     : Entity_Id;
2576
2577          begin
2578             if Is_Tagged_Type (Typ)
2579               and then Present (Controlling_Argument (N))
2580             then
2581                if Nkind (Parent (N)) /= N_Procedure_Call_Statement
2582                  and then Nkind (Parent (N)) /= N_Function_Call
2583                then
2584                   --  If this is a tag-indeterminate call, the object must
2585                   --  be classwide.
2586
2587                   if Is_Tag_Indeterminate (N) then
2588                      Temp_Typ := Class_Wide_Type (Typ);
2589                   end if;
2590
2591                else
2592                   --  If this is a dispatching call that is itself the
2593                   --  controlling argument of an enclosing call, the nominal
2594                   --  subtype of the object that replaces it must be classwide,
2595                   --  so that dispatching will take place properly. If it is
2596                   --  not a controlling argument, the object is not classwide.
2597
2598                   Proc := Entity (Name (Parent (N)));
2599                   F    := First_Formal (Proc);
2600                   A    := First_Actual (Parent (N));
2601
2602                   while A /= N loop
2603                      Next_Formal (F);
2604                      Next_Actual (A);
2605                   end loop;
2606
2607                   if Is_Controlling_Formal (F) then
2608                      Temp_Typ := Class_Wide_Type (Typ);
2609                   end if;
2610                end if;
2611             end if;
2612
2613             Decl :=
2614               Make_Object_Declaration (Loc,
2615                 Defining_Identifier => Temp_Obj,
2616                 Object_Definition   => New_Occurrence_Of (Temp_Typ, Loc),
2617                 Constant_Present    => True,
2618                 Expression          => Relocate_Node (N));
2619             Set_Assignment_OK (Decl);
2620
2621             Insert_Actions (N, New_List (Decl));
2622             Rewrite (N, New_Occurrence_Of (Temp_Obj, Loc));
2623          end;
2624
2625       --  Normal case, expand the call
2626
2627       else
2628          Expand_Call (N);
2629       end if;
2630    end Expand_N_Function_Call;
2631
2632    ---------------------------------------
2633    -- Expand_N_Procedure_Call_Statement --
2634    ---------------------------------------
2635
2636    procedure Expand_N_Procedure_Call_Statement (N : Node_Id) is
2637    begin
2638       Expand_Call (N);
2639    end Expand_N_Procedure_Call_Statement;
2640
2641    ------------------------------
2642    -- Expand_N_Subprogram_Body --
2643    ------------------------------
2644
2645    --  Add poll call if ATC polling is enabled
2646
2647    --  Add return statement if last statement in body is not a return
2648    --  statement (this makes things easier on Gigi which does not want
2649    --  to have to handle a missing return).
2650
2651    --  Add call to Activate_Tasks if body is a task activator
2652
2653    --  Deal with possible detection of infinite recursion
2654
2655    --  Eliminate body completely if convention stubbed
2656
2657    --  Encode entity names within body, since we will not need to reference
2658    --  these entities any longer in the front end.
2659
2660    --  Initialize scalar out parameters if Initialize/Normalize_Scalars
2661
2662    procedure Expand_N_Subprogram_Body (N : Node_Id) is
2663       Loc      : constant Source_Ptr := Sloc (N);
2664       H        : constant Node_Id    := Handled_Statement_Sequence (N);
2665       Spec_Id  : Entity_Id;
2666       Except_H : Node_Id;
2667       Scop     : Entity_Id;
2668       Dec      : Node_Id;
2669       Next_Op  : Node_Id;
2670       L        : List_Id;
2671
2672       procedure Add_Return (S : List_Id);
2673       --  Append a return statement to the statement sequence S if the last
2674       --  statement is not already a return or a goto statement. Note that
2675       --  the latter test is not critical, it does not matter if we add a
2676       --  few extra returns, since they get eliminated anyway later on.
2677
2678       ----------------
2679       -- Add_Return --
2680       ----------------
2681
2682       procedure Add_Return (S : List_Id) is
2683          Last_S : constant Node_Id := Last (S);
2684          --  Get original node, in case raise has been rewritten
2685
2686       begin
2687          if not Is_Transfer (Last_S) then
2688             Append_To (S, Make_Return_Statement (Sloc (Last_S)));
2689          end if;
2690       end Add_Return;
2691
2692    --  Start of processing for Expand_N_Subprogram_Body
2693
2694    begin
2695       --  Set L to either the list of declarations if present, or
2696       --  to the list of statements if no declarations are present.
2697       --  This is used to insert new stuff at the start.
2698
2699       if Is_Non_Empty_List (Declarations (N)) then
2700          L := Declarations (N);
2701       else
2702          L := Statements (Handled_Statement_Sequence (N));
2703       end if;
2704
2705       --  Need poll on entry to subprogram if polling enabled. We only
2706       --  do this for non-empty subprograms, since it does not seem
2707       --  necessary to poll for a dummy null subprogram.
2708
2709       if Is_Non_Empty_List (L) then
2710          Generate_Poll_Call (First (L));
2711       end if;
2712
2713       --  Find entity for subprogram
2714
2715       if Present (Corresponding_Spec (N)) then
2716          Spec_Id := Corresponding_Spec (N);
2717       else
2718          Spec_Id := Defining_Entity (N);
2719       end if;
2720
2721       --  Initialize any scalar OUT args if Initialize/Normalize_Scalars
2722
2723       if Init_Or_Norm_Scalars and then Is_Subprogram (Spec_Id) then
2724          declare
2725             F : Entity_Id := First_Formal (Spec_Id);
2726             V : constant Boolean := Validity_Checks_On;
2727
2728          begin
2729             --  We turn off validity checking, since we do not want any
2730             --  check on the initializing value itself (which we know
2731             --  may well be invalid!)
2732
2733             Validity_Checks_On := False;
2734
2735             --  Loop through formals
2736
2737             while Present (F) loop
2738                if Is_Scalar_Type (Etype (F))
2739                  and then Ekind (F) = E_Out_Parameter
2740                then
2741                   Insert_Before_And_Analyze (First (L),
2742                     Make_Assignment_Statement (Loc,
2743                       Name => New_Occurrence_Of (F, Loc),
2744                       Expression => Get_Simple_Init_Val (Etype (F), Loc)));
2745                end if;
2746
2747                Next_Formal (F);
2748             end loop;
2749
2750             Validity_Checks_On := V;
2751          end;
2752       end if;
2753
2754       --  Clear out statement list for stubbed procedure
2755
2756       if Present (Corresponding_Spec (N)) then
2757          Set_Elaboration_Flag (N, Spec_Id);
2758
2759          if Convention (Spec_Id) = Convention_Stubbed
2760            or else Is_Eliminated (Spec_Id)
2761          then
2762             Set_Declarations (N, Empty_List);
2763             Set_Handled_Statement_Sequence (N,
2764               Make_Handled_Sequence_Of_Statements (Loc,
2765                 Statements => New_List (
2766                   Make_Null_Statement (Loc))));
2767             return;
2768          end if;
2769       end if;
2770
2771       Scop := Scope (Spec_Id);
2772
2773       --  Returns_By_Ref flag is normally set when the subprogram is frozen
2774       --  but subprograms with no specs are not frozen
2775
2776       declare
2777          Typ  : constant Entity_Id := Etype (Spec_Id);
2778          Utyp : constant Entity_Id := Underlying_Type (Typ);
2779
2780       begin
2781          if not Acts_As_Spec (N)
2782            and then Nkind (Parent (Parent (Spec_Id))) /=
2783              N_Subprogram_Body_Stub
2784          then
2785             null;
2786
2787          elsif Is_Return_By_Reference_Type (Typ) then
2788             Set_Returns_By_Ref (Spec_Id);
2789
2790          elsif Present (Utyp) and then Controlled_Type (Utyp) then
2791             Set_Returns_By_Ref (Spec_Id);
2792          end if;
2793       end;
2794
2795       --  For a procedure, we add a return for all possible syntactic ends
2796       --  of the subprogram. Note that reanalysis is not necessary in this
2797       --  case since it would require a lot of work and accomplish nothing.
2798
2799       if Ekind (Spec_Id) = E_Procedure
2800         or else Ekind (Spec_Id) = E_Generic_Procedure
2801       then
2802          Add_Return (Statements (H));
2803
2804          if Present (Exception_Handlers (H)) then
2805             Except_H := First_Non_Pragma (Exception_Handlers (H));
2806
2807             while Present (Except_H) loop
2808                Add_Return (Statements (Except_H));
2809                Next_Non_Pragma (Except_H);
2810             end loop;
2811          end if;
2812
2813       --  For a function, we must deal with the case where there is at
2814       --  least one missing return. What we do is to wrap the entire body
2815       --  of the function in a block:
2816
2817       --    begin
2818       --      ...
2819       --    end;
2820
2821       --  becomes
2822
2823       --    begin
2824       --       begin
2825       --          ...
2826       --       end;
2827
2828       --       raise Program_Error;
2829       --    end;
2830
2831       --  This approach is necessary because the raise must be signalled
2832       --  to the caller, not handled by any local handler (RM 6.4(11)).
2833
2834       --  Note: we do not need to analyze the constructed sequence here,
2835       --  since it has no handler, and an attempt to analyze the handled
2836       --  statement sequence twice is risky in various ways (e.g. the
2837       --  issue of expanding cleanup actions twice).
2838
2839       elsif Has_Missing_Return (Spec_Id) then
2840          declare
2841             Hloc : constant Source_Ptr := Sloc (H);
2842             Blok : constant Node_Id    :=
2843                      Make_Block_Statement (Hloc,
2844                        Handled_Statement_Sequence => H);
2845             Rais : constant Node_Id    :=
2846                      Make_Raise_Program_Error (Hloc);
2847
2848          begin
2849             Set_Handled_Statement_Sequence (N,
2850               Make_Handled_Sequence_Of_Statements (Hloc,
2851                 Statements => New_List (Blok, Rais)));
2852
2853             New_Scope (Spec_Id);
2854             Analyze (Blok);
2855             Analyze (Rais);
2856             Pop_Scope;
2857          end;
2858       end if;
2859
2860       --  Add discriminal renamings to protected subprograms.
2861       --  Install new discriminals for expansion of the next
2862       --  subprogram of this protected type, if any.
2863
2864       if Is_List_Member (N)
2865         and then Present (Parent (List_Containing (N)))
2866         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
2867       then
2868          Add_Discriminal_Declarations
2869            (Declarations (N), Scop, Name_uObject, Loc);
2870          Add_Private_Declarations (Declarations (N), Scop, Name_uObject, Loc);
2871
2872          --  Associate privals and discriminals with the next protected
2873          --  operation body to be expanded. These are used to expand
2874          --  references to private data objects and discriminants,
2875          --  respectively.
2876
2877          Next_Op := Next_Protected_Operation (N);
2878
2879          if Present (Next_Op) then
2880             Dec := Parent (Base_Type (Scop));
2881             Set_Privals (Dec, Next_Op, Loc);
2882             Set_Discriminals (Dec, Next_Op, Loc);
2883          end if;
2884
2885       end if;
2886
2887       --  If subprogram contains a parameterless recursive call, then we may
2888       --  have an infinite recursion, so see if we can generate code to check
2889       --  for this possibility if storage checks are not suppressed.
2890
2891       if Ekind (Spec_Id) = E_Procedure
2892         and then Has_Recursive_Call (Spec_Id)
2893         and then not Storage_Checks_Suppressed (Spec_Id)
2894       then
2895          Detect_Infinite_Recursion (N, Spec_Id);
2896       end if;
2897
2898       --  Finally, if we are in Normalize_Scalars mode, then any scalar out
2899       --  parameters must be initialized to the appropriate default value.
2900
2901       if Ekind (Spec_Id) = E_Procedure and then Normalize_Scalars then
2902          declare
2903             Floc   : Source_Ptr;
2904             Formal : Entity_Id;
2905             Stm    : Node_Id;
2906
2907          begin
2908             Formal := First_Formal (Spec_Id);
2909
2910             while Present (Formal) loop
2911                Floc := Sloc (Formal);
2912
2913                if Ekind (Formal) = E_Out_Parameter
2914                  and then Is_Scalar_Type (Etype (Formal))
2915                then
2916                   Stm :=
2917                     Make_Assignment_Statement (Floc,
2918                       Name => New_Occurrence_Of (Formal, Floc),
2919                       Expression =>
2920                         Get_Simple_Init_Val (Etype (Formal), Floc));
2921                   Prepend (Stm, Declarations (N));
2922                   Analyze (Stm);
2923                end if;
2924
2925                Next_Formal (Formal);
2926             end loop;
2927          end;
2928       end if;
2929
2930       --  If the subprogram does not have pending instantiations, then we
2931       --  must generate the subprogram descriptor now, since the code for
2932       --  the subprogram is complete, and this is our last chance. However
2933       --  if there are pending instantiations, then the code is not
2934       --  complete, and we will delay the generation.
2935
2936       if Is_Subprogram (Spec_Id)
2937         and then not Delay_Subprogram_Descriptors (Spec_Id)
2938       then
2939          Generate_Subprogram_Descriptor_For_Subprogram (N, Spec_Id);
2940       end if;
2941
2942       --  Set to encode entity names in package body before gigi is called
2943
2944       Qualify_Entity_Names (N);
2945    end Expand_N_Subprogram_Body;
2946
2947    -----------------------------------
2948    -- Expand_N_Subprogram_Body_Stub --
2949    -----------------------------------
2950
2951    procedure Expand_N_Subprogram_Body_Stub (N : Node_Id) is
2952    begin
2953       if Present (Corresponding_Body (N)) then
2954          Expand_N_Subprogram_Body (
2955            Unit_Declaration_Node (Corresponding_Body (N)));
2956       end if;
2957
2958    end Expand_N_Subprogram_Body_Stub;
2959
2960    -------------------------------------
2961    -- Expand_N_Subprogram_Declaration --
2962    -------------------------------------
2963
2964    --  The first task to be performed is the construction of default
2965    --  expression functions for in parameters with default values. These
2966    --  are parameterless inlined functions that are used to evaluate
2967    --  default expressions that are more complicated than simple literals
2968    --  or identifiers referencing constants and variables.
2969
2970    --  If the declaration appears within a protected body, it is a private
2971    --  operation of the protected type. We must create the corresponding
2972    --  protected subprogram an associated formals. For a normal protected
2973    --  operation, this is done when expanding the protected type declaration.
2974
2975    procedure Expand_N_Subprogram_Declaration (N : Node_Id) is
2976       Loc      : constant Source_Ptr := Sloc (N);
2977       Subp     : Entity_Id := Defining_Entity (N);
2978       Scop     : Entity_Id := Scope (Subp);
2979       Prot_Sub : Entity_Id;
2980       Prot_Bod : Node_Id;
2981
2982    begin
2983       --  Deal with case of protected subprogram
2984
2985       if Is_List_Member (N)
2986         and then Present (Parent (List_Containing (N)))
2987         and then Nkind (Parent (List_Containing (N))) = N_Protected_Body
2988         and then Is_Protected_Type (Scop)
2989       then
2990          if No (Protected_Body_Subprogram (Subp)) then
2991             Prot_Sub :=
2992               Make_Subprogram_Declaration (Loc,
2993                 Specification =>
2994                   Build_Protected_Sub_Specification
2995                     (N, Scop, Unprotected => True));
2996
2997             --  The protected subprogram is declared outside of the protected
2998             --  body. Given that the body has frozen all entities so far, we
2999             --  freeze the subprogram explicitly. If the body is a subunit,
3000             --  the insertion point is before the stub in the parent.
3001
3002             Prot_Bod := Parent (List_Containing (N));
3003
3004             if Nkind (Parent (Prot_Bod)) = N_Subunit then
3005                Prot_Bod := Corresponding_Stub (Parent (Prot_Bod));
3006             end if;
3007
3008             Insert_Before (Prot_Bod, Prot_Sub);
3009
3010             New_Scope (Scope (Scop));
3011             Analyze (Prot_Sub);
3012             Set_Protected_Body_Subprogram (Subp,
3013               Defining_Unit_Name (Specification (Prot_Sub)));
3014             Pop_Scope;
3015          end if;
3016       end if;
3017    end Expand_N_Subprogram_Declaration;
3018
3019    ---------------------------------------
3020    -- Expand_Protected_Object_Reference --
3021    ---------------------------------------
3022
3023    function Expand_Protected_Object_Reference
3024      (N    : Node_Id;
3025       Scop : Entity_Id)
3026      return Node_Id
3027    is
3028       Loc   : constant Source_Ptr := Sloc (N);
3029       Corr  : Entity_Id;
3030       Rec   : Node_Id;
3031       Param : Entity_Id;
3032       Proc  : Entity_Id;
3033
3034    begin
3035       Rec := Make_Identifier (Loc, Name_uObject);
3036       Set_Etype (Rec, Corresponding_Record_Type (Scop));
3037
3038       --  Find enclosing protected operation, and retrieve its first
3039       --  parameter, which denotes the enclosing protected object.
3040       --  If the enclosing operation is an entry, we are immediately
3041       --  within the protected body, and we can retrieve the object
3042       --  from the service entries procedure. A barrier function has
3043       --  has the same signature as an entry. A barrier function is
3044       --  compiled within the protected object, but unlike protected
3045       --  operations its never needs locks, so that its protected body
3046       --  subprogram points to itself.
3047
3048       Proc := Current_Scope;
3049
3050       while Present (Proc)
3051         and then Scope (Proc) /= Scop
3052       loop
3053          Proc := Scope (Proc);
3054       end loop;
3055
3056       Corr := Protected_Body_Subprogram (Proc);
3057
3058       if No (Corr) then
3059
3060          --  Previous error left expansion incomplete.
3061          --  Nothing to do on this call.
3062
3063          return Empty;
3064       end if;
3065
3066       Param :=
3067         Defining_Identifier
3068           (First (Parameter_Specifications (Parent (Corr))));
3069
3070       if Is_Subprogram (Proc)
3071         and then Proc /= Corr
3072       then
3073          --  Protected function or procedure.
3074
3075          Set_Entity (Rec, Param);
3076
3077          --  Rec is a reference to an entity which will not be in scope
3078          --  when the call is reanalyzed, and needs no further analysis.
3079
3080          Set_Analyzed (Rec);
3081
3082       else
3083          --  Entry or barrier function for entry body.
3084          --  The first parameter of the entry body procedure is a
3085          --  pointer to the object. We create a local variable
3086          --  of the proper type, duplicating what is done to define
3087          --  _object later on.
3088
3089          declare
3090             Decls : List_Id;
3091             Obj_Ptr : Entity_Id :=  Make_Defining_Identifier
3092                                       (Loc, New_Internal_Name ('T'));
3093          begin
3094             Decls := New_List (
3095               Make_Full_Type_Declaration (Loc,
3096                 Defining_Identifier => Obj_Ptr,
3097                   Type_Definition =>
3098                      Make_Access_To_Object_Definition (Loc,
3099                        Subtype_Indication =>
3100                          New_Reference_To
3101                       (Corresponding_Record_Type (Scop), Loc))));
3102
3103             Insert_Actions (N, Decls);
3104             Insert_Actions (N, Freeze_Entity (Obj_Ptr, Sloc (N)));
3105
3106             Rec :=
3107               Make_Explicit_Dereference (Loc,
3108                 Unchecked_Convert_To (Obj_Ptr,
3109                   New_Occurrence_Of (Param, Loc)));
3110
3111             --  Analyze new actual. Other actuals in calls are already
3112             --  analyzed and the list of actuals is not renalyzed after
3113             --  rewriting.
3114
3115             Set_Parent (Rec, N);
3116             Analyze (Rec);
3117          end;
3118       end if;
3119
3120       return Rec;
3121    end Expand_Protected_Object_Reference;
3122
3123    --------------------------------------
3124    -- Expand_Protected_Subprogram_Call --
3125    --------------------------------------
3126
3127    procedure Expand_Protected_Subprogram_Call
3128      (N    : Node_Id;
3129       Subp : Entity_Id;
3130       Scop : Entity_Id)
3131    is
3132       Rec   : Node_Id;
3133
3134    begin
3135       --  If the protected object is not an enclosing scope, this is
3136       --  an inter-object function call. Inter-object procedure
3137       --  calls are expanded by Exp_Ch9.Build_Simple_Entry_Call.
3138       --  The call is intra-object only if the subprogram being
3139       --  called is in the protected body being compiled, and if the
3140       --  protected object in the call is statically the enclosing type.
3141       --  The object may be an component of some other data structure,
3142       --  in which case this must be handled as an inter-object call.
3143
3144       if not In_Open_Scopes (Scop)
3145         or else not Is_Entity_Name (Name (N))
3146       then
3147          if Nkind (Name (N)) = N_Selected_Component then
3148             Rec := Prefix (Name (N));
3149
3150          else
3151             pragma Assert (Nkind (Name (N)) = N_Indexed_Component);
3152             Rec := Prefix (Prefix (Name (N)));
3153          end if;
3154
3155          Build_Protected_Subprogram_Call (N,
3156            Name => New_Occurrence_Of (Subp, Sloc (N)),
3157            Rec =>  Convert_Concurrent (Rec, Etype (Rec)),
3158            External => True);
3159
3160       else
3161          Rec := Expand_Protected_Object_Reference (N, Scop);
3162
3163          if No (Rec) then
3164             return;
3165          end if;
3166
3167          Build_Protected_Subprogram_Call (N,
3168            Name     => Name (N),
3169            Rec      => Rec,
3170            External => False);
3171
3172       end if;
3173
3174       Analyze (N);
3175
3176       --  If it is a function call it can appear in elaboration code and
3177       --  the called entity must be frozen here.
3178
3179       if Ekind (Subp) = E_Function then
3180          Freeze_Expression (Name (N));
3181       end if;
3182    end Expand_Protected_Subprogram_Call;
3183
3184    -----------------------
3185    -- Freeze_Subprogram --
3186    -----------------------
3187
3188    procedure Freeze_Subprogram (N : Node_Id) is
3189       E : constant Entity_Id := Entity (N);
3190
3191    begin
3192       --  When a primitive is frozen, enter its name in the corresponding
3193       --  dispatch table. If the DTC_Entity field is not set this is an
3194       --  overridden primitive that can be ignored. We suppress the
3195       --  initialization of the dispatch table entry when Java_VM because
3196       --  the dispatching mechanism is handled internally by the JVM.
3197
3198       if Is_Dispatching_Operation (E)
3199         and then not Is_Abstract (E)
3200         and then Present (DTC_Entity (E))
3201         and then not Is_CPP_Class (Scope (DTC_Entity (E)))
3202         and then not Java_VM
3203       then
3204          Check_Overriding_Operation (E);
3205          Insert_After (N, Fill_DT_Entry (Sloc (N), E));
3206       end if;
3207
3208       --  Mark functions that return by reference. Note that it cannot be
3209       --  part of the normal semantic analysis of the spec since the
3210       --  underlying returned type may not be known yet (for private types)
3211
3212       declare
3213          Typ  : constant Entity_Id := Etype (E);
3214          Utyp : constant Entity_Id := Underlying_Type (Typ);
3215
3216       begin
3217          if Is_Return_By_Reference_Type (Typ) then
3218             Set_Returns_By_Ref (E);
3219
3220          elsif Present (Utyp) and then Controlled_Type (Utyp) then
3221             Set_Returns_By_Ref (E);
3222          end if;
3223       end;
3224
3225    end Freeze_Subprogram;
3226
3227 end Exp_Ch6;