OSDN Git Service

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