OSDN Git Service

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