OSDN Git Service

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