OSDN Git Service

2011-08-03 Robert Dewar <dewar@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_aggr.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                             E X P _ A G G R                              --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2011, 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 Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Expander; use Expander;
33 with Exp_Util; use Exp_Util;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch7;  use Exp_Ch7;
36 with Exp_Ch9;  use Exp_Ch9;
37 with Exp_Disp; use Exp_Disp;
38 with Exp_Tss;  use Exp_Tss;
39 with Fname;    use Fname;
40 with Freeze;   use Freeze;
41 with Itypes;   use Itypes;
42 with Lib;      use Lib;
43 with Namet;    use Namet;
44 with Nmake;    use Nmake;
45 with Nlists;   use Nlists;
46 with Opt;      use Opt;
47 with Restrict; use Restrict;
48 with Rident;   use Rident;
49 with Rtsfind;  use Rtsfind;
50 with Ttypes;   use Ttypes;
51 with Sem;      use Sem;
52 with Sem_Aggr; use Sem_Aggr;
53 with Sem_Aux;  use Sem_Aux;
54 with Sem_Ch3;  use Sem_Ch3;
55 with Sem_Eval; use Sem_Eval;
56 with Sem_Res;  use Sem_Res;
57 with Sem_Util; use Sem_Util;
58 with Sinfo;    use Sinfo;
59 with Snames;   use Snames;
60 with Stand;    use Stand;
61 with Targparm; use Targparm;
62 with Tbuild;   use Tbuild;
63 with Uintp;    use Uintp;
64
65 package body Exp_Aggr is
66
67    type Case_Bounds is record
68      Choice_Lo   : Node_Id;
69      Choice_Hi   : Node_Id;
70      Choice_Node : Node_Id;
71    end record;
72
73    type Case_Table_Type is array (Nat range <>) of Case_Bounds;
74    --  Table type used by Check_Case_Choices procedure
75
76    function Must_Slide
77      (Obj_Type : Entity_Id;
78       Typ      : Entity_Id) return Boolean;
79    --  A static array aggregate in an object declaration can in most cases be
80    --  expanded in place. The one exception is when the aggregate is given
81    --  with component associations that specify different bounds from those of
82    --  the type definition in the object declaration. In this pathological
83    --  case the aggregate must slide, and we must introduce an intermediate
84    --  temporary to hold it.
85    --
86    --  The same holds in an assignment to one-dimensional array of arrays,
87    --  when a component may be given with bounds that differ from those of the
88    --  component type.
89
90    procedure Sort_Case_Table (Case_Table : in out Case_Table_Type);
91    --  Sort the Case Table using the Lower Bound of each Choice as the key.
92    --  A simple insertion sort is used since the number of choices in a case
93    --  statement of variant part will usually be small and probably in near
94    --  sorted order.
95
96    function Has_Default_Init_Comps (N : Node_Id) return Boolean;
97    --  N is an aggregate (record or array). Checks the presence of default
98    --  initialization (<>) in any component (Ada 2005: AI-287).
99
100    function Is_Static_Dispatch_Table_Aggregate (N : Node_Id) return Boolean;
101    --  Returns true if N is an aggregate used to initialize the components
102    --  of an statically allocated dispatch table.
103
104    ------------------------------------------------------
105    -- Local subprograms for Record Aggregate Expansion --
106    ------------------------------------------------------
107
108    procedure Expand_Record_Aggregate
109      (N           : Node_Id;
110       Orig_Tag    : Node_Id := Empty;
111       Parent_Expr : Node_Id := Empty);
112    --  This is the top level procedure for record aggregate expansion.
113    --  Expansion for record aggregates needs expand aggregates for tagged
114    --  record types. Specifically Expand_Record_Aggregate adds the Tag
115    --  field in front of the Component_Association list that was created
116    --  during resolution by Resolve_Record_Aggregate.
117    --
118    --    N is the record aggregate node.
119    --    Orig_Tag is the value of the Tag that has to be provided for this
120    --      specific aggregate. It carries the tag corresponding to the type
121    --      of the outermost aggregate during the recursive expansion
122    --    Parent_Expr is the ancestor part of the original extension
123    --      aggregate
124
125    procedure Convert_To_Assignments (N : Node_Id; Typ : Entity_Id);
126    --  N is an N_Aggregate or an N_Extension_Aggregate. Typ is the type of the
127    --  aggregate (which can only be a record type, this procedure is only used
128    --  for record types). Transform the given aggregate into a sequence of
129    --  assignments performed component by component.
130
131    function Build_Record_Aggr_Code
132      (N                             : Node_Id;
133       Typ                           : Entity_Id;
134       Lhs                           : Node_Id;
135       Flist                         : Node_Id   := Empty;
136       Obj                           : Entity_Id := Empty;
137       Is_Limited_Ancestor_Expansion : Boolean   := False) return List_Id;
138    --  N is an N_Aggregate or an N_Extension_Aggregate. Typ is the type of the
139    --  aggregate. Target is an expression containing the location on which the
140    --  component by component assignments will take place. Returns the list of
141    --  assignments plus all other adjustments needed for tagged and controlled
142    --  types. Flist is an expression representing the finalization list on
143    --  which to attach the controlled components if any. Obj is present in the
144    --  object declaration and dynamic allocation cases, it contains an entity
145    --  that allows to know if the value being created needs to be attached to
146    --  the final list in case of pragma Finalize_Storage_Only.
147    --
148    --  ???
149    --  The meaning of the Obj formal is extremely unclear. *What* entity
150    --  should be passed? For the object declaration case we may guess that
151    --  this is the object being declared, but what about the allocator case?
152    --
153    --  Is_Limited_Ancestor_Expansion indicates that the function has been
154    --  called recursively to expand the limited ancestor to avoid copying it.
155
156    function Has_Mutable_Components (Typ : Entity_Id) return Boolean;
157    --  Return true if one of the component is of a discriminated type with
158    --  defaults. An aggregate for a type with mutable components must be
159    --  expanded into individual assignments.
160
161    procedure Initialize_Discriminants (N : Node_Id; Typ : Entity_Id);
162    --  If the type of the aggregate is a type extension with renamed discrimi-
163    --  nants, we must initialize the hidden discriminants of the parent.
164    --  Otherwise, the target object must not be initialized. The discriminants
165    --  are initialized by calling the initialization procedure for the type.
166    --  This is incorrect if the initialization of other components has any
167    --  side effects. We restrict this call to the case where the parent type
168    --  has a variant part, because this is the only case where the hidden
169    --  discriminants are accessed, namely when calling discriminant checking
170    --  functions of the parent type, and when applying a stream attribute to
171    --  an object of the derived type.
172
173    -----------------------------------------------------
174    -- Local Subprograms for Array Aggregate Expansion --
175    -----------------------------------------------------
176
177    function Aggr_Size_OK (N : Node_Id; Typ : Entity_Id) return Boolean;
178    --  Very large static aggregates present problems to the back-end, and are
179    --  transformed into assignments and loops. This function verifies that the
180    --  total number of components of an aggregate is acceptable for rewriting
181    --  into a purely positional static form. Aggr_Size_OK must be called before
182    --  calling Flatten.
183    --
184    --  This function also detects and warns about one-component aggregates that
185    --  appear in a non-static context. Even if the component value is static,
186    --  such an aggregate must be expanded into an assignment.
187
188    procedure Convert_Array_Aggr_In_Allocator
189      (Decl   : Node_Id;
190       Aggr   : Node_Id;
191       Target : Node_Id);
192    --  If the aggregate appears within an allocator and can be expanded in
193    --  place, this routine generates the individual assignments to components
194    --  of the designated object. This is an optimization over the general
195    --  case, where a temporary is first created on the stack and then used to
196    --  construct the allocated object on the heap.
197
198    procedure Convert_To_Positional
199      (N                    : Node_Id;
200       Max_Others_Replicate : Nat     := 5;
201       Handle_Bit_Packed    : Boolean := False);
202    --  If possible, convert named notation to positional notation. This
203    --  conversion is possible only in some static cases. If the conversion is
204    --  possible, then N is rewritten with the analyzed converted aggregate.
205    --  The parameter Max_Others_Replicate controls the maximum number of
206    --  values corresponding to an others choice that will be converted to
207    --  positional notation (the default of 5 is the normal limit, and reflects
208    --  the fact that normally the loop is better than a lot of separate
209    --  assignments). Note that this limit gets overridden in any case if
210    --  either of the restrictions No_Elaboration_Code or No_Implicit_Loops is
211    --  set. The parameter Handle_Bit_Packed is usually set False (since we do
212    --  not expect the back end to handle bit packed arrays, so the normal case
213    --  of conversion is pointless), but in the special case of a call from
214    --  Packed_Array_Aggregate_Handled, we set this parameter to True, since
215    --  these are cases we handle in there.
216
217    procedure Expand_Array_Aggregate (N : Node_Id);
218    --  This is the top-level routine to perform array aggregate expansion.
219    --  N is the N_Aggregate node to be expanded.
220
221    function Backend_Processing_Possible (N : Node_Id) return Boolean;
222    --  This function checks if array aggregate N can be processed directly
223    --  by the backend. If this is the case True is returned.
224
225    function Build_Array_Aggr_Code
226      (N           : Node_Id;
227       Ctype       : Entity_Id;
228       Index       : Node_Id;
229       Into        : Node_Id;
230       Scalar_Comp : Boolean;
231       Indexes     : List_Id := No_List;
232       Flist       : Node_Id := Empty) return List_Id;
233    --  This recursive routine returns a list of statements containing the
234    --  loops and assignments that are needed for the expansion of the array
235    --  aggregate N.
236    --
237    --    N is the (sub-)aggregate node to be expanded into code. This node
238    --    has been fully analyzed, and its Etype is properly set.
239    --
240    --    Index is the index node corresponding to the array sub-aggregate N.
241    --
242    --    Into is the target expression into which we are copying the aggregate.
243    --    Note that this node may not have been analyzed yet, and so the Etype
244    --    field may not be set.
245    --
246    --    Scalar_Comp is True if the component type of the aggregate is scalar.
247    --
248    --    Indexes is the current list of expressions used to index the
249    --    object we are writing into.
250    --
251    --    Flist is an expression representing the finalization list on which
252    --    to attach the controlled components if any.
253
254    function Number_Of_Choices (N : Node_Id) return Nat;
255    --  Returns the number of discrete choices (not including the others choice
256    --  if present) contained in (sub-)aggregate N.
257
258    function Late_Expansion
259      (N      : Node_Id;
260       Typ    : Entity_Id;
261       Target : Node_Id;
262       Flist  : Node_Id := Empty;
263       Obj    : Entity_Id := Empty) return List_Id;
264    --  N is a nested (record or array) aggregate that has been marked with
265    --  'Delay_Expansion'. Typ is the expected type of the aggregate and Target
266    --  is a (duplicable) expression that will hold the result of the aggregate
267    --  expansion. Flist is the finalization list to be used to attach
268    --  controlled components. 'Obj' when non empty, carries the original
269    --  object being initialized in order to know if it needs to be attached to
270    --  the previous parameter which may not be the case in the case where
271    --  Finalize_Storage_Only is set. Basically this procedure is used to
272    --  implement top-down expansions of nested aggregates. This is necessary
273    --  for avoiding temporaries at each level as well as for propagating the
274    --  right internal finalization list.
275
276    function Make_OK_Assignment_Statement
277      (Sloc       : Source_Ptr;
278       Name       : Node_Id;
279       Expression : Node_Id) return Node_Id;
280    --  This is like Make_Assignment_Statement, except that Assignment_OK
281    --  is set in the left operand. All assignments built by this unit
282    --  use this routine. This is needed to deal with assignments to
283    --  initialized constants that are done in place.
284
285    function Packed_Array_Aggregate_Handled (N : Node_Id) return Boolean;
286    --  Given an array aggregate, this function handles the case of a packed
287    --  array aggregate with all constant values, where the aggregate can be
288    --  evaluated at compile time. If this is possible, then N is rewritten
289    --  to be its proper compile time value with all the components properly
290    --  assembled. The expression is analyzed and resolved and True is
291    --  returned. If this transformation is not possible, N is unchanged
292    --  and False is returned
293
294    function Safe_Slice_Assignment (N : Node_Id) return Boolean;
295    --  If a slice assignment has an aggregate with a single others_choice,
296    --  the assignment can be done in place even if bounds are not static,
297    --  by converting it into a loop over the discrete range of the slice.
298
299    ------------------
300    -- Aggr_Size_OK --
301    ------------------
302
303    function Aggr_Size_OK (N : Node_Id; Typ : Entity_Id) return Boolean is
304       Lo   : Node_Id;
305       Hi   : Node_Id;
306       Indx : Node_Id;
307       Siz  : Int;
308       Lov  : Uint;
309       Hiv  : Uint;
310
311       --  The following constant determines the maximum size of an array
312       --  aggregate produced by converting named to positional notation (e.g.
313       --  from others clauses). This avoids running away with attempts to
314       --  convert huge aggregates, which hit memory limits in the backend.
315
316       --  The normal limit is 5000, but we increase this limit to 2**24 (about
317       --  16 million) if Restrictions (No_Elaboration_Code) or Restrictions
318       --  (No_Implicit_Loops) is specified, since in either case, we are at
319       --  risk of declaring the program illegal because of this limit.
320
321       Max_Aggr_Size : constant Nat :=
322                         5000 + (2 ** 24 - 5000) *
323                           Boolean'Pos
324                             (Restriction_Active (No_Elaboration_Code)
325                               or else
326                              Restriction_Active (No_Implicit_Loops));
327
328       function Component_Count (T : Entity_Id) return Int;
329       --  The limit is applied to the total number of components that the
330       --  aggregate will have, which is the number of static expressions
331       --  that will appear in the flattened array. This requires a recursive
332       --  computation of the number of scalar components of the structure.
333
334       ---------------------
335       -- Component_Count --
336       ---------------------
337
338       function Component_Count (T : Entity_Id) return Int is
339          Res  : Int := 0;
340          Comp : Entity_Id;
341
342       begin
343          if Is_Scalar_Type (T) then
344             return 1;
345
346          elsif Is_Record_Type (T) then
347             Comp := First_Component (T);
348             while Present (Comp) loop
349                Res := Res + Component_Count (Etype (Comp));
350                Next_Component (Comp);
351             end loop;
352
353             return Res;
354
355          elsif Is_Array_Type (T) then
356             declare
357                Lo : constant Node_Id :=
358                       Type_Low_Bound (Etype (First_Index (T)));
359                Hi : constant Node_Id :=
360                       Type_High_Bound (Etype (First_Index (T)));
361
362                Siz  : constant Int := Component_Count (Component_Type (T));
363
364             begin
365                if not Compile_Time_Known_Value (Lo)
366                  or else not Compile_Time_Known_Value (Hi)
367                then
368                   return 0;
369                else
370                   return
371                     Siz * UI_To_Int (Expr_Value (Hi) - Expr_Value (Lo) + 1);
372                end if;
373             end;
374
375          else
376             --  Can only be a null for an access type
377
378             return 1;
379          end if;
380       end Component_Count;
381
382    --  Start of processing for Aggr_Size_OK
383
384    begin
385       Siz  := Component_Count (Component_Type (Typ));
386
387       Indx := First_Index (Typ);
388       while Present (Indx) loop
389          Lo  := Type_Low_Bound (Etype (Indx));
390          Hi  := Type_High_Bound (Etype (Indx));
391
392          --  Bounds need to be known at compile time
393
394          if not Compile_Time_Known_Value (Lo)
395            or else not Compile_Time_Known_Value (Hi)
396          then
397             return False;
398          end if;
399
400          Lov := Expr_Value (Lo);
401          Hiv := Expr_Value (Hi);
402
403          --  A flat array is always safe
404
405          if Hiv < Lov then
406             return True;
407          end if;
408
409          --  One-component aggregates are suspicious, and if the context type
410          --  is an object declaration with non-static bounds it will trip gcc;
411          --  such an aggregate must be expanded into a single assignment.
412
413          if Hiv = Lov
414            and then Nkind (Parent (N)) = N_Object_Declaration
415          then
416             declare
417                Index_Type : constant Entity_Id :=
418                               Etype
419                                 (First_Index
420                                    (Etype (Defining_Identifier (Parent (N)))));
421                Indx       : Node_Id;
422
423             begin
424                if not Compile_Time_Known_Value (Type_Low_Bound (Index_Type))
425                   or else not Compile_Time_Known_Value
426                                 (Type_High_Bound (Index_Type))
427                then
428                   if Present (Component_Associations (N)) then
429                      Indx :=
430                        First (Choices (First (Component_Associations (N))));
431                      if Is_Entity_Name (Indx)
432                        and then not Is_Type (Entity (Indx))
433                      then
434                         Error_Msg_N
435                           ("single component aggregate in non-static context?",
436                             Indx);
437                         Error_Msg_N ("\maybe subtype name was meant?", Indx);
438                      end if;
439                   end if;
440
441                   return False;
442                end if;
443             end;
444          end if;
445
446          declare
447             Rng : constant Uint := Hiv - Lov + 1;
448
449          begin
450             --  Check if size is too large
451
452             if not UI_Is_In_Int_Range (Rng) then
453                return False;
454             end if;
455
456             Siz := Siz * UI_To_Int (Rng);
457          end;
458
459          if Siz <= 0
460            or else Siz > Max_Aggr_Size
461          then
462             return False;
463          end if;
464
465          --  Bounds must be in integer range, for later array construction
466
467          if not UI_Is_In_Int_Range (Lov)
468              or else
469             not UI_Is_In_Int_Range (Hiv)
470          then
471             return False;
472          end if;
473
474          Next_Index (Indx);
475       end loop;
476
477       return True;
478    end Aggr_Size_OK;
479
480    ---------------------------------
481    -- Backend_Processing_Possible --
482    ---------------------------------
483
484    --  Backend processing by Gigi/gcc is possible only if all the following
485    --  conditions are met:
486
487    --    1. N is fully positional
488
489    --    2. N is not a bit-packed array aggregate;
490
491    --    3. The size of N's array type must be known at compile time. Note
492    --       that this implies that the component size is also known
493
494    --    4. The array type of N does not follow the Fortran layout convention
495    --       or if it does it must be 1 dimensional.
496
497    --    5. The array component type may not be tagged (which could necessitate
498    --       reassignment of proper tags).
499
500    --    6. The array component type must not have unaligned bit components
501
502    --    7. None of the components of the aggregate may be bit unaligned
503    --       components.
504
505    --    8. There cannot be delayed components, since we do not know enough
506    --       at this stage to know if back end processing is possible.
507
508    --    9. There cannot be any discriminated record components, since the
509    --       back end cannot handle this complex case.
510
511    --   10. No controlled actions need to be generated for components
512
513    --   11. For a VM back end, the array should have no aliased components
514
515    function Backend_Processing_Possible (N : Node_Id) return Boolean is
516       Typ : constant Entity_Id := Etype (N);
517       --  Typ is the correct constrained array subtype of the aggregate
518
519       function Component_Check (N : Node_Id; Index : Node_Id) return Boolean;
520       --  This routine checks components of aggregate N, enforcing checks
521       --  1, 7, 8, and 9. In the multi-dimensional case, these checks are
522       --  performed on subaggregates. The Index value is the current index
523       --  being checked in the multi-dimensional case.
524
525       ---------------------
526       -- Component_Check --
527       ---------------------
528
529       function Component_Check (N : Node_Id; Index : Node_Id) return Boolean is
530          Expr : Node_Id;
531
532       begin
533          --  Checks 1: (no component associations)
534
535          if Present (Component_Associations (N)) then
536             return False;
537          end if;
538
539          --  Checks on components
540
541          --  Recurse to check subaggregates, which may appear in qualified
542          --  expressions. If delayed, the front-end will have to expand.
543          --  If the component is a discriminated record, treat as non-static,
544          --  as the back-end cannot handle this properly.
545
546          Expr := First (Expressions (N));
547          while Present (Expr) loop
548
549             --  Checks 8: (no delayed components)
550
551             if Is_Delayed_Aggregate (Expr) then
552                return False;
553             end if;
554
555             --  Checks 9: (no discriminated records)
556
557             if Present (Etype (Expr))
558               and then Is_Record_Type (Etype (Expr))
559               and then Has_Discriminants (Etype (Expr))
560             then
561                return False;
562             end if;
563
564             --  Checks 7. Component must not be bit aligned component
565
566             if Possible_Bit_Aligned_Component (Expr) then
567                return False;
568             end if;
569
570             --  Recursion to following indexes for multiple dimension case
571
572             if Present (Next_Index (Index))
573                and then not Component_Check (Expr, Next_Index (Index))
574             then
575                return False;
576             end if;
577
578             --  All checks for that component finished, on to next
579
580             Next (Expr);
581          end loop;
582
583          return True;
584       end Component_Check;
585
586    --  Start of processing for Backend_Processing_Possible
587
588    begin
589       --  Checks 2 (array not bit packed) and 10 (no controlled actions)
590
591       if Is_Bit_Packed_Array (Typ) or else Needs_Finalization (Typ) then
592          return False;
593       end if;
594
595       --  If component is limited, aggregate must be expanded because each
596       --  component assignment must be built in place.
597
598       if Is_Immutably_Limited_Type (Component_Type (Typ)) then
599          return False;
600       end if;
601
602       --  Checks 4 (array must not be multi-dimensional Fortran case)
603
604       if Convention (Typ) = Convention_Fortran
605         and then Number_Dimensions (Typ) > 1
606       then
607          return False;
608       end if;
609
610       --  Checks 3 (size of array must be known at compile time)
611
612       if not Size_Known_At_Compile_Time (Typ) then
613          return False;
614       end if;
615
616       --  Checks on components
617
618       if not Component_Check (N, First_Index (Typ)) then
619          return False;
620       end if;
621
622       --  Checks 5 (if the component type is tagged, then we may need to do
623       --    tag adjustments. Perhaps this should be refined to check for any
624       --    component associations that actually need tag adjustment, similar
625       --    to the test in Component_Not_OK_For_Backend for record aggregates
626       --    with tagged components, but not clear whether it's worthwhile ???;
627       --    in the case of the JVM, object tags are handled implicitly)
628
629       if Is_Tagged_Type (Component_Type (Typ))
630         and then Tagged_Type_Expansion
631       then
632          return False;
633       end if;
634
635       --  Checks 6 (component type must not have bit aligned components)
636
637       if Type_May_Have_Bit_Aligned_Components (Component_Type (Typ)) then
638          return False;
639       end if;
640
641       --  Checks 11: Array aggregates with aliased components are currently
642       --  not well supported by the VM backend; disable temporarily this
643       --  backend processing until it is definitely supported.
644
645       if VM_Target /= No_VM
646         and then Has_Aliased_Components (Base_Type (Typ))
647       then
648          return False;
649       end if;
650
651       --  Backend processing is possible
652
653       Set_Size_Known_At_Compile_Time (Etype (N), True);
654       return True;
655    end Backend_Processing_Possible;
656
657    ---------------------------
658    -- Build_Array_Aggr_Code --
659    ---------------------------
660
661    --  The code that we generate from a one dimensional aggregate is
662
663    --  1. If the sub-aggregate contains discrete choices we
664
665    --     (a) Sort the discrete choices
666
667    --     (b) Otherwise for each discrete choice that specifies a range we
668    --         emit a loop. If a range specifies a maximum of three values, or
669    --         we are dealing with an expression we emit a sequence of
670    --         assignments instead of a loop.
671
672    --     (c) Generate the remaining loops to cover the others choice if any
673
674    --  2. If the aggregate contains positional elements we
675
676    --     (a) translate the positional elements in a series of assignments
677
678    --     (b) Generate a final loop to cover the others choice if any.
679    --         Note that this final loop has to be a while loop since the case
680
681    --             L : Integer := Integer'Last;
682    --             H : Integer := Integer'Last;
683    --             A : array (L .. H) := (1, others =>0);
684
685    --         cannot be handled by a for loop. Thus for the following
686
687    --             array (L .. H) := (.. positional elements.., others =>E);
688
689    --         we always generate something like:
690
691    --             J : Index_Type := Index_Of_Last_Positional_Element;
692    --             while J < H loop
693    --                J := Index_Base'Succ (J)
694    --                Tmp (J) := E;
695    --             end loop;
696
697    function Build_Array_Aggr_Code
698      (N           : Node_Id;
699       Ctype       : Entity_Id;
700       Index       : Node_Id;
701       Into        : Node_Id;
702       Scalar_Comp : Boolean;
703       Indexes     : List_Id := No_List;
704       Flist       : Node_Id := Empty) return List_Id
705    is
706       Loc          : constant Source_Ptr := Sloc (N);
707       Index_Base   : constant Entity_Id  := Base_Type (Etype (Index));
708       Index_Base_L : constant Node_Id := Type_Low_Bound (Index_Base);
709       Index_Base_H : constant Node_Id := Type_High_Bound (Index_Base);
710
711       function Add (Val : Int; To : Node_Id) return Node_Id;
712       --  Returns an expression where Val is added to expression To, unless
713       --  To+Val is provably out of To's base type range. To must be an
714       --  already analyzed expression.
715
716       function Empty_Range (L, H : Node_Id) return Boolean;
717       --  Returns True if the range defined by L .. H is certainly empty
718
719       function Equal (L, H : Node_Id) return Boolean;
720       --  Returns True if L = H for sure
721
722       function Index_Base_Name return Node_Id;
723       --  Returns a new reference to the index type name
724
725       function Gen_Assign (Ind : Node_Id; Expr : Node_Id) return List_Id;
726       --  Ind must be a side-effect free expression. If the input aggregate
727       --  N to Build_Loop contains no sub-aggregates, then this function
728       --  returns the assignment statement:
729       --
730       --     Into (Indexes, Ind) := Expr;
731       --
732       --  Otherwise we call Build_Code recursively
733       --
734       --  Ada 2005 (AI-287): In case of default initialized component, Expr
735       --  is empty and we generate a call to the corresponding IP subprogram.
736
737       function Gen_Loop (L, H : Node_Id; Expr : Node_Id) return List_Id;
738       --  Nodes L and H must be side-effect free expressions.
739       --  If the input aggregate N to Build_Loop contains no sub-aggregates,
740       --  This routine returns the for loop statement
741       --
742       --     for J in Index_Base'(L) .. Index_Base'(H) loop
743       --        Into (Indexes, J) := Expr;
744       --     end loop;
745       --
746       --  Otherwise we call Build_Code recursively.
747       --  As an optimization if the loop covers 3 or less scalar elements we
748       --  generate a sequence of assignments.
749
750       function Gen_While (L, H : Node_Id; Expr : Node_Id) return List_Id;
751       --  Nodes L and H must be side-effect free expressions.
752       --  If the input aggregate N to Build_Loop contains no sub-aggregates,
753       --  This routine returns the while loop statement
754       --
755       --     J : Index_Base := L;
756       --     while J < H loop
757       --        J := Index_Base'Succ (J);
758       --        Into (Indexes, J) := Expr;
759       --     end loop;
760       --
761       --  Otherwise we call Build_Code recursively
762
763       function Local_Compile_Time_Known_Value (E : Node_Id) return Boolean;
764       function Local_Expr_Value               (E : Node_Id) return Uint;
765       --  These two Local routines are used to replace the corresponding ones
766       --  in sem_eval because while processing the bounds of an aggregate with
767       --  discrete choices whose index type is an enumeration, we build static
768       --  expressions not recognized by Compile_Time_Known_Value as such since
769       --  they have not yet been analyzed and resolved. All the expressions in
770       --  question are things like Index_Base_Name'Val (Const) which we can
771       --  easily recognize as being constant.
772
773       ---------
774       -- Add --
775       ---------
776
777       function Add (Val : Int; To : Node_Id) return Node_Id is
778          Expr_Pos : Node_Id;
779          Expr     : Node_Id;
780          To_Pos   : Node_Id;
781          U_To     : Uint;
782          U_Val    : constant Uint := UI_From_Int (Val);
783
784       begin
785          --  Note: do not try to optimize the case of Val = 0, because
786          --  we need to build a new node with the proper Sloc value anyway.
787
788          --  First test if we can do constant folding
789
790          if Local_Compile_Time_Known_Value (To) then
791             U_To := Local_Expr_Value (To) + Val;
792
793             --  Determine if our constant is outside the range of the index.
794             --  If so return an Empty node. This empty node will be caught
795             --  by Empty_Range below.
796
797             if Compile_Time_Known_Value (Index_Base_L)
798               and then U_To < Expr_Value (Index_Base_L)
799             then
800                return Empty;
801
802             elsif Compile_Time_Known_Value (Index_Base_H)
803               and then U_To > Expr_Value (Index_Base_H)
804             then
805                return Empty;
806             end if;
807
808             Expr_Pos := Make_Integer_Literal (Loc, U_To);
809             Set_Is_Static_Expression (Expr_Pos);
810
811             if not Is_Enumeration_Type (Index_Base) then
812                Expr := Expr_Pos;
813
814             --  If we are dealing with enumeration return
815             --     Index_Base'Val (Expr_Pos)
816
817             else
818                Expr :=
819                  Make_Attribute_Reference
820                    (Loc,
821                     Prefix         => Index_Base_Name,
822                     Attribute_Name => Name_Val,
823                     Expressions    => New_List (Expr_Pos));
824             end if;
825
826             return Expr;
827          end if;
828
829          --  If we are here no constant folding possible
830
831          if not Is_Enumeration_Type (Index_Base) then
832             Expr :=
833               Make_Op_Add (Loc,
834                            Left_Opnd  => Duplicate_Subexpr (To),
835                            Right_Opnd => Make_Integer_Literal (Loc, U_Val));
836
837          --  If we are dealing with enumeration return
838          --    Index_Base'Val (Index_Base'Pos (To) + Val)
839
840          else
841             To_Pos :=
842               Make_Attribute_Reference
843                 (Loc,
844                  Prefix         => Index_Base_Name,
845                  Attribute_Name => Name_Pos,
846                  Expressions    => New_List (Duplicate_Subexpr (To)));
847
848             Expr_Pos :=
849               Make_Op_Add (Loc,
850                            Left_Opnd  => To_Pos,
851                            Right_Opnd => Make_Integer_Literal (Loc, U_Val));
852
853             Expr :=
854               Make_Attribute_Reference
855                 (Loc,
856                  Prefix         => Index_Base_Name,
857                  Attribute_Name => Name_Val,
858                  Expressions    => New_List (Expr_Pos));
859          end if;
860
861          return Expr;
862       end Add;
863
864       -----------------
865       -- Empty_Range --
866       -----------------
867
868       function Empty_Range (L, H : Node_Id) return Boolean is
869          Is_Empty : Boolean := False;
870          Low      : Node_Id;
871          High     : Node_Id;
872
873       begin
874          --  First check if L or H were already detected as overflowing the
875          --  index base range type by function Add above. If this is so Add
876          --  returns the empty node.
877
878          if No (L) or else No (H) then
879             return True;
880          end if;
881
882          for J in 1 .. 3 loop
883             case J is
884
885                --  L > H    range is empty
886
887                when 1 =>
888                   Low  := L;
889                   High := H;
890
891                --  B_L > H  range must be empty
892
893                when 2 =>
894                   Low  := Index_Base_L;
895                   High := H;
896
897                --  L > B_H  range must be empty
898
899                when 3 =>
900                   Low  := L;
901                   High := Index_Base_H;
902             end case;
903
904             if Local_Compile_Time_Known_Value (Low)
905               and then Local_Compile_Time_Known_Value (High)
906             then
907                Is_Empty :=
908                  UI_Gt (Local_Expr_Value (Low), Local_Expr_Value (High));
909             end if;
910
911             exit when Is_Empty;
912          end loop;
913
914          return Is_Empty;
915       end Empty_Range;
916
917       -----------
918       -- Equal --
919       -----------
920
921       function Equal (L, H : Node_Id) return Boolean is
922       begin
923          if L = H then
924             return True;
925
926          elsif Local_Compile_Time_Known_Value (L)
927            and then Local_Compile_Time_Known_Value (H)
928          then
929             return UI_Eq (Local_Expr_Value (L), Local_Expr_Value (H));
930          end if;
931
932          return False;
933       end Equal;
934
935       ----------------
936       -- Gen_Assign --
937       ----------------
938
939       function Gen_Assign (Ind : Node_Id; Expr : Node_Id) return List_Id is
940          L : constant List_Id := New_List;
941          F : Entity_Id;
942          A : Node_Id;
943
944          New_Indexes  : List_Id;
945          Indexed_Comp : Node_Id;
946          Expr_Q       : Node_Id;
947          Comp_Type    : Entity_Id := Empty;
948
949          function Add_Loop_Actions (Lis : List_Id) return List_Id;
950          --  Collect insert_actions generated in the construction of a
951          --  loop, and prepend them to the sequence of assignments to
952          --  complete the eventual body of the loop.
953
954          ----------------------
955          -- Add_Loop_Actions --
956          ----------------------
957
958          function Add_Loop_Actions (Lis : List_Id) return List_Id is
959             Res : List_Id;
960
961          begin
962             --  Ada 2005 (AI-287): Do nothing else in case of default
963             --  initialized component.
964
965             if No (Expr) then
966                return Lis;
967
968             elsif Nkind (Parent (Expr)) = N_Component_Association
969               and then Present (Loop_Actions (Parent (Expr)))
970             then
971                Append_List (Lis, Loop_Actions (Parent (Expr)));
972                Res := Loop_Actions (Parent (Expr));
973                Set_Loop_Actions (Parent (Expr), No_List);
974                return Res;
975
976             else
977                return Lis;
978             end if;
979          end Add_Loop_Actions;
980
981       --  Start of processing for Gen_Assign
982
983       begin
984          if No (Indexes) then
985             New_Indexes := New_List;
986          else
987             New_Indexes := New_Copy_List_Tree (Indexes);
988          end if;
989
990          Append_To (New_Indexes, Ind);
991
992          if Present (Flist) then
993             F := New_Copy_Tree (Flist);
994
995          elsif Present (Etype (N)) and then Needs_Finalization (Etype (N)) then
996             if Is_Entity_Name (Into)
997               and then Present (Scope (Entity (Into)))
998             then
999                F := Find_Final_List (Scope (Entity (Into)));
1000             else
1001                F := Find_Final_List (Current_Scope);
1002             end if;
1003          else
1004             F := Empty;
1005          end if;
1006
1007          if Present (Next_Index (Index)) then
1008             return
1009               Add_Loop_Actions (
1010                 Build_Array_Aggr_Code
1011                   (N           => Expr,
1012                    Ctype       => Ctype,
1013                    Index       => Next_Index (Index),
1014                    Into        => Into,
1015                    Scalar_Comp => Scalar_Comp,
1016                    Indexes     => New_Indexes,
1017                    Flist       => F));
1018          end if;
1019
1020          --  If we get here then we are at a bottom-level (sub-)aggregate
1021
1022          Indexed_Comp :=
1023            Checks_Off
1024              (Make_Indexed_Component (Loc,
1025                 Prefix      => New_Copy_Tree (Into),
1026                 Expressions => New_Indexes));
1027
1028          Set_Assignment_OK (Indexed_Comp);
1029
1030          --  Ada 2005 (AI-287): In case of default initialized component, Expr
1031          --  is not present (and therefore we also initialize Expr_Q to empty).
1032
1033          if No (Expr) then
1034             Expr_Q := Empty;
1035          elsif Nkind (Expr) = N_Qualified_Expression then
1036             Expr_Q := Expression (Expr);
1037          else
1038             Expr_Q := Expr;
1039          end if;
1040
1041          if Present (Etype (N))
1042            and then Etype (N) /= Any_Composite
1043          then
1044             Comp_Type := Component_Type (Etype (N));
1045             pragma Assert (Comp_Type = Ctype); --  AI-287
1046
1047          elsif Present (Next (First (New_Indexes))) then
1048
1049             --  Ada 2005 (AI-287): Do nothing in case of default initialized
1050             --  component because we have received the component type in
1051             --  the formal parameter Ctype.
1052
1053             --  ??? Some assert pragmas have been added to check if this new
1054             --      formal can be used to replace this code in all cases.
1055
1056             if Present (Expr) then
1057
1058                --  This is a multidimensional array. Recover the component
1059                --  type from the outermost aggregate, because subaggregates
1060                --  do not have an assigned type.
1061
1062                declare
1063                   P : Node_Id;
1064
1065                begin
1066                   P := Parent (Expr);
1067                   while Present (P) loop
1068                      if Nkind (P) = N_Aggregate
1069                        and then Present (Etype (P))
1070                      then
1071                         Comp_Type := Component_Type (Etype (P));
1072                         exit;
1073
1074                      else
1075                         P := Parent (P);
1076                      end if;
1077                   end loop;
1078
1079                   pragma Assert (Comp_Type = Ctype); --  AI-287
1080                end;
1081             end if;
1082          end if;
1083
1084          --  Ada 2005 (AI-287): We only analyze the expression in case of non-
1085          --  default initialized components (otherwise Expr_Q is not present).
1086
1087          if Present (Expr_Q)
1088            and then Nkind_In (Expr_Q, N_Aggregate, N_Extension_Aggregate)
1089          then
1090             --  At this stage the Expression may not have been analyzed yet
1091             --  because the array aggregate code has not been updated to use
1092             --  the Expansion_Delayed flag and avoid analysis altogether to
1093             --  solve the same problem (see Resolve_Aggr_Expr). So let us do
1094             --  the analysis of non-array aggregates now in order to get the
1095             --  value of Expansion_Delayed flag for the inner aggregate ???
1096
1097             if Present (Comp_Type) and then not Is_Array_Type (Comp_Type) then
1098                Analyze_And_Resolve (Expr_Q, Comp_Type);
1099             end if;
1100
1101             if Is_Delayed_Aggregate (Expr_Q) then
1102
1103                --  This is either a subaggregate of a multidimensional array,
1104                --  or a component of an array type whose component type is
1105                --  also an array. In the latter case, the expression may have
1106                --  component associations that provide different bounds from
1107                --  those of the component type, and sliding must occur. Instead
1108                --  of decomposing the current aggregate assignment, force the
1109                --  re-analysis of the assignment, so that a temporary will be
1110                --  generated in the usual fashion, and sliding will take place.
1111
1112                if Nkind (Parent (N)) = N_Assignment_Statement
1113                  and then Is_Array_Type (Comp_Type)
1114                  and then Present (Component_Associations (Expr_Q))
1115                  and then Must_Slide (Comp_Type, Etype (Expr_Q))
1116                then
1117                   Set_Expansion_Delayed (Expr_Q, False);
1118                   Set_Analyzed (Expr_Q, False);
1119
1120                else
1121                   return
1122                     Add_Loop_Actions (
1123                       Late_Expansion (
1124                         Expr_Q, Etype (Expr_Q), Indexed_Comp, F));
1125                end if;
1126             end if;
1127          end if;
1128
1129          --  Ada 2005 (AI-287): In case of default initialized component, call
1130          --  the initialization subprogram associated with the component type.
1131          --  If the component type is an access type, add an explicit null
1132          --  assignment, because for the back-end there is an initialization
1133          --  present for the whole aggregate, and no default initialization
1134          --  will take place.
1135
1136          --  In addition, if the component type is controlled, we must call
1137          --  its Initialize procedure explicitly, because there is no explicit
1138          --  object creation that will invoke it otherwise.
1139
1140          if No (Expr) then
1141             if Present (Base_Init_Proc (Base_Type (Ctype)))
1142               or else Has_Task (Base_Type (Ctype))
1143             then
1144                Append_List_To (L,
1145                  Build_Initialization_Call (Loc,
1146                    Id_Ref            => Indexed_Comp,
1147                    Typ               => Ctype,
1148                    With_Default_Init => True));
1149
1150             elsif Is_Access_Type (Ctype) then
1151                Append_To (L,
1152                   Make_Assignment_Statement (Loc,
1153                      Name => Indexed_Comp,
1154                      Expression => Make_Null (Loc)));
1155             end if;
1156
1157             if Needs_Finalization (Ctype) then
1158                Append_List_To (L,
1159                  Make_Init_Call (
1160                    Ref         => New_Copy_Tree (Indexed_Comp),
1161                    Typ         => Ctype,
1162                    Flist_Ref   => Find_Final_List (Current_Scope),
1163                    With_Attach => Make_Integer_Literal (Loc, 1)));
1164             end if;
1165
1166          else
1167             --  Now generate the assignment with no associated controlled
1168             --  actions since the target of the assignment may not have been
1169             --  initialized, it is not possible to Finalize it as expected by
1170             --  normal controlled assignment. The rest of the controlled
1171             --  actions are done manually with the proper finalization list
1172             --  coming from the context.
1173
1174             A :=
1175               Make_OK_Assignment_Statement (Loc,
1176                 Name       => Indexed_Comp,
1177                 Expression => New_Copy_Tree (Expr));
1178
1179             if Present (Comp_Type) and then Needs_Finalization (Comp_Type) then
1180                Set_No_Ctrl_Actions (A);
1181
1182                --  If this is an aggregate for an array of arrays, each
1183                --  sub-aggregate will be expanded as well, and even with
1184                --  No_Ctrl_Actions the assignments of inner components will
1185                --  require attachment in their assignments to temporaries.
1186                --  These temporaries must be finalized for each subaggregate,
1187                --  to prevent multiple attachments of the same temporary
1188                --  location to same finalization chain (and consequently
1189                --  circular lists). To ensure that finalization takes place
1190                --  for each subaggregate we wrap the assignment in a block.
1191
1192                if Is_Array_Type (Comp_Type)
1193                  and then Nkind (Expr) = N_Aggregate
1194                then
1195                   A :=
1196                     Make_Block_Statement (Loc,
1197                       Handled_Statement_Sequence =>
1198                         Make_Handled_Sequence_Of_Statements (Loc,
1199                            Statements => New_List (A)));
1200                end if;
1201             end if;
1202
1203             Append_To (L, A);
1204
1205             --  Adjust the tag if tagged (because of possible view
1206             --  conversions), unless compiling for a VM where
1207             --  tags are implicit.
1208
1209             if Present (Comp_Type)
1210               and then Is_Tagged_Type (Comp_Type)
1211               and then Tagged_Type_Expansion
1212             then
1213                declare
1214                   Full_Typ : constant Entity_Id := Underlying_Type (Comp_Type);
1215
1216                begin
1217                   A :=
1218                     Make_OK_Assignment_Statement (Loc,
1219                       Name =>
1220                         Make_Selected_Component (Loc,
1221                           Prefix =>  New_Copy_Tree (Indexed_Comp),
1222                           Selector_Name =>
1223                             New_Reference_To
1224                               (First_Tag_Component (Full_Typ), Loc)),
1225
1226                       Expression =>
1227                         Unchecked_Convert_To (RTE (RE_Tag),
1228                           New_Reference_To
1229                             (Node (First_Elmt (Access_Disp_Table (Full_Typ))),
1230                              Loc)));
1231
1232                   Append_To (L, A);
1233                end;
1234             end if;
1235
1236             --  Adjust and attach the component to the proper final list, which
1237             --  can be the controller of the outer record object or the final
1238             --  list associated with the scope.
1239
1240             --  If the component is itself an array of controlled types, whose
1241             --  value is given by a sub-aggregate, then the attach calls have
1242             --  been generated when individual subcomponent are assigned, and
1243             --  must not be done again to prevent malformed finalization chains
1244             --  (see comments above, concerning the creation of a block to hold
1245             --  inner finalization actions).
1246
1247             if Present (Comp_Type)
1248               and then Needs_Finalization (Comp_Type)
1249               and then not Is_Limited_Type (Comp_Type)
1250               and then not
1251                 (Is_Array_Type (Comp_Type)
1252                    and then Is_Controlled (Component_Type (Comp_Type))
1253                    and then Nkind (Expr) = N_Aggregate)
1254             then
1255                Append_List_To (L,
1256                  Make_Adjust_Call (
1257                    Ref         => New_Copy_Tree (Indexed_Comp),
1258                    Typ         => Comp_Type,
1259                    Flist_Ref   => F,
1260                    With_Attach => Make_Integer_Literal (Loc, 1)));
1261             end if;
1262          end if;
1263
1264          return Add_Loop_Actions (L);
1265       end Gen_Assign;
1266
1267       --------------
1268       -- Gen_Loop --
1269       --------------
1270
1271       function Gen_Loop (L, H : Node_Id; Expr : Node_Id) return List_Id is
1272          L_J : Node_Id;
1273
1274          L_L : Node_Id;
1275          --  Index_Base'(L)
1276
1277          L_H : Node_Id;
1278          --  Index_Base'(H)
1279
1280          L_Range : Node_Id;
1281          --  Index_Base'(L) .. Index_Base'(H)
1282
1283          L_Iteration_Scheme : Node_Id;
1284          --  L_J in Index_Base'(L) .. Index_Base'(H)
1285
1286          L_Body : List_Id;
1287          --  The statements to execute in the loop
1288
1289          S : constant List_Id := New_List;
1290          --  List of statements
1291
1292          Tcopy : Node_Id;
1293          --  Copy of expression tree, used for checking purposes
1294
1295       begin
1296          --  If loop bounds define an empty range return the null statement
1297
1298          if Empty_Range (L, H) then
1299             Append_To (S, Make_Null_Statement (Loc));
1300
1301             --  Ada 2005 (AI-287): Nothing else need to be done in case of
1302             --  default initialized component.
1303
1304             if No (Expr) then
1305                null;
1306
1307             else
1308                --  The expression must be type-checked even though no component
1309                --  of the aggregate will have this value. This is done only for
1310                --  actual components of the array, not for subaggregates. Do
1311                --  the check on a copy, because the expression may be shared
1312                --  among several choices, some of which might be non-null.
1313
1314                if Present (Etype (N))
1315                  and then Is_Array_Type (Etype (N))
1316                  and then No (Next_Index (Index))
1317                then
1318                   Expander_Mode_Save_And_Set (False);
1319                   Tcopy := New_Copy_Tree (Expr);
1320                   Set_Parent (Tcopy, N);
1321                   Analyze_And_Resolve (Tcopy, Component_Type (Etype (N)));
1322                   Expander_Mode_Restore;
1323                end if;
1324             end if;
1325
1326             return S;
1327
1328          --  If loop bounds are the same then generate an assignment
1329
1330          elsif Equal (L, H) then
1331             return Gen_Assign (New_Copy_Tree (L), Expr);
1332
1333          --  If H - L <= 2 then generate a sequence of assignments when we are
1334          --  processing the bottom most aggregate and it contains scalar
1335          --  components.
1336
1337          elsif No (Next_Index (Index))
1338            and then Scalar_Comp
1339            and then Local_Compile_Time_Known_Value (L)
1340            and then Local_Compile_Time_Known_Value (H)
1341            and then Local_Expr_Value (H) - Local_Expr_Value (L) <= 2
1342          then
1343
1344             Append_List_To (S, Gen_Assign (New_Copy_Tree (L), Expr));
1345             Append_List_To (S, Gen_Assign (Add (1, To => L), Expr));
1346
1347             if Local_Expr_Value (H) - Local_Expr_Value (L) = 2 then
1348                Append_List_To (S, Gen_Assign (Add (2, To => L), Expr));
1349             end if;
1350
1351             return S;
1352          end if;
1353
1354          --  Otherwise construct the loop, starting with the loop index L_J
1355
1356          L_J := Make_Temporary (Loc, 'J', L);
1357
1358          --  Construct "L .. H" in Index_Base. We use a qualified expression
1359          --  for the bound to convert to the index base, but we don't need
1360          --  to do that if we already have the base type at hand.
1361
1362          if Etype (L) = Index_Base then
1363             L_L := L;
1364          else
1365             L_L :=
1366               Make_Qualified_Expression (Loc,
1367                 Subtype_Mark => Index_Base_Name,
1368                 Expression   => L);
1369          end if;
1370
1371          if Etype (H) = Index_Base then
1372             L_H := H;
1373          else
1374             L_H :=
1375               Make_Qualified_Expression (Loc,
1376                 Subtype_Mark => Index_Base_Name,
1377                 Expression   => H);
1378          end if;
1379
1380          L_Range :=
1381            Make_Range (Loc,
1382              Low_Bound => L_L,
1383              High_Bound => L_H);
1384
1385          --  Construct "for L_J in Index_Base range L .. H"
1386
1387          L_Iteration_Scheme :=
1388            Make_Iteration_Scheme
1389              (Loc,
1390               Loop_Parameter_Specification =>
1391                 Make_Loop_Parameter_Specification
1392                   (Loc,
1393                    Defining_Identifier         => L_J,
1394                    Discrete_Subtype_Definition => L_Range));
1395
1396          --  Construct the statements to execute in the loop body
1397
1398          L_Body := Gen_Assign (New_Reference_To (L_J, Loc), Expr);
1399
1400          --  Construct the final loop
1401
1402          Append_To (S, Make_Implicit_Loop_Statement
1403                          (Node             => N,
1404                           Identifier       => Empty,
1405                           Iteration_Scheme => L_Iteration_Scheme,
1406                           Statements       => L_Body));
1407
1408          --  A small optimization: if the aggregate is initialized with a box
1409          --  and the component type has no initialization procedure, remove the
1410          --  useless empty loop.
1411
1412          if Nkind (First (S)) = N_Loop_Statement
1413            and then Is_Empty_List (Statements (First (S)))
1414          then
1415             return New_List (Make_Null_Statement (Loc));
1416          else
1417             return S;
1418          end if;
1419       end Gen_Loop;
1420
1421       ---------------
1422       -- Gen_While --
1423       ---------------
1424
1425       --  The code built is
1426
1427       --     W_J : Index_Base := L;
1428       --     while W_J < H loop
1429       --        W_J := Index_Base'Succ (W);
1430       --        L_Body;
1431       --     end loop;
1432
1433       function Gen_While (L, H : Node_Id; Expr : Node_Id) return List_Id is
1434          W_J : Node_Id;
1435
1436          W_Decl : Node_Id;
1437          --  W_J : Base_Type := L;
1438
1439          W_Iteration_Scheme : Node_Id;
1440          --  while W_J < H
1441
1442          W_Index_Succ : Node_Id;
1443          --  Index_Base'Succ (J)
1444
1445          W_Increment : Node_Id;
1446          --  W_J := Index_Base'Succ (W)
1447
1448          W_Body : constant List_Id := New_List;
1449          --  The statements to execute in the loop
1450
1451          S : constant List_Id := New_List;
1452          --  list of statement
1453
1454       begin
1455          --  If loop bounds define an empty range or are equal return null
1456
1457          if Empty_Range (L, H) or else Equal (L, H) then
1458             Append_To (S, Make_Null_Statement (Loc));
1459             return S;
1460          end if;
1461
1462          --  Build the decl of W_J
1463
1464          W_J    := Make_Temporary (Loc, 'J', L);
1465          W_Decl :=
1466            Make_Object_Declaration
1467              (Loc,
1468               Defining_Identifier => W_J,
1469               Object_Definition   => Index_Base_Name,
1470               Expression          => L);
1471
1472          --  Theoretically we should do a New_Copy_Tree (L) here, but we know
1473          --  that in this particular case L is a fresh Expr generated by
1474          --  Add which we are the only ones to use.
1475
1476          Append_To (S, W_Decl);
1477
1478          --  Construct " while W_J < H"
1479
1480          W_Iteration_Scheme :=
1481            Make_Iteration_Scheme
1482              (Loc,
1483               Condition => Make_Op_Lt
1484                              (Loc,
1485                               Left_Opnd  => New_Reference_To (W_J, Loc),
1486                               Right_Opnd => New_Copy_Tree (H)));
1487
1488          --  Construct the statements to execute in the loop body
1489
1490          W_Index_Succ :=
1491            Make_Attribute_Reference
1492              (Loc,
1493               Prefix         => Index_Base_Name,
1494               Attribute_Name => Name_Succ,
1495               Expressions    => New_List (New_Reference_To (W_J, Loc)));
1496
1497          W_Increment  :=
1498            Make_OK_Assignment_Statement
1499              (Loc,
1500               Name       => New_Reference_To (W_J, Loc),
1501               Expression => W_Index_Succ);
1502
1503          Append_To (W_Body, W_Increment);
1504          Append_List_To (W_Body,
1505            Gen_Assign (New_Reference_To (W_J, Loc), Expr));
1506
1507          --  Construct the final loop
1508
1509          Append_To (S, Make_Implicit_Loop_Statement
1510                          (Node             => N,
1511                           Identifier       => Empty,
1512                           Iteration_Scheme => W_Iteration_Scheme,
1513                           Statements       => W_Body));
1514
1515          return S;
1516       end Gen_While;
1517
1518       ---------------------
1519       -- Index_Base_Name --
1520       ---------------------
1521
1522       function Index_Base_Name return Node_Id is
1523       begin
1524          return New_Reference_To (Index_Base, Sloc (N));
1525       end Index_Base_Name;
1526
1527       ------------------------------------
1528       -- Local_Compile_Time_Known_Value --
1529       ------------------------------------
1530
1531       function Local_Compile_Time_Known_Value (E : Node_Id) return Boolean is
1532       begin
1533          return Compile_Time_Known_Value (E)
1534            or else
1535              (Nkind (E) = N_Attribute_Reference
1536                and then Attribute_Name (E) = Name_Val
1537                and then Compile_Time_Known_Value (First (Expressions (E))));
1538       end Local_Compile_Time_Known_Value;
1539
1540       ----------------------
1541       -- Local_Expr_Value --
1542       ----------------------
1543
1544       function Local_Expr_Value (E : Node_Id) return Uint is
1545       begin
1546          if Compile_Time_Known_Value (E) then
1547             return Expr_Value (E);
1548          else
1549             return Expr_Value (First (Expressions (E)));
1550          end if;
1551       end Local_Expr_Value;
1552
1553       --  Build_Array_Aggr_Code Variables
1554
1555       Assoc  : Node_Id;
1556       Choice : Node_Id;
1557       Expr   : Node_Id;
1558       Typ    : Entity_Id;
1559
1560       Others_Expr        : Node_Id := Empty;
1561       Others_Box_Present : Boolean := False;
1562
1563       Aggr_L : constant Node_Id := Low_Bound (Aggregate_Bounds (N));
1564       Aggr_H : constant Node_Id := High_Bound (Aggregate_Bounds (N));
1565       --  The aggregate bounds of this specific sub-aggregate. Note that if
1566       --  the code generated by Build_Array_Aggr_Code is executed then these
1567       --  bounds are OK. Otherwise a Constraint_Error would have been raised.
1568
1569       Aggr_Low  : constant Node_Id := Duplicate_Subexpr_No_Checks (Aggr_L);
1570       Aggr_High : constant Node_Id := Duplicate_Subexpr_No_Checks (Aggr_H);
1571       --  After Duplicate_Subexpr these are side-effect free
1572
1573       Low        : Node_Id;
1574       High       : Node_Id;
1575
1576       Nb_Choices : Nat := 0;
1577       Table      : Case_Table_Type (1 .. Number_Of_Choices (N));
1578       --  Used to sort all the different choice values
1579
1580       Nb_Elements : Int;
1581       --  Number of elements in the positional aggregate
1582
1583       New_Code : constant List_Id := New_List;
1584
1585    --  Start of processing for Build_Array_Aggr_Code
1586
1587    begin
1588       --  First before we start, a special case. if we have a bit packed
1589       --  array represented as a modular type, then clear the value to
1590       --  zero first, to ensure that unused bits are properly cleared.
1591
1592       Typ := Etype (N);
1593
1594       if Present (Typ)
1595         and then Is_Bit_Packed_Array (Typ)
1596         and then Is_Modular_Integer_Type (Packed_Array_Type (Typ))
1597       then
1598          Append_To (New_Code,
1599            Make_Assignment_Statement (Loc,
1600              Name => New_Copy_Tree (Into),
1601              Expression =>
1602                Unchecked_Convert_To (Typ,
1603                  Make_Integer_Literal (Loc, Uint_0))));
1604       end if;
1605
1606       --  If the component type contains tasks, we need to build a Master
1607       --  entity in the current scope, because it will be needed if build-
1608       --  in-place functions are called in the expanded code.
1609
1610       if Nkind (Parent (N)) = N_Object_Declaration
1611         and then Has_Task (Typ)
1612       then
1613          Build_Master_Entity (Defining_Identifier (Parent (N)));
1614       end if;
1615
1616       --  STEP 1: Process component associations
1617
1618       --  For those associations that may generate a loop, initialize
1619       --  Loop_Actions to collect inserted actions that may be crated.
1620
1621       --  Skip this if no component associations
1622
1623       if No (Expressions (N)) then
1624
1625          --  STEP 1 (a): Sort the discrete choices
1626
1627          Assoc := First (Component_Associations (N));
1628          while Present (Assoc) loop
1629             Choice := First (Choices (Assoc));
1630             while Present (Choice) loop
1631                if Nkind (Choice) = N_Others_Choice then
1632                   Set_Loop_Actions (Assoc, New_List);
1633
1634                   if Box_Present (Assoc) then
1635                      Others_Box_Present := True;
1636                   else
1637                      Others_Expr := Expression (Assoc);
1638                   end if;
1639                   exit;
1640                end if;
1641
1642                Get_Index_Bounds (Choice, Low, High);
1643
1644                if Low /= High then
1645                   Set_Loop_Actions (Assoc, New_List);
1646                end if;
1647
1648                Nb_Choices := Nb_Choices + 1;
1649                if Box_Present (Assoc) then
1650                   Table (Nb_Choices) := (Choice_Lo   => Low,
1651                                          Choice_Hi   => High,
1652                                          Choice_Node => Empty);
1653                else
1654                   Table (Nb_Choices) := (Choice_Lo   => Low,
1655                                          Choice_Hi   => High,
1656                                          Choice_Node => Expression (Assoc));
1657                end if;
1658                Next (Choice);
1659             end loop;
1660
1661             Next (Assoc);
1662          end loop;
1663
1664          --  If there is more than one set of choices these must be static
1665          --  and we can therefore sort them. Remember that Nb_Choices does not
1666          --  account for an others choice.
1667
1668          if Nb_Choices > 1 then
1669             Sort_Case_Table (Table);
1670          end if;
1671
1672          --  STEP 1 (b):  take care of the whole set of discrete choices
1673
1674          for J in 1 .. Nb_Choices loop
1675             Low  := Table (J).Choice_Lo;
1676             High := Table (J).Choice_Hi;
1677             Expr := Table (J).Choice_Node;
1678             Append_List (Gen_Loop (Low, High, Expr), To => New_Code);
1679          end loop;
1680
1681          --  STEP 1 (c): generate the remaining loops to cover others choice
1682          --  We don't need to generate loops over empty gaps, but if there is
1683          --  a single empty range we must analyze the expression for semantics
1684
1685          if Present (Others_Expr) or else Others_Box_Present then
1686             declare
1687                First : Boolean := True;
1688
1689             begin
1690                for J in 0 .. Nb_Choices loop
1691                   if J = 0 then
1692                      Low := Aggr_Low;
1693                   else
1694                      Low := Add (1, To => Table (J).Choice_Hi);
1695                   end if;
1696
1697                   if J = Nb_Choices then
1698                      High := Aggr_High;
1699                   else
1700                      High := Add (-1, To => Table (J + 1).Choice_Lo);
1701                   end if;
1702
1703                   --  If this is an expansion within an init proc, make
1704                   --  sure that discriminant references are replaced by
1705                   --  the corresponding discriminal.
1706
1707                   if Inside_Init_Proc then
1708                      if Is_Entity_Name (Low)
1709                        and then Ekind (Entity (Low)) = E_Discriminant
1710                      then
1711                         Set_Entity (Low, Discriminal (Entity (Low)));
1712                      end if;
1713
1714                      if Is_Entity_Name (High)
1715                        and then Ekind (Entity (High)) = E_Discriminant
1716                      then
1717                         Set_Entity (High, Discriminal (Entity (High)));
1718                      end if;
1719                   end if;
1720
1721                   if First
1722                     or else not Empty_Range (Low, High)
1723                   then
1724                      First := False;
1725                      Append_List
1726                        (Gen_Loop (Low, High, Others_Expr), To => New_Code);
1727                   end if;
1728                end loop;
1729             end;
1730          end if;
1731
1732       --  STEP 2: Process positional components
1733
1734       else
1735          --  STEP 2 (a): Generate the assignments for each positional element
1736          --  Note that here we have to use Aggr_L rather than Aggr_Low because
1737          --  Aggr_L is analyzed and Add wants an analyzed expression.
1738
1739          Expr        := First (Expressions (N));
1740          Nb_Elements := -1;
1741          while Present (Expr) loop
1742             Nb_Elements := Nb_Elements + 1;
1743             Append_List (Gen_Assign (Add (Nb_Elements, To => Aggr_L), Expr),
1744                          To => New_Code);
1745             Next (Expr);
1746          end loop;
1747
1748          --  STEP 2 (b): Generate final loop if an others choice is present
1749          --  Here Nb_Elements gives the offset of the last positional element.
1750
1751          if Present (Component_Associations (N)) then
1752             Assoc := Last (Component_Associations (N));
1753
1754             --  Ada 2005 (AI-287)
1755
1756             if Box_Present (Assoc) then
1757                Append_List (Gen_While (Add (Nb_Elements, To => Aggr_L),
1758                                        Aggr_High,
1759                                        Empty),
1760                             To => New_Code);
1761             else
1762                Expr  := Expression (Assoc);
1763
1764                Append_List (Gen_While (Add (Nb_Elements, To => Aggr_L),
1765                                        Aggr_High,
1766                                        Expr), --  AI-287
1767                             To => New_Code);
1768             end if;
1769          end if;
1770       end if;
1771
1772       return New_Code;
1773    end Build_Array_Aggr_Code;
1774
1775    ----------------------------
1776    -- Build_Record_Aggr_Code --
1777    ----------------------------
1778
1779    function Build_Record_Aggr_Code
1780      (N                             : Node_Id;
1781       Typ                           : Entity_Id;
1782       Lhs                           : Node_Id;
1783       Flist                         : Node_Id   := Empty;
1784       Obj                           : Entity_Id := Empty;
1785       Is_Limited_Ancestor_Expansion : Boolean   := False) return List_Id
1786    is
1787       Loc     : constant Source_Ptr := Sloc (N);
1788       L       : constant List_Id    := New_List;
1789       N_Typ   : constant Entity_Id  := Etype (N);
1790
1791       Comp      : Node_Id;
1792       Instr     : Node_Id;
1793       Ref       : Node_Id;
1794       Target    : Entity_Id;
1795       F         : Node_Id;
1796       Comp_Type : Entity_Id;
1797       Selector  : Entity_Id;
1798       Comp_Expr : Node_Id;
1799       Expr_Q    : Node_Id;
1800
1801       Internal_Final_List : Node_Id := Empty;
1802
1803       --  If this is an internal aggregate, the External_Final_List is an
1804       --  expression for the controller record of the enclosing type.
1805
1806       --  If the current aggregate has several controlled components, this
1807       --  expression will appear in several calls to attach to the finali-
1808       --  zation list, and it must not be shared.
1809
1810       External_Final_List      : Node_Id;
1811       Ancestor_Is_Expression   : Boolean := False;
1812       Ancestor_Is_Subtype_Mark : Boolean := False;
1813
1814       Init_Typ : Entity_Id := Empty;
1815       Attach   : Node_Id;
1816
1817       Ctrl_Stuff_Done : Boolean := False;
1818       --  True if Gen_Ctrl_Actions_For_Aggr has already been called; calls
1819       --  after the first do nothing.
1820
1821       function Ancestor_Discriminant_Value (Disc : Entity_Id) return Node_Id;
1822       --  Returns the value that the given discriminant of an ancestor type
1823       --  should receive (in the absence of a conflict with the value provided
1824       --  by an ancestor part of an extension aggregate).
1825
1826       procedure Check_Ancestor_Discriminants (Anc_Typ : Entity_Id);
1827       --  Check that each of the discriminant values defined by the ancestor
1828       --  part of an extension aggregate match the corresponding values
1829       --  provided by either an association of the aggregate or by the
1830       --  constraint imposed by a parent type (RM95-4.3.2(8)).
1831
1832       function Compatible_Int_Bounds
1833         (Agg_Bounds : Node_Id;
1834          Typ_Bounds : Node_Id) return Boolean;
1835       --  Return true if Agg_Bounds are equal or within Typ_Bounds. It is
1836       --  assumed that both bounds are integer ranges.
1837
1838       procedure Gen_Ctrl_Actions_For_Aggr;
1839       --  Deal with the various controlled type data structure initializations
1840       --  (but only if it hasn't been done already).
1841
1842       function Get_Constraint_Association (T : Entity_Id) return Node_Id;
1843       --  Returns the first discriminant association in the constraint
1844       --  associated with T, if any, otherwise returns Empty.
1845
1846       function Init_Controller
1847         (Target  : Node_Id;
1848          Typ     : Entity_Id;
1849          F       : Node_Id;
1850          Attach  : Node_Id;
1851          Init_Pr : Boolean) return List_Id;
1852       --  Returns the list of statements necessary to initialize the internal
1853       --  controller of the (possible) ancestor typ into target and attach it
1854       --  to finalization list F. Init_Pr conditions the call to the init proc
1855       --  since it may already be done due to ancestor initialization.
1856
1857       function Is_Int_Range_Bounds (Bounds : Node_Id) return Boolean;
1858       --  Check whether Bounds is a range node and its lower and higher bounds
1859       --  are integers literals.
1860
1861       ---------------------------------
1862       -- Ancestor_Discriminant_Value --
1863       ---------------------------------
1864
1865       function Ancestor_Discriminant_Value (Disc : Entity_Id) return Node_Id is
1866          Assoc        : Node_Id;
1867          Assoc_Elmt   : Elmt_Id;
1868          Aggr_Comp    : Entity_Id;
1869          Corresp_Disc : Entity_Id;
1870          Current_Typ  : Entity_Id := Base_Type (Typ);
1871          Parent_Typ   : Entity_Id;
1872          Parent_Disc  : Entity_Id;
1873          Save_Assoc   : Node_Id := Empty;
1874
1875       begin
1876          --  First check any discriminant associations to see if any of them
1877          --  provide a value for the discriminant.
1878
1879          if Present (Discriminant_Specifications (Parent (Current_Typ))) then
1880             Assoc := First (Component_Associations (N));
1881             while Present (Assoc) loop
1882                Aggr_Comp := Entity (First (Choices (Assoc)));
1883
1884                if Ekind (Aggr_Comp) = E_Discriminant then
1885                   Save_Assoc := Expression (Assoc);
1886
1887                   Corresp_Disc := Corresponding_Discriminant (Aggr_Comp);
1888                   while Present (Corresp_Disc) loop
1889
1890                      --  If found a corresponding discriminant then return the
1891                      --  value given in the aggregate. (Note: this is not
1892                      --  correct in the presence of side effects. ???)
1893
1894                      if Disc = Corresp_Disc then
1895                         return Duplicate_Subexpr (Expression (Assoc));
1896                      end if;
1897
1898                      Corresp_Disc :=
1899                        Corresponding_Discriminant (Corresp_Disc);
1900                   end loop;
1901                end if;
1902
1903                Next (Assoc);
1904             end loop;
1905          end if;
1906
1907          --  No match found in aggregate, so chain up parent types to find
1908          --  a constraint that defines the value of the discriminant.
1909
1910          Parent_Typ := Etype (Current_Typ);
1911          while Current_Typ /= Parent_Typ loop
1912             if Has_Discriminants (Parent_Typ)
1913               and then not Has_Unknown_Discriminants (Parent_Typ)
1914             then
1915                Parent_Disc := First_Discriminant (Parent_Typ);
1916
1917                --  We either get the association from the subtype indication
1918                --  of the type definition itself, or from the discriminant
1919                --  constraint associated with the type entity (which is
1920                --  preferable, but it's not always present ???)
1921
1922                if Is_Empty_Elmt_List (
1923                  Discriminant_Constraint (Current_Typ))
1924                then
1925                   Assoc := Get_Constraint_Association (Current_Typ);
1926                   Assoc_Elmt := No_Elmt;
1927                else
1928                   Assoc_Elmt :=
1929                     First_Elmt (Discriminant_Constraint (Current_Typ));
1930                   Assoc := Node (Assoc_Elmt);
1931                end if;
1932
1933                --  Traverse the discriminants of the parent type looking
1934                --  for one that corresponds.
1935
1936                while Present (Parent_Disc) and then Present (Assoc) loop
1937                   Corresp_Disc := Parent_Disc;
1938                   while Present (Corresp_Disc)
1939                     and then Disc /= Corresp_Disc
1940                   loop
1941                      Corresp_Disc :=
1942                        Corresponding_Discriminant (Corresp_Disc);
1943                   end loop;
1944
1945                   if Disc = Corresp_Disc then
1946                      if Nkind (Assoc) = N_Discriminant_Association then
1947                         Assoc := Expression (Assoc);
1948                      end if;
1949
1950                      --  If the located association directly denotes a
1951                      --  discriminant, then use the value of a saved
1952                      --  association of the aggregate. This is a kludge to
1953                      --  handle certain cases involving multiple discriminants
1954                      --  mapped to a single discriminant of a descendant. It's
1955                      --  not clear how to locate the appropriate discriminant
1956                      --  value for such cases. ???
1957
1958                      if Is_Entity_Name (Assoc)
1959                        and then Ekind (Entity (Assoc)) = E_Discriminant
1960                      then
1961                         Assoc := Save_Assoc;
1962                      end if;
1963
1964                      return Duplicate_Subexpr (Assoc);
1965                   end if;
1966
1967                   Next_Discriminant (Parent_Disc);
1968
1969                   if No (Assoc_Elmt) then
1970                      Next (Assoc);
1971                   else
1972                      Next_Elmt (Assoc_Elmt);
1973                      if Present (Assoc_Elmt) then
1974                         Assoc := Node (Assoc_Elmt);
1975                      else
1976                         Assoc := Empty;
1977                      end if;
1978                   end if;
1979                end loop;
1980             end if;
1981
1982             Current_Typ := Parent_Typ;
1983             Parent_Typ := Etype (Current_Typ);
1984          end loop;
1985
1986          --  In some cases there's no ancestor value to locate (such as
1987          --  when an ancestor part given by an expression defines the
1988          --  discriminant value).
1989
1990          return Empty;
1991       end Ancestor_Discriminant_Value;
1992
1993       ----------------------------------
1994       -- Check_Ancestor_Discriminants --
1995       ----------------------------------
1996
1997       procedure Check_Ancestor_Discriminants (Anc_Typ : Entity_Id) is
1998          Discr      : Entity_Id;
1999          Disc_Value : Node_Id;
2000          Cond       : Node_Id;
2001
2002       begin
2003          Discr := First_Discriminant (Base_Type (Anc_Typ));
2004          while Present (Discr) loop
2005             Disc_Value := Ancestor_Discriminant_Value (Discr);
2006
2007             if Present (Disc_Value) then
2008                Cond := Make_Op_Ne (Loc,
2009                  Left_Opnd =>
2010                    Make_Selected_Component (Loc,
2011                      Prefix        => New_Copy_Tree (Target),
2012                      Selector_Name => New_Occurrence_Of (Discr, Loc)),
2013                  Right_Opnd => Disc_Value);
2014
2015                Append_To (L,
2016                  Make_Raise_Constraint_Error (Loc,
2017                    Condition => Cond,
2018                    Reason    => CE_Discriminant_Check_Failed));
2019             end if;
2020
2021             Next_Discriminant (Discr);
2022          end loop;
2023       end Check_Ancestor_Discriminants;
2024
2025       ---------------------------
2026       -- Compatible_Int_Bounds --
2027       ---------------------------
2028
2029       function Compatible_Int_Bounds
2030         (Agg_Bounds : Node_Id;
2031          Typ_Bounds : Node_Id) return Boolean
2032       is
2033          Agg_Lo : constant Uint := Intval (Low_Bound  (Agg_Bounds));
2034          Agg_Hi : constant Uint := Intval (High_Bound (Agg_Bounds));
2035          Typ_Lo : constant Uint := Intval (Low_Bound  (Typ_Bounds));
2036          Typ_Hi : constant Uint := Intval (High_Bound (Typ_Bounds));
2037       begin
2038          return Typ_Lo <= Agg_Lo and then Agg_Hi <= Typ_Hi;
2039       end Compatible_Int_Bounds;
2040
2041       --------------------------------
2042       -- Get_Constraint_Association --
2043       --------------------------------
2044
2045       function Get_Constraint_Association (T : Entity_Id) return Node_Id is
2046          Typ_Def : constant Node_Id := Type_Definition (Parent (T));
2047          Indic   : constant Node_Id := Subtype_Indication (Typ_Def);
2048
2049       begin
2050          --  ??? Also need to cover case of a type mark denoting a subtype
2051          --  with constraint.
2052
2053          if Nkind (Indic) = N_Subtype_Indication
2054            and then Present (Constraint (Indic))
2055          then
2056             return First (Constraints (Constraint (Indic)));
2057          end if;
2058
2059          return Empty;
2060       end Get_Constraint_Association;
2061
2062       ---------------------
2063       -- Init_Controller --
2064       ---------------------
2065
2066       function Init_Controller
2067         (Target  : Node_Id;
2068          Typ     : Entity_Id;
2069          F       : Node_Id;
2070          Attach  : Node_Id;
2071          Init_Pr : Boolean) return List_Id
2072       is
2073          L           : constant List_Id := New_List;
2074          Ref         : Node_Id;
2075          RC          : RE_Id;
2076          Target_Type : Entity_Id;
2077
2078       begin
2079          --  Generate:
2080          --     init-proc (target._controller);
2081          --     initialize (target._controller);
2082          --     Attach_to_Final_List (target._controller, F);
2083
2084          Ref :=
2085            Make_Selected_Component (Loc,
2086              Prefix        => Convert_To (Typ, New_Copy_Tree (Target)),
2087              Selector_Name => Make_Identifier (Loc, Name_uController));
2088          Set_Assignment_OK (Ref);
2089
2090          --  Ada 2005 (AI-287): Give support to aggregates of limited types.
2091          --  If the type is intrinsically limited the controller is limited as
2092          --  well. If it is tagged and limited then so is the controller.
2093          --  Otherwise an untagged type may have limited components without its
2094          --  full view being limited, so the controller is not limited.
2095
2096          if Nkind (Target) = N_Identifier then
2097             Target_Type := Etype (Target);
2098
2099          elsif Nkind (Target) = N_Selected_Component then
2100             Target_Type := Etype (Selector_Name (Target));
2101
2102          elsif Nkind (Target) = N_Unchecked_Type_Conversion then
2103             Target_Type := Etype (Target);
2104
2105          elsif Nkind (Target) = N_Unchecked_Expression
2106            and then Nkind (Expression (Target)) = N_Indexed_Component
2107          then
2108             Target_Type := Etype (Prefix (Expression (Target)));
2109
2110          else
2111             Target_Type := Etype (Target);
2112          end if;
2113
2114          --  If the target has not been analyzed yet, as will happen with
2115          --  delayed expansion, use the given type (either the aggregate type
2116          --  or an ancestor) to determine limitedness.
2117
2118          if No (Target_Type) then
2119             Target_Type := Typ;
2120          end if;
2121
2122          if (Is_Tagged_Type (Target_Type))
2123            and then Is_Limited_Type (Target_Type)
2124          then
2125             RC := RE_Limited_Record_Controller;
2126
2127          elsif Is_Immutably_Limited_Type (Target_Type) then
2128             RC := RE_Limited_Record_Controller;
2129
2130          else
2131             RC := RE_Record_Controller;
2132          end if;
2133
2134          if Init_Pr then
2135             Append_List_To (L,
2136               Build_Initialization_Call (Loc,
2137                 Id_Ref       => Ref,
2138                 Typ          => RTE (RC),
2139                 In_Init_Proc => Within_Init_Proc));
2140          end if;
2141
2142          Append_To (L,
2143            Make_Procedure_Call_Statement (Loc,
2144              Name =>
2145                New_Reference_To (
2146                  Find_Prim_Op (RTE (RC), Name_Initialize), Loc),
2147              Parameter_Associations =>
2148                New_List (New_Copy_Tree (Ref))));
2149
2150          Append_To (L,
2151            Make_Attach_Call (
2152              Obj_Ref     => New_Copy_Tree (Ref),
2153              Flist_Ref   => F,
2154              With_Attach => Attach));
2155
2156          return L;
2157       end Init_Controller;
2158
2159       -------------------------
2160       -- Is_Int_Range_Bounds --
2161       -------------------------
2162
2163       function Is_Int_Range_Bounds (Bounds : Node_Id) return Boolean is
2164       begin
2165          return Nkind (Bounds) = N_Range
2166            and then Nkind (Low_Bound  (Bounds)) = N_Integer_Literal
2167            and then Nkind (High_Bound (Bounds)) = N_Integer_Literal;
2168       end Is_Int_Range_Bounds;
2169
2170       -------------------------------
2171       -- Gen_Ctrl_Actions_For_Aggr --
2172       -------------------------------
2173
2174       procedure Gen_Ctrl_Actions_For_Aggr is
2175          Alloc : Node_Id := Empty;
2176
2177       begin
2178          --  Do the work only the first time this is called
2179
2180          if Ctrl_Stuff_Done then
2181             return;
2182          end if;
2183
2184          Ctrl_Stuff_Done := True;
2185
2186          if Present (Obj)
2187            and then Finalize_Storage_Only (Typ)
2188            and then
2189              (Is_Library_Level_Entity (Obj)
2190                 or else Entity (Constant_Value (RTE (RE_Garbage_Collected))) =
2191                                                           Standard_True)
2192
2193             --  why not Is_True (Expr_Value (RTE (RE_Garbaage_Collected) ???
2194          then
2195             Attach := Make_Integer_Literal (Loc, 0);
2196
2197          elsif Nkind (Parent (N)) = N_Qualified_Expression
2198            and then Nkind (Parent (Parent (N))) = N_Allocator
2199          then
2200             Alloc  := Parent (Parent (N));
2201             Attach := Make_Integer_Literal (Loc, 2);
2202
2203          else
2204             Attach := Make_Integer_Literal (Loc, 1);
2205          end if;
2206
2207          --  Determine the external finalization list. It is either the
2208          --  finalization list of the outer-scope or the one coming from
2209          --  an outer aggregate.  When the target is not a temporary, the
2210          --  proper scope is the scope of the target rather than the
2211          --  potentially transient current scope.
2212
2213          if Needs_Finalization (Typ) then
2214
2215             --  The current aggregate belongs to an allocator which creates
2216             --  an object through an anonymous access type or acts as the root
2217             --  of a coextension chain.
2218
2219             if Present (Alloc)
2220               and then
2221                 (Is_Coextension_Root (Alloc)
2222                    or else Ekind (Etype (Alloc)) = E_Anonymous_Access_Type)
2223             then
2224                if No (Associated_Final_Chain (Etype (Alloc))) then
2225                   Build_Final_List (Alloc, Etype (Alloc));
2226                end if;
2227
2228                External_Final_List :=
2229                  Make_Selected_Component (Loc,
2230                    Prefix =>
2231                      New_Reference_To (
2232                        Associated_Final_Chain (Etype (Alloc)), Loc),
2233                    Selector_Name => Make_Identifier (Loc, Name_F));
2234
2235             elsif Present (Flist) then
2236                External_Final_List := New_Copy_Tree (Flist);
2237
2238             elsif Is_Entity_Name (Target)
2239               and then Present (Scope (Entity (Target)))
2240             then
2241                External_Final_List :=
2242                  Find_Final_List (Scope (Entity (Target)));
2243
2244             else
2245                External_Final_List := Find_Final_List (Current_Scope);
2246             end if;
2247          else
2248             External_Final_List := Empty;
2249          end if;
2250
2251          --  Initialize and attach the outer object in the is_controlled case
2252
2253          if Is_Controlled (Typ) then
2254             if Ancestor_Is_Subtype_Mark then
2255                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2256                Set_Assignment_OK (Ref);
2257                Append_To (L,
2258                  Make_Procedure_Call_Statement (Loc,
2259                    Name =>
2260                      New_Reference_To
2261                        (Find_Prim_Op (Init_Typ, Name_Initialize), Loc),
2262                    Parameter_Associations => New_List (New_Copy_Tree (Ref))));
2263             end if;
2264
2265             if not Has_Controlled_Component (Typ) then
2266                Ref := New_Copy_Tree (Target);
2267                Set_Assignment_OK (Ref);
2268
2269                --  This is an aggregate of a coextension. Do not produce a
2270                --  finalization call, but rather attach the reference of the
2271                --  aggregate to its coextension chain.
2272
2273                if Present (Alloc)
2274                  and then Is_Dynamic_Coextension (Alloc)
2275                then
2276                   if No (Coextensions (Alloc)) then
2277                      Set_Coextensions (Alloc, New_Elmt_List);
2278                   end if;
2279
2280                   Append_Elmt (Ref, Coextensions (Alloc));
2281                else
2282                   Append_To (L,
2283                     Make_Attach_Call (
2284                       Obj_Ref     => Ref,
2285                       Flist_Ref   => New_Copy_Tree (External_Final_List),
2286                       With_Attach => Attach));
2287                end if;
2288             end if;
2289          end if;
2290
2291          --  In the Has_Controlled component case, all the intermediate
2292          --  controllers must be initialized.
2293
2294          if Has_Controlled_Component (Typ)
2295            and not Is_Limited_Ancestor_Expansion
2296          then
2297             declare
2298                Inner_Typ : Entity_Id;
2299                Outer_Typ : Entity_Id;
2300                At_Root   : Boolean;
2301
2302             begin
2303                --  Find outer type with a controller
2304
2305                Outer_Typ := Base_Type (Typ);
2306                while Outer_Typ /= Init_Typ
2307                  and then not Has_New_Controlled_Component (Outer_Typ)
2308                loop
2309                   Outer_Typ := Etype (Outer_Typ);
2310                end loop;
2311
2312                --  Attach it to the outer record controller to the external
2313                --  final list.
2314
2315                if Outer_Typ = Init_Typ then
2316                   Append_List_To (L,
2317                     Init_Controller (
2318                       Target  => Target,
2319                       Typ     => Outer_Typ,
2320                       F       => External_Final_List,
2321                       Attach  => Attach,
2322                       Init_Pr => False));
2323
2324                   At_Root   := True;
2325                   Inner_Typ := Init_Typ;
2326
2327                else
2328                   Append_List_To (L,
2329                     Init_Controller (
2330                       Target  => Target,
2331                       Typ     => Outer_Typ,
2332                       F       => External_Final_List,
2333                       Attach  => Attach,
2334                       Init_Pr => True));
2335
2336                   Inner_Typ := Etype (Outer_Typ);
2337                   At_Root   :=
2338                     not Is_Tagged_Type (Typ) or else Inner_Typ = Outer_Typ;
2339                end if;
2340
2341                --  The outer object has to be attached as well
2342
2343                if Is_Controlled (Typ) then
2344                   Ref := New_Copy_Tree (Target);
2345                   Set_Assignment_OK (Ref);
2346                   Append_To (L,
2347                     Make_Attach_Call (
2348                       Obj_Ref     => Ref,
2349                       Flist_Ref   => New_Copy_Tree (External_Final_List),
2350                       With_Attach => New_Copy_Tree (Attach)));
2351                end if;
2352
2353                --  Initialize the internal controllers for tagged types with
2354                --  more than one controller.
2355
2356                while not At_Root and then Inner_Typ /= Init_Typ loop
2357                   if Has_New_Controlled_Component (Inner_Typ) then
2358                      F :=
2359                        Make_Selected_Component (Loc,
2360                          Prefix =>
2361                            Convert_To (Outer_Typ, New_Copy_Tree (Target)),
2362                          Selector_Name =>
2363                            Make_Identifier (Loc, Name_uController));
2364                      F :=
2365                        Make_Selected_Component (Loc,
2366                          Prefix => F,
2367                          Selector_Name => Make_Identifier (Loc, Name_F));
2368
2369                      Append_List_To (L,
2370                        Init_Controller (
2371                          Target  => Target,
2372                          Typ     => Inner_Typ,
2373                          F       => F,
2374                          Attach  => Make_Integer_Literal (Loc, 1),
2375                          Init_Pr => True));
2376                      Outer_Typ := Inner_Typ;
2377                   end if;
2378
2379                   --  Stop at the root
2380
2381                   At_Root := Inner_Typ = Etype (Inner_Typ);
2382                   Inner_Typ := Etype (Inner_Typ);
2383                end loop;
2384
2385                --  If not done yet attach the controller of the ancestor part
2386
2387                if Outer_Typ /= Init_Typ
2388                  and then Inner_Typ = Init_Typ
2389                  and then Has_Controlled_Component (Init_Typ)
2390                then
2391                   F :=
2392                     Make_Selected_Component (Loc,
2393                       Prefix => Convert_To (Outer_Typ, New_Copy_Tree (Target)),
2394                       Selector_Name =>
2395                         Make_Identifier (Loc, Name_uController));
2396                   F :=
2397                     Make_Selected_Component (Loc,
2398                       Prefix        => F,
2399                       Selector_Name => Make_Identifier (Loc, Name_F));
2400
2401                   Attach := Make_Integer_Literal (Loc, 1);
2402                   Append_List_To (L,
2403                     Init_Controller (
2404                       Target  => Target,
2405                       Typ     => Init_Typ,
2406                       F       => F,
2407                       Attach  => Attach,
2408                       Init_Pr => False));
2409
2410                      --  Note: Init_Pr is False because the ancestor part has
2411                      --  already been initialized either way (by default, if
2412                      --  given by a type name, otherwise from the expression).
2413
2414                end if;
2415             end;
2416          end if;
2417       end Gen_Ctrl_Actions_For_Aggr;
2418
2419       function Rewrite_Discriminant (Expr : Node_Id) return Traverse_Result;
2420       --  If default expression of a component mentions a discriminant of the
2421       --  type, it must be rewritten as the discriminant of the target object.
2422
2423       function Replace_Type (Expr : Node_Id) return Traverse_Result;
2424       --  If the aggregate contains a self-reference, traverse each expression
2425       --  to replace a possible self-reference with a reference to the proper
2426       --  component of the target of the assignment.
2427
2428       --------------------------
2429       -- Rewrite_Discriminant --
2430       --------------------------
2431
2432       function Rewrite_Discriminant (Expr : Node_Id) return Traverse_Result is
2433       begin
2434          if Is_Entity_Name (Expr)
2435            and then Present (Entity (Expr))
2436            and then Ekind (Entity (Expr)) = E_In_Parameter
2437            and then Present (Discriminal_Link (Entity (Expr)))
2438            and then Scope (Discriminal_Link (Entity (Expr)))
2439                       = Base_Type (Etype (N))
2440          then
2441             Rewrite (Expr,
2442               Make_Selected_Component (Loc,
2443                 Prefix        => New_Copy_Tree (Lhs),
2444                 Selector_Name => Make_Identifier (Loc, Chars (Expr))));
2445          end if;
2446          return OK;
2447       end Rewrite_Discriminant;
2448
2449       ------------------
2450       -- Replace_Type --
2451       ------------------
2452
2453       function Replace_Type (Expr : Node_Id) return Traverse_Result is
2454       begin
2455          --  Note regarding the Root_Type test below: Aggregate components for
2456          --  self-referential types include attribute references to the current
2457          --  instance, of the form: Typ'access, etc.. These references are
2458          --  rewritten as references to the target of the aggregate: the
2459          --  left-hand side of an assignment, the entity in a declaration,
2460          --  or a temporary. Without this test, we would improperly extended
2461          --  this rewriting to attribute references whose prefix was not the
2462          --  type of the aggregate.
2463
2464          if Nkind (Expr) = N_Attribute_Reference
2465            and then Is_Entity_Name (Prefix (Expr))
2466            and then Is_Type (Entity (Prefix (Expr)))
2467            and then Root_Type (Etype (N)) = Root_Type (Entity (Prefix (Expr)))
2468          then
2469             if Is_Entity_Name (Lhs) then
2470                Rewrite (Prefix (Expr),
2471                  New_Occurrence_Of (Entity (Lhs), Loc));
2472
2473             elsif Nkind (Lhs) = N_Selected_Component then
2474                Rewrite (Expr,
2475                  Make_Attribute_Reference (Loc,
2476                    Attribute_Name => Name_Unrestricted_Access,
2477                    Prefix         => New_Copy_Tree (Prefix (Lhs))));
2478                Set_Analyzed (Parent (Expr), False);
2479
2480             else
2481                Rewrite (Expr,
2482                  Make_Attribute_Reference (Loc,
2483                    Attribute_Name => Name_Unrestricted_Access,
2484                    Prefix         => New_Copy_Tree (Lhs)));
2485                Set_Analyzed (Parent (Expr), False);
2486             end if;
2487          end if;
2488
2489          return OK;
2490       end Replace_Type;
2491
2492       procedure Replace_Self_Reference is
2493         new Traverse_Proc (Replace_Type);
2494
2495       procedure Replace_Discriminants is
2496         new Traverse_Proc (Rewrite_Discriminant);
2497
2498    --  Start of processing for Build_Record_Aggr_Code
2499
2500    begin
2501       if Has_Self_Reference (N) then
2502          Replace_Self_Reference (N);
2503       end if;
2504
2505       --  If the target of the aggregate is class-wide, we must convert it
2506       --  to the actual type of the aggregate, so that the proper components
2507       --  are visible. We know already that the types are compatible.
2508
2509       if Present (Etype (Lhs))
2510         and then Is_Class_Wide_Type (Etype (Lhs))
2511       then
2512          Target := Unchecked_Convert_To (Typ, Lhs);
2513       else
2514          Target := Lhs;
2515       end if;
2516
2517       --  Deal with the ancestor part of extension aggregates or with the
2518       --  discriminants of the root type.
2519
2520       if Nkind (N) = N_Extension_Aggregate then
2521          declare
2522             A      : constant Node_Id := Ancestor_Part (N);
2523             Assign : List_Id;
2524
2525          begin
2526             --  If the ancestor part is a subtype mark "T", we generate
2527
2528             --     init-proc (T(tmp));  if T is constrained and
2529             --     init-proc (S(tmp));  where S applies an appropriate
2530             --                          constraint if T is unconstrained
2531
2532             if Is_Entity_Name (A) and then Is_Type (Entity (A)) then
2533                Ancestor_Is_Subtype_Mark := True;
2534
2535                if Is_Constrained (Entity (A)) then
2536                   Init_Typ := Entity (A);
2537
2538                --  For an ancestor part given by an unconstrained type mark,
2539                --  create a subtype constrained by appropriate corresponding
2540                --  discriminant values coming from either associations of the
2541                --  aggregate or a constraint on a parent type. The subtype will
2542                --  be used to generate the correct default value for the
2543                --  ancestor part.
2544
2545                elsif Has_Discriminants (Entity (A)) then
2546                   declare
2547                      Anc_Typ    : constant Entity_Id := Entity (A);
2548                      Anc_Constr : constant List_Id   := New_List;
2549                      Discrim    : Entity_Id;
2550                      Disc_Value : Node_Id;
2551                      New_Indic  : Node_Id;
2552                      Subt_Decl  : Node_Id;
2553
2554                   begin
2555                      Discrim := First_Discriminant (Anc_Typ);
2556                      while Present (Discrim) loop
2557                         Disc_Value := Ancestor_Discriminant_Value (Discrim);
2558                         Append_To (Anc_Constr, Disc_Value);
2559                         Next_Discriminant (Discrim);
2560                      end loop;
2561
2562                      New_Indic :=
2563                        Make_Subtype_Indication (Loc,
2564                          Subtype_Mark => New_Occurrence_Of (Anc_Typ, Loc),
2565                          Constraint   =>
2566                            Make_Index_Or_Discriminant_Constraint (Loc,
2567                              Constraints => Anc_Constr));
2568
2569                      Init_Typ := Create_Itype (Ekind (Anc_Typ), N);
2570
2571                      Subt_Decl :=
2572                        Make_Subtype_Declaration (Loc,
2573                          Defining_Identifier => Init_Typ,
2574                          Subtype_Indication  => New_Indic);
2575
2576                      --  Itypes must be analyzed with checks off Declaration
2577                      --  must have a parent for proper handling of subsidiary
2578                      --  actions.
2579
2580                      Set_Parent (Subt_Decl, N);
2581                      Analyze (Subt_Decl, Suppress => All_Checks);
2582                   end;
2583                end if;
2584
2585                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2586                Set_Assignment_OK (Ref);
2587
2588                if not Is_Interface (Init_Typ) then
2589                   Append_List_To (L,
2590                     Build_Initialization_Call (Loc,
2591                       Id_Ref            => Ref,
2592                       Typ               => Init_Typ,
2593                       In_Init_Proc      => Within_Init_Proc,
2594                       With_Default_Init => Has_Default_Init_Comps (N)
2595                                              or else
2596                                            Has_Task (Base_Type (Init_Typ))));
2597
2598                   if Is_Constrained (Entity (A))
2599                     and then Has_Discriminants (Entity (A))
2600                   then
2601                      Check_Ancestor_Discriminants (Entity (A));
2602                   end if;
2603                end if;
2604
2605             --  Handle calls to C++ constructors
2606
2607             elsif Is_CPP_Constructor_Call (A) then
2608                Init_Typ := Etype (A);
2609                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2610                Set_Assignment_OK (Ref);
2611
2612                Append_List_To (L,
2613                  Build_Initialization_Call (Loc,
2614                    Id_Ref            => Ref,
2615                    Typ               => Init_Typ,
2616                    In_Init_Proc      => Within_Init_Proc,
2617                    With_Default_Init => Has_Default_Init_Comps (N),
2618                    Constructor_Ref   => A));
2619
2620             --  Ada 2005 (AI-287): If the ancestor part is an aggregate of
2621             --  limited type, a recursive call expands the ancestor. Note that
2622             --  in the limited case, the ancestor part must be either a
2623             --  function call (possibly qualified, or wrapped in an unchecked
2624             --  conversion) or aggregate (definitely qualified).
2625             --  The ancestor part can also be a function call (that may be
2626             --  transformed into an explicit dereference) or a qualification
2627             --  of one such.
2628
2629             elsif Is_Limited_Type (Etype (A))
2630               and then Nkind_In (Unqualify (A), N_Aggregate,
2631                                                 N_Extension_Aggregate)
2632             then
2633                Ancestor_Is_Expression := True;
2634
2635                --  Set up  finalization data for enclosing record, because
2636                --  controlled subcomponents of the ancestor part will be
2637                --  attached to it.
2638
2639                Gen_Ctrl_Actions_For_Aggr;
2640
2641                Append_List_To (L,
2642                   Build_Record_Aggr_Code (
2643                     N                             => Unqualify (A),
2644                     Typ                           => Etype (Unqualify (A)),
2645                     Lhs                           => Target,
2646                     Flist                         => Flist,
2647                     Obj                           => Obj,
2648                     Is_Limited_Ancestor_Expansion => True));
2649
2650             --  If the ancestor part is an expression "E", we generate
2651
2652             --     T(tmp) := E;
2653
2654             --  In Ada 2005, this includes the case of a (possibly qualified)
2655             --  limited function call. The assignment will turn into a
2656             --  build-in-place function call (for further details, see
2657             --  Make_Build_In_Place_Call_In_Assignment).
2658
2659             else
2660                Ancestor_Is_Expression := True;
2661                Init_Typ := Etype (A);
2662
2663                --  If the ancestor part is an aggregate, force its full
2664                --  expansion, which was delayed.
2665
2666                if Nkind_In (Unqualify (A), N_Aggregate,
2667                                            N_Extension_Aggregate)
2668                then
2669                   Set_Analyzed (A, False);
2670                   Set_Analyzed (Expression (A), False);
2671                end if;
2672
2673                Ref := Convert_To (Init_Typ, New_Copy_Tree (Target));
2674                Set_Assignment_OK (Ref);
2675
2676                --  Make the assignment without usual controlled actions since
2677                --  we only want the post adjust but not the pre finalize here
2678                --  Add manual adjust when necessary.
2679
2680                Assign := New_List (
2681                  Make_OK_Assignment_Statement (Loc,
2682                    Name       => Ref,
2683                    Expression => A));
2684                Set_No_Ctrl_Actions (First (Assign));
2685
2686                --  Assign the tag now to make sure that the dispatching call in
2687                --  the subsequent deep_adjust works properly (unless VM_Target,
2688                --  where tags are implicit).
2689
2690                if Tagged_Type_Expansion then
2691                   Instr :=
2692                     Make_OK_Assignment_Statement (Loc,
2693                       Name =>
2694                         Make_Selected_Component (Loc,
2695                           Prefix => New_Copy_Tree (Target),
2696                           Selector_Name =>
2697                             New_Reference_To
2698                               (First_Tag_Component (Base_Type (Typ)), Loc)),
2699
2700                       Expression =>
2701                         Unchecked_Convert_To (RTE (RE_Tag),
2702                           New_Reference_To
2703                             (Node (First_Elmt
2704                                (Access_Disp_Table (Base_Type (Typ)))),
2705                              Loc)));
2706
2707                   Set_Assignment_OK (Name (Instr));
2708                   Append_To (Assign, Instr);
2709
2710                   --  Ada 2005 (AI-251): If tagged type has progenitors we must
2711                   --  also initialize tags of the secondary dispatch tables.
2712
2713                   if Has_Interfaces (Base_Type (Typ)) then
2714                      Init_Secondary_Tags
2715                        (Typ        => Base_Type (Typ),
2716                         Target     => Target,
2717                         Stmts_List => Assign);
2718                   end if;
2719                end if;
2720
2721                --  Call Adjust manually
2722
2723                if Needs_Finalization (Etype (A))
2724                  and then not Is_Limited_Type (Etype (A))
2725                then
2726                   Append_List_To (Assign,
2727                     Make_Adjust_Call (
2728                       Ref         => New_Copy_Tree (Ref),
2729                       Typ         => Etype (A),
2730                       Flist_Ref   => New_Reference_To (
2731                         RTE (RE_Global_Final_List), Loc),
2732                       With_Attach => Make_Integer_Literal (Loc, 0)));
2733                end if;
2734
2735                Append_To (L,
2736                  Make_Unsuppress_Block (Loc, Name_Discriminant_Check, Assign));
2737
2738                if Has_Discriminants (Init_Typ) then
2739                   Check_Ancestor_Discriminants (Init_Typ);
2740                end if;
2741             end if;
2742          end;
2743
2744       --  Normal case (not an extension aggregate)
2745
2746       else
2747          --  Generate the discriminant expressions, component by component.
2748          --  If the base type is an unchecked union, the discriminants are
2749          --  unknown to the back-end and absent from a value of the type, so
2750          --  assignments for them are not emitted.
2751
2752          if Has_Discriminants (Typ)
2753            and then not Is_Unchecked_Union (Base_Type (Typ))
2754          then
2755             --  If the type is derived, and constrains discriminants of the
2756             --  parent type, these discriminants are not components of the
2757             --  aggregate, and must be initialized explicitly. They are not
2758             --  visible components of the object, but can become visible with
2759             --  a view conversion to the ancestor.
2760
2761             declare
2762                Btype      : Entity_Id;
2763                Parent_Type : Entity_Id;
2764                Disc        : Entity_Id;
2765                Discr_Val   : Elmt_Id;
2766
2767             begin
2768                Btype := Base_Type (Typ);
2769                while Is_Derived_Type (Btype)
2770                   and then Present (Stored_Constraint (Btype))
2771                loop
2772                   Parent_Type := Etype (Btype);
2773
2774                   Disc := First_Discriminant (Parent_Type);
2775                   Discr_Val :=
2776                     First_Elmt (Stored_Constraint (Base_Type (Typ)));
2777                   while Present (Discr_Val) loop
2778
2779                      --  Only those discriminants of the parent that are not
2780                      --  renamed by discriminants of the derived type need to
2781                      --  be added explicitly.
2782
2783                      if not Is_Entity_Name (Node (Discr_Val))
2784                        or else
2785                          Ekind (Entity (Node (Discr_Val))) /= E_Discriminant
2786                      then
2787                         Comp_Expr :=
2788                           Make_Selected_Component (Loc,
2789                             Prefix        => New_Copy_Tree (Target),
2790                             Selector_Name => New_Occurrence_Of (Disc, Loc));
2791
2792                         Instr :=
2793                           Make_OK_Assignment_Statement (Loc,
2794                             Name       => Comp_Expr,
2795                             Expression => New_Copy_Tree (Node (Discr_Val)));
2796
2797                         Set_No_Ctrl_Actions (Instr);
2798                         Append_To (L, Instr);
2799                      end if;
2800
2801                      Next_Discriminant (Disc);
2802                      Next_Elmt (Discr_Val);
2803                   end loop;
2804
2805                   Btype := Base_Type (Parent_Type);
2806                end loop;
2807             end;
2808
2809             --  Generate discriminant init values for the visible discriminants
2810
2811             declare
2812                Discriminant : Entity_Id;
2813                Discriminant_Value : Node_Id;
2814
2815             begin
2816                Discriminant := First_Stored_Discriminant (Typ);
2817                while Present (Discriminant) loop
2818                   Comp_Expr :=
2819                     Make_Selected_Component (Loc,
2820                       Prefix        => New_Copy_Tree (Target),
2821                       Selector_Name => New_Occurrence_Of (Discriminant, Loc));
2822
2823                   Discriminant_Value :=
2824                     Get_Discriminant_Value (
2825                       Discriminant,
2826                       N_Typ,
2827                       Discriminant_Constraint (N_Typ));
2828
2829                   Instr :=
2830                     Make_OK_Assignment_Statement (Loc,
2831                       Name       => Comp_Expr,
2832                       Expression => New_Copy_Tree (Discriminant_Value));
2833
2834                   Set_No_Ctrl_Actions (Instr);
2835                   Append_To (L, Instr);
2836
2837                   Next_Stored_Discriminant (Discriminant);
2838                end loop;
2839             end;
2840          end if;
2841       end if;
2842
2843       --  For CPP types we generate an implicit call to the C++ default
2844       --  constructor to ensure the proper initialization of the _Tag
2845       --  component.
2846
2847       if Is_CPP_Class (Root_Type (Typ))
2848         and then CPP_Num_Prims (Typ) > 0
2849       then
2850          Invoke_Constructor : declare
2851             CPP_Parent : constant Entity_Id :=
2852                            Enclosing_CPP_Parent (Typ);
2853
2854             procedure Invoke_IC_Proc (T : Entity_Id);
2855             --  Recursive routine used to climb to parents. Required because
2856             --  parents must be initialized before descendants to ensure
2857             --  propagation of inherited C++ slots.
2858
2859             --------------------
2860             -- Invoke_IC_Proc --
2861             --------------------
2862
2863             procedure Invoke_IC_Proc (T : Entity_Id) is
2864             begin
2865                --  Avoid generating extra calls. Initialization required
2866                --  only for types defined from the level of derivation of
2867                --  type of the constructor and the type of the aggregate.
2868
2869                if T = CPP_Parent then
2870                   return;
2871                end if;
2872
2873                Invoke_IC_Proc (Etype (T));
2874
2875                --  Generate call to the IC routine
2876
2877                if Present (CPP_Init_Proc (T)) then
2878                   Append_To (L,
2879                     Make_Procedure_Call_Statement (Loc,
2880                       New_Reference_To (CPP_Init_Proc (T), Loc)));
2881                end if;
2882             end Invoke_IC_Proc;
2883
2884          --  Start of processing for Invoke_Constructor
2885
2886          begin
2887             --  Implicit invocation of the C++ constructor
2888
2889             if Nkind (N) = N_Aggregate then
2890                Append_To (L,
2891                  Make_Procedure_Call_Statement (Loc,
2892                    Name =>
2893                      New_Reference_To
2894                        (Base_Init_Proc (CPP_Parent), Loc),
2895                    Parameter_Associations => New_List (
2896                      Unchecked_Convert_To (CPP_Parent,
2897                        New_Copy_Tree (Lhs)))));
2898             end if;
2899
2900             Invoke_IC_Proc (Typ);
2901          end Invoke_Constructor;
2902       end if;
2903
2904       --  Generate the assignments, component by component
2905
2906       --    tmp.comp1 := Expr1_From_Aggr;
2907       --    tmp.comp2 := Expr2_From_Aggr;
2908       --    ....
2909
2910       Comp := First (Component_Associations (N));
2911       while Present (Comp) loop
2912          Selector := Entity (First (Choices (Comp)));
2913
2914          --  C++ constructors
2915
2916          if Is_CPP_Constructor_Call (Expression (Comp)) then
2917             Append_List_To (L,
2918               Build_Initialization_Call (Loc,
2919                 Id_Ref            => Make_Selected_Component (Loc,
2920                                        Prefix        => New_Copy_Tree (Target),
2921                                        Selector_Name =>
2922                                          New_Occurrence_Of (Selector, Loc)),
2923                 Typ               => Etype (Selector),
2924                 Enclos_Type       => Typ,
2925                 With_Default_Init => True,
2926                 Constructor_Ref   => Expression (Comp)));
2927
2928          --  Ada 2005 (AI-287): For each default-initialized component generate
2929          --  a call to the corresponding IP subprogram if available.
2930
2931          elsif Box_Present (Comp)
2932            and then Has_Non_Null_Base_Init_Proc (Etype (Selector))
2933          then
2934             if Ekind (Selector) /= E_Discriminant then
2935                Gen_Ctrl_Actions_For_Aggr;
2936             end if;
2937
2938             --  Ada 2005 (AI-287): If the component type has tasks then
2939             --  generate the activation chain and master entities (except
2940             --  in case of an allocator because in that case these entities
2941             --  are generated by Build_Task_Allocate_Block_With_Init_Stmts).
2942
2943             declare
2944                Ctype            : constant Entity_Id := Etype (Selector);
2945                Inside_Allocator : Boolean            := False;
2946                P                : Node_Id            := Parent (N);
2947
2948             begin
2949                if Is_Task_Type (Ctype) or else Has_Task (Ctype) then
2950                   while Present (P) loop
2951                      if Nkind (P) = N_Allocator then
2952                         Inside_Allocator := True;
2953                         exit;
2954                      end if;
2955
2956                      P := Parent (P);
2957                   end loop;
2958
2959                   if not Inside_Init_Proc and not Inside_Allocator then
2960                      Build_Activation_Chain_Entity (N);
2961                   end if;
2962                end if;
2963             end;
2964
2965             Append_List_To (L,
2966               Build_Initialization_Call (Loc,
2967                 Id_Ref            => Make_Selected_Component (Loc,
2968                                        Prefix        => New_Copy_Tree (Target),
2969                                        Selector_Name =>
2970                                          New_Occurrence_Of (Selector, Loc)),
2971                 Typ               => Etype (Selector),
2972                 Enclos_Type       => Typ,
2973                 With_Default_Init => True));
2974
2975          --  Prepare for component assignment
2976
2977          elsif Ekind (Selector) /= E_Discriminant
2978            or else Nkind (N) = N_Extension_Aggregate
2979          then
2980             --  All the discriminants have now been assigned
2981
2982             --  This is now a good moment to initialize and attach all the
2983             --  controllers. Their position may depend on the discriminants.
2984
2985             if Ekind (Selector) /= E_Discriminant then
2986                Gen_Ctrl_Actions_For_Aggr;
2987             end if;
2988
2989             Comp_Type := Underlying_Type (Etype (Selector));
2990             Comp_Expr :=
2991               Make_Selected_Component (Loc,
2992                 Prefix        => New_Copy_Tree (Target),
2993                 Selector_Name => New_Occurrence_Of (Selector, Loc));
2994
2995             if Nkind (Expression (Comp)) = N_Qualified_Expression then
2996                Expr_Q := Expression (Expression (Comp));
2997             else
2998                Expr_Q := Expression (Comp);
2999             end if;
3000
3001             --  The controller is the one of the parent type defining the
3002             --  component (in case of inherited components).
3003
3004             if Needs_Finalization (Comp_Type) then
3005                Internal_Final_List :=
3006                  Make_Selected_Component (Loc,
3007                    Prefix        => Convert_To
3008                      (Scope (Original_Record_Component (Selector)),
3009                       New_Copy_Tree (Target)),
3010                    Selector_Name => Make_Identifier (Loc, Name_uController));
3011
3012                Internal_Final_List :=
3013                  Make_Selected_Component (Loc,
3014                    Prefix        => Internal_Final_List,
3015                    Selector_Name => Make_Identifier (Loc, Name_F));
3016
3017                --  The internal final list can be part of a constant object
3018
3019                Set_Assignment_OK (Internal_Final_List);
3020
3021             else
3022                Internal_Final_List := Empty;
3023             end if;
3024
3025             --  Now either create the assignment or generate the code for the
3026             --  inner aggregate top-down.
3027
3028             if Is_Delayed_Aggregate (Expr_Q) then
3029
3030                --  We have the following case of aggregate nesting inside
3031                --  an object declaration:
3032
3033                --    type Arr_Typ is array (Integer range <>) of ...;
3034
3035                --    type Rec_Typ (...) is record
3036                --       Obj_Arr_Typ : Arr_Typ (A .. B);
3037                --    end record;
3038
3039                --    Obj_Rec_Typ : Rec_Typ := (...,
3040                --      Obj_Arr_Typ => (X => (...), Y => (...)));
3041
3042                --  The length of the ranges of the aggregate and Obj_Add_Typ
3043                --  are equal (B - A = Y - X), but they do not coincide (X /=
3044                --  A and B /= Y). This case requires array sliding which is
3045                --  performed in the following manner:
3046
3047                --    subtype Arr_Sub is Arr_Typ (X .. Y);
3048                --    Temp : Arr_Sub;
3049                --    Temp (X) := (...);
3050                --    ...
3051                --    Temp (Y) := (...);
3052                --    Obj_Rec_Typ.Obj_Arr_Typ := Temp;
3053
3054                if Ekind (Comp_Type) = E_Array_Subtype
3055                  and then Is_Int_Range_Bounds (Aggregate_Bounds (Expr_Q))
3056                  and then Is_Int_Range_Bounds (First_Index (Comp_Type))
3057                  and then not
3058                    Compatible_Int_Bounds
3059                      (Agg_Bounds => Aggregate_Bounds (Expr_Q),
3060                       Typ_Bounds => First_Index (Comp_Type))
3061                then
3062                   --  Create the array subtype with bounds equal to those of
3063                   --  the corresponding aggregate.
3064
3065                   declare
3066                      SubE : constant Entity_Id := Make_Temporary (Loc, 'T');
3067
3068                      SubD : constant Node_Id :=
3069                               Make_Subtype_Declaration (Loc,
3070                                 Defining_Identifier => SubE,
3071                                 Subtype_Indication  =>
3072                                   Make_Subtype_Indication (Loc,
3073                                     Subtype_Mark =>
3074                                       New_Reference_To
3075                                         (Etype (Comp_Type), Loc),
3076                                     Constraint =>
3077                                       Make_Index_Or_Discriminant_Constraint
3078                                         (Loc,
3079                                          Constraints => New_List (
3080                                           New_Copy_Tree
3081                                             (Aggregate_Bounds (Expr_Q))))));
3082
3083                      --  Create a temporary array of the above subtype which
3084                      --  will be used to capture the aggregate assignments.
3085
3086                      TmpE : constant Entity_Id := Make_Temporary (Loc, 'A', N);
3087
3088                      TmpD : constant Node_Id :=
3089                               Make_Object_Declaration (Loc,
3090                                 Defining_Identifier => TmpE,
3091                                 Object_Definition   =>
3092                                   New_Reference_To (SubE, Loc));
3093
3094                   begin
3095                      Set_No_Initialization (TmpD);
3096                      Append_To (L, SubD);
3097                      Append_To (L, TmpD);
3098
3099                      --  Expand aggregate into assignments to the temp array
3100
3101                      Append_List_To (L,
3102                        Late_Expansion (Expr_Q, Comp_Type,
3103                          New_Reference_To (TmpE, Loc), Internal_Final_List));
3104
3105                      --  Slide
3106
3107                      Append_To (L,
3108                        Make_Assignment_Statement (Loc,
3109                          Name       => New_Copy_Tree (Comp_Expr),
3110                          Expression => New_Reference_To (TmpE, Loc)));
3111
3112                      --  Do not pass the original aggregate to Gigi as is,
3113                      --  since it will potentially clobber the front or the end
3114                      --  of the array. Setting the expression to empty is safe
3115                      --  since all aggregates are expanded into assignments.
3116
3117                      if Present (Obj) then
3118                         Set_Expression (Parent (Obj), Empty);
3119                      end if;
3120                   end;
3121
3122                --  Normal case (sliding not required)
3123
3124                else
3125                   Append_List_To (L,
3126                     Late_Expansion (Expr_Q, Comp_Type, Comp_Expr,
3127                       Internal_Final_List));
3128                end if;
3129
3130             --  Expr_Q is not delayed aggregate
3131
3132             else
3133                if Has_Discriminants (Typ) then
3134                   Replace_Discriminants (Expr_Q);
3135                end if;
3136
3137                Instr :=
3138                  Make_OK_Assignment_Statement (Loc,
3139                    Name       => Comp_Expr,
3140                    Expression => Expr_Q);
3141
3142                Set_No_Ctrl_Actions (Instr);
3143                Append_To (L, Instr);
3144
3145                --  Adjust the tag if tagged (because of possible view
3146                --  conversions), unless compiling for a VM where tags are
3147                --  implicit.
3148
3149                --    tmp.comp._tag := comp_typ'tag;
3150
3151                if Is_Tagged_Type (Comp_Type)
3152                  and then Tagged_Type_Expansion
3153                then
3154                   Instr :=
3155                     Make_OK_Assignment_Statement (Loc,
3156                       Name =>
3157                         Make_Selected_Component (Loc,
3158                           Prefix =>  New_Copy_Tree (Comp_Expr),
3159                           Selector_Name =>
3160                             New_Reference_To
3161                               (First_Tag_Component (Comp_Type), Loc)),
3162
3163                       Expression =>
3164                         Unchecked_Convert_To (RTE (RE_Tag),
3165                           New_Reference_To
3166                             (Node (First_Elmt (Access_Disp_Table (Comp_Type))),
3167                              Loc)));
3168
3169                   Append_To (L, Instr);
3170                end if;
3171
3172                --  Adjust and Attach the component to the proper controller
3173
3174                --     Adjust (tmp.comp);
3175                --     Attach_To_Final_List (tmp.comp,
3176                --       comp_typ (tmp)._record_controller.f)
3177
3178                if Needs_Finalization (Comp_Type)
3179                  and then not Is_Limited_Type (Comp_Type)
3180                then
3181                   Append_List_To (L,
3182                     Make_Adjust_Call (
3183                       Ref         => New_Copy_Tree (Comp_Expr),
3184                       Typ         => Comp_Type,
3185                       Flist_Ref   => Internal_Final_List,
3186                       With_Attach => Make_Integer_Literal (Loc, 1)));
3187                end if;
3188             end if;
3189
3190          --  ???
3191
3192          elsif Ekind (Selector) = E_Discriminant
3193            and then Nkind (N) /= N_Extension_Aggregate
3194            and then Nkind (Parent (N)) = N_Component_Association
3195            and then Is_Constrained (Typ)
3196          then
3197             --  We must check that the discriminant value imposed by the
3198             --  context is the same as the value given in the subaggregate,
3199             --  because after the expansion into assignments there is no
3200             --  record on which to perform a regular discriminant check.
3201
3202             declare
3203                D_Val : Elmt_Id;
3204                Disc  : Entity_Id;
3205
3206             begin
3207                D_Val := First_Elmt (Discriminant_Constraint (Typ));
3208                Disc  := First_Discriminant (Typ);
3209                while Chars (Disc) /= Chars (Selector) loop
3210                   Next_Discriminant (Disc);
3211                   Next_Elmt (D_Val);
3212                end loop;
3213
3214                pragma Assert (Present (D_Val));
3215
3216                --  This check cannot performed for components that are
3217                --  constrained by a current instance, because this is not a
3218                --  value that can be compared with the actual constraint.
3219
3220                if Nkind (Node (D_Val)) /= N_Attribute_Reference
3221                  or else not Is_Entity_Name (Prefix (Node (D_Val)))
3222                  or else not Is_Type (Entity (Prefix (Node (D_Val))))
3223                then
3224                   Append_To (L,
3225                   Make_Raise_Constraint_Error (Loc,
3226                     Condition =>
3227                       Make_Op_Ne (Loc,
3228                         Left_Opnd => New_Copy_Tree (Node (D_Val)),
3229                         Right_Opnd => Expression (Comp)),
3230                       Reason => CE_Discriminant_Check_Failed));
3231
3232                else
3233                   --  Find self-reference in previous discriminant assignment,
3234                   --  and replace with proper expression.
3235
3236                   declare
3237                      Ass : Node_Id;
3238
3239                   begin
3240                      Ass := First (L);
3241                      while Present (Ass) loop
3242                         if Nkind (Ass) = N_Assignment_Statement
3243                           and then Nkind (Name (Ass)) = N_Selected_Component
3244                           and then Chars (Selector_Name (Name (Ass))) =
3245                              Chars (Disc)
3246                         then
3247                            Set_Expression
3248                              (Ass, New_Copy_Tree (Expression (Comp)));
3249                            exit;
3250                         end if;
3251                         Next (Ass);
3252                      end loop;
3253                   end;
3254                end if;
3255             end;
3256          end if;
3257
3258          Next (Comp);
3259       end loop;
3260
3261       --  If the type is tagged, the tag needs to be initialized (unless
3262       --  compiling for the Java VM where tags are implicit). It is done
3263       --  late in the initialization process because in some cases, we call
3264       --  the init proc of an ancestor which will not leave out the right tag
3265
3266       if Ancestor_Is_Expression then
3267          null;
3268
3269       --  For CPP types we generated a call to the C++ default constructor
3270       --  before the components have been initialized to ensure the proper
3271       --  initialization of the _Tag component (see above).
3272
3273       elsif Is_CPP_Class (Typ) then
3274          null;
3275
3276       elsif Is_Tagged_Type (Typ) and then Tagged_Type_Expansion then
3277          Instr :=
3278            Make_OK_Assignment_Statement (Loc,
3279              Name =>
3280                Make_Selected_Component (Loc,
3281                  Prefix => New_Copy_Tree (Target),
3282                  Selector_Name =>
3283                    New_Reference_To
3284                      (First_Tag_Component (Base_Type (Typ)), Loc)),
3285
3286              Expression =>
3287                Unchecked_Convert_To (RTE (RE_Tag),
3288                  New_Reference_To
3289                    (Node (First_Elmt (Access_Disp_Table (Base_Type (Typ)))),
3290                     Loc)));
3291
3292          Append_To (L, Instr);
3293
3294          --  Ada 2005 (AI-251): If the tagged type has been derived from
3295          --  abstract interfaces we must also initialize the tags of the
3296          --  secondary dispatch tables.
3297
3298          if Has_Interfaces (Base_Type (Typ)) then
3299             Init_Secondary_Tags
3300               (Typ        => Base_Type (Typ),
3301                Target     => Target,
3302                Stmts_List => L);
3303          end if;
3304       end if;
3305
3306       --  If the controllers have not been initialized yet (by lack of non-
3307       --  discriminant components), let's do it now.
3308
3309       Gen_Ctrl_Actions_For_Aggr;
3310
3311       return L;
3312    end Build_Record_Aggr_Code;
3313
3314    -------------------------------
3315    -- Convert_Aggr_In_Allocator --
3316    -------------------------------
3317
3318    procedure Convert_Aggr_In_Allocator
3319      (Alloc :  Node_Id;
3320       Decl  :  Node_Id;
3321       Aggr  :  Node_Id)
3322    is
3323       Loc  : constant Source_Ptr := Sloc (Aggr);
3324       Typ  : constant Entity_Id  := Etype (Aggr);
3325       Temp : constant Entity_Id  := Defining_Identifier (Decl);
3326
3327       Occ  : constant Node_Id :=
3328                Unchecked_Convert_To (Typ,
3329                  Make_Explicit_Dereference (Loc,
3330                    New_Reference_To (Temp, Loc)));
3331
3332       Access_Type : constant Entity_Id := Etype (Temp);
3333       Flist       : Entity_Id;
3334
3335    begin
3336       --  If the allocator is for an access discriminant, there is no
3337       --  finalization list for the anonymous access type, and the eventual
3338       --  finalization of the object is handled through the coextension
3339       --  mechanism. If the enclosing object is not dynamically allocated,
3340       --  the access discriminant is itself placed on the stack. Otherwise,
3341       --  some other finalization list is used (see exp_ch4.adb).
3342
3343       --  Decl has been inserted in the code ahead of the allocator, using
3344       --  Insert_Actions. We use Insert_Actions below as well, to ensure that
3345       --  subsequent insertions are done in the proper order. Using (for
3346       --  example) Insert_Actions_After to place the expanded aggregate
3347       --  immediately after Decl may lead to out-of-order references if the
3348       --  allocator has generated a finalization list, as when the designated
3349       --  object is controlled and there is an open transient scope.
3350
3351       if Ekind (Access_Type) = E_Anonymous_Access_Type
3352         and then Nkind (Associated_Node_For_Itype (Access_Type)) =
3353                                               N_Discriminant_Specification
3354       then
3355          Flist := Empty;
3356
3357       elsif Needs_Finalization (Typ) then
3358          Flist := Find_Final_List (Access_Type);
3359
3360       --  Otherwise there are no controlled actions to be performed.
3361
3362       else
3363          Flist := Empty;
3364       end if;
3365
3366       if Is_Array_Type (Typ) then
3367          Convert_Array_Aggr_In_Allocator (Decl, Aggr, Occ);
3368
3369       elsif Has_Default_Init_Comps (Aggr) then
3370          declare
3371             L          : constant List_Id := New_List;
3372             Init_Stmts : List_Id;
3373
3374          begin
3375             Init_Stmts :=
3376               Late_Expansion
3377                 (Aggr, Typ, Occ,
3378                  Flist,
3379                  Associated_Final_Chain (Base_Type (Access_Type)));
3380
3381             --  ??? Dubious actual for Obj: expect 'the original object being
3382             --  initialized'
3383
3384             if Has_Task (Typ) then
3385                Build_Task_Allocate_Block_With_Init_Stmts (L, Aggr, Init_Stmts);
3386                Insert_Actions (Alloc, L);
3387             else
3388                Insert_Actions (Alloc, Init_Stmts);
3389             end if;
3390          end;
3391
3392       else
3393          Insert_Actions (Alloc,
3394            Late_Expansion
3395              (Aggr, Typ, Occ, Flist,
3396               Associated_Final_Chain (Base_Type (Access_Type))));
3397
3398          --  ??? Dubious actual for Obj: expect 'the original object being
3399          --  initialized'
3400
3401       end if;
3402    end Convert_Aggr_In_Allocator;
3403
3404    --------------------------------
3405    -- Convert_Aggr_In_Assignment --
3406    --------------------------------
3407
3408    procedure Convert_Aggr_In_Assignment (N : Node_Id) is
3409       Aggr : Node_Id            := Expression (N);
3410       Typ  : constant Entity_Id := Etype (Aggr);
3411       Occ  : constant Node_Id   := New_Copy_Tree (Name (N));
3412
3413    begin
3414       if Nkind (Aggr) = N_Qualified_Expression then
3415          Aggr := Expression (Aggr);
3416       end if;
3417
3418       Insert_Actions_After (N,
3419         Late_Expansion
3420           (Aggr, Typ, Occ,
3421            Find_Final_List (Typ, New_Copy_Tree (Occ))));
3422    end Convert_Aggr_In_Assignment;
3423
3424    ---------------------------------
3425    -- Convert_Aggr_In_Object_Decl --
3426    ---------------------------------
3427
3428    procedure Convert_Aggr_In_Object_Decl (N : Node_Id) is
3429       Obj  : constant Entity_Id  := Defining_Identifier (N);
3430       Aggr : Node_Id             := Expression (N);
3431       Loc  : constant Source_Ptr := Sloc (Aggr);
3432       Typ  : constant Entity_Id  := Etype (Aggr);
3433       Occ  : constant Node_Id    := New_Occurrence_Of (Obj, Loc);
3434
3435       function Discriminants_Ok return Boolean;
3436       --  If the object type is constrained, the discriminants in the
3437       --  aggregate must be checked against the discriminants of the subtype.
3438       --  This cannot be done using Apply_Discriminant_Checks because after
3439       --  expansion there is no aggregate left to check.
3440
3441       ----------------------
3442       -- Discriminants_Ok --
3443       ----------------------
3444
3445       function Discriminants_Ok return Boolean is
3446          Cond  : Node_Id := Empty;
3447          Check : Node_Id;
3448          D     : Entity_Id;
3449          Disc1 : Elmt_Id;
3450          Disc2 : Elmt_Id;
3451          Val1  : Node_Id;
3452          Val2  : Node_Id;
3453
3454       begin
3455          D := First_Discriminant (Typ);
3456          Disc1 := First_Elmt (Discriminant_Constraint (Typ));
3457          Disc2 := First_Elmt (Discriminant_Constraint (Etype (Obj)));
3458          while Present (Disc1) and then Present (Disc2) loop
3459             Val1 := Node (Disc1);
3460             Val2 := Node (Disc2);
3461
3462             if not Is_OK_Static_Expression (Val1)
3463               or else not Is_OK_Static_Expression (Val2)
3464             then
3465                Check := Make_Op_Ne (Loc,
3466                  Left_Opnd  => Duplicate_Subexpr (Val1),
3467                  Right_Opnd => Duplicate_Subexpr (Val2));
3468
3469                if No (Cond) then
3470                   Cond := Check;
3471
3472                else
3473                   Cond := Make_Or_Else (Loc,
3474                     Left_Opnd => Cond,
3475                     Right_Opnd => Check);
3476                end if;
3477
3478             elsif Expr_Value (Val1) /= Expr_Value (Val2) then
3479                Apply_Compile_Time_Constraint_Error (Aggr,
3480                  Msg    => "incorrect value for discriminant&?",
3481                  Reason => CE_Discriminant_Check_Failed,
3482                  Ent    => D);
3483                return False;
3484             end if;
3485
3486             Next_Discriminant (D);
3487             Next_Elmt (Disc1);
3488             Next_Elmt (Disc2);
3489          end loop;
3490
3491          --  If any discriminant constraint is non-static, emit a check
3492
3493          if Present (Cond) then
3494             Insert_Action (N,
3495               Make_Raise_Constraint_Error (Loc,
3496                 Condition => Cond,
3497                 Reason => CE_Discriminant_Check_Failed));
3498          end if;
3499
3500          return True;
3501       end Discriminants_Ok;
3502
3503    --  Start of processing for Convert_Aggr_In_Object_Decl
3504
3505    begin
3506       Set_Assignment_OK (Occ);
3507
3508       if Nkind (Aggr) = N_Qualified_Expression then
3509          Aggr := Expression (Aggr);
3510       end if;
3511
3512       if Has_Discriminants (Typ)
3513         and then Typ /= Etype (Obj)
3514         and then Is_Constrained (Etype (Obj))
3515         and then not Discriminants_Ok
3516       then
3517          return;
3518       end if;
3519
3520       --  If the context is an extended return statement, it has its own
3521       --  finalization machinery (i.e. works like a transient scope) and
3522       --  we do not want to create an additional one, because objects on
3523       --  the finalization list of the return must be moved to the caller's
3524       --  finalization list to complete the return.
3525
3526       --  However, if the aggregate is limited, it is built in place, and the
3527       --  controlled components are not assigned to intermediate temporaries
3528       --  so there is no need for a transient scope in this case either.
3529
3530       if Requires_Transient_Scope (Typ)
3531         and then Ekind (Current_Scope) /= E_Return_Statement
3532         and then not Is_Limited_Type (Typ)
3533       then
3534          Establish_Transient_Scope
3535            (Aggr,
3536             Sec_Stack =>
3537               Is_Controlled (Typ) or else Has_Controlled_Component (Typ));
3538       end if;
3539
3540       Insert_Actions_After (N, Late_Expansion (Aggr, Typ, Occ, Obj => Obj));
3541       Set_No_Initialization (N);
3542       Initialize_Discriminants (N, Typ);
3543    end Convert_Aggr_In_Object_Decl;
3544
3545    -------------------------------------
3546    -- Convert_Array_Aggr_In_Allocator --
3547    -------------------------------------
3548
3549    procedure Convert_Array_Aggr_In_Allocator
3550      (Decl   : Node_Id;
3551       Aggr   : Node_Id;
3552       Target : Node_Id)
3553    is
3554       Aggr_Code : List_Id;
3555       Typ       : constant Entity_Id := Etype (Aggr);
3556       Ctyp      : constant Entity_Id := Component_Type (Typ);
3557
3558    begin
3559       --  The target is an explicit dereference of the allocated object.
3560       --  Generate component assignments to it, as for an aggregate that
3561       --  appears on the right-hand side of an assignment statement.
3562
3563       Aggr_Code :=
3564         Build_Array_Aggr_Code (Aggr,
3565           Ctype       => Ctyp,
3566           Index       => First_Index (Typ),
3567           Into        => Target,
3568           Scalar_Comp => Is_Scalar_Type (Ctyp));
3569
3570       Insert_Actions_After (Decl, Aggr_Code);
3571    end Convert_Array_Aggr_In_Allocator;
3572
3573    ----------------------------
3574    -- Convert_To_Assignments --
3575    ----------------------------
3576
3577    procedure Convert_To_Assignments (N : Node_Id; Typ : Entity_Id) is
3578       Loc  : constant Source_Ptr := Sloc (N);
3579       T    : Entity_Id;
3580       Temp : Entity_Id;
3581
3582       Instr       : Node_Id;
3583       Target_Expr : Node_Id;
3584       Parent_Kind : Node_Kind;
3585       Unc_Decl    : Boolean := False;
3586       Parent_Node : Node_Id;
3587
3588    begin
3589       pragma Assert (not Is_Static_Dispatch_Table_Aggregate (N));
3590       pragma Assert (Is_Record_Type (Typ));
3591
3592       Parent_Node := Parent (N);
3593       Parent_Kind := Nkind (Parent_Node);
3594
3595       if Parent_Kind = N_Qualified_Expression then
3596
3597          --  Check if we are in a unconstrained declaration because in this
3598          --  case the current delayed expansion mechanism doesn't work when
3599          --  the declared object size depend on the initializing expr.
3600
3601          begin
3602             Parent_Node := Parent (Parent_Node);
3603             Parent_Kind := Nkind (Parent_Node);
3604
3605             if Parent_Kind = N_Object_Declaration then
3606                Unc_Decl :=
3607                  not Is_Entity_Name (Object_Definition (Parent_Node))
3608                    or else Has_Discriminants
3609                              (Entity (Object_Definition (Parent_Node)))
3610                    or else Is_Class_Wide_Type
3611                              (Entity (Object_Definition (Parent_Node)));
3612             end if;
3613          end;
3614       end if;
3615
3616       --  Just set the Delay flag in the cases where the transformation will be
3617       --  done top down from above.
3618
3619       if False
3620
3621          --  Internal aggregate (transformed when expanding the parent)
3622
3623          or else Parent_Kind = N_Aggregate
3624          or else Parent_Kind = N_Extension_Aggregate
3625          or else Parent_Kind = N_Component_Association
3626
3627          --  Allocator (see Convert_Aggr_In_Allocator)
3628
3629          or else Parent_Kind = N_Allocator
3630
3631          --  Object declaration (see Convert_Aggr_In_Object_Decl)
3632
3633          or else (Parent_Kind = N_Object_Declaration and then not Unc_Decl)
3634
3635          --  Safe assignment (see Convert_Aggr_Assignments). So far only the
3636          --  assignments in init procs are taken into account.
3637
3638          or else (Parent_Kind = N_Assignment_Statement
3639                    and then Inside_Init_Proc)
3640
3641          --  (Ada 2005) An inherently limited type in a return statement,
3642          --  which will be handled in a build-in-place fashion, and may be
3643          --  rewritten as an extended return and have its own finalization
3644          --  machinery. In the case of a simple return, the aggregate needs
3645          --  to be delayed until the scope for the return statement has been
3646          --  created, so that any finalization chain will be associated with
3647          --  that scope. For extended returns, we delay expansion to avoid the
3648          --  creation of an unwanted transient scope that could result in
3649          --  premature finalization of the return object (which is built in
3650          --  in place within the caller's scope).
3651
3652          or else
3653            (Is_Immutably_Limited_Type (Typ)
3654              and then
3655                (Nkind (Parent (Parent_Node)) = N_Extended_Return_Statement
3656                  or else Nkind (Parent_Node) = N_Simple_Return_Statement))
3657       then
3658          Set_Expansion_Delayed (N);
3659          return;
3660       end if;
3661
3662       if Requires_Transient_Scope (Typ) then
3663          Establish_Transient_Scope
3664            (N, Sec_Stack =>
3665                  Is_Controlled (Typ) or else Has_Controlled_Component (Typ));
3666       end if;
3667
3668       --  If the aggregate is non-limited, create a temporary. If it is limited
3669       --  and the context is an assignment, this is a subaggregate for an
3670       --  enclosing aggregate being expanded. It must be built in place, so use
3671       --  the target of the current assignment.
3672
3673       if Is_Limited_Type (Typ)
3674         and then Nkind (Parent (N)) = N_Assignment_Statement
3675       then
3676          Target_Expr := New_Copy_Tree (Name (Parent (N)));
3677          Insert_Actions
3678            (Parent (N), Build_Record_Aggr_Code (N, Typ, Target_Expr));
3679          Rewrite (Parent (N), Make_Null_Statement (Loc));
3680
3681       else
3682          Temp := Make_Temporary (Loc, 'A', N);
3683
3684          --  If the type inherits unknown discriminants, use the view with
3685          --  known discriminants if available.
3686
3687          if Has_Unknown_Discriminants (Typ)
3688             and then Present (Underlying_Record_View (Typ))
3689          then
3690             T := Underlying_Record_View (Typ);
3691          else
3692             T := Typ;
3693          end if;
3694
3695          Instr :=
3696            Make_Object_Declaration (Loc,
3697              Defining_Identifier => Temp,
3698              Object_Definition   => New_Occurrence_Of (T, Loc));
3699
3700          Set_No_Initialization (Instr);
3701          Insert_Action (N, Instr);
3702          Initialize_Discriminants (Instr, T);
3703          Target_Expr := New_Occurrence_Of (Temp, Loc);
3704          Insert_Actions (N, Build_Record_Aggr_Code (N, T, Target_Expr));
3705          Rewrite (N, New_Occurrence_Of (Temp, Loc));
3706          Analyze_And_Resolve (N, T);
3707       end if;
3708    end Convert_To_Assignments;
3709
3710    ---------------------------
3711    -- Convert_To_Positional --
3712    ---------------------------
3713
3714    procedure Convert_To_Positional
3715      (N                    : Node_Id;
3716       Max_Others_Replicate : Nat     := 5;
3717       Handle_Bit_Packed    : Boolean := False)
3718    is
3719       Typ : constant Entity_Id := Etype (N);
3720
3721       Static_Components : Boolean := True;
3722
3723       procedure Check_Static_Components;
3724       --  Check whether all components of the aggregate are compile-time known
3725       --  values, and can be passed as is to the back-end without further
3726       --  expansion.
3727
3728       function Flatten
3729         (N   : Node_Id;
3730          Ix  : Node_Id;
3731          Ixb : Node_Id) return Boolean;
3732       --  Convert the aggregate into a purely positional form if possible. On
3733       --  entry the bounds of all dimensions are known to be static, and the
3734       --  total number of components is safe enough to expand.
3735
3736       function Is_Flat (N : Node_Id; Dims : Int) return Boolean;
3737       --  Return True iff the array N is flat (which is not trivial in the case
3738       --  of multidimensional aggregates).
3739
3740       -----------------------------
3741       -- Check_Static_Components --
3742       -----------------------------
3743
3744       procedure Check_Static_Components is
3745          Expr : Node_Id;
3746
3747       begin
3748          Static_Components := True;
3749
3750          if Nkind (N) = N_String_Literal then
3751             null;
3752
3753          elsif Present (Expressions (N)) then
3754             Expr := First (Expressions (N));
3755             while Present (Expr) loop
3756                if Nkind (Expr) /= N_Aggregate
3757                  or else not Compile_Time_Known_Aggregate (Expr)
3758                  or else Expansion_Delayed (Expr)
3759                then
3760                   Static_Components := False;
3761                   exit;
3762                end if;
3763
3764                Next (Expr);
3765             end loop;
3766          end if;
3767
3768          if Nkind (N) = N_Aggregate
3769            and then  Present (Component_Associations (N))
3770          then
3771             Expr := First (Component_Associations (N));
3772             while Present (Expr) loop
3773                if Nkind_In (Expression (Expr), N_Integer_Literal,
3774                                                N_Real_Literal)
3775                then
3776                   null;
3777
3778                elsif Is_Entity_Name (Expression (Expr))
3779                  and then Present (Entity (Expression (Expr)))
3780                  and then Ekind (Entity (Expression (Expr))) =
3781                    E_Enumeration_Literal
3782                then
3783                   null;
3784
3785                elsif Nkind (Expression (Expr)) /= N_Aggregate
3786                  or else not Compile_Time_Known_Aggregate (Expression (Expr))
3787                  or else Expansion_Delayed (Expression (Expr))
3788                then
3789                   Static_Components := False;
3790                   exit;
3791                end if;
3792
3793                Next (Expr);
3794             end loop;
3795          end if;
3796       end Check_Static_Components;
3797
3798       -------------
3799       -- Flatten --
3800       -------------
3801
3802       function Flatten
3803         (N   : Node_Id;
3804          Ix  : Node_Id;
3805          Ixb : Node_Id) return Boolean
3806       is
3807          Loc : constant Source_Ptr := Sloc (N);
3808          Blo : constant Node_Id    := Type_Low_Bound (Etype (Ixb));
3809          Lo  : constant Node_Id    := Type_Low_Bound (Etype (Ix));
3810          Hi  : constant Node_Id    := Type_High_Bound (Etype (Ix));
3811          Lov : Uint;
3812          Hiv : Uint;
3813
3814       begin
3815          if Nkind (Original_Node (N)) = N_String_Literal then
3816             return True;
3817          end if;
3818
3819          if not Compile_Time_Known_Value (Lo)
3820            or else not Compile_Time_Known_Value (Hi)
3821          then
3822             return False;
3823          end if;
3824
3825          Lov := Expr_Value (Lo);
3826          Hiv := Expr_Value (Hi);
3827
3828          if Hiv < Lov
3829            or else not Compile_Time_Known_Value (Blo)
3830          then
3831             return False;
3832          end if;
3833
3834          --  Determine if set of alternatives is suitable for conversion and
3835          --  build an array containing the values in sequence.
3836
3837          declare
3838             Vals : array (UI_To_Int (Lov) .. UI_To_Int (Hiv))
3839                      of Node_Id := (others => Empty);
3840             --  The values in the aggregate sorted appropriately
3841
3842             Vlist : List_Id;
3843             --  Same data as Vals in list form
3844
3845             Rep_Count : Nat;
3846             --  Used to validate Max_Others_Replicate limit
3847
3848             Elmt         : Node_Id;
3849             Num          : Int := UI_To_Int (Lov);
3850             Choice_Index : Int;
3851             Choice       : Node_Id;
3852             Lo, Hi       : Node_Id;
3853
3854          begin
3855             if Present (Expressions (N)) then
3856                Elmt := First (Expressions (N));
3857                while Present (Elmt) loop
3858                   if Nkind (Elmt) = N_Aggregate
3859                     and then Present (Next_Index (Ix))
3860                     and then
3861                       not Flatten (Elmt, Next_Index (Ix), Next_Index (Ixb))
3862                   then
3863                      return False;
3864                   end if;
3865
3866                   Vals (Num) := Relocate_Node (Elmt);
3867                   Num := Num + 1;
3868
3869                   Next (Elmt);
3870                end loop;
3871             end if;
3872
3873             if No (Component_Associations (N)) then
3874                return True;
3875             end if;
3876
3877             Elmt := First (Component_Associations (N));
3878
3879             if Nkind (Expression (Elmt)) = N_Aggregate then
3880                if Present (Next_Index (Ix))
3881                  and then
3882                    not Flatten
3883                         (Expression (Elmt), Next_Index (Ix), Next_Index (Ixb))
3884                then
3885                   return False;
3886                end if;
3887             end if;
3888
3889             Component_Loop : while Present (Elmt) loop
3890                Choice := First (Choices (Elmt));
3891                Choice_Loop : while Present (Choice) loop
3892
3893                   --  If we have an others choice, fill in the missing elements
3894                   --  subject to the limit established by Max_Others_Replicate.
3895
3896                   if Nkind (Choice) = N_Others_Choice then
3897                      Rep_Count := 0;
3898
3899                      for J in Vals'Range loop
3900                         if No (Vals (J)) then
3901                            Vals (J) := New_Copy_Tree (Expression (Elmt));
3902                            Rep_Count := Rep_Count + 1;
3903
3904                            --  Check for maximum others replication. Note that
3905                            --  we skip this test if either of the restrictions
3906                            --  No_Elaboration_Code or No_Implicit_Loops is
3907                            --  active, if this is a preelaborable unit or a
3908                            --  predefined unit. This ensures that predefined
3909                            --  units get the same level of constant folding in
3910                            --  Ada 95 and Ada 05, where their categorization
3911                            --  has changed.
3912
3913                            declare
3914                               P : constant Entity_Id :=
3915                                     Cunit_Entity (Current_Sem_Unit);
3916
3917                            begin
3918                               --  Check if duplication OK and if so continue
3919                               --  processing.
3920
3921                               if Restriction_Active (No_Elaboration_Code)
3922                                 or else Restriction_Active (No_Implicit_Loops)
3923                                 or else Is_Preelaborated (P)
3924                                 or else (Ekind (P) = E_Package_Body
3925                                           and then
3926                                             Is_Preelaborated (Spec_Entity (P)))
3927                                 or else
3928                                   Is_Predefined_File_Name
3929                                     (Unit_File_Name (Get_Source_Unit (P)))
3930                               then
3931                                  null;
3932
3933                               --  If duplication not OK, then we return False
3934                               --  if the replication count is too high
3935
3936                               elsif Rep_Count > Max_Others_Replicate then
3937                                  return False;
3938
3939                               --  Continue on if duplication not OK, but the
3940                               --  replication count is not excessive.
3941
3942                               else
3943                                  null;
3944                               end if;
3945                            end;
3946                         end if;
3947                      end loop;
3948
3949                      exit Component_Loop;
3950
3951                   --  Case of a subtype mark, identifier or expanded name
3952
3953                   elsif Is_Entity_Name (Choice)
3954                     and then Is_Type (Entity (Choice))
3955                   then
3956                      Lo := Type_Low_Bound  (Etype (Choice));
3957                      Hi := Type_High_Bound (Etype (Choice));
3958
3959                   --  Case of subtype indication
3960
3961                   elsif Nkind (Choice) = N_Subtype_Indication then
3962                      Lo := Low_Bound  (Range_Expression (Constraint (Choice)));
3963                      Hi := High_Bound (Range_Expression (Constraint (Choice)));
3964
3965                   --  Case of a range
3966
3967                   elsif Nkind (Choice) = N_Range then
3968                      Lo := Low_Bound (Choice);
3969                      Hi := High_Bound (Choice);
3970
3971                   --  Normal subexpression case
3972
3973                   else pragma Assert (Nkind (Choice) in N_Subexpr);
3974                      if not Compile_Time_Known_Value (Choice) then
3975                         return False;
3976
3977                      else
3978                         Choice_Index := UI_To_Int (Expr_Value (Choice));
3979                         if Choice_Index in Vals'Range then
3980                            Vals (Choice_Index) :=
3981                              New_Copy_Tree (Expression (Elmt));
3982                            goto Continue;
3983
3984                         else
3985                            --  Choice is statically out-of-range, will be
3986                            --  rewritten to raise Constraint_Error.
3987
3988                            return False;
3989                         end if;
3990                      end if;
3991                   end if;
3992
3993                   --  Range cases merge with Lo,Hi set
3994
3995                   if not Compile_Time_Known_Value (Lo)
3996                        or else
3997                      not Compile_Time_Known_Value (Hi)
3998                   then
3999                      return False;
4000                   else
4001                      for J in UI_To_Int (Expr_Value (Lo)) ..
4002                               UI_To_Int (Expr_Value (Hi))
4003                      loop
4004                         Vals (J) := New_Copy_Tree (Expression (Elmt));
4005                      end loop;
4006                   end if;
4007
4008                <<Continue>>
4009                   Next (Choice);
4010                end loop Choice_Loop;
4011
4012                Next (Elmt);
4013             end loop Component_Loop;
4014
4015             --  If we get here the conversion is possible
4016
4017             Vlist := New_List;
4018             for J in Vals'Range loop
4019                Append (Vals (J), Vlist);
4020             end loop;
4021
4022             Rewrite (N, Make_Aggregate (Loc, Expressions => Vlist));
4023             Set_Aggregate_Bounds (N, Aggregate_Bounds (Original_Node (N)));
4024             return True;
4025          end;
4026       end Flatten;
4027
4028       -------------
4029       -- Is_Flat --
4030       -------------
4031
4032       function Is_Flat (N : Node_Id; Dims : Int) return Boolean is
4033          Elmt : Node_Id;
4034
4035       begin
4036          if Dims = 0 then
4037             return True;
4038
4039          elsif Nkind (N) = N_Aggregate then
4040             if Present (Component_Associations (N)) then
4041                return False;
4042
4043             else
4044                Elmt := First (Expressions (N));
4045                while Present (Elmt) loop
4046                   if not Is_Flat (Elmt, Dims - 1) then
4047                      return False;
4048                   end if;
4049
4050                   Next (Elmt);
4051                end loop;
4052
4053                return True;
4054             end if;
4055          else
4056             return True;
4057          end if;
4058       end Is_Flat;
4059
4060    --  Start of processing for Convert_To_Positional
4061
4062    begin
4063       --  Ada 2005 (AI-287): Do not convert in case of default initialized
4064       --  components because in this case will need to call the corresponding
4065       --  IP procedure.
4066
4067       if Has_Default_Init_Comps (N) then
4068          return;
4069       end if;
4070
4071       if Is_Flat (N, Number_Dimensions (Typ)) then
4072          return;
4073       end if;
4074
4075       if Is_Bit_Packed_Array (Typ)
4076         and then not Handle_Bit_Packed
4077       then
4078          return;
4079       end if;
4080
4081       --  Do not convert to positional if controlled components are involved
4082       --  since these require special processing
4083
4084       if Has_Controlled_Component (Typ) then
4085          return;
4086       end if;
4087
4088       Check_Static_Components;
4089
4090       --  If the size is known, or all the components are static, try to
4091       --  build a fully positional aggregate.
4092
4093       --  The size of the type  may not be known for an aggregate with
4094       --  discriminated array components, but if the components are static
4095       --  it is still possible to verify statically that the length is
4096       --  compatible with the upper bound of the type, and therefore it is
4097       --  worth flattening such aggregates as well.
4098
4099       --  For now the back-end expands these aggregates into individual
4100       --  assignments to the target anyway, but it is conceivable that
4101       --  it will eventually be able to treat such aggregates statically???
4102
4103       if Aggr_Size_OK (N, Typ)
4104         and then Flatten (N, First_Index (Typ), First_Index (Base_Type (Typ)))
4105       then
4106          if Static_Components then
4107             Set_Compile_Time_Known_Aggregate (N);
4108             Set_Expansion_Delayed (N, False);
4109          end if;
4110
4111          Analyze_And_Resolve (N, Typ);
4112       end if;
4113    end Convert_To_Positional;
4114
4115    ----------------------------
4116    -- Expand_Array_Aggregate --
4117    ----------------------------
4118
4119    --  Array aggregate expansion proceeds as follows:
4120
4121    --  1. If requested we generate code to perform all the array aggregate
4122    --     bound checks, specifically
4123
4124    --         (a) Check that the index range defined by aggregate bounds is
4125    --             compatible with corresponding index subtype.
4126
4127    --         (b) If an others choice is present check that no aggregate
4128    --             index is outside the bounds of the index constraint.
4129
4130    --         (c) For multidimensional arrays make sure that all subaggregates
4131    --             corresponding to the same dimension have the same bounds.
4132
4133    --  2. Check for packed array aggregate which can be converted to a
4134    --     constant so that the aggregate disappeares completely.
4135
4136    --  3. Check case of nested aggregate. Generally nested aggregates are
4137    --     handled during the processing of the parent aggregate.
4138
4139    --  4. Check if the aggregate can be statically processed. If this is the
4140    --     case pass it as is to Gigi. Note that a necessary condition for
4141    --     static processing is that the aggregate be fully positional.
4142
4143    --  5. If in place aggregate expansion is possible (i.e. no need to create
4144    --     a temporary) then mark the aggregate as such and return. Otherwise
4145    --     create a new temporary and generate the appropriate initialization
4146    --     code.
4147
4148    procedure Expand_Array_Aggregate (N : Node_Id) is
4149       Loc : constant Source_Ptr := Sloc (N);
4150
4151       Typ  : constant Entity_Id := Etype (N);
4152       Ctyp : constant Entity_Id := Component_Type (Typ);
4153       --  Typ is the correct constrained array subtype of the aggregate
4154       --  Ctyp is the corresponding component type.
4155
4156       Aggr_Dimension : constant Pos := Number_Dimensions (Typ);
4157       --  Number of aggregate index dimensions
4158
4159       Aggr_Low  : array (1 .. Aggr_Dimension) of Node_Id;
4160       Aggr_High : array (1 .. Aggr_Dimension) of Node_Id;
4161       --  Low and High bounds of the constraint for each aggregate index
4162
4163       Aggr_Index_Typ : array (1 .. Aggr_Dimension) of Entity_Id;
4164       --  The type of each index
4165
4166       Maybe_In_Place_OK : Boolean;
4167       --  If the type is neither controlled nor packed and the aggregate
4168       --  is the expression in an assignment, assignment in place may be
4169       --  possible, provided other conditions are met on the LHS.
4170
4171       Others_Present : array (1 .. Aggr_Dimension) of Boolean :=
4172                          (others => False);
4173       --  If Others_Present (J) is True, then there is an others choice
4174       --  in one of the sub-aggregates of N at dimension J.
4175
4176       procedure Build_Constrained_Type (Positional : Boolean);
4177       --  If the subtype is not static or unconstrained, build a constrained
4178       --  type using the computable sizes of the aggregate and its sub-
4179       --  aggregates.
4180
4181       procedure Check_Bounds (Aggr_Bounds : Node_Id; Index_Bounds : Node_Id);
4182       --  Checks that the bounds of Aggr_Bounds are within the bounds defined
4183       --  by Index_Bounds.
4184
4185       procedure Check_Same_Aggr_Bounds (Sub_Aggr : Node_Id; Dim : Pos);
4186       --  Checks that in a multi-dimensional array aggregate all subaggregates
4187       --  corresponding to the same dimension have the same bounds.
4188       --  Sub_Aggr is an array sub-aggregate. Dim is the dimension
4189       --  corresponding to the sub-aggregate.
4190
4191       procedure Compute_Others_Present (Sub_Aggr : Node_Id; Dim : Pos);
4192       --  Computes the values of array Others_Present. Sub_Aggr is the
4193       --  array sub-aggregate we start the computation from. Dim is the
4194       --  dimension corresponding to the sub-aggregate.
4195
4196       function In_Place_Assign_OK return Boolean;
4197       --  Simple predicate to determine whether an aggregate assignment can
4198       --  be done in place, because none of the new values can depend on the
4199       --  components of the target of the assignment.
4200
4201       procedure Others_Check (Sub_Aggr : Node_Id; Dim : Pos);
4202       --  Checks that if an others choice is present in any sub-aggregate no
4203       --  aggregate index is outside the bounds of the index constraint.
4204       --  Sub_Aggr is an array sub-aggregate. Dim is the dimension
4205       --  corresponding to the sub-aggregate.
4206
4207       function Safe_Left_Hand_Side (N : Node_Id) return Boolean;
4208       --  In addition to Maybe_In_Place_OK, in order for an aggregate to be
4209       --  built directly into the target of the assignment it must be free
4210       --  of side-effects.
4211
4212       ----------------------------
4213       -- Build_Constrained_Type --
4214       ----------------------------
4215
4216       procedure Build_Constrained_Type (Positional : Boolean) is
4217          Loc      : constant Source_Ptr := Sloc (N);
4218          Agg_Type : constant Entity_Id  := Make_Temporary (Loc, 'A');
4219          Comp     : Node_Id;
4220          Decl     : Node_Id;
4221          Typ      : constant Entity_Id := Etype (N);
4222          Indexes  : constant List_Id   := New_List;
4223          Num      : Int;
4224          Sub_Agg  : Node_Id;
4225
4226       begin
4227          --  If the aggregate is purely positional, all its subaggregates
4228          --  have the same size. We collect the dimensions from the first
4229          --  subaggregate at each level.
4230
4231          if Positional then
4232             Sub_Agg := N;
4233
4234             for D in 1 .. Number_Dimensions (Typ) loop
4235                Sub_Agg := First (Expressions (Sub_Agg));
4236
4237                Comp := Sub_Agg;
4238                Num := 0;
4239                while Present (Comp) loop
4240                   Num := Num + 1;
4241                   Next (Comp);
4242                end loop;
4243
4244                Append_To (Indexes,
4245                  Make_Range (Loc,
4246                    Low_Bound =>  Make_Integer_Literal (Loc, 1),
4247                    High_Bound => Make_Integer_Literal (Loc, Num)));
4248             end loop;
4249
4250          else
4251             --  We know the aggregate type is unconstrained and the aggregate
4252             --  is not processable by the back end, therefore not necessarily
4253             --  positional. Retrieve each dimension bounds (computed earlier).
4254
4255             for D in 1 .. Number_Dimensions (Typ) loop
4256                Append (
4257                  Make_Range (Loc,
4258                     Low_Bound  => Aggr_Low  (D),
4259                     High_Bound => Aggr_High (D)),
4260                  Indexes);
4261             end loop;
4262          end if;
4263
4264          Decl :=
4265            Make_Full_Type_Declaration (Loc,
4266                Defining_Identifier => Agg_Type,
4267                Type_Definition =>
4268                  Make_Constrained_Array_Definition (Loc,
4269                    Discrete_Subtype_Definitions => Indexes,
4270                    Component_Definition         =>
4271                      Make_Component_Definition (Loc,
4272                        Aliased_Present    => False,
4273                        Subtype_Indication =>
4274                          New_Occurrence_Of (Component_Type (Typ), Loc))));
4275
4276          Insert_Action (N, Decl);
4277          Analyze (Decl);
4278          Set_Etype (N, Agg_Type);
4279          Set_Is_Itype (Agg_Type);
4280          Freeze_Itype (Agg_Type, N);
4281       end Build_Constrained_Type;
4282
4283       ------------------
4284       -- Check_Bounds --
4285       ------------------
4286
4287       procedure Check_Bounds (Aggr_Bounds : Node_Id; Index_Bounds : Node_Id) is
4288          Aggr_Lo : Node_Id;
4289          Aggr_Hi : Node_Id;
4290
4291          Ind_Lo  : Node_Id;
4292          Ind_Hi  : Node_Id;
4293
4294          Cond    : Node_Id := Empty;
4295
4296       begin
4297          Get_Index_Bounds (Aggr_Bounds, Aggr_Lo, Aggr_Hi);
4298          Get_Index_Bounds (Index_Bounds, Ind_Lo, Ind_Hi);
4299
4300          --  Generate the following test:
4301          --
4302          --    [constraint_error when
4303          --      Aggr_Lo <= Aggr_Hi and then
4304          --        (Aggr_Lo < Ind_Lo or else Aggr_Hi > Ind_Hi)]
4305
4306          --  As an optimization try to see if some tests are trivially vacuous
4307          --  because we are comparing an expression against itself.
4308
4309          if Aggr_Lo = Ind_Lo and then Aggr_Hi = Ind_Hi then
4310             Cond := Empty;
4311
4312          elsif Aggr_Hi = Ind_Hi then
4313             Cond :=
4314               Make_Op_Lt (Loc,
4315                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4316                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Lo));
4317
4318          elsif Aggr_Lo = Ind_Lo then
4319             Cond :=
4320               Make_Op_Gt (Loc,
4321                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Hi),
4322                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Hi));
4323
4324          else
4325             Cond :=
4326               Make_Or_Else (Loc,
4327                 Left_Opnd =>
4328                   Make_Op_Lt (Loc,
4329                     Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4330                     Right_Opnd => Duplicate_Subexpr_Move_Checks (Ind_Lo)),
4331
4332                 Right_Opnd =>
4333                   Make_Op_Gt (Loc,
4334                     Left_Opnd  => Duplicate_Subexpr (Aggr_Hi),
4335                     Right_Opnd => Duplicate_Subexpr (Ind_Hi)));
4336          end if;
4337
4338          if Present (Cond) then
4339             Cond :=
4340               Make_And_Then (Loc,
4341                 Left_Opnd =>
4342                   Make_Op_Le (Loc,
4343                     Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4344                     Right_Opnd => Duplicate_Subexpr_Move_Checks (Aggr_Hi)),
4345
4346                 Right_Opnd => Cond);
4347
4348             Set_Analyzed (Left_Opnd  (Left_Opnd (Cond)), False);
4349             Set_Analyzed (Right_Opnd (Left_Opnd (Cond)), False);
4350             Insert_Action (N,
4351               Make_Raise_Constraint_Error (Loc,
4352                 Condition => Cond,
4353                 Reason    => CE_Length_Check_Failed));
4354          end if;
4355       end Check_Bounds;
4356
4357       ----------------------------
4358       -- Check_Same_Aggr_Bounds --
4359       ----------------------------
4360
4361       procedure Check_Same_Aggr_Bounds (Sub_Aggr : Node_Id; Dim : Pos) is
4362          Sub_Lo : constant Node_Id := Low_Bound (Aggregate_Bounds (Sub_Aggr));
4363          Sub_Hi : constant Node_Id := High_Bound (Aggregate_Bounds (Sub_Aggr));
4364          --  The bounds of this specific sub-aggregate
4365
4366          Aggr_Lo : constant Node_Id := Aggr_Low (Dim);
4367          Aggr_Hi : constant Node_Id := Aggr_High (Dim);
4368          --  The bounds of the aggregate for this dimension
4369
4370          Ind_Typ : constant Entity_Id := Aggr_Index_Typ (Dim);
4371          --  The index type for this dimension.xxx
4372
4373          Cond  : Node_Id := Empty;
4374          Assoc : Node_Id;
4375          Expr  : Node_Id;
4376
4377       begin
4378          --  If index checks are on generate the test
4379
4380          --    [constraint_error when
4381          --      Aggr_Lo /= Sub_Lo or else Aggr_Hi /= Sub_Hi]
4382
4383          --  As an optimization try to see if some tests are trivially vacuos
4384          --  because we are comparing an expression against itself. Also for
4385          --  the first dimension the test is trivially vacuous because there
4386          --  is just one aggregate for dimension 1.
4387
4388          if Index_Checks_Suppressed (Ind_Typ) then
4389             Cond := Empty;
4390
4391          elsif Dim = 1
4392            or else (Aggr_Lo = Sub_Lo and then Aggr_Hi = Sub_Hi)
4393          then
4394             Cond := Empty;
4395
4396          elsif Aggr_Hi = Sub_Hi then
4397             Cond :=
4398               Make_Op_Ne (Loc,
4399                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4400                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Lo));
4401
4402          elsif Aggr_Lo = Sub_Lo then
4403             Cond :=
4404               Make_Op_Ne (Loc,
4405                 Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Hi),
4406                 Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Hi));
4407
4408          else
4409             Cond :=
4410               Make_Or_Else (Loc,
4411                 Left_Opnd =>
4412                   Make_Op_Ne (Loc,
4413                     Left_Opnd  => Duplicate_Subexpr_Move_Checks (Aggr_Lo),
4414                     Right_Opnd => Duplicate_Subexpr_Move_Checks (Sub_Lo)),
4415
4416                 Right_Opnd =>
4417                   Make_Op_Ne (Loc,
4418                     Left_Opnd  => Duplicate_Subexpr (Aggr_Hi),
4419                     Right_Opnd => Duplicate_Subexpr (Sub_Hi)));
4420          end if;
4421
4422          if Present (Cond) then
4423             Insert_Action (N,
4424               Make_Raise_Constraint_Error (Loc,
4425                 Condition => Cond,
4426                 Reason    => CE_Length_Check_Failed));
4427          end if;
4428
4429          --  Now look inside the sub-aggregate to see if there is more work
4430
4431          if Dim < Aggr_Dimension then
4432
4433             --  Process positional components
4434
4435             if Present (Expressions (Sub_Aggr)) then
4436                Expr := First (Expressions (Sub_Aggr));
4437                while Present (Expr) loop
4438                   Check_Same_Aggr_Bounds (Expr, Dim + 1);
4439                   Next (Expr);
4440                end loop;
4441             end if;
4442
4443             --  Process component associations
4444
4445             if Present (Component_Associations (Sub_Aggr)) then
4446                Assoc := First (Component_Associations (Sub_Aggr));
4447                while Present (Assoc) loop
4448                   Expr := Expression (Assoc);
4449                   Check_Same_Aggr_Bounds (Expr, Dim + 1);
4450                   Next (Assoc);
4451                end loop;
4452             end if;
4453          end if;
4454       end Check_Same_Aggr_Bounds;
4455
4456       ----------------------------
4457       -- Compute_Others_Present --
4458       ----------------------------
4459
4460       procedure Compute_Others_Present (Sub_Aggr : Node_Id; Dim : Pos) is
4461          Assoc : Node_Id;
4462          Expr  : Node_Id;
4463
4464       begin
4465          if Present (Component_Associations (Sub_Aggr)) then
4466             Assoc := Last (Component_Associations (Sub_Aggr));
4467
4468             if Nkind (First (Choices (Assoc))) = N_Others_Choice then
4469                Others_Present (Dim) := True;
4470             end if;
4471          end if;
4472
4473          --  Now look inside the sub-aggregate to see if there is more work
4474
4475          if Dim < Aggr_Dimension then
4476
4477             --  Process positional components
4478
4479             if Present (Expressions (Sub_Aggr)) then
4480                Expr := First (Expressions (Sub_Aggr));
4481                while Present (Expr) loop
4482                   Compute_Others_Present (Expr, Dim + 1);
4483                   Next (Expr);
4484                end loop;
4485             end if;
4486
4487             --  Process component associations
4488
4489             if Present (Component_Associations (Sub_Aggr)) then
4490                Assoc := First (Component_Associations (Sub_Aggr));
4491                while Present (Assoc) loop
4492                   Expr := Expression (Assoc);
4493                   Compute_Others_Present (Expr, Dim + 1);
4494                   Next (Assoc);
4495                end loop;
4496             end if;
4497          end if;
4498       end Compute_Others_Present;
4499
4500       ------------------------
4501       -- In_Place_Assign_OK --
4502       ------------------------
4503
4504       function In_Place_Assign_OK return Boolean is
4505          Aggr_In : Node_Id;
4506          Aggr_Lo : Node_Id;
4507          Aggr_Hi : Node_Id;
4508          Obj_In  : Node_Id;
4509          Obj_Lo  : Node_Id;
4510          Obj_Hi  : Node_Id;
4511
4512          function Safe_Aggregate (Aggr : Node_Id) return Boolean;
4513          --  Check recursively that each component of a (sub)aggregate does
4514          --  not depend on the variable being assigned to.
4515
4516          function Safe_Component (Expr : Node_Id) return Boolean;
4517          --  Verify that an expression cannot depend on the variable being
4518          --  assigned to. Room for improvement here (but less than before).
4519
4520          --------------------
4521          -- Safe_Aggregate --
4522          --------------------
4523
4524          function Safe_Aggregate (Aggr : Node_Id) return Boolean is
4525             Expr : Node_Id;
4526
4527          begin
4528             if Present (Expressions (Aggr)) then
4529                Expr := First (Expressions (Aggr));
4530                while Present (Expr) loop
4531                   if Nkind (Expr) = N_Aggregate then
4532                      if not Safe_Aggregate (Expr) then
4533                         return False;
4534                      end if;
4535
4536                   elsif not Safe_Component (Expr) then
4537                      return False;
4538                   end if;
4539
4540                   Next (Expr);
4541                end loop;
4542             end if;
4543
4544             if Present (Component_Associations (Aggr)) then
4545                Expr := First (Component_Associations (Aggr));
4546                while Present (Expr) loop
4547                   if Nkind (Expression (Expr)) = N_Aggregate then
4548                      if not Safe_Aggregate (Expression (Expr)) then
4549                         return False;
4550                      end if;
4551
4552                   elsif not Safe_Component (Expression (Expr)) then
4553                      return False;
4554                   end if;
4555
4556                   Next (Expr);
4557                end loop;
4558             end if;
4559
4560             return True;
4561          end Safe_Aggregate;
4562
4563          --------------------
4564          -- Safe_Component --
4565          --------------------
4566
4567          function Safe_Component (Expr : Node_Id) return Boolean is
4568             Comp : Node_Id := Expr;
4569
4570             function Check_Component (Comp : Node_Id) return Boolean;
4571             --  Do the recursive traversal, after copy
4572
4573             ---------------------
4574             -- Check_Component --
4575             ---------------------
4576
4577             function Check_Component (Comp : Node_Id) return Boolean is
4578             begin
4579                if Is_Overloaded (Comp) then
4580                   return False;
4581                end if;
4582
4583                return Compile_Time_Known_Value (Comp)
4584
4585                  or else (Is_Entity_Name (Comp)
4586                            and then  Present (Entity (Comp))
4587                            and then No (Renamed_Object (Entity (Comp))))
4588
4589                  or else (Nkind (Comp) = N_Attribute_Reference
4590                            and then Check_Component (Prefix (Comp)))
4591
4592                  or else (Nkind (Comp) in N_Binary_Op
4593                            and then Check_Component (Left_Opnd  (Comp))
4594                            and then Check_Component (Right_Opnd (Comp)))
4595
4596                  or else (Nkind (Comp) in N_Unary_Op
4597                            and then Check_Component (Right_Opnd (Comp)))
4598
4599                  or else (Nkind (Comp) = N_Selected_Component
4600                            and then Check_Component (Prefix (Comp)))
4601
4602                  or else (Nkind (Comp) = N_Unchecked_Type_Conversion
4603                            and then Check_Component (Expression (Comp)));
4604             end Check_Component;
4605
4606          --  Start of processing for Safe_Component
4607
4608          begin
4609             --  If the component appears in an association that may
4610             --  correspond to more than one element, it is not analyzed
4611             --  before the expansion into assignments, to avoid side effects.
4612             --  We analyze, but do not resolve the copy, to obtain sufficient
4613             --  entity information for the checks that follow. If component is
4614             --  overloaded we assume an unsafe function call.
4615
4616             if not Analyzed (Comp) then
4617                if Is_Overloaded (Expr) then
4618                   return False;
4619
4620                elsif Nkind (Expr) = N_Aggregate
4621                   and then not Is_Others_Aggregate (Expr)
4622                then
4623                   return False;
4624
4625                elsif Nkind (Expr) = N_Allocator then
4626
4627                   --  For now, too complex to analyze
4628
4629                   return False;
4630                end if;
4631
4632                Comp := New_Copy_Tree (Expr);
4633                Set_Parent (Comp, Parent (Expr));
4634                Analyze (Comp);
4635             end if;
4636
4637             if Nkind (Comp) = N_Aggregate then
4638                return Safe_Aggregate (Comp);
4639             else
4640                return Check_Component (Comp);
4641             end if;
4642          end Safe_Component;
4643
4644       --  Start of processing for In_Place_Assign_OK
4645
4646       begin
4647          if Present (Component_Associations (N)) then
4648
4649             --  On assignment, sliding can take place, so we cannot do the
4650             --  assignment in place unless the bounds of the aggregate are
4651             --  statically equal to those of the target.
4652
4653             --  If the aggregate is given by an others choice, the bounds
4654             --  are derived from the left-hand side, and the assignment is
4655             --  safe if the expression is.
4656
4657             if Is_Others_Aggregate (N) then
4658                return
4659                  Safe_Component
4660                   (Expression (First (Component_Associations (N))));
4661             end if;
4662
4663             Aggr_In := First_Index (Etype (N));
4664
4665             if Nkind (Parent (N)) = N_Assignment_Statement then
4666                Obj_In  := First_Index (Etype (Name (Parent (N))));
4667
4668             else
4669                --  Context is an allocator. Check bounds of aggregate
4670                --  against given type in qualified expression.
4671
4672                pragma Assert (Nkind (Parent (Parent (N))) = N_Allocator);
4673                Obj_In :=
4674                  First_Index (Etype (Entity (Subtype_Mark (Parent (N)))));
4675             end if;
4676
4677             while Present (Aggr_In) loop
4678                Get_Index_Bounds (Aggr_In, Aggr_Lo, Aggr_Hi);
4679                Get_Index_Bounds (Obj_In, Obj_Lo, Obj_Hi);
4680
4681                if not Compile_Time_Known_Value (Aggr_Lo)
4682                  or else not Compile_Time_Known_Value (Aggr_Hi)
4683                  or else not Compile_Time_Known_Value (Obj_Lo)
4684                  or else not Compile_Time_Known_Value (Obj_Hi)
4685                  or else Expr_Value (Aggr_Lo) /= Expr_Value (Obj_Lo)
4686                  or else Expr_Value (Aggr_Hi) /= Expr_Value (Obj_Hi)
4687                then
4688                   return False;
4689                end if;
4690
4691                Next_Index (Aggr_In);
4692                Next_Index (Obj_In);
4693             end loop;
4694          end if;
4695
4696          --  Now check the component values themselves
4697
4698          return Safe_Aggregate (N);
4699       end In_Place_Assign_OK;
4700
4701       ------------------
4702       -- Others_Check --
4703       ------------------
4704
4705       procedure Others_Check (Sub_Aggr : Node_Id; Dim : Pos) is
4706          Aggr_Lo : constant Node_Id := Aggr_Low (Dim);
4707          Aggr_Hi : constant Node_Id := Aggr_High (Dim);
4708          --  The bounds of the aggregate for this dimension
4709
4710          Ind_Typ : constant Entity_Id := Aggr_Index_Typ (Dim);
4711          --  The index type for this dimension
4712
4713          Need_To_Check : Boolean := False;
4714
4715          Choices_Lo : Node_Id := Empty;
4716          Choices_Hi : Node_Id := Empty;
4717          --  The lowest and highest discrete choices for a named sub-aggregate
4718
4719          Nb_Choices : Int := -1;
4720          --  The number of discrete non-others choices in this sub-aggregate
4721
4722          Nb_Elements : Uint := Uint_0;
4723          --  The number of elements in a positional aggregate
4724
4725          Cond : Node_Id := Empty;
4726
4727          Assoc  : Node_Id;
4728          Choice : Node_Id;
4729          Expr   : Node_Id;
4730
4731       begin
4732          --  Check if we have an others choice. If we do make sure that this
4733          --  sub-aggregate contains at least one element in addition to the
4734          --  others choice.
4735
4736          if Range_Checks_Suppressed (Ind_Typ) then
4737             Need_To_Check := False;
4738
4739          elsif Present (Expressions (Sub_Aggr))
4740            and then Present (Component_Associations (Sub_Aggr))
4741          then
4742             Need_To_Check := True;
4743
4744          elsif Present (Component_Associations (Sub_Aggr)) then
4745             Assoc := Last (Component_Associations (Sub_Aggr));
4746
4747             if Nkind (First (Choices (Assoc))) /= N_Others_Choice then
4748                Need_To_Check := False;
4749
4750             else
4751                --  Count the number of discrete choices. Start with -1 because
4752                --  the others choice does not count.
4753
4754                Nb_Choices := -1;
4755                Assoc := First (Component_Associations (Sub_Aggr));
4756                while Present (Assoc) loop
4757                   Choice := First (Choices (Assoc));
4758                   while Present (Choice) loop
4759                      Nb_Choices := Nb_Choices + 1;
4760                      Next (Choice);
4761                   end loop;
4762
4763                   Next (Assoc);
4764                end loop;
4765
4766                --  If there is only an others choice nothing to do
4767
4768                Need_To_Check := (Nb_Choices > 0);
4769             end if;
4770
4771          else
4772             Need_To_Check := False;
4773          end if;
4774
4775          --  If we are dealing with a positional sub-aggregate with an others
4776          --  choice then compute the number or positional elements.
4777
4778          if Need_To_Check and then Present (Expressions (Sub_Aggr)) then
4779             Expr := First (Expressions (Sub_Aggr));
4780             Nb_Elements := Uint_0;
4781             while Present (Expr) loop
4782                Nb_Elements := Nb_Elements + 1;
4783                Next (Expr);
4784             end loop;
4785
4786          --  If the aggregate contains discrete choices and an others choice
4787          --  compute the smallest and largest discrete choice values.
4788
4789          elsif Need_To_Check then
4790             Compute_Choices_Lo_And_Choices_Hi : declare
4791
4792                Table : Case_Table_Type (1 .. Nb_Choices);
4793                --  Used to sort all the different choice values
4794
4795                J    : Pos := 1;
4796                Low  : Node_Id;
4797                High : Node_Id;
4798
4799             begin
4800                Assoc := First (Component_Associations (Sub_Aggr));
4801                while Present (Assoc) loop
4802                   Choice := First (Choices (Assoc));
4803                   while Present (Choice) loop
4804                      if Nkind (Choice) = N_Others_Choice then
4805                         exit;
4806                      end if;
4807
4808                      Get_Index_Bounds (Choice, Low, High);
4809                      Table (J).Choice_Lo := Low;
4810                      Table (J).Choice_Hi := High;
4811
4812                      J := J + 1;
4813                      Next (Choice);
4814                   end loop;
4815
4816                   Next (Assoc);
4817                end loop;
4818
4819                --  Sort the discrete choices
4820
4821                Sort_Case_Table (Table);
4822
4823                Choices_Lo := Table (1).Choice_Lo;
4824                Choices_Hi := Table (Nb_Choices).Choice_Hi;
4825             end Compute_Choices_Lo_And_Choices_Hi;
4826          end if;
4827
4828          --  If no others choice in this sub-aggregate, or the aggregate
4829          --  comprises only an others choice, nothing to do.
4830
4831          if not Need_To_Check then
4832             Cond := Empty;
4833
4834          --  If we are dealing with an aggregate containing an others choice
4835          --  and positional components, we generate the following test:
4836
4837          --    if Ind_Typ'Pos (Aggr_Lo) + (Nb_Elements - 1) >
4838          --            Ind_Typ'Pos (Aggr_Hi)
4839          --    then
4840          --       raise Constraint_Error;
4841          --    end if;
4842
4843          elsif Nb_Elements > Uint_0 then
4844             Cond :=
4845               Make_Op_Gt (Loc,
4846                 Left_Opnd  =>
4847                   Make_Op_Add (Loc,
4848                     Left_Opnd  =>
4849                       Make_Attribute_Reference (Loc,
4850                         Prefix         => New_Reference_To (Ind_Typ, Loc),
4851                         Attribute_Name => Name_Pos,
4852                         Expressions    =>
4853                           New_List
4854                             (Duplicate_Subexpr_Move_Checks (Aggr_Lo))),
4855                     Right_Opnd => Make_Integer_Literal (Loc, Nb_Elements - 1)),
4856
4857                 Right_Opnd =>
4858                   Make_Attribute_Reference (Loc,
4859                     Prefix         => New_Reference_To (Ind_Typ, Loc),
4860                     Attribute_Name => Name_Pos,
4861                     Expressions    => New_List (
4862                       Duplicate_Subexpr_Move_Checks (Aggr_Hi))));
4863
4864          --  If we are dealing with an aggregate containing an others choice
4865          --  and discrete choices we generate the following test:
4866
4867          --    [constraint_error when
4868          --      Choices_Lo < Aggr_Lo or else Choices_Hi > Aggr_Hi];
4869
4870          else
4871             Cond :=
4872               Make_Or_Else (Loc,
4873                 Left_Opnd =>
4874                   Make_Op_Lt (Loc,
4875                     Left_Opnd  =>
4876                       Duplicate_Subexpr_Move_Checks (Choices_Lo),
4877                     Right_Opnd =>
4878                       Duplicate_Subexpr_Move_Checks (Aggr_Lo)),
4879
4880                 Right_Opnd =>
4881                   Make_Op_Gt (Loc,
4882                     Left_Opnd  =>
4883                       Duplicate_Subexpr (Choices_Hi),
4884                     Right_Opnd =>
4885                       Duplicate_Subexpr (Aggr_Hi)));
4886          end if;
4887
4888          if Present (Cond) then
4889             Insert_Action (N,
4890               Make_Raise_Constraint_Error (Loc,
4891                 Condition => Cond,
4892                 Reason    => CE_Length_Check_Failed));
4893             --  Questionable reason code, shouldn't that be a
4894             --  CE_Range_Check_Failed ???
4895          end if;
4896
4897          --  Now look inside the sub-aggregate to see if there is more work
4898
4899          if Dim < Aggr_Dimension then
4900
4901             --  Process positional components
4902
4903             if Present (Expressions (Sub_Aggr)) then
4904                Expr := First (Expressions (Sub_Aggr));
4905                while Present (Expr) loop
4906                   Others_Check (Expr, Dim + 1);
4907                   Next (Expr);
4908                end loop;
4909             end if;
4910
4911             --  Process component associations
4912
4913             if Present (Component_Associations (Sub_Aggr)) then
4914                Assoc := First (Component_Associations (Sub_Aggr));
4915                while Present (Assoc) loop
4916                   Expr := Expression (Assoc);
4917                   Others_Check (Expr, Dim + 1);
4918                   Next (Assoc);
4919                end loop;
4920             end if;
4921          end if;
4922       end Others_Check;
4923
4924       -------------------------
4925       -- Safe_Left_Hand_Side --
4926       -------------------------
4927
4928       function Safe_Left_Hand_Side (N : Node_Id) return Boolean is
4929          function Is_Safe_Index (Indx : Node_Id) return Boolean;
4930          --  If the left-hand side includes an indexed component, check that
4931          --  the indexes are free of side-effect.
4932
4933          -------------------
4934          -- Is_Safe_Index --
4935          -------------------
4936
4937          function Is_Safe_Index (Indx : Node_Id) return Boolean is
4938          begin
4939             if Is_Entity_Name (Indx) then
4940                return True;
4941
4942             elsif Nkind (Indx) = N_Integer_Literal then
4943                return True;
4944
4945             elsif Nkind (Indx) = N_Function_Call
4946               and then Is_Entity_Name (Name (Indx))
4947               and then
4948                 Has_Pragma_Pure_Function (Entity (Name (Indx)))
4949             then
4950                return True;
4951
4952             elsif Nkind (Indx) = N_Type_Conversion
4953               and then Is_Safe_Index (Expression (Indx))
4954             then
4955                return True;
4956
4957             else
4958                return False;
4959             end if;
4960          end Is_Safe_Index;
4961
4962       --  Start of processing for Safe_Left_Hand_Side
4963
4964       begin
4965          if Is_Entity_Name (N) then
4966             return True;
4967
4968          elsif Nkind_In (N, N_Explicit_Dereference, N_Selected_Component)
4969            and then Safe_Left_Hand_Side (Prefix (N))
4970          then
4971             return True;
4972
4973          elsif Nkind (N) = N_Indexed_Component
4974            and then Safe_Left_Hand_Side (Prefix (N))
4975            and then
4976              Is_Safe_Index (First (Expressions (N)))
4977          then
4978             return True;
4979
4980          elsif Nkind (N) = N_Unchecked_Type_Conversion then
4981             return Safe_Left_Hand_Side (Expression (N));
4982
4983          else
4984             return False;
4985          end if;
4986       end Safe_Left_Hand_Side;
4987
4988       --  Local variables
4989
4990       Tmp : Entity_Id;
4991       --  Holds the temporary aggregate value
4992
4993       Tmp_Decl : Node_Id;
4994       --  Holds the declaration of Tmp
4995
4996       Aggr_Code   : List_Id;
4997       Parent_Node : Node_Id;
4998       Parent_Kind : Node_Kind;
4999
5000    --  Start of processing for Expand_Array_Aggregate
5001
5002    begin
5003       --  Do not touch the special aggregates of attributes used for Asm calls
5004
5005       if Is_RTE (Ctyp, RE_Asm_Input_Operand)
5006         or else Is_RTE (Ctyp, RE_Asm_Output_Operand)
5007       then
5008          return;
5009       end if;
5010
5011       --  If the semantic analyzer has determined that aggregate N will raise
5012       --  Constraint_Error at run time, then the aggregate node has been
5013       --  replaced with an N_Raise_Constraint_Error node and we should
5014       --  never get here.
5015
5016       pragma Assert (not Raises_Constraint_Error (N));
5017
5018       --  STEP 1a
5019
5020       --  Check that the index range defined by aggregate bounds is
5021       --  compatible with corresponding index subtype.
5022
5023       Index_Compatibility_Check : declare
5024          Aggr_Index_Range : Node_Id := First_Index (Typ);
5025          --  The current aggregate index range
5026
5027          Index_Constraint : Node_Id := First_Index (Etype (Typ));
5028          --  The corresponding index constraint against which we have to
5029          --  check the above aggregate index range.
5030
5031       begin
5032          Compute_Others_Present (N, 1);
5033
5034          for J in 1 .. Aggr_Dimension loop
5035             --  There is no need to emit a check if an others choice is
5036             --  present for this array aggregate dimension since in this
5037             --  case one of N's sub-aggregates has taken its bounds from the
5038             --  context and these bounds must have been checked already. In
5039             --  addition all sub-aggregates corresponding to the same
5040             --  dimension must all have the same bounds (checked in (c) below).
5041
5042             if not Range_Checks_Suppressed (Etype (Index_Constraint))
5043               and then not Others_Present (J)
5044             then
5045                --  We don't use Checks.Apply_Range_Check here because it emits
5046                --  a spurious check. Namely it checks that the range defined by
5047                --  the aggregate bounds is non empty. But we know this already
5048                --  if we get here.
5049
5050                Check_Bounds (Aggr_Index_Range, Index_Constraint);
5051             end if;
5052
5053             --  Save the low and high bounds of the aggregate index as well as
5054             --  the index type for later use in checks (b) and (c) below.
5055
5056             Aggr_Low  (J) := Low_Bound (Aggr_Index_Range);
5057             Aggr_High (J) := High_Bound (Aggr_Index_Range);
5058
5059             Aggr_Index_Typ (J) := Etype (Index_Constraint);
5060
5061             Next_Index (Aggr_Index_Range);
5062             Next_Index (Index_Constraint);
5063          end loop;
5064       end Index_Compatibility_Check;
5065
5066       --  STEP 1b
5067
5068       --  If an others choice is present check that no aggregate index is
5069       --  outside the bounds of the index constraint.
5070
5071       Others_Check (N, 1);
5072
5073       --  STEP 1c
5074
5075       --  For multidimensional arrays make sure that all subaggregates
5076       --  corresponding to the same dimension have the same bounds.
5077
5078       if Aggr_Dimension > 1 then
5079          Check_Same_Aggr_Bounds (N, 1);
5080       end if;
5081
5082       --  STEP 2
5083
5084       --  Here we test for is packed array aggregate that we can handle at
5085       --  compile time. If so, return with transformation done. Note that we do
5086       --  this even if the aggregate is nested, because once we have done this
5087       --  processing, there is no more nested aggregate!
5088
5089       if Packed_Array_Aggregate_Handled (N) then
5090          return;
5091       end if;
5092
5093       --  At this point we try to convert to positional form
5094
5095       if Ekind (Current_Scope) = E_Package
5096         and then Static_Elaboration_Desired (Current_Scope)
5097       then
5098          Convert_To_Positional (N, Max_Others_Replicate => 100);
5099
5100       else
5101          Convert_To_Positional (N);
5102       end if;
5103
5104       --  if the result is no longer an aggregate (e.g. it may be a string
5105       --  literal, or a temporary which has the needed value), then we are
5106       --  done, since there is no longer a nested aggregate.
5107
5108       if Nkind (N) /= N_Aggregate then
5109          return;
5110
5111       --  We are also done if the result is an analyzed aggregate
5112       --  This case could use more comments ???
5113
5114       elsif Analyzed (N)
5115         and then N /= Original_Node (N)
5116       then
5117          return;
5118       end if;
5119
5120       --  If all aggregate components are compile-time known and the aggregate
5121       --  has been flattened, nothing left to do. The same occurs if the
5122       --  aggregate is used to initialize the components of an statically
5123       --  allocated dispatch table.
5124
5125       if Compile_Time_Known_Aggregate (N)
5126         or else Is_Static_Dispatch_Table_Aggregate (N)
5127       then
5128          Set_Expansion_Delayed (N, False);
5129          return;
5130       end if;
5131
5132       --  Now see if back end processing is possible
5133
5134       if Backend_Processing_Possible (N) then
5135
5136          --  If the aggregate is static but the constraints are not, build
5137          --  a static subtype for the aggregate, so that Gigi can place it
5138          --  in static memory. Perform an unchecked_conversion to the non-
5139          --  static type imposed by the context.
5140
5141          declare
5142             Itype      : constant Entity_Id := Etype (N);
5143             Index      : Node_Id;
5144             Needs_Type : Boolean := False;
5145
5146          begin
5147             Index := First_Index (Itype);
5148             while Present (Index) loop
5149                if not Is_Static_Subtype (Etype (Index)) then
5150                   Needs_Type := True;
5151                   exit;
5152                else
5153                   Next_Index (Index);
5154                end if;
5155             end loop;
5156
5157             if Needs_Type then
5158                Build_Constrained_Type (Positional => True);
5159                Rewrite (N, Unchecked_Convert_To (Itype, N));
5160                Analyze (N);
5161             end if;
5162          end;
5163
5164          return;
5165       end if;
5166
5167       --  STEP 3
5168
5169       --  Delay expansion for nested aggregates: it will be taken care of
5170       --  when the parent aggregate is expanded.
5171
5172       Parent_Node := Parent (N);
5173       Parent_Kind := Nkind (Parent_Node);
5174
5175       if Parent_Kind = N_Qualified_Expression then
5176          Parent_Node := Parent (Parent_Node);
5177          Parent_Kind := Nkind (Parent_Node);
5178       end if;
5179
5180       if Parent_Kind = N_Aggregate
5181         or else Parent_Kind = N_Extension_Aggregate
5182         or else Parent_Kind = N_Component_Association
5183         or else (Parent_Kind = N_Object_Declaration
5184                   and then Needs_Finalization (Typ))
5185         or else (Parent_Kind = N_Assignment_Statement
5186                   and then Inside_Init_Proc)
5187       then
5188          if Static_Array_Aggregate (N)
5189            or else Compile_Time_Known_Aggregate (N)
5190          then
5191             Set_Expansion_Delayed (N, False);
5192             return;
5193          else
5194             Set_Expansion_Delayed (N);
5195             return;
5196          end if;
5197       end if;
5198
5199       --  STEP 4
5200
5201       --  Look if in place aggregate expansion is possible
5202
5203       --  For object declarations we build the aggregate in place, unless
5204       --  the array is bit-packed or the component is controlled.
5205
5206       --  For assignments we do the assignment in place if all the component
5207       --  associations have compile-time known values. For other cases we
5208       --  create a temporary. The analysis for safety of on-line assignment
5209       --  is delicate, i.e. we don't know how to do it fully yet ???
5210
5211       --  For allocators we assign to the designated object in place if the
5212       --  aggregate meets the same conditions as other in-place assignments.
5213       --  In this case the aggregate may not come from source but was created
5214       --  for default initialization, e.g. with Initialize_Scalars.
5215
5216       if Requires_Transient_Scope (Typ) then
5217          Establish_Transient_Scope
5218            (N, Sec_Stack => Has_Controlled_Component (Typ));
5219       end if;
5220
5221       if Has_Default_Init_Comps (N) then
5222          Maybe_In_Place_OK := False;
5223
5224       elsif Is_Bit_Packed_Array (Typ)
5225         or else Has_Controlled_Component (Typ)
5226       then
5227          Maybe_In_Place_OK := False;
5228
5229       else
5230          Maybe_In_Place_OK :=
5231           (Nkind (Parent (N)) = N_Assignment_Statement
5232             and then Comes_From_Source (N)
5233             and then In_Place_Assign_OK)
5234
5235           or else
5236             (Nkind (Parent (Parent (N))) = N_Allocator
5237               and then In_Place_Assign_OK);
5238       end if;
5239
5240       --  If this is an array of tasks, it will be expanded into build-in-place
5241       --  assignments. Build an activation chain for the tasks now.
5242
5243       if Has_Task (Etype (N)) then
5244          Build_Activation_Chain_Entity (N);
5245       end if;
5246
5247       --  Should document these individual tests ???
5248
5249       if not Has_Default_Init_Comps (N)
5250          and then Comes_From_Source (Parent (N))
5251          and then Nkind (Parent (N)) = N_Object_Declaration
5252          and then not
5253            Must_Slide (Etype (Defining_Identifier (Parent (N))), Typ)
5254          and then N = Expression (Parent (N))
5255          and then not Is_Bit_Packed_Array (Typ)
5256          and then not Has_Controlled_Component (Typ)
5257
5258       --  If the aggregate is the expression in an object declaration, it
5259       --  cannot be expanded in place. Lookahead in the current declarative
5260       --  part to find an address clause for the object being declared. If
5261       --  one is present, we cannot build in place. Unclear comment???
5262
5263          and then not Has_Following_Address_Clause (Parent (N))
5264       then
5265          Tmp := Defining_Identifier (Parent (N));
5266          Set_No_Initialization (Parent (N));
5267          Set_Expression (Parent (N), Empty);
5268
5269          --  Set the type of the entity, for use in the analysis of the
5270          --  subsequent indexed assignments. If the nominal type is not
5271          --  constrained, build a subtype from the known bounds of the
5272          --  aggregate. If the declaration has a subtype mark, use it,
5273          --  otherwise use the itype of the aggregate.
5274
5275          if not Is_Constrained (Typ) then
5276             Build_Constrained_Type (Positional => False);
5277          elsif Is_Entity_Name (Object_Definition (Parent (N)))
5278            and then Is_Constrained (Entity (Object_Definition (Parent (N))))
5279          then
5280             Set_Etype (Tmp, Entity (Object_Definition (Parent (N))));
5281          else
5282             Set_Size_Known_At_Compile_Time (Typ, False);
5283             Set_Etype (Tmp, Typ);
5284          end if;
5285
5286       elsif Maybe_In_Place_OK
5287         and then Nkind (Parent (N)) = N_Qualified_Expression
5288         and then Nkind (Parent (Parent (N))) = N_Allocator
5289       then
5290          Set_Expansion_Delayed (N);
5291          return;
5292
5293       --  In the remaining cases the aggregate is the RHS of an assignment
5294
5295       elsif Maybe_In_Place_OK
5296         and then Safe_Left_Hand_Side (Name (Parent (N)))
5297       then
5298          Tmp := Name (Parent (N));
5299
5300          if Etype (Tmp) /= Etype (N) then
5301             Apply_Length_Check (N, Etype (Tmp));
5302
5303             if Nkind (N) = N_Raise_Constraint_Error then
5304
5305                --  Static error, nothing further to expand
5306
5307                return;
5308             end if;
5309          end if;
5310
5311       elsif Maybe_In_Place_OK
5312         and then Nkind (Name (Parent (N))) = N_Slice
5313         and then Safe_Slice_Assignment (N)
5314       then
5315          --  Safe_Slice_Assignment rewrites assignment as a loop
5316
5317          return;
5318
5319       --  Step 5
5320
5321       --  In place aggregate expansion is not possible
5322
5323       else
5324          Maybe_In_Place_OK := False;
5325          Tmp := Make_Temporary (Loc, 'A', N);
5326          Tmp_Decl :=
5327            Make_Object_Declaration
5328              (Loc,
5329               Defining_Identifier => Tmp,
5330               Object_Definition   => New_Occurrence_Of (Typ, Loc));
5331          Set_No_Initialization (Tmp_Decl, True);
5332
5333          --  If we are within a loop, the temporary will be pushed on the
5334          --  stack at each iteration. If the aggregate is the expression for an
5335          --  allocator, it will be immediately copied to the heap and can
5336          --  be reclaimed at once. We create a transient scope around the
5337          --  aggregate for this purpose.
5338
5339          if Ekind (Current_Scope) = E_Loop
5340            and then Nkind (Parent (Parent (N))) = N_Allocator
5341          then
5342             Establish_Transient_Scope (N, False);
5343          end if;
5344
5345          Insert_Action (N, Tmp_Decl);
5346       end if;
5347
5348       --  Construct and insert the aggregate code. We can safely suppress index
5349       --  checks because this code is guaranteed not to raise CE on index
5350       --  checks. However we should *not* suppress all checks.
5351
5352       declare
5353          Target : Node_Id;
5354
5355       begin
5356          if Nkind (Tmp) = N_Defining_Identifier then
5357             Target := New_Reference_To (Tmp, Loc);
5358
5359          else
5360
5361             if Has_Default_Init_Comps (N) then
5362
5363                --  Ada 2005 (AI-287): This case has not been analyzed???
5364
5365                raise Program_Error;
5366             end if;
5367
5368             --  Name in assignment is explicit dereference
5369
5370             Target := New_Copy (Tmp);
5371          end if;
5372
5373          Aggr_Code :=
5374            Build_Array_Aggr_Code (N,
5375              Ctype       => Ctyp,
5376              Index       => First_Index (Typ),
5377              Into        => Target,
5378              Scalar_Comp => Is_Scalar_Type (Ctyp));
5379       end;
5380
5381       if Comes_From_Source (Tmp) then
5382          Insert_Actions_After (Parent (N), Aggr_Code);
5383
5384       else
5385          Insert_Actions (N, Aggr_Code);
5386       end if;
5387
5388       --  If the aggregate has been assigned in place, remove the original
5389       --  assignment.
5390
5391       if Nkind (Parent (N)) = N_Assignment_Statement
5392         and then Maybe_In_Place_OK
5393       then
5394          Rewrite (Parent (N), Make_Null_Statement (Loc));
5395
5396       elsif Nkind (Parent (N)) /= N_Object_Declaration
5397         or else Tmp /= Defining_Identifier (Parent (N))
5398       then
5399          Rewrite (N, New_Occurrence_Of (Tmp, Loc));
5400          Analyze_And_Resolve (N, Typ);
5401       end if;
5402    end Expand_Array_Aggregate;
5403
5404    ------------------------
5405    -- Expand_N_Aggregate --
5406    ------------------------
5407
5408    procedure Expand_N_Aggregate (N : Node_Id) is
5409    begin
5410       if Is_Record_Type (Etype (N)) then
5411          Expand_Record_Aggregate (N);
5412       else
5413          Expand_Array_Aggregate (N);
5414       end if;
5415    exception
5416       when RE_Not_Available =>
5417          return;
5418    end Expand_N_Aggregate;
5419
5420    ----------------------------------
5421    -- Expand_N_Extension_Aggregate --
5422    ----------------------------------
5423
5424    --  If the ancestor part is an expression, add a component association for
5425    --  the parent field. If the type of the ancestor part is not the direct
5426    --  parent of the expected type,  build recursively the needed ancestors.
5427    --  If the ancestor part is a subtype_mark, replace aggregate with a decla-
5428    --  ration for a temporary of the expected type, followed by individual
5429    --  assignments to the given components.
5430
5431    procedure Expand_N_Extension_Aggregate (N : Node_Id) is
5432       Loc : constant Source_Ptr := Sloc  (N);
5433       A   : constant Node_Id    := Ancestor_Part (N);
5434       Typ : constant Entity_Id  := Etype (N);
5435
5436    begin
5437       --  If the ancestor is a subtype mark, an init proc must be called
5438       --  on the resulting object which thus has to be materialized in
5439       --  the front-end
5440
5441       if Is_Entity_Name (A) and then Is_Type (Entity (A)) then
5442          Convert_To_Assignments (N, Typ);
5443
5444       --  The extension aggregate is transformed into a record aggregate
5445       --  of the following form (c1 and c2 are inherited components)
5446
5447       --   (Exp with c3 => a, c4 => b)
5448       --      ==> (c1 => Exp.c1, c2 => Exp.c2, c3 => a, c4 => b)
5449
5450       else
5451          Set_Etype (N, Typ);
5452
5453          if Tagged_Type_Expansion then
5454             Expand_Record_Aggregate (N,
5455               Orig_Tag    =>
5456                 New_Occurrence_Of
5457                   (Node (First_Elmt (Access_Disp_Table (Typ))), Loc),
5458               Parent_Expr => A);
5459
5460          --  No tag is needed in the case of a VM
5461
5462          else
5463             Expand_Record_Aggregate (N, Parent_Expr => A);
5464          end if;
5465       end if;
5466
5467    exception
5468       when RE_Not_Available =>
5469          return;
5470    end Expand_N_Extension_Aggregate;
5471
5472    -----------------------------
5473    -- Expand_Record_Aggregate --
5474    -----------------------------
5475
5476    procedure Expand_Record_Aggregate
5477      (N           : Node_Id;
5478       Orig_Tag    : Node_Id := Empty;
5479       Parent_Expr : Node_Id := Empty)
5480    is
5481       Loc      : constant Source_Ptr := Sloc  (N);
5482       Comps    : constant List_Id    := Component_Associations (N);
5483       Typ      : constant Entity_Id  := Etype (N);
5484       Base_Typ : constant Entity_Id  := Base_Type (Typ);
5485
5486       Static_Components : Boolean := True;
5487       --  Flag to indicate whether all components are compile-time known,
5488       --  and the aggregate can be constructed statically and handled by
5489       --  the back-end.
5490
5491       function Component_Not_OK_For_Backend return Boolean;
5492       --  Check for presence of component which makes it impossible for the
5493       --  backend to process the aggregate, thus requiring the use of a series
5494       --  of assignment statements. Cases checked for are a nested aggregate
5495       --  needing Late_Expansion, the presence of a tagged component which may
5496       --  need tag adjustment, and a bit unaligned component reference.
5497       --
5498       --  We also force expansion into assignments if a component is of a
5499       --  mutable type (including a private type with discriminants) because
5500       --  in that case the size of the component to be copied may be smaller
5501       --  than the side of the target, and there is no simple way for gigi
5502       --  to compute the size of the object to be copied.
5503       --
5504       --  NOTE: This is part of the ongoing work to define precisely the
5505       --  interface between front-end and back-end handling of aggregates.
5506       --  In general it is desirable to pass aggregates as they are to gigi,
5507       --  in order to minimize elaboration code. This is one case where the
5508       --  semantics of Ada complicate the analysis and lead to anomalies in
5509       --  the gcc back-end if the aggregate is not expanded into assignments.
5510
5511       ----------------------------------
5512       -- Component_Not_OK_For_Backend --
5513       ----------------------------------
5514
5515       function Component_Not_OK_For_Backend return Boolean is
5516          C      : Node_Id;
5517          Expr_Q : Node_Id;
5518
5519       begin
5520          if No (Comps) then
5521             return False;
5522          end if;
5523
5524          C := First (Comps);
5525          while Present (C) loop
5526
5527             --  If the component has box initialization, expansion is needed
5528             --  and component is not ready for backend.
5529
5530             if Box_Present (C) then
5531                return True;
5532             end if;
5533
5534             if Nkind (Expression (C)) = N_Qualified_Expression then
5535                Expr_Q := Expression (Expression (C));
5536             else
5537                Expr_Q := Expression (C);
5538             end if;
5539
5540             --  Return true if the aggregate has any associations for tagged
5541             --  components that may require tag adjustment.
5542
5543             --  These are cases where the source expression may have a tag that
5544             --  could differ from the component tag (e.g., can occur for type
5545             --  conversions and formal parameters). (Tag adjustment not needed
5546             --  if VM_Target because object tags are implicit in the machine.)
5547
5548             if Is_Tagged_Type (Etype (Expr_Q))
5549               and then (Nkind (Expr_Q) = N_Type_Conversion
5550                          or else (Is_Entity_Name (Expr_Q)
5551                                     and then
5552                                       Ekind (Entity (Expr_Q)) in Formal_Kind))
5553               and then Tagged_Type_Expansion
5554             then
5555                Static_Components := False;
5556                return True;
5557
5558             elsif Is_Delayed_Aggregate (Expr_Q) then
5559                Static_Components := False;
5560                return True;
5561
5562             elsif Possible_Bit_Aligned_Component (Expr_Q) then
5563                Static_Components := False;
5564                return True;
5565             end if;
5566
5567             if Is_Scalar_Type (Etype (Expr_Q)) then
5568                if not Compile_Time_Known_Value (Expr_Q) then
5569                   Static_Components := False;
5570                end if;
5571
5572             elsif Nkind (Expr_Q) /= N_Aggregate
5573               or else not Compile_Time_Known_Aggregate (Expr_Q)
5574             then
5575                Static_Components := False;
5576
5577                if Is_Private_Type (Etype (Expr_Q))
5578                  and then Has_Discriminants (Etype (Expr_Q))
5579                then
5580                   return True;
5581                end if;
5582             end if;
5583
5584             Next (C);
5585          end loop;
5586
5587          return False;
5588       end Component_Not_OK_For_Backend;
5589
5590       --  Remaining Expand_Record_Aggregate variables
5591
5592       Tag_Value : Node_Id;
5593       Comp      : Entity_Id;
5594       New_Comp  : Node_Id;
5595
5596    --  Start of processing for Expand_Record_Aggregate
5597
5598    begin
5599       --  If the aggregate is to be assigned to an atomic variable, we
5600       --  have to prevent a piecemeal assignment even if the aggregate
5601       --  is to be expanded. We create a temporary for the aggregate, and
5602       --  assign the temporary instead, so that the back end can generate
5603       --  an atomic move for it.
5604
5605       if Is_Atomic (Typ)
5606         and then Comes_From_Source (Parent (N))
5607         and then Is_Atomic_Aggregate (N, Typ)
5608       then
5609          return;
5610
5611       --  No special management required for aggregates used to initialize
5612       --  statically allocated dispatch tables
5613
5614       elsif Is_Static_Dispatch_Table_Aggregate (N) then
5615          return;
5616       end if;
5617
5618       --  Ada 2005 (AI-318-2): We need to convert to assignments if components
5619       --  are build-in-place function calls. The assignments will each turn
5620       --  into a build-in-place function call.  If components are all static,
5621       --  we can pass the aggregate to the backend regardless of limitedness.
5622
5623       --  Extension aggregates, aggregates in extended return statements, and
5624       --  aggregates for C++ imported types must be expanded.
5625
5626       if Ada_Version >= Ada_2005 and then Is_Immutably_Limited_Type (Typ) then
5627          if not Nkind_In (Parent (N), N_Object_Declaration,
5628                                       N_Component_Association)
5629          then
5630             Convert_To_Assignments (N, Typ);
5631
5632          elsif Nkind (N) = N_Extension_Aggregate
5633            or else Convention (Typ) = Convention_CPP
5634          then
5635             Convert_To_Assignments (N, Typ);
5636
5637          elsif not Size_Known_At_Compile_Time (Typ)
5638            or else Component_Not_OK_For_Backend
5639            or else not Static_Components
5640          then
5641             Convert_To_Assignments (N, Typ);
5642
5643          else
5644             Set_Compile_Time_Known_Aggregate (N);
5645             Set_Expansion_Delayed (N, False);
5646          end if;
5647
5648       --  Gigi doesn't properly handle temporaries of variable size so we
5649       --  generate it in the front-end
5650
5651       elsif not Size_Known_At_Compile_Time (Typ)
5652         and then Tagged_Type_Expansion
5653       then
5654          Convert_To_Assignments (N, Typ);
5655
5656       --  Temporaries for controlled aggregates need to be attached to a final
5657       --  chain in order to be properly finalized, so it has to be created in
5658       --  the front-end
5659
5660       elsif Is_Controlled (Typ)
5661         or else Has_Controlled_Component (Base_Type (Typ))
5662       then
5663          Convert_To_Assignments (N, Typ);
5664
5665          --  Ada 2005 (AI-287): In case of default initialized components we
5666          --  convert the aggregate into assignments.
5667
5668       elsif Has_Default_Init_Comps (N) then
5669          Convert_To_Assignments (N, Typ);
5670
5671       --  Check components
5672
5673       elsif Component_Not_OK_For_Backend then
5674          Convert_To_Assignments (N, Typ);
5675
5676       --  If an ancestor is private, some components are not inherited and
5677       --  we cannot expand into a record aggregate
5678
5679       elsif Has_Private_Ancestor (Typ) then
5680          Convert_To_Assignments (N, Typ);
5681
5682       --  ??? The following was done to compile fxacc00.ads in the ACVCs. Gigi
5683       --  is not able to handle the aggregate for Late_Request.
5684
5685       elsif Is_Tagged_Type (Typ) and then Has_Discriminants (Typ) then
5686          Convert_To_Assignments (N, Typ);
5687
5688       --  If the tagged types covers interface types we need to initialize all
5689       --  hidden components containing pointers to secondary dispatch tables.
5690
5691       elsif Is_Tagged_Type (Typ) and then Has_Interfaces (Typ) then
5692          Convert_To_Assignments (N, Typ);
5693
5694       --  If some components are mutable, the size of the aggregate component
5695       --  may be distinct from the default size of the type component, so
5696       --  we need to expand to insure that the back-end copies the proper
5697       --  size of the data. However, if the aggregate is the initial value of
5698       --  a constant, the target is immutable and may be built statically.
5699
5700       elsif Has_Mutable_Components (Typ)
5701         and then
5702           (Nkind (Parent (N)) /= N_Object_Declaration
5703              or else not Constant_Present (Parent (N)))
5704       then
5705          Convert_To_Assignments (N, Typ);
5706
5707       --  If the type involved has any non-bit aligned components, then we are
5708       --  not sure that the back end can handle this case correctly.
5709
5710       elsif Type_May_Have_Bit_Aligned_Components (Typ) then
5711          Convert_To_Assignments (N, Typ);
5712
5713       --  In all other cases, build a proper aggregate handlable by gigi
5714
5715       else
5716          if Nkind (N) = N_Aggregate then
5717
5718             --  If the aggregate is static and can be handled by the back-end,
5719             --  nothing left to do.
5720
5721             if Static_Components then
5722                Set_Compile_Time_Known_Aggregate (N);
5723                Set_Expansion_Delayed (N, False);
5724             end if;
5725          end if;
5726
5727          --  If no discriminants, nothing special to do
5728
5729          if not Has_Discriminants (Typ) then
5730             null;
5731
5732          --  Case of discriminants present
5733
5734          elsif Is_Derived_Type (Typ) then
5735
5736             --  For untagged types,  non-stored discriminants are replaced
5737             --  with stored discriminants, which are the ones that gigi uses
5738             --  to describe the type and its components.
5739
5740             Generate_Aggregate_For_Derived_Type : declare
5741                Constraints  : constant List_Id := New_List;
5742                First_Comp   : Node_Id;
5743                Discriminant : Entity_Id;
5744                Decl         : Node_Id;
5745                Num_Disc     : Int := 0;
5746                Num_Gird     : Int := 0;
5747
5748                procedure Prepend_Stored_Values (T : Entity_Id);
5749                --  Scan the list of stored discriminants of the type, and add
5750                --  their values to the aggregate being built.
5751
5752                ---------------------------
5753                -- Prepend_Stored_Values --
5754                ---------------------------
5755
5756                procedure Prepend_Stored_Values (T : Entity_Id) is
5757                begin
5758                   Discriminant := First_Stored_Discriminant (T);
5759                   while Present (Discriminant) loop
5760                      New_Comp :=
5761                        Make_Component_Association (Loc,
5762                          Choices    =>
5763                            New_List (New_Occurrence_Of (Discriminant, Loc)),
5764
5765                          Expression =>
5766                            New_Copy_Tree (
5767                              Get_Discriminant_Value (
5768                                  Discriminant,
5769                                  Typ,
5770                                  Discriminant_Constraint (Typ))));
5771
5772                      if No (First_Comp) then
5773                         Prepend_To (Component_Associations (N), New_Comp);
5774                      else
5775                         Insert_After (First_Comp, New_Comp);
5776                      end if;
5777
5778                      First_Comp := New_Comp;
5779                      Next_Stored_Discriminant (Discriminant);
5780                   end loop;
5781                end Prepend_Stored_Values;
5782
5783             --  Start of processing for Generate_Aggregate_For_Derived_Type
5784
5785             begin
5786                --  Remove the associations for the discriminant of derived type
5787
5788                First_Comp := First (Component_Associations (N));
5789                while Present (First_Comp) loop
5790                   Comp := First_Comp;
5791                   Next (First_Comp);
5792
5793                   if Ekind (Entity
5794                              (First (Choices (Comp)))) = E_Discriminant
5795                   then
5796                      Remove (Comp);
5797                      Num_Disc := Num_Disc + 1;
5798                   end if;
5799                end loop;
5800
5801                --  Insert stored discriminant associations in the correct
5802                --  order. If there are more stored discriminants than new
5803                --  discriminants, there is at least one new discriminant that
5804                --  constrains more than one of the stored discriminants. In
5805                --  this case we need to construct a proper subtype of the
5806                --  parent type, in order to supply values to all the
5807                --  components. Otherwise there is one-one correspondence
5808                --  between the constraints and the stored discriminants.
5809
5810                First_Comp := Empty;
5811
5812                Discriminant := First_Stored_Discriminant (Base_Type (Typ));
5813                while Present (Discriminant) loop
5814                   Num_Gird := Num_Gird + 1;
5815                   Next_Stored_Discriminant (Discriminant);
5816                end loop;
5817
5818                --  Case of more stored discriminants than new discriminants
5819
5820                if Num_Gird > Num_Disc then
5821
5822                   --  Create a proper subtype of the parent type, which is the
5823                   --  proper implementation type for the aggregate, and convert
5824                   --  it to the intended target type.
5825
5826                   Discriminant := First_Stored_Discriminant (Base_Type (Typ));
5827                   while Present (Discriminant) loop
5828                      New_Comp :=
5829                        New_Copy_Tree (
5830                          Get_Discriminant_Value (
5831                              Discriminant,
5832                              Typ,
5833                              Discriminant_Constraint (Typ)));
5834                      Append (New_Comp, Constraints);
5835                      Next_Stored_Discriminant (Discriminant);
5836                   end loop;
5837
5838                   Decl :=
5839                     Make_Subtype_Declaration (Loc,
5840                       Defining_Identifier => Make_Temporary (Loc, 'T'),
5841                       Subtype_Indication =>
5842                         Make_Subtype_Indication (Loc,
5843                           Subtype_Mark =>
5844                             New_Occurrence_Of (Etype (Base_Type (Typ)), Loc),
5845                           Constraint =>
5846                             Make_Index_Or_Discriminant_Constraint
5847                               (Loc, Constraints)));
5848
5849                   Insert_Action (N, Decl);
5850                   Prepend_Stored_Values (Base_Type (Typ));
5851
5852                   Set_Etype (N, Defining_Identifier (Decl));
5853                   Set_Analyzed (N);
5854
5855                   Rewrite (N, Unchecked_Convert_To (Typ, N));
5856                   Analyze (N);
5857
5858                --  Case where we do not have fewer new discriminants than
5859                --  stored discriminants, so in this case we can simply use the
5860                --  stored discriminants of the subtype.
5861
5862                else
5863                   Prepend_Stored_Values (Typ);
5864                end if;
5865             end Generate_Aggregate_For_Derived_Type;
5866          end if;
5867
5868          if Is_Tagged_Type (Typ) then
5869
5870             --  The tagged case, _parent and _tag component must be created
5871
5872             --  Reset null_present unconditionally. tagged records always have
5873             --  at least one field (the tag or the parent)
5874
5875             Set_Null_Record_Present (N, False);
5876
5877             --  When the current aggregate comes from the expansion of an
5878             --  extension aggregate, the parent expr is replaced by an
5879             --  aggregate formed by selected components of this expr
5880
5881             if Present (Parent_Expr)
5882               and then Is_Empty_List (Comps)
5883             then
5884                Comp := First_Component_Or_Discriminant (Typ);
5885                while Present (Comp) loop
5886
5887                   --  Skip all expander-generated components
5888
5889                   if
5890                     not Comes_From_Source (Original_Record_Component (Comp))
5891                   then
5892                      null;
5893
5894                   else
5895                      New_Comp :=
5896                        Make_Selected_Component (Loc,
5897                          Prefix =>
5898                            Unchecked_Convert_To (Typ,
5899                              Duplicate_Subexpr (Parent_Expr, True)),
5900
5901                          Selector_Name => New_Occurrence_Of (Comp, Loc));
5902
5903                      Append_To (Comps,
5904                        Make_Component_Association (Loc,
5905                          Choices    =>
5906                            New_List (New_Occurrence_Of (Comp, Loc)),
5907                          Expression =>
5908                            New_Comp));
5909
5910                      Analyze_And_Resolve (New_Comp, Etype (Comp));
5911                   end if;
5912
5913                   Next_Component_Or_Discriminant (Comp);
5914                end loop;
5915             end if;
5916
5917             --  Compute the value for the Tag now, if the type is a root it
5918             --  will be included in the aggregate right away, otherwise it will
5919             --  be propagated to the parent aggregate
5920
5921             if Present (Orig_Tag) then
5922                Tag_Value := Orig_Tag;
5923             elsif not Tagged_Type_Expansion then
5924                Tag_Value := Empty;
5925             else
5926                Tag_Value :=
5927                  New_Occurrence_Of
5928                    (Node (First_Elmt (Access_Disp_Table (Typ))), Loc);
5929             end if;
5930
5931             --  For a derived type, an aggregate for the parent is formed with
5932             --  all the inherited components.
5933
5934             if Is_Derived_Type (Typ) then
5935
5936                declare
5937                   First_Comp   : Node_Id;
5938                   Parent_Comps : List_Id;
5939                   Parent_Aggr  : Node_Id;
5940                   Parent_Name  : Node_Id;
5941
5942                begin
5943                   --  Remove the inherited component association from the
5944                   --  aggregate and store them in the parent aggregate
5945
5946                   First_Comp := First (Component_Associations (N));
5947                   Parent_Comps := New_List;
5948                   while Present (First_Comp)
5949                     and then Scope (Original_Record_Component (
5950                             Entity (First (Choices (First_Comp))))) /= Base_Typ
5951                   loop
5952                      Comp := First_Comp;
5953                      Next (First_Comp);
5954                      Remove (Comp);
5955                      Append (Comp, Parent_Comps);
5956                   end loop;
5957
5958                   Parent_Aggr := Make_Aggregate (Loc,
5959                     Component_Associations => Parent_Comps);
5960                   Set_Etype (Parent_Aggr, Etype (Base_Type (Typ)));
5961
5962                   --  Find the _parent component
5963
5964                   Comp := First_Component (Typ);
5965                   while Chars (Comp) /= Name_uParent loop
5966                      Comp := Next_Component (Comp);
5967                   end loop;
5968
5969                   Parent_Name := New_Occurrence_Of (Comp, Loc);
5970
5971                   --  Insert the parent aggregate
5972
5973                   Prepend_To (Component_Associations (N),
5974                     Make_Component_Association (Loc,
5975                       Choices    => New_List (Parent_Name),
5976                       Expression => Parent_Aggr));
5977
5978                   --  Expand recursively the parent propagating the right Tag
5979
5980                   Expand_Record_Aggregate (
5981                     Parent_Aggr, Tag_Value, Parent_Expr);
5982                end;
5983
5984             --  For a root type, the tag component is added (unless compiling
5985             --  for the VMs, where tags are implicit).
5986
5987             elsif Tagged_Type_Expansion then
5988                declare
5989                   Tag_Name  : constant Node_Id :=
5990                                 New_Occurrence_Of
5991                                   (First_Tag_Component (Typ), Loc);
5992                   Typ_Tag   : constant Entity_Id := RTE (RE_Tag);
5993                   Conv_Node : constant Node_Id :=
5994                                 Unchecked_Convert_To (Typ_Tag, Tag_Value);
5995
5996                begin
5997                   Set_Etype (Conv_Node, Typ_Tag);
5998                   Prepend_To (Component_Associations (N),
5999                     Make_Component_Association (Loc,
6000                       Choices    => New_List (Tag_Name),
6001                       Expression => Conv_Node));
6002                end;
6003             end if;
6004          end if;
6005       end if;
6006
6007    end Expand_Record_Aggregate;
6008
6009    ----------------------------
6010    -- Has_Default_Init_Comps --
6011    ----------------------------
6012
6013    function Has_Default_Init_Comps (N : Node_Id) return Boolean is
6014       Comps : constant List_Id := Component_Associations (N);
6015       C     : Node_Id;
6016       Expr  : Node_Id;
6017    begin
6018       pragma Assert (Nkind_In (N, N_Aggregate, N_Extension_Aggregate));
6019
6020       if No (Comps) then
6021          return False;
6022       end if;
6023
6024       if Has_Self_Reference (N) then
6025          return True;
6026       end if;
6027
6028       --  Check if any direct component has default initialized components
6029
6030       C := First (Comps);
6031       while Present (C) loop
6032          if Box_Present (C) then
6033             return True;
6034          end if;
6035
6036          Next (C);
6037       end loop;
6038
6039       --  Recursive call in case of aggregate expression
6040
6041       C := First (Comps);
6042       while Present (C) loop
6043          Expr := Expression (C);
6044
6045          if Present (Expr)
6046            and then
6047              Nkind_In (Expr, N_Aggregate, N_Extension_Aggregate)
6048            and then Has_Default_Init_Comps (Expr)
6049          then
6050             return True;
6051          end if;
6052
6053          Next (C);
6054       end loop;
6055
6056       return False;
6057    end Has_Default_Init_Comps;
6058
6059    --------------------------
6060    -- Is_Delayed_Aggregate --
6061    --------------------------
6062
6063    function Is_Delayed_Aggregate (N : Node_Id) return Boolean is
6064       Node : Node_Id   := N;
6065       Kind : Node_Kind := Nkind (Node);
6066
6067    begin
6068       if Kind = N_Qualified_Expression then
6069          Node := Expression (Node);
6070          Kind := Nkind (Node);
6071       end if;
6072
6073       if Kind /= N_Aggregate and then Kind /= N_Extension_Aggregate then
6074          return False;
6075       else
6076          return Expansion_Delayed (Node);
6077       end if;
6078    end Is_Delayed_Aggregate;
6079
6080    ----------------------------------------
6081    -- Is_Static_Dispatch_Table_Aggregate --
6082    ----------------------------------------
6083
6084    function Is_Static_Dispatch_Table_Aggregate (N : Node_Id) return Boolean is
6085       Typ : constant Entity_Id := Base_Type (Etype (N));
6086
6087    begin
6088       return Static_Dispatch_Tables
6089         and then Tagged_Type_Expansion
6090         and then RTU_Loaded (Ada_Tags)
6091
6092          --  Avoid circularity when rebuilding the compiler
6093
6094         and then Cunit_Entity (Get_Source_Unit (N)) /= RTU_Entity (Ada_Tags)
6095         and then (Typ = RTE (RE_Dispatch_Table_Wrapper)
6096                     or else
6097                   Typ = RTE (RE_Address_Array)
6098                     or else
6099                   Typ = RTE (RE_Type_Specific_Data)
6100                     or else
6101                   Typ = RTE (RE_Tag_Table)
6102                     or else
6103                   (RTE_Available (RE_Interface_Data)
6104                      and then Typ = RTE (RE_Interface_Data))
6105                     or else
6106                   (RTE_Available (RE_Interfaces_Array)
6107                      and then Typ = RTE (RE_Interfaces_Array))
6108                     or else
6109                   (RTE_Available (RE_Interface_Data_Element)
6110                      and then Typ = RTE (RE_Interface_Data_Element)));
6111    end Is_Static_Dispatch_Table_Aggregate;
6112
6113    --------------------
6114    -- Late_Expansion --
6115    --------------------
6116
6117    function Late_Expansion
6118      (N      : Node_Id;
6119       Typ    : Entity_Id;
6120       Target : Node_Id;
6121       Flist  : Node_Id   := Empty;
6122       Obj    : Entity_Id := Empty) return List_Id
6123    is
6124    begin
6125       if Is_Record_Type (Etype (N)) then
6126          return Build_Record_Aggr_Code (N, Typ, Target, Flist, Obj);
6127
6128       else pragma Assert (Is_Array_Type (Etype (N)));
6129          return
6130            Build_Array_Aggr_Code
6131              (N           => N,
6132               Ctype       => Component_Type (Etype (N)),
6133               Index       => First_Index (Typ),
6134               Into        => Target,
6135               Scalar_Comp => Is_Scalar_Type (Component_Type (Typ)),
6136               Indexes     => No_List,
6137               Flist       => Flist);
6138       end if;
6139    end Late_Expansion;
6140
6141    ----------------------------------
6142    -- Make_OK_Assignment_Statement --
6143    ----------------------------------
6144
6145    function Make_OK_Assignment_Statement
6146      (Sloc       : Source_Ptr;
6147       Name       : Node_Id;
6148       Expression : Node_Id) return Node_Id
6149    is
6150    begin
6151       Set_Assignment_OK (Name);
6152
6153       return Make_Assignment_Statement (Sloc, Name, Expression);
6154    end Make_OK_Assignment_Statement;
6155
6156    -----------------------
6157    -- Number_Of_Choices --
6158    -----------------------
6159
6160    function Number_Of_Choices (N : Node_Id) return Nat is
6161       Assoc  : Node_Id;
6162       Choice : Node_Id;
6163
6164       Nb_Choices : Nat := 0;
6165
6166    begin
6167       if Present (Expressions (N)) then
6168          return 0;
6169       end if;
6170
6171       Assoc := First (Component_Associations (N));
6172       while Present (Assoc) loop
6173          Choice := First (Choices (Assoc));
6174          while Present (Choice) loop
6175             if Nkind (Choice) /= N_Others_Choice then
6176                Nb_Choices := Nb_Choices + 1;
6177             end if;
6178
6179             Next (Choice);
6180          end loop;
6181
6182          Next (Assoc);
6183       end loop;
6184
6185       return Nb_Choices;
6186    end Number_Of_Choices;
6187
6188    ------------------------------------
6189    -- Packed_Array_Aggregate_Handled --
6190    ------------------------------------
6191
6192    --  The current version of this procedure will handle at compile time
6193    --  any array aggregate that meets these conditions:
6194
6195    --    One dimensional, bit packed
6196    --    Underlying packed type is modular type
6197    --    Bounds are within 32-bit Int range
6198    --    All bounds and values are static
6199
6200    function Packed_Array_Aggregate_Handled (N : Node_Id) return Boolean is
6201       Loc  : constant Source_Ptr := Sloc (N);
6202       Typ  : constant Entity_Id  := Etype (N);
6203       Ctyp : constant Entity_Id  := Component_Type (Typ);
6204
6205       Not_Handled : exception;
6206       --  Exception raised if this aggregate cannot be handled
6207
6208    begin
6209       --  For now, handle only one dimensional bit packed arrays
6210
6211       if not Is_Bit_Packed_Array (Typ)
6212         or else Number_Dimensions (Typ) > 1
6213         or else not Is_Modular_Integer_Type (Packed_Array_Type (Typ))
6214       then
6215          return False;
6216       end if;
6217
6218       if not Is_Scalar_Type (Component_Type (Typ))
6219         and then Has_Non_Standard_Rep (Component_Type (Typ))
6220       then
6221          return False;
6222       end if;
6223
6224       declare
6225          Csiz  : constant Nat := UI_To_Int (Component_Size (Typ));
6226
6227          Lo : Node_Id;
6228          Hi : Node_Id;
6229          --  Bounds of index type
6230
6231          Lob : Uint;
6232          Hib : Uint;
6233          --  Values of bounds if compile time known
6234
6235          function Get_Component_Val (N : Node_Id) return Uint;
6236          --  Given a expression value N of the component type Ctyp, returns a
6237          --  value of Csiz (component size) bits representing this value. If
6238          --  the value is non-static or any other reason exists why the value
6239          --  cannot be returned, then Not_Handled is raised.
6240
6241          -----------------------
6242          -- Get_Component_Val --
6243          -----------------------
6244
6245          function Get_Component_Val (N : Node_Id) return Uint is
6246             Val  : Uint;
6247
6248          begin
6249             --  We have to analyze the expression here before doing any further
6250             --  processing here. The analysis of such expressions is deferred
6251             --  till expansion to prevent some problems of premature analysis.
6252
6253             Analyze_And_Resolve (N, Ctyp);
6254
6255             --  Must have a compile time value. String literals have to be
6256             --  converted into temporaries as well, because they cannot easily
6257             --  be converted into their bit representation.
6258
6259             if not Compile_Time_Known_Value (N)
6260               or else Nkind (N) = N_String_Literal
6261             then
6262                raise Not_Handled;
6263             end if;
6264
6265             Val := Expr_Rep_Value (N);
6266
6267             --  Adjust for bias, and strip proper number of bits
6268
6269             if Has_Biased_Representation (Ctyp) then
6270                Val := Val - Expr_Value (Type_Low_Bound (Ctyp));
6271             end if;
6272
6273             return Val mod Uint_2 ** Csiz;
6274          end Get_Component_Val;
6275
6276       --  Here we know we have a one dimensional bit packed array
6277
6278       begin
6279          Get_Index_Bounds (First_Index (Typ), Lo, Hi);
6280
6281          --  Cannot do anything if bounds are dynamic
6282
6283          if not Compile_Time_Known_Value (Lo)
6284               or else
6285             not Compile_Time_Known_Value (Hi)
6286          then
6287             return False;
6288          end if;
6289
6290          --  Or are silly out of range of int bounds
6291
6292          Lob := Expr_Value (Lo);
6293          Hib := Expr_Value (Hi);
6294
6295          if not UI_Is_In_Int_Range (Lob)
6296               or else
6297             not UI_Is_In_Int_Range (Hib)
6298          then
6299             return False;
6300          end if;
6301
6302          --  At this stage we have a suitable aggregate for handling at compile
6303          --  time (the only remaining checks are that the values of expressions
6304          --  in the aggregate are compile time known (check is performed by
6305          --  Get_Component_Val), and that any subtypes or ranges are statically
6306          --  known.
6307
6308          --  If the aggregate is not fully positional at this stage, then
6309          --  convert it to positional form. Either this will fail, in which
6310          --  case we can do nothing, or it will succeed, in which case we have
6311          --  succeeded in handling the aggregate, or it will stay an aggregate,
6312          --  in which case we have failed to handle this case.
6313
6314          if Present (Component_Associations (N)) then
6315             Convert_To_Positional
6316              (N, Max_Others_Replicate => 64, Handle_Bit_Packed => True);
6317             return Nkind (N) /= N_Aggregate;
6318          end if;
6319
6320          --  Otherwise we are all positional, so convert to proper value
6321
6322          declare
6323             Lov : constant Int := UI_To_Int (Lob);
6324             Hiv : constant Int := UI_To_Int (Hib);
6325
6326             Len : constant Nat := Int'Max (0, Hiv - Lov + 1);
6327             --  The length of the array (number of elements)
6328
6329             Aggregate_Val : Uint;
6330             --  Value of aggregate. The value is set in the low order bits of
6331             --  this value. For the little-endian case, the values are stored
6332             --  from low-order to high-order and for the big-endian case the
6333             --  values are stored from high-order to low-order. Note that gigi
6334             --  will take care of the conversions to left justify the value in
6335             --  the big endian case (because of left justified modular type
6336             --  processing), so we do not have to worry about that here.
6337
6338             Lit : Node_Id;
6339             --  Integer literal for resulting constructed value
6340
6341             Shift : Nat;
6342             --  Shift count from low order for next value
6343
6344             Incr : Int;
6345             --  Shift increment for loop
6346
6347             Expr : Node_Id;
6348             --  Next expression from positional parameters of aggregate
6349
6350          begin
6351             --  For little endian, we fill up the low order bits of the target
6352             --  value. For big endian we fill up the high order bits of the
6353             --  target value (which is a left justified modular value).
6354
6355             if Bytes_Big_Endian xor Debug_Flag_8 then
6356                Shift := Csiz * (Len - 1);
6357                Incr  := -Csiz;
6358             else
6359                Shift := 0;
6360                Incr  := +Csiz;
6361             end if;
6362
6363             --  Loop to set the values
6364
6365             if Len = 0 then
6366                Aggregate_Val := Uint_0;
6367             else
6368                Expr := First (Expressions (N));
6369                Aggregate_Val := Get_Component_Val (Expr) * Uint_2 ** Shift;
6370
6371                for J in 2 .. Len loop
6372                   Shift := Shift + Incr;
6373                   Next (Expr);
6374                   Aggregate_Val :=
6375                     Aggregate_Val + Get_Component_Val (Expr) * Uint_2 ** Shift;
6376                end loop;
6377             end if;
6378
6379             --  Now we can rewrite with the proper value
6380
6381             Lit :=
6382               Make_Integer_Literal (Loc,
6383                 Intval => Aggregate_Val);
6384             Set_Print_In_Hex (Lit);
6385
6386             --  Construct the expression using this literal. Note that it is
6387             --  important to qualify the literal with its proper modular type
6388             --  since universal integer does not have the required range and
6389             --  also this is a left justified modular type, which is important
6390             --  in the big-endian case.
6391
6392             Rewrite (N,
6393               Unchecked_Convert_To (Typ,
6394                 Make_Qualified_Expression (Loc,
6395                   Subtype_Mark =>
6396                     New_Occurrence_Of (Packed_Array_Type (Typ), Loc),
6397                   Expression   => Lit)));
6398
6399             Analyze_And_Resolve (N, Typ);
6400             return True;
6401          end;
6402       end;
6403
6404    exception
6405       when Not_Handled =>
6406          return False;
6407    end Packed_Array_Aggregate_Handled;
6408
6409    ----------------------------
6410    -- Has_Mutable_Components --
6411    ----------------------------
6412
6413    function Has_Mutable_Components (Typ : Entity_Id) return Boolean is
6414       Comp : Entity_Id;
6415
6416    begin
6417       Comp := First_Component (Typ);
6418       while Present (Comp) loop
6419          if Is_Record_Type (Etype (Comp))
6420            and then Has_Discriminants (Etype (Comp))
6421            and then not Is_Constrained (Etype (Comp))
6422          then
6423             return True;
6424          end if;
6425
6426          Next_Component (Comp);
6427       end loop;
6428
6429       return False;
6430    end Has_Mutable_Components;
6431
6432    ------------------------------
6433    -- Initialize_Discriminants --
6434    ------------------------------
6435
6436    procedure Initialize_Discriminants (N : Node_Id; Typ : Entity_Id) is
6437       Loc  : constant Source_Ptr := Sloc (N);
6438       Bas  : constant Entity_Id  := Base_Type (Typ);
6439       Par  : constant Entity_Id  := Etype (Bas);
6440       Decl : constant Node_Id    := Parent (Par);
6441       Ref  : Node_Id;
6442
6443    begin
6444       if Is_Tagged_Type (Bas)
6445         and then Is_Derived_Type (Bas)
6446         and then Has_Discriminants (Par)
6447         and then Has_Discriminants (Bas)
6448         and then Number_Discriminants (Bas) /= Number_Discriminants (Par)
6449         and then Nkind (Decl) = N_Full_Type_Declaration
6450         and then Nkind (Type_Definition (Decl)) = N_Record_Definition
6451         and then Present
6452           (Variant_Part (Component_List (Type_Definition (Decl))))
6453         and then Nkind (N) /= N_Extension_Aggregate
6454       then
6455
6456          --   Call init proc to set discriminants.
6457          --   There should eventually be a special procedure for this ???
6458
6459          Ref := New_Reference_To (Defining_Identifier (N), Loc);
6460          Insert_Actions_After (N,
6461            Build_Initialization_Call (Sloc (N), Ref, Typ));
6462       end if;
6463    end Initialize_Discriminants;
6464
6465    ----------------
6466    -- Must_Slide --
6467    ----------------
6468
6469    function Must_Slide
6470      (Obj_Type : Entity_Id;
6471       Typ      : Entity_Id) return Boolean
6472    is
6473       L1, L2, H1, H2 : Node_Id;
6474    begin
6475       --  No sliding if the type of the object is not established yet, if it is
6476       --  an unconstrained type whose actual subtype comes from the aggregate,
6477       --  or if the two types are identical.
6478
6479       if not Is_Array_Type (Obj_Type) then
6480          return False;
6481
6482       elsif not Is_Constrained (Obj_Type) then
6483          return False;
6484
6485       elsif Typ = Obj_Type then
6486          return False;
6487
6488       else
6489          --  Sliding can only occur along the first dimension
6490
6491          Get_Index_Bounds (First_Index (Typ), L1, H1);
6492          Get_Index_Bounds (First_Index (Obj_Type), L2, H2);
6493
6494          if not Is_Static_Expression (L1)
6495            or else not Is_Static_Expression (L2)
6496            or else not Is_Static_Expression (H1)
6497            or else not Is_Static_Expression (H2)
6498          then
6499             return False;
6500          else
6501             return Expr_Value (L1) /= Expr_Value (L2)
6502               or else Expr_Value (H1) /= Expr_Value (H2);
6503          end if;
6504       end if;
6505    end Must_Slide;
6506
6507    ---------------------------
6508    -- Safe_Slice_Assignment --
6509    ---------------------------
6510
6511    function Safe_Slice_Assignment (N : Node_Id) return Boolean is
6512       Loc        : constant Source_Ptr := Sloc (Parent (N));
6513       Pref       : constant Node_Id    := Prefix (Name (Parent (N)));
6514       Range_Node : constant Node_Id    := Discrete_Range (Name (Parent (N)));
6515       Expr       : Node_Id;
6516       L_J        : Entity_Id;
6517       L_Iter     : Node_Id;
6518       L_Body     : Node_Id;
6519       Stat       : Node_Id;
6520
6521    begin
6522       --  Generate: for J in Range loop Pref (J) := Expr; end loop;
6523
6524       if Comes_From_Source (N)
6525         and then No (Expressions (N))
6526         and then Nkind (First (Choices (First (Component_Associations (N)))))
6527                    = N_Others_Choice
6528       then
6529          Expr := Expression (First (Component_Associations (N)));
6530          L_J := Make_Temporary (Loc, 'J');
6531
6532          L_Iter :=
6533            Make_Iteration_Scheme (Loc,
6534              Loop_Parameter_Specification =>
6535                Make_Loop_Parameter_Specification
6536                  (Loc,
6537                   Defining_Identifier         => L_J,
6538                   Discrete_Subtype_Definition => Relocate_Node (Range_Node)));
6539
6540          L_Body :=
6541            Make_Assignment_Statement (Loc,
6542               Name =>
6543                 Make_Indexed_Component (Loc,
6544                   Prefix      => Relocate_Node (Pref),
6545                   Expressions => New_List (New_Occurrence_Of (L_J, Loc))),
6546                Expression => Relocate_Node (Expr));
6547
6548          --  Construct the final loop
6549
6550          Stat :=
6551            Make_Implicit_Loop_Statement
6552              (Node             => Parent (N),
6553               Identifier       => Empty,
6554               Iteration_Scheme => L_Iter,
6555               Statements       => New_List (L_Body));
6556
6557          --  Set type of aggregate to be type of lhs in assignment,
6558          --  to suppress redundant length checks.
6559
6560          Set_Etype (N, Etype (Name (Parent (N))));
6561
6562          Rewrite (Parent (N), Stat);
6563          Analyze (Parent (N));
6564          return True;
6565
6566       else
6567          return False;
6568       end if;
6569    end Safe_Slice_Assignment;
6570
6571    ---------------------
6572    -- Sort_Case_Table --
6573    ---------------------
6574
6575    procedure Sort_Case_Table (Case_Table : in out Case_Table_Type) is
6576       L : constant Int := Case_Table'First;
6577       U : constant Int := Case_Table'Last;
6578       K : Int;
6579       J : Int;
6580       T : Case_Bounds;
6581
6582    begin
6583       K := L;
6584       while K /= U loop
6585          T := Case_Table (K + 1);
6586
6587          J := K + 1;
6588          while J /= L
6589            and then Expr_Value (Case_Table (J - 1).Choice_Lo) >
6590                     Expr_Value (T.Choice_Lo)
6591          loop
6592             Case_Table (J) := Case_Table (J - 1);
6593             J := J - 1;
6594          end loop;
6595
6596          Case_Table (J) := T;
6597          K := K + 1;
6598       end loop;
6599    end Sort_Case_Table;
6600
6601    ----------------------------
6602    -- Static_Array_Aggregate --
6603    ----------------------------
6604
6605    function Static_Array_Aggregate (N : Node_Id) return Boolean is
6606       Bounds : constant Node_Id := Aggregate_Bounds (N);
6607
6608       Typ       : constant Entity_Id := Etype (N);
6609       Comp_Type : constant Entity_Id := Component_Type (Typ);
6610       Agg       : Node_Id;
6611       Expr      : Node_Id;
6612       Lo        : Node_Id;
6613       Hi        : Node_Id;
6614
6615    begin
6616       if Is_Tagged_Type (Typ)
6617         or else Is_Controlled (Typ)
6618         or else Is_Packed (Typ)
6619       then
6620          return False;
6621       end if;
6622
6623       if Present (Bounds)
6624         and then Nkind (Bounds) = N_Range
6625         and then Nkind (Low_Bound  (Bounds)) = N_Integer_Literal
6626         and then Nkind (High_Bound (Bounds)) = N_Integer_Literal
6627       then
6628          Lo := Low_Bound  (Bounds);
6629          Hi := High_Bound (Bounds);
6630
6631          if No (Component_Associations (N)) then
6632
6633             --  Verify that all components are static integers
6634
6635             Expr := First (Expressions (N));
6636             while Present (Expr) loop
6637                if Nkind (Expr) /= N_Integer_Literal then
6638                   return False;
6639                end if;
6640
6641                Next (Expr);
6642             end loop;
6643
6644             return True;
6645
6646          else
6647             --  We allow only a single named association, either a static
6648             --  range or an others_clause, with a static expression.
6649
6650             Expr := First (Component_Associations (N));
6651
6652             if Present (Expressions (N)) then
6653                return False;
6654
6655             elsif Present (Next (Expr)) then
6656                return False;
6657
6658             elsif Present (Next (First (Choices (Expr)))) then
6659                return False;
6660
6661             else
6662                --  The aggregate is static if all components are literals,
6663                --  or else all its components are static aggregates for the
6664                --  component type. We also limit the size of a static aggregate
6665                --  to prevent runaway static expressions.
6666
6667                if Is_Array_Type (Comp_Type)
6668                  or else Is_Record_Type (Comp_Type)
6669                then
6670                   if Nkind (Expression (Expr)) /= N_Aggregate
6671                     or else
6672                       not Compile_Time_Known_Aggregate (Expression (Expr))
6673                   then
6674                      return False;
6675                   end if;
6676
6677                elsif Nkind (Expression (Expr)) /= N_Integer_Literal then
6678                   return False;
6679                end if;
6680
6681                if not Aggr_Size_OK (N, Typ) then
6682                   return False;
6683                end if;
6684
6685                --  Create a positional aggregate with the right number of
6686                --  copies of the expression.
6687
6688                Agg := Make_Aggregate (Sloc (N), New_List, No_List);
6689
6690                for I in UI_To_Int (Intval (Lo)) .. UI_To_Int (Intval (Hi))
6691                loop
6692                   Append_To
6693                     (Expressions (Agg), New_Copy (Expression (Expr)));
6694
6695                   --  The copied expression must be analyzed and resolved.
6696                   --  Besides setting the type, this ensures that static
6697                   --  expressions are appropriately marked as such.
6698
6699                   Analyze_And_Resolve
6700                     (Last (Expressions (Agg)), Component_Type (Typ));
6701                end loop;
6702
6703                Set_Aggregate_Bounds (Agg, Bounds);
6704                Set_Etype (Agg, Typ);
6705                Set_Analyzed (Agg);
6706                Rewrite (N, Agg);
6707                Set_Compile_Time_Known_Aggregate (N);
6708
6709                return True;
6710             end if;
6711          end if;
6712
6713       else
6714          return False;
6715       end if;
6716    end Static_Array_Aggregate;
6717
6718 end Exp_Aggr;