OSDN Git Service

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