OSDN Git Service

* sysdep.c: Problem discovered during IA64 VMS port.
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch7.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 7                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2003, 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 --  This package contains virtually all expansion mechanisms related to
28 --    - controlled types
29 --    - transient scopes
30
31 with Atree;    use Atree;
32 with Debug;    use Debug;
33 with Einfo;    use Einfo;
34 with Errout;   use Errout;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Ch11; use Exp_Ch11;
37 with Exp_Dbug; use Exp_Dbug;
38 with Exp_Tss;  use Exp_Tss;
39 with Exp_Util; use Exp_Util;
40 with Fname;    use Fname;
41 with Freeze;   use Freeze;
42 with Hostparm; use Hostparm;
43 with Lib;      use Lib;
44 with Nlists;   use Nlists;
45 with Nmake;    use Nmake;
46 with Opt;      use Opt;
47 with Output;   use Output;
48 with Restrict; use Restrict;
49 with Rtsfind;  use Rtsfind;
50 with Targparm; use Targparm;
51 with Sinfo;    use Sinfo;
52 with Sem;      use Sem;
53 with Sem_Ch3;  use Sem_Ch3;
54 with Sem_Ch7;  use Sem_Ch7;
55 with Sem_Ch8;  use Sem_Ch8;
56 with Sem_Res;  use Sem_Res;
57 with Sem_Type; use Sem_Type;
58 with Sem_Util; use Sem_Util;
59 with Snames;   use Snames;
60 with Stand;    use Stand;
61 with Tbuild;   use Tbuild;
62 with Uintp;    use Uintp;
63
64 package body Exp_Ch7 is
65
66    --------------------------------
67    -- Transient Scope Management --
68    --------------------------------
69
70    --  A transient scope is created when temporary objects are created by the
71    --  compiler. These temporary objects are allocated on the secondary stack
72    --  and the transient scope is responsible for finalizing the object when
73    --  appropriate and reclaiming the memory at the right time. The temporary
74    --  objects are generally the objects allocated to store the result of a
75    --  function returning an unconstrained or a tagged value. Expressions
76    --  needing to be wrapped in a transient scope (functions calls returning
77    --  unconstrained or tagged values) may appear in 3 different contexts which
78    --  lead to 3 different kinds of transient scope expansion:
79
80    --   1. In a simple statement (procedure call, assignment, ...). In
81    --      this case the instruction is wrapped into a transient block.
82    --      (See Wrap_Transient_Statement for details)
83
84    --   2. In an expression of a control structure (test in a IF statement,
85    --      expression in a CASE statement, ...).
86    --      (See Wrap_Transient_Expression for details)
87
88    --   3. In a expression of an object_declaration. No wrapping is possible
89    --      here, so the finalization actions, if any are done right after the
90    --      declaration and the secondary stack deallocation is done in the
91    --      proper enclosing scope (see Wrap_Transient_Declaration for details)
92
93    --  Note about function returning tagged types: It has been decided to
94    --  always allocate their result in the secondary stack while it is not
95    --  absolutely mandatory when the tagged type is constrained because the
96    --  caller knows the size of the returned object and thus could allocate the
97    --  result in the primary stack. But, allocating them always in the
98    --  secondary stack simplifies many implementation hassles:
99
100    --    - If it is dispatching function call, the computation of the size of
101    --      the result is possible but complex from the outside.
102
103    --    - If the returned type is controlled, the assignment of the returned
104    --      value to the anonymous object involves an Adjust, and we have no
105    --      easy way to access the anonymous object created by the back-end
106
107    --    - If the returned type is class-wide, this is an unconstrained type
108    --      anyway
109
110    --  Furthermore, the little loss in efficiency which is the result of this
111    --  decision is not such a big deal because function returning tagged types
112    --  are not very much used in real life as opposed to functions returning
113    --  access to a tagged type
114
115    --------------------------------------------------
116    -- Transient Blocks and Finalization Management --
117    --------------------------------------------------
118
119    function Find_Node_To_Be_Wrapped (N : Node_Id) return Node_Id;
120    --  N is a node wich may generate a transient scope. Loop over the
121    --  parent pointers of N until it find the appropriate node to
122    --  wrap. It it returns Empty, it means that no transient scope is
123    --  needed in this context.
124
125    function Make_Clean
126      (N                          : Node_Id;
127       Clean                      : Entity_Id;
128       Mark                       : Entity_Id;
129       Flist                      : Entity_Id;
130       Is_Task                    : Boolean;
131       Is_Master                  : Boolean;
132       Is_Protected_Subprogram    : Boolean;
133       Is_Task_Allocation_Block   : Boolean;
134       Is_Asynchronous_Call_Block : Boolean)
135       return      Node_Id;
136    --  Expand a the clean-up procedure for controlled and/or transient
137    --  block, and/or task master or task body, or blocks used to
138    --  implement task allocation or asynchronous entry calls, or
139    --  procedures used to implement protected procedures. Clean is the
140    --  entity for such a procedure. Mark is the entity for the secondary
141    --  stack mark, if empty only controlled block clean-up will be
142    --  performed. Flist is the entity for the local final list, if empty
143    --  only transient scope clean-up will be performed. The flags
144    --  Is_Task and Is_Master control the calls to the corresponding
145    --  finalization actions for a task body or for an entity that is a
146    --  task master.
147
148    procedure Set_Node_To_Be_Wrapped (N : Node_Id);
149    --  Set the field Node_To_Be_Wrapped of the current scope
150
151    procedure Insert_Actions_In_Scope_Around (N : Node_Id);
152    --  Insert the before-actions kept in the scope stack before N, and the
153    --  after after-actions, after N which must be a member of a list.
154
155    function Make_Transient_Block
156      (Loc    : Source_Ptr;
157       Action : Node_Id)
158       return   Node_Id;
159    --  Create a transient block whose name is Scope, which is also a
160    --  controlled block if Flist is not empty and whose only code is
161    --  Action (either a single statement or single declaration).
162
163    type Final_Primitives is (Initialize_Case, Adjust_Case, Finalize_Case);
164    --  This enumeration type is defined in order to ease sharing code for
165    --  building finalization procedures for composite types.
166
167    Name_Of      : constant array (Final_Primitives) of Name_Id :=
168                     (Initialize_Case => Name_Initialize,
169                      Adjust_Case     => Name_Adjust,
170                      Finalize_Case   => Name_Finalize);
171
172    Deep_Name_Of : constant array (Final_Primitives) of TSS_Name_Type :=
173                     (Initialize_Case => TSS_Deep_Initialize,
174                      Adjust_Case     => TSS_Deep_Adjust,
175                      Finalize_Case   => TSS_Deep_Finalize);
176
177    procedure Build_Record_Deep_Procs (Typ : Entity_Id);
178    --  Build the deep Initialize/Adjust/Finalize for a record Typ with
179    --  Has_Component_Component set and store them using the TSS mechanism.
180
181    procedure Build_Array_Deep_Procs (Typ : Entity_Id);
182    --  Build the deep Initialize/Adjust/Finalize for a record Typ with
183    --  Has_Controlled_Component set and store them using the TSS mechanism.
184
185    function Make_Deep_Proc
186      (Prim  : Final_Primitives;
187       Typ   : Entity_Id;
188       Stmts : List_Id)
189       return  Node_Id;
190    --  This function generates the tree for Deep_Initialize, Deep_Adjust
191    --  or Deep_Finalize procedures according to the first parameter,
192    --  these procedures operate on the type Typ. The Stmts parameter
193    --  gives the body of the procedure.
194
195    function Make_Deep_Array_Body
196      (Prim : Final_Primitives;
197       Typ  : Entity_Id)
198       return List_Id;
199    --  This function generates the list of statements for implementing
200    --  Deep_Initialize, Deep_Adjust or Deep_Finalize procedures
201    --  according to the first parameter, these procedures operate on the
202    --  array type Typ.
203
204    function Make_Deep_Record_Body
205      (Prim : Final_Primitives;
206       Typ  : Entity_Id)
207       return List_Id;
208    --  This function generates the list of statements for implementing
209    --  Deep_Initialize, Deep_Adjust or Deep_Finalize procedures
210    --  according to the first parameter, these procedures operate on the
211    --  record type Typ.
212
213    procedure Check_Visibly_Controlled
214      (Prim : Final_Primitives;
215       Typ  : Entity_Id;
216       E    : in out Entity_Id;
217       Cref : in out Node_Id);
218    --  The controlled operation declared for a derived type may not be
219    --  overriding, if the controlled operations of the parent type are
220    --  hidden, for example when the parent is a private type whose full
221    --  view is controlled. For other primitive operations we modify the
222    --  name of the operation to indicate that it is not overriding, but
223    --  this is not possible for Initialize, etc. because they have to be
224    --  retrievable by name. Before generating the proper call to one of
225    --  these operations we check whether Typ is known to be controlled at
226    --  the point of definition. If it is not then we must retrieve the
227    --  hidden operation of the parent and use it instead.  This is one
228    --  case that might be solved more cleanly once Overriding pragmas or
229    --  declarations are in place.
230
231    function Convert_View
232      (Proc : Entity_Id;
233       Arg  : Node_Id;
234       Ind  : Pos := 1)
235       return Node_Id;
236    --  Proc is one of the Initialize/Adjust/Finalize operations, and
237    --  Arg is the argument being passed to it. Ind indicates which
238    --  formal of procedure Proc we are trying to match. This function
239    --  will, if necessary, generate an conversion between the partial
240    --  and full view of Arg to match the type of the formal of Proc,
241    --  or force a conversion to the class-wide type in the case where
242    --  the operation is abstract.
243
244    -----------------------------
245    -- Finalization Management --
246    -----------------------------
247
248    --  This part describe how Initialization/Adjusment/Finalization procedures
249    --  are generated and called. Two cases must be considered, types that are
250    --  Controlled (Is_Controlled flag set) and composite types that contain
251    --  controlled components (Has_Controlled_Component flag set). In the first
252    --  case the procedures to call are the user-defined primitive operations
253    --  Initialize/Adjust/Finalize. In the second case, GNAT generates
254    --  Deep_Initialize, Deep_Adjust and Deep_Finalize that are in charge of
255    --  calling the former procedures on the controlled components.
256
257    --  For records with Has_Controlled_Component set, a hidden "controller"
258    --  component is inserted. This controller component contains its own
259    --  finalization list on which all controlled components are attached
260    --  creating an indirection on the upper-level Finalization list. This
261    --  technique facilitates the management of objects whose number of
262    --  controlled components changes during execution. This controller
263    --  component is itself controlled and is attached to the upper-level
264    --  finalization chain. Its adjust primitive is in charge of calling
265    --  adjust on the components and adusting the finalization pointer to
266    --  match their new location (see a-finali.adb).
267
268    --  It is not possible to use a similar technique for arrays that have
269    --  Has_Controlled_Component set. In this case, deep procedures are
270    --  generated that call initialize/adjust/finalize + attachment or
271    --  detachment on the finalization list for all component.
272
273    --  Initialize calls: they are generated for declarations or dynamic
274    --  allocations of Controlled objects with no initial value. They are
275    --  always followed by an attachment to the current Finalization
276    --  Chain. For the dynamic allocation case this the chain attached to
277    --  the scope of the access type definition otherwise, this is the chain
278    --  of the current scope.
279
280    --  Adjust Calls: They are generated on 2 occasions: (1) for
281    --  declarations or dynamic allocations of Controlled objects with an
282    --  initial value. (2) after an assignment. In the first case they are
283    --  followed by an attachment to the final chain, in the second case
284    --  they are not.
285
286    --  Finalization Calls: They are generated on (1) scope exit, (2)
287    --  assignments, (3) unchecked deallocations. In case (3) they have to
288    --  be detached from the final chain, in case (2) they must not and in
289    --  case (1) this is not important since we are exiting the scope
290    --  anyway.
291
292    --  Other details:
293    --    - Type extensions will have a new record controller at each derivation
294    --      level containing controlled components.
295    --    - For types that are both Is_Controlled and Has_Controlled_Components,
296    --      the record controller and the object itself are handled separately.
297    --      It could seem simpler to attach the object at the end of its record
298    --      controller but this would not tackle view conversions properly.
299    --    - A classwide type can always potentially have controlled components
300    --      but the record controller of the corresponding actual type may not
301    --      be nown at compile time so the dispatch table contains a special
302    --      field that allows to compute the offset of the record controller
303    --      dynamically. See s-finimp.Deep_Tag_Attach and a-tags.RC_Offset
304
305    --  Here is a simple example of the expansion of a controlled block :
306
307    --    declare
308    --       X : Controlled ;
309    --       Y : Controlled := Init;
310    --
311    --       type R is record
312    --          C : Controlled;
313    --       end record;
314    --       W : R;
315    --       Z : R := (C => X);
316    --    begin
317    --       X := Y;
318    --       W := Z;
319    --    end;
320    --
321    --  is expanded into
322    --
323    --    declare
324    --       _L : System.FI.Finalizable_Ptr;
325
326    --       procedure _Clean is
327    --       begin
328    --          Abort_Defer;
329    --          System.FI.Finalize_List (_L);
330    --          Abort_Undefer;
331    --       end _Clean;
332
333    --       X : Controlled;
334    --       begin
335    --          Abort_Defer;
336    --          Initialize (X);
337    --          Attach_To_Final_List (_L, Finalizable (X), 1);
338    --       at end: Abort_Undefer;
339    --       Y : Controlled := Init;
340    --       Adjust (Y);
341    --       Attach_To_Final_List (_L, Finalizable (Y), 1);
342    --
343    --       type R is record
344    --         _C : Record_Controller;
345    --          C : Controlled;
346    --       end record;
347    --       W : R;
348    --       begin
349    --          Abort_Defer;
350    --          Deep_Initialize (W, _L, 1);
351    --       at end: Abort_Under;
352    --       Z : R := (C => X);
353    --       Deep_Adjust (Z, _L, 1);
354
355    --    begin
356    --       _Assign (X, Y);
357    --       Deep_Finalize (W, False);
358    --       <save W's final pointers>
359    --       W := Z;
360    --       <restore W's final pointers>
361    --       Deep_Adjust (W, _L, 0);
362    --    at end
363    --       _Clean;
364    --    end;
365
366    function Global_Flist_Ref (Flist_Ref : Node_Id) return Boolean;
367    --  Return True if Flist_Ref refers to a global final list, either
368    --  the object GLobal_Final_List which is used to attach standalone
369    --  objects, or any of the list controllers associated with library
370    --  level access to controlled objects
371
372    procedure Clean_Simple_Protected_Objects (N : Node_Id);
373    --  Protected objects without entries are not controlled types, and the
374    --  locks have to be released explicitly when such an object goes out
375    --  of scope. Traverse declarations in scope to determine whether such
376    --  objects are present.
377
378    ----------------------------
379    -- Build_Array_Deep_Procs --
380    ----------------------------
381
382    procedure Build_Array_Deep_Procs (Typ : Entity_Id) is
383    begin
384       Set_TSS (Typ,
385         Make_Deep_Proc (
386           Prim  => Initialize_Case,
387           Typ   => Typ,
388           Stmts => Make_Deep_Array_Body (Initialize_Case, Typ)));
389
390       if not Is_Return_By_Reference_Type (Typ) then
391          Set_TSS (Typ,
392            Make_Deep_Proc (
393              Prim  => Adjust_Case,
394              Typ   => Typ,
395              Stmts => Make_Deep_Array_Body (Adjust_Case, Typ)));
396       end if;
397
398       Set_TSS (Typ,
399         Make_Deep_Proc (
400           Prim  => Finalize_Case,
401           Typ   => Typ,
402           Stmts => Make_Deep_Array_Body (Finalize_Case, Typ)));
403    end Build_Array_Deep_Procs;
404
405    -----------------------------
406    -- Build_Controlling_Procs --
407    -----------------------------
408
409    procedure Build_Controlling_Procs (Typ : Entity_Id) is
410    begin
411       if Is_Array_Type (Typ) then
412          Build_Array_Deep_Procs (Typ);
413
414       else pragma Assert (Is_Record_Type (Typ));
415          Build_Record_Deep_Procs (Typ);
416       end if;
417    end Build_Controlling_Procs;
418
419    ----------------------
420    -- Build_Final_List --
421    ----------------------
422
423    procedure Build_Final_List (N : Node_Id; Typ : Entity_Id) is
424       Loc  : constant Source_Ptr := Sloc (N);
425       Decl : Node_Id;
426
427    begin
428       Set_Associated_Final_Chain (Typ,
429         Make_Defining_Identifier (Loc,
430           New_External_Name (Chars (Typ), 'L')));
431
432       Decl :=
433         Make_Object_Declaration (Loc,
434           Defining_Identifier =>
435              Associated_Final_Chain (Typ),
436           Object_Definition   =>
437             New_Reference_To
438               (RTE (RE_List_Controller), Loc));
439
440       --  The type may have been frozen already, and this is a late freezing
441       --  action, in which case the declaration must be elaborated at once.
442       --  If the call is for an allocator, the chain must also be created now,
443       --  because the freezing of the type does not build one. Otherwise, the
444       --  declaration is one of the freezing actions for a user-defined type.
445
446       if Is_Frozen (Typ)
447         or else (Nkind (N) = N_Allocator
448                   and then Ekind (Etype (N)) = E_Anonymous_Access_Type)
449       then
450          Insert_Action (N, Decl);
451       else
452          Append_Freeze_Action (Typ, Decl);
453       end if;
454    end Build_Final_List;
455
456    ---------------------
457    -- Build_Late_Proc --
458    ---------------------
459
460    procedure Build_Late_Proc (Typ : Entity_Id; Nam : Name_Id) is
461    begin
462       for Final_Prim in Name_Of'Range loop
463          if Name_Of (Final_Prim) = Nam then
464             Set_TSS (Typ,
465               Make_Deep_Proc (
466                 Prim  => Final_Prim,
467                 Typ   => Typ,
468                 Stmts => Make_Deep_Record_Body (Final_Prim, Typ)));
469          end if;
470       end loop;
471    end Build_Late_Proc;
472
473    -----------------------------
474    -- Build_Record_Deep_Procs --
475    -----------------------------
476
477    procedure Build_Record_Deep_Procs (Typ : Entity_Id) is
478    begin
479       Set_TSS (Typ,
480         Make_Deep_Proc (
481           Prim  => Initialize_Case,
482           Typ   => Typ,
483           Stmts => Make_Deep_Record_Body (Initialize_Case, Typ)));
484
485       if not Is_Return_By_Reference_Type (Typ) then
486          Set_TSS (Typ,
487            Make_Deep_Proc (
488              Prim  => Adjust_Case,
489              Typ   => Typ,
490              Stmts => Make_Deep_Record_Body (Adjust_Case, Typ)));
491       end if;
492
493       Set_TSS (Typ,
494         Make_Deep_Proc (
495           Prim  => Finalize_Case,
496           Typ   => Typ,
497           Stmts => Make_Deep_Record_Body (Finalize_Case, Typ)));
498    end Build_Record_Deep_Procs;
499
500    -------------------
501    -- Cleanup_Array --
502    -------------------
503
504    function Cleanup_Array
505      (N    : Node_Id;
506       Obj  : Node_Id;
507       Typ  : Entity_Id)
508       return List_Id
509    is
510       Loc        : constant Source_Ptr := Sloc (N);
511       Index_List : List_Id := New_List;
512
513       function Free_Component return List_Id;
514       --  Generate the code to finalize the task or protected  subcomponents
515       --  of a single component of the array.
516
517       function Free_One_Dimension (Dim : Int) return List_Id;
518       --  Generate a loop over one dimension of the array.
519
520       --------------------
521       -- Free_Component --
522       --------------------
523
524       function Free_Component return List_Id is
525          Stmts : List_Id := New_List;
526          Tsk   : Node_Id;
527          C_Typ : Entity_Id := Component_Type (Typ);
528
529       begin
530          --  Component type is known to contain tasks or protected objects
531
532          Tsk :=
533            Make_Indexed_Component (Loc,
534              Prefix        => Duplicate_Subexpr_No_Checks (Obj),
535              Expressions   => Index_List);
536
537          Set_Etype (Tsk, C_Typ);
538
539          if Is_Task_Type (C_Typ) then
540             Append_To (Stmts, Cleanup_Task (N, Tsk));
541
542          elsif Is_Simple_Protected_Type (C_Typ) then
543             Append_To (Stmts, Cleanup_Protected_Object (N, Tsk));
544
545          elsif Is_Record_Type (C_Typ) then
546             Stmts := Cleanup_Record (N, Tsk, C_Typ);
547
548          elsif Is_Array_Type (C_Typ) then
549             Stmts := Cleanup_Array (N, Tsk, C_Typ);
550          end if;
551
552          return Stmts;
553       end Free_Component;
554
555       ------------------------
556       -- Free_One_Dimension --
557       ------------------------
558
559       function Free_One_Dimension (Dim : Int) return List_Id is
560          Index      : Entity_Id;
561
562       begin
563          if Dim > Number_Dimensions (Typ) then
564             return Free_Component;
565
566          --  Here we generate the required loop
567
568          else
569             Index :=
570               Make_Defining_Identifier (Loc, New_Internal_Name ('J'));
571
572             Append (New_Reference_To (Index, Loc), Index_List);
573
574             return New_List (
575               Make_Implicit_Loop_Statement (N,
576                 Identifier => Empty,
577                 Iteration_Scheme =>
578                   Make_Iteration_Scheme (Loc,
579                     Loop_Parameter_Specification =>
580                       Make_Loop_Parameter_Specification (Loc,
581                         Defining_Identifier => Index,
582                         Discrete_Subtype_Definition =>
583                           Make_Attribute_Reference (Loc,
584                             Prefix => Duplicate_Subexpr (Obj),
585                             Attribute_Name  => Name_Range,
586                             Expressions => New_List (
587                               Make_Integer_Literal (Loc, Dim))))),
588                 Statements =>  Free_One_Dimension (Dim + 1)));
589          end if;
590       end Free_One_Dimension;
591
592    --  Start of processing for Cleanup_Array
593
594    begin
595       return Free_One_Dimension (1);
596    end Cleanup_Array;
597
598    --------------------
599    -- Cleanup_Record --
600    --------------------
601
602    function Cleanup_Record
603      (N    : Node_Id;
604       Obj  : Node_Id;
605       Typ  : Entity_Id)
606       return List_Id
607    is
608       Loc   : constant Source_Ptr := Sloc (N);
609       Tsk   : Node_Id;
610       Comp  : Entity_Id;
611       Stmts : List_Id := New_List;
612       U_Typ : constant Entity_Id := Underlying_Type (Typ);
613
614    begin
615       if Has_Discriminants (U_Typ)
616         and then Nkind (Parent (U_Typ)) = N_Full_Type_Declaration
617         and then
618           Nkind (Type_Definition (Parent (U_Typ))) = N_Record_Definition
619         and then
620           Present
621             (Variant_Part
622               (Component_List (Type_Definition (Parent (U_Typ)))))
623       then
624          --  For now, do not attempt to free a component that may appear in
625          --  a variant, and instead issue a warning. Doing this "properly"
626          --  would require building a case statement and would be quite a
627          --  mess. Note that the RM only requires that free "work" for the
628          --  case of a task access value, so already we go way beyond this
629          --  in that we deal with the array case and non-discriminated
630          --  record cases.
631
632          Error_Msg_N
633            ("task/protected object in variant record will not be freed?", N);
634          return New_List (Make_Null_Statement (Loc));
635       end if;
636
637       Comp := First_Component (Typ);
638
639       while Present (Comp) loop
640          if Has_Task (Etype (Comp))
641            or else Has_Simple_Protected_Object (Etype (Comp))
642          then
643             Tsk :=
644               Make_Selected_Component (Loc,
645                 Prefix        => Duplicate_Subexpr_No_Checks (Obj),
646                 Selector_Name => New_Occurrence_Of (Comp, Loc));
647             Set_Etype (Tsk, Etype (Comp));
648
649             if Is_Task_Type (Etype (Comp)) then
650                Append_To (Stmts, Cleanup_Task (N, Tsk));
651
652             elsif Is_Simple_Protected_Type (Etype (Comp)) then
653                Append_To (Stmts, Cleanup_Protected_Object (N, Tsk));
654
655             elsif Is_Record_Type (Etype (Comp)) then
656
657                --  Recurse, by generating the prefix of the argument to
658                --  the eventual cleanup call.
659
660                Append_List_To
661                  (Stmts, Cleanup_Record (N, Tsk, Etype (Comp)));
662
663             elsif Is_Array_Type (Etype (Comp)) then
664                Append_List_To
665                  (Stmts, Cleanup_Array (N, Tsk, Etype (Comp)));
666             end if;
667          end if;
668
669          Next_Component (Comp);
670       end loop;
671
672       return Stmts;
673    end Cleanup_Record;
674
675    -------------------------------
676    --  Cleanup_Protected_Object --
677    -------------------------------
678
679    function Cleanup_Protected_Object
680      (N    : Node_Id;
681       Ref  : Node_Id)
682       return Node_Id
683    is
684       Loc : constant Source_Ptr := Sloc (N);
685
686    begin
687       return
688         Make_Procedure_Call_Statement (Loc,
689           Name => New_Reference_To (RTE (RE_Finalize_Protection), Loc),
690           Parameter_Associations => New_List (
691             Concurrent_Ref (Ref)));
692    end Cleanup_Protected_Object;
693
694    ------------------------------------
695    -- Clean_Simple_Protected_Objects --
696    ------------------------------------
697
698    procedure Clean_Simple_Protected_Objects (N : Node_Id) is
699       E     : Entity_Id;
700       Stmts : List_Id := Statements (Handled_Statement_Sequence (N));
701       Stmt  : Node_Id := Last (Stmts);
702
703    begin
704       E := First_Entity (Current_Scope);
705
706       while Present (E) loop
707          if (Ekind (E) = E_Variable
708               or else Ekind (E) = E_Constant)
709            and then Has_Simple_Protected_Object (Etype (E))
710            and then not Has_Task (Etype (E))
711          then
712             declare
713                Typ : constant Entity_Id := Etype (E);
714                Ref : constant Node_Id := New_Occurrence_Of (E, Sloc (Stmt));
715
716             begin
717                if Is_Simple_Protected_Type (Typ) then
718                   Append_To (Stmts, Cleanup_Protected_Object (N, Ref));
719
720                elsif Has_Simple_Protected_Object (Typ) then
721                   if Is_Record_Type (Typ) then
722                      Append_List_To (Stmts, Cleanup_Record (N, Ref, Typ));
723
724                   elsif Is_Array_Type (Typ) then
725                      Append_List_To (Stmts, Cleanup_Array (N, Ref, Typ));
726                   end if;
727                end if;
728             end;
729          end if;
730
731          Next_Entity (E);
732       end loop;
733
734       --   Analyze inserted cleanup statements.
735
736       if Present (Stmt) then
737          Stmt := Next (Stmt);
738
739          while Present (Stmt) loop
740             Analyze (Stmt);
741             Next (Stmt);
742          end loop;
743       end if;
744    end Clean_Simple_Protected_Objects;
745
746    ------------------
747    -- Cleanup_Task --
748    ------------------
749
750    function Cleanup_Task
751      (N    : Node_Id;
752       Ref  : Node_Id)
753       return Node_Id
754    is
755       Loc  : constant Source_Ptr := Sloc (N);
756    begin
757       return
758         Make_Procedure_Call_Statement (Loc,
759           Name => New_Reference_To (RTE (RE_Free_Task), Loc),
760           Parameter_Associations =>
761             New_List (Concurrent_Ref (Ref)));
762    end Cleanup_Task;
763
764    ---------------------------------
765    -- Has_Simple_Protected_Object --
766    ---------------------------------
767
768    function Has_Simple_Protected_Object (T : Entity_Id) return Boolean is
769       Comp : Entity_Id;
770
771    begin
772       if Is_Simple_Protected_Type (T) then
773          return True;
774
775       elsif Is_Array_Type (T) then
776          return Has_Simple_Protected_Object (Component_Type (T));
777
778       elsif Is_Record_Type (T) then
779          Comp := First_Component (T);
780
781          while Present (Comp) loop
782             if Has_Simple_Protected_Object (Etype (Comp)) then
783                return True;
784             end if;
785
786             Next_Component (Comp);
787          end loop;
788
789          return False;
790
791       else
792          return False;
793       end if;
794    end Has_Simple_Protected_Object;
795
796    ------------------------------
797    -- Is_Simple_Protected_Type --
798    ------------------------------
799
800    function Is_Simple_Protected_Type (T : Entity_Id) return Boolean is
801    begin
802       return Is_Protected_Type (T) and then not Has_Entries (T);
803    end Is_Simple_Protected_Type;
804
805    ------------------------------
806    -- Check_Visibly_Controlled --
807    ------------------------------
808
809    procedure Check_Visibly_Controlled
810      (Prim : Final_Primitives;
811       Typ  : Entity_Id;
812       E    : in out Entity_Id;
813       Cref : in out Node_Id)
814    is
815       Parent_Type : Entity_Id;
816       Op          : Entity_Id;
817
818    begin
819       if Is_Derived_Type (Typ)
820         and then Comes_From_Source (E)
821         and then Is_Overriding_Operation (E)
822         and then
823           (not Is_Predefined_File_Name
824                      (Unit_File_Name (Get_Source_Unit (Root_Type (Typ)))))
825       then
826          --  We know that the explicit operation on the type overrode
827          --  the inherited operation of the parent, and that the derivation
828          --  is from a private type that is not visibly controlled.
829
830          Parent_Type := Etype (Typ);
831          Op := Find_Prim_Op (Parent_Type, Name_Of (Prim));
832
833          if Present (Op)
834             and then Is_Hidden (Op)
835             and then Scope (Scope (Typ)) /= Scope (Op)
836             and then not In_Open_Scopes (Scope (Typ))
837          then
838             --  If the parent operation is not visible, and the derived
839             --  type is not declared in a child unit, then the explicit
840             --  operation does not override, and we must use the operation
841             --  of the parent.
842
843             E := Op;
844
845             --  Wrap the object to be initialized into the proper
846             --  unchecked conversion, to be compatible with the operation
847             --  to be called.
848
849             if Nkind (Cref) = N_Unchecked_Type_Conversion then
850                Cref := Unchecked_Convert_To (Parent_Type, Expression (Cref));
851             else
852                Cref := Unchecked_Convert_To (Parent_Type, Cref);
853             end if;
854          end if;
855       end if;
856    end Check_Visibly_Controlled;
857
858    ---------------------
859    -- Controlled_Type --
860    ---------------------
861
862    function Controlled_Type (T : Entity_Id) return Boolean is
863
864       function Has_Some_Controlled_Component (Rec : Entity_Id) return Boolean;
865       --  If type is not frozen yet, check explicitly among its components,
866       --  because flag is not necessarily set.
867
868       ------------------------------------
869       --  Has_Some_Controlled_Component --
870       ------------------------------------
871
872       function Has_Some_Controlled_Component (Rec : Entity_Id)
873         return Boolean
874       is
875          Comp : Entity_Id;
876
877       begin
878          if Has_Controlled_Component (Rec) then
879             return True;
880
881          elsif not Is_Frozen (Rec) then
882             if Is_Record_Type (Rec) then
883                Comp := First_Entity (Rec);
884
885                while Present (Comp) loop
886                   if not Is_Type (Comp)
887                     and then Controlled_Type (Etype (Comp))
888                   then
889                      return True;
890                   end if;
891
892                   Next_Entity (Comp);
893                end loop;
894
895                return False;
896
897             elsif Is_Array_Type (Rec) then
898                return Is_Controlled (Component_Type (Rec));
899
900             else
901                return Has_Controlled_Component (Rec);
902             end if;
903          else
904             return False;
905          end if;
906       end Has_Some_Controlled_Component;
907
908    --  Start of processing for Controlled_Type
909
910    begin
911       --  Class-wide types must be treated as controlled because they may
912       --  contain an extension that has controlled components
913
914       --  We can skip this if finalization is not available
915
916       return (Is_Class_Wide_Type (T)
917                 and then not In_Finalization_Root (T)
918                 and then not Restrictions (No_Finalization))
919         or else Is_Controlled (T)
920         or else Has_Some_Controlled_Component (T)
921         or else (Is_Concurrent_Type (T)
922                    and then Present (Corresponding_Record_Type (T))
923                    and then Controlled_Type (Corresponding_Record_Type (T)));
924    end Controlled_Type;
925
926    --------------------------
927    -- Controller_Component --
928    --------------------------
929
930    function Controller_Component (Typ : Entity_Id) return Entity_Id is
931       T         : Entity_Id := Base_Type (Typ);
932       Comp      : Entity_Id;
933       Comp_Scop : Entity_Id;
934       Res       : Entity_Id := Empty;
935       Res_Scop  : Entity_Id := Empty;
936
937    begin
938       if Is_Class_Wide_Type (T) then
939          T := Root_Type (T);
940       end if;
941
942       if Is_Private_Type (T) then
943          T := Underlying_Type (T);
944       end if;
945
946       --  Fetch the outermost controller
947
948       Comp := First_Entity (T);
949       while Present (Comp) loop
950          if Chars (Comp) = Name_uController then
951             Comp_Scop := Scope (Original_Record_Component (Comp));
952
953             --  If this controller is at the outermost level, no need to
954             --  look for another one
955
956             if Comp_Scop = T then
957                return Comp;
958
959             --  Otherwise record the outermost one and continue looking
960
961             elsif Res = Empty or else Is_Ancestor (Res_Scop, Comp_Scop) then
962                Res      := Comp;
963                Res_Scop := Comp_Scop;
964             end if;
965          end if;
966
967          Next_Entity (Comp);
968       end loop;
969
970       --  If we fall through the loop, there is no controller component
971
972       return Res;
973    end Controller_Component;
974
975    ------------------
976    -- Convert_View --
977    ------------------
978
979    function Convert_View
980      (Proc : Entity_Id;
981       Arg  : Node_Id;
982       Ind  : Pos := 1)
983       return Node_Id
984    is
985       Fent : Entity_Id := First_Entity (Proc);
986       Ftyp : Entity_Id;
987       Atyp : Entity_Id;
988
989    begin
990       for J in 2 .. Ind loop
991          Next_Entity (Fent);
992       end loop;
993
994       Ftyp := Etype (Fent);
995
996       if Nkind (Arg) = N_Type_Conversion
997         or else Nkind (Arg) = N_Unchecked_Type_Conversion
998       then
999          Atyp := Entity (Subtype_Mark (Arg));
1000       else
1001          Atyp := Etype (Arg);
1002       end if;
1003
1004       if Is_Abstract (Proc) and then Is_Tagged_Type (Ftyp) then
1005          return Unchecked_Convert_To (Class_Wide_Type (Ftyp), Arg);
1006
1007       elsif Ftyp /= Atyp
1008         and then Present (Atyp)
1009         and then
1010           (Is_Private_Type (Ftyp) or else Is_Private_Type (Atyp))
1011         and then Underlying_Type (Atyp) = Underlying_Type (Ftyp)
1012       then
1013          return Unchecked_Convert_To (Ftyp, Arg);
1014
1015       --  If the argument is already a conversion, as generated by
1016       --  Make_Init_Call, set the target type to the type of the formal
1017       --  directly, to avoid spurious typing problems.
1018
1019       elsif (Nkind (Arg) = N_Unchecked_Type_Conversion
1020               or else Nkind (Arg) = N_Type_Conversion)
1021         and then not Is_Class_Wide_Type (Atyp)
1022       then
1023          Set_Subtype_Mark (Arg, New_Occurrence_Of (Ftyp, Sloc (Arg)));
1024          Set_Etype (Arg, Ftyp);
1025          return Arg;
1026
1027       else
1028          return Arg;
1029       end if;
1030    end Convert_View;
1031
1032    -------------------------------
1033    -- Establish_Transient_Scope --
1034    -------------------------------
1035
1036    --  This procedure is called each time a transient block has to be inserted
1037    --  that is to say for each call to a function with unconstrained ot tagged
1038    --  result. It creates a new scope on the stack scope in order to enclose
1039    --  all transient variables generated
1040
1041    procedure Establish_Transient_Scope (N : Node_Id; Sec_Stack : Boolean) is
1042       Loc       : constant Source_Ptr := Sloc (N);
1043       Wrap_Node : Node_Id;
1044
1045       Sec_Stk : constant Boolean :=
1046                   Sec_Stack and not Functions_Return_By_DSP_On_Target;
1047       --  We never need a secondary stack if functions return by DSP
1048
1049    begin
1050       --  Do not create a transient scope if we are already inside one
1051
1052       for S in reverse Scope_Stack.First .. Scope_Stack.Last loop
1053
1054          if Scope_Stack.Table (S).Is_Transient then
1055             if Sec_Stk then
1056                Set_Uses_Sec_Stack (Scope_Stack.Table (S).Entity);
1057             end if;
1058
1059             return;
1060
1061          --  If we have encountered Standard there are no enclosing
1062          --  transient scopes.
1063
1064          elsif Scope_Stack.Table (S).Entity = Standard_Standard then
1065             exit;
1066
1067          end if;
1068       end loop;
1069
1070       Wrap_Node := Find_Node_To_Be_Wrapped (N);
1071
1072       --  Case of no wrap node, false alert, no transient scope needed
1073
1074       if No (Wrap_Node) then
1075          null;
1076
1077       --  Transient scope is required
1078
1079       else
1080          New_Scope (New_Internal_Entity (E_Block, Current_Scope, Loc, 'B'));
1081          Set_Scope_Is_Transient;
1082
1083          if Sec_Stk then
1084             Set_Uses_Sec_Stack (Current_Scope);
1085             Check_Restriction (No_Secondary_Stack, N);
1086          end if;
1087
1088          Set_Etype (Current_Scope, Standard_Void_Type);
1089          Set_Node_To_Be_Wrapped (Wrap_Node);
1090
1091          if Debug_Flag_W then
1092             Write_Str ("    <Transient>");
1093             Write_Eol;
1094          end if;
1095       end if;
1096    end Establish_Transient_Scope;
1097
1098    ----------------------------
1099    -- Expand_Cleanup_Actions --
1100    ----------------------------
1101
1102    procedure Expand_Cleanup_Actions (N : Node_Id) is
1103       Loc                  :  Source_Ptr;
1104       S                    : constant Entity_Id  :=
1105                                Current_Scope;
1106       Flist                : constant Entity_Id  :=
1107                                Finalization_Chain_Entity (S);
1108       Is_Task              : constant Boolean    :=
1109                                (Nkind (Original_Node (N)) = N_Task_Body);
1110       Is_Master            : constant Boolean    :=
1111                                Nkind (N) /= N_Entry_Body
1112                                  and then Is_Task_Master (N);
1113       Is_Protected         : constant Boolean    :=
1114                                Nkind (N) = N_Subprogram_Body
1115                                  and then Is_Protected_Subprogram_Body (N);
1116       Is_Task_Allocation   : constant Boolean    :=
1117                                Nkind (N) = N_Block_Statement
1118                                  and then Is_Task_Allocation_Block (N);
1119       Is_Asynchronous_Call : constant Boolean    :=
1120                                Nkind (N) = N_Block_Statement
1121                                  and then Is_Asynchronous_Call_Block (N);
1122
1123       Clean     : Entity_Id;
1124       Mark      : Entity_Id := Empty;
1125       New_Decls : constant List_Id := New_List;
1126       Blok      : Node_Id;
1127       Wrapped   : Boolean;
1128       Chain     : Entity_Id := Empty;
1129       Decl      : Node_Id;
1130       Old_Poll  : Boolean;
1131
1132    begin
1133
1134       --  Compute a location that is not directly in the user code in
1135       --  order to avoid to generate confusing debug info. A good
1136       --  approximation is the name of the outer user-defined scope
1137
1138       declare
1139          S1 : Entity_Id := S;
1140
1141       begin
1142          while not Comes_From_Source (S1) and then S1 /= Standard_Standard loop
1143             S1 := Scope (S1);
1144          end loop;
1145
1146          Loc := Sloc (S1);
1147       end;
1148
1149       --  There are cleanup actions only if the secondary stack needs
1150       --  releasing or some finalizations are needed or in the context
1151       --  of tasking
1152
1153       if Uses_Sec_Stack  (Current_Scope)
1154         and then not Sec_Stack_Needed_For_Return (Current_Scope)
1155       then
1156          null;
1157       elsif No (Flist)
1158         and then not Is_Master
1159         and then not Is_Task
1160         and then not Is_Protected
1161         and then not Is_Task_Allocation
1162         and then not Is_Asynchronous_Call
1163       then
1164          Clean_Simple_Protected_Objects (N);
1165          return;
1166       end if;
1167
1168       --  If the current scope is the subprogram body that is the rewriting
1169       --  of a task body, and the descriptors have not been delayed (due to
1170       --  some nested instantiations) do not generate redundant cleanup
1171       --  actions: the cleanup procedure already exists for this body.
1172
1173       if Nkind (N) = N_Subprogram_Body
1174         and then Nkind (Original_Node (N)) = N_Task_Body
1175         and then not Delay_Subprogram_Descriptors (Corresponding_Spec (N))
1176       then
1177          return;
1178       end if;
1179
1180       --  Set polling off, since we don't need to poll during cleanup
1181       --  actions, and indeed for the cleanup routine, which is executed
1182       --  with aborts deferred, we don't want polling.
1183
1184       Old_Poll := Polling_Required;
1185       Polling_Required := False;
1186
1187       --  Make sure we have a declaration list, since we will add to it
1188
1189       if No (Declarations (N)) then
1190          Set_Declarations (N, New_List);
1191       end if;
1192
1193       --  The task activation call has already been built for task
1194       --  allocation blocks.
1195
1196       if not Is_Task_Allocation then
1197          Build_Task_Activation_Call (N);
1198       end if;
1199
1200       if Is_Master then
1201          Establish_Task_Master (N);
1202       end if;
1203
1204       --  If secondary stack is in use, expand:
1205       --    _Mxx : constant Mark_Id := SS_Mark;
1206
1207       --  Suppress calls to SS_Mark and SS_Release if Java_VM,
1208       --  since we never use the secondary stack on the JVM.
1209
1210       if Uses_Sec_Stack (Current_Scope)
1211         and then not Sec_Stack_Needed_For_Return (Current_Scope)
1212         and then not Java_VM
1213       then
1214          Mark := Make_Defining_Identifier (Loc, New_Internal_Name ('M'));
1215          Append_To (New_Decls,
1216            Make_Object_Declaration (Loc,
1217              Defining_Identifier => Mark,
1218              Object_Definition   => New_Reference_To (RTE (RE_Mark_Id), Loc),
1219              Expression =>
1220                Make_Function_Call (Loc,
1221                  Name => New_Reference_To (RTE (RE_SS_Mark), Loc))));
1222
1223          Set_Uses_Sec_Stack (Current_Scope, False);
1224       end if;
1225
1226       --  If finalization list is present then expand:
1227       --   Local_Final_List : System.FI.Finalizable_Ptr;
1228
1229       if Present (Flist) then
1230          Append_To (New_Decls,
1231            Make_Object_Declaration (Loc,
1232              Defining_Identifier => Flist,
1233              Object_Definition   =>
1234                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
1235       end if;
1236
1237       --  Clean-up procedure definition
1238
1239       Clean := Make_Defining_Identifier (Loc, Name_uClean);
1240       Set_Suppress_Elaboration_Warnings (Clean);
1241       Append_To (New_Decls,
1242         Make_Clean (N, Clean, Mark, Flist,
1243           Is_Task,
1244           Is_Master,
1245           Is_Protected,
1246           Is_Task_Allocation,
1247           Is_Asynchronous_Call));
1248
1249       --  If exception handlers are present, wrap the Sequence of
1250       --  statements in a block because it is not possible to get
1251       --  exception handlers and an AT END call in the same scope.
1252
1253       if Present (Exception_Handlers (Handled_Statement_Sequence (N))) then
1254          Blok :=
1255            Make_Block_Statement (Loc,
1256              Handled_Statement_Sequence => Handled_Statement_Sequence (N));
1257          Set_Handled_Statement_Sequence (N,
1258            Make_Handled_Sequence_Of_Statements (Loc, New_List (Blok)));
1259          Wrapped := True;
1260
1261       --  Otherwise we do not wrap
1262
1263       else
1264          Wrapped := False;
1265          Blok    := Empty;
1266       end if;
1267
1268       --  Don't move the _chain Activation_Chain declaration in task
1269       --  allocation blocks. Task allocation blocks use this object
1270       --  in their cleanup handlers, and gigi complains if it is declared
1271       --  in the sequence of statements of the scope that declares the
1272       --  handler.
1273
1274       if Is_Task_Allocation then
1275          Chain := Activation_Chain_Entity (N);
1276          Decl := First (Declarations (N));
1277
1278          while Nkind (Decl) /= N_Object_Declaration
1279            or else Defining_Identifier (Decl) /= Chain
1280          loop
1281             Next (Decl);
1282             pragma Assert (Present (Decl));
1283          end loop;
1284
1285          Remove (Decl);
1286          Prepend_To (New_Decls, Decl);
1287       end if;
1288
1289       --  Now we move the declarations into the Sequence of statements
1290       --  in order to get them protected by the AT END call. It may seem
1291       --  weird to put declarations in the sequence of statement but in
1292       --  fact nothing forbids that at the tree level. We also set the
1293       --  First_Real_Statement field so that we remember where the real
1294       --  statements (i.e. original statements) begin. Note that if we
1295       --  wrapped the statements, the first real statement is inside the
1296       --  inner block. If the First_Real_Statement is already set (as is
1297       --  the case for subprogram bodies that are expansions of task bodies)
1298       --  then do not reset it, because its declarative part would migrate
1299       --  to the statement part.
1300
1301       if not Wrapped then
1302          if No (First_Real_Statement (Handled_Statement_Sequence (N))) then
1303             Set_First_Real_Statement (Handled_Statement_Sequence (N),
1304               First (Statements (Handled_Statement_Sequence (N))));
1305          end if;
1306
1307       else
1308          Set_First_Real_Statement (Handled_Statement_Sequence (N), Blok);
1309       end if;
1310
1311       Append_List_To (Declarations (N),
1312         Statements (Handled_Statement_Sequence (N)));
1313       Set_Statements (Handled_Statement_Sequence (N), Declarations (N));
1314
1315       --  We need to reset the Sloc of the handled statement sequence to
1316       --  properly reflect the new initial "statement" in the sequence.
1317
1318       Set_Sloc
1319         (Handled_Statement_Sequence (N), Sloc (First (Declarations (N))));
1320
1321       --  The declarations of the _Clean procedure and finalization chain
1322       --  replace the old declarations that have been moved inward
1323
1324       Set_Declarations (N, New_Decls);
1325       Analyze_Declarations (New_Decls);
1326
1327       --  The At_End call is attached to the sequence of statements.
1328
1329       declare
1330          HSS : Node_Id;
1331
1332       begin
1333          --  If the construct is a protected subprogram, then the call to
1334          --  the corresponding unprotected program appears in a block which
1335          --  is the last statement in the body, and it is this block that
1336          --  must be covered by the At_End handler.
1337
1338          if Is_Protected then
1339             HSS := Handled_Statement_Sequence
1340               (Last (Statements (Handled_Statement_Sequence (N))));
1341          else
1342             HSS := Handled_Statement_Sequence (N);
1343          end if;
1344
1345          Set_At_End_Proc (HSS, New_Occurrence_Of (Clean, Loc));
1346          Expand_At_End_Handler (HSS, Empty);
1347       end;
1348
1349       --  Restore saved polling mode
1350
1351       Polling_Required := Old_Poll;
1352    end Expand_Cleanup_Actions;
1353
1354    -------------------------------
1355    -- Expand_Ctrl_Function_Call --
1356    -------------------------------
1357
1358    procedure Expand_Ctrl_Function_Call (N : Node_Id) is
1359       Loc     : constant Source_Ptr := Sloc (N);
1360       Rtype   : constant Entity_Id  := Etype (N);
1361       Utype   : constant Entity_Id  := Underlying_Type (Rtype);
1362       Ref     : Node_Id;
1363       Action  : Node_Id;
1364       Action2 : Node_Id := Empty;
1365
1366       Attach_Level : Uint    := Uint_1;
1367       Len_Ref      : Node_Id := Empty;
1368
1369       function Last_Array_Component
1370         (Ref :  Node_Id;
1371          Typ :  Entity_Id)
1372          return Node_Id;
1373       --  Creates a reference to the last component of the array object
1374       --  designated by Ref whose type is Typ.
1375
1376       --------------------------
1377       -- Last_Array_Component --
1378       --------------------------
1379
1380       function Last_Array_Component
1381         (Ref :  Node_Id;
1382          Typ :  Entity_Id)
1383          return Node_Id
1384       is
1385          Index_List : constant List_Id := New_List;
1386
1387       begin
1388          for N in 1 .. Number_Dimensions (Typ) loop
1389             Append_To (Index_List,
1390               Make_Attribute_Reference (Loc,
1391                 Prefix         => Duplicate_Subexpr_No_Checks (Ref),
1392                 Attribute_Name => Name_Last,
1393                 Expressions    => New_List (
1394                   Make_Integer_Literal (Loc, N))));
1395          end loop;
1396
1397          return
1398            Make_Indexed_Component (Loc,
1399              Prefix      => Duplicate_Subexpr (Ref),
1400              Expressions => Index_List);
1401       end Last_Array_Component;
1402
1403    --  Start of processing for Expand_Ctrl_Function_Call
1404
1405    begin
1406       --  Optimization, if the returned value (which is on the sec-stack)
1407       --  is returned again, no need to copy/readjust/finalize, we can just
1408       --  pass the value thru (see Expand_N_Return_Statement), and thus no
1409       --  attachment is needed
1410
1411       if Nkind (Parent (N)) = N_Return_Statement then
1412          return;
1413       end if;
1414
1415       --  Resolution is now finished, make sure we don't start analysis again
1416       --  because of the duplication
1417
1418       Set_Analyzed (N);
1419       Ref := Duplicate_Subexpr_No_Checks (N);
1420
1421       --  Now we can generate the Attach Call, note that this value is
1422       --  always in the (secondary) stack and thus is attached to a singly
1423       --  linked final list:
1424
1425       --    Resx := F (X)'reference;
1426       --    Attach_To_Final_List (_Lx, Resx.all, 1);
1427
1428       --  or when there are controlled components
1429
1430       --    Attach_To_Final_List (_Lx, Resx._controller, 1);
1431
1432       --  or when it is both is_controlled and has_controlled_components
1433
1434       --    Attach_To_Final_List (_Lx, Resx._controller, 1);
1435       --    Attach_To_Final_List (_Lx, Resx, 1);
1436
1437       --  or if it is an array with is_controlled (and has_controlled)
1438
1439       --    Attach_To_Final_List (_Lx, Resx (Resx'last), 3);
1440       --    An attach level of 3 means that a whole array is to be
1441       --    attached to the finalization list (including the controlled
1442       --    components)
1443
1444       --  or if it is an array with has_controlled components but not
1445       --  is_controlled
1446
1447       --    Attach_To_Final_List (_Lx, Resx (Resx'last)._controller, 3);
1448
1449       if Has_Controlled_Component (Rtype) then
1450          declare
1451             T1 : Entity_Id := Rtype;
1452             T2 : Entity_Id := Utype;
1453
1454          begin
1455             if Is_Array_Type (T2) then
1456                Len_Ref :=
1457                  Make_Attribute_Reference (Loc,
1458                  Prefix =>
1459                    Duplicate_Subexpr_Move_Checks
1460                      (Unchecked_Convert_To (T2, Ref)),
1461                  Attribute_Name => Name_Length);
1462             end if;
1463
1464             while Is_Array_Type (T2) loop
1465                if T1 /= T2 then
1466                   Ref := Unchecked_Convert_To (T2, Ref);
1467                end if;
1468
1469                Ref := Last_Array_Component (Ref, T2);
1470                Attach_Level := Uint_3;
1471                T1 := Component_Type (T2);
1472                T2 := Underlying_Type (T1);
1473             end loop;
1474
1475             --  If the type has controlled components, go to the controller
1476             --  except in the case of arrays of controlled objects since in
1477             --  this case objects and their components are already chained
1478             --  and the head of the chain is the last array element.
1479
1480             if Is_Array_Type (Rtype) and then Is_Controlled (T2) then
1481                null;
1482
1483             elsif Has_Controlled_Component (T2) then
1484                if T1 /= T2 then
1485                   Ref := Unchecked_Convert_To (T2, Ref);
1486                end if;
1487
1488                Ref :=
1489                  Make_Selected_Component (Loc,
1490                    Prefix        => Ref,
1491                    Selector_Name => Make_Identifier (Loc, Name_uController));
1492             end if;
1493          end;
1494
1495          --  Here we know that 'Ref' has a controller so we may as well
1496          --  attach it directly
1497
1498          Action :=
1499            Make_Attach_Call (
1500              Obj_Ref      => Ref,
1501              Flist_Ref    => Find_Final_List (Current_Scope),
1502              With_Attach  => Make_Integer_Literal (Loc, Attach_Level));
1503
1504          --  If it is also Is_Controlled we need to attach the global object
1505
1506          if Is_Controlled (Rtype) then
1507             Action2 :=
1508               Make_Attach_Call (
1509                 Obj_Ref      => Duplicate_Subexpr_No_Checks (N),
1510                 Flist_Ref    => Find_Final_List (Current_Scope),
1511                 With_Attach  => Make_Integer_Literal (Loc, Attach_Level));
1512          end if;
1513
1514       else
1515          --  Here, we have a controlled type that does not seem to have
1516          --  controlled components but it could be a class wide type whose
1517          --  further derivations have controlled components. So we don't know
1518          --  if the object itself needs to be attached or if it
1519          --  has a record controller. We need to call a runtime function
1520          --  (Deep_Tag_Attach) which knows what to do thanks to the
1521          --  RC_Offset in the dispatch table.
1522
1523          Action :=
1524            Make_Procedure_Call_Statement (Loc,
1525              Name => New_Reference_To (RTE (RE_Deep_Tag_Attach), Loc),
1526              Parameter_Associations => New_List (
1527                Find_Final_List (Current_Scope),
1528
1529                Make_Attribute_Reference (Loc,
1530                    Prefix => Ref,
1531                    Attribute_Name => Name_Address),
1532
1533                Make_Integer_Literal (Loc, Attach_Level)));
1534       end if;
1535
1536       if Present (Len_Ref) then
1537          Action :=
1538            Make_Implicit_If_Statement (N,
1539              Condition => Make_Op_Gt (Loc,
1540                Left_Opnd  => Len_Ref,
1541                Right_Opnd => Make_Integer_Literal (Loc, 0)),
1542              Then_Statements => New_List (Action));
1543       end if;
1544
1545       Insert_Action (N, Action);
1546       if Present (Action2) then
1547          Insert_Action (N, Action2);
1548       end if;
1549    end Expand_Ctrl_Function_Call;
1550
1551    ---------------------------
1552    -- Expand_N_Package_Body --
1553    ---------------------------
1554
1555    --  Add call to Activate_Tasks if body is an activator (actual
1556    --  processing is in chapter 9).
1557
1558    --  Generate subprogram descriptor for elaboration routine
1559
1560    --  ENcode entity names in package body
1561
1562    procedure Expand_N_Package_Body (N : Node_Id) is
1563       Ent : constant Entity_Id := Corresponding_Spec (N);
1564
1565    begin
1566       --  This is done only for non-generic packages
1567
1568       if Ekind (Ent) = E_Package then
1569          New_Scope (Corresponding_Spec (N));
1570          Build_Task_Activation_Call (N);
1571          Pop_Scope;
1572       end if;
1573
1574       Set_Elaboration_Flag (N, Corresponding_Spec (N));
1575
1576       --  Generate a subprogram descriptor for the elaboration routine of
1577       --  a package body if the package body has no pending instantiations
1578       --  and it has generated at least one exception handler
1579
1580       if Present (Handler_Records (Body_Entity (Ent)))
1581         and then Is_Compilation_Unit (Ent)
1582         and then not Delay_Subprogram_Descriptors (Body_Entity (Ent))
1583       then
1584          Generate_Subprogram_Descriptor_For_Package
1585            (N, Body_Entity (Ent));
1586       end if;
1587
1588       Set_In_Package_Body (Ent, False);
1589
1590       --  Set to encode entity names in package body before gigi is called
1591
1592       Qualify_Entity_Names (N);
1593    end Expand_N_Package_Body;
1594
1595    ----------------------------------
1596    -- Expand_N_Package_Declaration --
1597    ----------------------------------
1598
1599    --  Add call to Activate_Tasks if there are tasks declared and the
1600    --  package has no body. Note that in Ada83,  this may result in
1601    --  premature activation of some tasks, given that we cannot tell
1602    --  whether a body will eventually appear.
1603
1604    procedure Expand_N_Package_Declaration (N : Node_Id) is
1605    begin
1606       if Nkind (Parent (N)) = N_Compilation_Unit
1607         and then not Body_Required (Parent (N))
1608         and then not Unit_Requires_Body (Defining_Entity (N))
1609         and then Present (Activation_Chain_Entity (N))
1610       then
1611          New_Scope (Defining_Entity (N));
1612          Build_Task_Activation_Call (N);
1613          Pop_Scope;
1614       end if;
1615
1616       --  Note: it is not necessary to worry about generating a subprogram
1617       --  descriptor, since the only way to get exception handlers into a
1618       --  package spec is to include instantiations, and that would cause
1619       --  generation of subprogram descriptors to be delayed in any case.
1620
1621       --  Set to encode entity names in package spec before gigi is called
1622
1623       Qualify_Entity_Names (N);
1624    end Expand_N_Package_Declaration;
1625
1626    ---------------------
1627    -- Find_Final_List --
1628    ---------------------
1629
1630    function Find_Final_List
1631      (E    : Entity_Id;
1632       Ref  : Node_Id := Empty)
1633       return Node_Id
1634    is
1635       Loc : constant Source_Ptr := Sloc (Ref);
1636       S   : Entity_Id;
1637       Id  : Entity_Id;
1638       R   : Node_Id;
1639
1640    begin
1641       --  Case of an internal component. The Final list is the record
1642       --  controller of the enclosing record
1643
1644       if Present (Ref) then
1645          R := Ref;
1646          loop
1647             case Nkind (R) is
1648                when N_Unchecked_Type_Conversion | N_Type_Conversion =>
1649                   R := Expression (R);
1650
1651                when N_Indexed_Component | N_Explicit_Dereference =>
1652                   R := Prefix (R);
1653
1654                when  N_Selected_Component =>
1655                   R := Prefix (R);
1656                   exit;
1657
1658                when  N_Identifier =>
1659                   exit;
1660
1661                when others =>
1662                   raise Program_Error;
1663             end case;
1664          end loop;
1665
1666          return
1667            Make_Selected_Component (Loc,
1668              Prefix =>
1669                Make_Selected_Component (Loc,
1670                  Prefix        => R,
1671                  Selector_Name => Make_Identifier (Loc, Name_uController)),
1672              Selector_Name => Make_Identifier (Loc, Name_F));
1673
1674       --  Case of a dynamically allocated object. The final list is the
1675       --  corresponding list controller (The next entity in the scope of
1676       --  the access type with the right type). If the type comes from a
1677       --  With_Type clause, no controller was created, and we use the
1678       --  global chain instead.
1679
1680       elsif Is_Access_Type (E) then
1681          if not From_With_Type (E) then
1682             return
1683               Make_Selected_Component (Loc,
1684                 Prefix        =>
1685                   New_Reference_To
1686                     (Associated_Final_Chain (Base_Type (E)), Loc),
1687                 Selector_Name => Make_Identifier (Loc, Name_F));
1688          else
1689             return New_Reference_To (RTE (RE_Global_Final_List), Sloc (E));
1690          end if;
1691
1692       else
1693          if Is_Dynamic_Scope (E) then
1694             S := E;
1695          else
1696             S := Enclosing_Dynamic_Scope (E);
1697          end if;
1698
1699          --  When the finalization chain entity is 'Error', it means that
1700          --  there should not be any chain at that level and that the
1701          --  enclosing one should be used
1702
1703          --  This is a nasty kludge, see ??? note in exp_ch11
1704
1705          while Finalization_Chain_Entity (S) = Error loop
1706             S := Enclosing_Dynamic_Scope (S);
1707          end loop;
1708
1709          if S = Standard_Standard then
1710             return New_Reference_To (RTE (RE_Global_Final_List), Sloc (E));
1711          else
1712             if No (Finalization_Chain_Entity (S)) then
1713
1714                Id := Make_Defining_Identifier (Sloc (S),
1715                  New_Internal_Name ('F'));
1716                Set_Finalization_Chain_Entity (S, Id);
1717
1718                --  Set momentarily some semantics attributes to allow normal
1719                --  analysis of expansions containing references to this chain.
1720                --  Will be fully decorated during the expansion of the scope
1721                --  itself
1722
1723                Set_Ekind (Id, E_Variable);
1724                Set_Etype (Id, RTE (RE_Finalizable_Ptr));
1725             end if;
1726
1727             return New_Reference_To (Finalization_Chain_Entity (S), Sloc (E));
1728          end if;
1729       end if;
1730    end Find_Final_List;
1731
1732    -----------------------------
1733    -- Find_Node_To_Be_Wrapped --
1734    -----------------------------
1735
1736    function Find_Node_To_Be_Wrapped (N : Node_Id) return Node_Id is
1737       P          : Node_Id;
1738       The_Parent : Node_Id;
1739
1740    begin
1741       The_Parent := N;
1742       loop
1743          P := The_Parent;
1744          pragma Assert (P /= Empty);
1745          The_Parent := Parent (P);
1746
1747          case Nkind (The_Parent) is
1748
1749             --  Simple statement can be wrapped
1750
1751             when N_Pragma               =>
1752                return The_Parent;
1753
1754             --  Usually assignments are good candidate for wrapping
1755             --  except when they have been generated as part of a
1756             --  controlled aggregate where the wrapping should take
1757             --  place more globally.
1758
1759             when N_Assignment_Statement =>
1760                if No_Ctrl_Actions (The_Parent) then
1761                   null;
1762                else
1763                   return The_Parent;
1764                end if;
1765
1766             --  An entry call statement is a special case if it occurs in
1767             --  the context of a Timed_Entry_Call. In this case we wrap
1768             --  the entire timed entry call.
1769
1770             when N_Entry_Call_Statement     |
1771                  N_Procedure_Call_Statement =>
1772                if Nkind (Parent (The_Parent)) = N_Entry_Call_Alternative
1773                  and then
1774                    Nkind (Parent (Parent (The_Parent))) = N_Timed_Entry_Call
1775                then
1776                   return Parent (Parent (The_Parent));
1777                else
1778                   return The_Parent;
1779                end if;
1780
1781             --  Object declarations are also a boundary for the transient scope
1782             --  even if they are not really wrapped
1783             --  (see Wrap_Transient_Declaration)
1784
1785             when N_Object_Declaration          |
1786                  N_Object_Renaming_Declaration |
1787                  N_Subtype_Declaration         =>
1788                return The_Parent;
1789
1790             --  The expression itself is to be wrapped if its parent is a
1791             --  compound statement or any other statement where the expression
1792             --  is known to be scalar
1793
1794             when N_Accept_Alternative               |
1795                  N_Attribute_Definition_Clause      |
1796                  N_Case_Statement                   |
1797                  N_Code_Statement                   |
1798                  N_Delay_Alternative                |
1799                  N_Delay_Until_Statement            |
1800                  N_Delay_Relative_Statement         |
1801                  N_Discriminant_Association         |
1802                  N_Elsif_Part                       |
1803                  N_Entry_Body_Formal_Part           |
1804                  N_Exit_Statement                   |
1805                  N_If_Statement                     |
1806                  N_Iteration_Scheme                 |
1807                  N_Terminate_Alternative            =>
1808                return P;
1809
1810             when N_Attribute_Reference              =>
1811
1812                if Is_Procedure_Attribute_Name
1813                     (Attribute_Name (The_Parent))
1814                then
1815                   return The_Parent;
1816                end if;
1817
1818             --  ??? No scheme yet for "for I in Expression'Range loop"
1819             --  ??? the current scheme for Expression wrapping doesn't apply
1820             --  ??? because a RANGE is NOT an expression. Tricky problem...
1821             --  ??? while this problem is not solved we have a potential for
1822             --  ??? leak and unfinalized intermediate objects here.
1823
1824             when N_Loop_Parameter_Specification =>
1825                return Empty;
1826
1827             --  The following nodes contains "dummy calls" which don't
1828             --  need to be wrapped.
1829
1830             when N_Parameter_Specification     |
1831                  N_Discriminant_Specification  |
1832                  N_Component_Declaration       =>
1833                return Empty;
1834
1835             --  The return statement is not to be wrapped when the function
1836             --  itself needs wrapping at the outer-level
1837
1838             when N_Return_Statement            =>
1839                if Requires_Transient_Scope (Return_Type (The_Parent)) then
1840                   return Empty;
1841                else
1842                   return The_Parent;
1843                end if;
1844
1845             --  If we leave a scope without having been able to find a node to
1846             --  wrap, something is going wrong but this can happen in error
1847             --  situation that are not detected yet (such as a dynamic string
1848             --  in a pragma export)
1849
1850             when N_Subprogram_Body     |
1851                  N_Package_Declaration |
1852                  N_Package_Body        |
1853                  N_Block_Statement     =>
1854                return Empty;
1855
1856             --  otherwise continue the search
1857
1858             when others =>
1859                null;
1860          end case;
1861       end loop;
1862    end Find_Node_To_Be_Wrapped;
1863
1864    ----------------------
1865    -- Global_Flist_Ref --
1866    ----------------------
1867
1868    function Global_Flist_Ref  (Flist_Ref : Node_Id) return Boolean is
1869       Flist : Entity_Id;
1870
1871    begin
1872       --  Look for the Global_Final_List
1873
1874       if Is_Entity_Name (Flist_Ref) then
1875          Flist := Entity (Flist_Ref);
1876
1877       --  Look for the final list associated with an access to controlled
1878
1879       elsif  Nkind (Flist_Ref) = N_Selected_Component
1880         and then Is_Entity_Name (Prefix (Flist_Ref))
1881       then
1882          Flist :=  Entity (Prefix (Flist_Ref));
1883       else
1884          return False;
1885       end if;
1886
1887       return Present (Flist)
1888         and then Present (Scope (Flist))
1889         and then Enclosing_Dynamic_Scope (Flist) = Standard_Standard;
1890    end Global_Flist_Ref;
1891
1892    ----------------------------------
1893    -- Has_New_Controlled_Component --
1894    ----------------------------------
1895
1896    function Has_New_Controlled_Component (E : Entity_Id) return Boolean is
1897       Comp : Entity_Id;
1898
1899    begin
1900       if not Is_Tagged_Type (E) then
1901          return Has_Controlled_Component (E);
1902       elsif not Is_Derived_Type (E) then
1903          return Has_Controlled_Component (E);
1904       end if;
1905
1906       Comp := First_Component (E);
1907       while Present (Comp) loop
1908
1909          if Chars (Comp) = Name_uParent then
1910             null;
1911
1912          elsif Scope (Original_Record_Component (Comp)) = E
1913            and then Controlled_Type (Etype (Comp))
1914          then
1915             return True;
1916          end if;
1917
1918          Next_Component (Comp);
1919       end loop;
1920
1921       return False;
1922    end Has_New_Controlled_Component;
1923
1924    --------------------------
1925    -- In_Finalization_Root --
1926    --------------------------
1927
1928    --  It would seem simpler to test Scope (RTE (RE_Root_Controlled)) but
1929    --  the purpose of this function is to avoid a circular call to Rtsfind
1930    --  which would been caused by such a test.
1931
1932    function In_Finalization_Root (E : Entity_Id) return Boolean is
1933       S : constant Entity_Id := Scope (E);
1934
1935    begin
1936       return Chars (Scope (S))     = Name_System
1937         and then Chars (S)         = Name_Finalization_Root
1938         and then Scope (Scope (S)) = Standard_Standard;
1939    end  In_Finalization_Root;
1940
1941    ------------------------------------
1942    -- Insert_Actions_In_Scope_Around --
1943    ------------------------------------
1944
1945    procedure Insert_Actions_In_Scope_Around (N : Node_Id) is
1946       SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
1947
1948    begin
1949       if Present (SE.Actions_To_Be_Wrapped_Before) then
1950          Insert_List_Before (N, SE.Actions_To_Be_Wrapped_Before);
1951          SE.Actions_To_Be_Wrapped_Before := No_List;
1952       end if;
1953
1954       if Present (SE.Actions_To_Be_Wrapped_After) then
1955          Insert_List_After (N, SE.Actions_To_Be_Wrapped_After);
1956          SE.Actions_To_Be_Wrapped_After := No_List;
1957       end if;
1958    end Insert_Actions_In_Scope_Around;
1959
1960    -----------------------
1961    -- Make_Adjust_Call --
1962    -----------------------
1963
1964    function Make_Adjust_Call
1965      (Ref          : Node_Id;
1966       Typ          : Entity_Id;
1967       Flist_Ref    : Node_Id;
1968       With_Attach  : Node_Id)
1969       return         List_Id
1970    is
1971       Loc    : constant Source_Ptr := Sloc (Ref);
1972       Res    : constant List_Id    := New_List;
1973       Utyp   : Entity_Id;
1974       Proc   : Entity_Id;
1975       Cref   : Node_Id := Ref;
1976       Cref2  : Node_Id;
1977       Attach : Node_Id := With_Attach;
1978
1979    begin
1980       if Is_Class_Wide_Type (Typ) then
1981          Utyp := Underlying_Type (Base_Type (Root_Type (Typ)));
1982       else
1983          Utyp := Underlying_Type (Base_Type (Typ));
1984       end if;
1985
1986       Set_Assignment_OK (Cref);
1987
1988       --  Deal with non-tagged derivation of private views
1989
1990       if Is_Untagged_Derivation (Typ) then
1991          Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
1992          Cref := Unchecked_Convert_To (Utyp, Cref);
1993          Set_Assignment_OK (Cref);
1994          --  To prevent problems with UC see 1.156 RH ???
1995       end if;
1996
1997       --  If the underlying_type is a subtype, we are dealing with
1998       --  the completion of a private type. We need to access
1999       --  the base type and generate a conversion to it.
2000
2001       if Utyp /= Base_Type (Utyp) then
2002          pragma Assert (Is_Private_Type (Typ));
2003          Utyp := Base_Type (Utyp);
2004          Cref := Unchecked_Convert_To (Utyp, Cref);
2005       end if;
2006
2007       --  If the object is unanalyzed, set its expected type for use
2008       --  in Convert_View in case an additional conversion is needed.
2009
2010       if No (Etype (Cref))
2011         and then Nkind (Cref) /= N_Unchecked_Type_Conversion
2012       then
2013          Set_Etype (Cref, Typ);
2014       end if;
2015
2016       --  We do not need to attach to one of the Global Final Lists
2017       --  the objects whose type is Finalize_Storage_Only
2018
2019       if Finalize_Storage_Only (Typ)
2020         and then (Global_Flist_Ref (Flist_Ref)
2021           or else Entity (Constant_Value (RTE (RE_Garbage_Collected)))
2022                   = Standard_True)
2023       then
2024          Attach := Make_Integer_Literal (Loc, 0);
2025       end if;
2026
2027       --  Generate:
2028       --    Deep_Adjust (Flist_Ref, Ref, With_Attach);
2029
2030       if Has_Controlled_Component (Utyp)
2031         or else Is_Class_Wide_Type (Typ)
2032       then
2033          if Is_Tagged_Type (Utyp) then
2034             Proc := Find_Prim_Op (Utyp, TSS_Deep_Adjust);
2035
2036          else
2037             Proc := TSS (Utyp, TSS_Deep_Adjust);
2038          end if;
2039
2040          Cref := Convert_View (Proc, Cref, 2);
2041
2042          Append_To (Res,
2043            Make_Procedure_Call_Statement (Loc,
2044              Name => New_Reference_To (Proc, Loc),
2045              Parameter_Associations =>
2046                New_List (Flist_Ref, Cref, Attach)));
2047
2048       --  Generate:
2049       --    if With_Attach then
2050       --       Attach_To_Final_List (Ref, Flist_Ref);
2051       --    end if;
2052       --    Adjust (Ref);
2053
2054       else -- Is_Controlled (Utyp)
2055
2056          Proc  := Find_Prim_Op (Utyp, Name_Of (Adjust_Case));
2057          Cref  := Convert_View (Proc, Cref);
2058          Cref2 := New_Copy_Tree (Cref);
2059
2060          Append_To (Res,
2061            Make_Procedure_Call_Statement (Loc,
2062            Name => New_Reference_To (Proc, Loc),
2063            Parameter_Associations => New_List (Cref2)));
2064
2065          Append_To (Res, Make_Attach_Call (Cref, Flist_Ref, Attach));
2066       end if;
2067
2068       return Res;
2069    end Make_Adjust_Call;
2070
2071    ----------------------
2072    -- Make_Attach_Call --
2073    ----------------------
2074
2075    --  Generate:
2076    --    System.FI.Attach_To_Final_List (Flist, Ref, Nb_Link)
2077
2078    function Make_Attach_Call
2079      (Obj_Ref      : Node_Id;
2080       Flist_Ref    : Node_Id;
2081       With_Attach  : Node_Id)
2082       return Node_Id
2083    is
2084       Loc : constant Source_Ptr := Sloc (Obj_Ref);
2085
2086    begin
2087       --  Optimization: If the number of links is statically '0', don't
2088       --  call the attach_proc.
2089
2090       if Nkind (With_Attach) = N_Integer_Literal
2091         and then Intval (With_Attach) = Uint_0
2092       then
2093          return Make_Null_Statement (Loc);
2094       end if;
2095
2096       return
2097         Make_Procedure_Call_Statement (Loc,
2098           Name => New_Reference_To (RTE (RE_Attach_To_Final_List), Loc),
2099           Parameter_Associations => New_List (
2100             Flist_Ref,
2101             OK_Convert_To (RTE (RE_Finalizable), Obj_Ref),
2102             With_Attach));
2103    end Make_Attach_Call;
2104
2105    ----------------
2106    -- Make_Clean --
2107    ----------------
2108
2109    function Make_Clean
2110      (N                          : Node_Id;
2111       Clean                      : Entity_Id;
2112       Mark                       : Entity_Id;
2113       Flist                      : Entity_Id;
2114       Is_Task                    : Boolean;
2115       Is_Master                  : Boolean;
2116       Is_Protected_Subprogram    : Boolean;
2117       Is_Task_Allocation_Block   : Boolean;
2118       Is_Asynchronous_Call_Block : Boolean)
2119       return      Node_Id
2120    is
2121       Loc  : constant Source_Ptr := Sloc (Clean);
2122       Stmt : constant List_Id    := New_List;
2123
2124       Sbody        : Node_Id;
2125       Spec         : Node_Id;
2126       Name         : Node_Id;
2127       Param        : Node_Id;
2128       Unlock       : Node_Id;
2129       Param_Type   : Entity_Id;
2130       Pid          : Entity_Id := Empty;
2131       Cancel_Param : Entity_Id;
2132
2133    begin
2134       if Is_Task then
2135          if Restricted_Profile then
2136             Append_To
2137               (Stmt, Build_Runtime_Call (Loc, RE_Complete_Restricted_Task));
2138          else
2139             Append_To (Stmt, Build_Runtime_Call (Loc, RE_Complete_Task));
2140          end if;
2141
2142       elsif Is_Master then
2143          if Restrictions (No_Task_Hierarchy) = False then
2144             Append_To (Stmt, Build_Runtime_Call (Loc, RE_Complete_Master));
2145          end if;
2146
2147       elsif Is_Protected_Subprogram then
2148
2149          --  Add statements to the cleanup handler of the (ordinary)
2150          --  subprogram expanded to implement a protected subprogram,
2151          --  unlocking the protected object parameter and undeferring abortion.
2152          --  If this is a protected procedure, and the object contains
2153          --  entries, this also calls the entry service routine.
2154
2155          --  NOTE: This cleanup handler references _object, a parameter
2156          --        to the procedure.
2157
2158          --  Find the _object parameter representing the protected object.
2159
2160          Spec := Parent (Corresponding_Spec (N));
2161
2162          Param := First (Parameter_Specifications (Spec));
2163          loop
2164             Param_Type := Etype (Parameter_Type (Param));
2165
2166             if Ekind (Param_Type) = E_Record_Type then
2167                Pid := Corresponding_Concurrent_Type (Param_Type);
2168             end if;
2169
2170             exit when not Present (Param) or else Present (Pid);
2171             Next (Param);
2172          end loop;
2173
2174          pragma Assert (Present (Param));
2175
2176          --  If the associated protected object declares entries,
2177          --  a protected procedure has to service entry queues.
2178          --  In this case, add
2179
2180          --  Service_Entries (_object._object'Access);
2181
2182          --  _object is the record used to implement the protected object.
2183          --  It is a parameter to the protected subprogram.
2184
2185          if Nkind (Specification (N)) = N_Procedure_Specification
2186            and then Has_Entries (Pid)
2187          then
2188             if Abort_Allowed
2189               or else Restrictions (No_Entry_Queue) = False
2190               or else Number_Entries (Pid) > 1
2191             then
2192                Name := New_Reference_To (RTE (RE_Service_Entries), Loc);
2193             else
2194                Name := New_Reference_To (RTE (RE_Service_Entry), Loc);
2195             end if;
2196
2197             Append_To (Stmt,
2198               Make_Procedure_Call_Statement (Loc,
2199                 Name => Name,
2200                 Parameter_Associations => New_List (
2201                   Make_Attribute_Reference (Loc,
2202                     Prefix =>
2203                       Make_Selected_Component (Loc,
2204                         Prefix => New_Reference_To (
2205                           Defining_Identifier (Param), Loc),
2206                         Selector_Name =>
2207                           Make_Identifier (Loc, Name_uObject)),
2208                     Attribute_Name => Name_Unchecked_Access))));
2209          end if;
2210
2211          --  Unlock (_object._object'Access);
2212
2213          --  _object is the record used to implement the protected object.
2214          --  It is a parameter to the protected subprogram.
2215
2216          --  If the protected object is controlled (i.e it has entries or
2217          --  needs finalization for interrupt handling), call Unlock_Entries,
2218          --  except if the protected object follows the ravenscar profile, in
2219          --  which case call Unlock_Entry, otherwise call the simplified
2220          --  version, Unlock.
2221
2222          if Has_Entries (Pid)
2223            or else Has_Interrupt_Handler (Pid)
2224            or else (Has_Attach_Handler (Pid) and then not Restricted_Profile)
2225          then
2226             if Abort_Allowed
2227               or else Restrictions (No_Entry_Queue) = False
2228               or else Number_Entries (Pid) > 1
2229             then
2230                Unlock := New_Reference_To (RTE (RE_Unlock_Entries), Loc);
2231             else
2232                Unlock := New_Reference_To (RTE (RE_Unlock_Entry), Loc);
2233             end if;
2234
2235          else
2236             Unlock := New_Reference_To (RTE (RE_Unlock), Loc);
2237          end if;
2238
2239          Append_To (Stmt,
2240            Make_Procedure_Call_Statement (Loc,
2241              Name => Unlock,
2242              Parameter_Associations => New_List (
2243                Make_Attribute_Reference (Loc,
2244                  Prefix =>
2245                    Make_Selected_Component (Loc,
2246                      Prefix =>
2247                        New_Reference_To (Defining_Identifier (Param), Loc),
2248                      Selector_Name =>
2249                        Make_Identifier (Loc, Name_uObject)),
2250                  Attribute_Name => Name_Unchecked_Access))));
2251
2252          if Abort_Allowed then
2253             --  Abort_Undefer;
2254
2255             Append_To (Stmt,
2256               Make_Procedure_Call_Statement (Loc,
2257                 Name =>
2258                   New_Reference_To (
2259                     RTE (RE_Abort_Undefer), Loc),
2260                 Parameter_Associations => Empty_List));
2261          end if;
2262
2263       elsif Is_Task_Allocation_Block then
2264
2265          --  Add a call to Expunge_Unactivated_Tasks to the cleanup
2266          --  handler of a block created for the dynamic allocation of
2267          --  tasks:
2268
2269          --  Expunge_Unactivated_Tasks (_chain);
2270
2271          --  where _chain is the list of tasks created by the allocator
2272          --  but not yet activated. This list will be empty unless
2273          --  the block completes abnormally.
2274
2275          --  This only applies to dynamically allocated tasks;
2276          --  other unactivated tasks are completed by Complete_Task or
2277          --  Complete_Master.
2278
2279          --  NOTE: This cleanup handler references _chain, a local
2280          --        object.
2281
2282          Append_To (Stmt,
2283            Make_Procedure_Call_Statement (Loc,
2284              Name =>
2285                New_Reference_To (
2286                  RTE (RE_Expunge_Unactivated_Tasks), Loc),
2287              Parameter_Associations => New_List (
2288                New_Reference_To (Activation_Chain_Entity (N), Loc))));
2289
2290       elsif Is_Asynchronous_Call_Block then
2291
2292          --  Add a call to attempt to cancel the asynchronous entry call
2293          --  whenever the block containing the abortable part is exited.
2294
2295          --  NOTE: This cleanup handler references C, a local object
2296
2297          --  Get the argument to the Cancel procedure
2298          Cancel_Param := Entry_Cancel_Parameter (Entity (Identifier (N)));
2299
2300          --  If it is of type Communication_Block, this must be a
2301          --  protected entry call.
2302
2303          if Is_RTE (Etype (Cancel_Param), RE_Communication_Block) then
2304
2305             Append_To (Stmt,
2306
2307             --  if Enqueued (Cancel_Parameter) then
2308
2309               Make_Implicit_If_Statement (Clean,
2310                 Condition => Make_Function_Call (Loc,
2311                   Name => New_Reference_To (
2312                     RTE (RE_Enqueued), Loc),
2313                   Parameter_Associations => New_List (
2314                     New_Reference_To (Cancel_Param, Loc))),
2315                 Then_Statements => New_List (
2316
2317             --  Cancel_Protected_Entry_Call (Cancel_Param);
2318
2319                   Make_Procedure_Call_Statement (Loc,
2320                     Name => New_Reference_To (
2321                       RTE (RE_Cancel_Protected_Entry_Call), Loc),
2322                     Parameter_Associations => New_List (
2323                       New_Reference_To (Cancel_Param, Loc))))));
2324
2325          --  Asynchronous delay
2326
2327          elsif Is_RTE (Etype (Cancel_Param), RE_Delay_Block) then
2328             Append_To (Stmt,
2329               Make_Procedure_Call_Statement (Loc,
2330                 Name => New_Reference_To (RTE (RE_Cancel_Async_Delay), Loc),
2331                 Parameter_Associations => New_List (
2332                   Make_Attribute_Reference (Loc,
2333                     Prefix => New_Reference_To (Cancel_Param, Loc),
2334                     Attribute_Name => Name_Unchecked_Access))));
2335
2336          --  Task entry call
2337
2338          else
2339             --  Append call to Cancel_Task_Entry_Call (C);
2340
2341             Append_To (Stmt,
2342               Make_Procedure_Call_Statement (Loc,
2343                 Name => New_Reference_To (
2344                   RTE (RE_Cancel_Task_Entry_Call),
2345                   Loc),
2346                 Parameter_Associations => New_List (
2347                   New_Reference_To (Cancel_Param, Loc))));
2348
2349          end if;
2350       end if;
2351
2352       if Present (Flist) then
2353          Append_To (Stmt,
2354            Make_Procedure_Call_Statement (Loc,
2355              Name => New_Reference_To (RTE (RE_Finalize_List), Loc),
2356              Parameter_Associations => New_List (
2357                     New_Reference_To (Flist, Loc))));
2358       end if;
2359
2360       if Present (Mark) then
2361          Append_To (Stmt,
2362            Make_Procedure_Call_Statement (Loc,
2363              Name => New_Reference_To (RTE (RE_SS_Release), Loc),
2364              Parameter_Associations => New_List (
2365                     New_Reference_To (Mark, Loc))));
2366       end if;
2367
2368       Sbody :=
2369         Make_Subprogram_Body (Loc,
2370           Specification =>
2371             Make_Procedure_Specification (Loc,
2372               Defining_Unit_Name => Clean),
2373
2374           Declarations  => New_List,
2375
2376           Handled_Statement_Sequence =>
2377             Make_Handled_Sequence_Of_Statements (Loc,
2378               Statements => Stmt));
2379
2380       if Present (Flist) or else Is_Task or else Is_Master then
2381          Wrap_Cleanup_Procedure (Sbody);
2382       end if;
2383
2384       --  We do not want debug information for _Clean routines,
2385       --  since it just confuses the debugging operation unless
2386       --  we are debugging generated code.
2387
2388       if not Debug_Generated_Code then
2389          Set_Debug_Info_Off (Clean, True);
2390       end if;
2391
2392       return Sbody;
2393    end Make_Clean;
2394
2395    --------------------------
2396    -- Make_Deep_Array_Body --
2397    --------------------------
2398
2399    --  Array components are initialized and adjusted in the normal order
2400    --  and finalized in the reverse order. Exceptions are handled and
2401    --  Program_Error is re-raise in the Adjust and Finalize case
2402    --  (RM 7.6.1(12)). Generate the following code :
2403    --
2404    --  procedure Deep_<P>   --  with <P> being Initialize or Adjust or Finalize
2405    --   (L : in out Finalizable_Ptr;
2406    --    V : in out Typ)
2407    --  is
2408    --  begin
2409    --     for J1 in             Typ'First (1) .. Typ'Last (1) loop
2410    --               ^ reverse ^  --  in the finalization case
2411    --        ...
2412    --           for J2 in Typ'First (n) .. Typ'Last (n) loop
2413    --                 Make_<P>_Call (Typ, V (J1, .. , Jn), L, V);
2414    --           end loop;
2415    --        ...
2416    --     end loop;
2417    --  exception                                --  not in the
2418    --     when others => raise Program_Error;   --     Initialize case
2419    --  end Deep_<P>;
2420
2421    function Make_Deep_Array_Body
2422      (Prim : Final_Primitives;
2423       Typ  : Entity_Id)
2424       return List_Id
2425    is
2426       Loc : constant Source_Ptr := Sloc (Typ);
2427
2428       Index_List : constant List_Id := New_List;
2429       --  Stores the list of references to the indexes (one per dimension)
2430
2431       function One_Component return List_Id;
2432       --  Create one statement to initialize/adjust/finalize one array
2433       --  component, designated by a full set of indices.
2434
2435       function One_Dimension (N : Int) return List_Id;
2436       --  Create loop to deal with one dimension of the array. The single
2437       --  statement in the body of the loop initializes the inner dimensions if
2438       --  any, or else a single component.
2439
2440       -------------------
2441       -- One_Component --
2442       -------------------
2443
2444       function One_Component return List_Id is
2445          Comp_Typ : constant Entity_Id := Component_Type (Typ);
2446          Comp_Ref : constant Node_Id :=
2447                       Make_Indexed_Component (Loc,
2448                         Prefix      => Make_Identifier (Loc, Name_V),
2449                         Expressions => Index_List);
2450
2451       begin
2452          --  Set the etype of the component Reference, which is used to
2453          --  determine whether a conversion to a parent type is needed.
2454
2455          Set_Etype (Comp_Ref, Comp_Typ);
2456
2457          case Prim is
2458             when Initialize_Case =>
2459                return Make_Init_Call (Comp_Ref, Comp_Typ,
2460                         Make_Identifier (Loc, Name_L),
2461                         Make_Identifier (Loc, Name_B));
2462
2463             when Adjust_Case =>
2464                return Make_Adjust_Call (Comp_Ref, Comp_Typ,
2465                         Make_Identifier (Loc, Name_L),
2466                         Make_Identifier (Loc, Name_B));
2467
2468             when Finalize_Case =>
2469                return Make_Final_Call (Comp_Ref, Comp_Typ,
2470                         Make_Identifier (Loc, Name_B));
2471          end case;
2472       end One_Component;
2473
2474       -------------------
2475       -- One_Dimension --
2476       -------------------
2477
2478       function One_Dimension (N : Int) return List_Id is
2479          Index : Entity_Id;
2480
2481       begin
2482          if N > Number_Dimensions (Typ) then
2483             return One_Component;
2484
2485          else
2486             Index :=
2487               Make_Defining_Identifier (Loc, New_External_Name ('J', N));
2488
2489             Append_To (Index_List, New_Reference_To (Index, Loc));
2490
2491             return New_List (
2492               Make_Implicit_Loop_Statement (Typ,
2493                 Identifier => Empty,
2494                 Iteration_Scheme =>
2495                   Make_Iteration_Scheme (Loc,
2496                     Loop_Parameter_Specification =>
2497                       Make_Loop_Parameter_Specification (Loc,
2498                         Defining_Identifier => Index,
2499                         Discrete_Subtype_Definition =>
2500                           Make_Attribute_Reference (Loc,
2501                             Prefix => Make_Identifier (Loc, Name_V),
2502                             Attribute_Name  => Name_Range,
2503                             Expressions => New_List (
2504                               Make_Integer_Literal (Loc, N))),
2505                         Reverse_Present => Prim = Finalize_Case)),
2506                 Statements => One_Dimension (N + 1)));
2507          end if;
2508       end One_Dimension;
2509
2510    --  Start of processing for Make_Deep_Array_Body
2511
2512    begin
2513       return One_Dimension (1);
2514    end Make_Deep_Array_Body;
2515
2516    --------------------
2517    -- Make_Deep_Proc --
2518    --------------------
2519
2520    --  Generate:
2521    --    procedure DEEP_<prim>
2522    --      (L : IN OUT Finalizable_Ptr;    -- not for Finalize
2523    --       V : IN OUT <typ>;
2524    --       B : IN Short_Short_Integer) is
2525    --    begin
2526    --       <stmts>;
2527    --    exception                   --  Finalize and Adjust Cases only
2528    --       raise Program_Error;     --  idem
2529    --    end DEEP_<prim>;
2530
2531    function Make_Deep_Proc
2532      (Prim  : Final_Primitives;
2533       Typ   : Entity_Id;
2534       Stmts : List_Id)
2535       return Entity_Id
2536    is
2537       Loc       : constant Source_Ptr := Sloc (Typ);
2538       Formals   : List_Id;
2539       Proc_Name : Entity_Id;
2540       Handler   : List_Id := No_List;
2541       Type_B    : Entity_Id;
2542
2543    begin
2544       if Prim = Finalize_Case then
2545          Formals := New_List;
2546          Type_B := Standard_Boolean;
2547
2548       else
2549          Formals := New_List (
2550            Make_Parameter_Specification (Loc,
2551              Defining_Identifier => Make_Defining_Identifier (Loc, Name_L),
2552              In_Present          => True,
2553              Out_Present         => True,
2554              Parameter_Type      =>
2555                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
2556          Type_B := Standard_Short_Short_Integer;
2557       end if;
2558
2559       Append_To (Formals,
2560         Make_Parameter_Specification (Loc,
2561           Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
2562           In_Present          => True,
2563           Out_Present         => True,
2564           Parameter_Type      => New_Reference_To (Typ, Loc)));
2565
2566       Append_To (Formals,
2567         Make_Parameter_Specification (Loc,
2568           Defining_Identifier => Make_Defining_Identifier (Loc, Name_B),
2569           Parameter_Type      => New_Reference_To (Type_B, Loc)));
2570
2571       if Prim = Finalize_Case or else Prim = Adjust_Case then
2572          Handler := New_List (
2573            Make_Exception_Handler (Loc,
2574              Exception_Choices => New_List (Make_Others_Choice (Loc)),
2575              Statements        => New_List (
2576                Make_Raise_Program_Error (Loc,
2577                  Reason => PE_Finalize_Raised_Exception))));
2578       end if;
2579
2580       Proc_Name :=
2581         Make_Defining_Identifier (Loc,
2582           Chars => Make_TSS_Name (Typ, Deep_Name_Of (Prim)));
2583
2584       Discard_Node (
2585         Make_Subprogram_Body (Loc,
2586           Specification =>
2587             Make_Procedure_Specification (Loc,
2588               Defining_Unit_Name       => Proc_Name,
2589               Parameter_Specifications => Formals),
2590
2591           Declarations =>  Empty_List,
2592           Handled_Statement_Sequence =>
2593             Make_Handled_Sequence_Of_Statements (Loc,
2594               Statements         => Stmts,
2595               Exception_Handlers => Handler)));
2596
2597       return Proc_Name;
2598    end Make_Deep_Proc;
2599
2600    ---------------------------
2601    -- Make_Deep_Record_Body --
2602    ---------------------------
2603
2604    --  The Deep procedures call the appropriate Controlling proc on the
2605    --  the controller component. In the init case, it also attach the
2606    --  controller to the current finalization list.
2607
2608    function Make_Deep_Record_Body
2609      (Prim : Final_Primitives;
2610       Typ  : Entity_Id)
2611       return List_Id
2612    is
2613       Loc            : constant Source_Ptr := Sloc (Typ);
2614       Controller_Typ : Entity_Id;
2615       Obj_Ref        : constant Node_Id := Make_Identifier (Loc, Name_V);
2616       Controller_Ref : constant Node_Id :=
2617                          Make_Selected_Component (Loc,
2618                            Prefix        => Obj_Ref,
2619                            Selector_Name =>
2620                              Make_Identifier (Loc, Name_uController));
2621       Res            : constant List_Id := New_List;
2622
2623    begin
2624       if Is_Return_By_Reference_Type (Typ) then
2625          Controller_Typ := RTE (RE_Limited_Record_Controller);
2626       else
2627          Controller_Typ := RTE (RE_Record_Controller);
2628       end if;
2629
2630       case Prim is
2631          when Initialize_Case =>
2632             Append_List_To (Res,
2633               Make_Init_Call (
2634                 Ref          => Controller_Ref,
2635                 Typ          => Controller_Typ,
2636                 Flist_Ref    => Make_Identifier (Loc, Name_L),
2637                 With_Attach  => Make_Identifier (Loc, Name_B)));
2638
2639             --  When the type is also a controlled type by itself,
2640             --  Initialize it and attach it to the finalization chain
2641
2642             if Is_Controlled (Typ) then
2643                Append_To (Res,
2644                  Make_Procedure_Call_Statement (Loc,
2645                    Name => New_Reference_To (
2646                      Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
2647                    Parameter_Associations =>
2648                      New_List (New_Copy_Tree (Obj_Ref))));
2649
2650                Append_To (Res, Make_Attach_Call (
2651                  Obj_Ref      => New_Copy_Tree (Obj_Ref),
2652                  Flist_Ref    => Make_Identifier (Loc, Name_L),
2653                  With_Attach => Make_Identifier (Loc, Name_B)));
2654             end if;
2655
2656          when Adjust_Case =>
2657             Append_List_To (Res,
2658               Make_Adjust_Call (Controller_Ref, Controller_Typ,
2659                 Make_Identifier (Loc, Name_L),
2660                 Make_Identifier (Loc, Name_B)));
2661
2662             --  When the type is also a controlled type by itself,
2663             --  Adjust it it and attach it to the finalization chain
2664
2665             if Is_Controlled (Typ) then
2666                Append_To (Res,
2667                  Make_Procedure_Call_Statement (Loc,
2668                    Name => New_Reference_To (
2669                      Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
2670                    Parameter_Associations =>
2671                      New_List (New_Copy_Tree (Obj_Ref))));
2672
2673                Append_To (Res, Make_Attach_Call (
2674                  Obj_Ref      => New_Copy_Tree (Obj_Ref),
2675                  Flist_Ref    => Make_Identifier (Loc, Name_L),
2676                  With_Attach => Make_Identifier (Loc, Name_B)));
2677             end if;
2678
2679          when Finalize_Case =>
2680             if Is_Controlled (Typ) then
2681                Append_To (Res,
2682                  Make_Implicit_If_Statement (Obj_Ref,
2683                    Condition => Make_Identifier (Loc, Name_B),
2684                    Then_Statements => New_List (
2685                      Make_Procedure_Call_Statement (Loc,
2686                        Name => New_Reference_To (RTE (RE_Finalize_One), Loc),
2687                        Parameter_Associations => New_List (
2688                          OK_Convert_To (RTE (RE_Finalizable),
2689                            New_Copy_Tree (Obj_Ref))))),
2690
2691                    Else_Statements => New_List (
2692                      Make_Procedure_Call_Statement (Loc,
2693                        Name => New_Reference_To (
2694                          Find_Prim_Op (Typ, Name_Of (Prim)), Loc),
2695                        Parameter_Associations =>
2696                         New_List (New_Copy_Tree (Obj_Ref))))));
2697             end if;
2698
2699             Append_List_To (Res,
2700               Make_Final_Call (Controller_Ref, Controller_Typ,
2701                 Make_Identifier (Loc, Name_B)));
2702       end case;
2703       return Res;
2704    end Make_Deep_Record_Body;
2705
2706    ----------------------
2707    -- Make_Final_Call --
2708    ----------------------
2709
2710    function Make_Final_Call
2711      (Ref         : Node_Id;
2712       Typ         : Entity_Id;
2713       With_Detach : Node_Id)
2714       return        List_Id
2715    is
2716       Loc   : constant Source_Ptr := Sloc (Ref);
2717       Res   : constant List_Id    := New_List;
2718       Cref  : Node_Id;
2719       Cref2 : Node_Id;
2720       Proc  : Entity_Id;
2721       Utyp  : Entity_Id;
2722
2723    begin
2724       if Is_Class_Wide_Type (Typ) then
2725          Utyp := Root_Type (Typ);
2726          Cref := Ref;
2727
2728       elsif Is_Concurrent_Type (Typ) then
2729          Utyp := Corresponding_Record_Type (Typ);
2730          Cref := Convert_Concurrent (Ref, Typ);
2731
2732       elsif Is_Private_Type (Typ)
2733         and then Present (Full_View (Typ))
2734         and then Is_Concurrent_Type (Full_View (Typ))
2735       then
2736          Utyp := Corresponding_Record_Type (Full_View (Typ));
2737          Cref := Convert_Concurrent (Ref, Full_View (Typ));
2738       else
2739          Utyp := Typ;
2740          Cref := Ref;
2741       end if;
2742
2743       Utyp := Underlying_Type (Base_Type (Utyp));
2744       Set_Assignment_OK (Cref);
2745
2746       --  Deal with non-tagged derivation of private views
2747
2748       if Is_Untagged_Derivation (Typ) then
2749          Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
2750          Cref := Unchecked_Convert_To (Utyp, Cref);
2751          Set_Assignment_OK (Cref);
2752          --  To prevent problems with UC see 1.156 RH ???
2753       end if;
2754
2755       --  If the underlying_type is a subtype, we are dealing with
2756       --  the completion of a private type. We need to access
2757       --  the base type and generate a conversion to it.
2758
2759       if Utyp /= Base_Type (Utyp) then
2760          pragma Assert (Is_Private_Type (Typ));
2761          Utyp := Base_Type (Utyp);
2762          Cref := Unchecked_Convert_To (Utyp, Cref);
2763       end if;
2764
2765       --  Generate:
2766       --    Deep_Finalize (Ref, With_Detach);
2767
2768       if Has_Controlled_Component (Utyp)
2769         or else Is_Class_Wide_Type (Typ)
2770       then
2771          if Is_Tagged_Type (Utyp) then
2772             Proc := Find_Prim_Op (Utyp, TSS_Deep_Finalize);
2773          else
2774             Proc := TSS (Utyp, TSS_Deep_Finalize);
2775          end if;
2776
2777          Cref := Convert_View (Proc, Cref);
2778
2779          Append_To (Res,
2780            Make_Procedure_Call_Statement (Loc,
2781              Name => New_Reference_To (Proc, Loc),
2782              Parameter_Associations =>
2783                New_List (Cref, With_Detach)));
2784
2785       --  Generate:
2786       --    if With_Detach then
2787       --       Finalize_One (Ref);
2788       --    else
2789       --       Finalize (Ref);
2790       --    end if;
2791
2792       else
2793          Proc := Find_Prim_Op (Utyp, Name_Of (Finalize_Case));
2794
2795          if Chars (With_Detach) = Chars (Standard_True) then
2796             Append_To (Res,
2797               Make_Procedure_Call_Statement (Loc,
2798                 Name => New_Reference_To (RTE (RE_Finalize_One), Loc),
2799                 Parameter_Associations => New_List (
2800                   OK_Convert_To (RTE (RE_Finalizable), Cref))));
2801
2802          elsif Chars (With_Detach) = Chars (Standard_False) then
2803             Append_To (Res,
2804               Make_Procedure_Call_Statement (Loc,
2805                 Name => New_Reference_To (Proc, Loc),
2806                 Parameter_Associations =>
2807                   New_List (Convert_View (Proc, Cref))));
2808
2809          else
2810             Cref2 := New_Copy_Tree (Cref);
2811             Append_To (Res,
2812               Make_Implicit_If_Statement (Ref,
2813                 Condition => With_Detach,
2814                 Then_Statements => New_List (
2815                   Make_Procedure_Call_Statement (Loc,
2816                     Name => New_Reference_To (RTE (RE_Finalize_One), Loc),
2817                     Parameter_Associations => New_List (
2818                       OK_Convert_To (RTE (RE_Finalizable), Cref)))),
2819
2820                 Else_Statements => New_List (
2821                   Make_Procedure_Call_Statement (Loc,
2822                     Name => New_Reference_To (Proc, Loc),
2823                     Parameter_Associations =>
2824                       New_List (Convert_View (Proc, Cref2))))));
2825          end if;
2826       end if;
2827
2828       return Res;
2829    end Make_Final_Call;
2830
2831    --------------------
2832    -- Make_Init_Call --
2833    --------------------
2834
2835    function Make_Init_Call
2836      (Ref          : Node_Id;
2837       Typ          : Entity_Id;
2838       Flist_Ref    : Node_Id;
2839       With_Attach  : Node_Id)
2840       return         List_Id
2841    is
2842       Loc     : constant Source_Ptr := Sloc (Ref);
2843       Is_Conc : Boolean;
2844       Res     : constant List_Id := New_List;
2845       Proc    : Entity_Id;
2846       Utyp    : Entity_Id;
2847       Cref    : Node_Id;
2848       Cref2   : Node_Id;
2849       Attach  : Node_Id := With_Attach;
2850
2851    begin
2852       if Is_Concurrent_Type (Typ) then
2853          Is_Conc := True;
2854          Utyp    := Corresponding_Record_Type (Typ);
2855          Cref    := Convert_Concurrent (Ref, Typ);
2856
2857       elsif Is_Private_Type (Typ)
2858         and then Present (Full_View (Typ))
2859         and then Is_Concurrent_Type (Underlying_Type (Typ))
2860       then
2861          Is_Conc := True;
2862          Utyp    := Corresponding_Record_Type (Underlying_Type (Typ));
2863          Cref    := Convert_Concurrent (Ref, Underlying_Type (Typ));
2864
2865       else
2866          Is_Conc := False;
2867          Utyp    := Typ;
2868          Cref    := Ref;
2869       end if;
2870
2871       Utyp := Underlying_Type (Base_Type (Utyp));
2872
2873       Set_Assignment_OK (Cref);
2874
2875       --  Deal with non-tagged derivation of private views
2876
2877       if Is_Untagged_Derivation (Typ)
2878         and then not Is_Conc
2879       then
2880          Utyp := Underlying_Type (Root_Type (Base_Type (Typ)));
2881          Cref := Unchecked_Convert_To (Utyp, Cref);
2882          Set_Assignment_OK (Cref);
2883          --  To prevent problems with UC see 1.156 RH ???
2884       end if;
2885
2886       --  If the underlying_type is a subtype, we are dealing with
2887       --  the completion of a private type. We need to access
2888       --  the base type and generate a conversion to it.
2889
2890       if Utyp /= Base_Type (Utyp) then
2891          pragma Assert (Is_Private_Type (Typ));
2892          Utyp := Base_Type (Utyp);
2893          Cref := Unchecked_Convert_To (Utyp, Cref);
2894       end if;
2895
2896       --  We do not need to attach to one of the Global Final Lists
2897       --  the objects whose type is Finalize_Storage_Only
2898
2899       if Finalize_Storage_Only (Typ)
2900         and then (Global_Flist_Ref (Flist_Ref)
2901           or else Entity (Constant_Value (RTE (RE_Garbage_Collected)))
2902                   = Standard_True)
2903       then
2904          Attach := Make_Integer_Literal (Loc, 0);
2905       end if;
2906
2907       --  Generate:
2908       --    Deep_Initialize (Ref, Flist_Ref);
2909
2910       if Has_Controlled_Component (Utyp) then
2911          Proc := TSS (Utyp, Deep_Name_Of (Initialize_Case));
2912
2913          Cref := Convert_View (Proc, Cref, 2);
2914
2915          Append_To (Res,
2916            Make_Procedure_Call_Statement (Loc,
2917              Name => New_Reference_To (Proc, Loc),
2918              Parameter_Associations => New_List (
2919                Node1 => Flist_Ref,
2920                Node2 => Cref,
2921                Node3 => Attach)));
2922
2923       --  Generate:
2924       --    Attach_To_Final_List (Ref, Flist_Ref);
2925       --    Initialize (Ref);
2926
2927       else -- Is_Controlled (Utyp)
2928          Proc  := Find_Prim_Op (Utyp, Name_Of (Initialize_Case));
2929          Check_Visibly_Controlled (Initialize_Case, Typ, Proc, Cref);
2930
2931          Cref  := Convert_View (Proc, Cref);
2932          Cref2 := New_Copy_Tree (Cref);
2933
2934          Append_To (Res,
2935            Make_Procedure_Call_Statement (Loc,
2936            Name => New_Reference_To (Proc, Loc),
2937            Parameter_Associations => New_List (Cref2)));
2938
2939          Append_To (Res,
2940            Make_Attach_Call (Cref, Flist_Ref, Attach));
2941       end if;
2942
2943       return Res;
2944    end Make_Init_Call;
2945
2946    --------------------------
2947    -- Make_Transient_Block --
2948    --------------------------
2949
2950    --  If finalization is involved, this function just wraps the instruction
2951    --  into a block whose name is the transient block entity, and then
2952    --  Expand_Cleanup_Actions (called on the expansion of the handled
2953    --  sequence of statements will do the necessary expansions for
2954    --  cleanups).
2955
2956    function Make_Transient_Block
2957      (Loc    : Source_Ptr;
2958       Action : Node_Id)
2959       return   Node_Id
2960    is
2961       Flist  : constant Entity_Id := Finalization_Chain_Entity (Current_Scope);
2962       Decls  : constant List_Id   := New_List;
2963       Par    : constant Node_Id   := Parent (Action);
2964       Instrs : constant List_Id   := New_List (Action);
2965       Blk    : Node_Id;
2966
2967    begin
2968       --  Case where only secondary stack use is involved
2969
2970       if Uses_Sec_Stack (Current_Scope)
2971         and then No (Flist)
2972         and then Nkind (Action) /= N_Return_Statement
2973         and then Nkind (Par) /= N_Exception_Handler
2974       then
2975
2976          declare
2977             S  : Entity_Id;
2978             K  : Entity_Kind;
2979          begin
2980             S := Scope (Current_Scope);
2981             loop
2982                K := Ekind (S);
2983
2984                --  At the outer level, no need to release the sec stack
2985
2986                if S = Standard_Standard then
2987                   Set_Uses_Sec_Stack (Current_Scope, False);
2988                   exit;
2989
2990                --  In a function, only release the sec stack if the
2991                --  function does not return on the sec stack otherwise
2992                --  the result may be lost. The caller is responsible for
2993                --  releasing.
2994
2995                elsif K = E_Function then
2996                   Set_Uses_Sec_Stack (Current_Scope, False);
2997
2998                   if not Requires_Transient_Scope (Etype (S)) then
2999                      if not Functions_Return_By_DSP_On_Target then
3000                         Set_Uses_Sec_Stack (S, True);
3001                         Check_Restriction (No_Secondary_Stack, Action);
3002                      end if;
3003                   end if;
3004
3005                   exit;
3006
3007                --  In a loop or entry we should install a block encompassing
3008                --  all the construct. For now just release right away.
3009
3010                elsif K = E_Loop or else K = E_Entry then
3011                   exit;
3012
3013                --  In a procedure or a block, we release on exit of the
3014                --  procedure or block. ??? memory leak can be created by
3015                --  recursive calls.
3016
3017                elsif K = E_Procedure
3018                  or else K = E_Block
3019                then
3020                   if not Functions_Return_By_DSP_On_Target then
3021                      Set_Uses_Sec_Stack (S, True);
3022                      Check_Restriction (No_Secondary_Stack, Action);
3023                   end if;
3024
3025                   Set_Uses_Sec_Stack (Current_Scope, False);
3026                   exit;
3027
3028                else
3029                   S := Scope (S);
3030                end if;
3031             end loop;
3032          end;
3033       end if;
3034
3035       --  Insert actions stuck in the transient scopes as well as all
3036       --  freezing nodes needed by those actions
3037
3038       Insert_Actions_In_Scope_Around (Action);
3039
3040       declare
3041          Last_Inserted : Node_Id := Prev (Action);
3042
3043       begin
3044          if Present (Last_Inserted) then
3045             Freeze_All (First_Entity (Current_Scope), Last_Inserted);
3046          end if;
3047       end;
3048
3049       Blk :=
3050         Make_Block_Statement (Loc,
3051           Identifier => New_Reference_To (Current_Scope, Loc),
3052           Declarations => Decls,
3053           Handled_Statement_Sequence =>
3054             Make_Handled_Sequence_Of_Statements (Loc, Statements => Instrs),
3055           Has_Created_Identifier => True);
3056
3057       --  When the transient scope was established, we pushed the entry for
3058       --  the transient scope onto the scope stack, so that the scope was
3059       --  active for the installation of finalizable entities etc. Now we
3060       --  must remove this entry, since we have constructed a proper block.
3061
3062       Pop_Scope;
3063
3064       return Blk;
3065    end Make_Transient_Block;
3066
3067    ------------------------
3068    -- Node_To_Be_Wrapped --
3069    ------------------------
3070
3071    function Node_To_Be_Wrapped return Node_Id is
3072    begin
3073       return Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped;
3074    end Node_To_Be_Wrapped;
3075
3076    ----------------------------
3077    -- Set_Node_To_Be_Wrapped --
3078    ----------------------------
3079
3080    procedure Set_Node_To_Be_Wrapped (N : Node_Id) is
3081    begin
3082       Scope_Stack.Table (Scope_Stack.Last).Node_To_Be_Wrapped := N;
3083    end Set_Node_To_Be_Wrapped;
3084
3085    ----------------------------------
3086    -- Store_After_Actions_In_Scope --
3087    ----------------------------------
3088
3089    procedure Store_After_Actions_In_Scope (L : List_Id) is
3090       SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
3091
3092    begin
3093       if Present (SE.Actions_To_Be_Wrapped_After) then
3094          Insert_List_Before_And_Analyze (
3095           First (SE.Actions_To_Be_Wrapped_After), L);
3096
3097       else
3098          SE.Actions_To_Be_Wrapped_After := L;
3099
3100          if Is_List_Member (SE.Node_To_Be_Wrapped) then
3101             Set_Parent (L, Parent (SE.Node_To_Be_Wrapped));
3102          else
3103             Set_Parent (L, SE.Node_To_Be_Wrapped);
3104          end if;
3105
3106          Analyze_List (L);
3107       end if;
3108    end Store_After_Actions_In_Scope;
3109
3110    -----------------------------------
3111    -- Store_Before_Actions_In_Scope --
3112    -----------------------------------
3113
3114    procedure Store_Before_Actions_In_Scope (L : List_Id) is
3115       SE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
3116
3117    begin
3118       if Present (SE.Actions_To_Be_Wrapped_Before) then
3119          Insert_List_After_And_Analyze (
3120            Last (SE.Actions_To_Be_Wrapped_Before), L);
3121
3122       else
3123          SE.Actions_To_Be_Wrapped_Before := L;
3124
3125          if Is_List_Member (SE.Node_To_Be_Wrapped) then
3126             Set_Parent (L, Parent (SE.Node_To_Be_Wrapped));
3127          else
3128             Set_Parent (L, SE.Node_To_Be_Wrapped);
3129          end if;
3130
3131          Analyze_List (L);
3132       end if;
3133    end Store_Before_Actions_In_Scope;
3134
3135    --------------------------------
3136    -- Wrap_Transient_Declaration --
3137    --------------------------------
3138
3139    --  If a transient scope has been established during the processing of the
3140    --  Expression of an Object_Declaration, it is not possible to wrap the
3141    --  declaration into a transient block as usual case, otherwise the object
3142    --  would be itself declared in the wrong scope. Therefore, all entities (if
3143    --  any) defined in the transient block are moved to the proper enclosing
3144    --  scope, furthermore, if they are controlled variables they are finalized
3145    --  right after the declaration. The finalization list of the transient
3146    --  scope is defined as a renaming of the enclosing one so during their
3147    --  initialization they will be attached to the proper finalization
3148    --  list. For instance, the following declaration :
3149
3150    --        X : Typ := F (G (A), G (B));
3151
3152    --  (where G(A) and G(B) return controlled values, expanded as _v1 and _v2)
3153    --  is expanded into :
3154
3155    --    _local_final_list_1 : Finalizable_Ptr;
3156    --    X : Typ := [ complex Expression-Action ];
3157    --    Finalize_One(_v1);
3158    --    Finalize_One (_v2);
3159
3160    procedure Wrap_Transient_Declaration (N : Node_Id) is
3161       S           : Entity_Id;
3162       LC          : Entity_Id := Empty;
3163       Nodes       : List_Id;
3164       Loc         : constant Source_Ptr := Sloc (N);
3165       Enclosing_S : Entity_Id;
3166       Uses_SS     : Boolean;
3167       Next_N      : constant Node_Id := Next (N);
3168
3169    begin
3170       S := Current_Scope;
3171       Enclosing_S := Scope (S);
3172
3173       --  Insert Actions kept in the Scope stack
3174
3175       Insert_Actions_In_Scope_Around (N);
3176
3177       --  If the declaration is consuming some secondary stack, mark the
3178       --  Enclosing scope appropriately.
3179
3180       Uses_SS := Uses_Sec_Stack (S);
3181       Pop_Scope;
3182
3183       --  Create a List controller and rename the final list to be its
3184       --  internal final pointer:
3185       --       Lxxx : Simple_List_Controller;
3186       --       Fxxx : Finalizable_Ptr renames Lxxx.F;
3187
3188       if Present (Finalization_Chain_Entity (S)) then
3189          LC := Make_Defining_Identifier (Loc, New_Internal_Name ('L'));
3190
3191          Nodes := New_List (
3192            Make_Object_Declaration (Loc,
3193              Defining_Identifier => LC,
3194              Object_Definition   =>
3195                New_Reference_To (RTE (RE_Simple_List_Controller), Loc)),
3196
3197            Make_Object_Renaming_Declaration (Loc,
3198              Defining_Identifier => Finalization_Chain_Entity (S),
3199              Subtype_Mark => New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3200              Name =>
3201                Make_Selected_Component (Loc,
3202                  Prefix        => New_Reference_To (LC, Loc),
3203                  Selector_Name => Make_Identifier (Loc, Name_F))));
3204
3205          --  Put the declaration at the beginning of the declaration part
3206          --  to make sure it will be before all other actions that have been
3207          --  inserted before N.
3208
3209          Insert_List_Before_And_Analyze (First (List_Containing (N)), Nodes);
3210
3211          --  Generate the Finalization calls by finalizing the list
3212          --  controller right away. It will be re-finalized on scope
3213          --  exit but it doesn't matter. It cannot be done when the
3214          --  call initializes a renaming object though because in this
3215          --  case, the object becomes a pointer to the temporary and thus
3216          --  increases its life span.
3217
3218          if Nkind (N) = N_Object_Renaming_Declaration
3219            and then Controlled_Type (Etype (Defining_Identifier (N)))
3220          then
3221             null;
3222
3223          else
3224             Nodes :=
3225               Make_Final_Call (
3226                    Ref         => New_Reference_To (LC, Loc),
3227                    Typ         => Etype (LC),
3228                    With_Detach => New_Reference_To (Standard_False, Loc));
3229             if Present (Next_N) then
3230                Insert_List_Before_And_Analyze (Next_N, Nodes);
3231             else
3232                Append_List_To (List_Containing (N), Nodes);
3233             end if;
3234          end if;
3235       end if;
3236
3237       --  Put the local entities back in the enclosing scope, and set the
3238       --  Is_Public flag appropriately.
3239
3240       Transfer_Entities (S, Enclosing_S);
3241
3242       --  Mark the enclosing dynamic scope so that the sec stack will be
3243       --  released upon its exit unless this is a function that returns on
3244       --  the sec stack in which case this will be done by the caller.
3245
3246       if Uses_SS then
3247          S := Enclosing_Dynamic_Scope (S);
3248
3249          if Ekind (S) = E_Function
3250            and then Requires_Transient_Scope (Etype (S))
3251          then
3252             null;
3253          else
3254             Set_Uses_Sec_Stack (S);
3255             Check_Restriction (No_Secondary_Stack, N);
3256          end if;
3257       end if;
3258    end Wrap_Transient_Declaration;
3259
3260    -------------------------------
3261    -- Wrap_Transient_Expression --
3262    -------------------------------
3263
3264    --  Insert actions before <Expression>:
3265
3266    --  (lines marked with <CTRL> are expanded only in presence of Controlled
3267    --   objects needing finalization)
3268
3269    --     _E : Etyp;
3270    --     declare
3271    --        _M : constant Mark_Id := SS_Mark;
3272    --        Local_Final_List : System.FI.Finalizable_Ptr;    <CTRL>
3273
3274    --        procedure _Clean is
3275    --        begin
3276    --           Abort_Defer;
3277    --           System.FI.Finalize_List (Local_Final_List);   <CTRL>
3278    --           SS_Release (M);
3279    --           Abort_Undefer;
3280    --        end _Clean;
3281
3282    --     begin
3283    --        _E := <Expression>;
3284    --     at end
3285    --        _Clean;
3286    --     end;
3287
3288    --    then expression is replaced by _E
3289
3290    procedure Wrap_Transient_Expression (N : Node_Id) is
3291       Loc  : constant Source_Ptr := Sloc (N);
3292       E    : constant Entity_Id :=
3293                Make_Defining_Identifier (Loc, New_Internal_Name ('E'));
3294       Etyp : constant Entity_Id := Etype (N);
3295
3296    begin
3297       Insert_Actions (N, New_List (
3298         Make_Object_Declaration (Loc,
3299           Defining_Identifier => E,
3300           Object_Definition   => New_Reference_To (Etyp, Loc)),
3301
3302         Make_Transient_Block (Loc,
3303           Action =>
3304             Make_Assignment_Statement (Loc,
3305               Name       => New_Reference_To (E, Loc),
3306               Expression => Relocate_Node (N)))));
3307
3308       Rewrite (N, New_Reference_To (E, Loc));
3309       Analyze_And_Resolve (N, Etyp);
3310    end Wrap_Transient_Expression;
3311
3312    ------------------------------
3313    -- Wrap_Transient_Statement --
3314    ------------------------------
3315
3316    --  Transform <Instruction> into
3317
3318    --  (lines marked with <CTRL> are expanded only in presence of Controlled
3319    --   objects needing finalization)
3320
3321    --    declare
3322    --       _M : Mark_Id := SS_Mark;
3323    --       Local_Final_List : System.FI.Finalizable_Ptr ;    <CTRL>
3324
3325    --       procedure _Clean is
3326    --       begin
3327    --          Abort_Defer;
3328    --          System.FI.Finalize_List (Local_Final_List);    <CTRL>
3329    --          SS_Release (_M);
3330    --          Abort_Undefer;
3331    --       end _Clean;
3332
3333    --    begin
3334    --       <Instr uction>;
3335    --    at end
3336    --       _Clean;
3337    --    end;
3338
3339    procedure Wrap_Transient_Statement (N : Node_Id) is
3340       Loc           : constant Source_Ptr := Sloc (N);
3341       New_Statement : constant Node_Id := Relocate_Node (N);
3342
3343    begin
3344       Rewrite (N, Make_Transient_Block (Loc, New_Statement));
3345
3346       --  With the scope stack back to normal, we can call analyze on the
3347       --  resulting block. At this point, the transient scope is being
3348       --  treated like a perfectly normal scope, so there is nothing
3349       --  special about it.
3350
3351       --  Note: Wrap_Transient_Statement is called with the node already
3352       --  analyzed (i.e. Analyzed (N) is True). This is important, since
3353       --  otherwise we would get a recursive processing of the node when
3354       --  we do this Analyze call.
3355
3356       Analyze (N);
3357    end Wrap_Transient_Statement;
3358
3359 end Exp_Ch7;