OSDN Git Service

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