OSDN Git Service

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