OSDN Git Service

2010-06-17 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch3.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 3                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2009, 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 3,  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 COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Einfo;    use Einfo;
29 with Errout;   use Errout;
30 with Exp_Aggr; use Exp_Aggr;
31 with Exp_Atag; use Exp_Atag;
32 with Exp_Ch4;  use Exp_Ch4;
33 with Exp_Ch6;  use Exp_Ch6;
34 with Exp_Ch7;  use Exp_Ch7;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Ch11; use Exp_Ch11;
37 with Exp_Disp; use Exp_Disp;
38 with Exp_Dist; use Exp_Dist;
39 with Exp_Smem; use Exp_Smem;
40 with Exp_Strm; use Exp_Strm;
41 with Exp_Tss;  use Exp_Tss;
42 with Exp_Util; use Exp_Util;
43 with Freeze;   use Freeze;
44 with Nlists;   use Nlists;
45 with Namet;    use Namet;
46 with Nmake;    use Nmake;
47 with Opt;      use Opt;
48 with Restrict; use Restrict;
49 with Rident;   use Rident;
50 with Rtsfind;  use Rtsfind;
51 with Sem;      use Sem;
52 with Sem_Aux;  use Sem_Aux;
53 with Sem_Attr; use Sem_Attr;
54 with Sem_Cat;  use Sem_Cat;
55 with Sem_Ch3;  use Sem_Ch3;
56 with Sem_Ch6;  use Sem_Ch6;
57 with Sem_Ch8;  use Sem_Ch8;
58 with Sem_Disp; use Sem_Disp;
59 with Sem_Eval; use Sem_Eval;
60 with Sem_Mech; use Sem_Mech;
61 with Sem_Res;  use Sem_Res;
62 with Sem_SCIL; use Sem_SCIL;
63 with Sem_Type; use Sem_Type;
64 with Sem_Util; use Sem_Util;
65 with Sinfo;    use Sinfo;
66 with Stand;    use Stand;
67 with Snames;   use Snames;
68 with Targparm; use Targparm;
69 with Tbuild;   use Tbuild;
70 with Ttypes;   use Ttypes;
71 with Validsw;  use Validsw;
72
73 package body Exp_Ch3 is
74
75    -----------------------
76    -- Local Subprograms --
77    -----------------------
78
79    function Add_Final_Chain (Def_Id : Entity_Id) return Entity_Id;
80    --  Add the declaration of a finalization list to the freeze actions for
81    --  Def_Id, and return its defining identifier.
82
83    procedure Adjust_Discriminants (Rtype : Entity_Id);
84    --  This is used when freezing a record type. It attempts to construct
85    --  more restrictive subtypes for discriminants so that the max size of
86    --  the record can be calculated more accurately. See the body of this
87    --  procedure for details.
88
89    procedure Build_Array_Init_Proc (A_Type : Entity_Id; Nod : Node_Id);
90    --  Build initialization procedure for given array type. Nod is a node
91    --  used for attachment of any actions required in its construction.
92    --  It also supplies the source location used for the procedure.
93
94    function Build_Discriminant_Formals
95      (Rec_Id : Entity_Id;
96       Use_Dl : Boolean) return List_Id;
97    --  This function uses the discriminants of a type to build a list of
98    --  formal parameters, used in Build_Init_Procedure among other places.
99    --  If the flag Use_Dl is set, the list is built using the already
100    --  defined discriminals of the type, as is the case for concurrent
101    --  types with discriminants. Otherwise new identifiers are created,
102    --  with the source names of the discriminants.
103
104    function Build_Equivalent_Array_Aggregate (T : Entity_Id) return Node_Id;
105    --  This function builds a static aggregate that can serve as the initial
106    --  value for an array type whose bounds are static, and whose component
107    --  type is a composite type that has a static equivalent aggregate.
108    --  The equivalent array aggregate is used both for object initialization
109    --  and for component initialization, when used in the following function.
110
111    function Build_Equivalent_Record_Aggregate (T : Entity_Id) return Node_Id;
112    --  This function builds a static aggregate that can serve as the initial
113    --  value for a record type whose components are scalar and initialized
114    --  with compile-time values, or arrays with similar initialization or
115    --  defaults. When possible, initialization of an object of the type can
116    --  be achieved by using a copy of the aggregate as an initial value, thus
117    --  removing the implicit call that would otherwise constitute elaboration
118    --  code.
119
120    function Build_Master_Renaming
121      (N : Node_Id;
122       T : Entity_Id) return Entity_Id;
123    --  If the designated type of an access type is a task type or contains
124    --  tasks, we make sure that a _Master variable is declared in the current
125    --  scope, and then declare a renaming for it:
126    --
127    --    atypeM : Master_Id renames _Master;
128    --
129    --  where atyp is the name of the access type. This declaration is used when
130    --  an allocator for the access type is expanded. The node is the full
131    --  declaration of the designated type that contains tasks. The renaming
132    --  declaration is inserted before N, and after the Master declaration.
133
134    procedure Build_Record_Init_Proc (N : Node_Id; Pe : Entity_Id);
135    --  Build record initialization procedure. N is the type declaration
136    --  node, and Pe is the corresponding entity for the record type.
137
138    procedure Build_Slice_Assignment (Typ : Entity_Id);
139    --  Build assignment procedure for one-dimensional arrays of controlled
140    --  types. Other array and slice assignments are expanded in-line, but
141    --  the code expansion for controlled components (when control actions
142    --  are active) can lead to very large blocks that GCC3 handles poorly.
143
144    procedure Build_Variant_Record_Equality (Typ  : Entity_Id);
145    --  Create An Equality function for the non-tagged variant record 'Typ'
146    --  and attach it to the TSS list
147
148    procedure Check_Stream_Attributes (Typ : Entity_Id);
149    --  Check that if a limited extension has a parent with user-defined stream
150    --  attributes, and does not itself have user-defined stream-attributes,
151    --  then any limited component of the extension also has the corresponding
152    --  user-defined stream attributes.
153
154    procedure Clean_Task_Names
155      (Typ     : Entity_Id;
156       Proc_Id : Entity_Id);
157    --  If an initialization procedure includes calls to generate names
158    --  for task subcomponents, indicate that secondary stack cleanup is
159    --  needed after an initialization. Typ is the component type, and Proc_Id
160    --  the initialization procedure for the enclosing composite type.
161
162    procedure Expand_Tagged_Root (T : Entity_Id);
163    --  Add a field _Tag at the beginning of the record. This field carries
164    --  the value of the access to the Dispatch table. This procedure is only
165    --  called on root type, the _Tag field being inherited by the descendants.
166
167    procedure Expand_Record_Controller (T : Entity_Id);
168    --  T must be a record type that Has_Controlled_Component. Add a field
169    --  _controller of type Record_Controller or Limited_Record_Controller
170    --  in the record T.
171
172    procedure Expand_Freeze_Array_Type (N : Node_Id);
173    --  Freeze an array type. Deals with building the initialization procedure,
174    --  creating the packed array type for a packed array and also with the
175    --  creation of the controlling procedures for the controlled case. The
176    --  argument N is the N_Freeze_Entity node for the type.
177
178    procedure Expand_Freeze_Enumeration_Type (N : Node_Id);
179    --  Freeze enumeration type with non-standard representation. Builds the
180    --  array and function needed to convert between enumeration pos and
181    --  enumeration representation values. N is the N_Freeze_Entity node
182    --  for the type.
183
184    procedure Expand_Freeze_Record_Type (N : Node_Id);
185    --  Freeze record type. Builds all necessary discriminant checking
186    --  and other ancillary functions, and builds dispatch tables where
187    --  needed. The argument N is the N_Freeze_Entity node. This processing
188    --  applies only to E_Record_Type entities, not to class wide types,
189    --  record subtypes, or private types.
190
191    procedure Freeze_Stream_Operations (N : Node_Id; Typ : Entity_Id);
192    --  Treat user-defined stream operations as renaming_as_body if the
193    --  subprogram they rename is not frozen when the type is frozen.
194
195    procedure Initialization_Warning (E : Entity_Id);
196    --  If static elaboration of the package is requested, indicate
197    --  when a type does meet the conditions for static initialization. If
198    --  E is a type, it has components that have no static initialization.
199    --  if E is an entity, its initial expression is not compile-time known.
200
201    function Init_Formals (Typ : Entity_Id) return List_Id;
202    --  This function builds the list of formals for an initialization routine.
203    --  The first formal is always _Init with the given type. For task value
204    --  record types and types containing tasks, three additional formals are
205    --  added:
206    --
207    --    _Master    : Master_Id
208    --    _Chain     : in out Activation_Chain
209    --    _Task_Name : String
210    --
211    --  The caller must append additional entries for discriminants if required.
212
213    function In_Runtime (E : Entity_Id) return Boolean;
214    --  Check if E is defined in the RTL (in a child of Ada or System). Used
215    --  to avoid to bring in the overhead of _Input, _Output for tagged types.
216
217    function Is_Variable_Size_Record (E : Entity_Id) return Boolean;
218    --  Returns true if E has variable size components
219
220    function Make_Eq_Case
221      (E     : Entity_Id;
222       CL    : Node_Id;
223       Discr : Entity_Id := Empty) return List_Id;
224    --  Building block for variant record equality. Defined to share the code
225    --  between the tagged and non-tagged case. Given a Component_List node CL,
226    --  it generates an 'if' followed by a 'case' statement that compares all
227    --  components of local temporaries named X and Y (that are declared as
228    --  formals at some upper level). E provides the Sloc to be used for the
229    --  generated code. Discr is used as the case statement switch in the case
230    --  of Unchecked_Union equality.
231
232    function Make_Eq_If
233      (E : Entity_Id;
234       L : List_Id) return Node_Id;
235    --  Building block for variant record equality. Defined to share the code
236    --  between the tagged and non-tagged case. Given the list of components
237    --  (or discriminants) L, it generates a return statement that compares all
238    --  components of local temporaries named X and Y (that are declared as
239    --  formals at some upper level). E provides the Sloc to be used for the
240    --  generated code.
241
242    procedure Make_Predefined_Primitive_Specs
243      (Tag_Typ     : Entity_Id;
244       Predef_List : out List_Id;
245       Renamed_Eq  : out Entity_Id);
246    --  Create a list with the specs of the predefined primitive operations.
247    --  For tagged types that are interfaces all these primitives are defined
248    --  abstract.
249    --
250    --  The following entries are present for all tagged types, and provide
251    --  the results of the corresponding attribute applied to the object.
252    --  Dispatching is required in general, since the result of the attribute
253    --  will vary with the actual object subtype.
254    --
255    --     _alignment     provides result of 'Alignment attribute
256    --     _size          provides result of 'Size attribute
257    --     typSR          provides result of 'Read attribute
258    --     typSW          provides result of 'Write attribute
259    --     typSI          provides result of 'Input attribute
260    --     typSO          provides result of 'Output attribute
261    --
262    --  The following entries are additionally present for non-limited tagged
263    --  types, and implement additional dispatching operations for predefined
264    --  operations:
265    --
266    --     _equality      implements "=" operator
267    --     _assign        implements assignment operation
268    --     typDF          implements deep finalization
269    --     typDA          implements deep adjust
270    --
271    --  The latter two are empty procedures unless the type contains some
272    --  controlled components that require finalization actions (the deep
273    --  in the name refers to the fact that the action applies to components).
274    --
275    --  The list is returned in Predef_List. The Parameter Renamed_Eq either
276    --  returns the value Empty, or else the defining unit name for the
277    --  predefined equality function in the case where the type has a primitive
278    --  operation that is a renaming of predefined equality (but only if there
279    --  is also an overriding user-defined equality function). The returned
280    --  Renamed_Eq will be passed to the corresponding parameter of
281    --  Predefined_Primitive_Bodies.
282
283    function Has_New_Non_Standard_Rep (T : Entity_Id) return Boolean;
284    --  returns True if there are representation clauses for type T that are not
285    --  inherited. If the result is false, the init_proc and the discriminant
286    --  checking functions of the parent can be reused by a derived type.
287
288    procedure Make_Controlling_Function_Wrappers
289      (Tag_Typ   : Entity_Id;
290       Decl_List : out List_Id;
291       Body_List : out List_Id);
292    --  Ada 2005 (AI-391): Makes specs and bodies for the wrapper functions
293    --  associated with inherited functions with controlling results which
294    --  are not overridden. The body of each wrapper function consists solely
295    --  of a return statement whose expression is an extension aggregate
296    --  invoking the inherited subprogram's parent subprogram and extended
297    --  with a null association list.
298
299    procedure Make_Null_Procedure_Specs
300      (Tag_Typ   : Entity_Id;
301       Decl_List : out List_Id);
302    --  Ada 2005 (AI-251): Makes specs for null procedures associated with any
303    --  null procedures inherited from an interface type that have not been
304    --  overridden. Only one null procedure will be created for a given set of
305    --  inherited null procedures with homographic profiles.
306
307    function Predef_Spec_Or_Body
308      (Loc      : Source_Ptr;
309       Tag_Typ  : Entity_Id;
310       Name     : Name_Id;
311       Profile  : List_Id;
312       Ret_Type : Entity_Id := Empty;
313       For_Body : Boolean   := False) return Node_Id;
314    --  This function generates the appropriate expansion for a predefined
315    --  primitive operation specified by its name, parameter profile and
316    --  return type (Empty means this is a procedure). If For_Body is false,
317    --  then the returned node is a subprogram declaration. If For_Body is
318    --  true, then the returned node is a empty subprogram body containing
319    --  no declarations and no statements.
320
321    function Predef_Stream_Attr_Spec
322      (Loc      : Source_Ptr;
323       Tag_Typ  : Entity_Id;
324       Name     : TSS_Name_Type;
325       For_Body : Boolean := False) return Node_Id;
326    --  Specialized version of Predef_Spec_Or_Body that apply to read, write,
327    --  input and output attribute whose specs are constructed in Exp_Strm.
328
329    function Predef_Deep_Spec
330      (Loc      : Source_Ptr;
331       Tag_Typ  : Entity_Id;
332       Name     : TSS_Name_Type;
333       For_Body : Boolean := False) return Node_Id;
334    --  Specialized version of Predef_Spec_Or_Body that apply to _deep_adjust
335    --  and _deep_finalize
336
337    function Predefined_Primitive_Bodies
338      (Tag_Typ    : Entity_Id;
339       Renamed_Eq : Entity_Id) return List_Id;
340    --  Create the bodies of the predefined primitives that are described in
341    --  Predefined_Primitive_Specs. When not empty, Renamed_Eq must denote
342    --  the defining unit name of the type's predefined equality as returned
343    --  by Make_Predefined_Primitive_Specs.
344
345    function Predefined_Primitive_Freeze (Tag_Typ : Entity_Id) return List_Id;
346    --  Freeze entities of all predefined primitive operations. This is needed
347    --  because the bodies of these operations do not normally do any freezing.
348
349    function Stream_Operation_OK
350      (Typ       : Entity_Id;
351       Operation : TSS_Name_Type) return Boolean;
352    --  Check whether the named stream operation must be emitted for a given
353    --  type. The rules for inheritance of stream attributes by type extensions
354    --  are enforced by this function. Furthermore, various restrictions prevent
355    --  the generation of these operations, as a useful optimization or for
356    --  certification purposes.
357
358    ---------------------
359    -- Add_Final_Chain --
360    ---------------------
361
362    function Add_Final_Chain (Def_Id : Entity_Id) return Entity_Id is
363       Loc   : constant Source_Ptr := Sloc (Def_Id);
364       Flist : Entity_Id;
365
366    begin
367       Flist :=
368         Make_Defining_Identifier (Loc,
369           New_External_Name (Chars (Def_Id), 'L'));
370
371       Append_Freeze_Action (Def_Id,
372         Make_Object_Declaration (Loc,
373           Defining_Identifier => Flist,
374           Object_Definition   =>
375             New_Reference_To (RTE (RE_List_Controller), Loc)));
376
377       return Flist;
378    end Add_Final_Chain;
379
380    --------------------------
381    -- Adjust_Discriminants --
382    --------------------------
383
384    --  This procedure attempts to define subtypes for discriminants that are
385    --  more restrictive than those declared. Such a replacement is possible if
386    --  we can demonstrate that values outside the restricted range would cause
387    --  constraint errors in any case. The advantage of restricting the
388    --  discriminant types in this way is that the maximum size of the variant
389    --  record can be calculated more conservatively.
390
391    --  An example of a situation in which we can perform this type of
392    --  restriction is the following:
393
394    --    subtype B is range 1 .. 10;
395    --    type Q is array (B range <>) of Integer;
396
397    --    type V (N : Natural) is record
398    --       C : Q (1 .. N);
399    --    end record;
400
401    --  In this situation, we can restrict the upper bound of N to 10, since
402    --  any larger value would cause a constraint error in any case.
403
404    --  There are many situations in which such restriction is possible, but
405    --  for now, we just look for cases like the above, where the component
406    --  in question is a one dimensional array whose upper bound is one of
407    --  the record discriminants. Also the component must not be part of
408    --  any variant part, since then the component does not always exist.
409
410    procedure Adjust_Discriminants (Rtype : Entity_Id) is
411       Loc   : constant Source_Ptr := Sloc (Rtype);
412       Comp  : Entity_Id;
413       Ctyp  : Entity_Id;
414       Ityp  : Entity_Id;
415       Lo    : Node_Id;
416       Hi    : Node_Id;
417       P     : Node_Id;
418       Loval : Uint;
419       Discr : Entity_Id;
420       Dtyp  : Entity_Id;
421       Dhi   : Node_Id;
422       Dhiv  : Uint;
423       Ahi   : Node_Id;
424       Ahiv  : Uint;
425       Tnn   : Entity_Id;
426
427    begin
428       Comp := First_Component (Rtype);
429       while Present (Comp) loop
430
431          --  If our parent is a variant, quit, we do not look at components
432          --  that are in variant parts, because they may not always exist.
433
434          P := Parent (Comp);   -- component declaration
435          P := Parent (P);      -- component list
436
437          exit when Nkind (Parent (P)) = N_Variant;
438
439          --  We are looking for a one dimensional array type
440
441          Ctyp := Etype (Comp);
442
443          if not Is_Array_Type (Ctyp)
444            or else Number_Dimensions (Ctyp) > 1
445          then
446             goto Continue;
447          end if;
448
449          --  The lower bound must be constant, and the upper bound is a
450          --  discriminant (which is a discriminant of the current record).
451
452          Ityp := Etype (First_Index (Ctyp));
453          Lo := Type_Low_Bound (Ityp);
454          Hi := Type_High_Bound (Ityp);
455
456          if not Compile_Time_Known_Value (Lo)
457            or else Nkind (Hi) /= N_Identifier
458            or else No (Entity (Hi))
459            or else Ekind (Entity (Hi)) /= E_Discriminant
460          then
461             goto Continue;
462          end if;
463
464          --  We have an array with appropriate bounds
465
466          Loval := Expr_Value (Lo);
467          Discr := Entity (Hi);
468          Dtyp  := Etype (Discr);
469
470          --  See if the discriminant has a known upper bound
471
472          Dhi := Type_High_Bound (Dtyp);
473
474          if not Compile_Time_Known_Value (Dhi) then
475             goto Continue;
476          end if;
477
478          Dhiv := Expr_Value (Dhi);
479
480          --  See if base type of component array has known upper bound
481
482          Ahi := Type_High_Bound (Etype (First_Index (Base_Type (Ctyp))));
483
484          if not Compile_Time_Known_Value (Ahi) then
485             goto Continue;
486          end if;
487
488          Ahiv := Expr_Value (Ahi);
489
490          --  The condition for doing the restriction is that the high bound
491          --  of the discriminant is greater than the low bound of the array,
492          --  and is also greater than the high bound of the base type index.
493
494          if Dhiv > Loval and then Dhiv > Ahiv then
495
496             --  We can reset the upper bound of the discriminant type to
497             --  whichever is larger, the low bound of the component, or
498             --  the high bound of the base type array index.
499
500             --  We build a subtype that is declared as
501
502             --     subtype Tnn is discr_type range discr_type'First .. max;
503
504             --  And insert this declaration into the tree. The type of the
505             --  discriminant is then reset to this more restricted subtype.
506
507             Tnn := Make_Temporary (Loc, 'T');
508
509             Insert_Action (Declaration_Node (Rtype),
510               Make_Subtype_Declaration (Loc,
511                 Defining_Identifier => Tnn,
512                 Subtype_Indication =>
513                   Make_Subtype_Indication (Loc,
514                     Subtype_Mark => New_Occurrence_Of (Dtyp, Loc),
515                     Constraint   =>
516                       Make_Range_Constraint (Loc,
517                         Range_Expression =>
518                           Make_Range (Loc,
519                             Low_Bound =>
520                               Make_Attribute_Reference (Loc,
521                                 Attribute_Name => Name_First,
522                                 Prefix => New_Occurrence_Of (Dtyp, Loc)),
523                             High_Bound =>
524                               Make_Integer_Literal (Loc,
525                                 Intval => UI_Max (Loval, Ahiv)))))));
526
527             Set_Etype (Discr, Tnn);
528          end if;
529
530       <<Continue>>
531          Next_Component (Comp);
532       end loop;
533    end Adjust_Discriminants;
534
535    ---------------------------
536    -- Build_Array_Init_Proc --
537    ---------------------------
538
539    procedure Build_Array_Init_Proc (A_Type : Entity_Id; Nod : Node_Id) is
540       Loc              : constant Source_Ptr := Sloc (Nod);
541       Comp_Type        : constant Entity_Id  := Component_Type (A_Type);
542       Index_List       : List_Id;
543       Proc_Id          : Entity_Id;
544       Body_Stmts       : List_Id;
545       Has_Default_Init : Boolean;
546
547       function Init_Component return List_Id;
548       --  Create one statement to initialize one array component, designated
549       --  by a full set of indices.
550
551       function Init_One_Dimension (N : Int) return List_Id;
552       --  Create loop to initialize one dimension of the array. The single
553       --  statement in the loop body initializes the inner dimensions if any,
554       --  or else the single component. Note that this procedure is called
555       --  recursively, with N being the dimension to be initialized. A call
556       --  with N greater than the number of dimensions simply generates the
557       --  component initialization, terminating the recursion.
558
559       --------------------
560       -- Init_Component --
561       --------------------
562
563       function Init_Component return List_Id is
564          Comp : Node_Id;
565
566       begin
567          Comp :=
568            Make_Indexed_Component (Loc,
569              Prefix => Make_Identifier (Loc, Name_uInit),
570              Expressions => Index_List);
571
572          if Needs_Simple_Initialization (Comp_Type) then
573             Set_Assignment_OK (Comp);
574             return New_List (
575               Make_Assignment_Statement (Loc,
576                 Name => Comp,
577                 Expression =>
578                   Get_Simple_Init_Val
579                     (Comp_Type, Nod, Component_Size (A_Type))));
580
581          else
582             Clean_Task_Names (Comp_Type, Proc_Id);
583             return
584               Build_Initialization_Call
585                 (Loc, Comp, Comp_Type,
586                  In_Init_Proc => True,
587                  Enclos_Type  => A_Type);
588          end if;
589       end Init_Component;
590
591       ------------------------
592       -- Init_One_Dimension --
593       ------------------------
594
595       function Init_One_Dimension (N : Int) return List_Id is
596          Index : Entity_Id;
597
598       begin
599          --  If the component does not need initializing, then there is nothing
600          --  to do here, so we return a null body. This occurs when generating
601          --  the dummy Init_Proc needed for Initialize_Scalars processing.
602
603          if not Has_Non_Null_Base_Init_Proc (Comp_Type)
604            and then not Needs_Simple_Initialization (Comp_Type)
605            and then not Has_Task (Comp_Type)
606          then
607             return New_List (Make_Null_Statement (Loc));
608
609          --  If all dimensions dealt with, we simply initialize the component
610
611          elsif N > Number_Dimensions (A_Type) then
612             return Init_Component;
613
614          --  Here we generate the required loop
615
616          else
617             Index :=
618               Make_Defining_Identifier (Loc, New_External_Name ('J', N));
619
620             Append (New_Reference_To (Index, Loc), Index_List);
621
622             return New_List (
623               Make_Implicit_Loop_Statement (Nod,
624                 Identifier => Empty,
625                 Iteration_Scheme =>
626                   Make_Iteration_Scheme (Loc,
627                     Loop_Parameter_Specification =>
628                       Make_Loop_Parameter_Specification (Loc,
629                         Defining_Identifier => Index,
630                         Discrete_Subtype_Definition =>
631                           Make_Attribute_Reference (Loc,
632                             Prefix => Make_Identifier (Loc, Name_uInit),
633                             Attribute_Name  => Name_Range,
634                             Expressions => New_List (
635                               Make_Integer_Literal (Loc, N))))),
636                 Statements =>  Init_One_Dimension (N + 1)));
637          end if;
638       end Init_One_Dimension;
639
640    --  Start of processing for Build_Array_Init_Proc
641
642    begin
643       --  Nothing to generate in the following cases:
644
645       --    1. Initialization is suppressed for the type
646       --    2. The type is a value type, in the CIL sense.
647       --    3. The type has CIL/JVM convention.
648       --    4. An initialization already exists for the base type
649
650       if Suppress_Init_Proc (A_Type)
651         or else Is_Value_Type (Comp_Type)
652         or else Convention (A_Type) = Convention_CIL
653         or else Convention (A_Type) = Convention_Java
654         or else Present (Base_Init_Proc (A_Type))
655       then
656          return;
657       end if;
658
659       Index_List := New_List;
660
661       --  We need an initialization procedure if any of the following is true:
662
663       --    1. The component type has an initialization procedure
664       --    2. The component type needs simple initialization
665       --    3. Tasks are present
666       --    4. The type is marked as a public entity
667
668       --  The reason for the public entity test is to deal properly with the
669       --  Initialize_Scalars pragma. This pragma can be set in the client and
670       --  not in the declaring package, this means the client will make a call
671       --  to the initialization procedure (because one of conditions 1-3 must
672       --  apply in this case), and we must generate a procedure (even if it is
673       --  null) to satisfy the call in this case.
674
675       --  Exception: do not build an array init_proc for a type whose root
676       --  type is Standard.String or Standard.Wide_[Wide_]String, since there
677       --  is no place to put the code, and in any case we handle initialization
678       --  of such types (in the Initialize_Scalars case, that's the only time
679       --  the issue arises) in a special manner anyway which does not need an
680       --  init_proc.
681
682       Has_Default_Init := Has_Non_Null_Base_Init_Proc (Comp_Type)
683                             or else Needs_Simple_Initialization (Comp_Type)
684                             or else Has_Task (Comp_Type);
685
686       if Has_Default_Init
687         or else (not Restriction_Active (No_Initialize_Scalars)
688                   and then Is_Public (A_Type)
689                   and then Root_Type (A_Type) /= Standard_String
690                   and then Root_Type (A_Type) /= Standard_Wide_String
691                   and then Root_Type (A_Type) /= Standard_Wide_Wide_String)
692       then
693          Proc_Id :=
694            Make_Defining_Identifier (Loc,
695              Chars => Make_Init_Proc_Name (A_Type));
696
697          --  If No_Default_Initialization restriction is active, then we don't
698          --  want to build an init_proc, but we need to mark that an init_proc
699          --  would be needed if this restriction was not active (so that we can
700          --  detect attempts to call it), so set a dummy init_proc in place.
701          --  This is only done though when actual default initialization is
702          --  needed (and not done when only Is_Public is True), since otherwise
703          --  objects such as arrays of scalars could be wrongly flagged as
704          --  violating the restriction.
705
706          if Restriction_Active (No_Default_Initialization) then
707             if Has_Default_Init then
708                Set_Init_Proc (A_Type, Proc_Id);
709             end if;
710
711             return;
712          end if;
713
714          Body_Stmts := Init_One_Dimension (1);
715
716          Discard_Node (
717            Make_Subprogram_Body (Loc,
718              Specification =>
719                Make_Procedure_Specification (Loc,
720                  Defining_Unit_Name => Proc_Id,
721                  Parameter_Specifications => Init_Formals (A_Type)),
722              Declarations => New_List,
723              Handled_Statement_Sequence =>
724                Make_Handled_Sequence_Of_Statements (Loc,
725                  Statements => Body_Stmts)));
726
727          Set_Ekind          (Proc_Id, E_Procedure);
728          Set_Is_Public      (Proc_Id, Is_Public (A_Type));
729          Set_Is_Internal    (Proc_Id);
730          Set_Has_Completion (Proc_Id);
731
732          if not Debug_Generated_Code then
733             Set_Debug_Info_Off (Proc_Id);
734          end if;
735
736          --  Set inlined unless controlled stuff or tasks around, in which
737          --  case we do not want to inline, because nested stuff may cause
738          --  difficulties in inter-unit inlining, and furthermore there is
739          --  in any case no point in inlining such complex init procs.
740
741          if not Has_Task (Proc_Id)
742            and then not Needs_Finalization (Proc_Id)
743          then
744             Set_Is_Inlined (Proc_Id);
745          end if;
746
747          --  Associate Init_Proc with type, and determine if the procedure
748          --  is null (happens because of the Initialize_Scalars pragma case,
749          --  where we have to generate a null procedure in case it is called
750          --  by a client with Initialize_Scalars set). Such procedures have
751          --  to be generated, but do not have to be called, so we mark them
752          --  as null to suppress the call.
753
754          Set_Init_Proc (A_Type, Proc_Id);
755
756          if List_Length (Body_Stmts) = 1
757
758            --  We must skip SCIL nodes because they may have been added to this
759            --  list by Insert_Actions.
760
761            and then Nkind (First_Non_SCIL_Node (Body_Stmts)) = N_Null_Statement
762          then
763             Set_Is_Null_Init_Proc (Proc_Id);
764
765          else
766             --  Try to build a static aggregate to initialize statically
767             --  objects of the type. This can only be done for constrained
768             --  one-dimensional arrays with static bounds.
769
770             Set_Static_Initialization
771               (Proc_Id,
772                Build_Equivalent_Array_Aggregate (First_Subtype (A_Type)));
773          end if;
774       end if;
775    end Build_Array_Init_Proc;
776
777    -----------------------------
778    -- Build_Class_Wide_Master --
779    -----------------------------
780
781    procedure Build_Class_Wide_Master (T : Entity_Id) is
782       Loc  : constant Source_Ptr := Sloc (T);
783       M_Id : Entity_Id;
784       Decl : Node_Id;
785       P    : Node_Id;
786       Par  : Node_Id;
787
788    begin
789       --  Nothing to do if there is no task hierarchy
790
791       if Restriction_Active (No_Task_Hierarchy) then
792          return;
793       end if;
794
795       --  Find declaration that created the access type: either a type
796       --  declaration, or an object declaration with an access definition,
797       --  in which case the type is anonymous.
798
799       if Is_Itype (T) then
800          P := Associated_Node_For_Itype (T);
801       else
802          P := Parent (T);
803       end if;
804
805       --  Nothing to do if we already built a master entity for this scope
806
807       if not Has_Master_Entity (Scope (T)) then
808
809          --  First build the master entity
810          --    _Master : constant Master_Id := Current_Master.all;
811          --  and insert it just before the current declaration.
812
813          Decl :=
814            Make_Object_Declaration (Loc,
815              Defining_Identifier =>
816                Make_Defining_Identifier (Loc, Name_uMaster),
817              Constant_Present => True,
818              Object_Definition => New_Reference_To (Standard_Integer, Loc),
819              Expression =>
820                Make_Explicit_Dereference (Loc,
821                  New_Reference_To (RTE (RE_Current_Master), Loc)));
822
823          Insert_Action (P, Decl);
824          Analyze (Decl);
825          Set_Has_Master_Entity (Scope (T));
826
827          --  Now mark the containing scope as a task master. Masters
828          --  associated with return statements are already marked at
829          --  this stage (see Analyze_Subprogram_Body).
830
831          if Ekind (Current_Scope) /= E_Return_Statement then
832             Par := P;
833             while Nkind (Par) /= N_Compilation_Unit loop
834                Par := Parent (Par);
835
836             --  If we fall off the top, we are at the outer level, and the
837             --  environment task is our effective master, so nothing to mark.
838
839                if Nkind_In
840                    (Par, N_Task_Body, N_Block_Statement, N_Subprogram_Body)
841                then
842                   Set_Is_Task_Master (Par, True);
843                   exit;
844                end if;
845             end loop;
846          end if;
847       end if;
848
849       --  Now define the renaming of the master_id
850
851       M_Id :=
852         Make_Defining_Identifier (Loc,
853           New_External_Name (Chars (T), 'M'));
854
855       Decl :=
856         Make_Object_Renaming_Declaration (Loc,
857           Defining_Identifier => M_Id,
858           Subtype_Mark => New_Reference_To (Standard_Integer, Loc),
859           Name => Make_Identifier (Loc, Name_uMaster));
860       Insert_Before (P, Decl);
861       Analyze (Decl);
862
863       Set_Master_Id (T, M_Id);
864
865    exception
866       when RE_Not_Available =>
867          return;
868    end Build_Class_Wide_Master;
869
870    --------------------------------
871    -- Build_Discr_Checking_Funcs --
872    --------------------------------
873
874    procedure Build_Discr_Checking_Funcs (N : Node_Id) is
875       Rec_Id            : Entity_Id;
876       Loc               : Source_Ptr;
877       Enclosing_Func_Id : Entity_Id;
878       Sequence          : Nat     := 1;
879       Type_Def          : Node_Id;
880       V                 : Node_Id;
881
882       function Build_Case_Statement
883         (Case_Id : Entity_Id;
884          Variant : Node_Id) return Node_Id;
885       --  Build a case statement containing only two alternatives. The first
886       --  alternative corresponds exactly to the discrete choices given on the
887       --  variant with contains the components that we are generating the
888       --  checks for. If the discriminant is one of these return False. The
889       --  second alternative is an OTHERS choice that will return True
890       --  indicating the discriminant did not match.
891
892       function Build_Dcheck_Function
893         (Case_Id : Entity_Id;
894          Variant : Node_Id) return Entity_Id;
895       --  Build the discriminant checking function for a given variant
896
897       procedure Build_Dcheck_Functions (Variant_Part_Node : Node_Id);
898       --  Builds the discriminant checking function for each variant of the
899       --  given variant part of the record type.
900
901       --------------------------
902       -- Build_Case_Statement --
903       --------------------------
904
905       function Build_Case_Statement
906         (Case_Id : Entity_Id;
907          Variant : Node_Id) return Node_Id
908       is
909          Alt_List       : constant List_Id := New_List;
910          Actuals_List   : List_Id;
911          Case_Node      : Node_Id;
912          Case_Alt_Node  : Node_Id;
913          Choice         : Node_Id;
914          Choice_List    : List_Id;
915          D              : Entity_Id;
916          Return_Node    : Node_Id;
917
918       begin
919          Case_Node := New_Node (N_Case_Statement, Loc);
920
921          --  Replace the discriminant which controls the variant, with the name
922          --  of the formal of the checking function.
923
924          Set_Expression (Case_Node,
925            Make_Identifier (Loc, Chars (Case_Id)));
926
927          Choice := First (Discrete_Choices (Variant));
928
929          if Nkind (Choice) = N_Others_Choice then
930             Choice_List := New_Copy_List (Others_Discrete_Choices (Choice));
931          else
932             Choice_List := New_Copy_List (Discrete_Choices (Variant));
933          end if;
934
935          if not Is_Empty_List (Choice_List) then
936             Case_Alt_Node := New_Node (N_Case_Statement_Alternative, Loc);
937             Set_Discrete_Choices (Case_Alt_Node, Choice_List);
938
939             --  In case this is a nested variant, we need to return the result
940             --  of the discriminant checking function for the immediately
941             --  enclosing variant.
942
943             if Present (Enclosing_Func_Id) then
944                Actuals_List := New_List;
945
946                D := First_Discriminant (Rec_Id);
947                while Present (D) loop
948                   Append (Make_Identifier (Loc, Chars (D)), Actuals_List);
949                   Next_Discriminant (D);
950                end loop;
951
952                Return_Node :=
953                  Make_Simple_Return_Statement (Loc,
954                    Expression =>
955                      Make_Function_Call (Loc,
956                        Name =>
957                          New_Reference_To (Enclosing_Func_Id,  Loc),
958                        Parameter_Associations =>
959                          Actuals_List));
960
961             else
962                Return_Node :=
963                  Make_Simple_Return_Statement (Loc,
964                    Expression =>
965                      New_Reference_To (Standard_False, Loc));
966             end if;
967
968             Set_Statements (Case_Alt_Node, New_List (Return_Node));
969             Append (Case_Alt_Node, Alt_List);
970          end if;
971
972          Case_Alt_Node := New_Node (N_Case_Statement_Alternative, Loc);
973          Choice_List := New_List (New_Node (N_Others_Choice, Loc));
974          Set_Discrete_Choices (Case_Alt_Node, Choice_List);
975
976          Return_Node :=
977            Make_Simple_Return_Statement (Loc,
978              Expression =>
979                New_Reference_To (Standard_True, Loc));
980
981          Set_Statements (Case_Alt_Node, New_List (Return_Node));
982          Append (Case_Alt_Node, Alt_List);
983
984          Set_Alternatives (Case_Node, Alt_List);
985          return Case_Node;
986       end Build_Case_Statement;
987
988       ---------------------------
989       -- Build_Dcheck_Function --
990       ---------------------------
991
992       function Build_Dcheck_Function
993         (Case_Id : Entity_Id;
994          Variant : Node_Id) return Entity_Id
995       is
996          Body_Node           : Node_Id;
997          Func_Id             : Entity_Id;
998          Parameter_List      : List_Id;
999          Spec_Node           : Node_Id;
1000
1001       begin
1002          Body_Node := New_Node (N_Subprogram_Body, Loc);
1003          Sequence := Sequence + 1;
1004
1005          Func_Id :=
1006            Make_Defining_Identifier (Loc,
1007              Chars => New_External_Name (Chars (Rec_Id), 'D', Sequence));
1008
1009          Spec_Node := New_Node (N_Function_Specification, Loc);
1010          Set_Defining_Unit_Name (Spec_Node, Func_Id);
1011
1012          Parameter_List := Build_Discriminant_Formals (Rec_Id, False);
1013
1014          Set_Parameter_Specifications (Spec_Node, Parameter_List);
1015          Set_Result_Definition (Spec_Node,
1016                                 New_Reference_To (Standard_Boolean,  Loc));
1017          Set_Specification (Body_Node, Spec_Node);
1018          Set_Declarations (Body_Node, New_List);
1019
1020          Set_Handled_Statement_Sequence (Body_Node,
1021            Make_Handled_Sequence_Of_Statements (Loc,
1022              Statements => New_List (
1023                Build_Case_Statement (Case_Id, Variant))));
1024
1025          Set_Ekind       (Func_Id, E_Function);
1026          Set_Mechanism   (Func_Id, Default_Mechanism);
1027          Set_Is_Inlined  (Func_Id, True);
1028          Set_Is_Pure     (Func_Id, True);
1029          Set_Is_Public   (Func_Id, Is_Public (Rec_Id));
1030          Set_Is_Internal (Func_Id, True);
1031
1032          if not Debug_Generated_Code then
1033             Set_Debug_Info_Off (Func_Id);
1034          end if;
1035
1036          Analyze (Body_Node);
1037
1038          Append_Freeze_Action (Rec_Id, Body_Node);
1039          Set_Dcheck_Function (Variant, Func_Id);
1040          return Func_Id;
1041       end Build_Dcheck_Function;
1042
1043       ----------------------------
1044       -- Build_Dcheck_Functions --
1045       ----------------------------
1046
1047       procedure Build_Dcheck_Functions (Variant_Part_Node : Node_Id) is
1048          Component_List_Node : Node_Id;
1049          Decl                : Entity_Id;
1050          Discr_Name          : Entity_Id;
1051          Func_Id             : Entity_Id;
1052          Variant             : Node_Id;
1053          Saved_Enclosing_Func_Id : Entity_Id;
1054
1055       begin
1056          --  Build the discriminant-checking function for each variant, and
1057          --  label all components of that variant with the function's name.
1058          --  We only Generate a discriminant-checking function when the
1059          --  variant is not empty, to prevent the creation of dead code.
1060          --  The exception to that is when Frontend_Layout_On_Target is set,
1061          --  because the variant record size function generated in package
1062          --  Layout needs to generate calls to all discriminant-checking
1063          --  functions, including those for empty variants.
1064
1065          Discr_Name := Entity (Name (Variant_Part_Node));
1066          Variant := First_Non_Pragma (Variants (Variant_Part_Node));
1067
1068          while Present (Variant) loop
1069             Component_List_Node := Component_List (Variant);
1070
1071             if not Null_Present (Component_List_Node)
1072               or else Frontend_Layout_On_Target
1073             then
1074                Func_Id := Build_Dcheck_Function (Discr_Name, Variant);
1075                Decl :=
1076                  First_Non_Pragma (Component_Items (Component_List_Node));
1077
1078                while Present (Decl) loop
1079                   Set_Discriminant_Checking_Func
1080                     (Defining_Identifier (Decl), Func_Id);
1081
1082                   Next_Non_Pragma (Decl);
1083                end loop;
1084
1085                if Present (Variant_Part (Component_List_Node)) then
1086                   Saved_Enclosing_Func_Id := Enclosing_Func_Id;
1087                   Enclosing_Func_Id := Func_Id;
1088                   Build_Dcheck_Functions (Variant_Part (Component_List_Node));
1089                   Enclosing_Func_Id := Saved_Enclosing_Func_Id;
1090                end if;
1091             end if;
1092
1093             Next_Non_Pragma (Variant);
1094          end loop;
1095       end Build_Dcheck_Functions;
1096
1097    --  Start of processing for Build_Discr_Checking_Funcs
1098
1099    begin
1100       --  Only build if not done already
1101
1102       if not Discr_Check_Funcs_Built (N) then
1103          Type_Def := Type_Definition (N);
1104
1105          if Nkind (Type_Def) = N_Record_Definition then
1106             if No (Component_List (Type_Def)) then   -- null record.
1107                return;
1108             else
1109                V := Variant_Part (Component_List (Type_Def));
1110             end if;
1111
1112          else pragma Assert (Nkind (Type_Def) = N_Derived_Type_Definition);
1113             if No (Component_List (Record_Extension_Part (Type_Def))) then
1114                return;
1115             else
1116                V := Variant_Part
1117                       (Component_List (Record_Extension_Part (Type_Def)));
1118             end if;
1119          end if;
1120
1121          Rec_Id := Defining_Identifier (N);
1122
1123          if Present (V) and then not Is_Unchecked_Union (Rec_Id) then
1124             Loc := Sloc (N);
1125             Enclosing_Func_Id := Empty;
1126             Build_Dcheck_Functions (V);
1127          end if;
1128
1129          Set_Discr_Check_Funcs_Built (N);
1130       end if;
1131    end Build_Discr_Checking_Funcs;
1132
1133    --------------------------------
1134    -- Build_Discriminant_Formals --
1135    --------------------------------
1136
1137    function Build_Discriminant_Formals
1138      (Rec_Id : Entity_Id;
1139       Use_Dl : Boolean) return List_Id
1140    is
1141       Loc             : Source_Ptr       := Sloc (Rec_Id);
1142       Parameter_List  : constant List_Id := New_List;
1143       D               : Entity_Id;
1144       Formal          : Entity_Id;
1145       Formal_Type     : Entity_Id;
1146       Param_Spec_Node : Node_Id;
1147
1148    begin
1149       if Has_Discriminants (Rec_Id) then
1150          D := First_Discriminant (Rec_Id);
1151          while Present (D) loop
1152             Loc := Sloc (D);
1153
1154             if Use_Dl then
1155                Formal := Discriminal (D);
1156                Formal_Type := Etype (Formal);
1157             else
1158                Formal := Make_Defining_Identifier (Loc, Chars (D));
1159                Formal_Type := Etype (D);
1160             end if;
1161
1162             Param_Spec_Node :=
1163               Make_Parameter_Specification (Loc,
1164                   Defining_Identifier => Formal,
1165                 Parameter_Type =>
1166                   New_Reference_To (Formal_Type, Loc));
1167             Append (Param_Spec_Node, Parameter_List);
1168             Next_Discriminant (D);
1169          end loop;
1170       end if;
1171
1172       return Parameter_List;
1173    end Build_Discriminant_Formals;
1174
1175    --------------------------------------
1176    -- Build_Equivalent_Array_Aggregate --
1177    --------------------------------------
1178
1179    function Build_Equivalent_Array_Aggregate (T : Entity_Id) return Node_Id is
1180       Loc        : constant Source_Ptr := Sloc (T);
1181       Comp_Type  : constant Entity_Id := Component_Type (T);
1182       Index_Type : constant Entity_Id := Etype (First_Index (T));
1183       Proc       : constant Entity_Id := Base_Init_Proc (T);
1184       Lo, Hi     : Node_Id;
1185       Aggr       : Node_Id;
1186       Expr       : Node_Id;
1187
1188    begin
1189       if not Is_Constrained (T)
1190         or else Number_Dimensions (T) > 1
1191         or else No (Proc)
1192       then
1193          Initialization_Warning (T);
1194          return Empty;
1195       end if;
1196
1197       Lo := Type_Low_Bound  (Index_Type);
1198       Hi := Type_High_Bound (Index_Type);
1199
1200       if not Compile_Time_Known_Value (Lo)
1201         or else not Compile_Time_Known_Value (Hi)
1202       then
1203          Initialization_Warning (T);
1204          return Empty;
1205       end if;
1206
1207       if Is_Record_Type (Comp_Type)
1208         and then Present (Base_Init_Proc (Comp_Type))
1209       then
1210          Expr := Static_Initialization (Base_Init_Proc (Comp_Type));
1211
1212          if No (Expr) then
1213             Initialization_Warning (T);
1214             return Empty;
1215          end if;
1216
1217       else
1218          Initialization_Warning (T);
1219          return Empty;
1220       end if;
1221
1222       Aggr := Make_Aggregate (Loc, No_List, New_List);
1223       Set_Etype (Aggr, T);
1224       Set_Aggregate_Bounds (Aggr,
1225         Make_Range (Loc,
1226           Low_Bound  => New_Copy (Lo),
1227           High_Bound => New_Copy (Hi)));
1228       Set_Parent (Aggr, Parent (Proc));
1229
1230       Append_To (Component_Associations (Aggr),
1231          Make_Component_Association (Loc,
1232               Choices =>
1233                  New_List (
1234                    Make_Range (Loc,
1235                      Low_Bound  => New_Copy (Lo),
1236                      High_Bound => New_Copy (Hi))),
1237               Expression => Expr));
1238
1239       if Static_Array_Aggregate (Aggr) then
1240          return Aggr;
1241       else
1242          Initialization_Warning (T);
1243          return Empty;
1244       end if;
1245    end Build_Equivalent_Array_Aggregate;
1246
1247    ---------------------------------------
1248    -- Build_Equivalent_Record_Aggregate --
1249    ---------------------------------------
1250
1251    function Build_Equivalent_Record_Aggregate (T : Entity_Id) return Node_Id is
1252       Agg       : Node_Id;
1253       Comp      : Entity_Id;
1254       Comp_Type : Entity_Id;
1255
1256       --  Start of processing for Build_Equivalent_Record_Aggregate
1257
1258    begin
1259       if not Is_Record_Type (T)
1260         or else Has_Discriminants (T)
1261         or else Is_Limited_Type (T)
1262         or else Has_Non_Standard_Rep (T)
1263       then
1264          Initialization_Warning (T);
1265          return Empty;
1266       end if;
1267
1268       Comp := First_Component (T);
1269
1270       --  A null record needs no warning
1271
1272       if No (Comp) then
1273          return Empty;
1274       end if;
1275
1276       while Present (Comp) loop
1277
1278          --  Array components are acceptable if initialized by a positional
1279          --  aggregate with static components.
1280
1281          if Is_Array_Type (Etype (Comp)) then
1282             Comp_Type := Component_Type (Etype (Comp));
1283
1284             if Nkind (Parent (Comp)) /= N_Component_Declaration
1285               or else No (Expression (Parent (Comp)))
1286               or else Nkind (Expression (Parent (Comp))) /= N_Aggregate
1287             then
1288                Initialization_Warning (T);
1289                return Empty;
1290
1291             elsif Is_Scalar_Type (Component_Type (Etype (Comp)))
1292                and then
1293                  (not Compile_Time_Known_Value (Type_Low_Bound (Comp_Type))
1294                    or else
1295                   not Compile_Time_Known_Value (Type_High_Bound (Comp_Type)))
1296             then
1297                Initialization_Warning (T);
1298                return Empty;
1299
1300             elsif
1301               not Static_Array_Aggregate (Expression (Parent (Comp)))
1302             then
1303                Initialization_Warning (T);
1304                return Empty;
1305             end if;
1306
1307          elsif Is_Scalar_Type (Etype (Comp)) then
1308             Comp_Type := Etype (Comp);
1309
1310             if Nkind (Parent (Comp)) /= N_Component_Declaration
1311               or else No (Expression (Parent (Comp)))
1312               or else not Compile_Time_Known_Value (Expression (Parent (Comp)))
1313               or else not Compile_Time_Known_Value (Type_Low_Bound (Comp_Type))
1314               or else not
1315                 Compile_Time_Known_Value (Type_High_Bound (Comp_Type))
1316             then
1317                Initialization_Warning (T);
1318                return Empty;
1319             end if;
1320
1321          --  For now, other types are excluded
1322
1323          else
1324             Initialization_Warning (T);
1325             return Empty;
1326          end if;
1327
1328          Next_Component (Comp);
1329       end loop;
1330
1331       --  All components have static initialization. Build positional aggregate
1332       --  from the given expressions or defaults.
1333
1334       Agg := Make_Aggregate (Sloc (T), New_List, New_List);
1335       Set_Parent (Agg, Parent (T));
1336
1337       Comp := First_Component (T);
1338       while Present (Comp) loop
1339          Append
1340            (New_Copy_Tree (Expression (Parent (Comp))), Expressions (Agg));
1341          Next_Component (Comp);
1342       end loop;
1343
1344       Analyze_And_Resolve (Agg, T);
1345       return Agg;
1346    end Build_Equivalent_Record_Aggregate;
1347
1348    -------------------------------
1349    -- Build_Initialization_Call --
1350    -------------------------------
1351
1352    --  References to a discriminant inside the record type declaration can
1353    --  appear either in the subtype_indication to constrain a record or an
1354    --  array, or as part of a larger expression given for the initial value
1355    --  of a component. In both of these cases N appears in the record
1356    --  initialization procedure and needs to be replaced by the formal
1357    --  parameter of the initialization procedure which corresponds to that
1358    --  discriminant.
1359
1360    --  In the example below, references to discriminants D1 and D2 in proc_1
1361    --  are replaced by references to formals with the same name
1362    --  (discriminals)
1363
1364    --  A similar replacement is done for calls to any record initialization
1365    --  procedure for any components that are themselves of a record type.
1366
1367    --  type R (D1, D2 : Integer) is record
1368    --     X : Integer := F * D1;
1369    --     Y : Integer := F * D2;
1370    --  end record;
1371
1372    --  procedure proc_1 (Out_2 : out R; D1 : Integer; D2 : Integer) is
1373    --  begin
1374    --     Out_2.D1 := D1;
1375    --     Out_2.D2 := D2;
1376    --     Out_2.X := F * D1;
1377    --     Out_2.Y := F * D2;
1378    --  end;
1379
1380    function Build_Initialization_Call
1381      (Loc               : Source_Ptr;
1382       Id_Ref            : Node_Id;
1383       Typ               : Entity_Id;
1384       In_Init_Proc      : Boolean := False;
1385       Enclos_Type       : Entity_Id := Empty;
1386       Discr_Map         : Elist_Id := New_Elmt_List;
1387       With_Default_Init : Boolean := False;
1388       Constructor_Ref   : Node_Id := Empty) return List_Id
1389    is
1390       Res            : constant List_Id := New_List;
1391       Arg            : Node_Id;
1392       Args           : List_Id;
1393       Controller_Typ : Entity_Id;
1394       Decl           : Node_Id;
1395       Decls          : List_Id;
1396       Discr          : Entity_Id;
1397       First_Arg      : Node_Id;
1398       Full_Init_Type : Entity_Id;
1399       Full_Type      : Entity_Id := Typ;
1400       Init_Type      : Entity_Id;
1401       Proc           : Entity_Id;
1402
1403    begin
1404       pragma Assert (Constructor_Ref = Empty
1405         or else Is_CPP_Constructor_Call (Constructor_Ref));
1406
1407       if No (Constructor_Ref) then
1408          Proc := Base_Init_Proc (Typ);
1409       else
1410          Proc := Base_Init_Proc (Typ, Entity (Name (Constructor_Ref)));
1411       end if;
1412
1413       pragma Assert (Present (Proc));
1414       Init_Type      := Etype (First_Formal (Proc));
1415       Full_Init_Type := Underlying_Type (Init_Type);
1416
1417       --  Nothing to do if the Init_Proc is null, unless Initialize_Scalars
1418       --  is active (in which case we make the call anyway, since in the
1419       --  actual compiled client it may be non null).
1420       --  Also nothing to do for value types.
1421
1422       if (Is_Null_Init_Proc (Proc) and then not Init_Or_Norm_Scalars)
1423         or else Is_Value_Type (Typ)
1424         or else
1425           (Is_Array_Type (Typ) and then Is_Value_Type (Component_Type (Typ)))
1426       then
1427          return Empty_List;
1428       end if;
1429
1430       --  Go to full view if private type. In the case of successive
1431       --  private derivations, this can require more than one step.
1432
1433       while Is_Private_Type (Full_Type)
1434         and then Present (Full_View (Full_Type))
1435       loop
1436          Full_Type := Full_View (Full_Type);
1437       end loop;
1438
1439       --  If Typ is derived, the procedure is the initialization procedure for
1440       --  the root type. Wrap the argument in an conversion to make it type
1441       --  honest. Actually it isn't quite type honest, because there can be
1442       --  conflicts of views in the private type case. That is why we set
1443       --  Conversion_OK in the conversion node.
1444
1445       if (Is_Record_Type (Typ)
1446            or else Is_Array_Type (Typ)
1447            or else Is_Private_Type (Typ))
1448         and then Init_Type /= Base_Type (Typ)
1449       then
1450          First_Arg := OK_Convert_To (Etype (Init_Type), Id_Ref);
1451          Set_Etype (First_Arg, Init_Type);
1452
1453       else
1454          First_Arg := Id_Ref;
1455       end if;
1456
1457       Args := New_List (Convert_Concurrent (First_Arg, Typ));
1458
1459       --  In the tasks case, add _Master as the value of the _Master parameter
1460       --  and _Chain as the value of the _Chain parameter. At the outer level,
1461       --  these will be variables holding the corresponding values obtained
1462       --  from GNARL. At inner levels, they will be the parameters passed down
1463       --  through the outer routines.
1464
1465       if Has_Task (Full_Type) then
1466          if Restriction_Active (No_Task_Hierarchy) then
1467
1468             --  See comments in System.Tasking.Initialization.Init_RTS
1469             --  for the value 3 (should be rtsfindable constant ???)
1470
1471             Append_To (Args, Make_Integer_Literal (Loc, 3));
1472
1473          else
1474             Append_To (Args, Make_Identifier (Loc, Name_uMaster));
1475          end if;
1476
1477          Append_To (Args, Make_Identifier (Loc, Name_uChain));
1478
1479          --  Ada 2005 (AI-287): In case of default initialized components
1480          --  with tasks, we generate a null string actual parameter.
1481          --  This is just a workaround that must be improved later???
1482
1483          if With_Default_Init then
1484             Append_To (Args,
1485               Make_String_Literal (Loc,
1486                 Strval => ""));
1487
1488          else
1489             Decls :=
1490               Build_Task_Image_Decls (Loc, Id_Ref, Enclos_Type, In_Init_Proc);
1491             Decl  := Last (Decls);
1492
1493             Append_To (Args,
1494               New_Occurrence_Of (Defining_Identifier (Decl), Loc));
1495             Append_List (Decls, Res);
1496          end if;
1497
1498       else
1499          Decls := No_List;
1500          Decl  := Empty;
1501       end if;
1502
1503       --  Add discriminant values if discriminants are present
1504
1505       if Has_Discriminants (Full_Init_Type) then
1506          Discr := First_Discriminant (Full_Init_Type);
1507
1508          while Present (Discr) loop
1509
1510             --  If this is a discriminated concurrent type, the init_proc
1511             --  for the corresponding record is being called. Use that type
1512             --  directly to find the discriminant value, to handle properly
1513             --  intervening renamed discriminants.
1514
1515             declare
1516                T : Entity_Id := Full_Type;
1517
1518             begin
1519                if Is_Protected_Type (T) then
1520                   T := Corresponding_Record_Type (T);
1521
1522                elsif Is_Private_Type (T)
1523                  and then Present (Underlying_Full_View (T))
1524                  and then Is_Protected_Type (Underlying_Full_View (T))
1525                then
1526                   T := Corresponding_Record_Type (Underlying_Full_View (T));
1527                end if;
1528
1529                Arg :=
1530                  Get_Discriminant_Value (
1531                    Discr,
1532                    T,
1533                    Discriminant_Constraint (Full_Type));
1534             end;
1535
1536             if In_Init_Proc then
1537
1538                --  Replace any possible references to the discriminant in the
1539                --  call to the record initialization procedure with references
1540                --  to the appropriate formal parameter.
1541
1542                if Nkind (Arg) = N_Identifier
1543                   and then Ekind (Entity (Arg)) = E_Discriminant
1544                then
1545                   Arg := New_Reference_To (Discriminal (Entity (Arg)), Loc);
1546
1547                --  Case of access discriminants. We replace the reference
1548                --  to the type by a reference to the actual object
1549
1550                elsif Nkind (Arg) = N_Attribute_Reference
1551                  and then Is_Access_Type (Etype (Arg))
1552                  and then Is_Entity_Name (Prefix (Arg))
1553                  and then Is_Type (Entity (Prefix (Arg)))
1554                then
1555                   Arg :=
1556                     Make_Attribute_Reference (Loc,
1557                       Prefix         => New_Copy (Prefix (Id_Ref)),
1558                       Attribute_Name => Name_Unrestricted_Access);
1559
1560                --  Otherwise make a copy of the default expression. Note that
1561                --  we use the current Sloc for this, because we do not want the
1562                --  call to appear to be at the declaration point. Within the
1563                --  expression, replace discriminants with their discriminals.
1564
1565                else
1566                   Arg :=
1567                     New_Copy_Tree (Arg, Map => Discr_Map, New_Sloc => Loc);
1568                end if;
1569
1570             else
1571                if Is_Constrained (Full_Type) then
1572                   Arg := Duplicate_Subexpr_No_Checks (Arg);
1573                else
1574                   --  The constraints come from the discriminant default exps,
1575                   --  they must be reevaluated, so we use New_Copy_Tree but we
1576                   --  ensure the proper Sloc (for any embedded calls).
1577
1578                   Arg := New_Copy_Tree (Arg, New_Sloc => Loc);
1579                end if;
1580             end if;
1581
1582             --  Ada 2005 (AI-287): In case of default initialized components,
1583             --  if the component is constrained with a discriminant of the
1584             --  enclosing type, we need to generate the corresponding selected
1585             --  component node to access the discriminant value. In other cases
1586             --  this is not required, either  because we are inside the init
1587             --  proc and we use the corresponding formal, or else because the
1588             --  component is constrained by an expression.
1589
1590             if With_Default_Init
1591               and then Nkind (Id_Ref) = N_Selected_Component
1592               and then Nkind (Arg) = N_Identifier
1593               and then Ekind (Entity (Arg)) = E_Discriminant
1594             then
1595                Append_To (Args,
1596                  Make_Selected_Component (Loc,
1597                    Prefix => New_Copy_Tree (Prefix (Id_Ref)),
1598                    Selector_Name => Arg));
1599             else
1600                Append_To (Args, Arg);
1601             end if;
1602
1603             Next_Discriminant (Discr);
1604          end loop;
1605       end if;
1606
1607       --  If this is a call to initialize the parent component of a derived
1608       --  tagged type, indicate that the tag should not be set in the parent.
1609
1610       if Is_Tagged_Type (Full_Init_Type)
1611         and then not Is_CPP_Class (Full_Init_Type)
1612         and then Nkind (Id_Ref) = N_Selected_Component
1613         and then Chars (Selector_Name (Id_Ref)) = Name_uParent
1614       then
1615          Append_To (Args, New_Occurrence_Of (Standard_False, Loc));
1616
1617       elsif Present (Constructor_Ref) then
1618          Append_List_To (Args,
1619            New_Copy_List (Parameter_Associations (Constructor_Ref)));
1620       end if;
1621
1622       Append_To (Res,
1623         Make_Procedure_Call_Statement (Loc,
1624           Name => New_Occurrence_Of (Proc, Loc),
1625           Parameter_Associations => Args));
1626
1627       if Needs_Finalization (Typ)
1628         and then Nkind (Id_Ref) = N_Selected_Component
1629       then
1630          if Chars (Selector_Name (Id_Ref)) /= Name_uParent then
1631             Append_List_To (Res,
1632               Make_Init_Call (
1633                 Ref         => New_Copy_Tree (First_Arg),
1634                 Typ         => Typ,
1635                 Flist_Ref   =>
1636                   Find_Final_List (Typ, New_Copy_Tree (First_Arg)),
1637                 With_Attach => Make_Integer_Literal (Loc, 1)));
1638
1639          --  If the enclosing type is an extension with new controlled
1640          --  components, it has his own record controller. If the parent
1641          --  also had a record controller, attach it to the new one.
1642
1643          --  Build_Init_Statements relies on the fact that in this specific
1644          --  case the last statement of the result is the attach call to
1645          --  the controller. If this is changed, it must be synchronized.
1646
1647          elsif Present (Enclos_Type)
1648            and then Has_New_Controlled_Component (Enclos_Type)
1649            and then Has_Controlled_Component (Typ)
1650          then
1651             if Is_Inherently_Limited_Type (Typ) then
1652                Controller_Typ := RTE (RE_Limited_Record_Controller);
1653             else
1654                Controller_Typ := RTE (RE_Record_Controller);
1655             end if;
1656
1657             Append_List_To (Res,
1658               Make_Init_Call (
1659                 Ref       =>
1660                   Make_Selected_Component (Loc,
1661                     Prefix        => New_Copy_Tree (First_Arg),
1662                     Selector_Name => Make_Identifier (Loc, Name_uController)),
1663                 Typ       => Controller_Typ,
1664                 Flist_Ref => Find_Final_List (Typ, New_Copy_Tree (First_Arg)),
1665                 With_Attach => Make_Integer_Literal (Loc, 1)));
1666          end if;
1667       end if;
1668
1669       return Res;
1670
1671    exception
1672       when RE_Not_Available =>
1673          return Empty_List;
1674    end Build_Initialization_Call;
1675
1676    ---------------------------
1677    -- Build_Master_Renaming --
1678    ---------------------------
1679
1680    function Build_Master_Renaming
1681      (N : Node_Id;
1682       T : Entity_Id) return Entity_Id
1683    is
1684       Loc  : constant Source_Ptr := Sloc (N);
1685       M_Id : Entity_Id;
1686       Decl : Node_Id;
1687
1688    begin
1689       --  Nothing to do if there is no task hierarchy
1690
1691       if Restriction_Active (No_Task_Hierarchy) then
1692          return Empty;
1693       end if;
1694
1695       M_Id :=
1696         Make_Defining_Identifier (Loc,
1697           New_External_Name (Chars (T), 'M'));
1698
1699       Decl :=
1700         Make_Object_Renaming_Declaration (Loc,
1701           Defining_Identifier => M_Id,
1702           Subtype_Mark => New_Reference_To (RTE (RE_Master_Id), Loc),
1703           Name => Make_Identifier (Loc, Name_uMaster));
1704       Insert_Before (N, Decl);
1705       Analyze (Decl);
1706       return M_Id;
1707
1708    exception
1709       when RE_Not_Available =>
1710          return Empty;
1711    end Build_Master_Renaming;
1712
1713    ---------------------------
1714    -- Build_Master_Renaming --
1715    ---------------------------
1716
1717    procedure Build_Master_Renaming (N : Node_Id; T : Entity_Id) is
1718       M_Id : Entity_Id;
1719
1720    begin
1721       --  Nothing to do if there is no task hierarchy
1722
1723       if Restriction_Active (No_Task_Hierarchy) then
1724          return;
1725       end if;
1726
1727       M_Id := Build_Master_Renaming (N, T);
1728       Set_Master_Id (T, M_Id);
1729
1730    exception
1731       when RE_Not_Available =>
1732          return;
1733    end Build_Master_Renaming;
1734
1735    ----------------------------
1736    -- Build_Record_Init_Proc --
1737    ----------------------------
1738
1739    procedure Build_Record_Init_Proc (N : Node_Id; Pe : Entity_Id) is
1740       Loc       : Source_Ptr := Sloc (N);
1741       Discr_Map : constant Elist_Id := New_Elmt_List;
1742       Proc_Id   : Entity_Id;
1743       Rec_Type  : Entity_Id;
1744       Set_Tag   : Entity_Id := Empty;
1745
1746       function Build_Assignment (Id : Entity_Id; N : Node_Id) return List_Id;
1747       --  Build a assignment statement node which assigns to record component
1748       --  its default expression if defined. The assignment left hand side is
1749       --  marked Assignment_OK so that initialization of limited private
1750       --  records works correctly, Return also the adjustment call for
1751       --  controlled objects
1752
1753       procedure Build_Discriminant_Assignments (Statement_List : List_Id);
1754       --  If the record has discriminants, adds assignment statements to
1755       --  statement list to initialize the discriminant values from the
1756       --  arguments of the initialization procedure.
1757
1758       function Build_Init_Statements (Comp_List : Node_Id) return List_Id;
1759       --  Build a list representing a sequence of statements which initialize
1760       --  components of the given component list. This may involve building
1761       --  case statements for the variant parts.
1762
1763       function Build_Init_Call_Thru (Parameters : List_Id) return List_Id;
1764       --  Given a non-tagged type-derivation that declares discriminants,
1765       --  such as
1766       --
1767       --  type R (R1, R2 : Integer) is record ... end record;
1768       --
1769       --  type D (D1 : Integer) is new R (1, D1);
1770       --
1771       --  we make the _init_proc of D be
1772       --
1773       --       procedure _init_proc(X : D; D1 : Integer) is
1774       --       begin
1775       --          _init_proc( R(X), 1, D1);
1776       --       end _init_proc;
1777       --
1778       --  This function builds the call statement in this _init_proc.
1779
1780       procedure Build_Init_Procedure;
1781       --  Build the tree corresponding to the procedure specification and body
1782       --  of the initialization procedure (by calling all the preceding
1783       --  auxiliary routines), and install it as the _init TSS.
1784
1785       procedure Build_Offset_To_Top_Functions;
1786       --  Ada 2005 (AI-251): Build the tree corresponding to the procedure spec
1787       --  and body of the Offset_To_Top function that is generated when the
1788       --  parent of a type with discriminants has secondary dispatch tables.
1789
1790       procedure Build_Record_Checks (S : Node_Id; Check_List : List_Id);
1791       --  Add range checks to components of discriminated records. S is a
1792       --  subtype indication of a record component. Check_List is a list
1793       --  to which the check actions are appended.
1794
1795       function Component_Needs_Simple_Initialization
1796         (T : Entity_Id) return Boolean;
1797       --  Determines if a component needs simple initialization, given its type
1798       --  T. This is the same as Needs_Simple_Initialization except for the
1799       --  following difference: the types Tag and Interface_Tag, that are
1800       --  access types which would normally require simple initialization to
1801       --  null, do not require initialization as components, since they are
1802       --  explicitly initialized by other means.
1803
1804       procedure Constrain_Array
1805         (SI         : Node_Id;
1806          Check_List : List_Id);
1807       --  Called from Build_Record_Checks.
1808       --  Apply a list of index constraints to an unconstrained array type.
1809       --  The first parameter is the entity for the resulting subtype.
1810       --  Check_List is a list to which the check actions are appended.
1811
1812       procedure Constrain_Index
1813         (Index      : Node_Id;
1814          S          : Node_Id;
1815          Check_List : List_Id);
1816       --  Process an index constraint in a constrained array declaration.
1817       --  The constraint can be a subtype name, or a range with or without
1818       --  an explicit subtype mark. The index is the corresponding index of the
1819       --  unconstrained array. S is the range expression. Check_List is a list
1820       --  to which the check actions are appended (called from
1821       --  Build_Record_Checks).
1822
1823       function Parent_Subtype_Renaming_Discrims return Boolean;
1824       --  Returns True for base types N that rename discriminants, else False
1825
1826       function Requires_Init_Proc (Rec_Id : Entity_Id) return Boolean;
1827       --  Determines whether a record initialization procedure needs to be
1828       --  generated for the given record type.
1829
1830       ----------------------
1831       -- Build_Assignment --
1832       ----------------------
1833
1834       function Build_Assignment (Id : Entity_Id; N : Node_Id) return List_Id is
1835          Exp  : Node_Id := N;
1836          Lhs  : Node_Id;
1837          Typ  : constant Entity_Id := Underlying_Type (Etype (Id));
1838          Kind : Node_Kind := Nkind (N);
1839          Res  : List_Id;
1840
1841       begin
1842          Loc := Sloc (N);
1843          Lhs :=
1844            Make_Selected_Component (Loc,
1845              Prefix => Make_Identifier (Loc, Name_uInit),
1846              Selector_Name => New_Occurrence_Of (Id, Loc));
1847          Set_Assignment_OK (Lhs);
1848
1849          --  Case of an access attribute applied to the current instance.
1850          --  Replace the reference to the type by a reference to the actual
1851          --  object. (Note that this handles the case of the top level of
1852          --  the expression being given by such an attribute, but does not
1853          --  cover uses nested within an initial value expression. Nested
1854          --  uses are unlikely to occur in practice, but are theoretically
1855          --  possible. It is not clear how to handle them without fully
1856          --  traversing the expression. ???
1857
1858          if Kind = N_Attribute_Reference
1859            and then (Attribute_Name (N) = Name_Unchecked_Access
1860                        or else
1861                      Attribute_Name (N) = Name_Unrestricted_Access)
1862            and then Is_Entity_Name (Prefix (N))
1863            and then Is_Type (Entity (Prefix (N)))
1864            and then Entity (Prefix (N)) = Rec_Type
1865          then
1866             Exp :=
1867               Make_Attribute_Reference (Loc,
1868                 Prefix         => Make_Identifier (Loc, Name_uInit),
1869                 Attribute_Name => Name_Unrestricted_Access);
1870          end if;
1871
1872          --  Take a copy of Exp to ensure that later copies of this component
1873          --  declaration in derived types see the original tree, not a node
1874          --  rewritten during expansion of the init_proc. If the copy contains
1875          --  itypes, the scope of the new itypes is the init_proc being built.
1876
1877          Exp := New_Copy_Tree (Exp, New_Scope => Proc_Id);
1878
1879          Res := New_List (
1880            Make_Assignment_Statement (Loc,
1881              Name       => Lhs,
1882              Expression => Exp));
1883
1884          Set_No_Ctrl_Actions (First (Res));
1885
1886          --  Adjust the tag if tagged (because of possible view conversions).
1887          --  Suppress the tag adjustment when VM_Target because VM tags are
1888          --  represented implicitly in objects.
1889
1890          if Is_Tagged_Type (Typ) and then Tagged_Type_Expansion then
1891             Append_To (Res,
1892               Make_Assignment_Statement (Loc,
1893                 Name =>
1894                   Make_Selected_Component (Loc,
1895                     Prefix =>  New_Copy_Tree (Lhs, New_Scope => Proc_Id),
1896                     Selector_Name =>
1897                       New_Reference_To (First_Tag_Component (Typ), Loc)),
1898
1899                 Expression =>
1900                   Unchecked_Convert_To (RTE (RE_Tag),
1901                     New_Reference_To
1902                       (Node (First_Elmt (Access_Disp_Table (Typ))), Loc))));
1903          end if;
1904
1905          --  Adjust the component if controlled except if it is an aggregate
1906          --  that will be expanded inline.
1907
1908          if Kind = N_Qualified_Expression then
1909             Kind := Nkind (Expression (N));
1910          end if;
1911
1912          if Needs_Finalization (Typ)
1913            and then not (Nkind_In (Kind, N_Aggregate, N_Extension_Aggregate))
1914            and then not Is_Inherently_Limited_Type (Typ)
1915          then
1916             declare
1917                Ref : constant Node_Id :=
1918                        New_Copy_Tree (Lhs, New_Scope => Proc_Id);
1919             begin
1920                Append_List_To (Res,
1921                  Make_Adjust_Call (
1922                   Ref          => Ref,
1923                   Typ          => Etype (Id),
1924                   Flist_Ref    => Find_Final_List (Etype (Id), Ref),
1925                   With_Attach  => Make_Integer_Literal (Loc, 1)));
1926             end;
1927          end if;
1928
1929          return Res;
1930
1931       exception
1932          when RE_Not_Available =>
1933             return Empty_List;
1934       end Build_Assignment;
1935
1936       ------------------------------------
1937       -- Build_Discriminant_Assignments --
1938       ------------------------------------
1939
1940       procedure Build_Discriminant_Assignments (Statement_List : List_Id) is
1941          D         : Entity_Id;
1942          Is_Tagged : constant Boolean := Is_Tagged_Type (Rec_Type);
1943
1944       begin
1945          if Has_Discriminants (Rec_Type)
1946            and then not Is_Unchecked_Union (Rec_Type)
1947          then
1948             D := First_Discriminant (Rec_Type);
1949
1950             while Present (D) loop
1951
1952                --  Don't generate the assignment for discriminants in derived
1953                --  tagged types if the discriminant is a renaming of some
1954                --  ancestor discriminant. This initialization will be done
1955                --  when initializing the _parent field of the derived record.
1956
1957                if Is_Tagged and then
1958                  Present (Corresponding_Discriminant (D))
1959                then
1960                   null;
1961
1962                else
1963                   Loc := Sloc (D);
1964                   Append_List_To (Statement_List,
1965                     Build_Assignment (D,
1966                       New_Reference_To (Discriminal (D), Loc)));
1967                end if;
1968
1969                Next_Discriminant (D);
1970             end loop;
1971          end if;
1972       end Build_Discriminant_Assignments;
1973
1974       --------------------------
1975       -- Build_Init_Call_Thru --
1976       --------------------------
1977
1978       function Build_Init_Call_Thru (Parameters : List_Id) return List_Id is
1979          Parent_Proc : constant Entity_Id :=
1980                          Base_Init_Proc (Etype (Rec_Type));
1981
1982          Parent_Type : constant Entity_Id :=
1983                          Etype (First_Formal (Parent_Proc));
1984
1985          Uparent_Type : constant Entity_Id :=
1986                           Underlying_Type (Parent_Type);
1987
1988          First_Discr_Param : Node_Id;
1989
1990          Parent_Discr : Entity_Id;
1991          First_Arg    : Node_Id;
1992          Args         : List_Id;
1993          Arg          : Node_Id;
1994          Res          : List_Id;
1995
1996       begin
1997          --  First argument (_Init) is the object to be initialized.
1998          --  ??? not sure where to get a reasonable Loc for First_Arg
1999
2000          First_Arg :=
2001            OK_Convert_To (Parent_Type,
2002              New_Reference_To (Defining_Identifier (First (Parameters)), Loc));
2003
2004          Set_Etype (First_Arg, Parent_Type);
2005
2006          Args := New_List (Convert_Concurrent (First_Arg, Rec_Type));
2007
2008          --  In the tasks case,
2009          --    add _Master as the value of the _Master parameter
2010          --    add _Chain as the value of the _Chain parameter.
2011          --    add _Task_Name as the value of the _Task_Name parameter.
2012          --  At the outer level, these will be variables holding the
2013          --  corresponding values obtained from GNARL or the expander.
2014          --
2015          --  At inner levels, they will be the parameters passed down through
2016          --  the outer routines.
2017
2018          First_Discr_Param := Next (First (Parameters));
2019
2020          if Has_Task (Rec_Type) then
2021             if Restriction_Active (No_Task_Hierarchy) then
2022
2023                --  See comments in System.Tasking.Initialization.Init_RTS
2024                --  for the value 3.
2025
2026                Append_To (Args, Make_Integer_Literal (Loc, 3));
2027             else
2028                Append_To (Args, Make_Identifier (Loc, Name_uMaster));
2029             end if;
2030
2031             Append_To (Args, Make_Identifier (Loc, Name_uChain));
2032             Append_To (Args, Make_Identifier (Loc, Name_uTask_Name));
2033             First_Discr_Param := Next (Next (Next (First_Discr_Param)));
2034          end if;
2035
2036          --  Append discriminant values
2037
2038          if Has_Discriminants (Uparent_Type) then
2039             pragma Assert (not Is_Tagged_Type (Uparent_Type));
2040
2041             Parent_Discr := First_Discriminant (Uparent_Type);
2042             while Present (Parent_Discr) loop
2043
2044                --  Get the initial value for this discriminant
2045                --  ??? needs to be cleaned up to use parent_Discr_Constr
2046                --  directly.
2047
2048                declare
2049                   Discr_Value : Elmt_Id :=
2050                                   First_Elmt
2051                                     (Stored_Constraint (Rec_Type));
2052
2053                   Discr       : Entity_Id :=
2054                                   First_Stored_Discriminant (Uparent_Type);
2055                begin
2056                   while Original_Record_Component (Parent_Discr) /= Discr loop
2057                      Next_Stored_Discriminant (Discr);
2058                      Next_Elmt (Discr_Value);
2059                   end loop;
2060
2061                   Arg := Node (Discr_Value);
2062                end;
2063
2064                --  Append it to the list
2065
2066                if Nkind (Arg) = N_Identifier
2067                   and then Ekind (Entity (Arg)) = E_Discriminant
2068                then
2069                   Append_To (Args,
2070                     New_Reference_To (Discriminal (Entity (Arg)), Loc));
2071
2072                --  Case of access discriminants. We replace the reference
2073                --  to the type by a reference to the actual object.
2074
2075                --  Is above comment right??? Use of New_Copy below seems mighty
2076                --  suspicious ???
2077
2078                else
2079                   Append_To (Args, New_Copy (Arg));
2080                end if;
2081
2082                Next_Discriminant (Parent_Discr);
2083             end loop;
2084          end if;
2085
2086          Res :=
2087             New_List (
2088               Make_Procedure_Call_Statement (Loc,
2089                 Name => New_Occurrence_Of (Parent_Proc, Loc),
2090                 Parameter_Associations => Args));
2091
2092          return Res;
2093       end Build_Init_Call_Thru;
2094
2095       -----------------------------------
2096       -- Build_Offset_To_Top_Functions --
2097       -----------------------------------
2098
2099       procedure Build_Offset_To_Top_Functions is
2100
2101          procedure Build_Offset_To_Top_Function (Iface_Comp : Entity_Id);
2102          --  Generate:
2103          --    function Fxx (O : in Rec_Typ) return Storage_Offset is
2104          --    begin
2105          --       return O.Iface_Comp'Position;
2106          --    end Fxx;
2107
2108          ----------------------------------
2109          -- Build_Offset_To_Top_Function --
2110          ----------------------------------
2111
2112          procedure Build_Offset_To_Top_Function (Iface_Comp : Entity_Id) is
2113             Body_Node : Node_Id;
2114             Func_Id   : Entity_Id;
2115             Spec_Node : Node_Id;
2116
2117          begin
2118             Func_Id := Make_Temporary (Loc, 'F');
2119             Set_DT_Offset_To_Top_Func (Iface_Comp, Func_Id);
2120
2121             --  Generate
2122             --    function Fxx (O : in Rec_Typ) return Storage_Offset;
2123
2124             Spec_Node := New_Node (N_Function_Specification, Loc);
2125             Set_Defining_Unit_Name (Spec_Node, Func_Id);
2126             Set_Parameter_Specifications (Spec_Node, New_List (
2127               Make_Parameter_Specification (Loc,
2128                 Defining_Identifier => Make_Defining_Identifier (Loc, Name_uO),
2129                 In_Present          => True,
2130                 Parameter_Type      => New_Reference_To (Rec_Type, Loc))));
2131             Set_Result_Definition (Spec_Node,
2132               New_Reference_To (RTE (RE_Storage_Offset), Loc));
2133
2134             --  Generate
2135             --    function Fxx (O : in Rec_Typ) return Storage_Offset is
2136             --    begin
2137             --       return O.Iface_Comp'Position;
2138             --    end Fxx;
2139
2140             Body_Node := New_Node (N_Subprogram_Body, Loc);
2141             Set_Specification (Body_Node, Spec_Node);
2142             Set_Declarations (Body_Node, New_List);
2143             Set_Handled_Statement_Sequence (Body_Node,
2144               Make_Handled_Sequence_Of_Statements (Loc,
2145                 Statements => New_List (
2146                   Make_Simple_Return_Statement (Loc,
2147                     Expression =>
2148                       Make_Attribute_Reference (Loc,
2149                         Prefix =>
2150                           Make_Selected_Component (Loc,
2151                             Prefix => Make_Identifier (Loc, Name_uO),
2152                             Selector_Name => New_Reference_To
2153                                                (Iface_Comp, Loc)),
2154                         Attribute_Name => Name_Position)))));
2155
2156             Set_Ekind       (Func_Id, E_Function);
2157             Set_Mechanism   (Func_Id, Default_Mechanism);
2158             Set_Is_Internal (Func_Id, True);
2159
2160             if not Debug_Generated_Code then
2161                Set_Debug_Info_Off (Func_Id);
2162             end if;
2163
2164             Analyze (Body_Node);
2165
2166             Append_Freeze_Action (Rec_Type, Body_Node);
2167          end Build_Offset_To_Top_Function;
2168
2169          --  Local variables
2170
2171          Ifaces_Comp_List : Elist_Id;
2172          Iface_Comp_Elmt  : Elmt_Id;
2173          Iface_Comp       : Node_Id;
2174
2175       --  Start of processing for Build_Offset_To_Top_Functions
2176
2177       begin
2178          --  Offset_To_Top_Functions are built only for derivations of types
2179          --  with discriminants that cover interface types.
2180          --  Nothing is needed either in case of virtual machines, since
2181          --  interfaces are handled directly by the VM.
2182
2183          if not Is_Tagged_Type (Rec_Type)
2184            or else Etype (Rec_Type) = Rec_Type
2185            or else not Has_Discriminants (Etype (Rec_Type))
2186            or else not Tagged_Type_Expansion
2187          then
2188             return;
2189          end if;
2190
2191          Collect_Interface_Components (Rec_Type, Ifaces_Comp_List);
2192
2193          --  For each interface type with secondary dispatch table we generate
2194          --  the Offset_To_Top_Functions (required to displace the pointer in
2195          --  interface conversions)
2196
2197          Iface_Comp_Elmt := First_Elmt (Ifaces_Comp_List);
2198          while Present (Iface_Comp_Elmt) loop
2199             Iface_Comp := Node (Iface_Comp_Elmt);
2200             pragma Assert (Is_Interface (Related_Type (Iface_Comp)));
2201
2202             --  If the interface is a parent of Rec_Type it shares the primary
2203             --  dispatch table and hence there is no need to build the function
2204
2205             if not Is_Ancestor (Related_Type (Iface_Comp), Rec_Type) then
2206                Build_Offset_To_Top_Function (Iface_Comp);
2207             end if;
2208
2209             Next_Elmt (Iface_Comp_Elmt);
2210          end loop;
2211       end Build_Offset_To_Top_Functions;
2212
2213       --------------------------
2214       -- Build_Init_Procedure --
2215       --------------------------
2216
2217       procedure Build_Init_Procedure is
2218          Body_Node             : Node_Id;
2219          Handled_Stmt_Node     : Node_Id;
2220          Parameters            : List_Id;
2221          Proc_Spec_Node        : Node_Id;
2222          Body_Stmts            : List_Id;
2223          Record_Extension_Node : Node_Id;
2224          Init_Tags_List        : List_Id;
2225
2226       begin
2227          Body_Stmts := New_List;
2228          Body_Node := New_Node (N_Subprogram_Body, Loc);
2229          Set_Ekind (Proc_Id, E_Procedure);
2230
2231          Proc_Spec_Node := New_Node (N_Procedure_Specification, Loc);
2232          Set_Defining_Unit_Name (Proc_Spec_Node, Proc_Id);
2233
2234          Parameters := Init_Formals (Rec_Type);
2235          Append_List_To (Parameters,
2236            Build_Discriminant_Formals (Rec_Type, True));
2237
2238          --  For tagged types, we add a flag to indicate whether the routine
2239          --  is called to initialize a parent component in the init_proc of
2240          --  a type extension. If the flag is false, we do not set the tag
2241          --  because it has been set already in the extension.
2242
2243          if Is_Tagged_Type (Rec_Type)
2244            and then not Is_CPP_Class (Rec_Type)
2245          then
2246             Set_Tag := Make_Temporary (Loc, 'P');
2247
2248             Append_To (Parameters,
2249               Make_Parameter_Specification (Loc,
2250                 Defining_Identifier => Set_Tag,
2251                 Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
2252                 Expression => New_Occurrence_Of (Standard_True, Loc)));
2253          end if;
2254
2255          Set_Parameter_Specifications (Proc_Spec_Node, Parameters);
2256          Set_Specification (Body_Node, Proc_Spec_Node);
2257          Set_Declarations (Body_Node, New_List);
2258
2259          if Parent_Subtype_Renaming_Discrims then
2260
2261             --  N is a Derived_Type_Definition that renames the parameters
2262             --  of the ancestor type. We initialize it by expanding our
2263             --  discriminants and call the ancestor _init_proc with a
2264             --  type-converted object
2265
2266             Append_List_To (Body_Stmts,
2267               Build_Init_Call_Thru (Parameters));
2268
2269          elsif Nkind (Type_Definition (N)) = N_Record_Definition then
2270             Build_Discriminant_Assignments (Body_Stmts);
2271
2272             if not Null_Present (Type_Definition (N)) then
2273                Append_List_To (Body_Stmts,
2274                  Build_Init_Statements (
2275                    Component_List (Type_Definition (N))));
2276             end if;
2277
2278          else
2279             --  N is a Derived_Type_Definition with a possible non-empty
2280             --  extension. The initialization of a type extension consists
2281             --  in the initialization of the components in the extension.
2282
2283             Build_Discriminant_Assignments (Body_Stmts);
2284
2285             Record_Extension_Node :=
2286               Record_Extension_Part (Type_Definition (N));
2287
2288             if not Null_Present (Record_Extension_Node) then
2289                declare
2290                   Stmts : constant List_Id :=
2291                             Build_Init_Statements (
2292                               Component_List (Record_Extension_Node));
2293
2294                begin
2295                   --  The parent field must be initialized first because
2296                   --  the offset of the new discriminants may depend on it
2297
2298                   Prepend_To (Body_Stmts, Remove_Head (Stmts));
2299                   Append_List_To (Body_Stmts, Stmts);
2300                end;
2301             end if;
2302          end if;
2303
2304          --  Add here the assignment to instantiate the Tag
2305
2306          --  The assignment corresponds to the code:
2307
2308          --     _Init._Tag := Typ'Tag;
2309
2310          --  Suppress the tag assignment when VM_Target because VM tags are
2311          --  represented implicitly in objects. It is also suppressed in case
2312          --  of CPP_Class types because in this case the tag is initialized in
2313          --  the C++ side.
2314
2315          if Is_Tagged_Type (Rec_Type)
2316            and then not Is_CPP_Class (Rec_Type)
2317            and then Tagged_Type_Expansion
2318            and then not No_Run_Time_Mode
2319          then
2320             --  Initialize the primary tag
2321
2322             Init_Tags_List := New_List (
2323               Make_Assignment_Statement (Loc,
2324                 Name =>
2325                   Make_Selected_Component (Loc,
2326                     Prefix => Make_Identifier (Loc, Name_uInit),
2327                     Selector_Name =>
2328                       New_Reference_To (First_Tag_Component (Rec_Type), Loc)),
2329
2330                 Expression =>
2331                   New_Reference_To
2332                     (Node (First_Elmt (Access_Disp_Table (Rec_Type))), Loc)));
2333
2334             --  Generate the SCIL node associated with the initialization of
2335             --  the tag component.
2336
2337             if Generate_SCIL then
2338                declare
2339                   New_Node : Node_Id;
2340
2341                begin
2342                   New_Node :=
2343                     Make_SCIL_Tag_Init (Sloc (First (Init_Tags_List)));
2344                   Set_SCIL_Related_Node (New_Node, First (Init_Tags_List));
2345                   Set_SCIL_Entity (New_Node, Rec_Type);
2346                   Prepend_To (Init_Tags_List, New_Node);
2347                end;
2348             end if;
2349
2350             --  Ada 2005 (AI-251): Initialize the secondary tags components
2351             --  located at fixed positions (tags whose position depends on
2352             --  variable size components are initialized later ---see below).
2353
2354             if Ada_Version >= Ada_05
2355               and then not Is_Interface (Rec_Type)
2356               and then Has_Interfaces (Rec_Type)
2357             then
2358                Init_Secondary_Tags
2359                  (Typ            => Rec_Type,
2360                   Target         => Make_Identifier (Loc, Name_uInit),
2361                   Stmts_List     => Init_Tags_List,
2362                   Fixed_Comps    => True,
2363                   Variable_Comps => False);
2364             end if;
2365
2366             --  The tag must be inserted before the assignments to other
2367             --  components,  because the initial value of the component may
2368             --  depend on the tag (eg. through a dispatching operation on
2369             --  an access to the current type). The tag assignment is not done
2370             --  when initializing the parent component of a type extension,
2371             --  because in that case the tag is set in the extension.
2372
2373             --  Extensions of imported C++ classes add a final complication,
2374             --  because we cannot inhibit tag setting in the constructor for
2375             --  the parent. In that case we insert the tag initialization
2376             --  after the calls to initialize the parent.
2377
2378             if not Is_CPP_Class (Root_Type (Rec_Type)) then
2379                Prepend_To (Body_Stmts,
2380                  Make_If_Statement (Loc,
2381                    Condition => New_Occurrence_Of (Set_Tag, Loc),
2382                    Then_Statements => Init_Tags_List));
2383
2384             --  CPP_Class derivation: In this case the dispatch table of the
2385             --  parent was built in the C++ side and we copy the table of the
2386             --  parent to initialize the new dispatch table.
2387
2388             else
2389                declare
2390                   Nod : Node_Id;
2391
2392                begin
2393                   --  We assume the first init_proc call is for the parent
2394
2395                   Nod := First (Body_Stmts);
2396                   while Present (Next (Nod))
2397                     and then (Nkind (Nod) /= N_Procedure_Call_Statement
2398                                or else not Is_Init_Proc (Name (Nod)))
2399                   loop
2400                      Nod := Next (Nod);
2401                   end loop;
2402
2403                   --  Generate:
2404                   --     ancestor_constructor (_init.parent);
2405                   --     if Arg2 then
2406                   --        inherit_prim_ops (_init._tag, new_dt, num_prims);
2407                   --        _init._tag := new_dt;
2408                   --     end if;
2409
2410                   Prepend_To (Init_Tags_List,
2411                     Build_Inherit_Prims (Loc,
2412                       Typ          => Rec_Type,
2413                       Old_Tag_Node =>
2414                         Make_Selected_Component (Loc,
2415                           Prefix        =>
2416                             Make_Identifier (Loc,
2417                               Chars => Name_uInit),
2418                           Selector_Name =>
2419                             New_Reference_To
2420                               (First_Tag_Component (Rec_Type), Loc)),
2421                       New_Tag_Node =>
2422                         New_Reference_To
2423                           (Node (First_Elmt (Access_Disp_Table (Rec_Type))),
2424                            Loc),
2425                       Num_Prims    =>
2426                         UI_To_Int
2427                           (DT_Entry_Count (First_Tag_Component (Rec_Type)))));
2428
2429                   Insert_After (Nod,
2430                     Make_If_Statement (Loc,
2431                       Condition => New_Occurrence_Of (Set_Tag, Loc),
2432                       Then_Statements => Init_Tags_List));
2433
2434                   --  We have inherited table of the parent from the CPP side.
2435                   --  Now we fill the slots associated with Ada primitives.
2436                   --  This needs more work to avoid its execution each time
2437                   --  an object is initialized???
2438
2439                   declare
2440                      E    : Elmt_Id;
2441                      Prim : Node_Id;
2442
2443                   begin
2444                      E := First_Elmt (Primitive_Operations (Rec_Type));
2445                      while Present (E) loop
2446                         Prim := Node (E);
2447
2448                         if not Is_Imported (Prim)
2449                           and then Convention (Prim) = Convention_CPP
2450                           and then not Present (Interface_Alias (Prim))
2451                         then
2452                            Append_List_To (Init_Tags_List,
2453                              Register_Primitive (Loc, Prim => Prim));
2454                         end if;
2455
2456                         Next_Elmt (E);
2457                      end loop;
2458                   end;
2459                end;
2460             end if;
2461
2462             --  Ada 2005 (AI-251): Initialize the secondary tag components
2463             --  located at variable positions. We delay the generation of this
2464             --  code until here because the value of the attribute 'Position
2465             --  applied to variable size components of the parent type that
2466             --  depend on discriminants is only safely read at runtime after
2467             --  the parent components have been initialized.
2468
2469             if Ada_Version >= Ada_05
2470               and then not Is_Interface (Rec_Type)
2471               and then Has_Interfaces (Rec_Type)
2472               and then Has_Discriminants (Etype (Rec_Type))
2473               and then Is_Variable_Size_Record (Etype (Rec_Type))
2474             then
2475                Init_Tags_List := New_List;
2476
2477                Init_Secondary_Tags
2478                  (Typ            => Rec_Type,
2479                   Target         => Make_Identifier (Loc, Name_uInit),
2480                   Stmts_List     => Init_Tags_List,
2481                   Fixed_Comps    => False,
2482                   Variable_Comps => True);
2483
2484                if Is_Non_Empty_List (Init_Tags_List) then
2485                   Append_List_To (Body_Stmts, Init_Tags_List);
2486                end if;
2487             end if;
2488          end if;
2489
2490          Handled_Stmt_Node := New_Node (N_Handled_Sequence_Of_Statements, Loc);
2491          Set_Statements (Handled_Stmt_Node, Body_Stmts);
2492          Set_Exception_Handlers (Handled_Stmt_Node, No_List);
2493          Set_Handled_Statement_Sequence (Body_Node, Handled_Stmt_Node);
2494
2495          if not Debug_Generated_Code then
2496             Set_Debug_Info_Off (Proc_Id);
2497          end if;
2498
2499          --  Associate Init_Proc with type, and determine if the procedure
2500          --  is null (happens because of the Initialize_Scalars pragma case,
2501          --  where we have to generate a null procedure in case it is called
2502          --  by a client with Initialize_Scalars set). Such procedures have
2503          --  to be generated, but do not have to be called, so we mark them
2504          --  as null to suppress the call.
2505
2506          Set_Init_Proc (Rec_Type, Proc_Id);
2507
2508          if List_Length (Body_Stmts) = 1
2509
2510            --  We must skip SCIL nodes because they may have been added to this
2511            --  list by Insert_Actions.
2512
2513            and then Nkind (First_Non_SCIL_Node (Body_Stmts)) = N_Null_Statement
2514            and then VM_Target = No_VM
2515          then
2516             --  Even though the init proc may be null at this time it might get
2517             --  some stuff added to it later by the VM backend.
2518
2519             Set_Is_Null_Init_Proc (Proc_Id);
2520          end if;
2521       end Build_Init_Procedure;
2522
2523       ---------------------------
2524       -- Build_Init_Statements --
2525       ---------------------------
2526
2527       function Build_Init_Statements (Comp_List : Node_Id) return List_Id is
2528          Check_List     : constant List_Id := New_List;
2529          Alt_List       : List_Id;
2530          Decl           : Node_Id;
2531          Id             : Entity_Id;
2532          Names          : Node_Id;
2533          Statement_List : List_Id;
2534          Stmts          : List_Id;
2535          Typ            : Entity_Id;
2536          Variant        : Node_Id;
2537
2538          Per_Object_Constraint_Components : Boolean;
2539
2540          function Has_Access_Constraint (E : Entity_Id) return Boolean;
2541          --  Components with access discriminants that depend on the current
2542          --  instance must be initialized after all other components.
2543
2544          ---------------------------
2545          -- Has_Access_Constraint --
2546          ---------------------------
2547
2548          function Has_Access_Constraint (E : Entity_Id) return Boolean is
2549             Disc : Entity_Id;
2550             T    : constant Entity_Id := Etype (E);
2551
2552          begin
2553             if Has_Per_Object_Constraint (E)
2554               and then Has_Discriminants (T)
2555             then
2556                Disc := First_Discriminant (T);
2557                while Present (Disc) loop
2558                   if Is_Access_Type (Etype (Disc)) then
2559                      return True;
2560                   end if;
2561
2562                   Next_Discriminant (Disc);
2563                end loop;
2564
2565                return False;
2566             else
2567                return False;
2568             end if;
2569          end Has_Access_Constraint;
2570
2571       --  Start of processing for Build_Init_Statements
2572
2573       begin
2574          if Null_Present (Comp_List) then
2575             return New_List (Make_Null_Statement (Loc));
2576          end if;
2577
2578          Statement_List := New_List;
2579
2580          --  Loop through visible declarations of task types and protected
2581          --  types moving any expanded code from the spec to the body of the
2582          --  init procedure.
2583
2584          if Is_Task_Record_Type (Rec_Type)
2585            or else Is_Protected_Record_Type (Rec_Type)
2586          then
2587             declare
2588                Decl : constant Node_Id :=
2589                         Parent (Corresponding_Concurrent_Type (Rec_Type));
2590                Def  : Node_Id;
2591                N1   : Node_Id;
2592                N2   : Node_Id;
2593
2594             begin
2595                if Is_Task_Record_Type (Rec_Type) then
2596                   Def := Task_Definition (Decl);
2597                else
2598                   Def := Protected_Definition (Decl);
2599                end if;
2600
2601                if Present (Def) then
2602                   N1 := First (Visible_Declarations (Def));
2603                   while Present (N1) loop
2604                      N2 := N1;
2605                      N1 := Next (N1);
2606
2607                      if Nkind (N2) in N_Statement_Other_Than_Procedure_Call
2608                        or else Nkind (N2) in N_Raise_xxx_Error
2609                        or else Nkind (N2) = N_Procedure_Call_Statement
2610                      then
2611                         Append_To (Statement_List,
2612                           New_Copy_Tree (N2, New_Scope => Proc_Id));
2613                         Rewrite (N2, Make_Null_Statement (Sloc (N2)));
2614                         Analyze (N2);
2615                      end if;
2616                   end loop;
2617                end if;
2618             end;
2619          end if;
2620
2621          --  Loop through components, skipping pragmas, in 2 steps. The first
2622          --  step deals with regular components. The second step deals with
2623          --  components have per object constraints, and no explicit initia-
2624          --  lization.
2625
2626          Per_Object_Constraint_Components := False;
2627
2628          --  First step : regular components
2629
2630          Decl := First_Non_Pragma (Component_Items (Comp_List));
2631          while Present (Decl) loop
2632             Loc := Sloc (Decl);
2633             Build_Record_Checks
2634               (Subtype_Indication (Component_Definition (Decl)), Check_List);
2635
2636             Id := Defining_Identifier (Decl);
2637             Typ := Etype (Id);
2638
2639             if Has_Access_Constraint (Id)
2640               and then No (Expression (Decl))
2641             then
2642                --  Skip processing for now and ask for a second pass
2643
2644                Per_Object_Constraint_Components := True;
2645
2646             else
2647                --  Case of explicit initialization
2648
2649                if Present (Expression (Decl)) then
2650                   if Is_CPP_Constructor_Call (Expression (Decl)) then
2651                      Stmts :=
2652                        Build_Initialization_Call
2653                          (Loc,
2654                           Id_Ref          =>
2655                             Make_Selected_Component (Loc,
2656                               Prefix        =>
2657                                 Make_Identifier (Loc, Name_uInit),
2658                               Selector_Name => New_Occurrence_Of (Id, Loc)),
2659                           Typ             => Typ,
2660                           In_Init_Proc    => True,
2661                           Enclos_Type     => Rec_Type,
2662                           Discr_Map       => Discr_Map,
2663                           Constructor_Ref => Expression (Decl));
2664                   else
2665                      Stmts := Build_Assignment (Id, Expression (Decl));
2666                   end if;
2667
2668                --  Case of composite component with its own Init_Proc
2669
2670                elsif not Is_Interface (Typ)
2671                  and then Has_Non_Null_Base_Init_Proc (Typ)
2672                then
2673                   Stmts :=
2674                     Build_Initialization_Call
2675                       (Loc,
2676                        Id_Ref       =>
2677                          Make_Selected_Component (Loc,
2678                            Prefix        => Make_Identifier (Loc, Name_uInit),
2679                            Selector_Name => New_Occurrence_Of (Id, Loc)),
2680                        Typ          => Typ,
2681                        In_Init_Proc => True,
2682                        Enclos_Type  => Rec_Type,
2683                        Discr_Map    => Discr_Map);
2684
2685                   Clean_Task_Names (Typ, Proc_Id);
2686
2687                --  Case of component needing simple initialization
2688
2689                elsif Component_Needs_Simple_Initialization (Typ) then
2690                   Stmts :=
2691                     Build_Assignment
2692                       (Id, Get_Simple_Init_Val (Typ, N, Esize (Id)));
2693
2694                --  Nothing needed for this case
2695
2696                else
2697                   Stmts := No_List;
2698                end if;
2699
2700                if Present (Check_List) then
2701                   Append_List_To (Statement_List, Check_List);
2702                end if;
2703
2704                if Present (Stmts) then
2705
2706                   --  Add the initialization of the record controller before
2707                   --  the _Parent field is attached to it when the attachment
2708                   --  can occur. It does not work to simply initialize the
2709                   --  controller first: it must be initialized after the parent
2710                   --  if the parent holds discriminants that can be used to
2711                   --  compute the offset of the controller. We assume here that
2712                   --  the last statement of the initialization call is the
2713                   --  attachment of the parent (see Build_Initialization_Call)
2714
2715                   if Chars (Id) = Name_uController
2716                     and then Rec_Type /= Etype (Rec_Type)
2717                     and then Has_Controlled_Component (Etype (Rec_Type))
2718                     and then Has_New_Controlled_Component (Rec_Type)
2719                     and then Present (Last (Statement_List))
2720                   then
2721                      Insert_List_Before (Last (Statement_List), Stmts);
2722                   else
2723                      Append_List_To (Statement_List, Stmts);
2724                   end if;
2725                end if;
2726             end if;
2727
2728             Next_Non_Pragma (Decl);
2729          end loop;
2730
2731          --  Set up tasks and protected object support. This needs to be done
2732          --  before any component with a per-object access discriminant
2733          --  constraint, or any variant part (which may contain such
2734          --  components) is initialized, because the initialization of these
2735          --  components may reference the enclosing concurrent object.
2736
2737          --  For a task record type, add the task create call and calls
2738          --  to bind any interrupt (signal) entries.
2739
2740          if Is_Task_Record_Type (Rec_Type) then
2741
2742             --  In the case of the restricted run time the ATCB has already
2743             --  been preallocated.
2744
2745             if Restricted_Profile then
2746                Append_To (Statement_List,
2747                  Make_Assignment_Statement (Loc,
2748                    Name => Make_Selected_Component (Loc,
2749                      Prefix => Make_Identifier (Loc, Name_uInit),
2750                      Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
2751                    Expression => Make_Attribute_Reference (Loc,
2752                      Prefix =>
2753                        Make_Selected_Component (Loc,
2754                          Prefix => Make_Identifier (Loc, Name_uInit),
2755                          Selector_Name =>
2756                            Make_Identifier (Loc, Name_uATCB)),
2757                      Attribute_Name => Name_Unchecked_Access)));
2758             end if;
2759
2760             Append_To (Statement_List, Make_Task_Create_Call (Rec_Type));
2761
2762             --  Generate the statements which map a string entry name to a
2763             --  task entry index. Note that the task may not have entries.
2764
2765             if Entry_Names_OK then
2766                Names := Build_Entry_Names (Rec_Type);
2767
2768                if Present (Names) then
2769                   Append_To (Statement_List, Names);
2770                end if;
2771             end if;
2772
2773             declare
2774                Task_Type : constant Entity_Id :=
2775                              Corresponding_Concurrent_Type (Rec_Type);
2776                Task_Decl : constant Node_Id := Parent (Task_Type);
2777                Task_Def  : constant Node_Id := Task_Definition (Task_Decl);
2778                Vis_Decl  : Node_Id;
2779                Ent       : Entity_Id;
2780
2781             begin
2782                if Present (Task_Def) then
2783                   Vis_Decl := First (Visible_Declarations (Task_Def));
2784                   while Present (Vis_Decl) loop
2785                      Loc := Sloc (Vis_Decl);
2786
2787                      if Nkind (Vis_Decl) = N_Attribute_Definition_Clause then
2788                         if Get_Attribute_Id (Chars (Vis_Decl)) =
2789                                                        Attribute_Address
2790                         then
2791                            Ent := Entity (Name (Vis_Decl));
2792
2793                            if Ekind (Ent) = E_Entry then
2794                               Append_To (Statement_List,
2795                                 Make_Procedure_Call_Statement (Loc,
2796                                   Name => New_Reference_To (
2797                                     RTE (RE_Bind_Interrupt_To_Entry), Loc),
2798                                   Parameter_Associations => New_List (
2799                                     Make_Selected_Component (Loc,
2800                                       Prefix =>
2801                                         Make_Identifier (Loc, Name_uInit),
2802                                       Selector_Name =>
2803                                         Make_Identifier (Loc, Name_uTask_Id)),
2804                                     Entry_Index_Expression (
2805                                       Loc, Ent, Empty, Task_Type),
2806                                     Expression (Vis_Decl))));
2807                            end if;
2808                         end if;
2809                      end if;
2810
2811                      Next (Vis_Decl);
2812                   end loop;
2813                end if;
2814             end;
2815          end if;
2816
2817          --  For a protected type, add statements generated by
2818          --  Make_Initialize_Protection.
2819
2820          if Is_Protected_Record_Type (Rec_Type) then
2821             Append_List_To (Statement_List,
2822               Make_Initialize_Protection (Rec_Type));
2823
2824             --  Generate the statements which map a string entry name to a
2825             --  protected entry index. Note that the protected type may not
2826             --  have entries.
2827
2828             if Entry_Names_OK then
2829                Names := Build_Entry_Names (Rec_Type);
2830
2831                if Present (Names) then
2832                   Append_To (Statement_List, Names);
2833                end if;
2834             end if;
2835          end if;
2836
2837          if Per_Object_Constraint_Components then
2838
2839             --  Second pass: components with per-object constraints
2840
2841             Decl := First_Non_Pragma (Component_Items (Comp_List));
2842             while Present (Decl) loop
2843                Loc := Sloc (Decl);
2844                Id := Defining_Identifier (Decl);
2845                Typ := Etype (Id);
2846
2847                if Has_Access_Constraint (Id)
2848                  and then No (Expression (Decl))
2849                then
2850                   if Has_Non_Null_Base_Init_Proc (Typ) then
2851                      Append_List_To (Statement_List,
2852                        Build_Initialization_Call (Loc,
2853                          Make_Selected_Component (Loc,
2854                            Prefix        => Make_Identifier (Loc, Name_uInit),
2855                            Selector_Name => New_Occurrence_Of (Id, Loc)),
2856                          Typ,
2857                          In_Init_Proc => True,
2858                          Enclos_Type  => Rec_Type,
2859                          Discr_Map    => Discr_Map));
2860
2861                      Clean_Task_Names (Typ, Proc_Id);
2862
2863                   elsif Component_Needs_Simple_Initialization (Typ) then
2864                      Append_List_To (Statement_List,
2865                        Build_Assignment
2866                          (Id, Get_Simple_Init_Val (Typ, N, Esize (Id))));
2867                   end if;
2868                end if;
2869
2870                Next_Non_Pragma (Decl);
2871             end loop;
2872          end if;
2873
2874          --  Process the variant part
2875
2876          if Present (Variant_Part (Comp_List)) then
2877             Alt_List := New_List;
2878             Variant := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
2879             while Present (Variant) loop
2880                Loc := Sloc (Variant);
2881                Append_To (Alt_List,
2882                  Make_Case_Statement_Alternative (Loc,
2883                    Discrete_Choices =>
2884                      New_Copy_List (Discrete_Choices (Variant)),
2885                    Statements =>
2886                      Build_Init_Statements (Component_List (Variant))));
2887                Next_Non_Pragma (Variant);
2888             end loop;
2889
2890             --  The expression of the case statement which is a reference
2891             --  to one of the discriminants is replaced by the appropriate
2892             --  formal parameter of the initialization procedure.
2893
2894             Append_To (Statement_List,
2895               Make_Case_Statement (Loc,
2896                 Expression =>
2897                   New_Reference_To (Discriminal (
2898                     Entity (Name (Variant_Part (Comp_List)))), Loc),
2899                 Alternatives => Alt_List));
2900          end if;
2901
2902          --  If no initializations when generated for component declarations
2903          --  corresponding to this Statement_List, append a null statement
2904          --  to the Statement_List to make it a valid Ada tree.
2905
2906          if Is_Empty_List (Statement_List) then
2907             Append (New_Node (N_Null_Statement, Loc), Statement_List);
2908          end if;
2909
2910          return Statement_List;
2911
2912       exception
2913          when RE_Not_Available =>
2914          return Empty_List;
2915       end Build_Init_Statements;
2916
2917       -------------------------
2918       -- Build_Record_Checks --
2919       -------------------------
2920
2921       procedure Build_Record_Checks (S : Node_Id; Check_List : List_Id) is
2922          Subtype_Mark_Id : Entity_Id;
2923
2924       begin
2925          if Nkind (S) = N_Subtype_Indication then
2926             Find_Type (Subtype_Mark (S));
2927             Subtype_Mark_Id := Entity (Subtype_Mark (S));
2928
2929             --  Remaining processing depends on type
2930
2931             case Ekind (Subtype_Mark_Id) is
2932
2933                when Array_Kind =>
2934                   Constrain_Array (S, Check_List);
2935
2936                when others =>
2937                   null;
2938             end case;
2939          end if;
2940       end Build_Record_Checks;
2941
2942       -------------------------------------------
2943       -- Component_Needs_Simple_Initialization --
2944       -------------------------------------------
2945
2946       function Component_Needs_Simple_Initialization
2947         (T : Entity_Id) return Boolean
2948       is
2949       begin
2950          return
2951            Needs_Simple_Initialization (T)
2952              and then not Is_RTE (T, RE_Tag)
2953
2954                --  Ada 2005 (AI-251): Check also the tag of abstract interfaces
2955
2956              and then not Is_RTE (T, RE_Interface_Tag);
2957       end Component_Needs_Simple_Initialization;
2958
2959       ---------------------
2960       -- Constrain_Array --
2961       ---------------------
2962
2963       procedure Constrain_Array
2964         (SI          : Node_Id;
2965          Check_List  : List_Id)
2966       is
2967          C                     : constant Node_Id := Constraint (SI);
2968          Number_Of_Constraints : Nat := 0;
2969          Index                 : Node_Id;
2970          S, T                  : Entity_Id;
2971
2972       begin
2973          T := Entity (Subtype_Mark (SI));
2974
2975          if Ekind (T) in Access_Kind then
2976             T := Designated_Type (T);
2977          end if;
2978
2979          S := First (Constraints (C));
2980
2981          while Present (S) loop
2982             Number_Of_Constraints := Number_Of_Constraints + 1;
2983             Next (S);
2984          end loop;
2985
2986          --  In either case, the index constraint must provide a discrete
2987          --  range for each index of the array type and the type of each
2988          --  discrete range must be the same as that of the corresponding
2989          --  index. (RM 3.6.1)
2990
2991          S := First (Constraints (C));
2992          Index := First_Index (T);
2993          Analyze (Index);
2994
2995          --  Apply constraints to each index type
2996
2997          for J in 1 .. Number_Of_Constraints loop
2998             Constrain_Index (Index, S, Check_List);
2999             Next (Index);
3000             Next (S);
3001          end loop;
3002
3003       end Constrain_Array;
3004
3005       ---------------------
3006       -- Constrain_Index --
3007       ---------------------
3008
3009       procedure Constrain_Index
3010         (Index        : Node_Id;
3011          S            : Node_Id;
3012          Check_List   : List_Id)
3013       is
3014          T : constant Entity_Id := Etype (Index);
3015
3016       begin
3017          if Nkind (S) = N_Range then
3018             Process_Range_Expr_In_Decl (S, T, Check_List);
3019          end if;
3020       end Constrain_Index;
3021
3022       --------------------------------------
3023       -- Parent_Subtype_Renaming_Discrims --
3024       --------------------------------------
3025
3026       function Parent_Subtype_Renaming_Discrims return Boolean is
3027          De : Entity_Id;
3028          Dp : Entity_Id;
3029
3030       begin
3031          if Base_Type (Pe) /= Pe then
3032             return False;
3033          end if;
3034
3035          if Etype (Pe) = Pe
3036            or else not Has_Discriminants (Pe)
3037            or else Is_Constrained (Pe)
3038            or else Is_Tagged_Type (Pe)
3039          then
3040             return False;
3041          end if;
3042
3043          --  If there are no explicit stored discriminants we have inherited
3044          --  the root type discriminants so far, so no renamings occurred.
3045
3046          if First_Discriminant (Pe) = First_Stored_Discriminant (Pe) then
3047             return False;
3048          end if;
3049
3050          --  Check if we have done some trivial renaming of the parent
3051          --  discriminants, i.e. something like
3052          --
3053          --    type DT (X1,X2: int) is new PT (X1,X2);
3054
3055          De := First_Discriminant (Pe);
3056          Dp := First_Discriminant (Etype (Pe));
3057
3058          while Present (De) loop
3059             pragma Assert (Present (Dp));
3060
3061             if Corresponding_Discriminant (De) /= Dp then
3062                return True;
3063             end if;
3064
3065             Next_Discriminant (De);
3066             Next_Discriminant (Dp);
3067          end loop;
3068
3069          return Present (Dp);
3070       end Parent_Subtype_Renaming_Discrims;
3071
3072       ------------------------
3073       -- Requires_Init_Proc --
3074       ------------------------
3075
3076       function Requires_Init_Proc (Rec_Id : Entity_Id) return Boolean is
3077          Comp_Decl : Node_Id;
3078          Id        : Entity_Id;
3079          Typ       : Entity_Id;
3080
3081       begin
3082          --  Definitely do not need one if specifically suppressed
3083
3084          if Suppress_Init_Proc (Rec_Id) then
3085             return False;
3086          end if;
3087
3088          --  If it is a type derived from a type with unknown discriminants,
3089          --  we cannot build an initialization procedure for it.
3090
3091          if Has_Unknown_Discriminants (Rec_Id)
3092            or else Has_Unknown_Discriminants (Etype (Rec_Id))
3093          then
3094             return False;
3095          end if;
3096
3097          --  Otherwise we need to generate an initialization procedure if
3098          --  Is_CPP_Class is False and at least one of the following applies:
3099
3100          --  1. Discriminants are present, since they need to be initialized
3101          --     with the appropriate discriminant constraint expressions.
3102          --     However, the discriminant of an unchecked union does not
3103          --     count, since the discriminant is not present.
3104
3105          --  2. The type is a tagged type, since the implicit Tag component
3106          --     needs to be initialized with a pointer to the dispatch table.
3107
3108          --  3. The type contains tasks
3109
3110          --  4. One or more components has an initial value
3111
3112          --  5. One or more components is for a type which itself requires
3113          --     an initialization procedure.
3114
3115          --  6. One or more components is a type that requires simple
3116          --     initialization (see Needs_Simple_Initialization), except
3117          --     that types Tag and Interface_Tag are excluded, since fields
3118          --     of these types are initialized by other means.
3119
3120          --  7. The type is the record type built for a task type (since at
3121          --     the very least, Create_Task must be called)
3122
3123          --  8. The type is the record type built for a protected type (since
3124          --     at least Initialize_Protection must be called)
3125
3126          --  9. The type is marked as a public entity. The reason we add this
3127          --     case (even if none of the above apply) is to properly handle
3128          --     Initialize_Scalars. If a package is compiled without an IS
3129          --     pragma, and the client is compiled with an IS pragma, then
3130          --     the client will think an initialization procedure is present
3131          --     and call it, when in fact no such procedure is required, but
3132          --     since the call is generated, there had better be a routine
3133          --     at the other end of the call, even if it does nothing!)
3134
3135          --  Note: the reason we exclude the CPP_Class case is because in this
3136          --  case the initialization is performed in the C++ side.
3137
3138          if Is_CPP_Class (Rec_Id) then
3139             return False;
3140
3141          elsif Is_Interface (Rec_Id) then
3142             return False;
3143
3144          elsif (Has_Discriminants (Rec_Id)
3145                   and then not Is_Unchecked_Union (Rec_Id))
3146            or else Is_Tagged_Type (Rec_Id)
3147            or else Is_Concurrent_Record_Type (Rec_Id)
3148            or else Has_Task (Rec_Id)
3149          then
3150             return True;
3151          end if;
3152
3153          Id := First_Component (Rec_Id);
3154          while Present (Id) loop
3155             Comp_Decl := Parent (Id);
3156             Typ := Etype (Id);
3157
3158             if Present (Expression (Comp_Decl))
3159               or else Has_Non_Null_Base_Init_Proc (Typ)
3160               or else Component_Needs_Simple_Initialization (Typ)
3161             then
3162                return True;
3163             end if;
3164
3165             Next_Component (Id);
3166          end loop;
3167
3168          --  As explained above, a record initialization procedure is needed
3169          --  for public types in case Initialize_Scalars applies to a client.
3170          --  However, such a procedure is not needed in the case where either
3171          --  of restrictions No_Initialize_Scalars or No_Default_Initialization
3172          --  applies. No_Initialize_Scalars excludes the possibility of using
3173          --  Initialize_Scalars in any partition, and No_Default_Initialization
3174          --  implies that no initialization should ever be done for objects of
3175          --  the type, so is incompatible with Initialize_Scalars.
3176
3177          if not Restriction_Active (No_Initialize_Scalars)
3178            and then not Restriction_Active (No_Default_Initialization)
3179            and then Is_Public (Rec_Id)
3180          then
3181             return True;
3182          end if;
3183
3184          return False;
3185       end Requires_Init_Proc;
3186
3187    --  Start of processing for Build_Record_Init_Proc
3188
3189    begin
3190       --  Check for value type, which means no initialization required
3191
3192       Rec_Type := Defining_Identifier (N);
3193
3194       if Is_Value_Type (Rec_Type) then
3195          return;
3196       end if;
3197
3198       --  This may be full declaration of a private type, in which case
3199       --  the visible entity is a record, and the private entity has been
3200       --  exchanged with it in the private part of the current package.
3201       --  The initialization procedure is built for the record type, which
3202       --  is retrievable from the private entity.
3203
3204       if Is_Incomplete_Or_Private_Type (Rec_Type) then
3205          Rec_Type := Underlying_Type (Rec_Type);
3206       end if;
3207
3208       --  If there are discriminants, build the discriminant map to replace
3209       --  discriminants by their discriminals in complex bound expressions.
3210       --  These only arise for the corresponding records of synchronized types.
3211
3212       if Is_Concurrent_Record_Type (Rec_Type)
3213         and then Has_Discriminants (Rec_Type)
3214       then
3215          declare
3216             Disc : Entity_Id;
3217          begin
3218             Disc := First_Discriminant (Rec_Type);
3219             while Present (Disc) loop
3220                Append_Elmt (Disc, Discr_Map);
3221                Append_Elmt (Discriminal (Disc), Discr_Map);
3222                Next_Discriminant (Disc);
3223             end loop;
3224          end;
3225       end if;
3226
3227       --  Derived types that have no type extension can use the initialization
3228       --  procedure of their parent and do not need a procedure of their own.
3229       --  This is only correct if there are no representation clauses for the
3230       --  type or its parent, and if the parent has in fact been frozen so
3231       --  that its initialization procedure exists.
3232
3233       if Is_Derived_Type (Rec_Type)
3234         and then not Is_Tagged_Type (Rec_Type)
3235         and then not Is_Unchecked_Union (Rec_Type)
3236         and then not Has_New_Non_Standard_Rep (Rec_Type)
3237         and then not Parent_Subtype_Renaming_Discrims
3238         and then Has_Non_Null_Base_Init_Proc (Etype (Rec_Type))
3239       then
3240          Copy_TSS (Base_Init_Proc (Etype (Rec_Type)), Rec_Type);
3241
3242       --  Otherwise if we need an initialization procedure, then build one,
3243       --  mark it as public and inlinable and as having a completion.
3244
3245       elsif Requires_Init_Proc (Rec_Type)
3246         or else Is_Unchecked_Union (Rec_Type)
3247       then
3248          Proc_Id :=
3249            Make_Defining_Identifier (Loc,
3250              Chars => Make_Init_Proc_Name (Rec_Type));
3251
3252          --  If No_Default_Initialization restriction is active, then we don't
3253          --  want to build an init_proc, but we need to mark that an init_proc
3254          --  would be needed if this restriction was not active (so that we can
3255          --  detect attempts to call it), so set a dummy init_proc in place.
3256
3257          if Restriction_Active (No_Default_Initialization) then
3258             Set_Init_Proc (Rec_Type, Proc_Id);
3259             return;
3260          end if;
3261
3262          Build_Offset_To_Top_Functions;
3263          Build_Init_Procedure;
3264          Set_Is_Public (Proc_Id, Is_Public (Pe));
3265
3266          --  The initialization of protected records is not worth inlining.
3267          --  In addition, when compiled for another unit for inlining purposes,
3268          --  it may make reference to entities that have not been elaborated
3269          --  yet. The initialization of controlled records contains a nested
3270          --  clean-up procedure that makes it impractical to inline as well,
3271          --  and leads to undefined symbols if inlined in a different unit.
3272          --  Similar considerations apply to task types.
3273
3274          if not Is_Concurrent_Type (Rec_Type)
3275            and then not Has_Task (Rec_Type)
3276            and then not Needs_Finalization (Rec_Type)
3277          then
3278             Set_Is_Inlined  (Proc_Id);
3279          end if;
3280
3281          Set_Is_Internal    (Proc_Id);
3282          Set_Has_Completion (Proc_Id);
3283
3284          if not Debug_Generated_Code then
3285             Set_Debug_Info_Off (Proc_Id);
3286          end if;
3287
3288          declare
3289             Agg : constant Node_Id :=
3290                     Build_Equivalent_Record_Aggregate (Rec_Type);
3291
3292             procedure Collect_Itypes (Comp : Node_Id);
3293             --  Generate references to itypes in the aggregate, because
3294             --  the first use of the aggregate may be in a nested scope.
3295
3296             --------------------
3297             -- Collect_Itypes --
3298             --------------------
3299
3300             procedure Collect_Itypes (Comp : Node_Id) is
3301                Ref      : Node_Id;
3302                Sub_Aggr : Node_Id;
3303                Typ      : constant Entity_Id := Etype (Comp);
3304
3305             begin
3306                if Is_Array_Type (Typ)
3307                  and then Is_Itype (Typ)
3308                then
3309                   Ref := Make_Itype_Reference (Loc);
3310                   Set_Itype (Ref, Typ);
3311                   Append_Freeze_Action (Rec_Type, Ref);
3312
3313                   Ref := Make_Itype_Reference (Loc);
3314                   Set_Itype (Ref, Etype (First_Index (Typ)));
3315                   Append_Freeze_Action (Rec_Type, Ref);
3316
3317                   Sub_Aggr := First (Expressions (Comp));
3318
3319                   --  Recurse on nested arrays
3320
3321                   while Present (Sub_Aggr) loop
3322                      Collect_Itypes (Sub_Aggr);
3323                      Next (Sub_Aggr);
3324                   end loop;
3325                end if;
3326             end Collect_Itypes;
3327
3328          begin
3329             --  If there is a static initialization aggregate for the type,
3330             --  generate itype references for the types of its (sub)components,
3331             --  to prevent out-of-scope errors in the resulting tree.
3332             --  The aggregate may have been rewritten as a Raise node, in which
3333             --  case there are no relevant itypes.
3334
3335             if Present (Agg)
3336               and then Nkind (Agg) = N_Aggregate
3337             then
3338                Set_Static_Initialization (Proc_Id, Agg);
3339
3340                declare
3341                   Comp  : Node_Id;
3342                begin
3343                   Comp := First (Component_Associations (Agg));
3344                   while Present (Comp) loop
3345                      Collect_Itypes (Expression (Comp));
3346                      Next (Comp);
3347                   end loop;
3348                end;
3349             end if;
3350          end;
3351       end if;
3352    end Build_Record_Init_Proc;
3353
3354    ----------------------------
3355    -- Build_Slice_Assignment --
3356    ----------------------------
3357
3358    --  Generates the following subprogram:
3359
3360    --    procedure Assign
3361    --     (Source,  Target    : Array_Type,
3362    --      Left_Lo, Left_Hi   : Index;
3363    --      Right_Lo, Right_Hi : Index;
3364    --      Rev                : Boolean)
3365    --    is
3366    --       Li1 : Index;
3367    --       Ri1 : Index;
3368
3369    --    begin
3370
3371    --       if Left_Hi < Left_Lo then
3372    --          return;
3373    --       end if;
3374
3375    --       if Rev  then
3376    --          Li1 := Left_Hi;
3377    --          Ri1 := Right_Hi;
3378    --       else
3379    --          Li1 := Left_Lo;
3380    --          Ri1 := Right_Lo;
3381    --       end if;
3382
3383    --       loop
3384    --          Target (Li1) := Source (Ri1);
3385
3386    --          if Rev then
3387    --             exit when Li1 = Left_Lo;
3388    --             Li1 := Index'pred (Li1);
3389    --             Ri1 := Index'pred (Ri1);
3390    --          else
3391    --             exit when Li1 = Left_Hi;
3392    --             Li1 := Index'succ (Li1);
3393    --             Ri1 := Index'succ (Ri1);
3394    --          end if;
3395    --       end loop;
3396    --    end Assign;
3397
3398    procedure Build_Slice_Assignment (Typ : Entity_Id) is
3399       Loc   : constant Source_Ptr := Sloc (Typ);
3400       Index : constant Entity_Id  := Base_Type (Etype (First_Index (Typ)));
3401
3402       Larray    : constant Entity_Id := Make_Temporary (Loc, 'A');
3403       Rarray    : constant Entity_Id := Make_Temporary (Loc, 'R');
3404       Left_Lo   : constant Entity_Id := Make_Temporary (Loc, 'L');
3405       Left_Hi   : constant Entity_Id := Make_Temporary (Loc, 'L');
3406       Right_Lo  : constant Entity_Id := Make_Temporary (Loc, 'R');
3407       Right_Hi  : constant Entity_Id := Make_Temporary (Loc, 'R');
3408       Rev       : constant Entity_Id := Make_Temporary (Loc, 'D');
3409       --  Formal parameters of procedure
3410
3411       Proc_Name : constant Entity_Id :=
3412                     Make_Defining_Identifier (Loc,
3413                       Chars => Make_TSS_Name (Typ, TSS_Slice_Assign));
3414
3415       Lnn : constant Entity_Id := Make_Temporary (Loc, 'L');
3416       Rnn : constant Entity_Id := Make_Temporary (Loc, 'R');
3417       --  Subscripts for left and right sides
3418
3419       Decls : List_Id;
3420       Loops : Node_Id;
3421       Stats : List_Id;
3422
3423    begin
3424       --  Build declarations for indices
3425
3426       Decls := New_List;
3427
3428       Append_To (Decls,
3429          Make_Object_Declaration (Loc,
3430            Defining_Identifier => Lnn,
3431            Object_Definition  =>
3432              New_Occurrence_Of (Index, Loc)));
3433
3434       Append_To (Decls,
3435         Make_Object_Declaration (Loc,
3436           Defining_Identifier => Rnn,
3437           Object_Definition  =>
3438             New_Occurrence_Of (Index, Loc)));
3439
3440       Stats := New_List;
3441
3442       --  Build test for empty slice case
3443
3444       Append_To (Stats,
3445         Make_If_Statement (Loc,
3446           Condition =>
3447              Make_Op_Lt (Loc,
3448                Left_Opnd  => New_Occurrence_Of (Left_Hi, Loc),
3449                Right_Opnd => New_Occurrence_Of (Left_Lo, Loc)),
3450           Then_Statements => New_List (Make_Simple_Return_Statement (Loc))));
3451
3452       --  Build initializations for indices
3453
3454       declare
3455          F_Init : constant List_Id := New_List;
3456          B_Init : constant List_Id := New_List;
3457
3458       begin
3459          Append_To (F_Init,
3460            Make_Assignment_Statement (Loc,
3461              Name => New_Occurrence_Of (Lnn, Loc),
3462              Expression => New_Occurrence_Of (Left_Lo, Loc)));
3463
3464          Append_To (F_Init,
3465            Make_Assignment_Statement (Loc,
3466              Name => New_Occurrence_Of (Rnn, Loc),
3467              Expression => New_Occurrence_Of (Right_Lo, Loc)));
3468
3469          Append_To (B_Init,
3470            Make_Assignment_Statement (Loc,
3471              Name => New_Occurrence_Of (Lnn, Loc),
3472              Expression => New_Occurrence_Of (Left_Hi, Loc)));
3473
3474          Append_To (B_Init,
3475            Make_Assignment_Statement (Loc,
3476              Name => New_Occurrence_Of (Rnn, Loc),
3477              Expression => New_Occurrence_Of (Right_Hi, Loc)));
3478
3479          Append_To (Stats,
3480            Make_If_Statement (Loc,
3481              Condition => New_Occurrence_Of (Rev, Loc),
3482              Then_Statements => B_Init,
3483              Else_Statements => F_Init));
3484       end;
3485
3486       --  Now construct the assignment statement
3487
3488       Loops :=
3489         Make_Loop_Statement (Loc,
3490           Statements => New_List (
3491             Make_Assignment_Statement (Loc,
3492               Name =>
3493                 Make_Indexed_Component (Loc,
3494                   Prefix => New_Occurrence_Of (Larray, Loc),
3495                   Expressions => New_List (New_Occurrence_Of (Lnn, Loc))),
3496               Expression =>
3497                 Make_Indexed_Component (Loc,
3498                   Prefix => New_Occurrence_Of (Rarray, Loc),
3499                   Expressions => New_List (New_Occurrence_Of (Rnn, Loc))))),
3500           End_Label  => Empty);
3501
3502       --  Build the exit condition and increment/decrement statements
3503
3504       declare
3505          F_Ass : constant List_Id := New_List;
3506          B_Ass : constant List_Id := New_List;
3507
3508       begin
3509          Append_To (F_Ass,
3510            Make_Exit_Statement (Loc,
3511              Condition =>
3512                Make_Op_Eq (Loc,
3513                  Left_Opnd  => New_Occurrence_Of (Lnn, Loc),
3514                  Right_Opnd => New_Occurrence_Of (Left_Hi, Loc))));
3515
3516          Append_To (F_Ass,
3517            Make_Assignment_Statement (Loc,
3518              Name => New_Occurrence_Of (Lnn, Loc),
3519              Expression =>
3520                Make_Attribute_Reference (Loc,
3521                  Prefix =>
3522                    New_Occurrence_Of (Index, Loc),
3523                  Attribute_Name => Name_Succ,
3524                  Expressions => New_List (
3525                    New_Occurrence_Of (Lnn, Loc)))));
3526
3527          Append_To (F_Ass,
3528            Make_Assignment_Statement (Loc,
3529              Name => New_Occurrence_Of (Rnn, Loc),
3530              Expression =>
3531                Make_Attribute_Reference (Loc,
3532                  Prefix =>
3533                    New_Occurrence_Of (Index, Loc),
3534                  Attribute_Name => Name_Succ,
3535                  Expressions => New_List (
3536                    New_Occurrence_Of (Rnn, Loc)))));
3537
3538          Append_To (B_Ass,
3539            Make_Exit_Statement (Loc,
3540              Condition =>
3541                Make_Op_Eq (Loc,
3542                  Left_Opnd  => New_Occurrence_Of (Lnn, Loc),
3543                  Right_Opnd => New_Occurrence_Of (Left_Lo, Loc))));
3544
3545          Append_To (B_Ass,
3546            Make_Assignment_Statement (Loc,
3547              Name => New_Occurrence_Of (Lnn, Loc),
3548              Expression =>
3549                Make_Attribute_Reference (Loc,
3550                  Prefix =>
3551                    New_Occurrence_Of (Index, Loc),
3552                  Attribute_Name => Name_Pred,
3553                    Expressions => New_List (
3554                      New_Occurrence_Of (Lnn, Loc)))));
3555
3556          Append_To (B_Ass,
3557            Make_Assignment_Statement (Loc,
3558              Name => New_Occurrence_Of (Rnn, Loc),
3559              Expression =>
3560                Make_Attribute_Reference (Loc,
3561                  Prefix =>
3562                    New_Occurrence_Of (Index, Loc),
3563                  Attribute_Name => Name_Pred,
3564                  Expressions => New_List (
3565                    New_Occurrence_Of (Rnn, Loc)))));
3566
3567          Append_To (Statements (Loops),
3568            Make_If_Statement (Loc,
3569              Condition => New_Occurrence_Of (Rev, Loc),
3570              Then_Statements => B_Ass,
3571              Else_Statements => F_Ass));
3572       end;
3573
3574       Append_To (Stats, Loops);
3575
3576       declare
3577          Spec    : Node_Id;
3578          Formals : List_Id := New_List;
3579
3580       begin
3581          Formals := New_List (
3582            Make_Parameter_Specification (Loc,
3583              Defining_Identifier => Larray,
3584              Out_Present => True,
3585              Parameter_Type =>
3586                New_Reference_To (Base_Type (Typ), Loc)),
3587
3588            Make_Parameter_Specification (Loc,
3589              Defining_Identifier => Rarray,
3590              Parameter_Type =>
3591                New_Reference_To (Base_Type (Typ), Loc)),
3592
3593            Make_Parameter_Specification (Loc,
3594              Defining_Identifier => Left_Lo,
3595              Parameter_Type =>
3596                New_Reference_To (Index, Loc)),
3597
3598            Make_Parameter_Specification (Loc,
3599              Defining_Identifier => Left_Hi,
3600              Parameter_Type =>
3601                New_Reference_To (Index, Loc)),
3602
3603            Make_Parameter_Specification (Loc,
3604              Defining_Identifier => Right_Lo,
3605              Parameter_Type =>
3606                New_Reference_To (Index, Loc)),
3607
3608            Make_Parameter_Specification (Loc,
3609              Defining_Identifier => Right_Hi,
3610              Parameter_Type =>
3611                New_Reference_To (Index, Loc)));
3612
3613          Append_To (Formals,
3614            Make_Parameter_Specification (Loc,
3615              Defining_Identifier => Rev,
3616              Parameter_Type =>
3617                New_Reference_To (Standard_Boolean, Loc)));
3618
3619          Spec :=
3620            Make_Procedure_Specification (Loc,
3621              Defining_Unit_Name       => Proc_Name,
3622              Parameter_Specifications => Formals);
3623
3624          Discard_Node (
3625            Make_Subprogram_Body (Loc,
3626              Specification              => Spec,
3627              Declarations               => Decls,
3628              Handled_Statement_Sequence =>
3629                Make_Handled_Sequence_Of_Statements (Loc,
3630                  Statements => Stats)));
3631       end;
3632
3633       Set_TSS (Typ, Proc_Name);
3634       Set_Is_Pure (Proc_Name);
3635    end Build_Slice_Assignment;
3636
3637    ------------------------------------
3638    -- Build_Variant_Record_Equality --
3639    ------------------------------------
3640
3641    --  Generates:
3642
3643    --    function _Equality (X, Y : T) return Boolean is
3644    --    begin
3645    --       --  Compare discriminants
3646
3647    --       if False or else X.D1 /= Y.D1 or else X.D2 /= Y.D2 then
3648    --          return False;
3649    --       end if;
3650
3651    --       --  Compare components
3652
3653    --       if False or else X.C1 /= Y.C1 or else X.C2 /= Y.C2 then
3654    --          return False;
3655    --       end if;
3656
3657    --       --  Compare variant part
3658
3659    --       case X.D1 is
3660    --          when V1 =>
3661    --             if False or else X.C2 /= Y.C2 or else X.C3 /= Y.C3 then
3662    --                return False;
3663    --             end if;
3664    --          ...
3665    --          when Vn =>
3666    --             if False or else X.Cn /= Y.Cn then
3667    --                return False;
3668    --             end if;
3669    --       end case;
3670
3671    --       return True;
3672    --    end _Equality;
3673
3674    procedure Build_Variant_Record_Equality (Typ : Entity_Id) is
3675       Loc : constant Source_Ptr := Sloc (Typ);
3676
3677       F : constant Entity_Id :=
3678             Make_Defining_Identifier (Loc,
3679               Chars => Make_TSS_Name (Typ, TSS_Composite_Equality));
3680
3681       X : constant Entity_Id :=
3682            Make_Defining_Identifier (Loc,
3683              Chars => Name_X);
3684
3685       Y : constant Entity_Id :=
3686             Make_Defining_Identifier (Loc,
3687               Chars => Name_Y);
3688
3689       Def    : constant Node_Id := Parent (Typ);
3690       Comps  : constant Node_Id := Component_List (Type_Definition (Def));
3691       Stmts  : constant List_Id := New_List;
3692       Pspecs : constant List_Id := New_List;
3693
3694    begin
3695       --  Derived Unchecked_Union types no longer inherit the equality function
3696       --  of their parent.
3697
3698       if Is_Derived_Type (Typ)
3699         and then not Is_Unchecked_Union (Typ)
3700         and then not Has_New_Non_Standard_Rep (Typ)
3701       then
3702          declare
3703             Parent_Eq : constant Entity_Id :=
3704                           TSS (Root_Type (Typ), TSS_Composite_Equality);
3705
3706          begin
3707             if Present (Parent_Eq) then
3708                Copy_TSS (Parent_Eq, Typ);
3709                return;
3710             end if;
3711          end;
3712       end if;
3713
3714       Discard_Node (
3715         Make_Subprogram_Body (Loc,
3716           Specification =>
3717             Make_Function_Specification (Loc,
3718               Defining_Unit_Name       => F,
3719               Parameter_Specifications => Pspecs,
3720               Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
3721           Declarations               => New_List,
3722           Handled_Statement_Sequence =>
3723             Make_Handled_Sequence_Of_Statements (Loc,
3724               Statements => Stmts)));
3725
3726       Append_To (Pspecs,
3727         Make_Parameter_Specification (Loc,
3728           Defining_Identifier => X,
3729           Parameter_Type      => New_Reference_To (Typ, Loc)));
3730
3731       Append_To (Pspecs,
3732         Make_Parameter_Specification (Loc,
3733           Defining_Identifier => Y,
3734           Parameter_Type      => New_Reference_To (Typ, Loc)));
3735
3736       --  Unchecked_Unions require additional machinery to support equality.
3737       --  Two extra parameters (A and B) are added to the equality function
3738       --  parameter list in order to capture the inferred values of the
3739       --  discriminants in later calls.
3740
3741       if Is_Unchecked_Union (Typ) then
3742          declare
3743             Discr_Type : constant Node_Id := Etype (First_Discriminant (Typ));
3744
3745             A : constant Node_Id :=
3746                   Make_Defining_Identifier (Loc,
3747                     Chars => Name_A);
3748
3749             B : constant Node_Id :=
3750                   Make_Defining_Identifier (Loc,
3751                     Chars => Name_B);
3752
3753          begin
3754             --  Add A and B to the parameter list
3755
3756             Append_To (Pspecs,
3757               Make_Parameter_Specification (Loc,
3758                 Defining_Identifier => A,
3759                 Parameter_Type => New_Reference_To (Discr_Type, Loc)));
3760
3761             Append_To (Pspecs,
3762               Make_Parameter_Specification (Loc,
3763                 Defining_Identifier => B,
3764                 Parameter_Type => New_Reference_To (Discr_Type, Loc)));
3765
3766             --  Generate the following header code to compare the inferred
3767             --  discriminants:
3768
3769             --  if a /= b then
3770             --     return False;
3771             --  end if;
3772
3773             Append_To (Stmts,
3774               Make_If_Statement (Loc,
3775                 Condition =>
3776                   Make_Op_Ne (Loc,
3777                     Left_Opnd => New_Reference_To (A, Loc),
3778                     Right_Opnd => New_Reference_To (B, Loc)),
3779                 Then_Statements => New_List (
3780                   Make_Simple_Return_Statement (Loc,
3781                     Expression => New_Occurrence_Of (Standard_False, Loc)))));
3782
3783             --  Generate component-by-component comparison. Note that we must
3784             --  propagate one of the inferred discriminant formals to act as
3785             --  the case statement switch.
3786
3787             Append_List_To (Stmts,
3788               Make_Eq_Case (Typ, Comps, A));
3789
3790          end;
3791
3792       --  Normal case (not unchecked union)
3793
3794       else
3795          Append_To (Stmts,
3796            Make_Eq_If (Typ,
3797              Discriminant_Specifications (Def)));
3798
3799          Append_List_To (Stmts,
3800            Make_Eq_Case (Typ, Comps));
3801       end if;
3802
3803       Append_To (Stmts,
3804         Make_Simple_Return_Statement (Loc,
3805           Expression => New_Reference_To (Standard_True, Loc)));
3806
3807       Set_TSS (Typ, F);
3808       Set_Is_Pure (F);
3809
3810       if not Debug_Generated_Code then
3811          Set_Debug_Info_Off (F);
3812       end if;
3813    end Build_Variant_Record_Equality;
3814
3815    -----------------------------
3816    -- Check_Stream_Attributes --
3817    -----------------------------
3818
3819    procedure Check_Stream_Attributes (Typ : Entity_Id) is
3820       Comp      : Entity_Id;
3821       Par_Read  : constant Boolean :=
3822                     Stream_Attribute_Available (Typ, TSS_Stream_Read)
3823                       and then not Has_Specified_Stream_Read (Typ);
3824       Par_Write : constant Boolean :=
3825                     Stream_Attribute_Available (Typ, TSS_Stream_Write)
3826                       and then not Has_Specified_Stream_Write (Typ);
3827
3828       procedure Check_Attr (Nam : Name_Id; TSS_Nam : TSS_Name_Type);
3829       --  Check that Comp has a user-specified Nam stream attribute
3830
3831       ----------------
3832       -- Check_Attr --
3833       ----------------
3834
3835       procedure Check_Attr (Nam : Name_Id; TSS_Nam : TSS_Name_Type) is
3836       begin
3837          if not Stream_Attribute_Available (Etype (Comp), TSS_Nam) then
3838             Error_Msg_Name_1 := Nam;
3839             Error_Msg_N
3840               ("|component& in limited extension must have% attribute", Comp);
3841          end if;
3842       end Check_Attr;
3843
3844    --  Start of processing for Check_Stream_Attributes
3845
3846    begin
3847       if Par_Read or else Par_Write then
3848          Comp := First_Component (Typ);
3849          while Present (Comp) loop
3850             if Comes_From_Source (Comp)
3851               and then Original_Record_Component (Comp) = Comp
3852               and then Is_Limited_Type (Etype (Comp))
3853             then
3854                if Par_Read then
3855                   Check_Attr (Name_Read, TSS_Stream_Read);
3856                end if;
3857
3858                if Par_Write then
3859                   Check_Attr (Name_Write, TSS_Stream_Write);
3860                end if;
3861             end if;
3862
3863             Next_Component (Comp);
3864          end loop;
3865       end if;
3866    end Check_Stream_Attributes;
3867
3868    -----------------------------
3869    -- Expand_Record_Extension --
3870    -----------------------------
3871
3872    --  Add a field _parent at the beginning of the record extension. This is
3873    --  used to implement inheritance. Here are some examples of expansion:
3874
3875    --  1. no discriminants
3876    --      type T2 is new T1 with null record;
3877    --   gives
3878    --      type T2 is new T1 with record
3879    --        _Parent : T1;
3880    --      end record;
3881
3882    --  2. renamed discriminants
3883    --    type T2 (B, C : Int) is new T1 (A => B) with record
3884    --       _Parent : T1 (A => B);
3885    --       D : Int;
3886    --    end;
3887
3888    --  3. inherited discriminants
3889    --    type T2 is new T1 with record -- discriminant A inherited
3890    --       _Parent : T1 (A);
3891    --       D : Int;
3892    --    end;
3893
3894    procedure Expand_Record_Extension (T : Entity_Id; Def : Node_Id) is
3895       Indic        : constant Node_Id    := Subtype_Indication (Def);
3896       Loc          : constant Source_Ptr := Sloc (Def);
3897       Rec_Ext_Part : Node_Id             := Record_Extension_Part (Def);
3898       Par_Subtype  : Entity_Id;
3899       Comp_List    : Node_Id;
3900       Comp_Decl    : Node_Id;
3901       Parent_N     : Node_Id;
3902       D            : Entity_Id;
3903       List_Constr  : constant List_Id    := New_List;
3904
3905    begin
3906       --  Expand_Record_Extension is called directly from the semantics, so
3907       --  we must check to see whether expansion is active before proceeding
3908
3909       if not Expander_Active then
3910          return;
3911       end if;
3912
3913       --  This may be a derivation of an untagged private type whose full
3914       --  view is tagged, in which case the Derived_Type_Definition has no
3915       --  extension part. Build an empty one now.
3916
3917       if No (Rec_Ext_Part) then
3918          Rec_Ext_Part :=
3919            Make_Record_Definition (Loc,
3920              End_Label      => Empty,
3921              Component_List => Empty,
3922              Null_Present   => True);
3923
3924          Set_Record_Extension_Part (Def, Rec_Ext_Part);
3925          Mark_Rewrite_Insertion (Rec_Ext_Part);
3926       end if;
3927
3928       Comp_List := Component_List (Rec_Ext_Part);
3929
3930       Parent_N := Make_Defining_Identifier (Loc, Name_uParent);
3931
3932       --  If the derived type inherits its discriminants the type of the
3933       --  _parent field must be constrained by the inherited discriminants
3934
3935       if Has_Discriminants (T)
3936         and then Nkind (Indic) /= N_Subtype_Indication
3937         and then not Is_Constrained (Entity (Indic))
3938       then
3939          D := First_Discriminant (T);
3940          while Present (D) loop
3941             Append_To (List_Constr, New_Occurrence_Of (D, Loc));
3942             Next_Discriminant (D);
3943          end loop;
3944
3945          Par_Subtype :=
3946            Process_Subtype (
3947              Make_Subtype_Indication (Loc,
3948                Subtype_Mark => New_Reference_To (Entity (Indic), Loc),
3949                Constraint   =>
3950                  Make_Index_Or_Discriminant_Constraint (Loc,
3951                    Constraints => List_Constr)),
3952              Def);
3953
3954       --  Otherwise the original subtype_indication is just what is needed
3955
3956       else
3957          Par_Subtype := Process_Subtype (New_Copy_Tree (Indic), Def);
3958       end if;
3959
3960       Set_Parent_Subtype (T, Par_Subtype);
3961
3962       Comp_Decl :=
3963         Make_Component_Declaration (Loc,
3964           Defining_Identifier => Parent_N,
3965           Component_Definition =>
3966             Make_Component_Definition (Loc,
3967               Aliased_Present => False,
3968               Subtype_Indication => New_Reference_To (Par_Subtype, Loc)));
3969
3970       if Null_Present (Rec_Ext_Part) then
3971          Set_Component_List (Rec_Ext_Part,
3972            Make_Component_List (Loc,
3973              Component_Items => New_List (Comp_Decl),
3974              Variant_Part => Empty,
3975              Null_Present => False));
3976          Set_Null_Present (Rec_Ext_Part, False);
3977
3978       elsif Null_Present (Comp_List)
3979         or else Is_Empty_List (Component_Items (Comp_List))
3980       then
3981          Set_Component_Items (Comp_List, New_List (Comp_Decl));
3982          Set_Null_Present (Comp_List, False);
3983
3984       else
3985          Insert_Before (First (Component_Items (Comp_List)), Comp_Decl);
3986       end if;
3987
3988       Analyze (Comp_Decl);
3989    end Expand_Record_Extension;
3990
3991    ------------------------------------
3992    -- Expand_N_Full_Type_Declaration --
3993    ------------------------------------
3994
3995    procedure Expand_N_Full_Type_Declaration (N : Node_Id) is
3996       Def_Id : constant Entity_Id := Defining_Identifier (N);
3997       B_Id   : constant Entity_Id := Base_Type (Def_Id);
3998       Par_Id : Entity_Id;
3999       FN     : Node_Id;
4000
4001       procedure Build_Master (Def_Id : Entity_Id);
4002       --  Create the master associated with Def_Id
4003
4004       ------------------
4005       -- Build_Master --
4006       ------------------
4007
4008       procedure Build_Master (Def_Id : Entity_Id) is
4009       begin
4010          --  Anonymous access types are created for the components of the
4011          --  record parameter for an entry declaration. No master is created
4012          --  for such a type.
4013
4014          if Has_Task (Designated_Type (Def_Id))
4015            and then Comes_From_Source (N)
4016          then
4017             Build_Master_Entity (Def_Id);
4018             Build_Master_Renaming (Parent (Def_Id), Def_Id);
4019
4020          --  Create a class-wide master because a Master_Id must be generated
4021          --  for access-to-limited-class-wide types whose root may be extended
4022          --  with task components.
4023
4024          --  Note: This code covers access-to-limited-interfaces because they
4025          --        can be used to reference tasks implementing them.
4026
4027          elsif Is_Class_Wide_Type (Designated_Type (Def_Id))
4028            and then Is_Limited_Type (Designated_Type (Def_Id))
4029            and then Tasking_Allowed
4030
4031             --  Do not create a class-wide master for types whose convention is
4032             --  Java since these types cannot embed Ada tasks anyway. Note that
4033             --  the following test cannot catch the following case:
4034
4035             --      package java.lang.Object is
4036             --         type Typ is tagged limited private;
4037             --         type Ref is access all Typ'Class;
4038             --      private
4039             --         type Typ is tagged limited ...;
4040             --         pragma Convention (Typ, Java)
4041             --      end;
4042
4043             --  Because the convention appears after we have done the
4044             --  processing for type Ref.
4045
4046            and then Convention (Designated_Type (Def_Id)) /= Convention_Java
4047            and then Convention (Designated_Type (Def_Id)) /= Convention_CIL
4048          then
4049             Build_Class_Wide_Master (Def_Id);
4050          end if;
4051       end Build_Master;
4052
4053    --  Start of processing for Expand_N_Full_Type_Declaration
4054
4055    begin
4056       if Is_Access_Type (Def_Id) then
4057          Build_Master (Def_Id);
4058
4059          if Ekind (Def_Id) = E_Access_Protected_Subprogram_Type then
4060             Expand_Access_Protected_Subprogram_Type (N);
4061          end if;
4062
4063       elsif Ada_Version >= Ada_05
4064         and then Is_Array_Type (Def_Id)
4065         and then Is_Access_Type (Component_Type (Def_Id))
4066         and then Ekind (Component_Type (Def_Id)) = E_Anonymous_Access_Type
4067       then
4068          Build_Master (Component_Type (Def_Id));
4069
4070       elsif Has_Task (Def_Id) then
4071          Expand_Previous_Access_Type (Def_Id);
4072
4073       elsif Ada_Version >= Ada_05
4074         and then
4075          (Is_Record_Type (Def_Id)
4076            or else (Is_Array_Type (Def_Id)
4077                       and then Is_Record_Type (Component_Type (Def_Id))))
4078       then
4079          declare
4080             Comp : Entity_Id;
4081             Typ  : Entity_Id;
4082             M_Id : Entity_Id;
4083
4084          begin
4085             --  Look for the first anonymous access type component
4086
4087             if Is_Array_Type (Def_Id) then
4088                Comp := First_Entity (Component_Type (Def_Id));
4089             else
4090                Comp := First_Entity (Def_Id);
4091             end if;
4092
4093             while Present (Comp) loop
4094                Typ := Etype (Comp);
4095
4096                exit when Is_Access_Type (Typ)
4097                  and then Ekind (Typ) = E_Anonymous_Access_Type;
4098
4099                Next_Entity (Comp);
4100             end loop;
4101
4102             --  If found we add a renaming declaration of master_id and we
4103             --  associate it to each anonymous access type component. Do
4104             --  nothing if the access type already has a master. This will be
4105             --  the case if the array type is the packed array created for a
4106             --  user-defined array type T, where the master_id is created when
4107             --  expanding the declaration for T.
4108
4109             if Present (Comp)
4110               and then Ekind (Typ) = E_Anonymous_Access_Type
4111               and then not Restriction_Active (No_Task_Hierarchy)
4112               and then No (Master_Id (Typ))
4113
4114                --  Do not consider run-times with no tasking support
4115
4116               and then RTE_Available (RE_Current_Master)
4117               and then Has_Task (Non_Limited_Designated_Type (Typ))
4118             then
4119                Build_Master_Entity (Def_Id);
4120                M_Id := Build_Master_Renaming (N, Def_Id);
4121
4122                if Is_Array_Type (Def_Id) then
4123                   Comp := First_Entity (Component_Type (Def_Id));
4124                else
4125                   Comp := First_Entity (Def_Id);
4126                end if;
4127
4128                while Present (Comp) loop
4129                   Typ := Etype (Comp);
4130
4131                   if Is_Access_Type (Typ)
4132                     and then Ekind (Typ) = E_Anonymous_Access_Type
4133                   then
4134                      Set_Master_Id (Typ, M_Id);
4135                   end if;
4136
4137                   Next_Entity (Comp);
4138                end loop;
4139             end if;
4140          end;
4141       end if;
4142
4143       Par_Id := Etype (B_Id);
4144
4145       --  The parent type is private then we need to inherit any TSS operations
4146       --  from the full view.
4147
4148       if Ekind (Par_Id) in Private_Kind
4149         and then Present (Full_View (Par_Id))
4150       then
4151          Par_Id := Base_Type (Full_View (Par_Id));
4152       end if;
4153
4154       if Nkind (Type_Definition (Original_Node (N))) =
4155                                                 N_Derived_Type_Definition
4156         and then not Is_Tagged_Type (Def_Id)
4157         and then Present (Freeze_Node (Par_Id))
4158         and then Present (TSS_Elist (Freeze_Node (Par_Id)))
4159       then
4160          Ensure_Freeze_Node (B_Id);
4161          FN := Freeze_Node (B_Id);
4162
4163          if No (TSS_Elist (FN)) then
4164             Set_TSS_Elist (FN, New_Elmt_List);
4165          end if;
4166
4167          declare
4168             T_E  : constant Elist_Id := TSS_Elist (FN);
4169             Elmt : Elmt_Id;
4170
4171          begin
4172             Elmt := First_Elmt (TSS_Elist (Freeze_Node (Par_Id)));
4173             while Present (Elmt) loop
4174                if Chars (Node (Elmt)) /= Name_uInit then
4175                   Append_Elmt (Node (Elmt), T_E);
4176                end if;
4177
4178                Next_Elmt (Elmt);
4179             end loop;
4180
4181             --  If the derived type itself is private with a full view, then
4182             --  associate the full view with the inherited TSS_Elist as well.
4183
4184             if Ekind (B_Id) in Private_Kind
4185               and then Present (Full_View (B_Id))
4186             then
4187                Ensure_Freeze_Node (Base_Type (Full_View (B_Id)));
4188                Set_TSS_Elist
4189                  (Freeze_Node (Base_Type (Full_View (B_Id))), TSS_Elist (FN));
4190             end if;
4191          end;
4192       end if;
4193    end Expand_N_Full_Type_Declaration;
4194
4195    ---------------------------------
4196    -- Expand_N_Object_Declaration --
4197    ---------------------------------
4198
4199    --  First we do special processing for objects of a tagged type where this
4200    --  is the point at which the type is frozen. The creation of the dispatch
4201    --  table and the initialization procedure have to be deferred to this
4202    --  point, since we reference previously declared primitive subprograms.
4203
4204    --  For all types, we call an initialization procedure if there is one
4205
4206    procedure Expand_N_Object_Declaration (N : Node_Id) is
4207       Def_Id   : constant Entity_Id  := Defining_Identifier (N);
4208       Expr     : constant Node_Id    := Expression (N);
4209       Loc      : constant Source_Ptr := Sloc (N);
4210       Typ      : constant Entity_Id  := Etype (Def_Id);
4211       Base_Typ : constant Entity_Id  := Base_Type (Typ);
4212       Expr_Q   : Node_Id;
4213       Id_Ref   : Node_Id;
4214       New_Ref  : Node_Id;
4215
4216       Init_After : Node_Id := N;
4217       --  Node after which the init proc call is to be inserted. This is
4218       --  normally N, except for the case of a shared passive variable, in
4219       --  which case the init proc call must be inserted only after the bodies
4220       --  of the shared variable procedures have been seen.
4221
4222       function Rewrite_As_Renaming return Boolean;
4223       --  Indicate whether to rewrite a declaration with initialization into an
4224       --  object renaming declaration (see below).
4225
4226       -------------------------
4227       -- Rewrite_As_Renaming --
4228       -------------------------
4229
4230       function Rewrite_As_Renaming return Boolean is
4231       begin
4232          return not Aliased_Present (N)
4233            and then Is_Entity_Name (Expr_Q)
4234            and then Ekind (Entity (Expr_Q)) = E_Variable
4235            and then OK_To_Rename (Entity (Expr_Q))
4236            and then Is_Entity_Name (Object_Definition (N));
4237       end Rewrite_As_Renaming;
4238
4239    --  Start of processing for Expand_N_Object_Declaration
4240
4241    begin
4242       --  Don't do anything for deferred constants. All proper actions will be
4243       --  expanded during the full declaration.
4244
4245       if No (Expr) and Constant_Present (N) then
4246          return;
4247       end if;
4248
4249       --  Force construction of dispatch tables of library level tagged types
4250
4251       if Tagged_Type_Expansion
4252         and then Static_Dispatch_Tables
4253         and then Is_Library_Level_Entity (Def_Id)
4254         and then Is_Library_Level_Tagged_Type (Base_Typ)
4255         and then (Ekind (Base_Typ) = E_Record_Type
4256                     or else Ekind (Base_Typ) = E_Protected_Type
4257                     or else Ekind (Base_Typ) = E_Task_Type)
4258         and then not Has_Dispatch_Table (Base_Typ)
4259       then
4260          declare
4261             New_Nodes : List_Id := No_List;
4262
4263          begin
4264             if Is_Concurrent_Type (Base_Typ) then
4265                New_Nodes := Make_DT (Corresponding_Record_Type (Base_Typ), N);
4266             else
4267                New_Nodes := Make_DT (Base_Typ, N);
4268             end if;
4269
4270             if not Is_Empty_List (New_Nodes) then
4271                Insert_List_Before (N, New_Nodes);
4272             end if;
4273          end;
4274       end if;
4275
4276       --  Make shared memory routines for shared passive variable
4277
4278       if Is_Shared_Passive (Def_Id) then
4279          Init_After := Make_Shared_Var_Procs (N);
4280       end if;
4281
4282       --  If tasks being declared, make sure we have an activation chain
4283       --  defined for the tasks (has no effect if we already have one), and
4284       --  also that a Master variable is established and that the appropriate
4285       --  enclosing construct is established as a task master.
4286
4287       if Has_Task (Typ) then
4288          Build_Activation_Chain_Entity (N);
4289          Build_Master_Entity (Def_Id);
4290       end if;
4291
4292       --  Build a list controller for declarations where the type is anonymous
4293       --  access and the designated type is controlled. Only declarations from
4294       --  source files receive such controllers in order to provide the same
4295       --  lifespan for any potential coextensions that may be associated with
4296       --  the object. Finalization lists of internal controlled anonymous
4297       --  access objects are already handled in Expand_N_Allocator.
4298
4299       if Comes_From_Source (N)
4300         and then Ekind (Typ) = E_Anonymous_Access_Type
4301         and then Is_Controlled (Directly_Designated_Type (Typ))
4302         and then No (Associated_Final_Chain (Typ))
4303       then
4304          Build_Final_List (N, Typ);
4305       end if;
4306
4307       --  Default initialization required, and no expression present
4308
4309       if No (Expr) then
4310
4311          --  Expand Initialize call for controlled objects. One may wonder why
4312          --  the Initialize Call is not done in the regular Init procedure
4313          --  attached to the record type. That's because the init procedure is
4314          --  recursively called on each component, including _Parent, thus the
4315          --  Init call for a controlled object would generate not only one
4316          --  Initialize call as it is required but one for each ancestor of
4317          --  its type. This processing is suppressed if No_Initialization set.
4318
4319          if not Needs_Finalization (Typ)
4320            or else No_Initialization (N)
4321          then
4322             null;
4323
4324          elsif not Abort_Allowed
4325            or else not Comes_From_Source (N)
4326          then
4327             Insert_Actions_After (Init_After,
4328               Make_Init_Call (
4329                 Ref         => New_Occurrence_Of (Def_Id, Loc),
4330                 Typ         => Base_Type (Typ),
4331                 Flist_Ref   => Find_Final_List (Def_Id),
4332                 With_Attach => Make_Integer_Literal (Loc, 1)));
4333
4334          --  Abort allowed
4335
4336          else
4337             --  We need to protect the initialize call
4338
4339             --  begin
4340             --     Defer_Abort.all;
4341             --     Initialize (...);
4342             --  at end
4343             --     Undefer_Abort.all;
4344             --  end;
4345
4346             --  ??? this won't protect the initialize call for controlled
4347             --  components which are part of the init proc, so this block
4348             --  should probably also contain the call to _init_proc but this
4349             --  requires some code reorganization...
4350
4351             declare
4352                L   : constant List_Id :=
4353                        Make_Init_Call
4354                          (Ref         => New_Occurrence_Of (Def_Id, Loc),
4355                           Typ         => Base_Type (Typ),
4356                           Flist_Ref   => Find_Final_List (Def_Id),
4357                           With_Attach => Make_Integer_Literal (Loc, 1));
4358
4359                Blk : constant Node_Id :=
4360                        Make_Block_Statement (Loc,
4361                          Handled_Statement_Sequence =>
4362                            Make_Handled_Sequence_Of_Statements (Loc, L));
4363
4364             begin
4365                Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
4366                Set_At_End_Proc (Handled_Statement_Sequence (Blk),
4367                  New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
4368                Insert_Actions_After (Init_After, New_List (Blk));
4369                Expand_At_End_Handler
4370                  (Handled_Statement_Sequence (Blk), Entity (Identifier (Blk)));
4371             end;
4372          end if;
4373
4374          --  Call type initialization procedure if there is one. We build the
4375          --  call and put it immediately after the object declaration, so that
4376          --  it will be expanded in the usual manner. Note that this will
4377          --  result in proper handling of defaulted discriminants.
4378
4379          --  Need call if there is a base init proc
4380
4381          if Has_Non_Null_Base_Init_Proc (Typ)
4382
4383             --  Suppress call if No_Initialization set on declaration
4384
4385             and then not No_Initialization (N)
4386
4387             --  Suppress call for special case of value type for VM
4388
4389             and then not Is_Value_Type (Typ)
4390
4391             --  Suppress call if Suppress_Init_Proc set on the type. This is
4392             --  needed for the derived type case, where Suppress_Initialization
4393             --  may be set for the derived type, even if there is an init proc
4394             --  defined for the root type.
4395
4396             and then not Suppress_Init_Proc (Typ)
4397          then
4398             --  Return without initializing when No_Default_Initialization
4399             --  applies. Note that the actual restriction check occurs later,
4400             --  when the object is frozen, because we don't know yet whether
4401             --  the object is imported, which is a case where the check does
4402             --  not apply.
4403
4404             if Restriction_Active (No_Default_Initialization) then
4405                return;
4406             end if;
4407
4408             --  The call to the initialization procedure does NOT freeze the
4409             --  object being initialized. This is because the call is not a
4410             --  source level call. This works fine, because the only possible
4411             --  statements depending on freeze status that can appear after the
4412             --  Init_Proc call are rep clauses which can safely appear after
4413             --  actual references to the object. Note that this call may
4414             --  subsequently be removed (if a pragma Import is encountered),
4415             --  or moved to the freeze actions for the object (e.g. if an
4416             --  address clause is applied to the object, causing it to get
4417             --  delayed freezing).
4418
4419             Id_Ref := New_Reference_To (Def_Id, Loc);
4420             Set_Must_Not_Freeze (Id_Ref);
4421             Set_Assignment_OK (Id_Ref);
4422
4423             declare
4424                Init_Expr : constant Node_Id :=
4425                              Static_Initialization (Base_Init_Proc (Typ));
4426             begin
4427                if Present (Init_Expr) then
4428                   Set_Expression
4429                     (N, New_Copy_Tree (Init_Expr, New_Scope => Current_Scope));
4430                   return;
4431                else
4432                   Initialization_Warning (Id_Ref);
4433
4434                   Insert_Actions_After (Init_After,
4435                     Build_Initialization_Call (Loc, Id_Ref, Typ));
4436                end if;
4437             end;
4438
4439          --  If simple initialization is required, then set an appropriate
4440          --  simple initialization expression in place. This special
4441          --  initialization is required even though No_Init_Flag is present,
4442          --  but is not needed if there was an explicit initialization.
4443
4444          --  An internally generated temporary needs no initialization because
4445          --  it will be assigned subsequently. In particular, there is no point
4446          --  in applying Initialize_Scalars to such a temporary.
4447
4448          elsif Needs_Simple_Initialization
4449                  (Typ,
4450                   Initialize_Scalars
4451                     and then not Has_Following_Address_Clause (N))
4452            and then not Is_Internal (Def_Id)
4453            and then not Has_Init_Expression (N)
4454          then
4455             Set_No_Initialization (N, False);
4456             Set_Expression (N, Get_Simple_Init_Val (Typ, N, Esize (Def_Id)));
4457             Analyze_And_Resolve (Expression (N), Typ);
4458          end if;
4459
4460          --  Generate attribute for Persistent_BSS if needed
4461
4462          if Persistent_BSS_Mode
4463            and then Comes_From_Source (N)
4464            and then Is_Potentially_Persistent_Type (Typ)
4465            and then not Has_Init_Expression (N)
4466            and then Is_Library_Level_Entity (Def_Id)
4467          then
4468             declare
4469                Prag : Node_Id;
4470             begin
4471                Prag :=
4472                  Make_Linker_Section_Pragma
4473                    (Def_Id, Sloc (N), ".persistent.bss");
4474                Insert_After (N, Prag);
4475                Analyze (Prag);
4476             end;
4477          end if;
4478
4479          --  If access type, then we know it is null if not initialized
4480
4481          if Is_Access_Type (Typ) then
4482             Set_Is_Known_Null (Def_Id);
4483          end if;
4484
4485       --  Explicit initialization present
4486
4487       else
4488          --  Obtain actual expression from qualified expression
4489
4490          if Nkind (Expr) = N_Qualified_Expression then
4491             Expr_Q := Expression (Expr);
4492          else
4493             Expr_Q := Expr;
4494          end if;
4495
4496          --  When we have the appropriate type of aggregate in the expression
4497          --  (it has been determined during analysis of the aggregate by
4498          --  setting the delay flag), let's perform in place assignment and
4499          --  thus avoid creating a temporary.
4500
4501          if Is_Delayed_Aggregate (Expr_Q) then
4502             Convert_Aggr_In_Object_Decl (N);
4503
4504          --  Ada 2005 (AI-318-02): If the initialization expression is a call
4505          --  to a build-in-place function, then access to the declared object
4506          --  must be passed to the function. Currently we limit such functions
4507          --  to those with constrained limited result subtypes, but eventually
4508          --  plan to expand the allowed forms of functions that are treated as
4509          --  build-in-place.
4510
4511          elsif Ada_Version >= Ada_05
4512            and then Is_Build_In_Place_Function_Call (Expr_Q)
4513          then
4514             Make_Build_In_Place_Call_In_Object_Declaration (N, Expr_Q);
4515
4516             --  The previous call expands the expression initializing the
4517             --  built-in-place object into further code that will be analyzed
4518             --  later. No further expansion needed here.
4519
4520             return;
4521
4522          --  Ada 2005 (AI-251): Rewrite the expression that initializes a
4523          --  class-wide object to ensure that we copy the full object,
4524          --  unless we are targetting a VM where interfaces are handled by
4525          --  VM itself. Note that if the root type of Typ is an ancestor
4526          --  of Expr's type, both types share the same dispatch table and
4527          --  there is no need to displace the pointer.
4528
4529          elsif Comes_From_Source (N)
4530            and then Is_Interface (Typ)
4531          then
4532             pragma Assert (Is_Class_Wide_Type (Typ));
4533
4534             --  If the object is a return object of an inherently limited type,
4535             --  which implies build-in-place treatment, bypass the special
4536             --  treatment of class-wide interface initialization below. In this
4537             --  case, the expansion of the return statement will take care of
4538             --  creating the object (via allocator) and initializing it.
4539
4540             if Is_Return_Object (Def_Id)
4541               and then Is_Inherently_Limited_Type (Typ)
4542             then
4543                null;
4544
4545             elsif Tagged_Type_Expansion then
4546                declare
4547                   Iface    : constant Entity_Id := Root_Type (Typ);
4548                   Expr_N   : Node_Id := Expr;
4549                   Expr_Typ : Entity_Id;
4550
4551                   Decl_1   : Node_Id;
4552                   Decl_2   : Node_Id;
4553                   New_Expr : Node_Id;
4554
4555                begin
4556                   --  If the original node of the expression was a conversion
4557                   --  to this specific class-wide interface type then we
4558                   --  restore the original node to generate code that
4559                   --  statically displaces the pointer to the interface
4560                   --  component.
4561
4562                   if not Comes_From_Source (Expr_N)
4563                     and then Nkind (Expr_N) = N_Unchecked_Type_Conversion
4564                     and then Nkind (Original_Node (Expr_N)) = N_Type_Conversion
4565                     and then Etype (Original_Node (Expr_N)) = Typ
4566                   then
4567                      Rewrite (Expr_N, Original_Node (Expression (N)));
4568                   end if;
4569
4570                   --  Avoid expansion of redundant interface conversion
4571
4572                   if Is_Interface (Etype (Expr_N))
4573                     and then Nkind (Expr_N) = N_Type_Conversion
4574                     and then Etype (Expr_N) = Typ
4575                   then
4576                      Expr_N := Expression (Expr_N);
4577                      Set_Expression (N, Expr_N);
4578                   end if;
4579
4580                   Expr_Typ := Base_Type (Etype (Expr_N));
4581
4582                   if Is_Class_Wide_Type (Expr_Typ) then
4583                      Expr_Typ := Root_Type (Expr_Typ);
4584                   end if;
4585
4586                   --  Replace
4587                   --     CW : I'Class := Obj;
4588                   --  by
4589                   --     Tmp : T := Obj;
4590                   --     CW  : I'Class renames TiC!(Tmp.I_Tag);
4591
4592                   if Comes_From_Source (Expr_N)
4593                     and then Nkind (Expr_N) = N_Identifier
4594                     and then not Is_Interface (Expr_Typ)
4595                     and then (Expr_Typ = Etype (Expr_Typ)
4596                                or else not
4597                               Is_Variable_Size_Record (Etype (Expr_Typ)))
4598                   then
4599                      Decl_1 :=
4600                        Make_Object_Declaration (Loc,
4601                          Defining_Identifier =>
4602                            Make_Temporary (Loc, 'D', Expr_N),
4603                          Object_Definition =>
4604                            New_Occurrence_Of (Expr_Typ, Loc),
4605                          Expression =>
4606                            Unchecked_Convert_To (Expr_Typ,
4607                              Relocate_Node (Expr_N)));
4608
4609                      --  Statically reference the tag associated with the
4610                      --  interface
4611
4612                      Decl_2 :=
4613                        Make_Object_Renaming_Declaration (Loc,
4614                          Defining_Identifier => Make_Temporary (Loc, 'D'),
4615                          Subtype_Mark        => New_Occurrence_Of (Typ, Loc),
4616                          Name                =>
4617                            Unchecked_Convert_To (Typ,
4618                              Make_Selected_Component (Loc,
4619                                Prefix =>
4620                                  New_Occurrence_Of
4621                                    (Defining_Identifier (Decl_1), Loc),
4622                                Selector_Name =>
4623                                  New_Reference_To
4624                                    (Find_Interface_Tag (Expr_Typ, Iface),
4625                                     Loc))));
4626
4627                   --  General case:
4628
4629                   --  Replace
4630                   --     IW : I'Class := Obj;
4631                   --  by
4632                   --     type Equiv_Record is record ... end record;
4633                   --     implicit subtype CW is <Class_Wide_Subtype>;
4634                   --     Temp : CW := CW!(Obj'Address);
4635                   --     IW : I'Class renames Displace (Temp, I'Tag);
4636
4637                   else
4638                      --  Generate the equivalent record type
4639
4640                      Expand_Subtype_From_Expr
4641                        (N             => N,
4642                         Unc_Type      => Typ,
4643                         Subtype_Indic => Object_Definition (N),
4644                         Exp           => Expression (N));
4645
4646                      if not Is_Interface (Etype (Expression (N))) then
4647                         New_Expr := Relocate_Node (Expression (N));
4648                      else
4649                         New_Expr :=
4650                           Make_Explicit_Dereference (Loc,
4651                             Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4652                               Make_Attribute_Reference (Loc,
4653                                 Prefix => Relocate_Node (Expression (N)),
4654                                 Attribute_Name => Name_Address)));
4655                      end if;
4656
4657                      Decl_1 :=
4658                        Make_Object_Declaration (Loc,
4659                          Defining_Identifier =>
4660                            Make_Temporary (Loc, 'D', New_Expr),
4661                          Object_Definition   =>
4662                            New_Occurrence_Of
4663                             (Etype (Object_Definition (N)), Loc),
4664                          Expression          =>
4665                            Unchecked_Convert_To
4666                              (Etype (Object_Definition (N)), New_Expr));
4667
4668                      Decl_2 :=
4669                        Make_Object_Renaming_Declaration (Loc,
4670                          Defining_Identifier => Make_Temporary (Loc, 'D'),
4671                          Subtype_Mark        => New_Occurrence_Of (Typ, Loc),
4672                          Name                =>
4673                            Unchecked_Convert_To (Typ,
4674                              Make_Explicit_Dereference (Loc,
4675                                Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4676                                  Make_Function_Call (Loc,
4677                                    Name =>
4678                                      New_Reference_To (RTE (RE_Displace), Loc),
4679                                    Parameter_Associations => New_List (
4680                                      Make_Attribute_Reference (Loc,
4681                                        Prefix =>
4682                                          New_Occurrence_Of
4683                                           (Defining_Identifier (Decl_1), Loc),
4684                                        Attribute_Name => Name_Address),
4685
4686                                      Unchecked_Convert_To (RTE (RE_Tag),
4687                                        New_Reference_To
4688                                          (Node
4689                                            (First_Elmt
4690                                              (Access_Disp_Table (Iface))),
4691                                           Loc))))))));
4692                   end if;
4693
4694                   Insert_Action (N, Decl_1);
4695                   Rewrite (N, Decl_2);
4696                   Analyze (N);
4697
4698                   --  Replace internal identifier of Decl_2 by the identifier
4699                   --  found in the sources. We also have to exchange entities
4700                   --  containing their defining identifiers to ensure the
4701                   --  correct replacement of the object declaration by this
4702                   --  object renaming declaration (because such definings
4703                   --  identifier have been previously added by Enter_Name to
4704                   --  the current scope). We must preserve the homonym chain
4705                   --  of the source entity as well.
4706
4707                   Set_Chars (Defining_Identifier (N), Chars (Def_Id));
4708                   Set_Homonym (Defining_Identifier (N), Homonym (Def_Id));
4709                   Exchange_Entities (Defining_Identifier (N), Def_Id);
4710                end;
4711             end if;
4712
4713             return;
4714
4715          else
4716             --  In most cases, we must check that the initial value meets any
4717             --  constraint imposed by the declared type. However, there is one
4718             --  very important exception to this rule. If the entity has an
4719             --  unconstrained nominal subtype, then it acquired its constraints
4720             --  from the expression in the first place, and not only does this
4721             --  mean that the constraint check is not needed, but an attempt to
4722             --  perform the constraint check can cause order of elaboration
4723             --  problems.
4724
4725             if not Is_Constr_Subt_For_U_Nominal (Typ) then
4726
4727                --  If this is an allocator for an aggregate that has been
4728                --  allocated in place, delay checks until assignments are
4729                --  made, because the discriminants are not initialized.
4730
4731                if Nkind (Expr) = N_Allocator
4732                  and then No_Initialization (Expr)
4733                then
4734                   null;
4735                else
4736                   Apply_Constraint_Check (Expr, Typ);
4737
4738                   --  If the expression has been marked as requiring a range
4739                   --  generate it now and reset the flag.
4740
4741                   if Do_Range_Check (Expr) then
4742                      Set_Do_Range_Check (Expr, False);
4743                      Generate_Range_Check (Expr, Typ, CE_Range_Check_Failed);
4744                   end if;
4745                end if;
4746             end if;
4747
4748             --  If the type is controlled and not inherently limited, then
4749             --  the target is adjusted after the copy and attached to the
4750             --  finalization list. However, no adjustment is done in the case
4751             --  where the object was initialized by a call to a function whose
4752             --  result is built in place, since no copy occurred. (Eventually
4753             --  we plan to support in-place function results for some cases
4754             --  of nonlimited types. ???) Similarly, no adjustment is required
4755             --  if we are going to rewrite the object declaration into a
4756             --  renaming declaration.
4757
4758             if Needs_Finalization (Typ)
4759               and then not Is_Inherently_Limited_Type (Typ)
4760               and then not Rewrite_As_Renaming
4761             then
4762                Insert_Actions_After (Init_After,
4763                  Make_Adjust_Call (
4764                    Ref          => New_Reference_To (Def_Id, Loc),
4765                    Typ          => Base_Type (Typ),
4766                    Flist_Ref    => Find_Final_List (Def_Id),
4767                    With_Attach  => Make_Integer_Literal (Loc, 1)));
4768             end if;
4769
4770             --  For tagged types, when an init value is given, the tag has to
4771             --  be re-initialized separately in order to avoid the propagation
4772             --  of a wrong tag coming from a view conversion unless the type
4773             --  is class wide (in this case the tag comes from the init value).
4774             --  Suppress the tag assignment when VM_Target because VM tags are
4775             --  represented implicitly in objects. Ditto for types that are
4776             --  CPP_CLASS, and for initializations that are aggregates, because
4777             --  they have to have the right tag.
4778
4779             if Is_Tagged_Type (Typ)
4780               and then not Is_Class_Wide_Type (Typ)
4781               and then not Is_CPP_Class (Typ)
4782               and then Tagged_Type_Expansion
4783               and then Nkind (Expr) /= N_Aggregate
4784             then
4785                --  The re-assignment of the tag has to be done even if the
4786                --  object is a constant.
4787
4788                New_Ref :=
4789                  Make_Selected_Component (Loc,
4790                     Prefix => New_Reference_To (Def_Id, Loc),
4791                     Selector_Name =>
4792                       New_Reference_To (First_Tag_Component (Typ), Loc));
4793
4794                Set_Assignment_OK (New_Ref);
4795
4796                Insert_After (Init_After,
4797                  Make_Assignment_Statement (Loc,
4798                    Name => New_Ref,
4799                    Expression =>
4800                      Unchecked_Convert_To (RTE (RE_Tag),
4801                        New_Reference_To
4802                          (Node
4803                            (First_Elmt
4804                              (Access_Disp_Table (Base_Type (Typ)))),
4805                           Loc))));
4806
4807             elsif Is_Tagged_Type (Typ)
4808               and then Is_CPP_Constructor_Call (Expr)
4809             then
4810                --  The call to the initialization procedure does NOT freeze the
4811                --  object being initialized.
4812
4813                Id_Ref := New_Reference_To (Def_Id, Loc);
4814                Set_Must_Not_Freeze (Id_Ref);
4815                Set_Assignment_OK (Id_Ref);
4816
4817                Insert_Actions_After (Init_After,
4818                  Build_Initialization_Call (Loc, Id_Ref, Typ,
4819                    Constructor_Ref => Expr));
4820
4821                --  We remove here the original call to the constructor
4822                --  to avoid its management in the backend
4823
4824                Set_Expression (N, Empty);
4825                return;
4826
4827             --  For discrete types, set the Is_Known_Valid flag if the
4828             --  initializing value is known to be valid.
4829
4830             elsif Is_Discrete_Type (Typ) and then Expr_Known_Valid (Expr) then
4831                Set_Is_Known_Valid (Def_Id);
4832
4833             elsif Is_Access_Type (Typ) then
4834
4835                --  For access types set the Is_Known_Non_Null flag if the
4836                --  initializing value is known to be non-null. We can also set
4837                --  Can_Never_Be_Null if this is a constant.
4838
4839                if Known_Non_Null (Expr) then
4840                   Set_Is_Known_Non_Null (Def_Id, True);
4841
4842                   if Constant_Present (N) then
4843                      Set_Can_Never_Be_Null (Def_Id);
4844                   end if;
4845                end if;
4846             end if;
4847
4848             --  If validity checking on copies, validate initial expression.
4849             --  But skip this if declaration is for a generic type, since it
4850             --  makes no sense to validate generic types. Not clear if this
4851             --  can happen for legal programs, but it definitely can arise
4852             --  from previous instantiation errors.
4853
4854             if Validity_Checks_On
4855               and then Validity_Check_Copies
4856               and then not Is_Generic_Type (Etype (Def_Id))
4857             then
4858                Ensure_Valid (Expr);
4859                Set_Is_Known_Valid (Def_Id);
4860             end if;
4861          end if;
4862
4863          --  Cases where the back end cannot handle the initialization directly
4864          --  In such cases, we expand an assignment that will be appropriately
4865          --  handled by Expand_N_Assignment_Statement.
4866
4867          --  The exclusion of the unconstrained case is wrong, but for now it
4868          --  is too much trouble ???
4869
4870          if (Is_Possibly_Unaligned_Slice (Expr)
4871                or else (Is_Possibly_Unaligned_Object (Expr)
4872                           and then not Represented_As_Scalar (Etype (Expr))))
4873
4874             --  The exclusion of the unconstrained case is wrong, but for now
4875             --  it is too much trouble ???
4876
4877            and then not (Is_Array_Type (Etype (Expr))
4878                            and then not Is_Constrained (Etype (Expr)))
4879          then
4880             declare
4881                Stat : constant Node_Id :=
4882                        Make_Assignment_Statement (Loc,
4883                          Name       => New_Reference_To (Def_Id, Loc),
4884                          Expression => Relocate_Node (Expr));
4885             begin
4886                Set_Expression (N, Empty);
4887                Set_No_Initialization (N);
4888                Set_Assignment_OK (Name (Stat));
4889                Set_No_Ctrl_Actions (Stat);
4890                Insert_After_And_Analyze (Init_After, Stat);
4891             end;
4892          end if;
4893
4894          --  Final transformation, if the initializing expression is an entity
4895          --  for a variable with OK_To_Rename set, then we transform:
4896
4897          --     X : typ := expr;
4898
4899          --  into
4900
4901          --     X : typ renames expr
4902
4903          --  provided that X is not aliased. The aliased case has to be
4904          --  excluded in general because Expr will not be aliased in general.
4905
4906          if Rewrite_As_Renaming then
4907             Rewrite (N,
4908               Make_Object_Renaming_Declaration (Loc,
4909                 Defining_Identifier => Defining_Identifier (N),
4910                 Subtype_Mark        => Object_Definition (N),
4911                 Name                => Expr_Q));
4912
4913             --  We do not analyze this renaming declaration, because all its
4914             --  components have already been analyzed, and if we were to go
4915             --  ahead and analyze it, we would in effect be trying to generate
4916             --  another declaration of X, which won't do!
4917
4918             Set_Renamed_Object (Defining_Identifier (N), Expr_Q);
4919             Set_Analyzed (N);
4920          end if;
4921
4922       end if;
4923
4924    exception
4925       when RE_Not_Available =>
4926          return;
4927    end Expand_N_Object_Declaration;
4928
4929    ---------------------------------
4930    -- Expand_N_Subtype_Indication --
4931    ---------------------------------
4932
4933    --  Add a check on the range of the subtype. The static case is partially
4934    --  duplicated by Process_Range_Expr_In_Decl in Sem_Ch3, but we still need
4935    --  to check here for the static case in order to avoid generating
4936    --  extraneous expanded code. Also deal with validity checking.
4937
4938    procedure Expand_N_Subtype_Indication (N : Node_Id) is
4939       Ran : constant Node_Id   := Range_Expression (Constraint (N));
4940       Typ : constant Entity_Id := Entity (Subtype_Mark (N));
4941
4942    begin
4943       if Nkind (Constraint (N)) = N_Range_Constraint then
4944          Validity_Check_Range (Range_Expression (Constraint (N)));
4945       end if;
4946
4947       if Nkind_In (Parent (N), N_Constrained_Array_Definition, N_Slice) then
4948          Apply_Range_Check (Ran, Typ);
4949       end if;
4950    end Expand_N_Subtype_Indication;
4951
4952    ---------------------------
4953    -- Expand_N_Variant_Part --
4954    ---------------------------
4955
4956    --  If the last variant does not contain the Others choice, replace it with
4957    --  an N_Others_Choice node since Gigi always wants an Others. Note that we
4958    --  do not bother to call Analyze on the modified variant part, since it's
4959    --  only effect would be to compute the Others_Discrete_Choices node
4960    --  laboriously, and of course we already know the list of choices that
4961    --  corresponds to the others choice (it's the list we are replacing!)
4962
4963    procedure Expand_N_Variant_Part (N : Node_Id) is
4964       Last_Var    : constant Node_Id := Last_Non_Pragma (Variants (N));
4965       Others_Node : Node_Id;
4966    begin
4967       if Nkind (First (Discrete_Choices (Last_Var))) /= N_Others_Choice then
4968          Others_Node := Make_Others_Choice (Sloc (Last_Var));
4969          Set_Others_Discrete_Choices
4970            (Others_Node, Discrete_Choices (Last_Var));
4971          Set_Discrete_Choices (Last_Var, New_List (Others_Node));
4972       end if;
4973    end Expand_N_Variant_Part;
4974
4975    ---------------------------------
4976    -- Expand_Previous_Access_Type --
4977    ---------------------------------
4978
4979    procedure Expand_Previous_Access_Type (Def_Id : Entity_Id) is
4980       T : Entity_Id := First_Entity (Current_Scope);
4981
4982    begin
4983       --  Find all access types declared in the current scope, whose
4984       --  designated type is Def_Id. If it does not have a Master_Id,
4985       --  create one now.
4986
4987       while Present (T) loop
4988          if Is_Access_Type (T)
4989            and then Designated_Type (T) = Def_Id
4990            and then No (Master_Id (T))
4991          then
4992             Build_Master_Entity (Def_Id);
4993             Build_Master_Renaming (Parent (Def_Id), T);
4994          end if;
4995
4996          Next_Entity (T);
4997       end loop;
4998    end Expand_Previous_Access_Type;
4999
5000    ------------------------------
5001    -- Expand_Record_Controller --
5002    ------------------------------
5003
5004    procedure Expand_Record_Controller (T : Entity_Id) is
5005       Def             : Node_Id := Type_Definition (Parent (T));
5006       Comp_List       : Node_Id;
5007       Comp_Decl       : Node_Id;
5008       Loc             : Source_Ptr;
5009       First_Comp      : Node_Id;
5010       Controller_Type : Entity_Id;
5011       Ent             : Entity_Id;
5012
5013    begin
5014       if Nkind (Def) = N_Derived_Type_Definition then
5015          Def := Record_Extension_Part (Def);
5016       end if;
5017
5018       if Null_Present (Def) then
5019          Set_Component_List (Def,
5020            Make_Component_List (Sloc (Def),
5021              Component_Items => Empty_List,
5022              Variant_Part => Empty,
5023              Null_Present => True));
5024       end if;
5025
5026       Comp_List := Component_List (Def);
5027
5028       if Null_Present (Comp_List)
5029         or else Is_Empty_List (Component_Items (Comp_List))
5030       then
5031          Loc := Sloc (Comp_List);
5032       else
5033          Loc := Sloc (First (Component_Items (Comp_List)));
5034       end if;
5035
5036       if Is_Inherently_Limited_Type (T) then
5037          Controller_Type := RTE (RE_Limited_Record_Controller);
5038       else
5039          Controller_Type := RTE (RE_Record_Controller);
5040       end if;
5041
5042       Ent := Make_Defining_Identifier (Loc, Name_uController);
5043
5044       Comp_Decl :=
5045         Make_Component_Declaration (Loc,
5046           Defining_Identifier =>  Ent,
5047           Component_Definition =>
5048             Make_Component_Definition (Loc,
5049               Aliased_Present => False,
5050               Subtype_Indication => New_Reference_To (Controller_Type, Loc)));
5051
5052       if Null_Present (Comp_List)
5053         or else Is_Empty_List (Component_Items (Comp_List))
5054       then
5055          Set_Component_Items (Comp_List, New_List (Comp_Decl));
5056          Set_Null_Present (Comp_List, False);
5057
5058       else
5059          --  The controller cannot be placed before the _Parent field since
5060          --  gigi lays out field in order and _parent must be first to preserve
5061          --  the polymorphism of tagged types.
5062
5063          First_Comp := First (Component_Items (Comp_List));
5064
5065          if not Is_Tagged_Type (T) then
5066             Insert_Before (First_Comp, Comp_Decl);
5067
5068          --  if T is a tagged type, place controller declaration after parent
5069          --  field and after eventual tags of interface types.
5070
5071          else
5072             while Present (First_Comp)
5073               and then
5074                 (Chars (Defining_Identifier (First_Comp)) = Name_uParent
5075                    or else Is_Tag (Defining_Identifier (First_Comp))
5076
5077                --  Ada 2005 (AI-251): The following condition covers secondary
5078                --  tags but also the adjacent component containing the offset
5079                --  to the base of the object (component generated if the parent
5080                --  has discriminants --- see Add_Interface_Tag_Components).
5081                --  This is required to avoid the addition of the controller
5082                --  between the secondary tag and its adjacent component.
5083
5084                    or else Present
5085                              (Related_Type
5086                                (Defining_Identifier (First_Comp))))
5087             loop
5088                Next (First_Comp);
5089             end loop;
5090
5091             --  An empty tagged extension might consist only of the parent
5092             --  component. Otherwise insert the controller before the first
5093             --  component that is neither parent nor tag.
5094
5095             if Present (First_Comp) then
5096                Insert_Before (First_Comp, Comp_Decl);
5097             else
5098                Append (Comp_Decl, Component_Items (Comp_List));
5099             end if;
5100          end if;
5101       end if;
5102
5103       Push_Scope (T);
5104       Analyze (Comp_Decl);
5105       Set_Ekind (Ent, E_Component);
5106       Init_Component_Location (Ent);
5107
5108       --  Move the _controller entity ahead in the list of internal entities
5109       --  of the enclosing record so that it is selected instead of a
5110       --  potentially inherited one.
5111
5112       declare
5113          E    : constant Entity_Id := Last_Entity (T);
5114          Comp : Entity_Id;
5115
5116       begin
5117          pragma Assert (Chars (E) = Name_uController);
5118
5119          Set_Next_Entity (E, First_Entity (T));
5120          Set_First_Entity (T, E);
5121
5122          Comp := Next_Entity (E);
5123          while Next_Entity (Comp) /= E loop
5124             Next_Entity (Comp);
5125          end loop;
5126
5127          Set_Next_Entity (Comp, Empty);
5128          Set_Last_Entity (T, Comp);
5129       end;
5130
5131       End_Scope;
5132
5133    exception
5134       when RE_Not_Available =>
5135          return;
5136    end Expand_Record_Controller;
5137
5138    ------------------------
5139    -- Expand_Tagged_Root --
5140    ------------------------
5141
5142    procedure Expand_Tagged_Root (T : Entity_Id) is
5143       Def       : constant Node_Id := Type_Definition (Parent (T));
5144       Comp_List : Node_Id;
5145       Comp_Decl : Node_Id;
5146       Sloc_N    : Source_Ptr;
5147
5148    begin
5149       if Null_Present (Def) then
5150          Set_Component_List (Def,
5151            Make_Component_List (Sloc (Def),
5152              Component_Items => Empty_List,
5153              Variant_Part => Empty,
5154              Null_Present => True));
5155       end if;
5156
5157       Comp_List := Component_List (Def);
5158
5159       if Null_Present (Comp_List)
5160         or else Is_Empty_List (Component_Items (Comp_List))
5161       then
5162          Sloc_N := Sloc (Comp_List);
5163       else
5164          Sloc_N := Sloc (First (Component_Items (Comp_List)));
5165       end if;
5166
5167       Comp_Decl :=
5168         Make_Component_Declaration (Sloc_N,
5169           Defining_Identifier => First_Tag_Component (T),
5170           Component_Definition =>
5171             Make_Component_Definition (Sloc_N,
5172               Aliased_Present => False,
5173               Subtype_Indication => New_Reference_To (RTE (RE_Tag), Sloc_N)));
5174
5175       if Null_Present (Comp_List)
5176         or else Is_Empty_List (Component_Items (Comp_List))
5177       then
5178          Set_Component_Items (Comp_List, New_List (Comp_Decl));
5179          Set_Null_Present (Comp_List, False);
5180
5181       else
5182          Insert_Before (First (Component_Items (Comp_List)), Comp_Decl);
5183       end if;
5184
5185       --  We don't Analyze the whole expansion because the tag component has
5186       --  already been analyzed previously. Here we just insure that the tree
5187       --  is coherent with the semantic decoration
5188
5189       Find_Type (Subtype_Indication (Component_Definition (Comp_Decl)));
5190
5191    exception
5192       when RE_Not_Available =>
5193          return;
5194    end Expand_Tagged_Root;
5195
5196    ----------------------
5197    -- Clean_Task_Names --
5198    ----------------------
5199
5200    procedure Clean_Task_Names
5201      (Typ     : Entity_Id;
5202       Proc_Id : Entity_Id)
5203    is
5204    begin
5205       if Has_Task (Typ)
5206         and then not Restriction_Active (No_Implicit_Heap_Allocations)
5207         and then not Global_Discard_Names
5208         and then Tagged_Type_Expansion
5209       then
5210          Set_Uses_Sec_Stack (Proc_Id);
5211       end if;
5212    end Clean_Task_Names;
5213
5214    ------------------------------
5215    -- Expand_Freeze_Array_Type --
5216    ------------------------------
5217
5218    procedure Expand_Freeze_Array_Type (N : Node_Id) is
5219       Typ      : constant Entity_Id  := Entity (N);
5220       Comp_Typ : constant Entity_Id := Component_Type (Typ);
5221       Base     : constant Entity_Id  := Base_Type (Typ);
5222
5223    begin
5224       if not Is_Bit_Packed_Array (Typ) then
5225
5226          --  If the component contains tasks, so does the array type. This may
5227          --  not be indicated in the array type because the component may have
5228          --  been a private type at the point of definition. Same if component
5229          --  type is controlled.
5230
5231          Set_Has_Task (Base, Has_Task (Comp_Typ));
5232          Set_Has_Controlled_Component (Base,
5233            Has_Controlled_Component (Comp_Typ)
5234              or else Is_Controlled (Comp_Typ));
5235
5236          if No (Init_Proc (Base)) then
5237
5238             --  If this is an anonymous array created for a declaration with
5239             --  an initial value, its init_proc will never be called. The
5240             --  initial value itself may have been expanded into assignments,
5241             --  in which case the object declaration is carries the
5242             --  No_Initialization flag.
5243
5244             if Is_Itype (Base)
5245               and then Nkind (Associated_Node_For_Itype (Base)) =
5246                                                     N_Object_Declaration
5247               and then (Present (Expression (Associated_Node_For_Itype (Base)))
5248                           or else
5249                         No_Initialization (Associated_Node_For_Itype (Base)))
5250             then
5251                null;
5252
5253             --  We do not need an init proc for string or wide [wide] string,
5254             --  since the only time these need initialization in normalize or
5255             --  initialize scalars mode, and these types are treated specially
5256             --  and do not need initialization procedures.
5257
5258             elsif Root_Type (Base) = Standard_String
5259               or else Root_Type (Base) = Standard_Wide_String
5260               or else Root_Type (Base) = Standard_Wide_Wide_String
5261             then
5262                null;
5263
5264             --  Otherwise we have to build an init proc for the subtype
5265
5266             else
5267                Build_Array_Init_Proc (Base, N);
5268             end if;
5269          end if;
5270
5271          if Typ = Base then
5272             if Has_Controlled_Component (Base) then
5273                Build_Controlling_Procs (Base);
5274
5275                if not Is_Limited_Type (Comp_Typ)
5276                  and then Number_Dimensions (Typ) = 1
5277                then
5278                   Build_Slice_Assignment (Typ);
5279                end if;
5280
5281             elsif Ekind (Comp_Typ) = E_Anonymous_Access_Type
5282               and then Needs_Finalization (Directly_Designated_Type (Comp_Typ))
5283             then
5284                Set_Associated_Final_Chain (Comp_Typ, Add_Final_Chain (Typ));
5285             end if;
5286          end if;
5287
5288       --  For packed case, default initialization, except if the component type
5289       --  is itself a packed structure with an initialization procedure, or
5290       --  initialize/normalize scalars active, and we have a base type, or the
5291       --  type is public, because in that case a client might specify
5292       --  Normalize_Scalars and there better be a public Init_Proc for it.
5293
5294       elsif (Present (Init_Proc (Component_Type (Base)))
5295                and then No (Base_Init_Proc (Base)))
5296         or else (Init_Or_Norm_Scalars and then Base = Typ)
5297         or else Is_Public (Typ)
5298       then
5299          Build_Array_Init_Proc (Base, N);
5300       end if;
5301    end Expand_Freeze_Array_Type;
5302
5303    ------------------------------------
5304    -- Expand_Freeze_Enumeration_Type --
5305    ------------------------------------
5306
5307    procedure Expand_Freeze_Enumeration_Type (N : Node_Id) is
5308       Typ           : constant Entity_Id  := Entity (N);
5309       Loc           : constant Source_Ptr := Sloc (Typ);
5310       Ent           : Entity_Id;
5311       Lst           : List_Id;
5312       Num           : Nat;
5313       Arr           : Entity_Id;
5314       Fent          : Entity_Id;
5315       Ityp          : Entity_Id;
5316       Is_Contiguous : Boolean;
5317       Pos_Expr      : Node_Id;
5318       Last_Repval   : Uint;
5319
5320       Func : Entity_Id;
5321       pragma Warnings (Off, Func);
5322
5323    begin
5324       --  Various optimizations possible if given representation is contiguous
5325
5326       Is_Contiguous := True;
5327
5328       Ent := First_Literal (Typ);
5329       Last_Repval := Enumeration_Rep (Ent);
5330
5331       Next_Literal (Ent);
5332       while Present (Ent) loop
5333          if Enumeration_Rep (Ent) - Last_Repval /= 1 then
5334             Is_Contiguous := False;
5335             exit;
5336          else
5337             Last_Repval := Enumeration_Rep (Ent);
5338          end if;
5339
5340          Next_Literal (Ent);
5341       end loop;
5342
5343       if Is_Contiguous then
5344          Set_Has_Contiguous_Rep (Typ);
5345          Ent := First_Literal (Typ);
5346          Num := 1;
5347          Lst := New_List (New_Reference_To (Ent, Sloc (Ent)));
5348
5349       else
5350          --  Build list of literal references
5351
5352          Lst := New_List;
5353          Num := 0;
5354
5355          Ent := First_Literal (Typ);
5356          while Present (Ent) loop
5357             Append_To (Lst, New_Reference_To (Ent, Sloc (Ent)));
5358             Num := Num + 1;
5359             Next_Literal (Ent);
5360          end loop;
5361       end if;
5362
5363       --  Now build an array declaration
5364
5365       --    typA : array (Natural range 0 .. num - 1) of ctype :=
5366       --             (v, v, v, v, v, ....)
5367
5368       --  where ctype is the corresponding integer type. If the representation
5369       --  is contiguous, we only keep the first literal, which provides the
5370       --  offset for Pos_To_Rep computations.
5371
5372       Arr :=
5373         Make_Defining_Identifier (Loc,
5374           Chars => New_External_Name (Chars (Typ), 'A'));
5375
5376       Append_Freeze_Action (Typ,
5377         Make_Object_Declaration (Loc,
5378           Defining_Identifier => Arr,
5379           Constant_Present    => True,
5380
5381           Object_Definition   =>
5382             Make_Constrained_Array_Definition (Loc,
5383               Discrete_Subtype_Definitions => New_List (
5384                 Make_Subtype_Indication (Loc,
5385                   Subtype_Mark => New_Reference_To (Standard_Natural, Loc),
5386                   Constraint =>
5387                     Make_Range_Constraint (Loc,
5388                       Range_Expression =>
5389                         Make_Range (Loc,
5390                           Low_Bound  =>
5391                             Make_Integer_Literal (Loc, 0),
5392                           High_Bound =>
5393                             Make_Integer_Literal (Loc, Num - 1))))),
5394
5395               Component_Definition =>
5396                 Make_Component_Definition (Loc,
5397                   Aliased_Present => False,
5398                   Subtype_Indication => New_Reference_To (Typ, Loc))),
5399
5400           Expression =>
5401             Make_Aggregate (Loc,
5402               Expressions => Lst)));
5403
5404       Set_Enum_Pos_To_Rep (Typ, Arr);
5405
5406       --  Now we build the function that converts representation values to
5407       --  position values. This function has the form:
5408
5409       --    function _Rep_To_Pos (A : etype; F : Boolean) return Integer is
5410       --    begin
5411       --       case ityp!(A) is
5412       --         when enum-lit'Enum_Rep => return posval;
5413       --         when enum-lit'Enum_Rep => return posval;
5414       --         ...
5415       --         when others   =>
5416       --           [raise Constraint_Error when F "invalid data"]
5417       --           return -1;
5418       --       end case;
5419       --    end;
5420
5421       --  Note: the F parameter determines whether the others case (no valid
5422       --  representation) raises Constraint_Error or returns a unique value
5423       --  of minus one. The latter case is used, e.g. in 'Valid code.
5424
5425       --  Note: the reason we use Enum_Rep values in the case here is to avoid
5426       --  the code generator making inappropriate assumptions about the range
5427       --  of the values in the case where the value is invalid. ityp is a
5428       --  signed or unsigned integer type of appropriate width.
5429
5430       --  Note: if exceptions are not supported, then we suppress the raise
5431       --  and return -1 unconditionally (this is an erroneous program in any
5432       --  case and there is no obligation to raise Constraint_Error here!) We
5433       --  also do this if pragma Restrictions (No_Exceptions) is active.
5434
5435       --  Is this right??? What about No_Exception_Propagation???
5436
5437       --  Representations are signed
5438
5439       if Enumeration_Rep (First_Literal (Typ)) < 0 then
5440
5441          --  The underlying type is signed. Reset the Is_Unsigned_Type
5442          --  explicitly, because it might have been inherited from
5443          --  parent type.
5444
5445          Set_Is_Unsigned_Type (Typ, False);
5446
5447          if Esize (Typ) <= Standard_Integer_Size then
5448             Ityp := Standard_Integer;
5449          else
5450             Ityp := Universal_Integer;
5451          end if;
5452
5453       --  Representations are unsigned
5454
5455       else
5456          if Esize (Typ) <= Standard_Integer_Size then
5457             Ityp := RTE (RE_Unsigned);
5458          else
5459             Ityp := RTE (RE_Long_Long_Unsigned);
5460          end if;
5461       end if;
5462
5463       --  The body of the function is a case statement. First collect case
5464       --  alternatives, or optimize the contiguous case.
5465
5466       Lst := New_List;
5467
5468       --  If representation is contiguous, Pos is computed by subtracting
5469       --  the representation of the first literal.
5470
5471       if Is_Contiguous then
5472          Ent := First_Literal (Typ);
5473
5474          if Enumeration_Rep (Ent) = Last_Repval then
5475
5476             --  Another special case: for a single literal, Pos is zero
5477
5478             Pos_Expr := Make_Integer_Literal (Loc, Uint_0);
5479
5480          else
5481             Pos_Expr :=
5482               Convert_To (Standard_Integer,
5483                 Make_Op_Subtract (Loc,
5484                   Left_Opnd =>
5485                      Unchecked_Convert_To (Ityp,
5486                        Make_Identifier (Loc, Name_uA)),
5487                    Right_Opnd =>
5488                      Make_Integer_Literal (Loc,
5489                         Intval =>
5490                           Enumeration_Rep (First_Literal (Typ)))));
5491          end if;
5492
5493          Append_To (Lst,
5494               Make_Case_Statement_Alternative (Loc,
5495                 Discrete_Choices => New_List (
5496                   Make_Range (Sloc (Enumeration_Rep_Expr (Ent)),
5497                     Low_Bound =>
5498                       Make_Integer_Literal (Loc,
5499                        Intval =>  Enumeration_Rep (Ent)),
5500                     High_Bound =>
5501                       Make_Integer_Literal (Loc, Intval => Last_Repval))),
5502
5503                 Statements => New_List (
5504                   Make_Simple_Return_Statement (Loc,
5505                     Expression => Pos_Expr))));
5506
5507       else
5508          Ent := First_Literal (Typ);
5509          while Present (Ent) loop
5510             Append_To (Lst,
5511               Make_Case_Statement_Alternative (Loc,
5512                 Discrete_Choices => New_List (
5513                   Make_Integer_Literal (Sloc (Enumeration_Rep_Expr (Ent)),
5514                     Intval => Enumeration_Rep (Ent))),
5515
5516                 Statements => New_List (
5517                   Make_Simple_Return_Statement (Loc,
5518                     Expression =>
5519                       Make_Integer_Literal (Loc,
5520                         Intval => Enumeration_Pos (Ent))))));
5521
5522             Next_Literal (Ent);
5523          end loop;
5524       end if;
5525
5526       --  In normal mode, add the others clause with the test
5527
5528       if not No_Exception_Handlers_Set then
5529          Append_To (Lst,
5530            Make_Case_Statement_Alternative (Loc,
5531              Discrete_Choices => New_List (Make_Others_Choice (Loc)),
5532              Statements => New_List (
5533                Make_Raise_Constraint_Error (Loc,
5534                  Condition => Make_Identifier (Loc, Name_uF),
5535                  Reason    => CE_Invalid_Data),
5536                Make_Simple_Return_Statement (Loc,
5537                  Expression =>
5538                    Make_Integer_Literal (Loc, -1)))));
5539
5540       --  If either of the restrictions No_Exceptions_Handlers/Propagation is
5541       --  active then return -1 (we cannot usefully raise Constraint_Error in
5542       --  this case). See description above for further details.
5543
5544       else
5545          Append_To (Lst,
5546            Make_Case_Statement_Alternative (Loc,
5547              Discrete_Choices => New_List (Make_Others_Choice (Loc)),
5548              Statements => New_List (
5549                Make_Simple_Return_Statement (Loc,
5550                  Expression =>
5551                    Make_Integer_Literal (Loc, -1)))));
5552       end if;
5553
5554       --  Now we can build the function body
5555
5556       Fent :=
5557         Make_Defining_Identifier (Loc, Make_TSS_Name (Typ, TSS_Rep_To_Pos));
5558
5559       Func :=
5560         Make_Subprogram_Body (Loc,
5561           Specification =>
5562             Make_Function_Specification (Loc,
5563               Defining_Unit_Name       => Fent,
5564               Parameter_Specifications => New_List (
5565                 Make_Parameter_Specification (Loc,
5566                   Defining_Identifier =>
5567                     Make_Defining_Identifier (Loc, Name_uA),
5568                   Parameter_Type => New_Reference_To (Typ, Loc)),
5569                 Make_Parameter_Specification (Loc,
5570                   Defining_Identifier =>
5571                     Make_Defining_Identifier (Loc, Name_uF),
5572                   Parameter_Type => New_Reference_To (Standard_Boolean, Loc))),
5573
5574               Result_Definition => New_Reference_To (Standard_Integer, Loc)),
5575
5576             Declarations => Empty_List,
5577
5578             Handled_Statement_Sequence =>
5579               Make_Handled_Sequence_Of_Statements (Loc,
5580                 Statements => New_List (
5581                   Make_Case_Statement (Loc,
5582                     Expression =>
5583                       Unchecked_Convert_To (Ityp,
5584                         Make_Identifier (Loc, Name_uA)),
5585                     Alternatives => Lst))));
5586
5587       Set_TSS (Typ, Fent);
5588       Set_Is_Pure (Fent);
5589
5590       if not Debug_Generated_Code then
5591          Set_Debug_Info_Off (Fent);
5592       end if;
5593
5594    exception
5595       when RE_Not_Available =>
5596          return;
5597    end Expand_Freeze_Enumeration_Type;
5598
5599    -------------------------------
5600    -- Expand_Freeze_Record_Type --
5601    -------------------------------
5602
5603    procedure Expand_Freeze_Record_Type (N : Node_Id) is
5604       Def_Id        : constant Node_Id := Entity (N);
5605       Type_Decl     : constant Node_Id := Parent (Def_Id);
5606       Comp          : Entity_Id;
5607       Comp_Typ      : Entity_Id;
5608       Has_Static_DT : Boolean := False;
5609       Predef_List   : List_Id;
5610
5611       Flist : Entity_Id := Empty;
5612       --  Finalization list allocated for the case of a type with anonymous
5613       --  access components whose designated type is potentially controlled.
5614
5615       Renamed_Eq : Node_Id := Empty;
5616       --  Defining unit name for the predefined equality function in the case
5617       --  where the type has a primitive operation that is a renaming of
5618       --  predefined equality (but only if there is also an overriding
5619       --  user-defined equality function). Used to pass this entity from
5620       --  Make_Predefined_Primitive_Specs to Predefined_Primitive_Bodies.
5621
5622       Wrapper_Decl_List   : List_Id := No_List;
5623       Wrapper_Body_List   : List_Id := No_List;
5624       Null_Proc_Decl_List : List_Id := No_List;
5625
5626    --  Start of processing for Expand_Freeze_Record_Type
5627
5628    begin
5629       --  Build discriminant checking functions if not a derived type (for
5630       --  derived types that are not tagged types, always use the discriminant
5631       --  checking functions of the parent type). However, for untagged types
5632       --  the derivation may have taken place before the parent was frozen, so
5633       --  we copy explicitly the discriminant checking functions from the
5634       --  parent into the components of the derived type.
5635
5636       if not Is_Derived_Type (Def_Id)
5637         or else Has_New_Non_Standard_Rep (Def_Id)
5638         or else Is_Tagged_Type (Def_Id)
5639       then
5640          Build_Discr_Checking_Funcs (Type_Decl);
5641
5642       elsif Is_Derived_Type (Def_Id)
5643         and then not Is_Tagged_Type (Def_Id)
5644
5645          --  If we have a derived Unchecked_Union, we do not inherit the
5646          --  discriminant checking functions from the parent type since the
5647          --  discriminants are non existent.
5648
5649         and then not Is_Unchecked_Union (Def_Id)
5650         and then Has_Discriminants (Def_Id)
5651       then
5652          declare
5653             Old_Comp : Entity_Id;
5654
5655          begin
5656             Old_Comp :=
5657               First_Component (Base_Type (Underlying_Type (Etype (Def_Id))));
5658             Comp := First_Component (Def_Id);
5659             while Present (Comp) loop
5660                if Ekind (Comp) = E_Component
5661                  and then Chars (Comp) = Chars (Old_Comp)
5662                then
5663                   Set_Discriminant_Checking_Func (Comp,
5664                     Discriminant_Checking_Func (Old_Comp));
5665                end if;
5666
5667                Next_Component (Old_Comp);
5668                Next_Component (Comp);
5669             end loop;
5670          end;
5671       end if;
5672
5673       if Is_Derived_Type (Def_Id)
5674         and then Is_Limited_Type (Def_Id)
5675         and then Is_Tagged_Type (Def_Id)
5676       then
5677          Check_Stream_Attributes (Def_Id);
5678       end if;
5679
5680       --  Update task and controlled component flags, because some of the
5681       --  component types may have been private at the point of the record
5682       --  declaration.
5683
5684       Comp := First_Component (Def_Id);
5685
5686       while Present (Comp) loop
5687          Comp_Typ := Etype (Comp);
5688
5689          if Has_Task (Comp_Typ) then
5690             Set_Has_Task (Def_Id);
5691
5692          --  Do not set Has_Controlled_Component on a class-wide equivalent
5693          --  type. See Make_CW_Equivalent_Type.
5694
5695          elsif not Is_Class_Wide_Equivalent_Type (Def_Id)
5696            and then (Has_Controlled_Component (Comp_Typ)
5697                       or else (Chars (Comp) /= Name_uParent
5698                                 and then Is_Controlled (Comp_Typ)))
5699          then
5700             Set_Has_Controlled_Component (Def_Id);
5701
5702          elsif Ekind (Comp_Typ) = E_Anonymous_Access_Type
5703            and then Needs_Finalization (Directly_Designated_Type (Comp_Typ))
5704          then
5705             if No (Flist) then
5706                Flist := Add_Final_Chain (Def_Id);
5707             end if;
5708
5709             Set_Associated_Final_Chain (Comp_Typ, Flist);
5710          end if;
5711
5712          Next_Component (Comp);
5713       end loop;
5714
5715       --  Handle constructors of non-tagged CPP_Class types
5716
5717       if not Is_Tagged_Type (Def_Id) and then Is_CPP_Class (Def_Id) then
5718          Set_CPP_Constructors (Def_Id);
5719       end if;
5720
5721       --  Creation of the Dispatch Table. Note that a Dispatch Table is built
5722       --  for regular tagged types as well as for Ada types deriving from a C++
5723       --  Class, but not for tagged types directly corresponding to C++ classes
5724       --  In the later case we assume that it is created in the C++ side and we
5725       --  just use it.
5726
5727       if Is_Tagged_Type (Def_Id) then
5728          Has_Static_DT :=
5729            Static_Dispatch_Tables
5730              and then Is_Library_Level_Tagged_Type (Def_Id);
5731
5732          --  Add the _Tag component
5733
5734          if Underlying_Type (Etype (Def_Id)) = Def_Id then
5735             Expand_Tagged_Root (Def_Id);
5736          end if;
5737
5738          if Is_CPP_Class (Def_Id) then
5739             Set_All_DT_Position (Def_Id);
5740             Set_CPP_Constructors (Def_Id);
5741
5742             --  Create the tag entities with a minimum decoration
5743
5744             if Tagged_Type_Expansion then
5745                Append_Freeze_Actions (Def_Id, Make_Tags (Def_Id));
5746             end if;
5747
5748          else
5749             if not Has_Static_DT then
5750
5751                --  Usually inherited primitives are not delayed but the first
5752                --  Ada extension of a CPP_Class is an exception since the
5753                --  address of the inherited subprogram has to be inserted in
5754                --  the new Ada Dispatch Table and this is a freezing action.
5755
5756                --  Similarly, if this is an inherited operation whose parent is
5757                --  not frozen yet, it is not in the DT of the parent, and we
5758                --  generate an explicit freeze node for the inherited operation
5759                --  so that it is properly inserted in the DT of the current
5760                --  type.
5761
5762                declare
5763                   Elmt : Elmt_Id := First_Elmt (Primitive_Operations (Def_Id));
5764                   Subp : Entity_Id;
5765
5766                begin
5767                   while Present (Elmt) loop
5768                      Subp := Node (Elmt);
5769
5770                      if Present (Alias (Subp)) then
5771                         if Is_CPP_Class (Etype (Def_Id)) then
5772                            Set_Has_Delayed_Freeze (Subp);
5773
5774                         elsif Has_Delayed_Freeze (Alias (Subp))
5775                           and then not Is_Frozen (Alias (Subp))
5776                         then
5777                            Set_Is_Frozen (Subp, False);
5778                            Set_Has_Delayed_Freeze (Subp);
5779                         end if;
5780                      end if;
5781
5782                      Next_Elmt (Elmt);
5783                   end loop;
5784                end;
5785             end if;
5786
5787             --  Unfreeze momentarily the type to add the predefined primitives
5788             --  operations. The reason we unfreeze is so that these predefined
5789             --  operations will indeed end up as primitive operations (which
5790             --  must be before the freeze point).
5791
5792             Set_Is_Frozen (Def_Id, False);
5793
5794             --  Do not add the spec of predefined primitives in case of
5795             --  CPP tagged type derivations that have convention CPP.
5796
5797             if Is_CPP_Class (Root_Type (Def_Id))
5798               and then Convention (Def_Id) = Convention_CPP
5799             then
5800                null;
5801
5802             --  Do not add the spec of the predefined primitives if we are
5803             --  compiling under restriction No_Dispatching_Calls
5804
5805             elsif not Restriction_Active (No_Dispatching_Calls) then
5806                Make_Predefined_Primitive_Specs
5807                  (Def_Id, Predef_List, Renamed_Eq);
5808                Insert_List_Before_And_Analyze (N, Predef_List);
5809             end if;
5810
5811             --  Ada 2005 (AI-391): For a nonabstract null extension, create
5812             --  wrapper functions for each nonoverridden inherited function
5813             --  with a controlling result of the type. The wrapper for such
5814             --  a function returns an extension aggregate that invokes the
5815             --  the parent function.
5816
5817             if Ada_Version >= Ada_05
5818               and then not Is_Abstract_Type (Def_Id)
5819               and then Is_Null_Extension (Def_Id)
5820             then
5821                Make_Controlling_Function_Wrappers
5822                  (Def_Id, Wrapper_Decl_List, Wrapper_Body_List);
5823                Insert_List_Before_And_Analyze (N, Wrapper_Decl_List);
5824             end if;
5825
5826             --  Ada 2005 (AI-251): For a nonabstract type extension, build
5827             --  null procedure declarations for each set of homographic null
5828             --  procedures that are inherited from interface types but not
5829             --  overridden. This is done to ensure that the dispatch table
5830             --  entry associated with such null primitives are properly filled.
5831
5832             if Ada_Version >= Ada_05
5833               and then Etype (Def_Id) /= Def_Id
5834               and then not Is_Abstract_Type (Def_Id)
5835             then
5836                Make_Null_Procedure_Specs (Def_Id, Null_Proc_Decl_List);
5837                Insert_Actions (N, Null_Proc_Decl_List);
5838             end if;
5839
5840             Set_Is_Frozen (Def_Id);
5841             Set_All_DT_Position (Def_Id);
5842
5843             --  Add the controlled component before the freezing actions
5844             --  referenced in those actions.
5845
5846             if Has_New_Controlled_Component (Def_Id) then
5847                Expand_Record_Controller (Def_Id);
5848             end if;
5849
5850             --  Create and decorate the tags. Suppress their creation when
5851             --  VM_Target because the dispatching mechanism is handled
5852             --  internally by the VMs.
5853
5854             if Tagged_Type_Expansion then
5855                Append_Freeze_Actions (Def_Id, Make_Tags (Def_Id));
5856
5857                --  Generate dispatch table of locally defined tagged type.
5858                --  Dispatch tables of library level tagged types are built
5859                --  later (see Analyze_Declarations).
5860
5861                if not Has_Static_DT then
5862                   Append_Freeze_Actions (Def_Id, Make_DT (Def_Id));
5863                end if;
5864             end if;
5865
5866             --  If the type has unknown discriminants, propagate dispatching
5867             --  information to its underlying record view, which does not get
5868             --  its own dispatch table.
5869
5870             if Is_Derived_Type (Def_Id)
5871               and then Has_Unknown_Discriminants (Def_Id)
5872               and then Present (Underlying_Record_View (Def_Id))
5873             then
5874                declare
5875                   Rep : constant Entity_Id :=
5876                            Underlying_Record_View (Def_Id);
5877                begin
5878                   Set_Access_Disp_Table
5879                     (Rep, Access_Disp_Table       (Def_Id));
5880                   Set_Dispatch_Table_Wrappers
5881                     (Rep, Dispatch_Table_Wrappers (Def_Id));
5882                   Set_Primitive_Operations
5883                     (Rep, Primitive_Operations    (Def_Id));
5884                end;
5885             end if;
5886
5887             --  Make sure that the primitives Initialize, Adjust and Finalize
5888             --  are Frozen before other TSS subprograms. We don't want them
5889             --  Frozen inside.
5890
5891             if Is_Controlled (Def_Id) then
5892                if not Is_Limited_Type (Def_Id) then
5893                   Append_Freeze_Actions (Def_Id,
5894                     Freeze_Entity
5895                       (Find_Prim_Op (Def_Id, Name_Adjust), Sloc (Def_Id)));
5896                end if;
5897
5898                Append_Freeze_Actions (Def_Id,
5899                  Freeze_Entity
5900                    (Find_Prim_Op (Def_Id, Name_Initialize), Sloc (Def_Id)));
5901
5902                Append_Freeze_Actions (Def_Id,
5903                  Freeze_Entity
5904                    (Find_Prim_Op (Def_Id, Name_Finalize), Sloc (Def_Id)));
5905             end if;
5906
5907             --  Freeze rest of primitive operations. There is no need to handle
5908             --  the predefined primitives if we are compiling under restriction
5909             --  No_Dispatching_Calls
5910
5911             if not Restriction_Active (No_Dispatching_Calls) then
5912                Append_Freeze_Actions
5913                  (Def_Id, Predefined_Primitive_Freeze (Def_Id));
5914             end if;
5915          end if;
5916
5917       --  In the non-tagged case, an equality function is provided only for
5918       --  variant records (that are not unchecked unions).
5919
5920       elsif Has_Discriminants (Def_Id)
5921         and then not Is_Limited_Type (Def_Id)
5922       then
5923          declare
5924             Comps : constant Node_Id :=
5925                       Component_List (Type_Definition (Type_Decl));
5926
5927          begin
5928             if Present (Comps)
5929               and then Present (Variant_Part (Comps))
5930             then
5931                Build_Variant_Record_Equality (Def_Id);
5932             end if;
5933          end;
5934       end if;
5935
5936       --  Before building the record initialization procedure, if we are
5937       --  dealing with a concurrent record value type, then we must go through
5938       --  the discriminants, exchanging discriminals between the concurrent
5939       --  type and the concurrent record value type. See the section "Handling
5940       --  of Discriminants" in the Einfo spec for details.
5941
5942       if Is_Concurrent_Record_Type (Def_Id)
5943         and then Has_Discriminants (Def_Id)
5944       then
5945          declare
5946             Ctyp : constant Entity_Id :=
5947                      Corresponding_Concurrent_Type (Def_Id);
5948             Conc_Discr : Entity_Id;
5949             Rec_Discr  : Entity_Id;
5950             Temp       : Entity_Id;
5951
5952          begin
5953             Conc_Discr := First_Discriminant (Ctyp);
5954             Rec_Discr  := First_Discriminant (Def_Id);
5955
5956             while Present (Conc_Discr) loop
5957                Temp := Discriminal (Conc_Discr);
5958                Set_Discriminal (Conc_Discr, Discriminal (Rec_Discr));
5959                Set_Discriminal (Rec_Discr, Temp);
5960
5961                Set_Discriminal_Link (Discriminal (Conc_Discr), Conc_Discr);
5962                Set_Discriminal_Link (Discriminal (Rec_Discr),  Rec_Discr);
5963
5964                Next_Discriminant (Conc_Discr);
5965                Next_Discriminant (Rec_Discr);
5966             end loop;
5967          end;
5968       end if;
5969
5970       if Has_Controlled_Component (Def_Id) then
5971          if No (Controller_Component (Def_Id)) then
5972             Expand_Record_Controller (Def_Id);
5973          end if;
5974
5975          Build_Controlling_Procs (Def_Id);
5976       end if;
5977
5978       Adjust_Discriminants (Def_Id);
5979
5980       if Tagged_Type_Expansion or else not Is_Interface (Def_Id) then
5981
5982          --  Do not need init for interfaces on e.g. CIL since they're
5983          --  abstract. Helps operation of peverify (the PE Verify tool).
5984
5985          Build_Record_Init_Proc (Type_Decl, Def_Id);
5986       end if;
5987
5988       --  For tagged type that are not interfaces, build bodies of primitive
5989       --  operations. Note that we do this after building the record
5990       --  initialization procedure, since the primitive operations may need
5991       --  the initialization routine. There is no need to add predefined
5992       --  primitives of interfaces because all their predefined primitives
5993       --  are abstract.
5994
5995       if Is_Tagged_Type (Def_Id)
5996         and then not Is_Interface (Def_Id)
5997       then
5998          --  Do not add the body of predefined primitives in case of
5999          --  CPP tagged type derivations that have convention CPP.
6000
6001          if Is_CPP_Class (Root_Type (Def_Id))
6002            and then Convention (Def_Id) = Convention_CPP
6003          then
6004             null;
6005
6006          --  Do not add the body of the predefined primitives if we are
6007          --  compiling under restriction No_Dispatching_Calls or if we are
6008          --  compiling a CPP tagged type.
6009
6010          elsif not Restriction_Active (No_Dispatching_Calls) then
6011             Predef_List := Predefined_Primitive_Bodies (Def_Id, Renamed_Eq);
6012             Append_Freeze_Actions (Def_Id, Predef_List);
6013          end if;
6014
6015          --  Ada 2005 (AI-391): If any wrappers were created for nonoverridden
6016          --  inherited functions, then add their bodies to the freeze actions.
6017
6018          if Present (Wrapper_Body_List) then
6019             Append_Freeze_Actions (Def_Id, Wrapper_Body_List);
6020          end if;
6021
6022          --  Create extra formals for the primitive operations of the type.
6023          --  This must be done before analyzing the body of the initialization
6024          --  procedure, because a self-referential type might call one of these
6025          --  primitives in the body of the init_proc itself.
6026
6027          declare
6028             Elmt : Elmt_Id;
6029             Subp : Entity_Id;
6030
6031          begin
6032             Elmt := First_Elmt (Primitive_Operations (Def_Id));
6033             while Present (Elmt) loop
6034                Subp := Node (Elmt);
6035                if not Has_Foreign_Convention (Subp)
6036                  and then not Is_Predefined_Dispatching_Operation (Subp)
6037                then
6038                   Create_Extra_Formals (Subp);
6039                end if;
6040
6041                Next_Elmt (Elmt);
6042             end loop;
6043          end;
6044       end if;
6045    end Expand_Freeze_Record_Type;
6046
6047    ------------------------------
6048    -- Freeze_Stream_Operations --
6049    ------------------------------
6050
6051    procedure Freeze_Stream_Operations (N : Node_Id; Typ : Entity_Id) is
6052       Names     : constant array (1 .. 4) of TSS_Name_Type :=
6053                     (TSS_Stream_Input,
6054                      TSS_Stream_Output,
6055                      TSS_Stream_Read,
6056                      TSS_Stream_Write);
6057       Stream_Op : Entity_Id;
6058
6059    begin
6060       --  Primitive operations of tagged types are frozen when the dispatch
6061       --  table is constructed.
6062
6063       if not Comes_From_Source (Typ)
6064         or else Is_Tagged_Type (Typ)
6065       then
6066          return;
6067       end if;
6068
6069       for J in Names'Range loop
6070          Stream_Op := TSS (Typ, Names (J));
6071
6072          if Present (Stream_Op)
6073            and then Is_Subprogram (Stream_Op)
6074            and then Nkind (Unit_Declaration_Node (Stream_Op)) =
6075                       N_Subprogram_Declaration
6076            and then not Is_Frozen (Stream_Op)
6077          then
6078             Append_Freeze_Actions
6079                (Typ, Freeze_Entity (Stream_Op, Sloc (N)));
6080          end if;
6081       end loop;
6082    end Freeze_Stream_Operations;
6083
6084    -----------------
6085    -- Freeze_Type --
6086    -----------------
6087
6088    --  Full type declarations are expanded at the point at which the type is
6089    --  frozen. The formal N is the Freeze_Node for the type. Any statements or
6090    --  declarations generated by the freezing (e.g. the procedure generated
6091    --  for initialization) are chained in the Actions field list of the freeze
6092    --  node using Append_Freeze_Actions.
6093
6094    function Freeze_Type (N : Node_Id) return Boolean is
6095       Def_Id    : constant Entity_Id := Entity (N);
6096       RACW_Seen : Boolean := False;
6097       Result    : Boolean := False;
6098
6099    begin
6100       --  Process associated access types needing special processing
6101
6102       if Present (Access_Types_To_Process (N)) then
6103          declare
6104             E : Elmt_Id := First_Elmt (Access_Types_To_Process (N));
6105          begin
6106             while Present (E) loop
6107
6108                if Is_Remote_Access_To_Class_Wide_Type (Node (E)) then
6109                   Validate_RACW_Primitives (Node (E));
6110                   RACW_Seen := True;
6111                end if;
6112
6113                E := Next_Elmt (E);
6114             end loop;
6115          end;
6116
6117          if RACW_Seen then
6118
6119             --  If there are RACWs designating this type, make stubs now
6120
6121             Remote_Types_Tagged_Full_View_Encountered (Def_Id);
6122          end if;
6123       end if;
6124
6125       --  Freeze processing for record types
6126
6127       if Is_Record_Type (Def_Id) then
6128          if Ekind (Def_Id) = E_Record_Type then
6129             Expand_Freeze_Record_Type (N);
6130
6131          --  The subtype may have been declared before the type was frozen. If
6132          --  the type has controlled components it is necessary to create the
6133          --  entity for the controller explicitly because it did not exist at
6134          --  the point of the subtype declaration. Only the entity is needed,
6135          --  the back-end will obtain the layout from the type. This is only
6136          --  necessary if this is constrained subtype whose component list is
6137          --  not shared with the base type.
6138
6139          elsif Ekind (Def_Id) = E_Record_Subtype
6140            and then Has_Discriminants (Def_Id)
6141            and then Last_Entity (Def_Id) /= Last_Entity (Base_Type (Def_Id))
6142            and then Present (Controller_Component (Def_Id))
6143          then
6144             declare
6145                Old_C : constant Entity_Id := Controller_Component (Def_Id);
6146                New_C : Entity_Id;
6147
6148             begin
6149                if Scope (Old_C) = Base_Type (Def_Id) then
6150
6151                   --  The entity is the one in the parent. Create new one
6152
6153                   New_C := New_Copy (Old_C);
6154                   Set_Parent (New_C, Parent (Old_C));
6155                   Push_Scope (Def_Id);
6156                   Enter_Name (New_C);
6157                   End_Scope;
6158                end if;
6159             end;
6160
6161             if Is_Itype (Def_Id)
6162               and then Is_Record_Type (Underlying_Type (Scope (Def_Id)))
6163             then
6164                --  The freeze node is only used to introduce the controller,
6165                --  the back-end has no use for it for a discriminated
6166                --  component.
6167
6168                Set_Freeze_Node (Def_Id, Empty);
6169                Set_Has_Delayed_Freeze (Def_Id, False);
6170                Result := True;
6171             end if;
6172
6173          --  Similar process if the controller of the subtype is not present
6174          --  but the parent has it. This can happen with constrained
6175          --  record components where the subtype is an itype.
6176
6177          elsif Ekind (Def_Id) = E_Record_Subtype
6178            and then Is_Itype (Def_Id)
6179            and then No (Controller_Component (Def_Id))
6180            and then Present (Controller_Component (Etype (Def_Id)))
6181          then
6182             declare
6183                Old_C : constant Entity_Id :=
6184                          Controller_Component (Etype (Def_Id));
6185                New_C : constant Entity_Id := New_Copy (Old_C);
6186
6187             begin
6188                Set_Next_Entity  (New_C, First_Entity (Def_Id));
6189                Set_First_Entity (Def_Id, New_C);
6190
6191                --  The freeze node is only used to introduce the controller,
6192                --  the back-end has no use for it for a discriminated
6193                --   component.
6194
6195                Set_Freeze_Node (Def_Id, Empty);
6196                Set_Has_Delayed_Freeze (Def_Id, False);
6197                Result := True;
6198             end;
6199          end if;
6200
6201       --  Freeze processing for array types
6202
6203       elsif Is_Array_Type (Def_Id) then
6204          Expand_Freeze_Array_Type (N);
6205
6206       --  Freeze processing for access types
6207
6208       --  For pool-specific access types, find out the pool object used for
6209       --  this type, needs actual expansion of it in some cases. Here are the
6210       --  different cases :
6211
6212       --  1. Rep Clause "for Def_Id'Storage_Size use 0;"
6213       --      ---> don't use any storage pool
6214
6215       --  2. Rep Clause : for Def_Id'Storage_Size use Expr.
6216       --     Expand:
6217       --      Def_Id__Pool : Stack_Bounded_Pool (Expr, DT'Size, DT'Alignment);
6218
6219       --  3. Rep Clause "for Def_Id'Storage_Pool use a_Pool_Object"
6220       --      ---> Storage Pool is the specified one
6221
6222       --  See GNAT Pool packages in the Run-Time for more details
6223
6224       elsif Ekind (Def_Id) = E_Access_Type
6225         or else Ekind (Def_Id) = E_General_Access_Type
6226       then
6227          declare
6228             Loc         : constant Source_Ptr := Sloc (N);
6229             Desig_Type  : constant Entity_Id  := Designated_Type (Def_Id);
6230             Pool_Object : Entity_Id;
6231
6232             Freeze_Action_Typ : Entity_Id;
6233
6234          begin
6235             --  Case 1
6236
6237             --    Rep Clause "for Def_Id'Storage_Size use 0;"
6238             --    ---> don't use any storage pool
6239
6240             if No_Pool_Assigned (Def_Id) then
6241                null;
6242
6243             --  Case 2
6244
6245             --    Rep Clause : for Def_Id'Storage_Size use Expr.
6246             --    ---> Expand:
6247             --           Def_Id__Pool : Stack_Bounded_Pool
6248             --                            (Expr, DT'Size, DT'Alignment);
6249
6250             elsif Has_Storage_Size_Clause (Def_Id) then
6251                declare
6252                   DT_Size  : Node_Id;
6253                   DT_Align : Node_Id;
6254
6255                begin
6256                   --  For unconstrained composite types we give a size of zero
6257                   --  so that the pool knows that it needs a special algorithm
6258                   --  for variable size object allocation.
6259
6260                   if Is_Composite_Type (Desig_Type)
6261                     and then not Is_Constrained (Desig_Type)
6262                   then
6263                      DT_Size :=
6264                        Make_Integer_Literal (Loc, 0);
6265
6266                      DT_Align :=
6267                        Make_Integer_Literal (Loc, Maximum_Alignment);
6268
6269                   else
6270                      DT_Size :=
6271                        Make_Attribute_Reference (Loc,
6272                          Prefix => New_Reference_To (Desig_Type, Loc),
6273                          Attribute_Name => Name_Max_Size_In_Storage_Elements);
6274
6275                      DT_Align :=
6276                        Make_Attribute_Reference (Loc,
6277                          Prefix => New_Reference_To (Desig_Type, Loc),
6278                          Attribute_Name => Name_Alignment);
6279                   end if;
6280
6281                   Pool_Object :=
6282                     Make_Defining_Identifier (Loc,
6283                       Chars => New_External_Name (Chars (Def_Id), 'P'));
6284
6285                   --  We put the code associated with the pools in the entity
6286                   --  that has the later freeze node, usually the access type
6287                   --  but it can also be the designated_type; because the pool
6288                   --  code requires both those types to be frozen
6289
6290                   if Is_Frozen (Desig_Type)
6291                     and then (No (Freeze_Node (Desig_Type))
6292                                or else Analyzed (Freeze_Node (Desig_Type)))
6293                   then
6294                      Freeze_Action_Typ := Def_Id;
6295
6296                   --  A Taft amendment type cannot get the freeze actions
6297                   --  since the full view is not there.
6298
6299                   elsif Is_Incomplete_Or_Private_Type (Desig_Type)
6300                     and then No (Full_View (Desig_Type))
6301                   then
6302                      Freeze_Action_Typ := Def_Id;
6303
6304                   else
6305                      Freeze_Action_Typ := Desig_Type;
6306                   end if;
6307
6308                   Append_Freeze_Action (Freeze_Action_Typ,
6309                     Make_Object_Declaration (Loc,
6310                       Defining_Identifier => Pool_Object,
6311                       Object_Definition =>
6312                         Make_Subtype_Indication (Loc,
6313                           Subtype_Mark =>
6314                             New_Reference_To
6315                               (RTE (RE_Stack_Bounded_Pool), Loc),
6316
6317                           Constraint =>
6318                             Make_Index_Or_Discriminant_Constraint (Loc,
6319                               Constraints => New_List (
6320
6321                               --  First discriminant is the Pool Size
6322
6323                                 New_Reference_To (
6324                                   Storage_Size_Variable (Def_Id), Loc),
6325
6326                               --  Second discriminant is the element size
6327
6328                                 DT_Size,
6329
6330                               --  Third discriminant is the alignment
6331
6332                                 DT_Align)))));
6333                end;
6334
6335                Set_Associated_Storage_Pool (Def_Id, Pool_Object);
6336
6337             --  Case 3
6338
6339             --    Rep Clause "for Def_Id'Storage_Pool use a_Pool_Object"
6340             --    ---> Storage Pool is the specified one
6341
6342             elsif Present (Associated_Storage_Pool (Def_Id)) then
6343
6344                --  Nothing to do the associated storage pool has been attached
6345                --  when analyzing the rep. clause
6346
6347                null;
6348             end if;
6349
6350             --  For access-to-controlled types (including class-wide types and
6351             --  Taft-amendment types which potentially have controlled
6352             --  components), expand the list controller object that will store
6353             --  the dynamically allocated objects. Do not do this
6354             --  transformation for expander-generated access types, but do it
6355             --  for types that are the full view of types derived from other
6356             --  private types. Also suppress the list controller in the case
6357             --  of a designated type with convention Java, since this is used
6358             --  when binding to Java API specs, where there's no equivalent of
6359             --  a finalization list and we don't want to pull in the
6360             --  finalization support if not needed.
6361
6362             if not Comes_From_Source (Def_Id)
6363                and then not Has_Private_Declaration (Def_Id)
6364             then
6365                null;
6366
6367             elsif (Needs_Finalization (Desig_Type)
6368                     and then Convention (Desig_Type) /= Convention_Java
6369                     and then Convention (Desig_Type) /= Convention_CIL)
6370               or else
6371                 (Is_Incomplete_Or_Private_Type (Desig_Type)
6372                    and then No (Full_View (Desig_Type))
6373
6374                   --  An exception is made for types defined in the run-time
6375                   --  because Ada.Tags.Tag itself is such a type and cannot
6376                   --  afford this unnecessary overhead that would generates a
6377                   --  loop in the expansion scheme...
6378
6379                   and then not In_Runtime (Def_Id)
6380
6381                   --  Another exception is if Restrictions (No_Finalization)
6382                   --  is active, since then we know nothing is controlled.
6383
6384                   and then not Restriction_Active (No_Finalization))
6385
6386                --  If the designated type is not frozen yet, its controlled
6387                --  status must be retrieved explicitly.
6388
6389               or else (Is_Array_Type (Desig_Type)
6390                 and then not Is_Frozen (Desig_Type)
6391                 and then Needs_Finalization (Component_Type (Desig_Type)))
6392
6393                --  The designated type has controlled anonymous access
6394                --  discriminants.
6395
6396               or else Has_Controlled_Coextensions (Desig_Type)
6397             then
6398                Set_Associated_Final_Chain (Def_Id, Add_Final_Chain (Def_Id));
6399             end if;
6400          end;
6401
6402       --  Freeze processing for enumeration types
6403
6404       elsif Ekind (Def_Id) = E_Enumeration_Type then
6405
6406          --  We only have something to do if we have a non-standard
6407          --  representation (i.e. at least one literal whose pos value
6408          --  is not the same as its representation)
6409
6410          if Has_Non_Standard_Rep (Def_Id) then
6411             Expand_Freeze_Enumeration_Type (N);
6412          end if;
6413
6414       --  Private types that are completed by a derivation from a private
6415       --  type have an internally generated full view, that needs to be
6416       --  frozen. This must be done explicitly because the two views share
6417       --  the freeze node, and the underlying full view is not visible when
6418       --  the freeze node is analyzed.
6419
6420       elsif Is_Private_Type (Def_Id)
6421         and then Is_Derived_Type (Def_Id)
6422         and then Present (Full_View (Def_Id))
6423         and then Is_Itype (Full_View (Def_Id))
6424         and then Has_Private_Declaration (Full_View (Def_Id))
6425         and then Freeze_Node (Full_View (Def_Id)) = N
6426       then
6427          Set_Entity (N, Full_View (Def_Id));
6428          Result := Freeze_Type (N);
6429          Set_Entity (N, Def_Id);
6430
6431       --  All other types require no expander action. There are such cases
6432       --  (e.g. task types and protected types). In such cases, the freeze
6433       --  nodes are there for use by Gigi.
6434
6435       end if;
6436
6437       Freeze_Stream_Operations (N, Def_Id);
6438       return Result;
6439
6440    exception
6441       when RE_Not_Available =>
6442          return False;
6443    end Freeze_Type;
6444
6445    -------------------------
6446    -- Get_Simple_Init_Val --
6447    -------------------------
6448
6449    function Get_Simple_Init_Val
6450      (T    : Entity_Id;
6451       N    : Node_Id;
6452       Size : Uint := No_Uint) return Node_Id
6453    is
6454       Loc    : constant Source_Ptr := Sloc (N);
6455       Val    : Node_Id;
6456       Result : Node_Id;
6457       Val_RE : RE_Id;
6458
6459       Size_To_Use : Uint;
6460       --  This is the size to be used for computation of the appropriate
6461       --  initial value for the Normalize_Scalars and Initialize_Scalars case.
6462
6463       IV_Attribute : constant Boolean :=
6464                        Nkind (N) = N_Attribute_Reference
6465                          and then Attribute_Name (N) = Name_Invalid_Value;
6466
6467       Lo_Bound : Uint;
6468       Hi_Bound : Uint;
6469       --  These are the values computed by the procedure Check_Subtype_Bounds
6470
6471       procedure Check_Subtype_Bounds;
6472       --  This procedure examines the subtype T, and its ancestor subtypes and
6473       --  derived types to determine the best known information about the
6474       --  bounds of the subtype. After the call Lo_Bound is set either to
6475       --  No_Uint if no information can be determined, or to a value which
6476       --  represents a known low bound, i.e. a valid value of the subtype can
6477       --  not be less than this value. Hi_Bound is similarly set to a known
6478       --  high bound (valid value cannot be greater than this).
6479
6480       --------------------------
6481       -- Check_Subtype_Bounds --
6482       --------------------------
6483
6484       procedure Check_Subtype_Bounds is
6485          ST1  : Entity_Id;
6486          ST2  : Entity_Id;
6487          Lo   : Node_Id;
6488          Hi   : Node_Id;
6489          Loval : Uint;
6490          Hival : Uint;
6491
6492       begin
6493          Lo_Bound := No_Uint;
6494          Hi_Bound := No_Uint;
6495
6496          --  Loop to climb ancestor subtypes and derived types
6497
6498          ST1 := T;
6499          loop
6500             if not Is_Discrete_Type (ST1) then
6501                return;
6502             end if;
6503
6504             Lo := Type_Low_Bound (ST1);
6505             Hi := Type_High_Bound (ST1);
6506
6507             if Compile_Time_Known_Value (Lo) then
6508                Loval := Expr_Value (Lo);
6509
6510                if Lo_Bound = No_Uint or else Lo_Bound < Loval then
6511                   Lo_Bound := Loval;
6512                end if;
6513             end if;
6514
6515             if Compile_Time_Known_Value (Hi) then
6516                Hival := Expr_Value (Hi);
6517
6518                if Hi_Bound = No_Uint or else Hi_Bound > Hival then
6519                   Hi_Bound := Hival;
6520                end if;
6521             end if;
6522
6523             ST2 := Ancestor_Subtype (ST1);
6524
6525             if No (ST2) then
6526                ST2 := Etype (ST1);
6527             end if;
6528
6529             exit when ST1 = ST2;
6530             ST1 := ST2;
6531          end loop;
6532       end Check_Subtype_Bounds;
6533
6534    --  Start of processing for Get_Simple_Init_Val
6535
6536    begin
6537       --  For a private type, we should always have an underlying type
6538       --  (because this was already checked in Needs_Simple_Initialization).
6539       --  What we do is to get the value for the underlying type and then do
6540       --  an Unchecked_Convert to the private type.
6541
6542       if Is_Private_Type (T) then
6543          Val := Get_Simple_Init_Val (Underlying_Type (T), N, Size);
6544
6545          --  A special case, if the underlying value is null, then qualify it
6546          --  with the underlying type, so that the null is properly typed
6547          --  Similarly, if it is an aggregate it must be qualified, because an
6548          --  unchecked conversion does not provide a context for it.
6549
6550          if Nkind_In (Val, N_Null, N_Aggregate) then
6551             Val :=
6552               Make_Qualified_Expression (Loc,
6553                 Subtype_Mark =>
6554                   New_Occurrence_Of (Underlying_Type (T), Loc),
6555                 Expression => Val);
6556          end if;
6557
6558          Result := Unchecked_Convert_To (T, Val);
6559
6560          --  Don't truncate result (important for Initialize/Normalize_Scalars)
6561
6562          if Nkind (Result) = N_Unchecked_Type_Conversion
6563            and then Is_Scalar_Type (Underlying_Type (T))
6564          then
6565             Set_No_Truncation (Result);
6566          end if;
6567
6568          return Result;
6569
6570       --  For scalars, we must have normalize/initialize scalars case, or
6571       --  if the node N is an 'Invalid_Value attribute node.
6572
6573       elsif Is_Scalar_Type (T) then
6574          pragma Assert (Init_Or_Norm_Scalars or IV_Attribute);
6575
6576          --  Compute size of object. If it is given by the caller, we can use
6577          --  it directly, otherwise we use Esize (T) as an estimate. As far as
6578          --  we know this covers all cases correctly.
6579
6580          if Size = No_Uint or else Size <= Uint_0 then
6581             Size_To_Use := UI_Max (Uint_1, Esize (T));
6582          else
6583             Size_To_Use := Size;
6584          end if;
6585
6586          --  Maximum size to use is 64 bits, since we will create values
6587          --  of type Unsigned_64 and the range must fit this type.
6588
6589          if Size_To_Use /= No_Uint and then Size_To_Use > Uint_64 then
6590             Size_To_Use := Uint_64;
6591          end if;
6592
6593          --  Check known bounds of subtype
6594
6595          Check_Subtype_Bounds;
6596
6597          --  Processing for Normalize_Scalars case
6598
6599          if Normalize_Scalars and then not IV_Attribute then
6600
6601             --  If zero is invalid, it is a convenient value to use that is
6602             --  for sure an appropriate invalid value in all situations.
6603
6604             if Lo_Bound /= No_Uint and then Lo_Bound > Uint_0 then
6605                Val := Make_Integer_Literal (Loc, 0);
6606
6607             --  Cases where all one bits is the appropriate invalid value
6608
6609             --  For modular types, all 1 bits is either invalid or valid. If
6610             --  it is valid, then there is nothing that can be done since there
6611             --  are no invalid values (we ruled out zero already).
6612
6613             --  For signed integer types that have no negative values, either
6614             --  there is room for negative values, or there is not. If there
6615             --  is, then all 1 bits may be interpreted as minus one, which is
6616             --  certainly invalid. Alternatively it is treated as the largest
6617             --  positive value, in which case the observation for modular types
6618             --  still applies.
6619
6620             --  For float types, all 1-bits is a NaN (not a number), which is
6621             --  certainly an appropriately invalid value.
6622
6623             elsif Is_Unsigned_Type (T)
6624               or else Is_Floating_Point_Type (T)
6625               or else Is_Enumeration_Type (T)
6626             then
6627                Val := Make_Integer_Literal (Loc, 2 ** Size_To_Use - 1);
6628
6629                --  Resolve as Unsigned_64, because the largest number we
6630                --  can generate is out of range of universal integer.
6631
6632                Analyze_And_Resolve (Val, RTE (RE_Unsigned_64));
6633
6634             --  Case of signed types
6635
6636             else
6637                declare
6638                   Signed_Size : constant Uint :=
6639                                   UI_Min (Uint_63, Size_To_Use - 1);
6640
6641                begin
6642                   --  Normally we like to use the most negative number. The
6643                   --  one exception is when this number is in the known
6644                   --  subtype range and the largest positive number is not in
6645                   --  the known subtype range.
6646
6647                   --  For this exceptional case, use largest positive value
6648
6649                   if Lo_Bound /= No_Uint and then Hi_Bound /= No_Uint
6650                     and then Lo_Bound <= (-(2 ** Signed_Size))
6651                     and then Hi_Bound < 2 ** Signed_Size
6652                   then
6653                      Val := Make_Integer_Literal (Loc, 2 ** Signed_Size - 1);
6654
6655                      --  Normal case of largest negative value
6656
6657                   else
6658                      Val := Make_Integer_Literal (Loc, -(2 ** Signed_Size));
6659                   end if;
6660                end;
6661             end if;
6662
6663          --  Here for Initialize_Scalars case (or Invalid_Value attribute used)
6664
6665          else
6666             --  For float types, use float values from System.Scalar_Values
6667
6668             if Is_Floating_Point_Type (T) then
6669                if Root_Type (T) = Standard_Short_Float then
6670                   Val_RE := RE_IS_Isf;
6671                elsif Root_Type (T) = Standard_Float then
6672                   Val_RE := RE_IS_Ifl;
6673                elsif Root_Type (T) = Standard_Long_Float then
6674                   Val_RE := RE_IS_Ilf;
6675                else pragma Assert (Root_Type (T) = Standard_Long_Long_Float);
6676                   Val_RE := RE_IS_Ill;
6677                end if;
6678
6679             --  If zero is invalid, use zero values from System.Scalar_Values
6680
6681             elsif Lo_Bound /= No_Uint and then Lo_Bound > Uint_0 then
6682                if Size_To_Use <= 8 then
6683                   Val_RE := RE_IS_Iz1;
6684                elsif Size_To_Use <= 16 then
6685                   Val_RE := RE_IS_Iz2;
6686                elsif Size_To_Use <= 32 then
6687                   Val_RE := RE_IS_Iz4;
6688                else
6689                   Val_RE := RE_IS_Iz8;
6690                end if;
6691
6692             --  For unsigned, use unsigned values from System.Scalar_Values
6693
6694             elsif Is_Unsigned_Type (T) then
6695                if Size_To_Use <= 8 then
6696                   Val_RE := RE_IS_Iu1;
6697                elsif Size_To_Use <= 16 then
6698                   Val_RE := RE_IS_Iu2;
6699                elsif Size_To_Use <= 32 then
6700                   Val_RE := RE_IS_Iu4;
6701                else
6702                   Val_RE := RE_IS_Iu8;
6703                end if;
6704
6705             --  For signed, use signed values from System.Scalar_Values
6706
6707             else
6708                if Size_To_Use <= 8 then
6709                   Val_RE := RE_IS_Is1;
6710                elsif Size_To_Use <= 16 then
6711                   Val_RE := RE_IS_Is2;
6712                elsif Size_To_Use <= 32 then
6713                   Val_RE := RE_IS_Is4;
6714                else
6715                   Val_RE := RE_IS_Is8;
6716                end if;
6717             end if;
6718
6719             Val := New_Occurrence_Of (RTE (Val_RE), Loc);
6720          end if;
6721
6722          --  The final expression is obtained by doing an unchecked conversion
6723          --  of this result to the base type of the required subtype. We use
6724          --  the base type to avoid the unchecked conversion from chopping
6725          --  bits, and then we set Kill_Range_Check to preserve the "bad"
6726          --  value.
6727
6728          Result := Unchecked_Convert_To (Base_Type (T), Val);
6729
6730          --  Ensure result is not truncated, since we want the "bad" bits
6731          --  and also kill range check on result.
6732
6733          if Nkind (Result) = N_Unchecked_Type_Conversion then
6734             Set_No_Truncation (Result);
6735             Set_Kill_Range_Check (Result, True);
6736          end if;
6737
6738          return Result;
6739
6740       --  String or Wide_[Wide]_String (must have Initialize_Scalars set)
6741
6742       elsif Root_Type (T) = Standard_String
6743               or else
6744             Root_Type (T) = Standard_Wide_String
6745               or else
6746             Root_Type (T) = Standard_Wide_Wide_String
6747       then
6748          pragma Assert (Init_Or_Norm_Scalars);
6749
6750          return
6751            Make_Aggregate (Loc,
6752              Component_Associations => New_List (
6753                Make_Component_Association (Loc,
6754                  Choices => New_List (
6755                    Make_Others_Choice (Loc)),
6756                  Expression =>
6757                    Get_Simple_Init_Val
6758                      (Component_Type (T), N, Esize (Root_Type (T))))));
6759
6760       --  Access type is initialized to null
6761
6762       elsif Is_Access_Type (T) then
6763          return
6764            Make_Null (Loc);
6765
6766       --  No other possibilities should arise, since we should only be
6767       --  calling Get_Simple_Init_Val if Needs_Simple_Initialization
6768       --  returned True, indicating one of the above cases held.
6769
6770       else
6771          raise Program_Error;
6772       end if;
6773
6774    exception
6775       when RE_Not_Available =>
6776          return Empty;
6777    end Get_Simple_Init_Val;
6778
6779    ------------------------------
6780    -- Has_New_Non_Standard_Rep --
6781    ------------------------------
6782
6783    function Has_New_Non_Standard_Rep (T : Entity_Id) return Boolean is
6784    begin
6785       if not Is_Derived_Type (T) then
6786          return Has_Non_Standard_Rep (T)
6787            or else Has_Non_Standard_Rep (Root_Type (T));
6788
6789       --  If Has_Non_Standard_Rep is not set on the derived type, the
6790       --  representation is fully inherited.
6791
6792       elsif not Has_Non_Standard_Rep (T) then
6793          return False;
6794
6795       else
6796          return First_Rep_Item (T) /= First_Rep_Item (Root_Type (T));
6797
6798          --  May need a more precise check here: the First_Rep_Item may
6799          --  be a stream attribute, which does not affect the representation
6800          --  of the type ???
6801       end if;
6802    end Has_New_Non_Standard_Rep;
6803
6804    ----------------
6805    -- In_Runtime --
6806    ----------------
6807
6808    function In_Runtime (E : Entity_Id) return Boolean is
6809       S1 : Entity_Id;
6810
6811    begin
6812       S1 := Scope (E);
6813       while Scope (S1) /= Standard_Standard loop
6814          S1 := Scope (S1);
6815       end loop;
6816
6817       return Chars (S1) = Name_System or else Chars (S1) = Name_Ada;
6818    end In_Runtime;
6819
6820    ----------------------------
6821    -- Initialization_Warning --
6822    ----------------------------
6823
6824    procedure Initialization_Warning (E : Entity_Id) is
6825       Warning_Needed : Boolean;
6826
6827    begin
6828       Warning_Needed := False;
6829
6830       if Ekind (Current_Scope) = E_Package
6831         and then Static_Elaboration_Desired (Current_Scope)
6832       then
6833          if Is_Type (E) then
6834             if Is_Record_Type (E) then
6835                if Has_Discriminants (E)
6836                  or else Is_Limited_Type (E)
6837                  or else Has_Non_Standard_Rep (E)
6838                then
6839                   Warning_Needed := True;
6840
6841                else
6842                   --  Verify that at least one component has an initialization
6843                   --  expression. No need for a warning on a type if all its
6844                   --  components have no initialization.
6845
6846                   declare
6847                      Comp : Entity_Id;
6848
6849                   begin
6850                      Comp := First_Component (E);
6851                      while Present (Comp) loop
6852                         if Ekind (Comp) = E_Discriminant
6853                           or else
6854                             (Nkind (Parent (Comp)) = N_Component_Declaration
6855                                and then Present (Expression (Parent (Comp))))
6856                         then
6857                            Warning_Needed := True;
6858                            exit;
6859                         end if;
6860
6861                         Next_Component (Comp);
6862                      end loop;
6863                   end;
6864                end if;
6865
6866                if Warning_Needed then
6867                   Error_Msg_N
6868                     ("Objects of the type cannot be initialized " &
6869                        "statically by default?",
6870                        Parent (E));
6871                end if;
6872             end if;
6873
6874          else
6875             Error_Msg_N ("Object cannot be initialized statically?", E);
6876          end if;
6877       end if;
6878    end Initialization_Warning;
6879
6880    ------------------
6881    -- Init_Formals --
6882    ------------------
6883
6884    function Init_Formals (Typ : Entity_Id) return List_Id is
6885       Loc     : constant Source_Ptr := Sloc (Typ);
6886       Formals : List_Id;
6887
6888    begin
6889       --  First parameter is always _Init : in out typ. Note that we need
6890       --  this to be in/out because in the case of the task record value,
6891       --  there are default record fields (_Priority, _Size, -Task_Info)
6892       --  that may be referenced in the generated initialization routine.
6893
6894       Formals := New_List (
6895         Make_Parameter_Specification (Loc,
6896           Defining_Identifier =>
6897             Make_Defining_Identifier (Loc, Name_uInit),
6898           In_Present  => True,
6899           Out_Present => True,
6900           Parameter_Type => New_Reference_To (Typ, Loc)));
6901
6902       --  For task record value, or type that contains tasks, add two more
6903       --  formals, _Master : Master_Id and _Chain : in out Activation_Chain
6904       --  We also add these parameters for the task record type case.
6905
6906       if Has_Task (Typ)
6907         or else (Is_Record_Type (Typ) and then Is_Task_Record_Type (Typ))
6908       then
6909          Append_To (Formals,
6910            Make_Parameter_Specification (Loc,
6911              Defining_Identifier =>
6912                Make_Defining_Identifier (Loc, Name_uMaster),
6913              Parameter_Type => New_Reference_To (RTE (RE_Master_Id), Loc)));
6914
6915          Append_To (Formals,
6916            Make_Parameter_Specification (Loc,
6917              Defining_Identifier =>
6918                Make_Defining_Identifier (Loc, Name_uChain),
6919              In_Present => True,
6920              Out_Present => True,
6921              Parameter_Type =>
6922                New_Reference_To (RTE (RE_Activation_Chain), Loc)));
6923
6924          Append_To (Formals,
6925            Make_Parameter_Specification (Loc,
6926              Defining_Identifier =>
6927                Make_Defining_Identifier (Loc, Name_uTask_Name),
6928              In_Present => True,
6929              Parameter_Type =>
6930                New_Reference_To (Standard_String, Loc)));
6931       end if;
6932
6933       return Formals;
6934
6935    exception
6936       when RE_Not_Available =>
6937          return Empty_List;
6938    end Init_Formals;
6939
6940    -------------------------
6941    -- Init_Secondary_Tags --
6942    -------------------------
6943
6944    procedure Init_Secondary_Tags
6945      (Typ            : Entity_Id;
6946       Target         : Node_Id;
6947       Stmts_List     : List_Id;
6948       Fixed_Comps    : Boolean := True;
6949       Variable_Comps : Boolean := True)
6950    is
6951       Loc : constant Source_Ptr := Sloc (Target);
6952
6953       procedure Inherit_CPP_Tag
6954         (Typ       : Entity_Id;
6955          Iface     : Entity_Id;
6956          Tag_Comp  : Entity_Id;
6957          Iface_Tag : Node_Id);
6958       --  Inherit the C++ tag of the secondary dispatch table of Typ associated
6959       --  with Iface. Tag_Comp is the component of Typ that stores Iface_Tag.
6960
6961       procedure Initialize_Tag
6962         (Typ       : Entity_Id;
6963          Iface     : Entity_Id;
6964          Tag_Comp  : Entity_Id;
6965          Iface_Tag : Node_Id);
6966       --  Initialize the tag of the secondary dispatch table of Typ associated
6967       --  with Iface. Tag_Comp is the component of Typ that stores Iface_Tag.
6968       --  Compiling under the CPP full ABI compatibility mode, if the ancestor
6969       --  of Typ CPP tagged type we generate code to inherit the contents of
6970       --  the dispatch table directly from the ancestor.
6971
6972       ---------------------
6973       -- Inherit_CPP_Tag --
6974       ---------------------
6975
6976       procedure Inherit_CPP_Tag
6977         (Typ       : Entity_Id;
6978          Iface     : Entity_Id;
6979          Tag_Comp  : Entity_Id;
6980          Iface_Tag : Node_Id)
6981       is
6982       begin
6983          pragma Assert (Is_CPP_Class (Etype (Typ)));
6984
6985          Append_To (Stmts_List,
6986            Build_Inherit_Prims (Loc,
6987              Typ          => Iface,
6988              Old_Tag_Node =>
6989                Make_Selected_Component (Loc,
6990                  Prefix        => New_Copy_Tree (Target),
6991                  Selector_Name => New_Reference_To (Tag_Comp, Loc)),
6992              New_Tag_Node =>
6993                New_Reference_To (Iface_Tag, Loc),
6994              Num_Prims    =>
6995                UI_To_Int (DT_Entry_Count (First_Tag_Component (Iface)))));
6996       end Inherit_CPP_Tag;
6997
6998       --------------------
6999       -- Initialize_Tag --
7000       --------------------
7001
7002       procedure Initialize_Tag
7003         (Typ       : Entity_Id;
7004          Iface     : Entity_Id;
7005          Tag_Comp  : Entity_Id;
7006          Iface_Tag : Node_Id)
7007       is
7008          Comp_Typ           : Entity_Id;
7009          Offset_To_Top_Comp : Entity_Id := Empty;
7010
7011       begin
7012          --  Initialize the pointer to the secondary DT associated with the
7013          --  interface.
7014
7015          if not Is_Ancestor (Iface, Typ) then
7016             Append_To (Stmts_List,
7017               Make_Assignment_Statement (Loc,
7018                 Name =>
7019                   Make_Selected_Component (Loc,
7020                     Prefix => New_Copy_Tree (Target),
7021                     Selector_Name => New_Reference_To (Tag_Comp, Loc)),
7022                 Expression =>
7023                   New_Reference_To (Iface_Tag, Loc)));
7024          end if;
7025
7026          Comp_Typ := Scope (Tag_Comp);
7027
7028          --  Initialize the entries of the table of interfaces. We generate a
7029          --  different call when the parent of the type has variable size
7030          --  components.
7031
7032          if Comp_Typ /= Etype (Comp_Typ)
7033            and then Is_Variable_Size_Record (Etype (Comp_Typ))
7034            and then Chars (Tag_Comp) /= Name_uTag
7035          then
7036             pragma Assert (Present (DT_Offset_To_Top_Func (Tag_Comp)));
7037
7038             --  Issue error if Set_Dynamic_Offset_To_Top is not available in a
7039             --  configurable run-time environment.
7040
7041             if not RTE_Available (RE_Set_Dynamic_Offset_To_Top) then
7042                Error_Msg_CRT
7043                  ("variable size record with interface types", Typ);
7044                return;
7045             end if;
7046
7047             --  Generate:
7048             --    Set_Dynamic_Offset_To_Top
7049             --      (This         => Init,
7050             --       Interface_T  => Iface'Tag,
7051             --       Offset_Value => n,
7052             --       Offset_Func  => Fn'Address)
7053
7054             Append_To (Stmts_List,
7055               Make_Procedure_Call_Statement (Loc,
7056                 Name => New_Reference_To
7057                           (RTE (RE_Set_Dynamic_Offset_To_Top), Loc),
7058                 Parameter_Associations => New_List (
7059                   Make_Attribute_Reference (Loc,
7060                     Prefix => New_Copy_Tree (Target),
7061                     Attribute_Name => Name_Address),
7062
7063                   Unchecked_Convert_To (RTE (RE_Tag),
7064                     New_Reference_To
7065                       (Node (First_Elmt (Access_Disp_Table (Iface))),
7066                        Loc)),
7067
7068                   Unchecked_Convert_To
7069                     (RTE (RE_Storage_Offset),
7070                      Make_Attribute_Reference (Loc,
7071                        Prefix         =>
7072                          Make_Selected_Component (Loc,
7073                            Prefix => New_Copy_Tree (Target),
7074                            Selector_Name =>
7075                              New_Reference_To (Tag_Comp, Loc)),
7076                        Attribute_Name => Name_Position)),
7077
7078                   Unchecked_Convert_To (RTE (RE_Offset_To_Top_Function_Ptr),
7079                     Make_Attribute_Reference (Loc,
7080                       Prefix => New_Reference_To
7081                                   (DT_Offset_To_Top_Func (Tag_Comp), Loc),
7082                       Attribute_Name => Name_Address)))));
7083
7084             --  In this case the next component stores the value of the
7085             --  offset to the top.
7086
7087             Offset_To_Top_Comp := Next_Entity (Tag_Comp);
7088             pragma Assert (Present (Offset_To_Top_Comp));
7089
7090             Append_To (Stmts_List,
7091               Make_Assignment_Statement (Loc,
7092                 Name =>
7093                   Make_Selected_Component (Loc,
7094                     Prefix => New_Copy_Tree (Target),
7095                     Selector_Name => New_Reference_To
7096                                        (Offset_To_Top_Comp, Loc)),
7097                 Expression =>
7098                   Make_Attribute_Reference (Loc,
7099                     Prefix         =>
7100                       Make_Selected_Component (Loc,
7101                         Prefix => New_Copy_Tree (Target),
7102                         Selector_Name =>
7103                           New_Reference_To (Tag_Comp, Loc)),
7104                   Attribute_Name => Name_Position)));
7105
7106          --  Normal case: No discriminants in the parent type
7107
7108          else
7109             --  Don't need to set any value if this interface shares
7110             --  the primary dispatch table.
7111
7112             if not Is_Ancestor (Iface, Typ) then
7113                Append_To (Stmts_List,
7114                  Build_Set_Static_Offset_To_Top (Loc,
7115                    Iface_Tag    => New_Reference_To (Iface_Tag, Loc),
7116                    Offset_Value =>
7117                      Unchecked_Convert_To (RTE (RE_Storage_Offset),
7118                        Make_Attribute_Reference (Loc,
7119                          Prefix =>
7120                            Make_Selected_Component (Loc,
7121                              Prefix        => New_Copy_Tree (Target),
7122                              Selector_Name =>
7123                                New_Reference_To (Tag_Comp, Loc)),
7124                          Attribute_Name => Name_Position))));
7125             end if;
7126
7127             --  Generate:
7128             --    Register_Interface_Offset
7129             --      (This         => Init,
7130             --       Interface_T  => Iface'Tag,
7131             --       Is_Constant  => True,
7132             --       Offset_Value => n,
7133             --       Offset_Func  => null);
7134
7135             if RTE_Available (RE_Register_Interface_Offset) then
7136                Append_To (Stmts_List,
7137                  Make_Procedure_Call_Statement (Loc,
7138                    Name => New_Reference_To
7139                              (RTE (RE_Register_Interface_Offset), Loc),
7140                    Parameter_Associations => New_List (
7141                      Make_Attribute_Reference (Loc,
7142                        Prefix         => New_Copy_Tree (Target),
7143                        Attribute_Name => Name_Address),
7144
7145                      Unchecked_Convert_To (RTE (RE_Tag),
7146                        New_Reference_To
7147                          (Node (First_Elmt (Access_Disp_Table (Iface))), Loc)),
7148
7149                      New_Occurrence_Of (Standard_True, Loc),
7150
7151                      Unchecked_Convert_To
7152                        (RTE (RE_Storage_Offset),
7153                         Make_Attribute_Reference (Loc,
7154                           Prefix =>
7155                             Make_Selected_Component (Loc,
7156                               Prefix         => New_Copy_Tree (Target),
7157                               Selector_Name  =>
7158                                 New_Reference_To (Tag_Comp, Loc)),
7159                          Attribute_Name => Name_Position)),
7160
7161                      Make_Null (Loc))));
7162             end if;
7163          end if;
7164       end Initialize_Tag;
7165
7166       --  Local variables
7167
7168       Full_Typ         : Entity_Id;
7169       Ifaces_List      : Elist_Id;
7170       Ifaces_Comp_List : Elist_Id;
7171       Ifaces_Tag_List  : Elist_Id;
7172       Iface_Elmt       : Elmt_Id;
7173       Iface_Comp_Elmt  : Elmt_Id;
7174       Iface_Tag_Elmt   : Elmt_Id;
7175       Tag_Comp         : Node_Id;
7176       In_Variable_Pos  : Boolean;
7177
7178    --  Start of processing for Init_Secondary_Tags
7179
7180    begin
7181       --  Handle private types
7182
7183       if Present (Full_View (Typ)) then
7184          Full_Typ := Full_View (Typ);
7185       else
7186          Full_Typ := Typ;
7187       end if;
7188
7189       Collect_Interfaces_Info
7190         (Full_Typ, Ifaces_List, Ifaces_Comp_List, Ifaces_Tag_List);
7191
7192       Iface_Elmt      := First_Elmt (Ifaces_List);
7193       Iface_Comp_Elmt := First_Elmt (Ifaces_Comp_List);
7194       Iface_Tag_Elmt  := First_Elmt (Ifaces_Tag_List);
7195       while Present (Iface_Elmt) loop
7196          Tag_Comp := Node (Iface_Comp_Elmt);
7197
7198          --  If we are compiling under the CPP full ABI compatibility mode and
7199          --  the ancestor is a CPP_Pragma tagged type then we generate code to
7200          --  inherit the contents of the dispatch table directly from the
7201          --  ancestor.
7202
7203          if Is_CPP_Class (Etype (Full_Typ)) then
7204             Inherit_CPP_Tag (Full_Typ,
7205               Iface     => Node (Iface_Elmt),
7206               Tag_Comp  => Tag_Comp,
7207               Iface_Tag => Node (Iface_Tag_Elmt));
7208
7209          --  Otherwise generate code to initialize the tag
7210
7211          else
7212             --  Check if the parent of the record type has variable size
7213             --  components.
7214
7215             In_Variable_Pos := Scope (Tag_Comp) /= Etype (Scope (Tag_Comp))
7216               and then Is_Variable_Size_Record (Etype (Scope (Tag_Comp)));
7217
7218             if (In_Variable_Pos and then Variable_Comps)
7219               or else (not In_Variable_Pos and then Fixed_Comps)
7220             then
7221                Initialize_Tag (Full_Typ,
7222                  Iface     => Node (Iface_Elmt),
7223                  Tag_Comp  => Tag_Comp,
7224                  Iface_Tag => Node (Iface_Tag_Elmt));
7225             end if;
7226          end if;
7227
7228          Next_Elmt (Iface_Elmt);
7229          Next_Elmt (Iface_Comp_Elmt);
7230          Next_Elmt (Iface_Tag_Elmt);
7231       end loop;
7232    end Init_Secondary_Tags;
7233
7234    -----------------------------
7235    -- Is_Variable_Size_Record --
7236    -----------------------------
7237
7238    function Is_Variable_Size_Record (E : Entity_Id) return Boolean is
7239       Comp     : Entity_Id;
7240       Comp_Typ : Entity_Id;
7241       Idx      : Node_Id;
7242
7243       function Is_Constant_Bound (Exp : Node_Id) return Boolean;
7244       --  To simplify handling of array components. Determines whether the
7245       --  given bound is constant (a constant or enumeration literal, or an
7246       --  integer literal) as opposed to per-object, through an expression
7247       --  or a discriminant.
7248
7249       -----------------------
7250       -- Is_Constant_Bound --
7251       -----------------------
7252
7253       function Is_Constant_Bound (Exp : Node_Id) return Boolean is
7254       begin
7255          if Nkind (Exp) = N_Integer_Literal then
7256             return True;
7257          else
7258             return
7259               Is_Entity_Name (Exp)
7260                 and then Present (Entity (Exp))
7261                 and then
7262                  (Ekind (Entity (Exp)) = E_Constant
7263                    or else Ekind (Entity (Exp)) = E_Enumeration_Literal);
7264          end if;
7265       end Is_Constant_Bound;
7266
7267    --  Start of processing for Is_Variable_Sized_Record
7268
7269    begin
7270       pragma Assert (Is_Record_Type (E));
7271
7272       Comp := First_Entity (E);
7273       while Present (Comp) loop
7274          Comp_Typ := Etype (Comp);
7275
7276          if Is_Record_Type (Comp_Typ) then
7277
7278             --  Recursive call if the record type has discriminants
7279
7280             if Has_Discriminants (Comp_Typ)
7281               and then Is_Variable_Size_Record (Comp_Typ)
7282             then
7283                return True;
7284             end if;
7285
7286          elsif Is_Array_Type (Comp_Typ) then
7287
7288             --  Check if some index is initialized with a non-constant value
7289
7290             Idx := First_Index (Comp_Typ);
7291             while Present (Idx) loop
7292                if Nkind (Idx) = N_Range then
7293                   if not Is_Constant_Bound (Low_Bound  (Idx))
7294                        or else
7295                      not Is_Constant_Bound (High_Bound (Idx))
7296                   then
7297                      return True;
7298                   end if;
7299                end if;
7300
7301                Idx := Next_Index (Idx);
7302             end loop;
7303          end if;
7304
7305          Next_Entity (Comp);
7306       end loop;
7307
7308       return False;
7309    end Is_Variable_Size_Record;
7310
7311    ----------------------------------------
7312    -- Make_Controlling_Function_Wrappers --
7313    ----------------------------------------
7314
7315    procedure Make_Controlling_Function_Wrappers
7316      (Tag_Typ   : Entity_Id;
7317       Decl_List : out List_Id;
7318       Body_List : out List_Id)
7319    is
7320       Loc         : constant Source_Ptr := Sloc (Tag_Typ);
7321       Prim_Elmt   : Elmt_Id;
7322       Subp        : Entity_Id;
7323       Actual_List : List_Id;
7324       Formal_List : List_Id;
7325       Formal      : Entity_Id;
7326       Par_Formal  : Entity_Id;
7327       Formal_Node : Node_Id;
7328       Func_Body   : Node_Id;
7329       Func_Decl   : Node_Id;
7330       Func_Spec   : Node_Id;
7331       Return_Stmt : Node_Id;
7332
7333    begin
7334       Decl_List := New_List;
7335       Body_List := New_List;
7336
7337       Prim_Elmt := First_Elmt (Primitive_Operations (Tag_Typ));
7338
7339       while Present (Prim_Elmt) loop
7340          Subp := Node (Prim_Elmt);
7341
7342          --  If a primitive function with a controlling result of the type has
7343          --  not been overridden by the user, then we must create a wrapper
7344          --  function here that effectively overrides it and invokes the
7345          --  (non-abstract) parent function. This can only occur for a null
7346          --  extension. Note that functions with anonymous controlling access
7347          --  results don't qualify and must be overridden. We also exclude
7348          --  Input attributes, since each type will have its own version of
7349          --  Input constructed by the expander. The test for Comes_From_Source
7350          --  is needed to distinguish inherited operations from renamings
7351          --  (which also have Alias set).
7352
7353          --  The function may be abstract, or require_Overriding may be set
7354          --  for it, because tests for null extensions may already have reset
7355          --  the Is_Abstract_Subprogram_Flag. If Requires_Overriding is not
7356          --  set, functions that need wrappers are recognized by having an
7357          --  alias that returns the parent type.
7358
7359          if Comes_From_Source (Subp)
7360            or else No (Alias (Subp))
7361            or else Ekind (Subp) /= E_Function
7362            or else not Has_Controlling_Result (Subp)
7363            or else Is_Access_Type (Etype (Subp))
7364            or else Is_Abstract_Subprogram (Alias (Subp))
7365            or else Is_TSS (Subp, TSS_Stream_Input)
7366          then
7367             goto Next_Prim;
7368
7369          elsif Is_Abstract_Subprogram (Subp)
7370            or else Requires_Overriding (Subp)
7371            or else
7372              (Is_Null_Extension (Etype (Subp))
7373                and then Etype (Alias (Subp)) /= Etype (Subp))
7374          then
7375             Formal_List := No_List;
7376             Formal := First_Formal (Subp);
7377
7378             if Present (Formal) then
7379                Formal_List := New_List;
7380
7381                while Present (Formal) loop
7382                   Append
7383                     (Make_Parameter_Specification
7384                        (Loc,
7385                         Defining_Identifier =>
7386                           Make_Defining_Identifier (Sloc (Formal),
7387                             Chars => Chars (Formal)),
7388                         In_Present  => In_Present (Parent (Formal)),
7389                         Out_Present => Out_Present (Parent (Formal)),
7390                         Null_Exclusion_Present =>
7391                           Null_Exclusion_Present (Parent (Formal)),
7392                         Parameter_Type =>
7393                           New_Reference_To (Etype (Formal), Loc),
7394                         Expression =>
7395                           New_Copy_Tree (Expression (Parent (Formal)))),
7396                      Formal_List);
7397
7398                   Next_Formal (Formal);
7399                end loop;
7400             end if;
7401
7402             Func_Spec :=
7403               Make_Function_Specification (Loc,
7404                 Defining_Unit_Name       =>
7405                   Make_Defining_Identifier (Loc,
7406                     Chars => Chars (Subp)),
7407                 Parameter_Specifications => Formal_List,
7408                 Result_Definition        =>
7409                   New_Reference_To (Etype (Subp), Loc));
7410
7411             Func_Decl := Make_Subprogram_Declaration (Loc, Func_Spec);
7412             Append_To (Decl_List, Func_Decl);
7413
7414             --  Build a wrapper body that calls the parent function. The body
7415             --  contains a single return statement that returns an extension
7416             --  aggregate whose ancestor part is a call to the parent function,
7417             --  passing the formals as actuals (with any controlling arguments
7418             --  converted to the types of the corresponding formals of the
7419             --  parent function, which might be anonymous access types), and
7420             --  having a null extension.
7421
7422             Formal      := First_Formal (Subp);
7423             Par_Formal  := First_Formal (Alias (Subp));
7424             Formal_Node := First (Formal_List);
7425
7426             if Present (Formal) then
7427                Actual_List := New_List;
7428             else
7429                Actual_List := No_List;
7430             end if;
7431
7432             while Present (Formal) loop
7433                if Is_Controlling_Formal (Formal) then
7434                   Append_To (Actual_List,
7435                     Make_Type_Conversion (Loc,
7436                       Subtype_Mark =>
7437                         New_Occurrence_Of (Etype (Par_Formal), Loc),
7438                       Expression   =>
7439                         New_Reference_To
7440                           (Defining_Identifier (Formal_Node), Loc)));
7441                else
7442                   Append_To
7443                     (Actual_List,
7444                      New_Reference_To
7445                        (Defining_Identifier (Formal_Node), Loc));
7446                end if;
7447
7448                Next_Formal (Formal);
7449                Next_Formal (Par_Formal);
7450                Next (Formal_Node);
7451             end loop;
7452
7453             Return_Stmt :=
7454               Make_Simple_Return_Statement (Loc,
7455                 Expression =>
7456                   Make_Extension_Aggregate (Loc,
7457                     Ancestor_Part =>
7458                       Make_Function_Call (Loc,
7459                         Name => New_Reference_To (Alias (Subp), Loc),
7460                         Parameter_Associations => Actual_List),
7461                     Null_Record_Present => True));
7462
7463             Func_Body :=
7464               Make_Subprogram_Body (Loc,
7465                 Specification => New_Copy_Tree (Func_Spec),
7466                 Declarations => Empty_List,
7467                 Handled_Statement_Sequence =>
7468                   Make_Handled_Sequence_Of_Statements (Loc,
7469                     Statements => New_List (Return_Stmt)));
7470
7471             Set_Defining_Unit_Name
7472               (Specification (Func_Body),
7473                 Make_Defining_Identifier (Loc, Chars (Subp)));
7474
7475             Append_To (Body_List, Func_Body);
7476
7477             --  Replace the inherited function with the wrapper function
7478             --  in the primitive operations list.
7479
7480             Override_Dispatching_Operation
7481               (Tag_Typ, Subp, New_Op => Defining_Unit_Name (Func_Spec));
7482          end if;
7483
7484       <<Next_Prim>>
7485          Next_Elmt (Prim_Elmt);
7486       end loop;
7487    end Make_Controlling_Function_Wrappers;
7488
7489    ------------------
7490    -- Make_Eq_Case --
7491    ------------------
7492
7493    --  <Make_Eq_If shared components>
7494    --  case X.D1 is
7495    --     when V1 => <Make_Eq_Case> on subcomponents
7496    --     ...
7497    --     when Vn => <Make_Eq_Case> on subcomponents
7498    --  end case;
7499
7500    function Make_Eq_Case
7501      (E     : Entity_Id;
7502       CL    : Node_Id;
7503       Discr : Entity_Id := Empty) return List_Id
7504    is
7505       Loc      : constant Source_Ptr := Sloc (E);
7506       Result   : constant List_Id    := New_List;
7507       Variant  : Node_Id;
7508       Alt_List : List_Id;
7509
7510    begin
7511       Append_To (Result, Make_Eq_If (E, Component_Items (CL)));
7512
7513       if No (Variant_Part (CL)) then
7514          return Result;
7515       end if;
7516
7517       Variant := First_Non_Pragma (Variants (Variant_Part (CL)));
7518
7519       if No (Variant) then
7520          return Result;
7521       end if;
7522
7523       Alt_List := New_List;
7524
7525       while Present (Variant) loop
7526          Append_To (Alt_List,
7527            Make_Case_Statement_Alternative (Loc,
7528              Discrete_Choices => New_Copy_List (Discrete_Choices (Variant)),
7529              Statements => Make_Eq_Case (E, Component_List (Variant))));
7530
7531          Next_Non_Pragma (Variant);
7532       end loop;
7533
7534       --  If we have an Unchecked_Union, use one of the parameters that
7535       --  captures the discriminants.
7536
7537       if Is_Unchecked_Union (E) then
7538          Append_To (Result,
7539            Make_Case_Statement (Loc,
7540              Expression => New_Reference_To (Discr, Loc),
7541              Alternatives => Alt_List));
7542
7543       else
7544          Append_To (Result,
7545            Make_Case_Statement (Loc,
7546              Expression =>
7547                Make_Selected_Component (Loc,
7548                  Prefix => Make_Identifier (Loc, Name_X),
7549                  Selector_Name => New_Copy (Name (Variant_Part (CL)))),
7550              Alternatives => Alt_List));
7551       end if;
7552
7553       return Result;
7554    end Make_Eq_Case;
7555
7556    ----------------
7557    -- Make_Eq_If --
7558    ----------------
7559
7560    --  Generates:
7561
7562    --    if
7563    --      X.C1 /= Y.C1
7564    --        or else
7565    --      X.C2 /= Y.C2
7566    --        ...
7567    --    then
7568    --       return False;
7569    --    end if;
7570
7571    --  or a null statement if the list L is empty
7572
7573    function Make_Eq_If
7574      (E : Entity_Id;
7575       L : List_Id) return Node_Id
7576    is
7577       Loc        : constant Source_Ptr := Sloc (E);
7578       C          : Node_Id;
7579       Field_Name : Name_Id;
7580       Cond       : Node_Id;
7581
7582    begin
7583       if No (L) then
7584          return Make_Null_Statement (Loc);
7585
7586       else
7587          Cond := Empty;
7588
7589          C := First_Non_Pragma (L);
7590          while Present (C) loop
7591             Field_Name := Chars (Defining_Identifier (C));
7592
7593             --  The tags must not be compared: they are not part of the value.
7594             --  Ditto for the controller component, if present.
7595
7596             --  Note also that in the following, we use Make_Identifier for
7597             --  the component names. Use of New_Reference_To to identify the
7598             --  components would be incorrect because the wrong entities for
7599             --  discriminants could be picked up in the private type case.
7600
7601             if Field_Name /= Name_uTag
7602                  and then
7603                Field_Name /= Name_uController
7604             then
7605                Evolve_Or_Else (Cond,
7606                  Make_Op_Ne (Loc,
7607                    Left_Opnd =>
7608                      Make_Selected_Component (Loc,
7609                        Prefix        => Make_Identifier (Loc, Name_X),
7610                        Selector_Name =>
7611                          Make_Identifier (Loc, Field_Name)),
7612
7613                    Right_Opnd =>
7614                      Make_Selected_Component (Loc,
7615                        Prefix        => Make_Identifier (Loc, Name_Y),
7616                        Selector_Name =>
7617                          Make_Identifier (Loc, Field_Name))));
7618             end if;
7619
7620             Next_Non_Pragma (C);
7621          end loop;
7622
7623          if No (Cond) then
7624             return Make_Null_Statement (Loc);
7625
7626          else
7627             return
7628               Make_Implicit_If_Statement (E,
7629                 Condition => Cond,
7630                 Then_Statements => New_List (
7631                   Make_Simple_Return_Statement (Loc,
7632                     Expression => New_Occurrence_Of (Standard_False, Loc))));
7633          end if;
7634       end if;
7635    end Make_Eq_If;
7636
7637    -------------------------------
7638    -- Make_Null_Procedure_Specs --
7639    -------------------------------
7640
7641    procedure Make_Null_Procedure_Specs
7642      (Tag_Typ   : Entity_Id;
7643       Decl_List : out List_Id)
7644    is
7645       Loc : constant Source_Ptr := Sloc (Tag_Typ);
7646
7647       Formal         : Entity_Id;
7648       Formal_List    : List_Id;
7649       New_Param_Spec : Node_Id;
7650       Parent_Subp    : Entity_Id;
7651       Prim_Elmt      : Elmt_Id;
7652       Proc_Decl      : Node_Id;
7653       Subp           : Entity_Id;
7654
7655       function Is_Null_Interface_Primitive (E : Entity_Id) return Boolean;
7656       --  Returns True if E is a null procedure that is an interface primitive
7657
7658       ---------------------------------
7659       -- Is_Null_Interface_Primitive --
7660       ---------------------------------
7661
7662       function Is_Null_Interface_Primitive (E : Entity_Id) return Boolean is
7663       begin
7664          return Comes_From_Source (E)
7665            and then Is_Dispatching_Operation (E)
7666            and then Ekind (E) = E_Procedure
7667            and then Null_Present (Parent (E))
7668            and then Is_Interface (Find_Dispatching_Type (E));
7669       end Is_Null_Interface_Primitive;
7670
7671    --  Start of processing for Make_Null_Procedure_Specs
7672
7673    begin
7674       Decl_List := New_List;
7675       Prim_Elmt := First_Elmt (Primitive_Operations (Tag_Typ));
7676       while Present (Prim_Elmt) loop
7677          Subp := Node (Prim_Elmt);
7678
7679          --  If a null procedure inherited from an interface has not been
7680          --  overridden, then we build a null procedure declaration to
7681          --  override the inherited procedure.
7682
7683          Parent_Subp := Alias (Subp);
7684
7685          if Present (Parent_Subp)
7686            and then Is_Null_Interface_Primitive (Parent_Subp)
7687          then
7688             Formal_List := No_List;
7689             Formal := First_Formal (Subp);
7690
7691             if Present (Formal) then
7692                Formal_List := New_List;
7693
7694                while Present (Formal) loop
7695
7696                   --  Copy the parameter spec including default expressions
7697
7698                   New_Param_Spec :=
7699                     New_Copy_Tree (Parent (Formal), New_Sloc => Loc);
7700
7701                   --  Generate a new defining identifier for the new formal.
7702                   --  required because New_Copy_Tree does not duplicate
7703                   --  semantic fields (except itypes).
7704
7705                   Set_Defining_Identifier (New_Param_Spec,
7706                     Make_Defining_Identifier (Sloc (Formal),
7707                       Chars => Chars (Formal)));
7708
7709                   --  For controlling arguments we must change their
7710                   --  parameter type to reference the tagged type (instead
7711                   --  of the interface type)
7712
7713                   if Is_Controlling_Formal (Formal) then
7714                      if Nkind (Parameter_Type (Parent (Formal)))
7715                        = N_Identifier
7716                      then
7717                         Set_Parameter_Type (New_Param_Spec,
7718                           New_Occurrence_Of (Tag_Typ, Loc));
7719
7720                      else pragma Assert
7721                             (Nkind (Parameter_Type (Parent (Formal)))
7722                                = N_Access_Definition);
7723                         Set_Subtype_Mark (Parameter_Type (New_Param_Spec),
7724                           New_Occurrence_Of (Tag_Typ, Loc));
7725                      end if;
7726                   end if;
7727
7728                   Append (New_Param_Spec, Formal_List);
7729
7730                   Next_Formal (Formal);
7731                end loop;
7732             end if;
7733
7734             Proc_Decl :=
7735               Make_Subprogram_Declaration (Loc,
7736                 Make_Procedure_Specification (Loc,
7737                   Defining_Unit_Name =>
7738                     Make_Defining_Identifier (Loc, Chars (Subp)),
7739                   Parameter_Specifications => Formal_List,
7740                   Null_Present => True));
7741             Append_To (Decl_List, Proc_Decl);
7742             Analyze (Proc_Decl);
7743          end if;
7744
7745          Next_Elmt (Prim_Elmt);
7746       end loop;
7747    end Make_Null_Procedure_Specs;
7748
7749    -------------------------------------
7750    -- Make_Predefined_Primitive_Specs --
7751    -------------------------------------
7752
7753    procedure Make_Predefined_Primitive_Specs
7754      (Tag_Typ     : Entity_Id;
7755       Predef_List : out List_Id;
7756       Renamed_Eq  : out Entity_Id)
7757    is
7758       Loc       : constant Source_Ptr := Sloc (Tag_Typ);
7759       Res       : constant List_Id    := New_List;
7760       Prim      : Elmt_Id;
7761       Eq_Needed : Boolean;
7762       Eq_Spec   : Node_Id;
7763       Eq_Name   : Name_Id := Name_Op_Eq;
7764
7765       function Is_Predefined_Eq_Renaming (Prim : Node_Id) return Boolean;
7766       --  Returns true if Prim is a renaming of an unresolved predefined
7767       --  equality operation.
7768
7769       -------------------------------
7770       -- Is_Predefined_Eq_Renaming --
7771       -------------------------------
7772
7773       function Is_Predefined_Eq_Renaming (Prim : Node_Id) return Boolean is
7774       begin
7775          return Chars (Prim) /= Name_Op_Eq
7776            and then Present (Alias (Prim))
7777            and then Comes_From_Source (Prim)
7778            and then Is_Intrinsic_Subprogram (Alias (Prim))
7779            and then Chars (Alias (Prim)) = Name_Op_Eq;
7780       end Is_Predefined_Eq_Renaming;
7781
7782    --  Start of processing for Make_Predefined_Primitive_Specs
7783
7784    begin
7785       Renamed_Eq := Empty;
7786
7787       --  Spec of _Size
7788
7789       Append_To (Res, Predef_Spec_Or_Body (Loc,
7790         Tag_Typ => Tag_Typ,
7791         Name    => Name_uSize,
7792         Profile => New_List (
7793           Make_Parameter_Specification (Loc,
7794             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
7795             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
7796
7797         Ret_Type => Standard_Long_Long_Integer));
7798
7799       --  Spec of _Alignment
7800
7801       Append_To (Res, Predef_Spec_Or_Body (Loc,
7802         Tag_Typ => Tag_Typ,
7803         Name    => Name_uAlignment,
7804         Profile => New_List (
7805           Make_Parameter_Specification (Loc,
7806             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
7807             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
7808
7809         Ret_Type => Standard_Integer));
7810
7811       --  Specs for dispatching stream attributes
7812
7813       declare
7814          Stream_Op_TSS_Names :
7815            constant array (Integer range <>) of TSS_Name_Type :=
7816              (TSS_Stream_Read,
7817               TSS_Stream_Write,
7818               TSS_Stream_Input,
7819               TSS_Stream_Output);
7820
7821       begin
7822          for Op in Stream_Op_TSS_Names'Range loop
7823             if Stream_Operation_OK (Tag_Typ, Stream_Op_TSS_Names (Op)) then
7824                Append_To (Res,
7825                  Predef_Stream_Attr_Spec (Loc, Tag_Typ,
7826                   Stream_Op_TSS_Names (Op)));
7827             end if;
7828          end loop;
7829       end;
7830
7831       --  Spec of "=" is expanded if the type is not limited and if a
7832       --  user defined "=" was not already declared for the non-full
7833       --  view of a private extension
7834
7835       if not Is_Limited_Type (Tag_Typ) then
7836          Eq_Needed := True;
7837          Prim := First_Elmt (Primitive_Operations (Tag_Typ));
7838          while Present (Prim) loop
7839
7840             --  If a primitive is encountered that renames the predefined
7841             --  equality operator before reaching any explicit equality
7842             --  primitive, then we still need to create a predefined
7843             --  equality function, because calls to it can occur via
7844             --  the renaming. A new name is created for the equality
7845             --  to avoid conflicting with any user-defined equality.
7846             --  (Note that this doesn't account for renamings of
7847             --  equality nested within subpackages???)
7848
7849             if Is_Predefined_Eq_Renaming (Node (Prim)) then
7850                Eq_Name := New_External_Name (Chars (Node (Prim)), 'E');
7851
7852             --  User-defined equality
7853
7854             elsif Chars (Node (Prim)) = Name_Op_Eq
7855               and then Etype (First_Formal (Node (Prim))) =
7856                          Etype (Next_Formal (First_Formal (Node (Prim))))
7857               and then Base_Type (Etype (Node (Prim))) = Standard_Boolean
7858             then
7859                if No (Alias (Node (Prim)))
7860                  or else Nkind (Unit_Declaration_Node (Node (Prim))) =
7861                            N_Subprogram_Renaming_Declaration
7862                then
7863                   Eq_Needed := False;
7864                   exit;
7865
7866                --  If the parent is not an interface type and has an abstract
7867                --  equality function, the inherited equality is abstract as
7868                --  well, and no body can be created for it.
7869
7870                elsif not Is_Interface (Etype (Tag_Typ))
7871                  and then Present (Alias (Node (Prim)))
7872                  and then Is_Abstract_Subprogram (Alias (Node (Prim)))
7873                then
7874                   Eq_Needed := False;
7875                   exit;
7876
7877                --  If the type has an equality function corresponding with
7878                --  a primitive defined in an interface type, the inherited
7879                --  equality is abstract as well, and no body can be created
7880                --  for it.
7881
7882                elsif Present (Alias (Node (Prim)))
7883                  and then Comes_From_Source (Ultimate_Alias (Node (Prim)))
7884                  and then
7885                    Is_Interface
7886                      (Find_Dispatching_Type (Ultimate_Alias (Node (Prim))))
7887                then
7888                   Eq_Needed := False;
7889                   exit;
7890                end if;
7891             end if;
7892
7893             Next_Elmt (Prim);
7894          end loop;
7895
7896          --  If a renaming of predefined equality was found but there was no
7897          --  user-defined equality (so Eq_Needed is still true), then set the
7898          --  name back to Name_Op_Eq. But in the case where a user-defined
7899          --  equality was located after such a renaming, then the predefined
7900          --  equality function is still needed, so Eq_Needed must be set back
7901          --  to True.
7902
7903          if Eq_Name /= Name_Op_Eq then
7904             if Eq_Needed then
7905                Eq_Name := Name_Op_Eq;
7906             else
7907                Eq_Needed := True;
7908             end if;
7909          end if;
7910
7911          if Eq_Needed then
7912             Eq_Spec := Predef_Spec_Or_Body (Loc,
7913               Tag_Typ => Tag_Typ,
7914               Name    => Eq_Name,
7915               Profile => New_List (
7916                 Make_Parameter_Specification (Loc,
7917                   Defining_Identifier =>
7918                     Make_Defining_Identifier (Loc, Name_X),
7919                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
7920                 Make_Parameter_Specification (Loc,
7921                   Defining_Identifier =>
7922                     Make_Defining_Identifier (Loc, Name_Y),
7923                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
7924                 Ret_Type => Standard_Boolean);
7925             Append_To (Res, Eq_Spec);
7926
7927             if Eq_Name /= Name_Op_Eq then
7928                Renamed_Eq := Defining_Unit_Name (Specification (Eq_Spec));
7929
7930                Prim := First_Elmt (Primitive_Operations (Tag_Typ));
7931                while Present (Prim) loop
7932
7933                   --  Any renamings of equality that appeared before an
7934                   --  overriding equality must be updated to refer to the
7935                   --  entity for the predefined equality, otherwise calls via
7936                   --  the renaming would get incorrectly resolved to call the
7937                   --  user-defined equality function.
7938
7939                   if Is_Predefined_Eq_Renaming (Node (Prim)) then
7940                      Set_Alias (Node (Prim), Renamed_Eq);
7941
7942                   --  Exit upon encountering a user-defined equality
7943
7944                   elsif Chars (Node (Prim)) = Name_Op_Eq
7945                     and then No (Alias (Node (Prim)))
7946                   then
7947                      exit;
7948                   end if;
7949
7950                   Next_Elmt (Prim);
7951                end loop;
7952             end if;
7953          end if;
7954
7955          --  Spec for dispatching assignment
7956
7957          Append_To (Res, Predef_Spec_Or_Body (Loc,
7958            Tag_Typ => Tag_Typ,
7959            Name    => Name_uAssign,
7960            Profile => New_List (
7961              Make_Parameter_Specification (Loc,
7962                Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
7963                Out_Present         => True,
7964                Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
7965
7966              Make_Parameter_Specification (Loc,
7967                Defining_Identifier => Make_Defining_Identifier (Loc, Name_Y),
7968                Parameter_Type      => New_Reference_To (Tag_Typ, Loc)))));
7969       end if;
7970
7971       --  Ada 2005: Generate declarations for the following primitive
7972       --  operations for limited interfaces and synchronized types that
7973       --  implement a limited interface.
7974
7975       --    Disp_Asynchronous_Select
7976       --    Disp_Conditional_Select
7977       --    Disp_Get_Prim_Op_Kind
7978       --    Disp_Get_Task_Id
7979       --    Disp_Requeue
7980       --    Disp_Timed_Select
7981
7982       --  These operations cannot be implemented on VM targets, so we simply
7983       --  disable their generation in this case. Disable the generation of
7984       --  these bodies if No_Dispatching_Calls, Ravenscar or ZFP is active.
7985
7986       if Ada_Version >= Ada_05
7987         and then Tagged_Type_Expansion
7988         and then not Restriction_Active (No_Dispatching_Calls)
7989         and then not Restriction_Active (No_Select_Statements)
7990         and then RTE_Available (RE_Select_Specific_Data)
7991       then
7992          --  These primitives are defined abstract in interface types
7993
7994          if Is_Interface (Tag_Typ)
7995            and then Is_Limited_Record (Tag_Typ)
7996          then
7997             Append_To (Res,
7998               Make_Abstract_Subprogram_Declaration (Loc,
7999                 Specification =>
8000                   Make_Disp_Asynchronous_Select_Spec (Tag_Typ)));
8001
8002             Append_To (Res,
8003               Make_Abstract_Subprogram_Declaration (Loc,
8004                 Specification =>
8005                   Make_Disp_Conditional_Select_Spec (Tag_Typ)));
8006
8007             Append_To (Res,
8008               Make_Abstract_Subprogram_Declaration (Loc,
8009                 Specification =>
8010                   Make_Disp_Get_Prim_Op_Kind_Spec (Tag_Typ)));
8011
8012             Append_To (Res,
8013               Make_Abstract_Subprogram_Declaration (Loc,
8014                 Specification =>
8015                   Make_Disp_Get_Task_Id_Spec (Tag_Typ)));
8016
8017             Append_To (Res,
8018               Make_Abstract_Subprogram_Declaration (Loc,
8019                 Specification =>
8020                   Make_Disp_Requeue_Spec (Tag_Typ)));
8021
8022             Append_To (Res,
8023               Make_Abstract_Subprogram_Declaration (Loc,
8024                 Specification =>
8025                   Make_Disp_Timed_Select_Spec (Tag_Typ)));
8026
8027          --  If the ancestor is an interface type we declare non-abstract
8028          --  primitives to override the abstract primitives of the interface
8029          --  type.
8030
8031          elsif (not Is_Interface (Tag_Typ)
8032                   and then Is_Interface (Etype (Tag_Typ))
8033                   and then Is_Limited_Record (Etype (Tag_Typ)))
8034              or else
8035                (Is_Concurrent_Record_Type (Tag_Typ)
8036                   and then Has_Interfaces (Tag_Typ))
8037          then
8038             Append_To (Res,
8039               Make_Subprogram_Declaration (Loc,
8040                 Specification =>
8041                   Make_Disp_Asynchronous_Select_Spec (Tag_Typ)));
8042
8043             Append_To (Res,
8044               Make_Subprogram_Declaration (Loc,
8045                 Specification =>
8046                   Make_Disp_Conditional_Select_Spec (Tag_Typ)));
8047
8048             Append_To (Res,
8049               Make_Subprogram_Declaration (Loc,
8050                 Specification =>
8051                   Make_Disp_Get_Prim_Op_Kind_Spec (Tag_Typ)));
8052
8053             Append_To (Res,
8054               Make_Subprogram_Declaration (Loc,
8055                 Specification =>
8056                   Make_Disp_Get_Task_Id_Spec (Tag_Typ)));
8057
8058             Append_To (Res,
8059               Make_Subprogram_Declaration (Loc,
8060                 Specification =>
8061                   Make_Disp_Requeue_Spec (Tag_Typ)));
8062
8063             Append_To (Res,
8064               Make_Subprogram_Declaration (Loc,
8065                 Specification =>
8066                   Make_Disp_Timed_Select_Spec (Tag_Typ)));
8067          end if;
8068       end if;
8069
8070       --  Specs for finalization actions that may be required in case a future
8071       --  extension contain a controlled element. We generate those only for
8072       --  root tagged types where they will get dummy bodies or when the type
8073       --  has controlled components and their body must be generated. It is
8074       --  also impossible to provide those for tagged types defined within
8075       --  s-finimp since it would involve circularity problems
8076
8077       if In_Finalization_Root (Tag_Typ) then
8078          null;
8079
8080       --  We also skip these if finalization is not available
8081
8082       elsif Restriction_Active (No_Finalization) then
8083          null;
8084
8085       --  Skip these for CIL Value types, where finalization is not available
8086
8087       elsif Is_Value_Type (Tag_Typ) then
8088          null;
8089
8090       elsif Etype (Tag_Typ) = Tag_Typ
8091         or else Needs_Finalization (Tag_Typ)
8092
8093          --  Ada 2005 (AI-251): We must also generate these subprograms if
8094          --  the immediate ancestor is an interface to ensure the correct
8095          --  initialization of its dispatch table.
8096
8097         or else (not Is_Interface (Tag_Typ)
8098                    and then Is_Interface (Etype (Tag_Typ)))
8099
8100          --  Ada 205 (AI-251): We must also generate these subprograms if
8101          --  the parent of an nonlimited interface is a limited interface
8102
8103         or else (Is_Interface (Tag_Typ)
8104                   and then not Is_Limited_Interface (Tag_Typ)
8105                   and then Is_Limited_Interface (Etype (Tag_Typ)))
8106       then
8107          if not Is_Limited_Type (Tag_Typ) then
8108             Append_To (Res,
8109               Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Adjust));
8110          end if;
8111
8112          Append_To (Res, Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Finalize));
8113       end if;
8114
8115       Predef_List := Res;
8116    end Make_Predefined_Primitive_Specs;
8117
8118    ---------------------------------
8119    -- Needs_Simple_Initialization --
8120    ---------------------------------
8121
8122    function Needs_Simple_Initialization
8123      (T           : Entity_Id;
8124       Consider_IS : Boolean := True) return Boolean
8125    is
8126       Consider_IS_NS : constant Boolean :=
8127                          Normalize_Scalars
8128                            or (Initialize_Scalars and Consider_IS);
8129
8130    begin
8131       --  Check for private type, in which case test applies to the underlying
8132       --  type of the private type.
8133
8134       if Is_Private_Type (T) then
8135          declare
8136             RT : constant Entity_Id := Underlying_Type (T);
8137
8138          begin
8139             if Present (RT) then
8140                return Needs_Simple_Initialization (RT);
8141             else
8142                return False;
8143             end if;
8144          end;
8145
8146       --  Cases needing simple initialization are access types, and, if pragma
8147       --  Normalize_Scalars or Initialize_Scalars is in effect, then all scalar
8148       --  types.
8149
8150       elsif Is_Access_Type (T)
8151         or else (Consider_IS_NS and then (Is_Scalar_Type (T)))
8152       then
8153          return True;
8154
8155       --  If Initialize/Normalize_Scalars is in effect, string objects also
8156       --  need initialization, unless they are created in the course of
8157       --  expanding an aggregate (since in the latter case they will be
8158       --  filled with appropriate initializing values before they are used).
8159
8160       elsif Consider_IS_NS
8161         and then
8162           (Root_Type (T) = Standard_String
8163              or else Root_Type (T) = Standard_Wide_String
8164              or else Root_Type (T) = Standard_Wide_Wide_String)
8165         and then
8166           (not Is_Itype (T)
8167             or else Nkind (Associated_Node_For_Itype (T)) /= N_Aggregate)
8168       then
8169          return True;
8170
8171       else
8172          return False;
8173       end if;
8174    end Needs_Simple_Initialization;
8175
8176    ----------------------
8177    -- Predef_Deep_Spec --
8178    ----------------------
8179
8180    function Predef_Deep_Spec
8181      (Loc      : Source_Ptr;
8182       Tag_Typ  : Entity_Id;
8183       Name     : TSS_Name_Type;
8184       For_Body : Boolean := False) return Node_Id
8185    is
8186       Prof   : List_Id;
8187       Type_B : Entity_Id;
8188
8189    begin
8190       if Name = TSS_Deep_Finalize then
8191          Prof := New_List;
8192          Type_B := Standard_Boolean;
8193
8194       else
8195          Prof := New_List (
8196            Make_Parameter_Specification (Loc,
8197              Defining_Identifier => Make_Defining_Identifier (Loc, Name_L),
8198              In_Present          => True,
8199              Out_Present         => True,
8200              Parameter_Type      =>
8201                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
8202          Type_B := Standard_Short_Short_Integer;
8203       end if;
8204
8205       Append_To (Prof,
8206            Make_Parameter_Specification (Loc,
8207              Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
8208              In_Present          => True,
8209              Out_Present         => True,
8210              Parameter_Type      => New_Reference_To (Tag_Typ, Loc)));
8211
8212       Append_To (Prof,
8213            Make_Parameter_Specification (Loc,
8214              Defining_Identifier => Make_Defining_Identifier (Loc, Name_B),
8215              Parameter_Type      => New_Reference_To (Type_B, Loc)));
8216
8217       return Predef_Spec_Or_Body (Loc,
8218         Name     => Make_TSS_Name (Tag_Typ, Name),
8219         Tag_Typ  => Tag_Typ,
8220         Profile  => Prof,
8221         For_Body => For_Body);
8222
8223    exception
8224       when RE_Not_Available =>
8225          return Empty;
8226    end Predef_Deep_Spec;
8227
8228    -------------------------
8229    -- Predef_Spec_Or_Body --
8230    -------------------------
8231
8232    function Predef_Spec_Or_Body
8233      (Loc      : Source_Ptr;
8234       Tag_Typ  : Entity_Id;
8235       Name     : Name_Id;
8236       Profile  : List_Id;
8237       Ret_Type : Entity_Id := Empty;
8238       For_Body : Boolean := False) return Node_Id
8239    is
8240       Id   : constant Entity_Id := Make_Defining_Identifier (Loc, Name);
8241       Spec : Node_Id;
8242
8243    begin
8244       Set_Is_Public (Id, Is_Public (Tag_Typ));
8245
8246       --  The internal flag is set to mark these declarations because they have
8247       --  specific properties. First, they are primitives even if they are not
8248       --  defined in the type scope (the freezing point is not necessarily in
8249       --  the same scope). Second, the predefined equality can be overridden by
8250       --  a user-defined equality, no body will be generated in this case.
8251
8252       Set_Is_Internal (Id);
8253
8254       if not Debug_Generated_Code then
8255          Set_Debug_Info_Off (Id);
8256       end if;
8257
8258       if No (Ret_Type) then
8259          Spec :=
8260            Make_Procedure_Specification (Loc,
8261              Defining_Unit_Name       => Id,
8262              Parameter_Specifications => Profile);
8263       else
8264          Spec :=
8265            Make_Function_Specification (Loc,
8266              Defining_Unit_Name       => Id,
8267              Parameter_Specifications => Profile,
8268              Result_Definition        =>
8269                New_Reference_To (Ret_Type, Loc));
8270       end if;
8271
8272       if Is_Interface (Tag_Typ) then
8273          return Make_Abstract_Subprogram_Declaration (Loc, Spec);
8274
8275       --  If body case, return empty subprogram body. Note that this is ill-
8276       --  formed, because there is not even a null statement, and certainly not
8277       --  a return in the function case. The caller is expected to do surgery
8278       --  on the body to add the appropriate stuff.
8279
8280       elsif For_Body then
8281          return Make_Subprogram_Body (Loc, Spec, Empty_List, Empty);
8282
8283       --  For the case of an Input attribute predefined for an abstract type,
8284       --  generate an abstract specification. This will never be called, but we
8285       --  need the slot allocated in the dispatching table so that attributes
8286       --  typ'Class'Input and typ'Class'Output will work properly.
8287
8288       elsif Is_TSS (Name, TSS_Stream_Input)
8289         and then Is_Abstract_Type (Tag_Typ)
8290       then
8291          return Make_Abstract_Subprogram_Declaration (Loc, Spec);
8292
8293       --  Normal spec case, where we return a subprogram declaration
8294
8295       else
8296          return Make_Subprogram_Declaration (Loc, Spec);
8297       end if;
8298    end Predef_Spec_Or_Body;
8299
8300    -----------------------------
8301    -- Predef_Stream_Attr_Spec --
8302    -----------------------------
8303
8304    function Predef_Stream_Attr_Spec
8305      (Loc      : Source_Ptr;
8306       Tag_Typ  : Entity_Id;
8307       Name     : TSS_Name_Type;
8308       For_Body : Boolean := False) return Node_Id
8309    is
8310       Ret_Type : Entity_Id;
8311
8312    begin
8313       if Name = TSS_Stream_Input then
8314          Ret_Type := Tag_Typ;
8315       else
8316          Ret_Type := Empty;
8317       end if;
8318
8319       return Predef_Spec_Or_Body (Loc,
8320         Name     => Make_TSS_Name (Tag_Typ, Name),
8321         Tag_Typ  => Tag_Typ,
8322         Profile  => Build_Stream_Attr_Profile (Loc, Tag_Typ, Name),
8323         Ret_Type => Ret_Type,
8324         For_Body => For_Body);
8325    end Predef_Stream_Attr_Spec;
8326
8327    ---------------------------------
8328    -- Predefined_Primitive_Bodies --
8329    ---------------------------------
8330
8331    function Predefined_Primitive_Bodies
8332      (Tag_Typ    : Entity_Id;
8333       Renamed_Eq : Entity_Id) return List_Id
8334    is
8335       Loc       : constant Source_Ptr := Sloc (Tag_Typ);
8336       Res       : constant List_Id    := New_List;
8337       Decl      : Node_Id;
8338       Prim      : Elmt_Id;
8339       Eq_Needed : Boolean;
8340       Eq_Name   : Name_Id;
8341       Ent       : Entity_Id;
8342
8343       pragma Warnings (Off, Ent);
8344
8345    begin
8346       pragma Assert (not Is_Interface (Tag_Typ));
8347
8348       --  See if we have a predefined "=" operator
8349
8350       if Present (Renamed_Eq) then
8351          Eq_Needed := True;
8352          Eq_Name   := Chars (Renamed_Eq);
8353
8354       --  If the parent is an interface type then it has defined all the
8355       --  predefined primitives abstract and we need to check if the type
8356       --  has some user defined "=" function to avoid generating it.
8357
8358       elsif Is_Interface (Etype (Tag_Typ)) then
8359          Eq_Needed := True;
8360          Eq_Name := Name_Op_Eq;
8361
8362          Prim := First_Elmt (Primitive_Operations (Tag_Typ));
8363          while Present (Prim) loop
8364             if Chars (Node (Prim)) = Name_Op_Eq
8365               and then not Is_Internal (Node (Prim))
8366             then
8367                Eq_Needed := False;
8368                Eq_Name := No_Name;
8369                exit;
8370             end if;
8371
8372             Next_Elmt (Prim);
8373          end loop;
8374
8375       else
8376          Eq_Needed := False;
8377          Eq_Name   := No_Name;
8378
8379          Prim := First_Elmt (Primitive_Operations (Tag_Typ));
8380          while Present (Prim) loop
8381             if Chars (Node (Prim)) = Name_Op_Eq
8382               and then Is_Internal (Node (Prim))
8383             then
8384                Eq_Needed := True;
8385                Eq_Name := Name_Op_Eq;
8386                exit;
8387             end if;
8388
8389             Next_Elmt (Prim);
8390          end loop;
8391       end if;
8392
8393       --  Body of _Alignment
8394
8395       Decl := Predef_Spec_Or_Body (Loc,
8396         Tag_Typ => Tag_Typ,
8397         Name    => Name_uAlignment,
8398         Profile => New_List (
8399           Make_Parameter_Specification (Loc,
8400             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
8401             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8402
8403         Ret_Type => Standard_Integer,
8404         For_Body => True);
8405
8406       Set_Handled_Statement_Sequence (Decl,
8407         Make_Handled_Sequence_Of_Statements (Loc, New_List (
8408           Make_Simple_Return_Statement (Loc,
8409             Expression =>
8410               Make_Attribute_Reference (Loc,
8411                 Prefix => Make_Identifier (Loc, Name_X),
8412                 Attribute_Name  => Name_Alignment)))));
8413
8414       Append_To (Res, Decl);
8415
8416       --  Body of _Size
8417
8418       Decl := Predef_Spec_Or_Body (Loc,
8419         Tag_Typ => Tag_Typ,
8420         Name    => Name_uSize,
8421         Profile => New_List (
8422           Make_Parameter_Specification (Loc,
8423             Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
8424             Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8425
8426         Ret_Type => Standard_Long_Long_Integer,
8427         For_Body => True);
8428
8429       Set_Handled_Statement_Sequence (Decl,
8430         Make_Handled_Sequence_Of_Statements (Loc, New_List (
8431           Make_Simple_Return_Statement (Loc,
8432             Expression =>
8433               Make_Attribute_Reference (Loc,
8434                 Prefix => Make_Identifier (Loc, Name_X),
8435                 Attribute_Name  => Name_Size)))));
8436
8437       Append_To (Res, Decl);
8438
8439       --  Bodies for Dispatching stream IO routines. We need these only for
8440       --  non-limited types (in the limited case there is no dispatching).
8441       --  We also skip them if dispatching or finalization are not available.
8442
8443       if Stream_Operation_OK (Tag_Typ, TSS_Stream_Read)
8444         and then No (TSS (Tag_Typ, TSS_Stream_Read))
8445       then
8446          Build_Record_Read_Procedure (Loc, Tag_Typ, Decl, Ent);
8447          Append_To (Res, Decl);
8448       end if;
8449
8450       if Stream_Operation_OK (Tag_Typ, TSS_Stream_Write)
8451         and then No (TSS (Tag_Typ, TSS_Stream_Write))
8452       then
8453          Build_Record_Write_Procedure (Loc, Tag_Typ, Decl, Ent);
8454          Append_To (Res, Decl);
8455       end if;
8456
8457       --  Skip body of _Input for the abstract case, since the corresponding
8458       --  spec is abstract (see Predef_Spec_Or_Body).
8459
8460       if not Is_Abstract_Type (Tag_Typ)
8461         and then Stream_Operation_OK (Tag_Typ, TSS_Stream_Input)
8462         and then No (TSS (Tag_Typ, TSS_Stream_Input))
8463       then
8464          Build_Record_Or_Elementary_Input_Function
8465            (Loc, Tag_Typ, Decl, Ent);
8466          Append_To (Res, Decl);
8467       end if;
8468
8469       if Stream_Operation_OK (Tag_Typ, TSS_Stream_Output)
8470         and then No (TSS (Tag_Typ, TSS_Stream_Output))
8471       then
8472          Build_Record_Or_Elementary_Output_Procedure
8473            (Loc, Tag_Typ, Decl, Ent);
8474          Append_To (Res, Decl);
8475       end if;
8476
8477       --  Ada 2005: Generate bodies for the following primitive operations for
8478       --  limited interfaces and synchronized types that implement a limited
8479       --  interface.
8480
8481       --    disp_asynchronous_select
8482       --    disp_conditional_select
8483       --    disp_get_prim_op_kind
8484       --    disp_get_task_id
8485       --    disp_timed_select
8486
8487       --  The interface versions will have null bodies
8488
8489       --  These operations cannot be implemented on VM targets, so we simply
8490       --  disable their generation in this case. Disable the generation of
8491       --  these bodies if No_Dispatching_Calls, Ravenscar or ZFP is active.
8492
8493       if Ada_Version >= Ada_05
8494         and then Tagged_Type_Expansion
8495         and then not Is_Interface (Tag_Typ)
8496         and then
8497           ((Is_Interface (Etype (Tag_Typ))
8498               and then Is_Limited_Record (Etype (Tag_Typ)))
8499            or else (Is_Concurrent_Record_Type (Tag_Typ)
8500                       and then Has_Interfaces (Tag_Typ)))
8501         and then not Restriction_Active (No_Dispatching_Calls)
8502         and then not Restriction_Active (No_Select_Statements)
8503         and then RTE_Available (RE_Select_Specific_Data)
8504       then
8505          Append_To (Res, Make_Disp_Asynchronous_Select_Body (Tag_Typ));
8506          Append_To (Res, Make_Disp_Conditional_Select_Body  (Tag_Typ));
8507          Append_To (Res, Make_Disp_Get_Prim_Op_Kind_Body    (Tag_Typ));
8508          Append_To (Res, Make_Disp_Get_Task_Id_Body         (Tag_Typ));
8509          Append_To (Res, Make_Disp_Requeue_Body             (Tag_Typ));
8510          Append_To (Res, Make_Disp_Timed_Select_Body        (Tag_Typ));
8511       end if;
8512
8513       if not Is_Limited_Type (Tag_Typ)
8514         and then not Is_Interface (Tag_Typ)
8515       then
8516          --  Body for equality
8517
8518          if Eq_Needed then
8519             Decl :=
8520               Predef_Spec_Or_Body (Loc,
8521                 Tag_Typ => Tag_Typ,
8522                 Name    => Eq_Name,
8523                 Profile => New_List (
8524                   Make_Parameter_Specification (Loc,
8525                     Defining_Identifier =>
8526                       Make_Defining_Identifier (Loc, Name_X),
8527                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
8528
8529                   Make_Parameter_Specification (Loc,
8530                     Defining_Identifier =>
8531                       Make_Defining_Identifier (Loc, Name_Y),
8532                     Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8533
8534                 Ret_Type => Standard_Boolean,
8535                 For_Body => True);
8536
8537             declare
8538                Def          : constant Node_Id := Parent (Tag_Typ);
8539                Stmts        : constant List_Id := New_List;
8540                Variant_Case : Boolean := Has_Discriminants (Tag_Typ);
8541                Comps        : Node_Id := Empty;
8542                Typ_Def      : Node_Id := Type_Definition (Def);
8543
8544             begin
8545                if Variant_Case then
8546                   if Nkind (Typ_Def) = N_Derived_Type_Definition then
8547                      Typ_Def := Record_Extension_Part (Typ_Def);
8548                   end if;
8549
8550                   if Present (Typ_Def) then
8551                      Comps := Component_List (Typ_Def);
8552                   end if;
8553
8554                   Variant_Case := Present (Comps)
8555                     and then Present (Variant_Part (Comps));
8556                end if;
8557
8558                if Variant_Case then
8559                   Append_To (Stmts,
8560                     Make_Eq_If (Tag_Typ, Discriminant_Specifications (Def)));
8561                   Append_List_To (Stmts, Make_Eq_Case (Tag_Typ, Comps));
8562                   Append_To (Stmts,
8563                     Make_Simple_Return_Statement (Loc,
8564                       Expression => New_Reference_To (Standard_True, Loc)));
8565
8566                else
8567                   Append_To (Stmts,
8568                     Make_Simple_Return_Statement (Loc,
8569                       Expression =>
8570                         Expand_Record_Equality (Tag_Typ,
8571                           Typ => Tag_Typ,
8572                           Lhs => Make_Identifier (Loc, Name_X),
8573                           Rhs => Make_Identifier (Loc, Name_Y),
8574                           Bodies => Declarations (Decl))));
8575                end if;
8576
8577                Set_Handled_Statement_Sequence (Decl,
8578                  Make_Handled_Sequence_Of_Statements (Loc, Stmts));
8579             end;
8580             Append_To (Res, Decl);
8581          end if;
8582
8583          --  Body for dispatching assignment
8584
8585          Decl :=
8586            Predef_Spec_Or_Body (Loc,
8587              Tag_Typ => Tag_Typ,
8588              Name    => Name_uAssign,
8589              Profile => New_List (
8590                Make_Parameter_Specification (Loc,
8591                  Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
8592                  Out_Present         => True,
8593                  Parameter_Type      => New_Reference_To (Tag_Typ, Loc)),
8594
8595                Make_Parameter_Specification (Loc,
8596                  Defining_Identifier => Make_Defining_Identifier (Loc, Name_Y),
8597                  Parameter_Type      => New_Reference_To (Tag_Typ, Loc))),
8598              For_Body => True);
8599
8600          Set_Handled_Statement_Sequence (Decl,
8601            Make_Handled_Sequence_Of_Statements (Loc, New_List (
8602              Make_Assignment_Statement (Loc,
8603                Name       => Make_Identifier (Loc, Name_X),
8604                Expression => Make_Identifier (Loc, Name_Y)))));
8605
8606          Append_To (Res, Decl);
8607       end if;
8608
8609       --  Generate dummy bodies for finalization actions of types that have
8610       --  no controlled components.
8611
8612       --  Skip this processing if we are in the finalization routine in the
8613       --  runtime itself, otherwise we get hopelessly circularly confused!
8614
8615       if In_Finalization_Root (Tag_Typ) then
8616          null;
8617
8618       --  Skip this if finalization is not available
8619
8620       elsif Restriction_Active (No_Finalization) then
8621          null;
8622
8623       elsif (Etype (Tag_Typ) = Tag_Typ
8624              or else Is_Controlled (Tag_Typ)
8625
8626                --  Ada 2005 (AI-251): We must also generate these subprograms
8627                --  if the immediate ancestor of Tag_Typ is an interface to
8628                --  ensure the correct initialization of its dispatch table.
8629
8630              or else (not Is_Interface (Tag_Typ)
8631                         and then
8632                       Is_Interface (Etype (Tag_Typ))))
8633         and then not Has_Controlled_Component (Tag_Typ)
8634       then
8635          if not Is_Limited_Type (Tag_Typ) then
8636             Decl := Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Adjust, True);
8637
8638             if Is_Controlled (Tag_Typ) then
8639                Set_Handled_Statement_Sequence (Decl,
8640                  Make_Handled_Sequence_Of_Statements (Loc,
8641                    Make_Adjust_Call (
8642                      Ref          => Make_Identifier (Loc, Name_V),
8643                      Typ          => Tag_Typ,
8644                      Flist_Ref    => Make_Identifier (Loc, Name_L),
8645                      With_Attach  => Make_Identifier (Loc, Name_B))));
8646
8647             else
8648                Set_Handled_Statement_Sequence (Decl,
8649                  Make_Handled_Sequence_Of_Statements (Loc, New_List (
8650                    Make_Null_Statement (Loc))));
8651             end if;
8652
8653             Append_To (Res, Decl);
8654          end if;
8655
8656          Decl := Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Finalize, True);
8657
8658          if Is_Controlled (Tag_Typ) then
8659             Set_Handled_Statement_Sequence (Decl,
8660               Make_Handled_Sequence_Of_Statements (Loc,
8661                 Make_Final_Call (
8662                   Ref         => Make_Identifier (Loc, Name_V),
8663                   Typ         => Tag_Typ,
8664                   With_Detach => Make_Identifier (Loc, Name_B))));
8665
8666          else
8667             Set_Handled_Statement_Sequence (Decl,
8668               Make_Handled_Sequence_Of_Statements (Loc, New_List (
8669                 Make_Null_Statement (Loc))));
8670          end if;
8671
8672          Append_To (Res, Decl);
8673       end if;
8674
8675       return Res;
8676    end Predefined_Primitive_Bodies;
8677
8678    ---------------------------------
8679    -- Predefined_Primitive_Freeze --
8680    ---------------------------------
8681
8682    function Predefined_Primitive_Freeze
8683      (Tag_Typ : Entity_Id) return List_Id
8684    is
8685       Loc     : constant Source_Ptr := Sloc (Tag_Typ);
8686       Res     : constant List_Id    := New_List;
8687       Prim    : Elmt_Id;
8688       Frnodes : List_Id;
8689
8690    begin
8691       Prim := First_Elmt (Primitive_Operations (Tag_Typ));
8692       while Present (Prim) loop
8693          if Is_Predefined_Dispatching_Operation (Node (Prim)) then
8694             Frnodes := Freeze_Entity (Node (Prim), Loc);
8695
8696             if Present (Frnodes) then
8697                Append_List_To (Res, Frnodes);
8698             end if;
8699          end if;
8700
8701          Next_Elmt (Prim);
8702       end loop;
8703
8704       return Res;
8705    end Predefined_Primitive_Freeze;
8706
8707    -------------------------
8708    -- Stream_Operation_OK --
8709    -------------------------
8710
8711    function Stream_Operation_OK
8712      (Typ       : Entity_Id;
8713       Operation : TSS_Name_Type) return Boolean
8714    is
8715       Has_Predefined_Or_Specified_Stream_Attribute : Boolean := False;
8716
8717    begin
8718       --  Special case of a limited type extension: a default implementation
8719       --  of the stream attributes Read or Write exists if that attribute
8720       --  has been specified or is available for an ancestor type; a default
8721       --  implementation of the attribute Output (resp. Input) exists if the
8722       --  attribute has been specified or Write (resp. Read) is available for
8723       --  an ancestor type. The last condition only applies under Ada 2005.
8724
8725       if Is_Limited_Type (Typ)
8726         and then Is_Tagged_Type (Typ)
8727       then
8728          if Operation = TSS_Stream_Read then
8729             Has_Predefined_Or_Specified_Stream_Attribute :=
8730               Has_Specified_Stream_Read (Typ);
8731
8732          elsif Operation = TSS_Stream_Write then
8733             Has_Predefined_Or_Specified_Stream_Attribute :=
8734               Has_Specified_Stream_Write (Typ);
8735
8736          elsif Operation = TSS_Stream_Input then
8737             Has_Predefined_Or_Specified_Stream_Attribute :=
8738               Has_Specified_Stream_Input (Typ)
8739                 or else
8740                   (Ada_Version >= Ada_05
8741                     and then Stream_Operation_OK (Typ, TSS_Stream_Read));
8742
8743          elsif Operation = TSS_Stream_Output then
8744             Has_Predefined_Or_Specified_Stream_Attribute :=
8745               Has_Specified_Stream_Output (Typ)
8746                 or else
8747                   (Ada_Version >= Ada_05
8748                     and then Stream_Operation_OK (Typ, TSS_Stream_Write));
8749          end if;
8750
8751          --  Case of inherited TSS_Stream_Read or TSS_Stream_Write
8752
8753          if not Has_Predefined_Or_Specified_Stream_Attribute
8754            and then Is_Derived_Type (Typ)
8755            and then (Operation = TSS_Stream_Read
8756                       or else Operation = TSS_Stream_Write)
8757          then
8758             Has_Predefined_Or_Specified_Stream_Attribute :=
8759               Present
8760                 (Find_Inherited_TSS (Base_Type (Etype (Typ)), Operation));
8761          end if;
8762       end if;
8763
8764       --  If the type is not limited, or else is limited but the attribute is
8765       --  explicitly specified or is predefined for the type, then return True,
8766       --  unless other conditions prevail, such as restrictions prohibiting
8767       --  streams or dispatching operations. We also return True for limited
8768       --  interfaces, because they may be extended by nonlimited types and
8769       --  permit inheritance in this case (addresses cases where an abstract
8770       --  extension doesn't get 'Input declared, as per comments below, but
8771       --  'Class'Input must still be allowed). Note that attempts to apply
8772       --  stream attributes to a limited interface or its class-wide type
8773       --  (or limited extensions thereof) will still get properly rejected
8774       --  by Check_Stream_Attribute.
8775
8776       --  We exclude the Input operation from being a predefined subprogram in
8777       --  the case where the associated type is an abstract extension, because
8778       --  the attribute is not callable in that case, per 13.13.2(49/2). Also,
8779       --  we don't want an abstract version created because types derived from
8780       --  the abstract type may not even have Input available (for example if
8781       --  derived from a private view of the abstract type that doesn't have
8782       --  a visible Input), but a VM such as .NET or the Java VM can treat the
8783       --  operation as inherited anyway, and we don't want an abstract function
8784       --  to be (implicitly) inherited in that case because it can lead to a VM
8785       --  exception.
8786
8787       return (not Is_Limited_Type (Typ)
8788                or else Is_Interface (Typ)
8789                or else Has_Predefined_Or_Specified_Stream_Attribute)
8790         and then (Operation /= TSS_Stream_Input
8791                    or else not Is_Abstract_Type (Typ)
8792                    or else not Is_Derived_Type (Typ))
8793         and then not Has_Unknown_Discriminants (Typ)
8794         and then not (Is_Interface (Typ)
8795                        and then (Is_Task_Interface (Typ)
8796                                   or else Is_Protected_Interface (Typ)
8797                                   or else Is_Synchronized_Interface (Typ)))
8798         and then not Restriction_Active (No_Streams)
8799         and then not Restriction_Active (No_Dispatch)
8800         and then not No_Run_Time_Mode
8801         and then RTE_Available (RE_Tag)
8802         and then RTE_Available (RE_Root_Stream_Type);
8803    end Stream_Operation_OK;
8804
8805 end Exp_Ch3;