OSDN Git Service

2008-09-10 Joel Sherrill <joel.sherrill@oarcorp.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-2008, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Errout;   use Errout;
31 with Exp_Ch3;  use Exp_Ch3;
32 with Exp_Util; use Exp_Util;
33 with Namet;    use Namet;
34 with Nlists;   use Nlists;
35 with Nmake;    use Nmake;
36 with Opt;      use Opt;
37 with Repinfo;  use Repinfo;
38 with Sem;      use Sem;
39 with Sem_Ch13; use Sem_Ch13;
40 with Sem_Eval; use Sem_Eval;
41 with Sem_Util; use Sem_Util;
42 with Sinfo;    use Sinfo;
43 with Snames;   use Snames;
44 with Stand;    use Stand;
45 with Targparm; use Targparm;
46 with Tbuild;   use Tbuild;
47 with Ttypes;   use Ttypes;
48 with Uintp;    use Uintp;
49
50 package body Layout is
51
52    ------------------------
53    -- Local Declarations --
54    ------------------------
55
56    SSU : constant Int := Ttypes.System_Storage_Unit;
57    --  Short hand for System_Storage_Unit
58
59    Vname : constant Name_Id := Name_uV;
60    --  Formal parameter name used for functions generated for size offset
61    --  values that depend on the discriminant. All such functions have the
62    --  following form:
63    --
64    --     function xxx (V : vtyp) return Unsigned is
65    --     begin
66    --        return ... expression involving V.discrim
67    --     end xxx;
68
69    -----------------------
70    -- Local Subprograms --
71    -----------------------
72
73    function Assoc_Add
74      (Loc        : Source_Ptr;
75       Left_Opnd  : Node_Id;
76       Right_Opnd : Node_Id) return Node_Id;
77    --  This is like Make_Op_Add except that it optimizes some cases knowing
78    --  that associative rearrangement is allowed for constant folding if one
79    --  of the operands is a compile time known value.
80
81    function Assoc_Multiply
82      (Loc        : Source_Ptr;
83       Left_Opnd  : Node_Id;
84       Right_Opnd : Node_Id) return Node_Id;
85    --  This is like Make_Op_Multiply except that it optimizes some cases
86    --  knowing that associative rearrangement is allowed for constant folding
87    --  if one of the operands is a compile time known value
88
89    function Assoc_Subtract
90      (Loc        : Source_Ptr;
91       Left_Opnd  : Node_Id;
92       Right_Opnd : Node_Id) return Node_Id;
93    --  This is like Make_Op_Subtract except that it optimizes some cases
94    --  knowing that associative rearrangement is allowed for constant folding
95    --  if one of the operands is a compile time known value
96
97    function Bits_To_SU (N : Node_Id) return Node_Id;
98    --  This is used when we cross the boundary from static sizes in bits to
99    --  dynamic sizes in storage units. If the argument N is anything other
100    --  than an integer literal, it is returned unchanged, but if it is an
101    --  integer literal, then it is taken as a size in bits, and is replaced
102    --  by the corresponding size in storage units.
103
104    function Compute_Length (Lo : Node_Id; Hi : Node_Id) return Node_Id;
105    --  Given expressions for the low bound (Lo) and the high bound (Hi),
106    --  Build an expression for the value hi-lo+1, converted to type
107    --  Standard.Unsigned. Takes care of the case where the operands
108    --  are of an enumeration type (so that the subtraction cannot be
109    --  done directly) by applying the Pos operator to Hi/Lo first.
110
111    function Expr_From_SO_Ref
112      (Loc  : Source_Ptr;
113       D    : SO_Ref;
114       Comp : Entity_Id := Empty) return Node_Id;
115    --  Given a value D from a size or offset field, return an expression
116    --  representing the value stored. If the value is known at compile time,
117    --  then an N_Integer_Literal is returned with the appropriate value. If
118    --  the value references a constant entity, then an N_Identifier node
119    --  referencing this entity is returned. If the value denotes a size
120    --  function, then returns a call node denoting the given function, with
121    --  a single actual parameter that either refers to the parameter V of
122    --  an enclosing size function (if Comp is Empty or its type doesn't match
123    --  the function's formal), or else is a selected component V.c when Comp
124    --  denotes a component c whose type matches that of the function formal.
125    --  The Loc value is used for the Sloc value of constructed notes.
126
127    function SO_Ref_From_Expr
128      (Expr      : Node_Id;
129       Ins_Type  : Entity_Id;
130       Vtype     : Entity_Id := Empty;
131       Make_Func : Boolean   := False) return Dynamic_SO_Ref;
132    --  This routine is used in the case where a size/offset value is dynamic
133    --  and is represented by the expression Expr. SO_Ref_From_Expr checks if
134    --  the Expr contains a reference to the identifier V, and if so builds
135    --  a function depending on discriminants of the formal parameter V which
136    --  is of type Vtype. Otherwise, if the parameter Make_Func is True, then
137    --  Expr will be encapsulated in a parameterless function; if Make_Func is
138    --  False, then a constant entity with the value Expr is built. The result
139    --  is a Dynamic_SO_Ref to the created entity. Note that Vtype can be
140    --  omitted if Expr does not contain any reference to V, the created entity.
141    --  The declaration created is inserted in the freeze actions of Ins_Type,
142    --  which also supplies the Sloc for created nodes. This function also takes
143    --  care of making sure that the expression is properly analyzed and
144    --  resolved (which may not be the case yet if we build the expression
145    --  in this unit).
146
147    function Get_Max_SU_Size (E : Entity_Id) return Node_Id;
148    --  E is an array type or subtype that has at least one index bound that
149    --  is the value of a record discriminant. For such an array, the function
150    --  computes an expression that yields the maximum possible size of the
151    --  array in storage units. The result is not defined for any other type,
152    --  or for arrays that do not depend on discriminants, and it is a fatal
153    --  error to call this unless Size_Depends_On_Discriminant (E) is True.
154
155    procedure Layout_Array_Type (E : Entity_Id);
156    --  Front-end layout of non-bit-packed array type or subtype
157
158    procedure Layout_Record_Type (E : Entity_Id);
159    --  Front-end layout of record type
160
161    procedure Rewrite_Integer (N : Node_Id; V : Uint);
162    --  Rewrite node N with an integer literal whose value is V. The Sloc for
163    --  the new node is taken from N, and the type of the literal is set to a
164    --  copy of the type of N on entry.
165
166    procedure Set_And_Check_Static_Size
167      (E      : Entity_Id;
168       Esiz   : SO_Ref;
169       RM_Siz : SO_Ref);
170    --  This procedure is called to check explicit given sizes (possibly stored
171    --  in the Esize and RM_Size fields of E) against computed Object_Size
172    --  (Esiz) and Value_Size (RM_Siz) values. Appropriate errors and warnings
173    --  are posted if specified sizes are inconsistent with specified sizes. On
174    --  return, Esize and RM_Size fields of E are set (either from previously
175    --  given values, or from the newly computed values, as appropriate).
176
177    procedure Set_Composite_Alignment (E : Entity_Id);
178    --  This procedure is called for record types and subtypes, and also for
179    --  atomic array types and subtypes. If no alignment is set, and the size
180    --  is 2 or 4 (or 8 if the word size is 8), then the alignment is set to
181    --  match the size.
182
183    ----------------------------
184    -- Adjust_Esize_Alignment --
185    ----------------------------
186
187    procedure Adjust_Esize_Alignment (E : Entity_Id) is
188       Abits     : Int;
189       Esize_Set : Boolean;
190
191    begin
192       --  Nothing to do if size unknown
193
194       if Unknown_Esize (E) then
195          return;
196       end if;
197
198       --  Determine if size is constrained by an attribute definition clause
199       --  which must be obeyed. If so, we cannot increase the size in this
200       --  routine.
201
202       --  For a type, the issue is whether an object size clause has been set.
203       --  A normal size clause constrains only the value size (RM_Size)
204
205       if Is_Type (E) then
206          Esize_Set := Has_Object_Size_Clause (E);
207
208       --  For an object, the issue is whether a size clause is present
209
210       else
211          Esize_Set := Has_Size_Clause (E);
212       end if;
213
214       --  If size is known it must be a multiple of the storage unit size
215
216       if Esize (E) mod SSU /= 0 then
217
218          --  If not, and size specified, then give error
219
220          if Esize_Set then
221             Error_Msg_NE
222               ("size for& not a multiple of storage unit size",
223                Size_Clause (E), E);
224             return;
225
226          --  Otherwise bump up size to a storage unit boundary
227
228          else
229             Set_Esize (E, (Esize (E) + SSU - 1) / SSU * SSU);
230          end if;
231       end if;
232
233       --  Now we have the size set, it must be a multiple of the alignment
234       --  nothing more we can do here if the alignment is unknown here.
235
236       if Unknown_Alignment (E) then
237          return;
238       end if;
239
240       --  At this point both the Esize and Alignment are known, so we need
241       --  to make sure they are consistent.
242
243       Abits := UI_To_Int (Alignment (E)) * SSU;
244
245       if Esize (E) mod Abits = 0 then
246          return;
247       end if;
248
249       --  Here we have a situation where the Esize is not a multiple of the
250       --  alignment. We must either increase Esize or reduce the alignment to
251       --  correct this situation.
252
253       --  The case in which we can decrease the alignment is where the
254       --  alignment was not set by an alignment clause, and the type in
255       --  question is a discrete type, where it is definitely safe to reduce
256       --  the alignment. For example:
257
258       --    t : integer range 1 .. 2;
259       --    for t'size use 8;
260
261       --  In this situation, the initial alignment of t is 4, copied from
262       --  the Integer base type, but it is safe to reduce it to 1 at this
263       --  stage, since we will only be loading a single storage unit.
264
265       if Is_Discrete_Type (Etype (E))
266         and then not Has_Alignment_Clause (E)
267       then
268          loop
269             Abits := Abits / 2;
270             exit when Esize (E) mod Abits = 0;
271          end loop;
272
273          Init_Alignment (E, Abits / SSU);
274          return;
275       end if;
276
277       --  Now the only possible approach left is to increase the Esize but we
278       --  can't do that if the size was set by a specific clause.
279
280       if Esize_Set then
281          Error_Msg_NE
282            ("size for& is not a multiple of alignment",
283             Size_Clause (E), E);
284
285       --  Otherwise we can indeed increase the size to a multiple of alignment
286
287       else
288          Set_Esize (E, ((Esize (E) + (Abits - 1)) / Abits) * Abits);
289       end if;
290    end Adjust_Esize_Alignment;
291
292    ---------------
293    -- Assoc_Add --
294    ---------------
295
296    function Assoc_Add
297      (Loc        : Source_Ptr;
298       Left_Opnd  : Node_Id;
299       Right_Opnd : Node_Id) return Node_Id
300    is
301       L : Node_Id;
302       R : Uint;
303
304    begin
305       --  Case of right operand is a constant
306
307       if Compile_Time_Known_Value (Right_Opnd) then
308          L := Left_Opnd;
309          R := Expr_Value (Right_Opnd);
310
311       --  Case of left operand is a constant
312
313       elsif Compile_Time_Known_Value (Left_Opnd) then
314          L := Right_Opnd;
315          R := Expr_Value (Left_Opnd);
316
317       --  Neither operand is a constant, do the addition with no optimization
318
319       else
320          return Make_Op_Add (Loc, Left_Opnd, Right_Opnd);
321       end if;
322
323       --  Case of left operand is an addition
324
325       if Nkind (L) = N_Op_Add then
326
327          --  (C1 + E) + C2 = (C1 + C2) + E
328
329          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
330             Rewrite_Integer
331               (Sinfo.Left_Opnd (L),
332                Expr_Value (Sinfo.Left_Opnd (L)) + R);
333             return L;
334
335          --  (E + C1) + C2 = E + (C1 + C2)
336
337          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
338             Rewrite_Integer
339               (Sinfo.Right_Opnd (L),
340                Expr_Value (Sinfo.Right_Opnd (L)) + R);
341             return L;
342          end if;
343
344       --  Case of left operand is a subtraction
345
346       elsif Nkind (L) = N_Op_Subtract then
347
348          --  (C1 - E) + C2 = (C1 + C2) + E
349
350          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
351             Rewrite_Integer
352               (Sinfo.Left_Opnd (L),
353                Expr_Value (Sinfo.Left_Opnd (L)) + R);
354             return L;
355
356          --  (E - C1) + C2 = E - (C1 - C2)
357
358          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
359             Rewrite_Integer
360               (Sinfo.Right_Opnd (L),
361                Expr_Value (Sinfo.Right_Opnd (L)) - R);
362             return L;
363          end if;
364       end if;
365
366       --  Not optimizable, do the addition
367
368       return Make_Op_Add (Loc, Left_Opnd, Right_Opnd);
369    end Assoc_Add;
370
371    --------------------
372    -- Assoc_Multiply --
373    --------------------
374
375    function Assoc_Multiply
376      (Loc        : Source_Ptr;
377       Left_Opnd  : Node_Id;
378       Right_Opnd : Node_Id) return Node_Id
379    is
380       L : Node_Id;
381       R : Uint;
382
383    begin
384       --  Case of right operand is a constant
385
386       if Compile_Time_Known_Value (Right_Opnd) then
387          L := Left_Opnd;
388          R := Expr_Value (Right_Opnd);
389
390       --  Case of left operand is a constant
391
392       elsif Compile_Time_Known_Value (Left_Opnd) then
393          L := Right_Opnd;
394          R := Expr_Value (Left_Opnd);
395
396       --  Neither operand is a constant, do the multiply with no optimization
397
398       else
399          return Make_Op_Multiply (Loc, Left_Opnd, Right_Opnd);
400       end if;
401
402       --  Case of left operand is an multiplication
403
404       if Nkind (L) = N_Op_Multiply then
405
406          --  (C1 * E) * C2 = (C1 * C2) + E
407
408          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
409             Rewrite_Integer
410               (Sinfo.Left_Opnd (L),
411                Expr_Value (Sinfo.Left_Opnd (L)) * R);
412             return L;
413
414          --  (E * C1) * C2 = E * (C1 * C2)
415
416          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
417             Rewrite_Integer
418               (Sinfo.Right_Opnd (L),
419                Expr_Value (Sinfo.Right_Opnd (L)) * R);
420             return L;
421          end if;
422       end if;
423
424       --  Not optimizable, do the multiplication
425
426       return Make_Op_Multiply (Loc, Left_Opnd, Right_Opnd);
427    end Assoc_Multiply;
428
429    --------------------
430    -- Assoc_Subtract --
431    --------------------
432
433    function Assoc_Subtract
434      (Loc        : Source_Ptr;
435       Left_Opnd  : Node_Id;
436       Right_Opnd : Node_Id) return Node_Id
437    is
438       L : Node_Id;
439       R : Uint;
440
441    begin
442       --  Case of right operand is a constant
443
444       if Compile_Time_Known_Value (Right_Opnd) then
445          L := Left_Opnd;
446          R := Expr_Value (Right_Opnd);
447
448       --  Right operand is a constant, do the subtract with no optimization
449
450       else
451          return Make_Op_Subtract (Loc, Left_Opnd, Right_Opnd);
452       end if;
453
454       --  Case of left operand is an addition
455
456       if Nkind (L) = N_Op_Add then
457
458          --  (C1 + E) - C2 = (C1 - C2) + E
459
460          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
461             Rewrite_Integer
462               (Sinfo.Left_Opnd (L),
463                Expr_Value (Sinfo.Left_Opnd (L)) - R);
464             return L;
465
466          --  (E + C1) - C2 = E + (C1 - C2)
467
468          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
469             Rewrite_Integer
470               (Sinfo.Right_Opnd (L),
471                Expr_Value (Sinfo.Right_Opnd (L)) - R);
472             return L;
473          end if;
474
475       --  Case of left operand is a subtraction
476
477       elsif Nkind (L) = N_Op_Subtract then
478
479          --  (C1 - E) - C2 = (C1 - C2) + E
480
481          if Compile_Time_Known_Value (Sinfo.Left_Opnd (L)) then
482             Rewrite_Integer
483               (Sinfo.Left_Opnd (L),
484                Expr_Value (Sinfo.Left_Opnd (L)) + R);
485             return L;
486
487          --  (E - C1) - C2 = E - (C1 + C2)
488
489          elsif Compile_Time_Known_Value (Sinfo.Right_Opnd (L)) then
490             Rewrite_Integer
491               (Sinfo.Right_Opnd (L),
492                Expr_Value (Sinfo.Right_Opnd (L)) + R);
493             return L;
494          end if;
495       end if;
496
497       --  Not optimizable, do the subtraction
498
499       return Make_Op_Subtract (Loc, Left_Opnd, Right_Opnd);
500    end Assoc_Subtract;
501
502    ----------------
503    -- Bits_To_SU --
504    ----------------
505
506    function Bits_To_SU (N : Node_Id) return Node_Id is
507    begin
508       if Nkind (N) = N_Integer_Literal then
509          Set_Intval (N, (Intval (N) + (SSU - 1)) / SSU);
510       end if;
511
512       return N;
513    end Bits_To_SU;
514
515    --------------------
516    -- Compute_Length --
517    --------------------
518
519    function Compute_Length (Lo : Node_Id; Hi : Node_Id) return Node_Id is
520       Loc    : constant Source_Ptr := Sloc (Lo);
521       Typ    : constant Entity_Id  := Etype (Lo);
522       Lo_Op  : Node_Id;
523       Hi_Op  : Node_Id;
524       Lo_Dim : Uint;
525       Hi_Dim : Uint;
526
527    begin
528       --  If the bounds are First and Last attributes for the same dimension
529       --  and both have prefixes that denotes the same entity, then we create
530       --  and return a Length attribute. This may allow the back end to
531       --  generate better code in cases where it already has the length.
532
533       if Nkind (Lo) = N_Attribute_Reference
534         and then Attribute_Name (Lo) = Name_First
535         and then Nkind (Hi) = N_Attribute_Reference
536         and then Attribute_Name (Hi) = Name_Last
537         and then Is_Entity_Name (Prefix (Lo))
538         and then Is_Entity_Name (Prefix (Hi))
539         and then Entity (Prefix (Lo)) = Entity (Prefix (Hi))
540       then
541          Lo_Dim := Uint_1;
542          Hi_Dim := Uint_1;
543
544          if Present (First (Expressions (Lo))) then
545             Lo_Dim := Expr_Value (First (Expressions (Lo)));
546          end if;
547
548          if Present (First (Expressions (Hi))) then
549             Hi_Dim := Expr_Value (First (Expressions (Hi)));
550          end if;
551
552          if Lo_Dim = Hi_Dim then
553             return
554               Make_Attribute_Reference (Loc,
555                 Prefix         => New_Occurrence_Of
556                                     (Entity (Prefix (Lo)), Loc),
557                 Attribute_Name => Name_Length,
558                 Expressions    => New_List
559                                     (Make_Integer_Literal (Loc, Lo_Dim)));
560          end if;
561       end if;
562
563       Lo_Op := New_Copy_Tree (Lo);
564       Hi_Op := New_Copy_Tree (Hi);
565
566       --  If type is enumeration type, then use Pos attribute to convert
567       --  to integer type for which subtraction is a permitted operation.
568
569       if Is_Enumeration_Type (Typ) then
570          Lo_Op :=
571            Make_Attribute_Reference (Loc,
572              Prefix         => New_Occurrence_Of (Typ, Loc),
573              Attribute_Name => Name_Pos,
574              Expressions    => New_List (Lo_Op));
575
576          Hi_Op :=
577            Make_Attribute_Reference (Loc,
578              Prefix         => New_Occurrence_Of (Typ, Loc),
579              Attribute_Name => Name_Pos,
580              Expressions    => New_List (Hi_Op));
581       end if;
582
583       return
584         Assoc_Add (Loc,
585           Left_Opnd =>
586             Assoc_Subtract (Loc,
587               Left_Opnd  => Hi_Op,
588               Right_Opnd => Lo_Op),
589           Right_Opnd => Make_Integer_Literal (Loc, 1));
590    end Compute_Length;
591
592    ----------------------
593    -- Expr_From_SO_Ref --
594    ----------------------
595
596    function Expr_From_SO_Ref
597      (Loc  : Source_Ptr;
598       D    : SO_Ref;
599       Comp : Entity_Id := Empty) return Node_Id
600    is
601       Ent : Entity_Id;
602
603    begin
604       if Is_Dynamic_SO_Ref (D) then
605          Ent := Get_Dynamic_SO_Entity (D);
606
607          if Is_Discrim_SO_Function (Ent) then
608
609             --  If a component is passed in whose type matches the type of
610             --  the function formal, then select that component from the "V"
611             --  parameter rather than passing "V" directly.
612
613             if Present (Comp)
614                and then Base_Type (Etype (Comp))
615                           = Base_Type (Etype (First_Formal (Ent)))
616             then
617                return
618                  Make_Function_Call (Loc,
619                    Name                   => New_Occurrence_Of (Ent, Loc),
620                    Parameter_Associations => New_List (
621                      Make_Selected_Component (Loc,
622                        Prefix        => Make_Identifier (Loc, Chars => Vname),
623                        Selector_Name => New_Occurrence_Of (Comp, Loc))));
624
625             else
626                return
627                  Make_Function_Call (Loc,
628                    Name                   => New_Occurrence_Of (Ent, Loc),
629                    Parameter_Associations => New_List (
630                      Make_Identifier (Loc, Chars => Vname)));
631             end if;
632
633          else
634             return New_Occurrence_Of (Ent, Loc);
635          end if;
636
637       else
638          return Make_Integer_Literal (Loc, D);
639       end if;
640    end Expr_From_SO_Ref;
641
642    ---------------------
643    -- Get_Max_SU_Size --
644    ---------------------
645
646    function Get_Max_SU_Size (E : Entity_Id) return Node_Id is
647       Loc  : constant Source_Ptr := Sloc (E);
648       Indx : Node_Id;
649       Ityp : Entity_Id;
650       Lo   : Node_Id;
651       Hi   : Node_Id;
652       S    : Uint;
653       Len  : Node_Id;
654
655       type Val_Status_Type is (Const, Dynamic);
656
657       type Val_Type (Status : Val_Status_Type := Const) is
658          record
659             case Status is
660                when Const   => Val : Uint;
661                when Dynamic => Nod : Node_Id;
662             end case;
663          end record;
664       --  Shows the status of the value so far. Const means that the value is
665       --  constant, and Val is the current constant value. Dynamic means that
666       --  the value is dynamic, and in this case Nod is the Node_Id of the
667       --  expression to compute the value.
668
669       Size : Val_Type;
670       --  Calculated value so far if Size.Status = Const,
671       --  or expression value so far if Size.Status = Dynamic.
672
673       SU_Convert_Required : Boolean := False;
674       --  This is set to True if the final result must be converted from bits
675       --  to storage units (rounding up to a storage unit boundary).
676
677       -----------------------
678       -- Local Subprograms --
679       -----------------------
680
681       procedure Max_Discrim (N : in out Node_Id);
682       --  If the node N represents a discriminant, replace it by the maximum
683       --  value of the discriminant.
684
685       procedure Min_Discrim (N : in out Node_Id);
686       --  If the node N represents a discriminant, replace it by the minimum
687       --  value of the discriminant.
688
689       -----------------
690       -- Max_Discrim --
691       -----------------
692
693       procedure Max_Discrim (N : in out Node_Id) is
694       begin
695          if Nkind (N) = N_Identifier
696            and then Ekind (Entity (N)) = E_Discriminant
697          then
698             N := Type_High_Bound (Etype (N));
699          end if;
700       end Max_Discrim;
701
702       -----------------
703       -- Min_Discrim --
704       -----------------
705
706       procedure Min_Discrim (N : in out Node_Id) is
707       begin
708          if Nkind (N) = N_Identifier
709            and then Ekind (Entity (N)) = E_Discriminant
710          then
711             N := Type_Low_Bound (Etype (N));
712          end if;
713       end Min_Discrim;
714
715    --  Start of processing for Get_Max_SU_Size
716
717    begin
718       pragma Assert (Size_Depends_On_Discriminant (E));
719
720       --  Initialize status from component size
721
722       if Known_Static_Component_Size (E) then
723          Size := (Const, Component_Size (E));
724
725       else
726          Size := (Dynamic, Expr_From_SO_Ref (Loc, Component_Size (E)));
727       end if;
728
729       --  Loop through indices
730
731       Indx := First_Index (E);
732       while Present (Indx) loop
733          Ityp := Etype (Indx);
734          Lo := Type_Low_Bound (Ityp);
735          Hi := Type_High_Bound (Ityp);
736
737          Min_Discrim (Lo);
738          Max_Discrim (Hi);
739
740          --  Value of the current subscript range is statically known
741
742          if Compile_Time_Known_Value (Lo)
743            and then Compile_Time_Known_Value (Hi)
744          then
745             S := Expr_Value (Hi) - Expr_Value (Lo) + 1;
746
747             --  If known flat bound, entire size of array is zero!
748
749             if S <= 0 then
750                return Make_Integer_Literal (Loc, 0);
751             end if;
752
753             --  Current value is constant, evolve value
754
755             if Size.Status = Const then
756                Size.Val := Size.Val * S;
757
758             --  Current value is dynamic
759
760             else
761                --  An interesting little optimization, if we have a pending
762                --  conversion from bits to storage units, and the current
763                --  length is a multiple of the storage unit size, then we
764                --  can take the factor out here statically, avoiding some
765                --  extra dynamic computations at the end.
766
767                if SU_Convert_Required and then S mod SSU = 0 then
768                   S := S / SSU;
769                   SU_Convert_Required := False;
770                end if;
771
772                Size.Nod :=
773                  Assoc_Multiply (Loc,
774                    Left_Opnd  => Size.Nod,
775                    Right_Opnd =>
776                      Make_Integer_Literal (Loc, Intval => S));
777             end if;
778
779          --  Value of the current subscript range is dynamic
780
781          else
782             --  If the current size value is constant, then here is where we
783             --  make a transition to dynamic values, which are always stored
784             --  in storage units, However, we do not want to convert to SU's
785             --  too soon, consider the case of a packed array of single bits,
786             --  we want to do the SU conversion after computing the size in
787             --  this case.
788
789             if Size.Status = Const then
790
791                --  If the current value is a multiple of the storage unit,
792                --  then most certainly we can do the conversion now, simply
793                --  by dividing the current value by the storage unit value.
794                --  If this works, we set SU_Convert_Required to False.
795
796                if Size.Val mod SSU = 0 then
797
798                   Size :=
799                     (Dynamic, Make_Integer_Literal (Loc, Size.Val / SSU));
800                   SU_Convert_Required := False;
801
802                --  Otherwise, we go ahead and convert the value in bits, and
803                --  set SU_Convert_Required to True to ensure that the final
804                --  value is indeed properly converted.
805
806                else
807                   Size := (Dynamic, Make_Integer_Literal (Loc, Size.Val));
808                   SU_Convert_Required := True;
809                end if;
810             end if;
811
812             --  Length is hi-lo+1
813
814             Len := Compute_Length (Lo, Hi);
815
816             --  Check possible range of Len
817
818             declare
819                OK  : Boolean;
820                LLo : Uint;
821                LHi : Uint;
822                pragma Warnings (Off, LHi);
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, we need
831                --  a max with zero, since length must be non-negative.
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 a
850       --  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 the
904       --  array (which has already been set) by the length of each of the
905       --  indexes. If all these values are known at compile time, then the
906       --  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 discriminant
945       --  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 expression 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 is
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, then
1143                --  we can use a value of one for the size and reduce the
1144                --  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, and
1152                --  set SU_Convert_Required to True to ensure that the final
1153                --  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 be
1169             --  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, we
1197                   --  need a max with zero, since length cannot be negative.
1198
1199                   if not OK or else LLo < 0 then
1200                      Len :=
1201                        Make_Attribute_Reference (Loc,
1202                          Prefix         =>
1203                            New_Occurrence_Of (Standard_Unsigned, Loc),
1204                          Attribute_Name => Name_Max,
1205                          Expressions    => New_List (
1206                            Make_Integer_Literal (Loc, 0),
1207                            Len));
1208                   end if;
1209                end;
1210             end if;
1211
1212             --  At this stage, Len has the expression for the length
1213
1214             Size.Nod :=
1215               Assoc_Multiply (Loc,
1216                 Left_Opnd  => Size.Nod,
1217                 Right_Opnd => Len);
1218          end if;
1219
1220          Next_Index (Indx);
1221       end loop;
1222
1223       --  Here after processing all bounds to set sizes. If the value is a
1224       --  constant, then it is bits, and the only thing we need to do is to
1225       --  check against explicit given size and do alignment adjust.
1226
1227       if Size.Status = Const then
1228          Set_And_Check_Static_Size (E, Size.Val, Size.Val);
1229          Adjust_Esize_Alignment (E);
1230
1231       --  Case where the value is dynamic
1232
1233       else
1234          --  Do convert from bits to SU's if needed
1235
1236          if SU_Convert_Required then
1237
1238             --  The expression required is:
1239             --    (Size.Nod + Storage_Divisor - 1) / Storage_Divisor
1240
1241             Size.Nod :=
1242               Make_Op_Divide (Loc,
1243                 Left_Opnd =>
1244                   Make_Op_Add (Loc,
1245                     Left_Opnd  => Size.Nod,
1246                     Right_Opnd => Make_Integer_Literal
1247                                     (Loc, Storage_Divisor - 1)),
1248                 Right_Opnd => Make_Integer_Literal (Loc, Storage_Divisor));
1249          end if;
1250
1251          --  If the array entity is not declared at the library level and its
1252          --  not nested within a subprogram that is marked for inlining, then
1253          --  we request that the size expression be encapsulated in a function.
1254          --  Since this expression is not needed in most cases, we prefer not
1255          --  to incur the overhead of the computation on calls to the enclosing
1256          --  subprogram except for subprograms that require the size.
1257
1258          if not Is_Library_Level_Entity (E) then
1259             Make_Size_Function := True;
1260
1261             declare
1262                Parent_Subp : Entity_Id := Enclosing_Subprogram (E);
1263
1264             begin
1265                while Present (Parent_Subp) loop
1266                   if Is_Inlined (Parent_Subp) then
1267                      Make_Size_Function := False;
1268                      exit;
1269                   end if;
1270
1271                   Parent_Subp := Enclosing_Subprogram (Parent_Subp);
1272                end loop;
1273             end;
1274          end if;
1275
1276          --  Now set the dynamic size (the Value_Size is always the same
1277          --  as the Object_Size for arrays whose length is dynamic).
1278
1279          --  ??? If Size.Status = Dynamic, Vtyp will not have been set.
1280          --  The added initialization sets it to Empty now, but is this
1281          --  correct?
1282
1283          Set_Esize
1284            (E,
1285             SO_Ref_From_Expr
1286               (Size.Nod, Insert_Typ, Vtyp, Make_Func => Make_Size_Function));
1287          Set_RM_Size (E, Esize (E));
1288       end if;
1289    end Layout_Array_Type;
1290
1291    -------------------
1292    -- Layout_Object --
1293    -------------------
1294
1295    procedure Layout_Object (E : Entity_Id) is
1296       T : constant Entity_Id := Etype (E);
1297
1298    begin
1299       --  Nothing to do if backend does layout
1300
1301       if not Frontend_Layout_On_Target then
1302          return;
1303       end if;
1304
1305       --  Set size if not set for object and known for type. Use the RM_Size if
1306       --  that is known for the type and Esize is not.
1307
1308       if Unknown_Esize (E) then
1309          if Known_Esize (T) then
1310             Set_Esize (E, Esize (T));
1311
1312          elsif Known_RM_Size (T) then
1313             Set_Esize (E, RM_Size (T));
1314          end if;
1315       end if;
1316
1317       --  Set alignment from type if unknown and type alignment known
1318
1319       if Unknown_Alignment (E) and then Known_Alignment (T) then
1320          Set_Alignment (E, Alignment (T));
1321       end if;
1322
1323       --  Make sure size and alignment are consistent
1324
1325       Adjust_Esize_Alignment (E);
1326
1327       --  Final adjustment, if we don't know the alignment, and the Esize was
1328       --  not set by an explicit Object_Size attribute clause, then we reset
1329       --  the Esize to unknown, since we really don't know it.
1330
1331       if Unknown_Alignment (E)
1332         and then not Has_Size_Clause (E)
1333       then
1334          Set_Esize (E, Uint_0);
1335       end if;
1336    end Layout_Object;
1337
1338    ------------------------
1339    -- Layout_Record_Type --
1340    ------------------------
1341
1342    procedure Layout_Record_Type (E : Entity_Id) is
1343       Loc  : constant Source_Ptr := Sloc (E);
1344       Decl : Node_Id;
1345
1346       Comp : Entity_Id;
1347       --  Current component being laid out
1348
1349       Prev_Comp : Entity_Id;
1350       --  Previous laid out component
1351
1352       procedure Get_Next_Component_Location
1353         (Prev_Comp  : Entity_Id;
1354          Align      : Uint;
1355          New_Npos   : out SO_Ref;
1356          New_Fbit   : out SO_Ref;
1357          New_NPMax  : out SO_Ref;
1358          Force_SU   : Boolean);
1359       --  Given the previous component in Prev_Comp, which is already laid
1360       --  out, and the alignment of the following component, lays out the
1361       --  following component, and returns its starting position in New_Npos
1362       --  (Normalized_Position value), New_Fbit (Normalized_First_Bit value),
1363       --  and New_NPMax (Normalized_Position_Max value). If Prev_Comp is empty
1364       --  (no previous component is present), then New_Npos, New_Fbit and
1365       --  New_NPMax are all set to zero on return. This procedure is also
1366       --  used to compute the size of a record or variant by giving it the
1367       --  last component, and the record alignment. Force_SU is used to force
1368       --  the new component location to be aligned on a storage unit boundary,
1369       --  even in a packed record, False means that the new position does not
1370       --  need to be bumped to a storage unit boundary, True means a storage
1371       --  unit boundary is always required.
1372
1373       procedure Layout_Component (Comp : Entity_Id; Prev_Comp : Entity_Id);
1374       --  Lays out component Comp, given Prev_Comp, the previously laid-out
1375       --  component (Prev_Comp = Empty if no components laid out yet). The
1376       --  alignment of the record itself is also updated if needed. Both
1377       --  Comp and Prev_Comp can be either components or discriminants.
1378
1379       procedure Layout_Components
1380         (From   : Entity_Id;
1381          To     : Entity_Id;
1382          Esiz   : out SO_Ref;
1383          RM_Siz : out SO_Ref);
1384       --  This procedure lays out the components of the given component list
1385       --  which contains the components starting with From and ending with To.
1386       --  The Next_Entity chain is used to traverse the components. On entry,
1387       --  Prev_Comp is set to the component preceding the list, so that the
1388       --  list is laid out after this component. Prev_Comp is set to Empty if
1389       --  the component list is to be laid out starting at the start of the
1390       --  record. On return, the components are all laid out, and Prev_Comp is
1391       --  set to the last laid out component. On return, Esiz is set to the
1392       --  resulting Object_Size value, which is the length of the record up
1393       --  to and including the last laid out entity. For Esiz, the value is
1394       --  adjusted to match the alignment of the record. RM_Siz is similarly
1395       --  set to the resulting Value_Size value, which is the same length, but
1396       --  not adjusted to meet the alignment. Note that in the case of variant
1397       --  records, Esiz represents the maximum size.
1398
1399       procedure Layout_Non_Variant_Record;
1400       --  Procedure called to lay out a non-variant record type or subtype
1401
1402       procedure Layout_Variant_Record;
1403       --  Procedure called to lay out a variant record type. Decl is set to the
1404       --  full type declaration for the variant record.
1405
1406       ---------------------------------
1407       -- Get_Next_Component_Location --
1408       ---------------------------------
1409
1410       procedure Get_Next_Component_Location
1411         (Prev_Comp  : Entity_Id;
1412          Align      : Uint;
1413          New_Npos   : out SO_Ref;
1414          New_Fbit   : out SO_Ref;
1415          New_NPMax  : out SO_Ref;
1416          Force_SU   : Boolean)
1417       is
1418       begin
1419          --  No previous component, return zero position
1420
1421          if No (Prev_Comp) then
1422             New_Npos  := Uint_0;
1423             New_Fbit  := Uint_0;
1424             New_NPMax := Uint_0;
1425             return;
1426          end if;
1427
1428          --  Here we have a previous component
1429
1430          declare
1431             Loc       : constant Source_Ptr := Sloc (Prev_Comp);
1432
1433             Old_Npos  : constant SO_Ref := Normalized_Position     (Prev_Comp);
1434             Old_Fbit  : constant SO_Ref := Normalized_First_Bit    (Prev_Comp);
1435             Old_NPMax : constant SO_Ref := Normalized_Position_Max (Prev_Comp);
1436             Old_Esiz  : constant SO_Ref := Esize                   (Prev_Comp);
1437
1438             Old_Maxsz : Node_Id;
1439             --  Expression representing maximum size of previous component
1440
1441          begin
1442             --  Case where previous field had a dynamic size
1443
1444             if Is_Dynamic_SO_Ref (Esize (Prev_Comp)) then
1445
1446                --  If the previous field had a dynamic length, then it is
1447                --  required to occupy an integral number of storage units,
1448                --  and start on a storage unit boundary. This means that
1449                --  the Normalized_First_Bit value is zero in the previous
1450                --  component, and the new value is also set to zero.
1451
1452                New_Fbit := Uint_0;
1453
1454                --  In this case, the new position is given by an expression
1455                --  that is the sum of old normalized position and old size.
1456
1457                New_Npos :=
1458                  SO_Ref_From_Expr
1459                    (Assoc_Add (Loc,
1460                       Left_Opnd  =>
1461                         Expr_From_SO_Ref (Loc, Old_Npos),
1462                       Right_Opnd =>
1463                         Expr_From_SO_Ref (Loc, Old_Esiz, Prev_Comp)),
1464                     Ins_Type => E,
1465                     Vtype    => E);
1466
1467                --  Get maximum size of previous component
1468
1469                if Size_Depends_On_Discriminant (Etype (Prev_Comp)) then
1470                   Old_Maxsz := Get_Max_SU_Size (Etype (Prev_Comp));
1471                else
1472                   Old_Maxsz := Expr_From_SO_Ref (Loc, Old_Esiz, Prev_Comp);
1473                end if;
1474
1475                --  Now we can compute the new max position. If the max size
1476                --  is static and the old position is static, then we can
1477                --  compute the new position statically.
1478
1479                if Nkind (Old_Maxsz) = N_Integer_Literal
1480                  and then Known_Static_Normalized_Position_Max (Prev_Comp)
1481                then
1482                   New_NPMax := Old_NPMax + Intval (Old_Maxsz);
1483
1484                --  Otherwise new max position is dynamic
1485
1486                else
1487                   New_NPMax :=
1488                     SO_Ref_From_Expr
1489                       (Assoc_Add (Loc,
1490                          Left_Opnd  => Expr_From_SO_Ref (Loc, Old_NPMax),
1491                          Right_Opnd => Old_Maxsz),
1492                        Ins_Type => E,
1493                        Vtype    => E);
1494                end if;
1495
1496             --  Previous field has known static Esize
1497
1498             else
1499                New_Fbit := Old_Fbit + Old_Esiz;
1500
1501                --  Bump New_Fbit to storage unit boundary if required
1502
1503                if New_Fbit /= 0 and then Force_SU then
1504                   New_Fbit := (New_Fbit + SSU - 1) / SSU * SSU;
1505                end if;
1506
1507                --  If old normalized position is static, we can go ahead and
1508                --  compute the new normalized position directly.
1509
1510                if Known_Static_Normalized_Position (Prev_Comp) then
1511                   New_Npos := Old_Npos;
1512
1513                   if New_Fbit >= SSU then
1514                      New_Npos := New_Npos + New_Fbit / SSU;
1515                      New_Fbit := New_Fbit mod SSU;
1516                   end if;
1517
1518                   --  Bump alignment if stricter than prev
1519
1520                   if Align > Alignment (Etype (Prev_Comp)) then
1521                      New_Npos := (New_Npos + Align - 1) / Align * Align;
1522                   end if;
1523
1524                   --  The max position is always equal to the position if
1525                   --  the latter is static, since arrays depending on the
1526                   --  values of discriminants never have static sizes.
1527
1528                   New_NPMax := New_Npos;
1529                   return;
1530
1531                --  Case of old normalized position is dynamic
1532
1533                else
1534                   --  If new bit position is within the current storage unit,
1535                   --  we can just copy the old position as the result position
1536                   --  (we have already set the new first bit value).
1537
1538                   if New_Fbit < SSU then
1539                      New_Npos  := Old_Npos;
1540                      New_NPMax := Old_NPMax;
1541
1542                   --  If new bit position is past the current storage unit, we
1543                   --  need to generate a new dynamic value for the position
1544                   --  ??? need to deal with alignment
1545
1546                   else
1547                      New_Npos :=
1548                        SO_Ref_From_Expr
1549                          (Assoc_Add (Loc,
1550                             Left_Opnd  => Expr_From_SO_Ref (Loc, Old_Npos),
1551                             Right_Opnd =>
1552                               Make_Integer_Literal (Loc,
1553                                 Intval => New_Fbit / SSU)),
1554                           Ins_Type => E,
1555                           Vtype    => E);
1556
1557                      New_NPMax :=
1558                        SO_Ref_From_Expr
1559                          (Assoc_Add (Loc,
1560                             Left_Opnd  => Expr_From_SO_Ref (Loc, Old_NPMax),
1561                             Right_Opnd =>
1562                               Make_Integer_Literal (Loc,
1563                                 Intval => New_Fbit / SSU)),
1564                             Ins_Type => E,
1565                             Vtype    => E);
1566                      New_Fbit := New_Fbit mod SSU;
1567                   end if;
1568                end if;
1569             end if;
1570          end;
1571       end Get_Next_Component_Location;
1572
1573       ----------------------
1574       -- Layout_Component --
1575       ----------------------
1576
1577       procedure Layout_Component (Comp : Entity_Id; Prev_Comp : Entity_Id) is
1578          Ctyp  : constant Entity_Id := Etype (Comp);
1579          ORC   : constant Entity_Id := Original_Record_Component (Comp);
1580          Npos  : SO_Ref;
1581          Fbit  : SO_Ref;
1582          NPMax : SO_Ref;
1583          Forc  : Boolean;
1584
1585       begin
1586          --  Increase alignment of record if necessary. Note that we do not
1587          --  do this for packed records, which have an alignment of one by
1588          --  default, or for records for which an explicit alignment was
1589          --  specified with an alignment clause.
1590
1591          if not Is_Packed (E)
1592            and then not Has_Alignment_Clause (E)
1593            and then Alignment (Ctyp) > Alignment (E)
1594          then
1595             Set_Alignment (E, Alignment (Ctyp));
1596          end if;
1597
1598          --  If original component set, then use same layout
1599
1600          if Present (ORC) and then ORC /= Comp then
1601             Set_Normalized_Position     (Comp, Normalized_Position     (ORC));
1602             Set_Normalized_First_Bit    (Comp, Normalized_First_Bit    (ORC));
1603             Set_Normalized_Position_Max (Comp, Normalized_Position_Max (ORC));
1604             Set_Component_Bit_Offset    (Comp, Component_Bit_Offset    (ORC));
1605             Set_Esize                   (Comp, Esize                   (ORC));
1606             return;
1607          end if;
1608
1609          --  Parent field is always at start of record, this will overlap
1610          --  the actual fields that are part of the parent, and that's fine
1611
1612          if Chars (Comp) = Name_uParent then
1613             Set_Normalized_Position     (Comp, Uint_0);
1614             Set_Normalized_First_Bit    (Comp, Uint_0);
1615             Set_Normalized_Position_Max (Comp, Uint_0);
1616             Set_Component_Bit_Offset    (Comp, Uint_0);
1617             Set_Esize                   (Comp, Esize (Ctyp));
1618             return;
1619          end if;
1620
1621          --  Check case of type of component has a scope of the record we are
1622          --  laying out. When this happens, the type in question is an Itype
1623          --  that has not yet been laid out (that's because such types do not
1624          --  get frozen in the normal manner, because there is no place for
1625          --  the freeze nodes).
1626
1627          if Scope (Ctyp) = E then
1628             Layout_Type (Ctyp);
1629          end if;
1630
1631          --  If component already laid out, then we are done
1632
1633          if Known_Normalized_Position (Comp) then
1634             return;
1635          end if;
1636
1637          --  Set size of component from type. We use the Esize except in a
1638          --  packed record, where we use the RM_Size (since that is what the
1639          --  RM_Size value, as distinct from the Object_Size is useful for!)
1640
1641          if Is_Packed (E) then
1642             Set_Esize (Comp, RM_Size (Ctyp));
1643          else
1644             Set_Esize (Comp, Esize (Ctyp));
1645          end if;
1646
1647          --  Compute the component position from the previous one. See if
1648          --  current component requires being on a storage unit boundary.
1649
1650          --  If record is not packed, we always go to a storage unit boundary
1651
1652          if not Is_Packed (E) then
1653             Forc := True;
1654
1655          --  Packed cases
1656
1657          else
1658             --  Elementary types do not need SU boundary in packed record
1659
1660             if Is_Elementary_Type (Ctyp) then
1661                Forc := False;
1662
1663             --  Packed array types with a modular packed array type do not
1664             --  force a storage unit boundary (since the code generation
1665             --  treats these as equivalent to the underlying modular type),
1666
1667             elsif Is_Array_Type (Ctyp)
1668               and then Is_Bit_Packed_Array (Ctyp)
1669               and then Is_Modular_Integer_Type (Packed_Array_Type (Ctyp))
1670             then
1671                Forc := False;
1672
1673             --  Record types with known length less than or equal to the length
1674             --  of long long integer can also be unaligned, since they can be
1675             --  treated as scalars.
1676
1677             elsif Is_Record_Type (Ctyp)
1678               and then not Is_Dynamic_SO_Ref (Esize (Ctyp))
1679               and then Esize (Ctyp) <= Esize (Standard_Long_Long_Integer)
1680             then
1681                Forc := False;
1682
1683             --  All other cases force a storage unit boundary, even when packed
1684
1685             else
1686                Forc := True;
1687             end if;
1688          end if;
1689
1690          --  Now get the next component location
1691
1692          Get_Next_Component_Location
1693            (Prev_Comp, Alignment (Ctyp), Npos, Fbit, NPMax, Forc);
1694          Set_Normalized_Position     (Comp, Npos);
1695          Set_Normalized_First_Bit    (Comp, Fbit);
1696          Set_Normalized_Position_Max (Comp, NPMax);
1697
1698          --  Set Component_Bit_Offset in the static case
1699
1700          if Known_Static_Normalized_Position (Comp)
1701            and then Known_Normalized_First_Bit (Comp)
1702          then
1703             Set_Component_Bit_Offset (Comp, SSU * Npos + Fbit);
1704          end if;
1705       end Layout_Component;
1706
1707       -----------------------
1708       -- Layout_Components --
1709       -----------------------
1710
1711       procedure Layout_Components
1712         (From   : Entity_Id;
1713          To     : Entity_Id;
1714          Esiz   : out SO_Ref;
1715          RM_Siz : out SO_Ref)
1716       is
1717          End_Npos  : SO_Ref;
1718          End_Fbit  : SO_Ref;
1719          End_NPMax : SO_Ref;
1720
1721       begin
1722          --  Only lay out components if there are some to lay out!
1723
1724          if Present (From) then
1725
1726             --  Lay out components with no component clauses
1727
1728             Comp := From;
1729             loop
1730                if Ekind (Comp) = E_Component
1731                  or else Ekind (Comp) = E_Discriminant
1732                then
1733                   --  The compatibility of component clauses with composite
1734                   --  types isn't checked in Sem_Ch13, so we check it here.
1735
1736                   if Present (Component_Clause (Comp)) then
1737                      if Is_Composite_Type (Etype (Comp))
1738                        and then Esize (Comp) < RM_Size (Etype (Comp))
1739                      then
1740                         Error_Msg_Uint_1 := RM_Size (Etype (Comp));
1741                         Error_Msg_NE
1742                           ("size for & too small, minimum allowed is ^",
1743                            Component_Clause (Comp),
1744                            Comp);
1745                      end if;
1746
1747                   else
1748                      Layout_Component (Comp, Prev_Comp);
1749                      Prev_Comp := Comp;
1750                   end if;
1751                end if;
1752
1753                exit when Comp = To;
1754                Next_Entity (Comp);
1755             end loop;
1756          end if;
1757
1758          --  Set size fields, both are zero if no components
1759
1760          if No (Prev_Comp) then
1761             Esiz := Uint_0;
1762             RM_Siz := Uint_0;
1763
1764             --  If record subtype with non-static discriminants, then we don't
1765             --  know which variant will be the one which gets chosen. We don't
1766             --  just want to set the maximum size from the base, because the
1767             --  size should depend on the particular variant.
1768
1769             --  What we do is to use the RM_Size of the base type, which has
1770             --  the necessary conditional computation of the size, using the
1771             --  size information for the particular variant chosen. Records
1772             --  with default discriminants for example have an Esize that is
1773             --  set to the maximum of all variants, but that's not what we
1774             --  want for a constrained subtype.
1775
1776          elsif Ekind (E) = E_Record_Subtype
1777            and then not Has_Static_Discriminants (E)
1778          then
1779             declare
1780                BT : constant Node_Id := Base_Type (E);
1781             begin
1782                Esiz   := RM_Size (BT);
1783                RM_Siz := RM_Size (BT);
1784                Set_Alignment (E, Alignment (BT));
1785             end;
1786
1787          else
1788             --  First the object size, for which we align past the last field
1789             --  to the alignment of the record (the object size is required to
1790             --  be a multiple of the alignment).
1791
1792             Get_Next_Component_Location
1793               (Prev_Comp,
1794                Alignment (E),
1795                End_Npos,
1796                End_Fbit,
1797                End_NPMax,
1798                Force_SU => True);
1799
1800             --  If the resulting normalized position is a dynamic reference,
1801             --  then the size is dynamic, and is stored in storage units. In
1802             --  this case, we set the RM_Size to the same value, it is simply
1803             --  not worth distinguishing Esize and RM_Size values in the
1804             --  dynamic case, since the RM has nothing to say about them.
1805
1806             --  Note that a size cannot have been given in this case, since
1807             --  size specifications cannot be given for variable length types.
1808
1809             declare
1810                Align : constant Uint := Alignment (E);
1811
1812             begin
1813                if Is_Dynamic_SO_Ref (End_Npos) then
1814                   RM_Siz := End_Npos;
1815
1816                   --  Set the Object_Size allowing for the alignment. In the
1817                   --  dynamic case, we must do the actual runtime computation.
1818                   --  We can skip this in the non-packed record case if the
1819                   --  last component has a smaller alignment than the overall
1820                   --  record alignment.
1821
1822                   if Is_Dynamic_SO_Ref (End_NPMax) then
1823                      Esiz := End_NPMax;
1824
1825                      if Is_Packed (E)
1826                        or else Alignment (Etype (Prev_Comp)) < Align
1827                      then
1828                         --  The expression we build is:
1829                         --    (expr + align - 1) / align * align
1830
1831                         Esiz :=
1832                           SO_Ref_From_Expr
1833                             (Expr =>
1834                                Make_Op_Multiply (Loc,
1835                                  Left_Opnd =>
1836                                    Make_Op_Divide (Loc,
1837                                      Left_Opnd =>
1838                                        Make_Op_Add (Loc,
1839                                          Left_Opnd =>
1840                                            Expr_From_SO_Ref (Loc, Esiz),
1841                                          Right_Opnd =>
1842                                            Make_Integer_Literal (Loc,
1843                                              Intval => Align - 1)),
1844                                      Right_Opnd =>
1845                                        Make_Integer_Literal (Loc, Align)),
1846                                  Right_Opnd =>
1847                                    Make_Integer_Literal (Loc, Align)),
1848                             Ins_Type => E,
1849                             Vtype    => E);
1850                      end if;
1851
1852                   --  Here Esiz is static, so we can adjust the alignment
1853                   --  directly go give the required aligned value.
1854
1855                   else
1856                      Esiz := (End_NPMax + Align - 1) / Align * Align * SSU;
1857                   end if;
1858
1859                --  Case where computed size is static
1860
1861                else
1862                   --  The ending size was computed in Npos in storage units,
1863                   --  but the actual size is stored in bits, so adjust
1864                   --  accordingly. We also adjust the size to match the
1865                   --  alignment here.
1866
1867                   Esiz := (End_NPMax + Align - 1) / Align * Align * SSU;
1868
1869                   --  Compute the resulting Value_Size (RM_Size). For this
1870                   --  purpose we do not force alignment of the record or
1871                   --  storage size alignment of the result.
1872
1873                   Get_Next_Component_Location
1874                     (Prev_Comp,
1875                      Uint_0,
1876                      End_Npos,
1877                      End_Fbit,
1878                      End_NPMax,
1879                      Force_SU => False);
1880
1881                   RM_Siz := End_Npos * SSU + End_Fbit;
1882                   Set_And_Check_Static_Size (E, Esiz, RM_Siz);
1883                end if;
1884             end;
1885          end if;
1886       end Layout_Components;
1887
1888       -------------------------------
1889       -- Layout_Non_Variant_Record --
1890       -------------------------------
1891
1892       procedure Layout_Non_Variant_Record is
1893          Esiz   : SO_Ref;
1894          RM_Siz : SO_Ref;
1895       begin
1896          Layout_Components (First_Entity (E), Last_Entity (E), Esiz, RM_Siz);
1897          Set_Esize   (E, Esiz);
1898          Set_RM_Size (E, RM_Siz);
1899       end Layout_Non_Variant_Record;
1900
1901       ---------------------------
1902       -- Layout_Variant_Record --
1903       ---------------------------
1904
1905       procedure Layout_Variant_Record is
1906          Tdef        : constant Node_Id := Type_Definition (Decl);
1907          First_Discr : Entity_Id;
1908          Last_Discr  : Entity_Id;
1909          Esiz        : SO_Ref;
1910
1911          RM_Siz : SO_Ref;
1912          pragma Warnings (Off, 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 values
1917          --  that are formed as references to the entity V. At the end of
1918          --  scanning all the components, a suitable function is constructed
1919          --  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 Esiz
1930          --  and RM_Siz_Expr are set to the Object_Size and Value_Size values
1931          --  respectively representing the record size up to and including the
1932          --  last component in the component list (including any variants in
1933          --  this component list). RM_Siz_Expr is returned as an expression
1934          --  which may in the general case involve some references to the
1935          --  discriminants of the current record value, referenced by selecting
1936          --  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 create
1984                   --  an appropriate function call using V as the parameter to
1985                   --  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 result
2082                      --  as the expression. Note that this takes care of the
2083                      --  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 be
2238          --  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 are
2245          --  components which have already been laid out by component clauses.
2246          --  If there are such components, we start our lay out of the
2247          --  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       Desig_Type : Entity_Id;
2302
2303    begin
2304       --  For string literal types, for now, kill the size always, this is
2305       --  because gigi does not like or need the size to be set ???
2306
2307       if Ekind (E) = E_String_Literal_Subtype then
2308          Set_Esize (E, Uint_0);
2309          Set_RM_Size (E, Uint_0);
2310          return;
2311       end if;
2312
2313       --  For access types, set size/alignment. This is system address size,
2314       --  except for fat pointers (unconstrained array access types), where the
2315       --  size is two times the address size, to accommodate the two pointers
2316       --  that are required for a fat pointer (data and template). Note that
2317       --  E_Access_Protected_Subprogram_Type is not an access type for this
2318       --  purpose since it is not a pointer but is equivalent to a record. For
2319       --  access subtypes, copy the size from the base type since Gigi
2320       --  represents them the same way.
2321
2322       if Is_Access_Type (E) then
2323
2324          Desig_Type :=  Underlying_Type (Designated_Type (E));
2325
2326          --  If we only have a limited view of the type, see whether the
2327          --  non-limited view is available.
2328
2329          if From_With_Type (Designated_Type (E))
2330            and then Ekind (Designated_Type (E)) = E_Incomplete_Type
2331            and then Present (Non_Limited_View (Designated_Type (E)))
2332          then
2333             Desig_Type := Non_Limited_View (Designated_Type (E));
2334          end if;
2335
2336          --  If Esize already set (e.g. by a size clause), then nothing further
2337          --  to be done here.
2338
2339          if Known_Esize (E) then
2340             null;
2341
2342          --  Access to subprogram is a strange beast, and we let the backend
2343          --  figure out what is needed (it may be some kind of fat pointer,
2344          --  including the static link for example.
2345
2346          elsif Is_Access_Protected_Subprogram_Type (E) then
2347             null;
2348
2349          --  For access subtypes, copy the size information from base type
2350
2351          elsif Ekind (E) = E_Access_Subtype then
2352             Set_Size_Info (E, Base_Type (E));
2353             Set_RM_Size   (E, RM_Size (Base_Type (E)));
2354
2355          --  For other access types, we use either address size, or, if a fat
2356          --  pointer is used (pointer-to-unconstrained array case), twice the
2357          --  address size to accommodate a fat pointer.
2358
2359          elsif Present (Desig_Type)
2360             and then Is_Array_Type (Desig_Type)
2361             and then not Is_Constrained (Desig_Type)
2362             and then not Has_Completion_In_Body (Desig_Type)
2363             and then not Debug_Flag_6
2364          then
2365             Init_Size (E, 2 * System_Address_Size);
2366
2367             --  Check for bad convention set
2368
2369             if Warn_On_Export_Import
2370               and then
2371                 (Convention (E) = Convention_C
2372                    or else
2373                  Convention (E) = Convention_CPP)
2374             then
2375                Error_Msg_N
2376                  ("?this access type does not correspond to C pointer", E);
2377             end if;
2378
2379          --  If the designated type is a limited view it is unanalyzed. We can
2380          --  examine the declaration itself to determine whether it will need a
2381          --  fat pointer.
2382
2383          elsif Present (Desig_Type)
2384             and then Present (Parent (Desig_Type))
2385             and then Nkind (Parent (Desig_Type)) = N_Full_Type_Declaration
2386             and then
2387               Nkind (Type_Definition (Parent (Desig_Type)))
2388                  = N_Unconstrained_Array_Definition
2389          then
2390             Init_Size (E, 2 * System_Address_Size);
2391
2392          --  When the target is AAMP, access-to-subprogram types are fat
2393          --  pointers consisting of the subprogram address and a static link
2394          --  (with the exception of library-level access types, where a simple
2395          --  subprogram address is used).
2396
2397          elsif AAMP_On_Target
2398            and then
2399              (Ekind (E) = E_Anonymous_Access_Subprogram_Type
2400                or else (Ekind (E) = E_Access_Subprogram_Type
2401                          and then Present (Enclosing_Subprogram (E))))
2402          then
2403             Init_Size (E, 2 * System_Address_Size);
2404
2405          else
2406             Init_Size (E, System_Address_Size);
2407          end if;
2408
2409          --  On VMS, reset size to 32 for convention C access type if no
2410          --  explicit size clause is given and the default size is 64. Really
2411          --  we do not know the size, since depending on options for the VMS
2412          --  compiler, the size of a pointer type can be 32 or 64, but choosing
2413          --  32 as the default improves compatibility with legacy VMS code.
2414
2415          --  Note: we do not use Has_Size_Clause in the test below, because we
2416          --  want to catch the case of a derived type inheriting a size clause.
2417          --  We want to consider this to be an explicit size clause for this
2418          --  purpose, since it would be weird not to inherit the size in this
2419          --  case.
2420
2421          --  We do NOT do this if we are in -gnatdm mode on a non-VMS target
2422          --  since in that case we want the normal pointer representation.
2423
2424          if Opt.True_VMS_Target
2425            and then (Convention (E) = Convention_C
2426                       or else
2427                      Convention (E) = Convention_CPP)
2428            and then No (Get_Attribute_Definition_Clause (E, Attribute_Size))
2429            and then Esize (E) = 64
2430          then
2431             Init_Size (E, 32);
2432          end if;
2433
2434          Set_Elem_Alignment (E);
2435
2436       --  Scalar types: set size and alignment
2437
2438       elsif Is_Scalar_Type (E) then
2439
2440          --  For discrete types, the RM_Size and Esize must be set already,
2441          --  since this is part of the earlier processing and the front end is
2442          --  always required to lay out the sizes of such types (since they are
2443          --  available as static attributes). All we do is to check that this
2444          --  rule is indeed obeyed!
2445
2446          if Is_Discrete_Type (E) then
2447
2448             --  If the RM_Size is not set, then here is where we set it
2449
2450             --  Note: an RM_Size of zero looks like not set here, but this
2451             --  is a rare case, and we can simply reset it without any harm.
2452
2453             if not Known_RM_Size (E) then
2454                Set_Discrete_RM_Size (E);
2455             end if;
2456
2457             --  If Esize for a discrete type is not set then set it
2458
2459             if not Known_Esize (E) then
2460                declare
2461                   S : Int := 8;
2462
2463                begin
2464                   loop
2465                      --  If size is big enough, set it and exit
2466
2467                      if S >= RM_Size (E) then
2468                         Init_Esize (E, S);
2469                         exit;
2470
2471                      --  If the RM_Size is greater than 64 (happens only when
2472                      --  strange values are specified by the user, then Esize
2473                      --  is simply a copy of RM_Size, it will be further
2474                      --  refined later on)
2475
2476                      elsif S = 64 then
2477                         Set_Esize (E, RM_Size (E));
2478                         exit;
2479
2480                      --  Otherwise double possible size and keep trying
2481
2482                      else
2483                         S := S * 2;
2484                      end if;
2485                   end loop;
2486                end;
2487             end if;
2488
2489          --  For non-discrete scalar types, if the RM_Size is not set, then set
2490          --  it now to a copy of the Esize if the Esize is set.
2491
2492          else
2493             if Known_Esize (E) and then Unknown_RM_Size (E) then
2494                Set_RM_Size (E, Esize (E));
2495             end if;
2496          end if;
2497
2498          Set_Elem_Alignment (E);
2499
2500       --  Non-elementary (composite) types
2501
2502       else
2503          --  If RM_Size is known, set Esize if not known
2504
2505          if Known_RM_Size (E) and then Unknown_Esize (E) then
2506
2507             --  If the alignment is known, we bump the Esize up to the next
2508             --  alignment boundary if it is not already on one.
2509
2510             if Known_Alignment (E) then
2511                declare
2512                   A : constant Uint   := Alignment_In_Bits (E);
2513                   S : constant SO_Ref := RM_Size (E);
2514                begin
2515                   Set_Esize (E, (S + A - 1) / A * A);
2516                end;
2517             end if;
2518
2519          --  If Esize is set, and RM_Size is not, RM_Size is copied from Esize.
2520          --  At least for now this seems reasonable, and is in any case needed
2521          --  for compatibility with old versions of gigi.
2522
2523          elsif Known_Esize (E) and then Unknown_RM_Size (E) then
2524             Set_RM_Size (E, Esize (E));
2525          end if;
2526
2527          --  For array base types, set component size if object size of the
2528          --  component type is known and is a small power of 2 (8, 16, 32, 64),
2529          --  since this is what will always be used.
2530
2531          if Ekind (E) = E_Array_Type
2532            and then Unknown_Component_Size (E)
2533          then
2534             declare
2535                CT : constant Entity_Id := Component_Type (E);
2536
2537             begin
2538                --  For some reasons, access types can cause trouble, So let's
2539                --  just do this for discrete types ???
2540
2541                if Present (CT)
2542                  and then Is_Discrete_Type (CT)
2543                  and then Known_Static_Esize (CT)
2544                then
2545                   declare
2546                      S : constant Uint := Esize (CT);
2547
2548                   begin
2549                      if S = 8  or else
2550                         S = 16 or else
2551                         S = 32 or else
2552                         S = 64
2553                      then
2554                         Set_Component_Size (E, Esize (CT));
2555                      end if;
2556                   end;
2557                end if;
2558             end;
2559          end if;
2560       end if;
2561
2562       --  Lay out array and record types if front end layout set
2563
2564       if Frontend_Layout_On_Target then
2565          if Is_Array_Type (E) and then not Is_Bit_Packed_Array (E) then
2566             Layout_Array_Type (E);
2567          elsif Is_Record_Type (E) then
2568             Layout_Record_Type (E);
2569          end if;
2570
2571       --  Case of backend layout, we still do a little in the front end
2572
2573       else
2574          --  Processing for record types
2575
2576          if Is_Record_Type (E) then
2577
2578             --  Special remaining processing for record types with a known
2579             --  size of 16, 32, or 64 bits whose alignment is not yet set.
2580             --  For these types, we set a corresponding alignment matching
2581             --  the size if possible, or as large as possible if not.
2582
2583             if Convention (E) = Convention_Ada
2584                and then not Debug_Flag_Q
2585             then
2586                Set_Composite_Alignment (E);
2587             end if;
2588
2589          --  Processing for array types
2590
2591          elsif Is_Array_Type (E) then
2592
2593             --  For arrays that are required to be atomic, we do the same
2594             --  processing as described above for short records, since we
2595             --  really need to have the alignment set for the whole array.
2596
2597             if Is_Atomic (E) and then not Debug_Flag_Q then
2598                Set_Composite_Alignment (E);
2599             end if;
2600
2601             --  For unpacked array types, set an alignment of 1 if we know
2602             --  that the component alignment is not greater than 1. The reason
2603             --  we do this is to avoid unnecessary copying of slices of such
2604             --  arrays when passed to subprogram parameters (see special test
2605             --  in Exp_Ch6.Expand_Actuals).
2606
2607             if not Is_Packed (E)
2608               and then Unknown_Alignment (E)
2609             then
2610                if Known_Static_Component_Size (E)
2611                  and then Component_Size (E) = 1
2612                then
2613                   Set_Alignment (E, Uint_1);
2614                end if;
2615             end if;
2616          end if;
2617       end if;
2618
2619       --  Final step is to check that Esize and RM_Size are compatible
2620
2621       if Known_Static_Esize (E) and then Known_Static_RM_Size (E) then
2622          if Esize (E) < RM_Size (E) then
2623
2624             --  Esize is less than RM_Size. That's not good. First we test
2625             --  whether this was set deliberately with an Object_Size clause
2626             --  and if so, object to the clause.
2627
2628             if Has_Object_Size_Clause (E) then
2629                Error_Msg_Uint_1 := RM_Size (E);
2630                Error_Msg_F
2631                  ("object size is too small, minimum allowed is ^",
2632                   Expression (Get_Attribute_Definition_Clause
2633                                              (E, Attribute_Object_Size)));
2634             end if;
2635
2636             --  Adjust Esize up to RM_Size value
2637
2638             declare
2639                Size : constant Uint := RM_Size (E);
2640
2641             begin
2642                Set_Esize (E, RM_Size (E));
2643
2644                --  For scalar types, increase Object_Size to power of 2, but
2645                --  not less than a storage unit in any case (i.e., normally
2646                --  this means it will be storage-unit addressable).
2647
2648                if Is_Scalar_Type (E) then
2649                   if Size <= System_Storage_Unit then
2650                      Init_Esize (E, System_Storage_Unit);
2651                   elsif Size <= 16 then
2652                      Init_Esize (E, 16);
2653                   elsif Size <= 32 then
2654                      Init_Esize (E, 32);
2655                   else
2656                      Set_Esize  (E, (Size + 63) / 64 * 64);
2657                   end if;
2658
2659                   --  Finally, make sure that alignment is consistent with
2660                   --  the newly assigned size.
2661
2662                   while Alignment (E) * System_Storage_Unit < Esize (E)
2663                     and then Alignment (E) < Maximum_Alignment
2664                   loop
2665                      Set_Alignment (E, 2 * Alignment (E));
2666                   end loop;
2667                end if;
2668             end;
2669          end if;
2670       end if;
2671    end Layout_Type;
2672
2673    ---------------------
2674    -- Rewrite_Integer --
2675    ---------------------
2676
2677    procedure Rewrite_Integer (N : Node_Id; V : Uint) is
2678       Loc : constant Source_Ptr := Sloc (N);
2679       Typ : constant Entity_Id  := Etype (N);
2680
2681    begin
2682       Rewrite (N, Make_Integer_Literal (Loc, Intval => V));
2683       Set_Etype (N, Typ);
2684    end Rewrite_Integer;
2685
2686    -------------------------------
2687    -- Set_And_Check_Static_Size --
2688    -------------------------------
2689
2690    procedure Set_And_Check_Static_Size
2691      (E      : Entity_Id;
2692       Esiz   : SO_Ref;
2693       RM_Siz : SO_Ref)
2694    is
2695       SC : Node_Id;
2696
2697       procedure Check_Size_Too_Small (Spec : Uint; Min : Uint);
2698       --  Spec is the number of bit specified in the size clause, and Min is
2699       --  the minimum computed size. An error is given that the specified size
2700       --  is too small if Spec < Min, and in this case both Esize and RM_Size
2701       --  are set to unknown in E. The error message is posted on node SC.
2702
2703       procedure Check_Unused_Bits (Spec : Uint; Max : Uint);
2704       --  Spec is the number of bits specified in the size clause, and Max is
2705       --  the maximum computed size. A warning is given about unused bits if
2706       --  Spec > Max. This warning is posted on node SC.
2707
2708       --------------------------
2709       -- Check_Size_Too_Small --
2710       --------------------------
2711
2712       procedure Check_Size_Too_Small (Spec : Uint; Min : Uint) is
2713       begin
2714          if Spec < Min then
2715             Error_Msg_Uint_1 := Min;
2716             Error_Msg_NE
2717               ("size for & too small, minimum allowed is ^", SC, E);
2718             Init_Esize   (E);
2719             Init_RM_Size (E);
2720          end if;
2721       end Check_Size_Too_Small;
2722
2723       -----------------------
2724       -- Check_Unused_Bits --
2725       -----------------------
2726
2727       procedure Check_Unused_Bits (Spec : Uint; Max : Uint) is
2728       begin
2729          if Spec > Max then
2730             Error_Msg_Uint_1 := Spec - Max;
2731             Error_Msg_NE ("?^ bits of & unused", SC, E);
2732          end if;
2733       end Check_Unused_Bits;
2734
2735    --  Start of processing for Set_And_Check_Static_Size
2736
2737    begin
2738       --  Case where Object_Size (Esize) is already set by a size clause
2739
2740       if Known_Static_Esize (E) then
2741          SC := Size_Clause (E);
2742
2743          if No (SC) then
2744             SC := Get_Attribute_Definition_Clause (E, Attribute_Object_Size);
2745          end if;
2746
2747          --  Perform checks on specified size against computed sizes
2748
2749          if Present (SC) then
2750             Check_Unused_Bits    (Esize (E), Esiz);
2751             Check_Size_Too_Small (Esize (E), RM_Siz);
2752          end if;
2753       end if;
2754
2755       --  Case where Value_Size (RM_Size) is set by specific Value_Size clause
2756       --  (we do not need to worry about Value_Size being set by a Size clause,
2757       --  since that will have set Esize as well, and we already took care of
2758       --  that case).
2759
2760       if Known_Static_RM_Size (E) then
2761          SC := Get_Attribute_Definition_Clause (E, Attribute_Value_Size);
2762
2763          --  Perform checks on specified size against computed sizes
2764
2765          if Present (SC) then
2766             Check_Unused_Bits    (RM_Size (E), Esiz);
2767             Check_Size_Too_Small (RM_Size (E), RM_Siz);
2768          end if;
2769       end if;
2770
2771       --  Set sizes if unknown
2772
2773       if Unknown_Esize (E) then
2774          Set_Esize (E, Esiz);
2775       end if;
2776
2777       if Unknown_RM_Size (E) then
2778          Set_RM_Size (E, RM_Siz);
2779       end if;
2780    end Set_And_Check_Static_Size;
2781
2782    -----------------------------
2783    -- Set_Composite_Alignment --
2784    -----------------------------
2785
2786    procedure Set_Composite_Alignment (E : Entity_Id) is
2787       Siz   : Uint;
2788       Align : Nat;
2789
2790    begin
2791       --  If alignment is already set, then nothing to do
2792
2793       if Known_Alignment (E) then
2794          return;
2795       end if;
2796
2797       --  Alignment is not known, see if we can set it, taking into account
2798       --  the setting of the Optimize_Alignment mode.
2799
2800       --  If Optimize_Alignment is set to Space, then packed records always
2801       --  have an alignment of 1. But don't do anything for atomic records
2802       --  since we may need higher alignment for indivisible access.
2803
2804       if Optimize_Alignment_Space (E)
2805         and then Is_Record_Type (E)
2806         and then Is_Packed (E)
2807         and then not Is_Atomic (E)
2808       then
2809          Align := 1;
2810
2811       --  Not a record, or not packed
2812
2813       else
2814          --  The only other cases we worry about here are where the size is
2815          --  statically known at compile time.
2816
2817          if Known_Static_Esize (E) then
2818             Siz := Esize (E);
2819
2820          elsif Unknown_Esize (E)
2821            and then Known_Static_RM_Size (E)
2822          then
2823             Siz := RM_Size (E);
2824
2825          else
2826             return;
2827          end if;
2828
2829          --  Size is known, alignment is not set
2830
2831          --  Reset alignment to match size if the known size is exactly 2, 4,
2832          --  or 8 storage units.
2833
2834          if Siz = 2 * System_Storage_Unit then
2835             Align := 2;
2836          elsif Siz = 4 * System_Storage_Unit then
2837             Align := 4;
2838          elsif Siz = 8 * System_Storage_Unit then
2839             Align := 8;
2840
2841             --  If Optimize_Alignment is set to Space, then make sure the
2842             --  alignment matches the size, for example, if the size is 17
2843             --  bytes then we want an alignment of 1 for the type.
2844
2845          elsif Optimize_Alignment_Space (E) then
2846             if Siz mod (8 * System_Storage_Unit) = 0 then
2847                Align := 8;
2848             elsif Siz mod (4 * System_Storage_Unit) = 0 then
2849                Align := 4;
2850             elsif Siz mod (2 * System_Storage_Unit) = 0 then
2851                Align := 2;
2852             else
2853                Align := 1;
2854             end if;
2855
2856             --  If Optimize_Alignment is set to Time, then we reset for odd
2857             --  "in between sizes", for example a 17 bit record is given an
2858             --  alignment of 4. Note that this matches the old VMS behavior
2859             --  in versions of GNAT prior to 6.1.1.
2860
2861          elsif Optimize_Alignment_Time (E)
2862            and then Siz > System_Storage_Unit
2863            and then Siz <= 8 * System_Storage_Unit
2864          then
2865             if Siz <= 2 * System_Storage_Unit then
2866                Align := 2;
2867             elsif Siz <= 4 * System_Storage_Unit then
2868                Align := 4;
2869             else -- Siz <= 8 * System_Storage_Unit then
2870                Align := 8;
2871             end if;
2872
2873             --  No special alignment fiddling needed
2874
2875          else
2876             return;
2877          end if;
2878       end if;
2879
2880       --  Here we have Set Align to the proposed improved value. Make sure the
2881       --  value set does not exceed Maximum_Alignment for the target.
2882
2883       if Align > Maximum_Alignment then
2884          Align := Maximum_Alignment;
2885       end if;
2886
2887       --  Further processing for record types only to reduce the alignment
2888       --  set by the above processing in some specific cases. We do not
2889       --  do this for atomic records, since we need max alignment there,
2890
2891       if Is_Record_Type (E) and then not Is_Atomic (E) then
2892
2893          --  For records, there is generally no point in setting alignment
2894          --  higher than word size since we cannot do better than move by
2895          --  words in any case. Omit this if we are optimizing for time,
2896          --  since conceivably we may be able to do better.
2897
2898          if Align > System_Word_Size / System_Storage_Unit
2899            and then not Optimize_Alignment_Time (E)
2900          then
2901             Align := System_Word_Size / System_Storage_Unit;
2902          end if;
2903
2904          --  Check components. If any component requires a higher alignment,
2905          --  then we set that higher alignment in any case. Don't do this if
2906          --  we have Optimize_Alignment set to Space. Note that that covers
2907          --  the case of packed records, where we already set alignment to 1.
2908
2909          if not Optimize_Alignment_Space (E) then
2910             declare
2911                Comp : Entity_Id;
2912
2913             begin
2914                Comp := First_Component (E);
2915                while Present (Comp) loop
2916                   if Known_Alignment (Etype (Comp)) then
2917                      declare
2918                         Calign : constant Uint := Alignment (Etype (Comp));
2919
2920                      begin
2921                         --  The cases to process are when the alignment of the
2922                         --  component type is larger than the alignment we have
2923                         --  so far, and either there is no component clause for
2924                         --  the component, or the length set by the component
2925                         --  clause matches the length of the component type.
2926
2927                         if Calign > Align
2928                           and then
2929                             (Unknown_Esize (Comp)
2930                               or else (Known_Static_Esize (Comp)
2931                                         and then
2932                                          Esize (Comp) =
2933                                               Calign * System_Storage_Unit))
2934                         then
2935                            Align := UI_To_Int (Calign);
2936                         end if;
2937                      end;
2938                   end if;
2939
2940                   Next_Component (Comp);
2941                end loop;
2942             end;
2943          end if;
2944       end if;
2945
2946       --  Set chosen alignment, and increase Esize if necessary to match the
2947       --  chosen alignment.
2948
2949       Set_Alignment (E, UI_From_Int (Align));
2950
2951       if Known_Static_Esize (E)
2952         and then Esize (E) < Align * System_Storage_Unit
2953       then
2954          Set_Esize (E, UI_From_Int (Align * System_Storage_Unit));
2955       end if;
2956    end Set_Composite_Alignment;
2957
2958    --------------------------
2959    -- Set_Discrete_RM_Size --
2960    --------------------------
2961
2962    procedure Set_Discrete_RM_Size (Def_Id : Entity_Id) is
2963       FST : constant Entity_Id := First_Subtype (Def_Id);
2964
2965    begin
2966       --  All discrete types except for the base types in standard are
2967       --  constrained, so indicate this by setting Is_Constrained.
2968
2969       Set_Is_Constrained (Def_Id);
2970
2971       --  Set generic types to have an unknown size, since the representation
2972       --  of a generic type is irrelevant, in view of the fact that they have
2973       --  nothing to do with code.
2974
2975       if Is_Generic_Type (Root_Type (FST)) then
2976          Set_RM_Size (Def_Id, Uint_0);
2977
2978       --  If the subtype statically matches the first subtype, then it is
2979       --  required to have exactly the same layout. This is required by
2980       --  aliasing considerations.
2981
2982       elsif Def_Id /= FST and then
2983         Subtypes_Statically_Match (Def_Id, FST)
2984       then
2985          Set_RM_Size   (Def_Id, RM_Size (FST));
2986          Set_Size_Info (Def_Id, FST);
2987
2988       --  In all other cases the RM_Size is set to the minimum size. Note that
2989       --  this routine is never called for subtypes for which the RM_Size is
2990       --  set explicitly by an attribute clause.
2991
2992       else
2993          Set_RM_Size (Def_Id, UI_From_Int (Minimum_Size (Def_Id)));
2994       end if;
2995    end Set_Discrete_RM_Size;
2996
2997    ------------------------
2998    -- Set_Elem_Alignment --
2999    ------------------------
3000
3001    procedure Set_Elem_Alignment (E : Entity_Id) is
3002    begin
3003       --  Do not set alignment for packed array types, unless we are doing
3004       --  front end layout, because otherwise this is always handled in the
3005       --  backend.
3006
3007       if Is_Packed_Array_Type (E) and then not Frontend_Layout_On_Target then
3008          return;
3009
3010       --  If there is an alignment clause, then we respect it
3011
3012       elsif Has_Alignment_Clause (E) then
3013          return;
3014
3015       --  If the size is not set, then don't attempt to set the alignment. This
3016       --  happens in the backend layout case for access-to-subprogram types.
3017
3018       elsif not Known_Static_Esize (E) then
3019          return;
3020
3021       --  For access types, do not set the alignment if the size is less than
3022       --  the allowed minimum size. This avoids cascaded error messages.
3023
3024       elsif Is_Access_Type (E)
3025         and then Esize (E) < System_Address_Size
3026       then
3027          return;
3028       end if;
3029
3030       --  Here we calculate the alignment as the largest power of two multiple
3031       --  of System.Storage_Unit that does not exceed either the actual size of
3032       --  the type, or the maximum allowed alignment.
3033
3034       declare
3035          S : constant Int :=
3036                UI_To_Int (Esize (E)) / SSU;
3037          A : Nat;
3038
3039       begin
3040          A := 1;
3041          while 2 * A <= Ttypes.Maximum_Alignment
3042             and then 2 * A <= S
3043          loop
3044             A := 2 * A;
3045          end loop;
3046
3047          --  Now we think we should set the alignment to A, but we skip this if
3048          --  an alignment is already set to a value greater than A (happens for
3049          --  derived types).
3050
3051          --  However, if the alignment is known and too small it must be
3052          --  increased, this happens in a case like:
3053
3054          --     type R is new Character;
3055          --     for R'Size use 16;
3056
3057          --  Here the alignment inherited from Character is 1, but it must be
3058          --  increased to 2 to reflect the increased size.
3059
3060          if Unknown_Alignment (E) or else Alignment (E) < A then
3061             Init_Alignment (E, A);
3062          end if;
3063       end;
3064    end Set_Elem_Alignment;
3065
3066    ----------------------
3067    -- SO_Ref_From_Expr --
3068    ----------------------
3069
3070    function SO_Ref_From_Expr
3071      (Expr      : Node_Id;
3072       Ins_Type  : Entity_Id;
3073       Vtype     : Entity_Id := Empty;
3074       Make_Func : Boolean   := False) return Dynamic_SO_Ref
3075    is
3076       Loc  : constant Source_Ptr := Sloc (Ins_Type);
3077
3078       K : constant Entity_Id :=
3079             Make_Defining_Identifier (Loc,
3080               Chars => New_Internal_Name ('K'));
3081
3082       Decl : Node_Id;
3083
3084       Vtype_Primary_View : Entity_Id;
3085
3086       function Check_Node_V_Ref (N : Node_Id) return Traverse_Result;
3087       --  Function used to check one node for reference to V
3088
3089       function Has_V_Ref is new Traverse_Func (Check_Node_V_Ref);
3090       --  Function used to traverse tree to check for reference to V
3091
3092       ----------------------
3093       -- Check_Node_V_Ref --
3094       ----------------------
3095
3096       function Check_Node_V_Ref (N : Node_Id) return Traverse_Result is
3097       begin
3098          if Nkind (N) = N_Identifier then
3099             if Chars (N) = Vname then
3100                return Abandon;
3101             else
3102                return Skip;
3103             end if;
3104
3105          else
3106             return OK;
3107          end if;
3108       end Check_Node_V_Ref;
3109
3110    --  Start of processing for SO_Ref_From_Expr
3111
3112    begin
3113       --  Case of expression is an integer literal, in this case we just
3114       --  return the value (which must always be non-negative, since size
3115       --  and offset values can never be negative).
3116
3117       if Nkind (Expr) = N_Integer_Literal then
3118          pragma Assert (Intval (Expr) >= 0);
3119          return Intval (Expr);
3120       end if;
3121
3122       --  Case where there is a reference to V, create function
3123
3124       if Has_V_Ref (Expr) = Abandon then
3125
3126          pragma Assert (Present (Vtype));
3127
3128          --  Check whether Vtype is a view of a private type and ensure that
3129          --  we use the primary view of the type (which is denoted by its
3130          --  Etype, whether it's the type's partial or full view entity).
3131          --  This is needed to make sure that we use the same (primary) view
3132          --  of the type for all V formals, whether the current view of the
3133          --  type is the partial or full view, so that types will always
3134          --  match on calls from one size function to another.
3135
3136          if  Has_Private_Declaration (Vtype) then
3137             Vtype_Primary_View := Etype (Vtype);
3138          else
3139             Vtype_Primary_View := Vtype;
3140          end if;
3141
3142          Set_Is_Discrim_SO_Function (K);
3143
3144          Decl :=
3145            Make_Subprogram_Body (Loc,
3146
3147              Specification =>
3148                Make_Function_Specification (Loc,
3149                  Defining_Unit_Name => K,
3150                    Parameter_Specifications => New_List (
3151                      Make_Parameter_Specification (Loc,
3152                        Defining_Identifier =>
3153                          Make_Defining_Identifier (Loc, Chars => Vname),
3154                        Parameter_Type      =>
3155                          New_Occurrence_Of (Vtype_Primary_View, Loc))),
3156                    Result_Definition =>
3157                      New_Occurrence_Of (Standard_Unsigned, Loc)),
3158
3159              Declarations => Empty_List,
3160
3161              Handled_Statement_Sequence =>
3162                Make_Handled_Sequence_Of_Statements (Loc,
3163                  Statements => New_List (
3164                    Make_Simple_Return_Statement (Loc,
3165                      Expression => Expr))));
3166
3167       --  The caller requests that the expression be encapsulated in a
3168       --  parameterless function.
3169
3170       elsif Make_Func then
3171          Decl :=
3172            Make_Subprogram_Body (Loc,
3173
3174              Specification =>
3175                Make_Function_Specification (Loc,
3176                  Defining_Unit_Name => K,
3177                    Parameter_Specifications => Empty_List,
3178                    Result_Definition =>
3179                      New_Occurrence_Of (Standard_Unsigned, Loc)),
3180
3181              Declarations => Empty_List,
3182
3183              Handled_Statement_Sequence =>
3184                Make_Handled_Sequence_Of_Statements (Loc,
3185                  Statements => New_List (
3186                    Make_Simple_Return_Statement (Loc, Expression => Expr))));
3187
3188       --  No reference to V and function not requested, so create a constant
3189
3190       else
3191          Decl :=
3192            Make_Object_Declaration (Loc,
3193              Defining_Identifier => K,
3194              Object_Definition   =>
3195                New_Occurrence_Of (Standard_Unsigned, Loc),
3196              Constant_Present    => True,
3197              Expression          => Expr);
3198       end if;
3199
3200       Append_Freeze_Action (Ins_Type, Decl);
3201       Analyze (Decl);
3202       return Create_Dynamic_SO_Ref (K);
3203    end SO_Ref_From_Expr;
3204
3205 end Layout;