OSDN Git Service

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