OSDN Git Service

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