OSDN Git Service

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