OSDN Git Service

2007-08-14 Gary Dismukes <dismukes@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / layout.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                               L A Y O U T                                --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 2001-2007, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 2,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT;  see file COPYING.  If not, write --
19 -- to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, --
20 -- Boston, MA 02110-1301, USA.                                              --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Einfo;    use Einfo;
31 with Errout;   use Errout;
32 with Exp_Ch3;  use Exp_Ch3;
33 with Exp_Util; use Exp_Util;
34 with Namet;    use Namet;
35 with Nlists;   use Nlists;
36 with Nmake;    use Nmake;
37 with Opt;      use Opt;
38 with Repinfo;  use Repinfo;
39 with Sem;      use Sem;
40 with Sem_Ch13; use Sem_Ch13;
41 with Sem_Eval; use Sem_Eval;
42 with Sem_Util; use Sem_Util;
43 with Sinfo;    use Sinfo;
44 with Snames;   use Snames;
45 with Stand;    use Stand;
46 with Targparm; use Targparm;
47 with Tbuild;   use Tbuild;
48 with Ttypes;   use Ttypes;
49 with Uintp;    use Uintp;
50
51 package body Layout is
52
53    ------------------------
54    -- Local Declarations --
55    ------------------------
56
57    SSU : constant Int := Ttypes.System_Storage_Unit;
58    --  Short hand for System_Storage_Unit
59
60    Vname : constant Name_Id := Name_uV;
61    --  Formal parameter name used for functions generated for size offset
62    --  values that depend on the discriminant. All such functions have the
63    --  following form:
64    --
65    --     function xxx (V : vtyp) return Unsigned is
66    --     begin
67    --        return ... expression involving V.discrim
68    --     end xxx;
69
70    -----------------------
71    -- Local Subprograms --
72    -----------------------
73
74    function Assoc_Add
75      (Loc        : Source_Ptr;
76       Left_Opnd  : Node_Id;
77       Right_Opnd : Node_Id) return Node_Id;
78    --  This is like Make_Op_Add except that it optimizes some cases knowing
79    --  that associative rearrangement is allowed for constant folding if one
80    --  of the operands is a compile time known value.
81
82    function Assoc_Multiply
83      (Loc        : Source_Ptr;
84       Left_Opnd  : Node_Id;
85       Right_Opnd : Node_Id) return Node_Id;
86    --  This is like Make_Op_Multiply except that it optimizes some cases
87    --  knowing that associative rearrangement is allowed for constant
88    --  folding if one of the operands is a compile time known value
89
90    function Assoc_Subtract
91      (Loc        : Source_Ptr;
92       Left_Opnd  : Node_Id;
93       Right_Opnd : Node_Id) return Node_Id;
94    --  This is like Make_Op_Subtract except that it optimizes some cases
95    --  knowing that associative rearrangement is allowed for constant
96    --  folding if one of the operands is a compile time known value
97
98    function Bits_To_SU (N : Node_Id) return Node_Id;
99    --  This is used when we cross the boundary from static sizes in bits to
100    --  dynamic sizes in storage units. If the argument N is anything other
101    --  than an integer literal, it is returned unchanged, but if it is an
102    --  integer literal, then it is taken as a size in bits, and is replaced
103    --  by the corresponding size in storage units.
104
105    function Compute_Length (Lo : Node_Id; Hi : Node_Id) return Node_Id;
106    --  Given expressions for the low bound (Lo) and the high bound (Hi),
107    --  Build an expression for the value hi-lo+1, converted to type
108    --  Standard.Unsigned. Takes care of the case where the operands
109    --  are of an enumeration type (so that the subtraction cannot be
110    --  done directly) by applying the Pos operator to Hi/Lo first.
111
112    function Expr_From_SO_Ref
113      (Loc  : Source_Ptr;
114       D    : SO_Ref;
115       Comp : Entity_Id := Empty) return Node_Id;
116    --  Given a value D from a size or offset field, return an expression
117    --  representing the value stored. If the value is known at compile time,
118    --  then an N_Integer_Literal is returned with the appropriate value. If
119    --  the value references a constant entity, then an N_Identifier node
120    --  referencing this entity is returned. If the value denotes a size
121    --  function, then returns a call node denoting the given function, with
122    --  a single actual parameter that either refers to the parameter V of
123    --  an enclosing size function (if Comp is Empty or its type doesn't match
124    --  the function's formal), or else is a selected component V.c when Comp
125    --  denotes a component c whose type matches that of the function formal.
126    --  The Loc value is used for the Sloc value of constructed notes.
127
128    function SO_Ref_From_Expr
129      (Expr      : Node_Id;
130       Ins_Type  : Entity_Id;
131       Vtype     : Entity_Id := Empty;
132       Make_Func : Boolean   := False) return Dynamic_SO_Ref;
133    --  This routine is used in the case where a size/offset value is dynamic
134    --  and is represented by the expression Expr. SO_Ref_From_Expr checks if
135    --  the Expr contains a reference to the identifier V, and if so builds
136    --  a function depending on discriminants of the formal parameter V which
137    --  is of type Vtype. Otherwise, if the parameter Make_Func is True, then
138    --  Expr will be encapsulated in a parameterless function; if Make_Func is
139    --  False, then a constant entity with the value Expr is built. The result
140    --  is a Dynamic_SO_Ref to the created entity. Note that Vtype can be
141    --  omitted if Expr does not contain any reference to V, the created entity.
142    --  The declaration created is inserted in the freeze actions of Ins_Type,
143    --  which also supplies the Sloc for created nodes. This function also takes
144    --  care of making sure that the expression is properly analyzed and
145    --  resolved (which may not be the case yet if we build the expression
146    --  in this unit).
147
148    function Get_Max_SU_Size (E : Entity_Id) return Node_Id;
149    --  E is an array type or subtype that has at least one index bound that
150    --  is the value of a record discriminant. For such an array, the function
151    --  computes an expression that yields the maximum possible size of the
152    --  array in storage units. The result is not defined for any other type,
153    --  or for arrays that do not depend on discriminants, and it is a fatal
154    --  error to call this unless Size_Depends_On_Discriminant (E) is True.
155
156    procedure Layout_Array_Type (E : Entity_Id);
157    --  Front-end layout of non-bit-packed array type or subtype
158
159    procedure Layout_Record_Type (E : Entity_Id);
160    --  Front-end layout of record type
161
162    procedure Rewrite_Integer (N : Node_Id; V : Uint);
163    --  Rewrite node N with an integer literal whose value is V. The Sloc
164    --  for the new node is taken from N, and the type of the literal is
165    --  set to a copy of the type of N on entry.
166
167    procedure Set_And_Check_Static_Size
168      (E      : Entity_Id;
169       Esiz   : SO_Ref;
170       RM_Siz : SO_Ref);
171    --  This procedure is called to check explicit given sizes (possibly
172    --  stored in the Esize and RM_Size fields of E) against computed
173    --  Object_Size (Esiz) and Value_Size (RM_Siz) values. Appropriate
174    --  errors and warnings are posted if specified sizes are inconsistent
175    --  with specified sizes. On return, the Esize and RM_Size fields of
176    --  E are set (either from previously given values, or from the newly
177    --  computed values, as appropriate).
178
179    procedure Set_Composite_Alignment (E : Entity_Id);
180    --  This procedure is called for record types and subtypes, and also for
181    --  atomic array types and subtypes. If no alignment is set, and the size
182    --  is 2 or 4 (or 8 if the word size is 8), then the alignment is set to
183    --  match the size.
184
185    ----------------------------
186    -- Adjust_Esize_Alignment --
187    ----------------------------
188
189    procedure Adjust_Esize_Alignment (E : Entity_Id) is
190       Abits     : Int;
191       Esize_Set : Boolean;
192
193    begin
194       --  Nothing to do if size unknown
195
196       if Unknown_Esize (E) then
197          return;
198       end if;
199
200       --  Determine if size is constrained by an attribute definition clause
201       --  which must be obeyed. If so, we cannot increase the size in this
202       --  routine.
203
204       --  For a type, the issue is whether an object size clause has been
205       --  set. A normal size clause constrains only the value size (RM_Size)
206
207       if Is_Type (E) then
208          Esize_Set := Has_Object_Size_Clause (E);
209
210       --  For an object, the issue is whether a size clause is present
211
212       else
213          Esize_Set := Has_Size_Clause (E);
214       end if;
215
216       --  If size is known it must be a multiple of the storage unit size
217
218       if Esize (E) mod SSU /= 0 then
219
220          --  If not, and size specified, then give error
221
222          if Esize_Set then
223             Error_Msg_NE
224               ("size for& not a multiple of storage unit size",
225                Size_Clause (E), E);
226             return;
227
228          --  Otherwise bump up size to a storage unit boundary
229
230          else
231             Set_Esize (E, (Esize (E) + SSU - 1) / SSU * SSU);
232          end if;
233       end if;
234
235       --  Now we have the size set, it must be a multiple of the alignment
236       --  nothing more we can do here if the alignment is unknown here.
237
238       if Unknown_Alignment (E) then
239          return;
240       end if;
241
242       --  At this point both the Esize and Alignment are known, so we need
243       --  to make sure they are consistent.
244
245       Abits := UI_To_Int (Alignment (E)) * SSU;
246
247       if Esize (E) mod Abits = 0 then
248          return;
249       end if;
250
251       --  Here we have a situation where the Esize is not a multiple of
252       --  the alignment. We must either increase Esize or reduce the
253       --  alignment to correct this situation.
254
255       --  The case in which we can decrease the alignment is where the
256       --  alignment was not set by an alignment clause, and the type in
257       --  question is a discrete type, where it is definitely safe to
258       --  reduce the alignment. For example:
259
260       --    t : integer range 1 .. 2;
261       --    for t'size use 8;
262
263       --  In this situation, the initial alignment of t is 4, copied from
264       --  the Integer base type, but it is safe to reduce it to 1 at this
265       --  stage, since we will only be loading a single storage unit.
266
267       if Is_Discrete_Type (Etype (E))
268         and then not Has_Alignment_Clause (E)
269       then
270          loop
271             Abits := Abits / 2;
272             exit when Esize (E) mod Abits = 0;
273          end loop;
274
275          Init_Alignment (E, Abits / SSU);
276          return;
277       end if;
278
279       --  Now the only possible approach left is to increase the Esize
280       --  but we can't do that if the size was set by a specific clause.
281
282       if Esize_Set then
283          Error_Msg_NE
284            ("size for& is not a multiple of alignment",
285             Size_Clause (E), E);
286
287       --  Otherwise we can indeed increase the size to a multiple of alignment
288
289       else
290          Set_Esize (E, ((Esize (E) + (Abits - 1)) / Abits) * Abits);
291       end if;
292    end Adjust_Esize_Alignment;
293
294    ---------------
295    -- Assoc_Add --
296    ---------------
297
298    function Assoc_Add
299      (Loc        : Source_Ptr;
300       Left_Opnd  : Node_Id;
301       Right_Opnd : Node_Id) return Node_Id
302    is
303       L : Node_Id;
304       R : Uint;
305
306    begin
307       --  Case of right operand is a constant
308
309       if Compile_Time_Known_Value (Right_Opnd) then
310          L := Left_Opnd;
311          R := Expr_Value (Right_Opnd);
312
313       --  Case of left operand is a constant
314
315       elsif Compile_Time_Known_Value (Left_Opnd) then
316          L := Right_Opnd;
317          R := Expr_Value (Left_Opnd);
318
319       --  Neither operand is a constant, do the addition with no optimization
320
321       else
322          return Make_Op_Add (Loc, Left_Opnd, Right_Opnd);
323       end if;
324
325       --  Case of left operand is an addition
326
327       if Nkind (L) = N_Op_Add then
328
329          --  (C1 + E) + C2 = (C1 + C2) + E
330
331          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
332             Rewrite_Integer
333               (Sinfo.Left_Opnd (L),
334                Expr_Value (Sinfo.Left_Opnd (L)) + R);
335             return L;
336
337          --  (E + C1) + C2 = E + (C1 + C2)
338
339          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
340             Rewrite_Integer
341               (Sinfo.Right_Opnd (L),
342                Expr_Value (Sinfo.Right_Opnd (L)) + R);
343             return L;
344          end if;
345
346       --  Case of left operand is a subtraction
347
348       elsif Nkind (L) = N_Op_Subtract then
349
350          --  (C1 - E) + C2 = (C1 + C2) + E
351
352          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
353             Rewrite_Integer
354               (Sinfo.Left_Opnd (L),
355                Expr_Value (Sinfo.Left_Opnd (L)) + R);
356             return L;
357
358          --  (E - C1) + C2 = E - (C1 - C2)
359
360          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
361             Rewrite_Integer
362               (Sinfo.Right_Opnd (L),
363                Expr_Value (Sinfo.Right_Opnd (L)) - R);
364             return L;
365          end if;
366       end if;
367
368       --  Not optimizable, do the addition
369
370       return Make_Op_Add (Loc, Left_Opnd, Right_Opnd);
371    end Assoc_Add;
372
373    --------------------
374    -- Assoc_Multiply --
375    --------------------
376
377    function Assoc_Multiply
378      (Loc        : Source_Ptr;
379       Left_Opnd  : Node_Id;
380       Right_Opnd : Node_Id) return Node_Id
381    is
382       L : Node_Id;
383       R : Uint;
384
385    begin
386       --  Case of right operand is a constant
387
388       if Compile_Time_Known_Value (Right_Opnd) then
389          L := Left_Opnd;
390          R := Expr_Value (Right_Opnd);
391
392       --  Case of left operand is a constant
393
394       elsif Compile_Time_Known_Value (Left_Opnd) then
395          L := Right_Opnd;
396          R := Expr_Value (Left_Opnd);
397
398       --  Neither operand is a constant, do the multiply with no optimization
399
400       else
401          return Make_Op_Multiply (Loc, Left_Opnd, Right_Opnd);
402       end if;
403
404       --  Case of left operand is an multiplication
405
406       if Nkind (L) = N_Op_Multiply then
407
408          --  (C1 * E) * C2 = (C1 * C2) + E
409
410          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
411             Rewrite_Integer
412               (Sinfo.Left_Opnd (L),
413                Expr_Value (Sinfo.Left_Opnd (L)) * R);
414             return L;
415
416          --  (E * C1) * C2 = E * (C1 * C2)
417
418          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
419             Rewrite_Integer
420               (Sinfo.Right_Opnd (L),
421                Expr_Value (Sinfo.Right_Opnd (L)) * R);
422             return L;
423          end if;
424       end if;
425
426       --  Not optimizable, do the multiplication
427
428       return Make_Op_Multiply (Loc, Left_Opnd, Right_Opnd);
429    end Assoc_Multiply;
430
431    --------------------
432    -- Assoc_Subtract --
433    --------------------
434
435    function Assoc_Subtract
436      (Loc        : Source_Ptr;
437       Left_Opnd  : Node_Id;
438       Right_Opnd : Node_Id) return Node_Id
439    is
440       L : Node_Id;
441       R : Uint;
442
443    begin
444       --  Case of right operand is a constant
445
446       if Compile_Time_Known_Value (Right_Opnd) then
447          L := Left_Opnd;
448          R := Expr_Value (Right_Opnd);
449
450       --  Right operand is a constant, do the subtract with no optimization
451
452       else
453          return Make_Op_Subtract (Loc, Left_Opnd, Right_Opnd);
454       end if;
455
456       --  Case of left operand is an addition
457
458       if Nkind (L) = N_Op_Add then
459
460          --  (C1 + E) - C2 = (C1 - C2) + E
461
462          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
463             Rewrite_Integer
464               (Sinfo.Left_Opnd (L),
465                Expr_Value (Sinfo.Left_Opnd (L)) - R);
466             return L;
467
468          --  (E + C1) - C2 = E + (C1 - C2)
469
470          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
471             Rewrite_Integer
472               (Sinfo.Right_Opnd (L),
473                Expr_Value (Sinfo.Right_Opnd (L)) - R);
474             return L;
475          end if;
476
477       --  Case of left operand is a subtraction
478
479       elsif Nkind (L) = N_Op_Subtract then
480
481          --  (C1 - E) - C2 = (C1 - C2) + E
482
483          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
484             Rewrite_Integer
485               (Sinfo.Left_Opnd (L),
486                Expr_Value (Sinfo.Left_Opnd (L)) + R);
487             return L;
488
489          --  (E - C1) - C2 = E - (C1 + C2)
490
491          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
492             Rewrite_Integer
493               (Sinfo.Right_Opnd (L),
494                Expr_Value (Sinfo.Right_Opnd (L)) + R);
495             return L;
496          end if;
497       end if;
498
499       --  Not optimizable, do the subtraction
500
501       return Make_Op_Subtract (Loc, Left_Opnd, Right_Opnd);
502    end Assoc_Subtract;
503
504    ----------------
505    -- Bits_To_SU --
506    ----------------
507
508    function Bits_To_SU (N : Node_Id) return Node_Id is
509    begin
510       if Nkind (N) = N_Integer_Literal then
511          Set_Intval (N, (Intval (N) + (SSU - 1)) / SSU);
512       end if;
513
514       return N;
515    end Bits_To_SU;
516
517    --------------------
518    -- Compute_Length --
519    --------------------
520
521    function Compute_Length (Lo : Node_Id; Hi : Node_Id) return Node_Id is
522       Loc    : constant Source_Ptr := Sloc (Lo);
523       Typ    : constant Entity_Id  := Etype (Lo);
524       Lo_Op  : Node_Id;
525       Hi_Op  : Node_Id;
526       Lo_Dim : Uint;
527       Hi_Dim : Uint;
528
529    begin
530       --  If the bounds are First and Last attributes for the same dimension
531       --  and both have prefixes that denotes the same entity, then we create
532       --  and return a Length attribute. This may allow the back end to
533       --  generate better code in cases where it already has the length.
534
535       if Nkind (Lo) = N_Attribute_Reference
536         and then Attribute_Name (Lo) = Name_First
537         and then Nkind (Hi) = N_Attribute_Reference
538         and then Attribute_Name (Hi) = Name_Last
539         and then Is_Entity_Name (Prefix (Lo))
540         and then Is_Entity_Name (Prefix (Hi))
541         and then Entity (Prefix (Lo)) = Entity (Prefix (Hi))
542       then
543          Lo_Dim := Uint_1;
544          Hi_Dim := Uint_1;
545
546          if Present (First (Expressions (Lo))) then
547             Lo_Dim := Expr_Value (First (Expressions (Lo)));
548          end if;
549
550          if Present (First (Expressions (Hi))) then
551             Hi_Dim := Expr_Value (First (Expressions (Hi)));
552          end if;
553
554          if Lo_Dim = Hi_Dim then
555             return
556               Make_Attribute_Reference (Loc,
557                 Prefix         => New_Occurrence_Of
558                                     (Entity (Prefix (Lo)), Loc),
559                 Attribute_Name => Name_Length,
560                 Expressions    => New_List
561                                     (Make_Integer_Literal (Loc, Lo_Dim)));
562          end if;
563       end if;
564
565       Lo_Op := New_Copy_Tree (Lo);
566       Hi_Op := New_Copy_Tree (Hi);
567
568       --  If type is enumeration type, then use Pos attribute to convert
569       --  to integer type for which subtraction is a permitted operation.
570
571       if Is_Enumeration_Type (Typ) then
572          Lo_Op :=
573            Make_Attribute_Reference (Loc,
574              Prefix         => New_Occurrence_Of (Typ, Loc),
575              Attribute_Name => Name_Pos,
576              Expressions    => New_List (Lo_Op));
577
578          Hi_Op :=
579            Make_Attribute_Reference (Loc,
580              Prefix         => New_Occurrence_Of (Typ, Loc),
581              Attribute_Name => Name_Pos,
582              Expressions    => New_List (Hi_Op));
583       end if;
584
585       return
586         Assoc_Add (Loc,
587           Left_Opnd =>
588             Assoc_Subtract (Loc,
589               Left_Opnd  => Hi_Op,
590               Right_Opnd => Lo_Op),
591           Right_Opnd => Make_Integer_Literal (Loc, 1));
592    end Compute_Length;
593
594    ----------------------
595    -- Expr_From_SO_Ref --
596    ----------------------
597
598    function Expr_From_SO_Ref
599      (Loc  : Source_Ptr;
600       D    : SO_Ref;
601       Comp : Entity_Id := Empty) return Node_Id
602    is
603       Ent : Entity_Id;
604
605    begin
606       if Is_Dynamic_SO_Ref (D) then
607          Ent := Get_Dynamic_SO_Entity (D);
608
609          if Is_Discrim_SO_Function (Ent) then
610             --  If a component is passed in whose type matches the type
611             --  of the function formal, then select that component from
612             --  the "V" parameter rather than passing "V" directly.
613
614             if Present (Comp)
615                and then Base_Type (Etype (Comp))
616                           = Base_Type (Etype (First_Formal (Ent)))
617             then
618                return
619                  Make_Function_Call (Loc,
620                    Name                   => New_Occurrence_Of (Ent, Loc),
621                    Parameter_Associations => New_List (
622                      Make_Selected_Component (Loc,
623                        Prefix        => Make_Identifier (Loc, Chars => Vname),
624                        Selector_Name => New_Occurrence_Of (Comp, Loc))));
625
626             else
627                return
628                  Make_Function_Call (Loc,
629                    Name                   => New_Occurrence_Of (Ent, Loc),
630                    Parameter_Associations => New_List (
631                      Make_Identifier (Loc, Chars => Vname)));
632             end if;
633
634          else
635             return New_Occurrence_Of (Ent, Loc);
636          end if;
637
638       else
639          return Make_Integer_Literal (Loc, D);
640       end if;
641    end Expr_From_SO_Ref;
642
643    ---------------------
644    -- Get_Max_SU_Size --
645    ---------------------
646
647    function Get_Max_SU_Size (E : Entity_Id) return Node_Id is
648       Loc  : constant Source_Ptr := Sloc (E);
649       Indx : Node_Id;
650       Ityp : Entity_Id;
651       Lo   : Node_Id;
652       Hi   : Node_Id;
653       S    : Uint;
654       Len  : Node_Id;
655
656       type Val_Status_Type is (Const, Dynamic);
657
658       type Val_Type (Status : Val_Status_Type := Const) is
659          record
660             case Status is
661                when Const   => Val : Uint;
662                when Dynamic => Nod : Node_Id;
663             end case;
664          end record;
665       --  Shows the status of the value so far. Const means that the value
666       --  is constant, and Val is the current constant value. Dynamic means
667       --  that the value is dynamic, and in this case Nod is the Node_Id of
668       --  the expression to compute the value.
669
670       Size : Val_Type;
671       --  Calculated value so far if Size.Status = Const,
672       --  or expression value so far if Size.Status = Dynamic.
673
674       SU_Convert_Required : Boolean := False;
675       --  This is set to True if the final result must be converted from
676       --  bits to storage units (rounding up to a storage unit boundary).
677
678       -----------------------
679       -- Local Subprograms --
680       -----------------------
681
682       procedure Max_Discrim (N : in out Node_Id);
683       --  If the node N represents a discriminant, replace it by the maximum
684       --  value of the discriminant.
685
686       procedure Min_Discrim (N : in out Node_Id);
687       --  If the node N represents a discriminant, replace it by the minimum
688       --  value of the discriminant.
689
690       -----------------
691       -- Max_Discrim --
692       -----------------
693
694       procedure Max_Discrim (N : in out Node_Id) is
695       begin
696          if Nkind (N) = N_Identifier
697            and then Ekind (Entity (N)) = E_Discriminant
698          then
699             N := Type_High_Bound (Etype (N));
700          end if;
701       end Max_Discrim;
702
703       -----------------
704       -- Min_Discrim --
705       -----------------
706
707       procedure Min_Discrim (N : in out Node_Id) is
708       begin
709          if Nkind (N) = N_Identifier
710            and then Ekind (Entity (N)) = E_Discriminant
711          then
712             N := Type_Low_Bound (Etype (N));
713          end if;
714       end Min_Discrim;
715
716    --  Start of processing for Get_Max_SU_Size
717
718    begin
719       pragma Assert (Size_Depends_On_Discriminant (E));
720
721       --  Initialize status from component size
722
723       if Known_Static_Component_Size (E) then
724          Size := (Const, Component_Size (E));
725
726       else
727          Size := (Dynamic, Expr_From_SO_Ref (Loc, Component_Size (E)));
728       end if;
729
730       --  Loop through indices
731
732       Indx := First_Index (E);
733       while Present (Indx) loop
734          Ityp := Etype (Indx);
735          Lo := Type_Low_Bound (Ityp);
736          Hi := Type_High_Bound (Ityp);
737
738          Min_Discrim (Lo);
739          Max_Discrim (Hi);
740
741          --  Value of the current subscript range is statically known
742
743          if Compile_Time_Known_Value (Lo)
744            and then Compile_Time_Known_Value (Hi)
745          then
746             S := Expr_Value (Hi) - Expr_Value (Lo) + 1;
747
748             --  If known flat bound, entire size of array is zero!
749
750             if S <= 0 then
751                return Make_Integer_Literal (Loc, 0);
752             end if;
753
754             --  Current value is constant, evolve value
755
756             if Size.Status = Const then
757                Size.Val := Size.Val * S;
758
759             --  Current value is dynamic
760
761             else
762                --  An interesting little optimization, if we have a pending
763                --  conversion from bits to storage units, and the current
764                --  length is a multiple of the storage unit size, then we
765                --  can take the factor out here statically, avoiding some
766                --  extra dynamic computations at the end.
767
768                if SU_Convert_Required and then S mod SSU = 0 then
769                   S := S / SSU;
770                   SU_Convert_Required := False;
771                end if;
772
773                Size.Nod :=
774                  Assoc_Multiply (Loc,
775                    Left_Opnd  => Size.Nod,
776                    Right_Opnd =>
777                      Make_Integer_Literal (Loc, Intval => S));
778             end if;
779
780          --  Value of the current subscript range is dynamic
781
782          else
783             --  If the current size value is constant, then here is where we
784             --  make a transition to dynamic values, which are always stored
785             --  in storage units, However, we do not want to convert to SU's
786             --  too soon, consider the case of a packed array of single bits,
787             --  we want to do the SU conversion after computing the size in
788             --  this case.
789
790             if Size.Status = Const then
791
792                --  If the current value is a multiple of the storage unit,
793                --  then most certainly we can do the conversion now, simply
794                --  by dividing the current value by the storage unit value.
795                --  If this works, we set SU_Convert_Required to False.
796
797                if Size.Val mod SSU = 0 then
798
799                   Size :=
800                     (Dynamic, Make_Integer_Literal (Loc, Size.Val / SSU));
801                   SU_Convert_Required := False;
802
803                --  Otherwise, we go ahead and convert the value in bits,
804                --  and set SU_Convert_Required to True to ensure that the
805                --  final value is indeed properly converted.
806
807                else
808                   Size := (Dynamic, Make_Integer_Literal (Loc, Size.Val));
809                   SU_Convert_Required := True;
810                end if;
811             end if;
812
813             --  Length is hi-lo+1
814
815             Len := Compute_Length (Lo, Hi);
816
817             --  Check possible range of Len
818
819             declare
820                OK  : Boolean;
821                LLo : Uint;
822                LHi : Uint;
823
824             begin
825                Set_Parent (Len, E);
826                Determine_Range (Len, OK, LLo, LHi);
827
828                Len := Convert_To (Standard_Unsigned, Len);
829
830                --  If we cannot verify that range cannot be super-flat,
831                --  we need a max with zero, since length must be non-neg.
832
833                if not OK or else LLo < 0 then
834                   Len :=
835                     Make_Attribute_Reference (Loc,
836                       Prefix         =>
837                         New_Occurrence_Of (Standard_Unsigned, Loc),
838                       Attribute_Name => Name_Max,
839                       Expressions    => New_List (
840                         Make_Integer_Literal (Loc, 0),
841                         Len));
842                end if;
843             end;
844          end if;
845
846          Next_Index (Indx);
847       end loop;
848
849       --  Here after processing all bounds to set sizes. If the value is
850       --  a constant, then it is bits, so we convert to storage units.
851
852       if Size.Status = Const then
853          return Bits_To_SU (Make_Integer_Literal (Loc, Size.Val));
854
855       --  Case where the value is dynamic
856
857       else
858          --  Do convert from bits to SU's if needed
859
860          if SU_Convert_Required then
861
862             --  The expression required is (Size.Nod + SU - 1) / SU
863
864             Size.Nod :=
865               Make_Op_Divide (Loc,
866                 Left_Opnd =>
867                   Make_Op_Add (Loc,
868                     Left_Opnd  => Size.Nod,
869                     Right_Opnd => Make_Integer_Literal (Loc, SSU - 1)),
870                 Right_Opnd => Make_Integer_Literal (Loc, SSU));
871          end if;
872
873          return Size.Nod;
874       end if;
875    end Get_Max_SU_Size;
876
877    -----------------------
878    -- Layout_Array_Type --
879    -----------------------
880
881    procedure Layout_Array_Type (E : Entity_Id) is
882       Loc  : constant Source_Ptr := Sloc (E);
883       Ctyp : constant Entity_Id  := Component_Type (E);
884       Indx : Node_Id;
885       Ityp : Entity_Id;
886       Lo   : Node_Id;
887       Hi   : Node_Id;
888       S    : Uint;
889       Len  : Node_Id;
890
891       Insert_Typ : Entity_Id;
892       --  This is the type with which any generated constants or functions
893       --  will be associated (i.e. inserted into the freeze actions). This
894       --  is normally the type being laid out. The exception occurs when
895       --  we are laying out Itype's which are local to a record type, and
896       --  whose scope is this record type. Such types do not have freeze
897       --  nodes (because we have no place to put them).
898
899       ------------------------------------
900       -- How An Array Type is Laid Out --
901       ------------------------------------
902
903       --  Here is what goes on. We need to multiply the component size of
904       --  the array (which has already been set) by the length of each of
905       --  the indexes. If all these values are known at compile time, then
906       --  the resulting size of the array is the appropriate constant value.
907
908       --  If the component size or at least one bound is dynamic (but no
909       --  discriminants are present), then the size will be computed as an
910       --  expression that calculates the proper size.
911
912       --  If there is at least one discriminant bound, then the size is also
913       --  computed as an expression, but this expression contains discriminant
914       --  values which are obtained by selecting from a function parameter, and
915       --  the size is given by a function that is passed the variant record in
916       --  question, and whose body is the expression.
917
918       type Val_Status_Type is (Const, Dynamic, Discrim);
919
920       type Val_Type (Status : Val_Status_Type := Const) is
921          record
922             case Status is
923                when Const =>
924                   Val : Uint;
925                   --  Calculated value so far if Val_Status = Const
926
927                when Dynamic | Discrim =>
928                   Nod : Node_Id;
929                   --  Expression value so far if Val_Status /= Const
930
931             end case;
932          end record;
933       --  Records the value or expression computed so far. Const means that
934       --  the value is constant, and Val is the current constant value.
935       --  Dynamic means that the value is dynamic, and in this case Nod is
936       --  the Node_Id of the expression to compute the value, and Discrim
937       --  means that at least one bound is a discriminant, in which case Nod
938       --  is the expression so far (which will be the body of the function).
939
940       Size : Val_Type;
941       --  Value of size computed so far. See comments above
942
943       Vtyp : Entity_Id := Empty;
944       --  Variant record type for the formal parameter of the
945       --  discriminant function V if Status = Discrim.
946
947       SU_Convert_Required : Boolean := False;
948       --  This is set to True if the final result must be converted from
949       --  bits to storage units (rounding up to a storage unit boundary).
950
951       Storage_Divisor : Uint := UI_From_Int (SSU);
952       --  This is the amount that a nonstatic computed size will be divided
953       --  by to convert it from bits to storage units. This is normally
954       --  equal to SSU, but can be reduced in the case of packed components
955       --  that fit evenly into a storage unit.
956
957       Make_Size_Function : Boolean := False;
958       --  Indicates whether to request that SO_Ref_From_Expr should
959       --  encapsulate the array size expresion in a function.
960
961       procedure Discrimify (N : in out Node_Id);
962       --  If N represents a discriminant, then the Size.Status is set to
963       --  Discrim, and Vtyp is set. The parameter N is replaced with the
964       --  proper expression to extract the discriminant value from V.
965
966       ----------------
967       -- Discrimify --
968       ----------------
969
970       procedure Discrimify (N : in out Node_Id) is
971          Decl : Node_Id;
972          Typ  : Entity_Id;
973
974       begin
975          if Nkind (N) = N_Identifier
976            and then Ekind (Entity (N)) = E_Discriminant
977          then
978             Set_Size_Depends_On_Discriminant (E);
979
980             if Size.Status /= Discrim then
981                Decl := Parent (Parent (Entity (N)));
982                Size := (Discrim, Size.Nod);
983                Vtyp := Defining_Identifier (Decl);
984             end if;
985
986             Typ := Etype (N);
987
988             N :=
989               Make_Selected_Component (Loc,
990                 Prefix        => Make_Identifier (Loc, Chars => Vname),
991                 Selector_Name => New_Occurrence_Of (Entity (N), Loc));
992
993             --  Set the Etype attributes of the selected name and its prefix.
994             --  Analyze_And_Resolve can't be called here because the Vname
995             --  entity denoted by the prefix will not yet exist (it's created
996             --  by SO_Ref_From_Expr, called at the end of Layout_Array_Type).
997
998             Set_Etype (Prefix (N), Vtyp);
999             Set_Etype (N, Typ);
1000          end if;
1001       end Discrimify;
1002
1003    --  Start of processing for Layout_Array_Type
1004
1005    begin
1006       --  Default alignment is component alignment
1007
1008       if Unknown_Alignment (E) then
1009          Set_Alignment (E, Alignment (Ctyp));
1010       end if;
1011
1012       --  Calculate proper type for insertions
1013
1014       if Is_Record_Type (Underlying_Type (Scope (E))) then
1015          Insert_Typ := Underlying_Type (Scope (E));
1016       else
1017          Insert_Typ := E;
1018       end if;
1019
1020       --  If the component type is a generic formal type then there's no point
1021       --  in determining a size for the array type.
1022
1023       if Is_Generic_Type (Ctyp) then
1024          return;
1025       end if;
1026
1027       --  Deal with component size if base type
1028
1029       if Ekind (E) = E_Array_Type then
1030
1031          --  Cannot do anything if Esize of component type unknown
1032
1033          if Unknown_Esize (Ctyp) then
1034             return;
1035          end if;
1036
1037          --  Set component size if not set already
1038
1039          if Unknown_Component_Size (E) then
1040             Set_Component_Size (E, Esize (Ctyp));
1041          end if;
1042       end if;
1043
1044       --  (RM 13.3 (48)) says that the size of an unconstrained array
1045       --  is implementation defined. We choose to leave it as Unknown
1046       --  here, and the actual behavior is determined by the back end.
1047
1048       if not Is_Constrained (E) then
1049          return;
1050       end if;
1051
1052       --  Initialize status from component size
1053
1054       if Known_Static_Component_Size (E) then
1055          Size := (Const, Component_Size (E));
1056
1057       else
1058          Size := (Dynamic, Expr_From_SO_Ref (Loc, Component_Size (E)));
1059       end if;
1060
1061       --  Loop to process array indices
1062
1063       Indx := First_Index (E);
1064       while Present (Indx) loop
1065          Ityp := Etype (Indx);
1066
1067          --  If an index of the array is a generic formal type then there's
1068          --  no point in determining a size for the array type.
1069
1070          if Is_Generic_Type (Ityp) then
1071             return;
1072          end if;
1073
1074          Lo := Type_Low_Bound (Ityp);
1075          Hi := Type_High_Bound (Ityp);
1076
1077          --  Value of the current subscript range is statically known
1078
1079          if Compile_Time_Known_Value (Lo)
1080            and then Compile_Time_Known_Value (Hi)
1081          then
1082             S := Expr_Value (Hi) - Expr_Value (Lo) + 1;
1083
1084             --  If known flat bound, entire size of array is zero!
1085
1086             if S <= 0 then
1087                Set_Esize (E, Uint_0);
1088                Set_RM_Size (E, Uint_0);
1089                return;
1090             end if;
1091
1092             --  If constant, evolve value
1093
1094             if Size.Status = Const then
1095                Size.Val := Size.Val * S;
1096
1097             --  Current value is dynamic
1098
1099             else
1100                --  An interesting little optimization, if we have a pending
1101                --  conversion from bits to storage units, and the current
1102                --  length is a multiple of the storage unit size, then we
1103                --  can take the factor out here statically, avoiding some
1104                --  extra dynamic computations at the end.
1105
1106                if SU_Convert_Required and then S mod SSU = 0 then
1107                   S := S / SSU;
1108                   SU_Convert_Required := False;
1109                end if;
1110
1111                --  Now go ahead and evolve the expression
1112
1113                Size.Nod :=
1114                  Assoc_Multiply (Loc,
1115                    Left_Opnd  => Size.Nod,
1116                    Right_Opnd =>
1117                      Make_Integer_Literal (Loc, Intval => S));
1118             end if;
1119
1120          --  Value of the current subscript range is dynamic
1121
1122          else
1123             --  If the current size value is constant, then here is where we
1124             --  make a transition to dynamic values, which are always stored
1125             --  in storage units, However, we do not want to convert to SU's
1126             --  too soon, consider the case of a packed array of single bits,
1127             --  we want to do the SU conversion after computing the size in
1128             --  this case.
1129
1130             if Size.Status = Const then
1131
1132                --  If the current value is a multiple of the storage unit,
1133                --  then most certainly we can do the conversion now, simply
1134                --  by dividing the current value by the storage unit value.
1135                --  If this works, we set SU_Convert_Required to False.
1136
1137                if Size.Val mod SSU = 0 then
1138                   Size :=
1139                     (Dynamic, Make_Integer_Literal (Loc, Size.Val / SSU));
1140                   SU_Convert_Required := False;
1141
1142                --  If the current value is a factor of the storage unit,
1143                --  then we can use a value of one for the size and reduce
1144                --  the strength of the later division.
1145
1146                elsif SSU mod Size.Val = 0 then
1147                   Storage_Divisor := SSU / Size.Val;
1148                   Size := (Dynamic, Make_Integer_Literal (Loc, Uint_1));
1149                   SU_Convert_Required := True;
1150
1151                --  Otherwise, we go ahead and convert the value in bits,
1152                --  and set SU_Convert_Required to True to ensure that the
1153                --  final value is indeed properly converted.
1154
1155                else
1156                   Size := (Dynamic, Make_Integer_Literal (Loc, Size.Val));
1157                   SU_Convert_Required := True;
1158                end if;
1159             end if;
1160
1161             Discrimify (Lo);
1162             Discrimify (Hi);
1163
1164             --  Length is hi-lo+1
1165
1166             Len := Compute_Length (Lo, Hi);
1167
1168             --  If Len isn't a Length attribute, then its range needs to
1169             --  be checked a possible Max with zero needs to be computed.
1170
1171             if Nkind (Len) /= N_Attribute_Reference
1172               or else Attribute_Name (Len) /= Name_Length
1173             then
1174                declare
1175                   OK  : Boolean;
1176                   LLo : Uint;
1177                   LHi : Uint;
1178
1179                begin
1180                   --  Check possible range of Len
1181
1182                   Set_Parent (Len, E);
1183                   Determine_Range (Len, OK, LLo, LHi);
1184
1185                   Len := Convert_To (Standard_Unsigned, Len);
1186
1187                   --  If range definitely flat or superflat,
1188                   --  result size is zero
1189
1190                   if OK and then LHi <= 0 then
1191                      Set_Esize (E, Uint_0);
1192                      Set_RM_Size (E, Uint_0);
1193                      return;
1194                   end if;
1195
1196                   --  If we cannot verify that range cannot be super-flat,
1197                   --  we need a maximum with zero, since length cannot be
1198                   --  negative.
1199
1200                   if not OK or else LLo < 0 then
1201                      Len :=
1202                        Make_Attribute_Reference (Loc,
1203                          Prefix         =>
1204                            New_Occurrence_Of (Standard_Unsigned, Loc),
1205                          Attribute_Name => Name_Max,
1206                          Expressions    => New_List (
1207                            Make_Integer_Literal (Loc, 0),
1208                            Len));
1209                   end if;
1210                end;
1211             end if;
1212
1213             --  At this stage, Len has the expression for the length
1214
1215             Size.Nod :=
1216               Assoc_Multiply (Loc,
1217                 Left_Opnd  => Size.Nod,
1218                 Right_Opnd => Len);
1219          end if;
1220
1221          Next_Index (Indx);
1222       end loop;
1223
1224       --  Here after processing all bounds to set sizes. If the value is
1225       --  a constant, then it is bits, and the only thing we need to do
1226       --  is to check against explicit given size and do alignment adjust.
1227
1228       if Size.Status = Const then
1229          Set_And_Check_Static_Size (E, Size.Val, Size.Val);
1230          Adjust_Esize_Alignment (E);
1231
1232       --  Case where the value is dynamic
1233
1234       else
1235          --  Do convert from bits to SU's if needed
1236
1237          if SU_Convert_Required then
1238
1239             --  The expression required is:
1240             --    (Size.Nod + Storage_Divisor - 1) / Storage_Divisor
1241
1242             Size.Nod :=
1243               Make_Op_Divide (Loc,
1244                 Left_Opnd =>
1245                   Make_Op_Add (Loc,
1246                     Left_Opnd  => Size.Nod,
1247                     Right_Opnd => Make_Integer_Literal
1248                                     (Loc, Storage_Divisor - 1)),
1249                 Right_Opnd => Make_Integer_Literal (Loc, Storage_Divisor));
1250          end if;
1251
1252          --  If the array entity is not declared at the library level and its
1253          --  not nested within a subprogram that is marked for inlining, then
1254          --  we request that the size expression be encapsulated in a function.
1255          --  Since this expression is not needed in most cases, we prefer not
1256          --  to incur the overhead of the computation on calls to the enclosing
1257          --  subprogram except for subprograms that require the size.
1258
1259          if not Is_Library_Level_Entity (E) then
1260             Make_Size_Function := True;
1261
1262             declare
1263                Parent_Subp : Entity_Id := Enclosing_Subprogram (E);
1264
1265             begin
1266                while Present (Parent_Subp) loop
1267                   if Is_Inlined (Parent_Subp) then
1268                      Make_Size_Function := False;
1269                      exit;
1270                   end if;
1271
1272                   Parent_Subp := Enclosing_Subprogram (Parent_Subp);
1273                end loop;
1274             end;
1275          end if;
1276
1277          --  Now set the dynamic size (the Value_Size is always the same
1278          --  as the Object_Size for arrays whose length is dynamic).
1279
1280          --  ??? If Size.Status = Dynamic, Vtyp will not have been set.
1281          --  The added initialization sets it to Empty now, but is this
1282          --  correct?
1283
1284          Set_Esize
1285            (E,
1286             SO_Ref_From_Expr
1287               (Size.Nod, Insert_Typ, Vtyp, Make_Func => Make_Size_Function));
1288          Set_RM_Size (E, Esize (E));
1289       end if;
1290    end Layout_Array_Type;
1291
1292    -------------------
1293    -- Layout_Object --
1294    -------------------
1295
1296    procedure Layout_Object (E : Entity_Id) is
1297       T : constant Entity_Id := Etype (E);
1298
1299    begin
1300       --  Nothing to do if backend does layout
1301
1302       if not Frontend_Layout_On_Target then
1303          return;
1304       end if;
1305
1306       --  Set size if not set for object and known for type. Use the
1307       --  RM_Size if that is known for the type and Esize is not.
1308
1309       if Unknown_Esize (E) then
1310          if Known_Esize (T) then
1311             Set_Esize (E, Esize (T));
1312
1313          elsif Known_RM_Size (T) then
1314             Set_Esize (E, RM_Size (T));
1315          end if;
1316       end if;
1317
1318       --  Set alignment from type if unknown and type alignment known
1319
1320       if Unknown_Alignment (E) and then Known_Alignment (T) then
1321          Set_Alignment (E, Alignment (T));
1322       end if;
1323
1324       --  Make sure size and alignment are consistent
1325
1326       Adjust_Esize_Alignment (E);
1327
1328       --  Final adjustment, if we don't know the alignment, and the Esize
1329       --  was not set by an explicit Object_Size attribute clause, then
1330       --  we reset the Esize to unknown, since we really don't know it.
1331
1332       if Unknown_Alignment (E)
1333         and then not Has_Size_Clause (E)
1334       then
1335          Set_Esize (E, Uint_0);
1336       end if;
1337    end Layout_Object;
1338
1339    ------------------------
1340    -- Layout_Record_Type --
1341    ------------------------
1342
1343    procedure Layout_Record_Type (E : Entity_Id) is
1344       Loc  : constant Source_Ptr := Sloc (E);
1345       Decl : Node_Id;
1346
1347       Comp : Entity_Id;
1348       --  Current component being laid out
1349
1350       Prev_Comp : Entity_Id;
1351       --  Previous laid out component
1352
1353       procedure Get_Next_Component_Location
1354         (Prev_Comp  : Entity_Id;
1355          Align      : Uint;
1356          New_Npos   : out SO_Ref;
1357          New_Fbit   : out SO_Ref;
1358          New_NPMax  : out SO_Ref;
1359          Force_SU   : Boolean);
1360       --  Given the previous component in Prev_Comp, which is already laid
1361       --  out, and the alignment of the following component, lays out the
1362       --  following component, and returns its starting position in New_Npos
1363       --  (Normalized_Position value), New_Fbit (Normalized_First_Bit value),
1364       --  and New_NPMax (Normalized_Position_Max value). If Prev_Comp is empty
1365       --  (no previous component is present), then New_Npos, New_Fbit and
1366       --  New_NPMax are all set to zero on return. This procedure is also
1367       --  used to compute the size of a record or variant by giving it the
1368       --  last component, and the record alignment. Force_SU is used to force
1369       --  the new component location to be aligned on a storage unit boundary,
1370       --  even in a packed record, False means that the new position does not
1371       --  need to be bumped to a storage unit boundary, True means a storage
1372       --  unit boundary is always required.
1373
1374       procedure Layout_Component (Comp : Entity_Id; Prev_Comp : Entity_Id);
1375       --  Lays out component Comp, given Prev_Comp, the previously laid-out
1376       --  component (Prev_Comp = Empty if no components laid out yet). The
1377       --  alignment of the record itself is also updated if needed. Both
1378       --  Comp and Prev_Comp can be either components or discriminants.
1379
1380       procedure Layout_Components
1381         (From   : Entity_Id;
1382          To     : Entity_Id;
1383          Esiz   : out SO_Ref;
1384          RM_Siz : out SO_Ref);
1385       --  This procedure lays out the components of the given component list
1386       --  which contains the components starting with From and ending with To.
1387       --  The Next_Entity chain is used to traverse the components. On entry,
1388       --  Prev_Comp is set to the component preceding the list, so that the
1389       --  list is laid out after this component. Prev_Comp is set to Empty if
1390       --  the component list is to be laid out starting at the start of the
1391       --  record. On return, the components are all laid out, and Prev_Comp is
1392       --  set to the last laid out component. On return, Esiz is set to the
1393       --  resulting Object_Size value, which is the length of the record up
1394       --  to and including the last laid out entity. For Esiz, the value is
1395       --  adjusted to match the alignment of the record. RM_Siz is similarly
1396       --  set to the resulting Value_Size value, which is the same length, but
1397       --  not adjusted to meet the alignment. Note that in the case of variant
1398       --  records, Esiz represents the maximum size.
1399
1400       procedure Layout_Non_Variant_Record;
1401       --  Procedure called to lay out a non-variant record type or subtype
1402
1403       procedure Layout_Variant_Record;
1404       --  Procedure called to lay out a variant record type. Decl is set to the
1405       --  full type declaration for the variant record.
1406
1407       ---------------------------------
1408       -- Get_Next_Component_Location --
1409       ---------------------------------
1410
1411       procedure Get_Next_Component_Location
1412         (Prev_Comp  : Entity_Id;
1413          Align      : Uint;
1414          New_Npos   : out SO_Ref;
1415          New_Fbit   : out SO_Ref;
1416          New_NPMax  : out SO_Ref;
1417          Force_SU   : Boolean)
1418       is
1419       begin
1420          --  No previous component, return zero position
1421
1422          if No (Prev_Comp) then
1423             New_Npos  := Uint_0;
1424             New_Fbit  := Uint_0;
1425             New_NPMax := Uint_0;
1426             return;
1427          end if;
1428
1429          --  Here we have a previous component
1430
1431          declare
1432             Loc       : constant Source_Ptr := Sloc (Prev_Comp);
1433
1434             Old_Npos  : constant SO_Ref := Normalized_Position     (Prev_Comp);
1435             Old_Fbit  : constant SO_Ref := Normalized_First_Bit    (Prev_Comp);
1436             Old_NPMax : constant SO_Ref := Normalized_Position_Max (Prev_Comp);
1437             Old_Esiz  : constant SO_Ref := Esize                   (Prev_Comp);
1438
1439             Old_Maxsz : Node_Id;
1440             --  Expression representing maximum size of previous component
1441
1442          begin
1443             --  Case where previous field had a dynamic size
1444
1445             if Is_Dynamic_SO_Ref (Esize (Prev_Comp)) then
1446
1447                --  If the previous field had a dynamic length, then it is
1448                --  required to occupy an integral number of storage units,
1449                --  and start on a storage unit boundary. This means that
1450                --  the Normalized_First_Bit value is zero in the previous
1451                --  component, and the new value is also set to zero.
1452
1453                New_Fbit := Uint_0;
1454
1455                --  In this case, the new position is given by an expression
1456                --  that is the sum of old normalized position and old size.
1457
1458                New_Npos :=
1459                  SO_Ref_From_Expr
1460                    (Assoc_Add (Loc,
1461                       Left_Opnd  =>
1462                         Expr_From_SO_Ref (Loc, Old_Npos),
1463                       Right_Opnd =>
1464                         Expr_From_SO_Ref (Loc, Old_Esiz, Prev_Comp)),
1465                     Ins_Type => E,
1466                     Vtype    => E);
1467
1468                --  Get maximum size of previous component
1469
1470                if Size_Depends_On_Discriminant (Etype (Prev_Comp)) then
1471                   Old_Maxsz := Get_Max_SU_Size (Etype (Prev_Comp));
1472                else
1473                   Old_Maxsz := Expr_From_SO_Ref (Loc, Old_Esiz, Prev_Comp);
1474                end if;
1475
1476                --  Now we can compute the new max position. If the max size
1477                --  is static and the old position is static, then we can
1478                --  compute the new position statically.
1479
1480                if Nkind (Old_Maxsz) = N_Integer_Literal
1481                  and then Known_Static_Normalized_Position_Max (Prev_Comp)
1482                then
1483                   New_NPMax := Old_NPMax + Intval (Old_Maxsz);
1484
1485                --  Otherwise new max position is dynamic
1486
1487                else
1488                   New_NPMax :=
1489                     SO_Ref_From_Expr
1490                       (Assoc_Add (Loc,
1491                          Left_Opnd  => Expr_From_SO_Ref (Loc, Old_NPMax),
1492                          Right_Opnd => Old_Maxsz),
1493                        Ins_Type => E,
1494                        Vtype    => E);
1495                end if;
1496
1497             --  Previous field has known static Esize
1498
1499             else
1500                New_Fbit := Old_Fbit + Old_Esiz;
1501
1502                --  Bump New_Fbit to storage unit boundary if required
1503
1504                if New_Fbit /= 0 and then Force_SU then
1505                   New_Fbit := (New_Fbit + SSU - 1) / SSU * SSU;
1506                end if;
1507
1508                --  If old normalized position is static, we can go ahead
1509                --  and compute the new normalized position directly.
1510
1511                if Known_Static_Normalized_Position (Prev_Comp) then
1512                   New_Npos := Old_Npos;
1513
1514                   if New_Fbit >= SSU then
1515                      New_Npos := New_Npos + New_Fbit / SSU;
1516                      New_Fbit := New_Fbit mod SSU;
1517                   end if;
1518
1519                   --  Bump alignment if stricter than prev
1520
1521                   if Align > Alignment (Etype (Prev_Comp)) then
1522                      New_Npos := (New_Npos + Align - 1) / Align * Align;
1523                   end if;
1524
1525                   --  The max position is always equal to the position if
1526                   --  the latter is static, since arrays depending on the
1527                   --  values of discriminants never have static sizes.
1528
1529                   New_NPMax := New_Npos;
1530                   return;
1531
1532                --  Case of old normalized position is dynamic
1533
1534                else
1535                   --  If new bit position is within the current storage unit,
1536                   --  we can just copy the old position as the result position
1537                   --  (we have already set the new first bit value).
1538
1539                   if New_Fbit < SSU then
1540                      New_Npos  := Old_Npos;
1541                      New_NPMax := Old_NPMax;
1542
1543                   --  If new bit position is past the current storage unit, we
1544                   --  need to generate a new dynamic value for the position
1545                   --  ??? need to deal with alignment
1546
1547                   else
1548                      New_Npos :=
1549                        SO_Ref_From_Expr
1550                          (Assoc_Add (Loc,
1551                             Left_Opnd  => Expr_From_SO_Ref (Loc, Old_Npos),
1552                             Right_Opnd =>
1553                               Make_Integer_Literal (Loc,
1554                                 Intval => New_Fbit / SSU)),
1555                           Ins_Type => E,
1556                           Vtype    => E);
1557
1558                      New_NPMax :=
1559                        SO_Ref_From_Expr
1560                          (Assoc_Add (Loc,
1561                             Left_Opnd  => Expr_From_SO_Ref (Loc, Old_NPMax),
1562                             Right_Opnd =>
1563                               Make_Integer_Literal (Loc,
1564                                 Intval => New_Fbit / SSU)),
1565                             Ins_Type => E,
1566                             Vtype    => E);
1567                      New_Fbit := New_Fbit mod SSU;
1568                   end if;
1569                end if;
1570             end if;
1571          end;
1572       end Get_Next_Component_Location;
1573
1574       ----------------------
1575       -- Layout_Component --
1576       ----------------------
1577
1578       procedure Layout_Component (Comp : Entity_Id; Prev_Comp : Entity_Id) is
1579          Ctyp  : constant Entity_Id := Etype (Comp);
1580          ORC   : constant Entity_Id := Original_Record_Component (Comp);
1581          Npos  : SO_Ref;
1582          Fbit  : SO_Ref;
1583          NPMax : SO_Ref;
1584          Forc  : Boolean;
1585
1586       begin
1587          --  Increase alignment of record if necessary. Note that we do not
1588          --  do this for packed records, which have an alignment of one by
1589          --  default, or for records for which an explicit alignment was
1590          --  specified with an alignment clause.
1591
1592          if not Is_Packed (E)
1593            and then not Has_Alignment_Clause (E)
1594            and then Alignment (Ctyp) > Alignment (E)
1595          then
1596             Set_Alignment (E, Alignment (Ctyp));
1597          end if;
1598
1599          --  If original component set, then use same layout
1600
1601          if Present (ORC) and then ORC /= Comp then
1602             Set_Normalized_Position     (Comp, Normalized_Position     (ORC));
1603             Set_Normalized_First_Bit    (Comp, Normalized_First_Bit    (ORC));
1604             Set_Normalized_Position_Max (Comp, Normalized_Position_Max (ORC));
1605             Set_Component_Bit_Offset    (Comp, Component_Bit_Offset    (ORC));
1606             Set_Esize                   (Comp, Esize                   (ORC));
1607             return;
1608          end if;
1609
1610          --  Parent field is always at start of record, this will overlap
1611          --  the actual fields that are part of the parent, and that's fine
1612
1613          if Chars (Comp) = Name_uParent then
1614             Set_Normalized_Position     (Comp, Uint_0);
1615             Set_Normalized_First_Bit    (Comp, Uint_0);
1616             Set_Normalized_Position_Max (Comp, Uint_0);
1617             Set_Component_Bit_Offset    (Comp, Uint_0);
1618             Set_Esize                   (Comp, Esize (Ctyp));
1619             return;
1620          end if;
1621
1622          --  Check case of type of component has a scope of the record we
1623          --  are laying out. When this happens, the type in question is an
1624          --  Itype that has not yet been laid out (that's because such
1625          --  types do not get frozen in the normal manner, because there
1626          --  is no place for the freeze nodes).
1627
1628          if Scope (Ctyp) = E then
1629             Layout_Type (Ctyp);
1630          end if;
1631
1632          --  If component already laid out, then we are done
1633
1634          if Known_Normalized_Position (Comp) then
1635             return;
1636          end if;
1637
1638          --  Set size of component from type. We use the Esize except in a
1639          --  packed record, where we use the RM_Size (since that is exactly
1640          --  what the RM_Size value, as distinct from the Object_Size is
1641          --  useful for!)
1642
1643          if Is_Packed (E) then
1644             Set_Esize (Comp, RM_Size (Ctyp));
1645          else
1646             Set_Esize (Comp, Esize (Ctyp));
1647          end if;
1648
1649          --  Compute the component position from the previous one. See if
1650          --  current component requires being on a storage unit boundary.
1651
1652          --  If record is not packed, we always go to a storage unit boundary
1653
1654          if not Is_Packed (E) then
1655             Forc := True;
1656
1657          --  Packed cases
1658
1659          else
1660             --  Elementary types do not need SU boundary in packed record
1661
1662             if Is_Elementary_Type (Ctyp) then
1663                Forc := False;
1664
1665             --  Packed array types with a modular packed array type do not
1666             --  force a storage unit boundary (since the code generation
1667             --  treats these as equivalent to the underlying modular type),
1668
1669             elsif Is_Array_Type (Ctyp)
1670               and then Is_Bit_Packed_Array (Ctyp)
1671               and then Is_Modular_Integer_Type (Packed_Array_Type (Ctyp))
1672             then
1673                Forc := False;
1674
1675             --  Record types with known length less than or equal to the length
1676             --  of long long integer can also be unaligned, since they can be
1677             --  treated as scalars.
1678
1679             elsif Is_Record_Type (Ctyp)
1680               and then not Is_Dynamic_SO_Ref (Esize (Ctyp))
1681               and then Esize (Ctyp) <= Esize (Standard_Long_Long_Integer)
1682             then
1683                Forc := False;
1684
1685             --  All other cases force a storage unit boundary, even when packed
1686
1687             else
1688                Forc := True;
1689             end if;
1690          end if;
1691
1692          --  Now get the next component location
1693
1694          Get_Next_Component_Location
1695            (Prev_Comp, Alignment (Ctyp), Npos, Fbit, NPMax, Forc);
1696          Set_Normalized_Position     (Comp, Npos);
1697          Set_Normalized_First_Bit    (Comp, Fbit);
1698          Set_Normalized_Position_Max (Comp, NPMax);
1699
1700          --  Set Component_Bit_Offset in the static case
1701
1702          if Known_Static_Normalized_Position (Comp)
1703            and then Known_Normalized_First_Bit (Comp)
1704          then
1705             Set_Component_Bit_Offset (Comp, SSU * Npos + Fbit);
1706          end if;
1707       end Layout_Component;
1708
1709       -----------------------
1710       -- Layout_Components --
1711       -----------------------
1712
1713       procedure Layout_Components
1714         (From   : Entity_Id;
1715          To     : Entity_Id;
1716          Esiz   : out SO_Ref;
1717          RM_Siz : out SO_Ref)
1718       is
1719          End_Npos  : SO_Ref;
1720          End_Fbit  : SO_Ref;
1721          End_NPMax : SO_Ref;
1722
1723       begin
1724          --  Only lay out components if there are some to lay out!
1725
1726          if Present (From) then
1727
1728             --  Lay out components with no component clauses
1729
1730             Comp := From;
1731             loop
1732                if Ekind (Comp) = E_Component
1733                  or else Ekind (Comp) = E_Discriminant
1734                then
1735                   --  The compatibility of component clauses with composite
1736                   --  types isn't checked in Sem_Ch13, so we check it here.
1737
1738                   if Present (Component_Clause (Comp)) then
1739                      if Is_Composite_Type (Etype (Comp))
1740                        and then Esize (Comp) < RM_Size (Etype (Comp))
1741                      then
1742                         Error_Msg_Uint_1 := RM_Size (Etype (Comp));
1743                         Error_Msg_NE
1744                           ("size for & too small, minimum allowed is ^",
1745                            Component_Clause (Comp),
1746                            Comp);
1747                      end if;
1748
1749                   else
1750                      Layout_Component (Comp, Prev_Comp);
1751                      Prev_Comp := Comp;
1752                   end if;
1753                end if;
1754
1755                exit when Comp = To;
1756                Next_Entity (Comp);
1757             end loop;
1758          end if;
1759
1760          --  Set size fields, both are zero if no components
1761
1762          if No (Prev_Comp) then
1763             Esiz := Uint_0;
1764             RM_Siz := Uint_0;
1765
1766             --  If record subtype with non-static discriminants, then we don't
1767             --  know which variant will be the one which gets chosen. We don't
1768             --  just want to set the maximum size from the base, because the
1769             --  size should depend on the particular variant.
1770
1771             --  What we do is to use the RM_Size of the base type, which has
1772             --  the necessary conditional computation of the size, using the
1773             --  size information for the particular variant chosen. Records
1774             --  with default discriminants for example have an Esize that is
1775             --  set to the maximum of all variants, but that's not what we
1776             --  want for a constrained subtype.
1777
1778          elsif Ekind (E) = E_Record_Subtype
1779            and then not Has_Static_Discriminants (E)
1780          then
1781             declare
1782                BT : constant Node_Id := Base_Type (E);
1783             begin
1784                Esiz   := RM_Size (BT);
1785                RM_Siz := RM_Size (BT);
1786                Set_Alignment (E, Alignment (BT));
1787             end;
1788
1789          else
1790             --  First the object size, for which we align past the last field
1791             --  to the alignment of the record (the object size is required to
1792             --  be a multiple of the alignment).
1793
1794             Get_Next_Component_Location
1795               (Prev_Comp,
1796                Alignment (E),
1797                End_Npos,
1798                End_Fbit,
1799                End_NPMax,
1800                Force_SU => True);
1801
1802             --  If the resulting normalized position is a dynamic reference,
1803             --  then the size is dynamic, and is stored in storage units. In
1804             --  this case, we set the RM_Size to the same value, it is simply
1805             --  not worth distinguishing Esize and RM_Size values in the
1806             --  dynamic case, since the RM has nothing to say about them.
1807
1808             --  Note that a size cannot have been given in this case, since
1809             --  size specifications cannot be given for variable length types.
1810
1811             declare
1812                Align : constant Uint := Alignment (E);
1813
1814             begin
1815                if Is_Dynamic_SO_Ref (End_Npos) then
1816                   RM_Siz := End_Npos;
1817
1818                   --  Set the Object_Size allowing for the alignment. In the
1819                   --  dynamic case, we must do the actual runtime computation.
1820                   --  We can skip this in the non-packed record case if the
1821                   --  last component has a smaller alignment than the overall
1822                   --  record alignment.
1823
1824                   if Is_Dynamic_SO_Ref (End_NPMax) then
1825                      Esiz := End_NPMax;
1826
1827                      if Is_Packed (E)
1828                        or else Alignment (Etype (Prev_Comp)) < Align
1829                      then
1830                         --  The expression we build is:
1831                         --    (expr + align - 1) / align * align
1832
1833                         Esiz :=
1834                           SO_Ref_From_Expr
1835                             (Expr =>
1836                                Make_Op_Multiply (Loc,
1837                                  Left_Opnd =>
1838                                    Make_Op_Divide (Loc,
1839                                      Left_Opnd =>
1840                                        Make_Op_Add (Loc,
1841                                          Left_Opnd =>
1842                                            Expr_From_SO_Ref (Loc, Esiz),
1843                                          Right_Opnd =>
1844                                            Make_Integer_Literal (Loc,
1845                                              Intval => Align - 1)),
1846                                      Right_Opnd =>
1847                                        Make_Integer_Literal (Loc, Align)),
1848                                  Right_Opnd =>
1849                                    Make_Integer_Literal (Loc, Align)),
1850                             Ins_Type => E,
1851                             Vtype    => E);
1852                      end if;
1853
1854                   --  Here Esiz is static, so we can adjust the alignment
1855                   --  directly go give the required aligned value.
1856
1857                   else
1858                      Esiz := (End_NPMax + Align - 1) / Align * Align * SSU;
1859                   end if;
1860
1861                --  Case where computed size is static
1862
1863                else
1864                   --  The ending size was computed in Npos in storage units,
1865                   --  but the actual size is stored in bits, so adjust
1866                   --  accordingly. We also adjust the size to match the
1867                   --  alignment here.
1868
1869                   Esiz := (End_NPMax + Align - 1) / Align * Align * SSU;
1870
1871                   --  Compute the resulting Value_Size (RM_Size). For this
1872                   --  purpose we do not force alignment of the record or
1873                   --  storage size alignment of the result.
1874
1875                   Get_Next_Component_Location
1876                     (Prev_Comp,
1877                      Uint_0,
1878                      End_Npos,
1879                      End_Fbit,
1880                      End_NPMax,
1881                      Force_SU => False);
1882
1883                   RM_Siz := End_Npos * SSU + End_Fbit;
1884                   Set_And_Check_Static_Size (E, Esiz, RM_Siz);
1885                end if;
1886             end;
1887          end if;
1888       end Layout_Components;
1889
1890       -------------------------------
1891       -- Layout_Non_Variant_Record --
1892       -------------------------------
1893
1894       procedure Layout_Non_Variant_Record is
1895          Esiz   : SO_Ref;
1896          RM_Siz : SO_Ref;
1897       begin
1898          Layout_Components (First_Entity (E), Last_Entity (E), Esiz, RM_Siz);
1899          Set_Esize   (E, Esiz);
1900          Set_RM_Size (E, RM_Siz);
1901       end Layout_Non_Variant_Record;
1902
1903       ---------------------------
1904       -- Layout_Variant_Record --
1905       ---------------------------
1906
1907       procedure Layout_Variant_Record is
1908          Tdef        : constant Node_Id := Type_Definition (Decl);
1909          First_Discr : Entity_Id;
1910          Last_Discr  : Entity_Id;
1911          Esiz        : SO_Ref;
1912          RM_Siz      : SO_Ref;
1913
1914          RM_Siz_Expr : Node_Id := Empty;
1915          --  Expression for the evolving RM_Siz value. This is typically a
1916          --  conditional expression which involves tests of discriminant
1917          --  values that are formed as references to the entity V. At
1918          --  the end of scanning all the components, a suitable function
1919          --  is constructed in which V is the parameter.
1920
1921          -----------------------
1922          -- Local Subprograms --
1923          -----------------------
1924
1925          procedure Layout_Component_List
1926            (Clist       : Node_Id;
1927             Esiz        : out SO_Ref;
1928             RM_Siz_Expr : out Node_Id);
1929          --  Recursive procedure, called to lay out one component list
1930          --  Esiz and RM_Siz_Expr are set to the Object_Size and Value_Size
1931          --  values respectively representing the record size up to and
1932          --  including the last component in the component list (including
1933          --  any variants in this component list). RM_Siz_Expr is returned
1934          --  as an expression which may in the general case involve some
1935          --  references to the discriminants of the current record value,
1936          --  referenced by selecting from the entity V.
1937
1938          ---------------------------
1939          -- Layout_Component_List --
1940          ---------------------------
1941
1942          procedure Layout_Component_List
1943            (Clist       : Node_Id;
1944             Esiz        : out SO_Ref;
1945             RM_Siz_Expr : out Node_Id)
1946          is
1947             Citems  : constant List_Id := Component_Items (Clist);
1948             Vpart   : constant Node_Id := Variant_Part (Clist);
1949             Prv     : Node_Id;
1950             Var     : Node_Id;
1951             RM_Siz  : Uint;
1952             RMS_Ent : Entity_Id;
1953
1954          begin
1955             if Is_Non_Empty_List (Citems) then
1956                Layout_Components
1957                  (From   => Defining_Identifier (First (Citems)),
1958                   To     => Defining_Identifier (Last  (Citems)),
1959                   Esiz   => Esiz,
1960                   RM_Siz => RM_Siz);
1961             else
1962                Layout_Components (Empty, Empty, Esiz, RM_Siz);
1963             end if;
1964
1965             --  Case where no variants are present in the component list
1966
1967             if No (Vpart) then
1968
1969                --  The Esiz value has been correctly set by the call to
1970                --  Layout_Components, so there is nothing more to be done.
1971
1972                --  For RM_Siz, we have an SO_Ref value, which we must convert
1973                --  to an appropriate expression.
1974
1975                if Is_Static_SO_Ref (RM_Siz) then
1976                   RM_Siz_Expr :=
1977                     Make_Integer_Literal (Loc,
1978                                           Intval => RM_Siz);
1979
1980                else
1981                   RMS_Ent := Get_Dynamic_SO_Entity (RM_Siz);
1982
1983                   --  If the size is represented by a function, then we
1984                   --  create an appropriate function call using V as
1985                   --  the parameter to the call.
1986
1987                   if Is_Discrim_SO_Function (RMS_Ent) then
1988                      RM_Siz_Expr :=
1989                        Make_Function_Call (Loc,
1990                          Name => New_Occurrence_Of (RMS_Ent, Loc),
1991                          Parameter_Associations => New_List (
1992                            Make_Identifier (Loc, Chars => Vname)));
1993
1994                   --  If the size is represented by a constant, then the
1995                   --  expression we want is a reference to this constant
1996
1997                   else
1998                      RM_Siz_Expr := New_Occurrence_Of (RMS_Ent, Loc);
1999                   end if;
2000                end if;
2001
2002             --  Case where variants are present in this component list
2003
2004             else
2005                declare
2006                   EsizV    : SO_Ref;
2007                   RM_SizV  : Node_Id;
2008                   Dchoice  : Node_Id;
2009                   Discrim  : Node_Id;
2010                   Dtest    : Node_Id;
2011                   D_List   : List_Id;
2012                   D_Entity : Entity_Id;
2013
2014                begin
2015                   RM_Siz_Expr := Empty;
2016                   Prv := Prev_Comp;
2017
2018                   Var := Last (Variants (Vpart));
2019                   while Present (Var) loop
2020                      Prev_Comp := Prv;
2021                      Layout_Component_List
2022                        (Component_List (Var), EsizV, RM_SizV);
2023
2024                      --  Set the Object_Size. If this is the first variant,
2025                      --  we just set the size of this first variant.
2026
2027                      if Var = Last (Variants (Vpart)) then
2028                         Esiz := EsizV;
2029
2030                      --  Otherwise the Object_Size is formed as a maximum
2031                      --  of Esiz so far from previous variants, and the new
2032                      --  Esiz value from the variant we just processed.
2033
2034                      --  If both values are static, we can just compute the
2035                      --  maximum directly to save building junk nodes.
2036
2037                      elsif not Is_Dynamic_SO_Ref (Esiz)
2038                        and then not Is_Dynamic_SO_Ref (EsizV)
2039                      then
2040                         Esiz := UI_Max (Esiz, EsizV);
2041
2042                      --  If either value is dynamic, then we have to generate
2043                      --  an appropriate Standard_Unsigned'Max attribute call.
2044                      --  If one of the values is static then it needs to be
2045                      --  converted from bits to storage units to be compatible
2046                      --  with the dynamic value.
2047
2048                      else
2049                         if Is_Static_SO_Ref (Esiz) then
2050                            Esiz := (Esiz + SSU - 1) / SSU;
2051                         end if;
2052
2053                         if Is_Static_SO_Ref (EsizV) then
2054                            EsizV := (EsizV + SSU - 1) / SSU;
2055                         end if;
2056
2057                         Esiz :=
2058                           SO_Ref_From_Expr
2059                             (Make_Attribute_Reference (Loc,
2060                                Attribute_Name => Name_Max,
2061                                Prefix         =>
2062                                  New_Occurrence_Of (Standard_Unsigned, Loc),
2063                                Expressions => New_List (
2064                                  Expr_From_SO_Ref (Loc, Esiz),
2065                                  Expr_From_SO_Ref (Loc, EsizV))),
2066                              Ins_Type => E,
2067                              Vtype    => E);
2068                      end if;
2069
2070                      --  Now deal with Value_Size (RM_Siz). We are aiming at
2071                      --  an expression that looks like:
2072
2073                      --    if      xxDx (V.disc) then rmsiz1
2074                      --    else if xxDx (V.disc) then rmsiz2
2075                      --    else ...
2076
2077                      --  Where rmsiz1, rmsiz2... are the RM_Siz values for the
2078                      --  individual variants, and xxDx are the discriminant
2079                      --  checking functions generated for the variant type.
2080
2081                      --  If this is the first variant, we simply set the
2082                      --  result as the expression. Note that this takes
2083                      --  care of the others case.
2084
2085                      if No (RM_Siz_Expr) then
2086                         RM_Siz_Expr := Bits_To_SU (RM_SizV);
2087
2088                      --  Otherwise construct the appropriate test
2089
2090                      else
2091                         --  The test to be used in general is a call to the
2092                         --  discriminant checking function. However, it is
2093                         --  definitely worth special casing the very common
2094                         --  case where a single value is involved.
2095
2096                         Dchoice := First (Discrete_Choices (Var));
2097
2098                         if No (Next (Dchoice))
2099                           and then Nkind (Dchoice) /= N_Range
2100                         then
2101                            --  Discriminant to be tested
2102
2103                            Discrim :=
2104                              Make_Selected_Component (Loc,
2105                                Prefix        =>
2106                                  Make_Identifier (Loc, Chars => Vname),
2107                                Selector_Name =>
2108                                  New_Occurrence_Of
2109                                    (Entity (Name (Vpart)), Loc));
2110
2111                            Dtest :=
2112                              Make_Op_Eq (Loc,
2113                                Left_Opnd  => Discrim,
2114                                Right_Opnd => New_Copy (Dchoice));
2115
2116                         --  Generate a call to the discriminant-checking
2117                         --  function for the variant. Note that the result
2118                         --  has to be complemented since the function returns
2119                         --  False when the passed discriminant value matches.
2120
2121                         else
2122                            --  The checking function takes all of the type's
2123                            --  discriminants as parameters, so a list of all
2124                            --  the selected discriminants must be constructed.
2125
2126                            D_List := New_List;
2127                            D_Entity := First_Discriminant (E);
2128                            while Present (D_Entity) loop
2129                               Append (
2130                                 Make_Selected_Component (Loc,
2131                                   Prefix        =>
2132                                     Make_Identifier (Loc, Chars => Vname),
2133                                   Selector_Name =>
2134                                     New_Occurrence_Of
2135                                       (D_Entity, Loc)),
2136                                 D_List);
2137
2138                               D_Entity := Next_Discriminant (D_Entity);
2139                            end loop;
2140
2141                            Dtest :=
2142                              Make_Op_Not (Loc,
2143                                Right_Opnd =>
2144                                  Make_Function_Call (Loc,
2145                                    Name =>
2146                                      New_Occurrence_Of
2147                                        (Dcheck_Function (Var), Loc),
2148                                    Parameter_Associations =>
2149                                      D_List));
2150                         end if;
2151
2152                         RM_Siz_Expr :=
2153                           Make_Conditional_Expression (Loc,
2154                             Expressions =>
2155                               New_List
2156                                 (Dtest, Bits_To_SU (RM_SizV), RM_Siz_Expr));
2157                      end if;
2158
2159                      Prev (Var);
2160                   end loop;
2161                end;
2162             end if;
2163          end Layout_Component_List;
2164
2165       --  Start of processing for Layout_Variant_Record
2166
2167       begin
2168          --  We need the discriminant checking functions, since we generate
2169          --  calls to these functions for the RM_Size expression, so make
2170          --  sure that these functions have been constructed in time.
2171
2172          Build_Discr_Checking_Funcs (Decl);
2173
2174          --  Lay out the discriminants
2175
2176          First_Discr := First_Discriminant (E);
2177          Last_Discr  := First_Discr;
2178          while Present (Next_Discriminant (Last_Discr)) loop
2179             Next_Discriminant (Last_Discr);
2180          end loop;
2181
2182          Layout_Components
2183            (From   => First_Discr,
2184             To     => Last_Discr,
2185             Esiz   => Esiz,
2186             RM_Siz => RM_Siz);
2187
2188          --  Lay out the main component list (this will make recursive calls
2189          --  to lay out all component lists nested within variants).
2190
2191          Layout_Component_List (Component_List (Tdef), Esiz, RM_Siz_Expr);
2192          Set_Esize (E, Esiz);
2193
2194          --  If the RM_Size is a literal, set its value
2195
2196          if Nkind (RM_Siz_Expr) = N_Integer_Literal then
2197             Set_RM_Size (E, Intval (RM_Siz_Expr));
2198
2199          --  Otherwise we construct a dynamic SO_Ref
2200
2201          else
2202             Set_RM_Size (E,
2203               SO_Ref_From_Expr
2204                 (RM_Siz_Expr,
2205                  Ins_Type => E,
2206                  Vtype    => E));
2207          end if;
2208       end Layout_Variant_Record;
2209
2210    --  Start of processing for Layout_Record_Type
2211
2212    begin
2213       --  If this is a cloned subtype, just copy the size fields from the
2214       --  original, nothing else needs to be done in this case, since the
2215       --  components themselves are all shared.
2216
2217       if (Ekind (E) = E_Record_Subtype
2218             or else
2219           Ekind (E) = E_Class_Wide_Subtype)
2220         and then Present (Cloned_Subtype (E))
2221       then
2222          Set_Esize     (E, Esize     (Cloned_Subtype (E)));
2223          Set_RM_Size   (E, RM_Size   (Cloned_Subtype (E)));
2224          Set_Alignment (E, Alignment (Cloned_Subtype (E)));
2225
2226       --  Another special case, class-wide types. The RM says that the size
2227       --  of such types is implementation defined (RM 13.3(48)). What we do
2228       --  here is to leave the fields set as unknown values, and the backend
2229       --  determines the actual behavior.
2230
2231       elsif Ekind (E) = E_Class_Wide_Type then
2232          null;
2233
2234       --  All other cases
2235
2236       else
2237          --  Initialize alignment conservatively to 1. This value will
2238          --  be increased as necessary during processing of the record.
2239
2240          if Unknown_Alignment (E) then
2241             Set_Alignment (E, Uint_1);
2242          end if;
2243
2244          --  Initialize previous component. This is Empty unless there
2245          --  are components which have already been laid out by component
2246          --  clauses. If there are such components, we start our lay out of
2247          --  the remaining components following the last such component.
2248
2249          Prev_Comp := Empty;
2250
2251          Comp := First_Component_Or_Discriminant (E);
2252          while Present (Comp) loop
2253             if Present (Component_Clause (Comp)) then
2254                if No (Prev_Comp)
2255                  or else
2256                    Component_Bit_Offset (Comp) >
2257                    Component_Bit_Offset (Prev_Comp)
2258                then
2259                   Prev_Comp := Comp;
2260                end if;
2261             end if;
2262
2263             Next_Component_Or_Discriminant (Comp);
2264          end loop;
2265
2266          --  We have two separate circuits, one for non-variant records and
2267          --  one for variant records. For non-variant records, we simply go
2268          --  through the list of components. This handles all the non-variant
2269          --  cases including those cases of subtypes where there is no full
2270          --  type declaration, so the tree cannot be used to drive the layout.
2271          --  For variant records, we have to drive the layout from the tree
2272          --  since we need to understand the variant structure in this case.
2273
2274          if Present (Full_View (E)) then
2275             Decl := Declaration_Node (Full_View (E));
2276          else
2277             Decl := Declaration_Node (E);
2278          end if;
2279
2280          --  Scan all the components
2281
2282          if Nkind (Decl) = N_Full_Type_Declaration
2283            and then Has_Discriminants (E)
2284            and then Nkind (Type_Definition (Decl)) = N_Record_Definition
2285            and then Present (Component_List (Type_Definition (Decl)))
2286            and then
2287              Present (Variant_Part (Component_List (Type_Definition (Decl))))
2288          then
2289             Layout_Variant_Record;
2290          else
2291             Layout_Non_Variant_Record;
2292          end if;
2293       end if;
2294    end Layout_Record_Type;
2295
2296    -----------------
2297    -- Layout_Type --
2298    -----------------
2299
2300    procedure Layout_Type (E : Entity_Id) is
2301    begin
2302       --  For string literal types, for now, kill the size always, this
2303       --  is because gigi does not like or need the size to be set ???
2304
2305       if Ekind (E) = E_String_Literal_Subtype then
2306          Set_Esize (E, Uint_0);
2307          Set_RM_Size (E, Uint_0);
2308          return;
2309       end if;
2310
2311       --  For access types, set size/alignment. This is system address
2312       --  size, except for fat pointers (unconstrained array access types),
2313       --  where the size is two times the address size, to accommodate the
2314       --  two pointers that are required for a fat pointer (data and
2315       --  template). Note that E_Access_Protected_Subprogram_Type is not
2316       --  an access type for this purpose since it is not a pointer but is
2317       --  equivalent to a record. For access subtypes, copy the size from
2318       --  the base type since Gigi represents them the same way.
2319
2320       if Is_Access_Type (E) then
2321
2322          --  If Esize already set (e.g. by a size clause), then nothing
2323          --  further to be done here.
2324
2325          if Known_Esize (E) then
2326             null;
2327
2328          --  Access to subprogram is a strange beast, and we let the
2329          --  backend figure out what is needed (it may be some kind
2330          --  of fat pointer, including the static link for example.
2331
2332          elsif Is_Access_Protected_Subprogram_Type (E) then
2333             null;
2334
2335          --  For access subtypes, copy the size information from base type
2336
2337          elsif Ekind (E) = E_Access_Subtype then
2338             Set_Size_Info (E, Base_Type (E));
2339             Set_RM_Size   (E, RM_Size (Base_Type (E)));
2340
2341          --  For other access types, we use either address size, or, if
2342          --  a fat pointer is used (pointer-to-unconstrained array case),
2343          --  twice the address size to accommodate a fat pointer.
2344
2345          else
2346             declare
2347                Desig : Entity_Id := Designated_Type (E);
2348
2349             begin
2350                if Is_Private_Type (Desig)
2351                  and then Present (Full_View (Desig))
2352                then
2353                   Desig := Full_View (Desig);
2354                end if;
2355
2356                if Is_Array_Type (Desig)
2357                  and then not Is_Constrained (Desig)
2358                  and then not Has_Completion_In_Body (Desig)
2359                  and then not Debug_Flag_6
2360                then
2361                   Init_Size (E, 2 * System_Address_Size);
2362
2363                   --  Check for bad convention set
2364
2365                   if Warn_On_Export_Import
2366                     and then
2367                       (Convention (E) = Convention_C
2368                          or else
2369                        Convention (E) = Convention_CPP)
2370                   then
2371                      Error_Msg_N
2372                        ("?this access type does not " &
2373                         "correspond to C pointer", E);
2374                   end if;
2375
2376                --  When the target is AAMP, access-to-subprogram types are fat
2377                --  pointers consisting of the subprogram address and a static
2378                --  link (with the exception of library-level access types,
2379                --  where a simple subprogram address is used).
2380
2381                elsif AAMP_On_Target
2382                  and then
2383                    (Ekind (E) = E_Anonymous_Access_Subprogram_Type
2384                      or else (Ekind (E) = E_Access_Subprogram_Type
2385                                and then Present (Enclosing_Subprogram (E))))
2386                then
2387                   Init_Size (E, 2 * System_Address_Size);
2388
2389                else
2390                   Init_Size (E, System_Address_Size);
2391                end if;
2392             end;
2393          end if;
2394
2395          --  On VMS, reset size to 32 for convention C access type if no
2396          --  explicit size clause is given and the default size is 64. Really
2397          --  we do not know the size, since depending on options for the VMS
2398          --  compiler, the size of a pointer type can be 32 or 64, but choosing
2399          --  32 as the default improves compatibility with legacy VMS code.
2400
2401          --  Note: we do not use Has_Size_Clause in the test below, because we
2402          --  want to catch the case of a derived type inheriting a size clause.
2403          --  We want to consider this to be an explicit size clause for this
2404          --  purpose, since it would be weird not to inherit the size in this
2405          --  case.
2406
2407          if OpenVMS_On_Target
2408            and then (Convention (E) = Convention_C
2409                       or else
2410                      Convention (E) = Convention_CPP)
2411            and then No (Get_Attribute_Definition_Clause (E, Attribute_Size))
2412            and then Esize (E) = 64
2413          then
2414             Init_Size (E, 32);
2415          end if;
2416
2417          Set_Elem_Alignment (E);
2418
2419       --  Scalar types: set size and alignment
2420
2421       elsif Is_Scalar_Type (E) then
2422
2423          --  For discrete types, the RM_Size and Esize must be set
2424          --  already, since this is part of the earlier processing
2425          --  and the front end is always required to lay out the
2426          --  sizes of such types (since they are available as static
2427          --  attributes). All we do is to check that this rule is
2428          --  indeed obeyed!
2429
2430          if Is_Discrete_Type (E) then
2431
2432             --  If the RM_Size is not set, then here is where we set it
2433
2434             --  Note: an RM_Size of zero looks like not set here, but this
2435             --  is a rare case, and we can simply reset it without any harm.
2436
2437             if not Known_RM_Size (E) then
2438                Set_Discrete_RM_Size (E);
2439             end if;
2440
2441             --  If Esize for a discrete type is not set then set it
2442
2443             if not Known_Esize (E) then
2444                declare
2445                   S : Int := 8;
2446
2447                begin
2448                   loop
2449                      --  If size is big enough, set it and exit
2450
2451                      if S >= RM_Size (E) then
2452                         Init_Esize (E, S);
2453                         exit;
2454
2455                      --  If the RM_Size is greater than 64 (happens only
2456                      --  when strange values are specified by the user,
2457                      --  then Esize is simply a copy of RM_Size, it will
2458                      --  be further refined later on)
2459
2460                      elsif S = 64 then
2461                         Set_Esize (E, RM_Size (E));
2462                         exit;
2463
2464                      --  Otherwise double possible size and keep trying
2465
2466                      else
2467                         S := S * 2;
2468                      end if;
2469                   end loop;
2470                end;
2471             end if;
2472
2473          --  For non-discrete sclar types, if the RM_Size is not set,
2474          --  then set it now to a copy of the Esize if the Esize is set.
2475
2476          else
2477             if Known_Esize (E) and then Unknown_RM_Size (E) then
2478                Set_RM_Size (E, Esize (E));
2479             end if;
2480          end if;
2481
2482          Set_Elem_Alignment (E);
2483
2484       --  Non-elementary (composite) types
2485
2486       else
2487          --  If RM_Size is known, set Esize if not known
2488
2489          if Known_RM_Size (E) and then Unknown_Esize (E) then
2490
2491             --  If the alignment is known, we bump the Esize up to the
2492             --  next alignment boundary if it is not already on one.
2493
2494             if Known_Alignment (E) then
2495                declare
2496                   A : constant Uint   := Alignment_In_Bits (E);
2497                   S : constant SO_Ref := RM_Size (E);
2498                begin
2499                   Set_Esize (E, (S + A - 1) / A * A);
2500                end;
2501             end if;
2502
2503          --  If Esize is set, and RM_Size is not, RM_Size is copied from
2504          --  Esize at least for now this seems reasonable, and is in any
2505          --  case needed for compatibility with old versions of gigi.
2506          --  look to be unknown.
2507
2508          elsif Known_Esize (E) and then Unknown_RM_Size (E) then
2509             Set_RM_Size (E, Esize (E));
2510          end if;
2511
2512          --  For array base types, set component size if object size of
2513          --  the component type is known and is a small power of 2 (8,
2514          --  16, 32, 64), since this is what will always be used.
2515
2516          if Ekind (E) = E_Array_Type
2517            and then Unknown_Component_Size (E)
2518          then
2519             declare
2520                CT : constant Entity_Id := Component_Type (E);
2521
2522             begin
2523                --  For some reasons, access types can cause trouble,
2524                --  So let's just do this for discrete types ???
2525
2526                if Present (CT)
2527                  and then Is_Discrete_Type (CT)
2528                  and then Known_Static_Esize (CT)
2529                then
2530                   declare
2531                      S : constant Uint := Esize (CT);
2532
2533                   begin
2534                      if S = 8  or else
2535                         S = 16 or else
2536                         S = 32 or else
2537                         S = 64
2538                      then
2539                         Set_Component_Size (E, Esize (CT));
2540                      end if;
2541                   end;
2542                end if;
2543             end;
2544          end if;
2545       end if;
2546
2547       --  Lay out array and record types if front end layout set
2548
2549       if Frontend_Layout_On_Target then
2550          if Is_Array_Type (E) and then not Is_Bit_Packed_Array (E) then
2551             Layout_Array_Type (E);
2552          elsif Is_Record_Type (E) then
2553             Layout_Record_Type (E);
2554          end if;
2555
2556       --  Case of backend layout, we still do a little in the front end
2557
2558       else
2559          --  Processing for record types
2560
2561          if Is_Record_Type (E) then
2562
2563             --  Special remaining processing for record types with a known
2564             --  size of 16, 32, or 64 bits whose alignment is not yet set.
2565             --  For these types, we set a corresponding alignment matching
2566             --  the size if possible, or as large as possible if not.
2567
2568             if Convention (E) = Convention_Ada
2569                and then not Debug_Flag_Q
2570             then
2571                Set_Composite_Alignment (E);
2572             end if;
2573
2574          --  Procressing for array types
2575
2576          elsif Is_Array_Type (E) then
2577
2578             --  For arrays that are required to be atomic, we do the same
2579             --  processing as described above for short records, since we
2580             --  really need to have the alignment set for the whole array.
2581
2582             if Is_Atomic (E) and then not Debug_Flag_Q then
2583                Set_Composite_Alignment (E);
2584             end if;
2585
2586             --  For unpacked array types, set an alignment of 1 if we know
2587             --  that the component alignment is not greater than 1. The reason
2588             --  we do this is to avoid unnecessary copying of slices of such
2589             --  arrays when passed to subprogram parameters (see special test
2590             --  in Exp_Ch6.Expand_Actuals).
2591
2592             if not Is_Packed (E)
2593               and then Unknown_Alignment (E)
2594             then
2595                if Known_Static_Component_Size (E)
2596                  and then Component_Size (E) = 1
2597                then
2598                   Set_Alignment (E, Uint_1);
2599                end if;
2600             end if;
2601          end if;
2602       end if;
2603
2604       --  Final step is to check that Esize and RM_Size are compatible
2605
2606       if Known_Static_Esize (E) and then Known_Static_RM_Size (E) then
2607          if Esize (E) < RM_Size (E) then
2608
2609             --  Esize is less than RM_Size. That's not good. First we test
2610             --  whether this was set deliberately with an Object_Size clause
2611             --  and if so, object to the clause.
2612
2613             if Has_Object_Size_Clause (E) then
2614                Error_Msg_Uint_1 := RM_Size (E);
2615                Error_Msg_F
2616                  ("object size is too small, minimum allowed is ^",
2617                   Expression (Get_Attribute_Definition_Clause
2618                                              (E, Attribute_Object_Size)));
2619             end if;
2620
2621             --  Adjust Esize up to RM_Size value
2622
2623             declare
2624                Size : constant Uint := RM_Size (E);
2625
2626             begin
2627                Set_Esize (E, RM_Size (E));
2628
2629                --  For scalar types, increase Object_Size to power of 2,
2630                --  but not less than a storage unit in any case (i.e.,
2631                --  normally this means it will be storage-unit addressable).
2632
2633                if Is_Scalar_Type (E) then
2634                   if Size <= System_Storage_Unit then
2635                      Init_Esize (E, System_Storage_Unit);
2636                   elsif Size <= 16 then
2637                      Init_Esize (E, 16);
2638                   elsif Size <= 32 then
2639                      Init_Esize (E, 32);
2640                   else
2641                      Set_Esize  (E, (Size + 63) / 64 * 64);
2642                   end if;
2643
2644                   --  Finally, make sure that alignment is consistent with
2645                   --  the newly assigned size.
2646
2647                   while Alignment (E) * System_Storage_Unit < Esize (E)
2648                     and then Alignment (E) < Maximum_Alignment
2649                   loop
2650                      Set_Alignment (E, 2 * Alignment (E));
2651                   end loop;
2652                end if;
2653             end;
2654          end if;
2655       end if;
2656    end Layout_Type;
2657
2658    ---------------------
2659    -- Rewrite_Integer --
2660    ---------------------
2661
2662    procedure Rewrite_Integer (N : Node_Id; V : Uint) is
2663       Loc : constant Source_Ptr := Sloc (N);
2664       Typ : constant Entity_Id  := Etype (N);
2665
2666    begin
2667       Rewrite (N, Make_Integer_Literal (Loc, Intval => V));
2668       Set_Etype (N, Typ);
2669    end Rewrite_Integer;
2670
2671    -------------------------------
2672    -- Set_And_Check_Static_Size --
2673    -------------------------------
2674
2675    procedure Set_And_Check_Static_Size
2676      (E      : Entity_Id;
2677       Esiz   : SO_Ref;
2678       RM_Siz : SO_Ref)
2679    is
2680       SC : Node_Id;
2681
2682       procedure Check_Size_Too_Small (Spec : Uint; Min : Uint);
2683       --  Spec is the number of bit specified in the size clause, and
2684       --  Min is the minimum computed size. An error is given that the
2685       --  specified size is too small if Spec < Min, and in this case
2686       --  both Esize and RM_Size are set to unknown in E. The error
2687       --  message is posted on node SC.
2688
2689       procedure Check_Unused_Bits (Spec : Uint; Max : Uint);
2690       --  Spec is the number of bits specified in the size clause, and
2691       --  Max is the maximum computed size. A warning is given about
2692       --  unused bits if Spec > Max. This warning is posted on node SC.
2693
2694       --------------------------
2695       -- Check_Size_Too_Small --
2696       --------------------------
2697
2698       procedure Check_Size_Too_Small (Spec : Uint; Min : Uint) is
2699       begin
2700          if Spec < Min then
2701             Error_Msg_Uint_1 := Min;
2702             Error_Msg_NE
2703               ("size for & too small, minimum allowed is ^", SC, E);
2704             Init_Esize   (E);
2705             Init_RM_Size (E);
2706          end if;
2707       end Check_Size_Too_Small;
2708
2709       -----------------------
2710       -- Check_Unused_Bits --
2711       -----------------------
2712
2713       procedure Check_Unused_Bits (Spec : Uint; Max : Uint) is
2714       begin
2715          if Spec > Max then
2716             Error_Msg_Uint_1 := Spec - Max;
2717             Error_Msg_NE ("?^ bits of & unused", SC, E);
2718          end if;
2719       end Check_Unused_Bits;
2720
2721    --  Start of processing for Set_And_Check_Static_Size
2722
2723    begin
2724       --  Case where Object_Size (Esize) is already set by a size clause
2725
2726       if Known_Static_Esize (E) then
2727          SC := Size_Clause (E);
2728
2729          if No (SC) then
2730             SC := Get_Attribute_Definition_Clause (E, Attribute_Object_Size);
2731          end if;
2732
2733          --  Perform checks on specified size against computed sizes
2734
2735          if Present (SC) then
2736             Check_Unused_Bits    (Esize (E), Esiz);
2737             Check_Size_Too_Small (Esize (E), RM_Siz);
2738          end if;
2739       end if;
2740
2741       --  Case where Value_Size (RM_Size) is set by specific Value_Size
2742       --  clause (we do not need to worry about Value_Size being set by
2743       --  a Size clause, since that will have set Esize as well, and we
2744       --  already took care of that case).
2745
2746       if Known_Static_RM_Size (E) then
2747          SC := Get_Attribute_Definition_Clause (E, Attribute_Value_Size);
2748
2749          --  Perform checks on specified size against computed sizes
2750
2751          if Present (SC) then
2752             Check_Unused_Bits    (RM_Size (E), Esiz);
2753             Check_Size_Too_Small (RM_Size (E), RM_Siz);
2754          end if;
2755       end if;
2756
2757       --  Set sizes if unknown
2758
2759       if Unknown_Esize (E) then
2760          Set_Esize (E, Esiz);
2761       end if;
2762
2763       if Unknown_RM_Size (E) then
2764          Set_RM_Size (E, RM_Siz);
2765       end if;
2766    end Set_And_Check_Static_Size;
2767
2768    -----------------------------
2769    -- Set_Composite_Alignment --
2770    -----------------------------
2771
2772    procedure Set_Composite_Alignment (E : Entity_Id) is
2773       Siz   : Uint;
2774       Align : Nat;
2775
2776    begin
2777       if Unknown_Alignment (E) then
2778          if Known_Static_Esize (E) then
2779             Siz := Esize (E);
2780
2781          elsif Unknown_Esize (E)
2782            and then Known_Static_RM_Size (E)
2783          then
2784             Siz := RM_Size (E);
2785
2786          else
2787             return;
2788          end if;
2789
2790          --  Size is known, alignment is not set
2791
2792          --  Reset alignment to match size if size is exactly 2, 4, or 8
2793          --  storage units.
2794
2795          if Siz = 2 * System_Storage_Unit then
2796             Align := 2;
2797          elsif Siz = 4 * System_Storage_Unit then
2798             Align := 4;
2799          elsif Siz = 8 * System_Storage_Unit then
2800             Align := 8;
2801
2802          --  On VMS, also reset for odd "in between" sizes, e.g. a 17-bit
2803          --  record is given an alignment of 4. This is more consistent with
2804          --  what DEC Ada does.
2805
2806          elsif OpenVMS_On_Target and then Siz > System_Storage_Unit then
2807
2808             if Siz <= 2 * System_Storage_Unit then
2809                Align := 2;
2810             elsif Siz <= 4 * System_Storage_Unit then
2811                Align := 4;
2812             elsif Siz <= 8 * System_Storage_Unit then
2813                Align := 8;
2814             else
2815                return;
2816             end if;
2817
2818          --  No special alignment fiddling needed
2819
2820          else
2821             return;
2822          end if;
2823
2824          --  Here Align is set to the proposed improved alignment
2825
2826          if Align > Maximum_Alignment then
2827             Align := Maximum_Alignment;
2828          end if;
2829
2830          --  Further processing for record types only to reduce the alignment
2831          --  set by the above processing in some specific cases. We do not
2832          --  do this for atomic records, since we need max alignment there.
2833
2834          if Is_Record_Type (E) then
2835
2836             --  For records, there is generally no point in setting alignment
2837             --  higher than word size since we cannot do better than move by
2838             --  words in any case
2839
2840             if Align > System_Word_Size / System_Storage_Unit then
2841                Align := System_Word_Size / System_Storage_Unit;
2842             end if;
2843
2844             --  Check components. If any component requires a higher
2845             --  alignment, then we set that higher alignment in any case.
2846
2847             declare
2848                Comp : Entity_Id;
2849
2850             begin
2851                Comp := First_Component (E);
2852                while Present (Comp) loop
2853                   if Known_Alignment (Etype (Comp)) then
2854                      declare
2855                         Calign : constant Uint := Alignment (Etype (Comp));
2856
2857                      begin
2858                         --  The cases to worry about are when the alignment
2859                         --  of the component type is larger than the alignment
2860                         --  we have so far, and either there is no component
2861                         --  clause for the alignment, or the length set by
2862                         --  the component clause matches the alignment set.
2863
2864                         if Calign > Align
2865                           and then
2866                             (Unknown_Esize (Comp)
2867                                or else (Known_Static_Esize (Comp)
2868                                           and then
2869                                         Esize (Comp) =
2870                                            Calign * System_Storage_Unit))
2871                         then
2872                            Align := UI_To_Int (Calign);
2873                         end if;
2874                      end;
2875                   end if;
2876
2877                   Next_Component (Comp);
2878                end loop;
2879             end;
2880          end if;
2881
2882          --  Set chosen alignment
2883
2884          Set_Alignment (E, UI_From_Int (Align));
2885
2886          if Known_Static_Esize (E)
2887            and then Esize (E) < Align * System_Storage_Unit
2888          then
2889             Set_Esize (E, UI_From_Int (Align * System_Storage_Unit));
2890          end if;
2891       end if;
2892    end Set_Composite_Alignment;
2893
2894    --------------------------
2895    -- Set_Discrete_RM_Size --
2896    --------------------------
2897
2898    procedure Set_Discrete_RM_Size (Def_Id : Entity_Id) is
2899       FST : constant Entity_Id := First_Subtype (Def_Id);
2900
2901    begin
2902       --  All discrete types except for the base types in standard
2903       --  are constrained, so indicate this by setting Is_Constrained.
2904
2905       Set_Is_Constrained (Def_Id);
2906
2907       --  We set generic types to have an unknown size, since the
2908       --  representation of a generic type is irrelevant, in view
2909       --  of the fact that they have nothing to do with code.
2910
2911       if Is_Generic_Type (Root_Type (FST)) then
2912          Set_RM_Size (Def_Id, Uint_0);
2913
2914       --  If the subtype statically matches the first subtype, then
2915       --  it is required to have exactly the same layout. This is
2916       --  required by aliasing considerations.
2917
2918       elsif Def_Id /= FST and then
2919         Subtypes_Statically_Match (Def_Id, FST)
2920       then
2921          Set_RM_Size   (Def_Id, RM_Size (FST));
2922          Set_Size_Info (Def_Id, FST);
2923
2924       --  In all other cases the RM_Size is set to the minimum size.
2925       --  Note that this routine is never called for subtypes for which
2926       --  the RM_Size is set explicitly by an attribute clause.
2927
2928       else
2929          Set_RM_Size (Def_Id, UI_From_Int (Minimum_Size (Def_Id)));
2930       end if;
2931    end Set_Discrete_RM_Size;
2932
2933    ------------------------
2934    -- Set_Elem_Alignment --
2935    ------------------------
2936
2937    procedure Set_Elem_Alignment (E : Entity_Id) is
2938    begin
2939       --  Do not set alignment for packed array types, unless we are doing
2940       --  front end layout, because otherwise this is always handled in the
2941       --  backend.
2942
2943       if Is_Packed_Array_Type (E) and then not Frontend_Layout_On_Target then
2944          return;
2945
2946       --  If there is an alignment clause, then we respect it
2947
2948       elsif Has_Alignment_Clause (E) then
2949          return;
2950
2951       --  If the size is not set, then don't attempt to set the alignment. This
2952       --  happens in the backend layout case for access-to-subprogram types.
2953
2954       elsif not Known_Static_Esize (E) then
2955          return;
2956
2957       --  For access types, do not set the alignment if the size is less than
2958       --  the allowed minimum size. This avoids cascaded error messages.
2959
2960       elsif Is_Access_Type (E)
2961         and then Esize (E) < System_Address_Size
2962       then
2963          return;
2964       end if;
2965
2966       --  Here we calculate the alignment as the largest power of two
2967       --  multiple of System.Storage_Unit that does not exceed either
2968       --  the actual size of the type, or the maximum allowed alignment.
2969
2970       declare
2971          S : constant Int :=
2972                UI_To_Int (Esize (E)) / SSU;
2973          A : Nat;
2974
2975       begin
2976          A := 1;
2977          while 2 * A <= Ttypes.Maximum_Alignment
2978             and then 2 * A <= S
2979          loop
2980             A := 2 * A;
2981          end loop;
2982
2983          --  Now we think we should set the alignment to A, but we
2984          --  skip this if an alignment is already set to a value
2985          --  greater than A (happens for derived types).
2986
2987          --  However, if the alignment is known and too small it
2988          --  must be increased, this happens in a case like:
2989
2990          --     type R is new Character;
2991          --     for R'Size use 16;
2992
2993          --  Here the alignment inherited from Character is 1, but
2994          --  it must be increased to 2 to reflect the increased size.
2995
2996          if Unknown_Alignment (E) or else Alignment (E) < A then
2997             Init_Alignment (E, A);
2998          end if;
2999       end;
3000    end Set_Elem_Alignment;
3001
3002    ----------------------
3003    -- SO_Ref_From_Expr --
3004    ----------------------
3005
3006    function SO_Ref_From_Expr
3007      (Expr      : Node_Id;
3008       Ins_Type  : Entity_Id;
3009       Vtype     : Entity_Id := Empty;
3010       Make_Func : Boolean   := False) return Dynamic_SO_Ref
3011    is
3012       Loc  : constant Source_Ptr := Sloc (Ins_Type);
3013
3014       K : constant Entity_Id :=
3015             Make_Defining_Identifier (Loc,
3016               Chars => New_Internal_Name ('K'));
3017
3018       Decl : Node_Id;
3019
3020       Vtype_Primary_View : Entity_Id;
3021
3022       function Check_Node_V_Ref (N : Node_Id) return Traverse_Result;
3023       --  Function used to check one node for reference to V
3024
3025       function Has_V_Ref is new Traverse_Func (Check_Node_V_Ref);
3026       --  Function used to traverse tree to check for reference to V
3027
3028       ----------------------
3029       -- Check_Node_V_Ref --
3030       ----------------------
3031
3032       function Check_Node_V_Ref (N : Node_Id) return Traverse_Result is
3033       begin
3034          if Nkind (N) = N_Identifier then
3035             if Chars (N) = Vname then
3036                return Abandon;
3037             else
3038                return Skip;
3039             end if;
3040
3041          else
3042             return OK;
3043          end if;
3044       end Check_Node_V_Ref;
3045
3046    --  Start of processing for SO_Ref_From_Expr
3047
3048    begin
3049       --  Case of expression is an integer literal, in this case we just
3050       --  return the value (which must always be non-negative, since size
3051       --  and offset values can never be negative).
3052
3053       if Nkind (Expr) = N_Integer_Literal then
3054          pragma Assert (Intval (Expr) >= 0);
3055          return Intval (Expr);
3056       end if;
3057
3058       --  Case where there is a reference to V, create function
3059
3060       if Has_V_Ref (Expr) = Abandon then
3061
3062          pragma Assert (Present (Vtype));
3063
3064          --  Check whether Vtype is a view of a private type and ensure that
3065          --  we use the primary view of the type (which is denoted by its
3066          --  Etype, whether it's the type's partial or full view entity).
3067          --  This is needed to make sure that we use the same (primary) view
3068          --  of the type for all V formals, whether the current view of the
3069          --  type is the partial or full view, so that types will always
3070          --  match on calls from one size function to another.
3071
3072          if  Has_Private_Declaration (Vtype) then
3073             Vtype_Primary_View := Etype (Vtype);
3074          else
3075             Vtype_Primary_View := Vtype;
3076          end if;
3077
3078          Set_Is_Discrim_SO_Function (K);
3079
3080          Decl :=
3081            Make_Subprogram_Body (Loc,
3082
3083              Specification =>
3084                Make_Function_Specification (Loc,
3085                  Defining_Unit_Name => K,
3086                    Parameter_Specifications => New_List (
3087                      Make_Parameter_Specification (Loc,
3088                        Defining_Identifier =>
3089                          Make_Defining_Identifier (Loc, Chars => Vname),
3090                        Parameter_Type      =>
3091                          New_Occurrence_Of (Vtype_Primary_View, Loc))),
3092                    Result_Definition =>
3093                      New_Occurrence_Of (Standard_Unsigned, Loc)),
3094
3095              Declarations => Empty_List,
3096
3097              Handled_Statement_Sequence =>
3098                Make_Handled_Sequence_Of_Statements (Loc,
3099                  Statements => New_List (
3100                    Make_Simple_Return_Statement (Loc,
3101                      Expression => Expr))));
3102
3103       --  The caller requests that the expression be encapsulated in
3104       --  a parameterless function.
3105
3106       elsif Make_Func then
3107          Decl :=
3108            Make_Subprogram_Body (Loc,
3109
3110              Specification =>
3111                Make_Function_Specification (Loc,
3112                  Defining_Unit_Name => K,
3113                    Parameter_Specifications => Empty_List,
3114                    Result_Definition =>
3115                      New_Occurrence_Of (Standard_Unsigned, Loc)),
3116
3117              Declarations => Empty_List,
3118
3119              Handled_Statement_Sequence =>
3120                Make_Handled_Sequence_Of_Statements (Loc,
3121                  Statements => New_List (
3122                    Make_Simple_Return_Statement (Loc, Expression => Expr))));
3123
3124       --  No reference to V and function not requested, so create a constant
3125
3126       else
3127          Decl :=
3128            Make_Object_Declaration (Loc,
3129              Defining_Identifier => K,
3130              Object_Definition   =>
3131                New_Occurrence_Of (Standard_Unsigned, Loc),
3132              Constant_Present    => True,
3133              Expression          => Expr);
3134       end if;
3135
3136       Append_Freeze_Action (Ins_Type, Decl);
3137       Analyze (Decl);
3138       return Create_Dynamic_SO_Ref (K);
3139    end SO_Ref_From_Expr;
3140
3141 end Layout;