[multiple changes]
[platform/upstream/gcc.git] / gcc / ada / freeze.adb
1 -----------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                               F R E E Z E                                --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2009, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.                                     --
17 --                                                                          --
18 -- You should have received a copy of the GNU General Public License along  --
19 -- with this program; see file COPYING3.  If not see                        --
20 -- <http://www.gnu.org/licenses/>.                                          --
21 --                                                                          --
22 -- GNAT was originally developed  by the GNAT team at  New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
24 --                                                                          --
25 ------------------------------------------------------------------------------
26
27 with Atree;    use Atree;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Elists;   use Elists;
31 with Errout;   use Errout;
32 with Exp_Ch3;  use Exp_Ch3;
33 with Exp_Ch7;  use Exp_Ch7;
34 with Exp_Disp; use Exp_Disp;
35 with Exp_Pakd; use Exp_Pakd;
36 with Exp_Util; use Exp_Util;
37 with Exp_Tss;  use Exp_Tss;
38 with Layout;   use Layout;
39 with Namet;    use Namet;
40 with Nlists;   use Nlists;
41 with Nmake;    use Nmake;
42 with Opt;      use Opt;
43 with Restrict; use Restrict;
44 with Rident;   use Rident;
45 with Sem;      use Sem;
46 with Sem_Aux;  use Sem_Aux;
47 with Sem_Cat;  use Sem_Cat;
48 with Sem_Ch6;  use Sem_Ch6;
49 with Sem_Ch7;  use Sem_Ch7;
50 with Sem_Ch8;  use Sem_Ch8;
51 with Sem_Ch13; use Sem_Ch13;
52 with Sem_Eval; use Sem_Eval;
53 with Sem_Mech; use Sem_Mech;
54 with Sem_Prag; use Sem_Prag;
55 with Sem_Res;  use Sem_Res;
56 with Sem_Util; use Sem_Util;
57 with Sinfo;    use Sinfo;
58 with Snames;   use Snames;
59 with Stand;    use Stand;
60 with Targparm; use Targparm;
61 with Tbuild;   use Tbuild;
62 with Ttypes;   use Ttypes;
63 with Uintp;    use Uintp;
64 with Urealp;   use Urealp;
65
66 package body Freeze is
67
68    -----------------------
69    -- Local Subprograms --
70    -----------------------
71
72    procedure Adjust_Esize_For_Alignment (Typ : Entity_Id);
73    --  Typ is a type that is being frozen. If no size clause is given,
74    --  but a default Esize has been computed, then this default Esize is
75    --  adjusted up if necessary to be consistent with a given alignment,
76    --  but never to a value greater than Long_Long_Integer'Size. This
77    --  is used for all discrete types and for fixed-point types.
78
79    procedure Build_And_Analyze_Renamed_Body
80      (Decl  : Node_Id;
81       New_S : Entity_Id;
82       After : in out Node_Id);
83    --  Build body for a renaming declaration, insert in tree and analyze
84
85    procedure Check_Address_Clause (E : Entity_Id);
86    --  Apply legality checks to address clauses for object declarations,
87    --  at the point the object is frozen.
88
89    procedure Check_Strict_Alignment (E : Entity_Id);
90    --  E is a base type. If E is tagged or has a component that is aliased
91    --  or tagged or contains something this is aliased or tagged, set
92    --  Strict_Alignment.
93
94    procedure Check_Unsigned_Type (E : Entity_Id);
95    pragma Inline (Check_Unsigned_Type);
96    --  If E is a fixed-point or discrete type, then all the necessary work
97    --  to freeze it is completed except for possible setting of the flag
98    --  Is_Unsigned_Type, which is done by this procedure. The call has no
99    --  effect if the entity E is not a discrete or fixed-point type.
100
101    procedure Freeze_And_Append
102      (Ent    : Entity_Id;
103       Loc    : Source_Ptr;
104       Result : in out List_Id);
105    --  Freezes Ent using Freeze_Entity, and appends the resulting list of
106    --  nodes to Result, modifying Result from No_List if necessary.
107
108    procedure Freeze_Enumeration_Type (Typ : Entity_Id);
109    --  Freeze enumeration type. The Esize field is set as processing
110    --  proceeds (i.e. set by default when the type is declared and then
111    --  adjusted by rep clauses. What this procedure does is to make sure
112    --  that if a foreign convention is specified, and no specific size
113    --  is given, then the size must be at least Integer'Size.
114
115    procedure Freeze_Static_Object (E : Entity_Id);
116    --  If an object is frozen which has Is_Statically_Allocated set, then
117    --  all referenced types must also be marked with this flag. This routine
118    --  is in charge of meeting this requirement for the object entity E.
119
120    procedure Freeze_Subprogram (E : Entity_Id);
121    --  Perform freezing actions for a subprogram (create extra formals,
122    --  and set proper default mechanism values). Note that this routine
123    --  is not called for internal subprograms, for which neither of these
124    --  actions is needed (or desirable, we do not want for example to have
125    --  these extra formals present in initialization procedures, where they
126    --  would serve no purpose). In this call E is either a subprogram or
127    --  a subprogram type (i.e. an access to a subprogram).
128
129    function Is_Fully_Defined (T : Entity_Id) return Boolean;
130    --  True if T is not private and has no private components, or has a full
131    --  view. Used to determine whether the designated type of an access type
132    --  should be frozen when the access type is frozen. This is done when an
133    --  allocator is frozen, or an expression that may involve attributes of
134    --  the designated type. Otherwise freezing the access type does not freeze
135    --  the designated type.
136
137    procedure Process_Default_Expressions
138      (E     : Entity_Id;
139       After : in out Node_Id);
140    --  This procedure is called for each subprogram to complete processing
141    --  of default expressions at the point where all types are known to be
142    --  frozen. The expressions must be analyzed in full, to make sure that
143    --  all error processing is done (they have only been pre-analyzed). If
144    --  the expression is not an entity or literal, its analysis may generate
145    --  code which must not be executed. In that case we build a function
146    --  body to hold that code. This wrapper function serves no other purpose
147    --  (it used to be called to evaluate the default, but now the default is
148    --  inlined at each point of call).
149
150    procedure Set_Component_Alignment_If_Not_Set (Typ : Entity_Id);
151    --  Typ is a record or array type that is being frozen. This routine
152    --  sets the default component alignment from the scope stack values
153    --  if the alignment is otherwise not specified.
154
155    procedure Check_Debug_Info_Needed (T : Entity_Id);
156    --  As each entity is frozen, this routine is called to deal with the
157    --  setting of Debug_Info_Needed for the entity. This flag is set if
158    --  the entity comes from source, or if we are in Debug_Generated_Code
159    --  mode or if the -gnatdV debug flag is set. However, it never sets
160    --  the flag if Debug_Info_Off is set. This procedure also ensures that
161    --  subsidiary entities have the flag set as required.
162
163    procedure Undelay_Type (T : Entity_Id);
164    --  T is a type of a component that we know to be an Itype.
165    --  We don't want this to have a Freeze_Node, so ensure it doesn't.
166    --  Do the same for any Full_View or Corresponding_Record_Type.
167
168    procedure Warn_Overlay
169      (Expr : Node_Id;
170       Typ  : Entity_Id;
171       Nam  : Node_Id);
172    --  Expr is the expression for an address clause for entity Nam whose type
173    --  is Typ. If Typ has a default initialization, and there is no explicit
174    --  initialization in the source declaration, check whether the address
175    --  clause might cause overlaying of an entity, and emit a warning on the
176    --  side effect that the initialization will cause.
177
178    -------------------------------
179    -- Adjust_Esize_For_Alignment --
180    -------------------------------
181
182    procedure Adjust_Esize_For_Alignment (Typ : Entity_Id) is
183       Align : Uint;
184
185    begin
186       if Known_Esize (Typ) and then Known_Alignment (Typ) then
187          Align := Alignment_In_Bits (Typ);
188
189          if Align > Esize (Typ)
190            and then Align <= Standard_Long_Long_Integer_Size
191          then
192             Set_Esize (Typ, Align);
193          end if;
194       end if;
195    end Adjust_Esize_For_Alignment;
196
197    ------------------------------------
198    -- Build_And_Analyze_Renamed_Body --
199    ------------------------------------
200
201    procedure Build_And_Analyze_Renamed_Body
202      (Decl  : Node_Id;
203       New_S : Entity_Id;
204       After : in out Node_Id)
205    is
206       Body_Node : constant Node_Id := Build_Renamed_Body (Decl, New_S);
207    begin
208       Insert_After (After, Body_Node);
209       Mark_Rewrite_Insertion (Body_Node);
210       Analyze (Body_Node);
211       After := Body_Node;
212    end Build_And_Analyze_Renamed_Body;
213
214    ------------------------
215    -- Build_Renamed_Body --
216    ------------------------
217
218    function Build_Renamed_Body
219      (Decl  : Node_Id;
220       New_S : Entity_Id) return Node_Id
221    is
222       Loc : constant Source_Ptr := Sloc (New_S);
223       --  We use for the source location of the renamed body, the location
224       --  of the spec entity. It might seem more natural to use the location
225       --  of the renaming declaration itself, but that would be wrong, since
226       --  then the body we create would look as though it was created far
227       --  too late, and this could cause problems with elaboration order
228       --  analysis, particularly in connection with instantiations.
229
230       N          : constant Node_Id := Unit_Declaration_Node (New_S);
231       Nam        : constant Node_Id := Name (N);
232       Old_S      : Entity_Id;
233       Spec       : constant Node_Id := New_Copy_Tree (Specification (Decl));
234       Actuals    : List_Id := No_List;
235       Call_Node  : Node_Id;
236       Call_Name  : Node_Id;
237       Body_Node  : Node_Id;
238       Formal     : Entity_Id;
239       O_Formal   : Entity_Id;
240       Param_Spec : Node_Id;
241
242       Pref : Node_Id := Empty;
243       --  If the renamed entity is a primitive operation given in prefix form,
244       --  the prefix is the target object and it has to be added as the first
245       --  actual in the generated call.
246
247    begin
248       --  Determine the entity being renamed, which is the target of the call
249       --  statement. If the name is an explicit dereference, this is a renaming
250       --  of a subprogram type rather than a subprogram. The name itself is
251       --  fully analyzed.
252
253       if Nkind (Nam) = N_Selected_Component then
254          Old_S := Entity (Selector_Name (Nam));
255
256       elsif Nkind (Nam) = N_Explicit_Dereference then
257          Old_S := Etype (Nam);
258
259       elsif Nkind (Nam) = N_Indexed_Component then
260          if Is_Entity_Name (Prefix (Nam)) then
261             Old_S := Entity (Prefix (Nam));
262          else
263             Old_S := Entity (Selector_Name (Prefix (Nam)));
264          end if;
265
266       elsif Nkind (Nam) = N_Character_Literal then
267          Old_S := Etype (New_S);
268
269       else
270          Old_S := Entity (Nam);
271       end if;
272
273       if Is_Entity_Name (Nam) then
274
275          --  If the renamed entity is a predefined operator, retain full name
276          --  to ensure its visibility.
277
278          if Ekind (Old_S) = E_Operator
279            and then Nkind (Nam) = N_Expanded_Name
280          then
281             Call_Name := New_Copy (Name (N));
282          else
283             Call_Name := New_Reference_To (Old_S, Loc);
284          end if;
285
286       else
287          if Nkind (Nam) = N_Selected_Component
288            and then Present (First_Formal (Old_S))
289            and then
290              (Is_Controlling_Formal (First_Formal (Old_S))
291                 or else Is_Class_Wide_Type (Etype (First_Formal (Old_S))))
292          then
293
294             --  Retrieve the target object, to be added as a first actual
295             --  in the call.
296
297             Call_Name := New_Occurrence_Of (Old_S, Loc);
298             Pref := Prefix (Nam);
299
300          else
301             Call_Name := New_Copy (Name (N));
302          end if;
303
304          --  The original name may have been overloaded, but
305          --  is fully resolved now.
306
307          Set_Is_Overloaded (Call_Name, False);
308       end if;
309
310       --  For simple renamings, subsequent calls can be expanded directly as
311       --  called to the renamed entity. The body must be generated in any case
312       --  for calls they may appear elsewhere.
313
314       if (Ekind (Old_S) = E_Function
315            or else Ekind (Old_S) = E_Procedure)
316         and then Nkind (Decl) = N_Subprogram_Declaration
317       then
318          Set_Body_To_Inline (Decl, Old_S);
319       end if;
320
321       --  The body generated for this renaming is an internal artifact, and
322       --  does not  constitute a freeze point for the called entity.
323
324       Set_Must_Not_Freeze (Call_Name);
325
326       Formal := First_Formal (Defining_Entity (Decl));
327
328       if Present (Pref) then
329          declare
330             Pref_Type : constant Entity_Id := Etype (Pref);
331             Form_Type : constant Entity_Id := Etype (First_Formal (Old_S));
332
333          begin
334
335             --  The controlling formal may be an access parameter, or the
336             --  actual may be an access value, so adjust accordingly.
337
338             if Is_Access_Type (Pref_Type)
339               and then not Is_Access_Type (Form_Type)
340             then
341                Actuals := New_List
342                  (Make_Explicit_Dereference (Loc, Relocate_Node (Pref)));
343
344             elsif Is_Access_Type (Form_Type)
345               and then not Is_Access_Type (Pref)
346             then
347                Actuals := New_List
348                  (Make_Attribute_Reference (Loc,
349                    Attribute_Name => Name_Access,
350                    Prefix => Relocate_Node (Pref)));
351             else
352                Actuals := New_List (Pref);
353             end if;
354          end;
355
356       elsif Present (Formal) then
357          Actuals := New_List;
358
359       else
360          Actuals := No_List;
361       end if;
362
363       if Present (Formal) then
364          while Present (Formal) loop
365             Append (New_Reference_To (Formal, Loc), Actuals);
366             Next_Formal (Formal);
367          end loop;
368       end if;
369
370       --  If the renamed entity is an entry, inherit its profile. For other
371       --  renamings as bodies, both profiles must be subtype conformant, so it
372       --  is not necessary to replace the profile given in the declaration.
373       --  However, default values that are aggregates are rewritten when
374       --  partially analyzed, so we recover the original aggregate to insure
375       --  that subsequent conformity checking works. Similarly, if the default
376       --  expression was constant-folded, recover the original expression.
377
378       Formal := First_Formal (Defining_Entity (Decl));
379
380       if Present (Formal) then
381          O_Formal := First_Formal (Old_S);
382          Param_Spec := First (Parameter_Specifications (Spec));
383
384          while Present (Formal) loop
385             if Is_Entry (Old_S) then
386
387                if Nkind (Parameter_Type (Param_Spec)) /=
388                                                     N_Access_Definition
389                then
390                   Set_Etype (Formal, Etype (O_Formal));
391                   Set_Entity (Parameter_Type (Param_Spec), Etype (O_Formal));
392                end if;
393
394             elsif Nkind (Default_Value (O_Formal)) = N_Aggregate
395               or else Nkind (Original_Node (Default_Value (O_Formal))) /=
396                                            Nkind (Default_Value (O_Formal))
397             then
398                Set_Expression (Param_Spec,
399                  New_Copy_Tree (Original_Node (Default_Value (O_Formal))));
400             end if;
401
402             Next_Formal (Formal);
403             Next_Formal (O_Formal);
404             Next (Param_Spec);
405          end loop;
406       end if;
407
408       --  If the renamed entity is a function, the generated body contains a
409       --  return statement. Otherwise, build a procedure call. If the entity is
410       --  an entry, subsequent analysis of the call will transform it into the
411       --  proper entry or protected operation call. If the renamed entity is
412       --  a character literal, return it directly.
413
414       if Ekind (Old_S) = E_Function
415         or else Ekind (Old_S) = E_Operator
416         or else (Ekind (Old_S) = E_Subprogram_Type
417                   and then Etype (Old_S) /= Standard_Void_Type)
418       then
419          Call_Node :=
420            Make_Simple_Return_Statement (Loc,
421               Expression =>
422                 Make_Function_Call (Loc,
423                   Name => Call_Name,
424                   Parameter_Associations => Actuals));
425
426       elsif Ekind (Old_S) = E_Enumeration_Literal then
427          Call_Node :=
428            Make_Simple_Return_Statement (Loc,
429               Expression => New_Occurrence_Of (Old_S, Loc));
430
431       elsif Nkind (Nam) = N_Character_Literal then
432          Call_Node :=
433            Make_Simple_Return_Statement (Loc,
434              Expression => Call_Name);
435
436       else
437          Call_Node :=
438            Make_Procedure_Call_Statement (Loc,
439              Name => Call_Name,
440              Parameter_Associations => Actuals);
441       end if;
442
443       --  Create entities for subprogram body and formals
444
445       Set_Defining_Unit_Name (Spec,
446         Make_Defining_Identifier (Loc, Chars => Chars (New_S)));
447
448       Param_Spec := First (Parameter_Specifications (Spec));
449
450       while Present (Param_Spec) loop
451          Set_Defining_Identifier (Param_Spec,
452            Make_Defining_Identifier (Loc,
453              Chars => Chars (Defining_Identifier (Param_Spec))));
454          Next (Param_Spec);
455       end loop;
456
457       Body_Node :=
458         Make_Subprogram_Body (Loc,
459           Specification => Spec,
460           Declarations => New_List,
461           Handled_Statement_Sequence =>
462             Make_Handled_Sequence_Of_Statements (Loc,
463               Statements => New_List (Call_Node)));
464
465       if Nkind (Decl) /= N_Subprogram_Declaration then
466          Rewrite (N,
467            Make_Subprogram_Declaration (Loc,
468              Specification => Specification (N)));
469       end if;
470
471       --  Link the body to the entity whose declaration it completes. If
472       --  the body is analyzed when the renamed entity is frozen, it may
473       --  be necessary to restore the proper scope (see package Exp_Ch13).
474
475       if Nkind (N) =  N_Subprogram_Renaming_Declaration
476         and then Present (Corresponding_Spec (N))
477       then
478          Set_Corresponding_Spec (Body_Node, Corresponding_Spec (N));
479       else
480          Set_Corresponding_Spec (Body_Node, New_S);
481       end if;
482
483       return Body_Node;
484    end Build_Renamed_Body;
485
486    --------------------------
487    -- Check_Address_Clause --
488    --------------------------
489
490    procedure Check_Address_Clause (E : Entity_Id) is
491       Addr : constant Node_Id   := Address_Clause (E);
492       Expr : Node_Id;
493       Decl : constant Node_Id   := Declaration_Node (E);
494       Typ  : constant Entity_Id := Etype (E);
495
496    begin
497       if Present (Addr) then
498          Expr := Expression (Addr);
499
500          --  If we have no initialization of any kind, then we don't need to
501          --  place any restrictions on the address clause, because the object
502          --  will be elaborated after the address clause is evaluated. This
503          --  happens if the declaration has no initial expression, or the type
504          --  has no implicit initialization, or the object is imported.
505
506          --  The same holds for all initialized scalar types and all access
507          --  types. Packed bit arrays of size up to 64 are represented using a
508          --  modular type with an initialization (to zero) and can be processed
509          --  like other initialized scalar types.
510
511          --  If the type is controlled, code to attach the object to a
512          --  finalization chain is generated at the point of declaration,
513          --  and therefore the elaboration of the object cannot be delayed:
514          --  the address expression must be a constant.
515
516          if (No (Expression (Decl))
517               and then not Needs_Finalization (Typ)
518               and then
519                 (not Has_Non_Null_Base_Init_Proc (Typ)
520                   or else Is_Imported (E)))
521
522            or else
523              (Present (Expression (Decl))
524                and then Is_Scalar_Type (Typ))
525
526            or else
527              Is_Access_Type (Typ)
528
529            or else
530              (Is_Bit_Packed_Array (Typ)
531                and then
532                  Is_Modular_Integer_Type (Packed_Array_Type (Typ)))
533          then
534             null;
535
536          --  Otherwise, we require the address clause to be constant because
537          --  the call to the initialization procedure (or the attach code) has
538          --  to happen at the point of the declaration.
539
540          else
541             Check_Constant_Address_Clause (Expr, E);
542             Set_Has_Delayed_Freeze (E, False);
543          end if;
544
545          if not Error_Posted (Expr)
546            and then not Needs_Finalization (Typ)
547          then
548             Warn_Overlay (Expr, Typ, Name (Addr));
549          end if;
550       end if;
551    end Check_Address_Clause;
552
553    -----------------------------
554    -- Check_Compile_Time_Size --
555    -----------------------------
556
557    procedure Check_Compile_Time_Size (T : Entity_Id) is
558
559       procedure Set_Small_Size (T : Entity_Id; S : Uint);
560       --  Sets the compile time known size (32 bits or less) in the Esize
561       --  field, of T checking for a size clause that was given which attempts
562       --  to give a smaller size.
563
564       function Size_Known (T : Entity_Id) return Boolean;
565       --  Recursive function that does all the work
566
567       function Static_Discriminated_Components (T : Entity_Id) return Boolean;
568       --  If T is a constrained subtype, its size is not known if any of its
569       --  discriminant constraints is not static and it is not a null record.
570       --  The test is conservative and doesn't check that the components are
571       --  in fact constrained by non-static discriminant values. Could be made
572       --  more precise ???
573
574       --------------------
575       -- Set_Small_Size --
576       --------------------
577
578       procedure Set_Small_Size (T : Entity_Id; S : Uint) is
579       begin
580          if S > 32 then
581             return;
582
583          elsif Has_Size_Clause (T) then
584             if RM_Size (T) < S then
585                Error_Msg_Uint_1 := S;
586                Error_Msg_NE
587                  ("size for & too small, minimum allowed is ^",
588                   Size_Clause (T), T);
589
590             elsif Unknown_Esize (T) then
591                Set_Esize (T, S);
592             end if;
593
594          --  Set sizes if not set already
595
596          else
597             if Unknown_Esize (T) then
598                Set_Esize (T, S);
599             end if;
600
601             if Unknown_RM_Size (T) then
602                Set_RM_Size (T, S);
603             end if;
604          end if;
605       end Set_Small_Size;
606
607       ----------------
608       -- Size_Known --
609       ----------------
610
611       function Size_Known (T : Entity_Id) return Boolean is
612          Index : Entity_Id;
613          Comp  : Entity_Id;
614          Ctyp  : Entity_Id;
615          Low   : Node_Id;
616          High  : Node_Id;
617
618       begin
619          if Size_Known_At_Compile_Time (T) then
620             return True;
621
622          --  Always True for scalar types. This is true even for generic formal
623          --  scalar types. We used to return False in the latter case, but the
624          --  size is known at compile time, even in the template, we just do
625          --  not know the exact size but that's not the point of this routine.
626
627          elsif Is_Scalar_Type (T)
628            or else Is_Task_Type (T)
629          then
630             return True;
631
632          --  Array types
633
634          elsif Is_Array_Type (T) then
635
636             --  String literals always have known size, and we can set it
637
638             if Ekind (T) = E_String_Literal_Subtype then
639                Set_Small_Size (T, Component_Size (T)
640                                * String_Literal_Length (T));
641                return True;
642
643             --  Unconstrained types never have known at compile time size
644
645             elsif not Is_Constrained (T) then
646                return False;
647
648             --  Don't do any recursion on type with error posted, since we may
649             --  have a malformed type that leads us into a loop.
650
651             elsif Error_Posted (T) then
652                return False;
653
654             --  Otherwise if component size unknown, then array size unknown
655
656             elsif not Size_Known (Component_Type (T)) then
657                return False;
658             end if;
659
660             --  Check for all indexes static, and also compute possible size
661             --  (in case it is less than 32 and may be packable).
662
663             declare
664                Esiz : Uint := Component_Size (T);
665                Dim  : Uint;
666
667             begin
668                Index := First_Index (T);
669                while Present (Index) loop
670                   if Nkind (Index) = N_Range then
671                      Get_Index_Bounds (Index, Low, High);
672
673                   elsif Error_Posted (Scalar_Range (Etype (Index))) then
674                      return False;
675
676                   else
677                      Low  := Type_Low_Bound (Etype (Index));
678                      High := Type_High_Bound (Etype (Index));
679                   end if;
680
681                   if not Compile_Time_Known_Value (Low)
682                     or else not Compile_Time_Known_Value (High)
683                     or else Etype (Index) = Any_Type
684                   then
685                      return False;
686
687                   else
688                      Dim := Expr_Value (High) - Expr_Value (Low) + 1;
689
690                      if Dim >= 0 then
691                         Esiz := Esiz * Dim;
692                      else
693                         Esiz := Uint_0;
694                      end if;
695                   end if;
696
697                   Next_Index (Index);
698                end loop;
699
700                Set_Small_Size (T, Esiz);
701                return True;
702             end;
703
704          --  Access types always have known at compile time sizes
705
706          elsif Is_Access_Type (T) then
707             return True;
708
709          --  For non-generic private types, go to underlying type if present
710
711          elsif Is_Private_Type (T)
712            and then not Is_Generic_Type (T)
713            and then Present (Underlying_Type (T))
714          then
715             --  Don't do any recursion on type with error posted, since we may
716             --  have a malformed type that leads us into a loop.
717
718             if Error_Posted (T) then
719                return False;
720             else
721                return Size_Known (Underlying_Type (T));
722             end if;
723
724          --  Record types
725
726          elsif Is_Record_Type (T) then
727
728             --  A class-wide type is never considered to have a known size
729
730             if Is_Class_Wide_Type (T) then
731                return False;
732
733             --  A subtype of a variant record must not have non-static
734             --  discriminanted components.
735
736             elsif T /= Base_Type (T)
737               and then not Static_Discriminated_Components (T)
738             then
739                return False;
740
741             --  Don't do any recursion on type with error posted, since we may
742             --  have a malformed type that leads us into a loop.
743
744             elsif Error_Posted (T) then
745                return False;
746             end if;
747
748             --  Now look at the components of the record
749
750             declare
751                --  The following two variables are used to keep track of the
752                --  size of packed records if we can tell the size of the packed
753                --  record in the front end. Packed_Size_Known is True if so far
754                --  we can figure out the size. It is initialized to True for a
755                --  packed record, unless the record has discriminants. The
756                --  reason we eliminate the discriminated case is that we don't
757                --  know the way the back end lays out discriminated packed
758                --  records. If Packed_Size_Known is True, then Packed_Size is
759                --  the size in bits so far.
760
761                Packed_Size_Known : Boolean :=
762                                      Is_Packed (T)
763                                        and then not Has_Discriminants (T);
764
765                Packed_Size : Uint := Uint_0;
766
767             begin
768                --  Test for variant part present
769
770                if Has_Discriminants (T)
771                  and then Present (Parent (T))
772                  and then Nkind (Parent (T)) = N_Full_Type_Declaration
773                  and then Nkind (Type_Definition (Parent (T))) =
774                             N_Record_Definition
775                  and then not Null_Present (Type_Definition (Parent (T)))
776                  and then Present (Variant_Part
777                             (Component_List (Type_Definition (Parent (T)))))
778                then
779                   --  If variant part is present, and type is unconstrained,
780                   --  then we must have defaulted discriminants, or a size
781                   --  clause must be present for the type, or else the size
782                   --  is definitely not known at compile time.
783
784                   if not Is_Constrained (T)
785                     and then
786                       No (Discriminant_Default_Value
787                            (First_Discriminant (T)))
788                     and then Unknown_Esize (T)
789                   then
790                      return False;
791                   end if;
792                end if;
793
794                --  Loop through components
795
796                Comp := First_Component_Or_Discriminant (T);
797                while Present (Comp) loop
798                   Ctyp := Etype (Comp);
799
800                   --  We do not know the packed size if there is a component
801                   --  clause present (we possibly could, but this would only
802                   --  help in the case of a record with partial rep clauses.
803                   --  That's because in the case of full rep clauses, the
804                   --  size gets figured out anyway by a different circuit).
805
806                   if Present (Component_Clause (Comp)) then
807                      Packed_Size_Known := False;
808                   end if;
809
810                   --  We need to identify a component that is an array where
811                   --  the index type is an enumeration type with non-standard
812                   --  representation, and some bound of the type depends on a
813                   --  discriminant.
814
815                   --  This is because gigi computes the size by doing a
816                   --  substitution of the appropriate discriminant value in
817                   --  the size expression for the base type, and gigi is not
818                   --  clever enough to evaluate the resulting expression (which
819                   --  involves a call to rep_to_pos) at compile time.
820
821                   --  It would be nice if gigi would either recognize that
822                   --  this expression can be computed at compile time, or
823                   --  alternatively figured out the size from the subtype
824                   --  directly, where all the information is at hand ???
825
826                   if Is_Array_Type (Etype (Comp))
827                     and then Present (Packed_Array_Type (Etype (Comp)))
828                   then
829                      declare
830                         Ocomp  : constant Entity_Id :=
831                                    Original_Record_Component (Comp);
832                         OCtyp  : constant Entity_Id := Etype (Ocomp);
833                         Ind    : Node_Id;
834                         Indtyp : Entity_Id;
835                         Lo, Hi : Node_Id;
836
837                      begin
838                         Ind := First_Index (OCtyp);
839                         while Present (Ind) loop
840                            Indtyp := Etype (Ind);
841
842                            if Is_Enumeration_Type (Indtyp)
843                              and then Has_Non_Standard_Rep (Indtyp)
844                            then
845                               Lo := Type_Low_Bound  (Indtyp);
846                               Hi := Type_High_Bound (Indtyp);
847
848                               if Is_Entity_Name (Lo)
849                                 and then Ekind (Entity (Lo)) = E_Discriminant
850                               then
851                                  return False;
852
853                               elsif Is_Entity_Name (Hi)
854                                 and then Ekind (Entity (Hi)) = E_Discriminant
855                               then
856                                  return False;
857                               end if;
858                            end if;
859
860                            Next_Index (Ind);
861                         end loop;
862                      end;
863                   end if;
864
865                   --  Clearly size of record is not known if the size of one of
866                   --  the components is not known.
867
868                   if not Size_Known (Ctyp) then
869                      return False;
870                   end if;
871
872                   --  Accumulate packed size if possible
873
874                   if Packed_Size_Known then
875
876                      --  We can only deal with elementary types, since for
877                      --  non-elementary components, alignment enters into the
878                      --  picture, and we don't know enough to handle proper
879                      --  alignment in this context. Packed arrays count as
880                      --  elementary if the representation is a modular type.
881
882                      if Is_Elementary_Type (Ctyp)
883                        or else (Is_Array_Type (Ctyp)
884                                 and then Present (Packed_Array_Type (Ctyp))
885                                 and then Is_Modular_Integer_Type
886                                            (Packed_Array_Type (Ctyp)))
887                      then
888                         --  If RM_Size is known and static, then we can
889                         --  keep accumulating the packed size.
890
891                         if Known_Static_RM_Size (Ctyp) then
892
893                            --  A little glitch, to be removed sometime ???
894                            --  gigi does not understand zero sizes yet.
895
896                            if RM_Size (Ctyp) = Uint_0 then
897                               Packed_Size_Known := False;
898
899                            --  Normal case where we can keep accumulating the
900                            --  packed array size.
901
902                            else
903                               Packed_Size := Packed_Size + RM_Size (Ctyp);
904                            end if;
905
906                         --  If we have a field whose RM_Size is not known then
907                         --  we can't figure out the packed size here.
908
909                         else
910                            Packed_Size_Known := False;
911                         end if;
912
913                      --  If we have a non-elementary type we can't figure out
914                      --  the packed array size (alignment issues).
915
916                      else
917                         Packed_Size_Known := False;
918                      end if;
919                   end if;
920
921                   Next_Component_Or_Discriminant (Comp);
922                end loop;
923
924                if Packed_Size_Known then
925                   Set_Small_Size (T, Packed_Size);
926                end if;
927
928                return True;
929             end;
930
931          --  All other cases, size not known at compile time
932
933          else
934             return False;
935          end if;
936       end Size_Known;
937
938       -------------------------------------
939       -- Static_Discriminated_Components --
940       -------------------------------------
941
942       function Static_Discriminated_Components
943         (T : Entity_Id) return Boolean
944       is
945          Constraint : Elmt_Id;
946
947       begin
948          if Has_Discriminants (T)
949            and then Present (Discriminant_Constraint (T))
950            and then Present (First_Component (T))
951          then
952             Constraint := First_Elmt (Discriminant_Constraint (T));
953             while Present (Constraint) loop
954                if not Compile_Time_Known_Value (Node (Constraint)) then
955                   return False;
956                end if;
957
958                Next_Elmt (Constraint);
959             end loop;
960          end if;
961
962          return True;
963       end Static_Discriminated_Components;
964
965    --  Start of processing for Check_Compile_Time_Size
966
967    begin
968       Set_Size_Known_At_Compile_Time (T, Size_Known (T));
969    end Check_Compile_Time_Size;
970
971    -----------------------------
972    -- Check_Debug_Info_Needed --
973    -----------------------------
974
975    procedure Check_Debug_Info_Needed (T : Entity_Id) is
976    begin
977       if Debug_Info_Off (T) then
978          return;
979
980       elsif Comes_From_Source (T)
981         or else Debug_Generated_Code
982         or else Debug_Flag_VV
983         or else Needs_Debug_Info (T)
984       then
985          Set_Debug_Info_Needed (T);
986       end if;
987    end Check_Debug_Info_Needed;
988
989    ----------------------------
990    -- Check_Strict_Alignment --
991    ----------------------------
992
993    procedure Check_Strict_Alignment (E : Entity_Id) is
994       Comp  : Entity_Id;
995
996    begin
997       if Is_Tagged_Type (E) or else Is_Concurrent_Type (E) then
998          Set_Strict_Alignment (E);
999
1000       elsif Is_Array_Type (E) then
1001          Set_Strict_Alignment (E, Strict_Alignment (Component_Type (E)));
1002
1003       elsif Is_Record_Type (E) then
1004          if Is_Limited_Record (E) then
1005             Set_Strict_Alignment (E);
1006             return;
1007          end if;
1008
1009          Comp := First_Component (E);
1010
1011          while Present (Comp) loop
1012             if not Is_Type (Comp)
1013               and then (Strict_Alignment (Etype (Comp))
1014                          or else Is_Aliased (Comp))
1015             then
1016                Set_Strict_Alignment (E);
1017                return;
1018             end if;
1019
1020             Next_Component (Comp);
1021          end loop;
1022       end if;
1023    end Check_Strict_Alignment;
1024
1025    -------------------------
1026    -- Check_Unsigned_Type --
1027    -------------------------
1028
1029    procedure Check_Unsigned_Type (E : Entity_Id) is
1030       Ancestor : Entity_Id;
1031       Lo_Bound : Node_Id;
1032       Btyp     : Entity_Id;
1033
1034    begin
1035       if not Is_Discrete_Or_Fixed_Point_Type (E) then
1036          return;
1037       end if;
1038
1039       --  Do not attempt to analyze case where range was in error
1040
1041       if Error_Posted (Scalar_Range (E)) then
1042          return;
1043       end if;
1044
1045       --  The situation that is non trivial is something like
1046
1047       --     subtype x1 is integer range -10 .. +10;
1048       --     subtype x2 is x1 range 0 .. V1;
1049       --     subtype x3 is x2 range V2 .. V3;
1050       --     subtype x4 is x3 range V4 .. V5;
1051
1052       --  where Vn are variables. Here the base type is signed, but we still
1053       --  know that x4 is unsigned because of the lower bound of x2.
1054
1055       --  The only way to deal with this is to look up the ancestor chain
1056
1057       Ancestor := E;
1058       loop
1059          if Ancestor = Any_Type or else Etype (Ancestor) = Any_Type then
1060             return;
1061          end if;
1062
1063          Lo_Bound := Type_Low_Bound (Ancestor);
1064
1065          if Compile_Time_Known_Value (Lo_Bound) then
1066
1067             if Expr_Rep_Value (Lo_Bound) >= 0 then
1068                Set_Is_Unsigned_Type (E, True);
1069             end if;
1070
1071             return;
1072
1073          else
1074             Ancestor := Ancestor_Subtype (Ancestor);
1075
1076             --  If no ancestor had a static lower bound, go to base type
1077
1078             if No (Ancestor) then
1079
1080                --  Note: the reason we still check for a compile time known
1081                --  value for the base type is that at least in the case of
1082                --  generic formals, we can have bounds that fail this test,
1083                --  and there may be other cases in error situations.
1084
1085                Btyp := Base_Type (E);
1086
1087                if Btyp = Any_Type or else Etype (Btyp) = Any_Type then
1088                   return;
1089                end if;
1090
1091                Lo_Bound := Type_Low_Bound (Base_Type (E));
1092
1093                if Compile_Time_Known_Value (Lo_Bound)
1094                  and then Expr_Rep_Value (Lo_Bound) >= 0
1095                then
1096                   Set_Is_Unsigned_Type (E, True);
1097                end if;
1098
1099                return;
1100             end if;
1101          end if;
1102       end loop;
1103    end Check_Unsigned_Type;
1104
1105    -----------------------------
1106    -- Expand_Atomic_Aggregate --
1107    -----------------------------
1108
1109    procedure Expand_Atomic_Aggregate (E : Entity_Id; Typ : Entity_Id) is
1110       Loc   : constant Source_Ptr := Sloc (E);
1111       New_N : Node_Id;
1112       Temp  : Entity_Id;
1113
1114    begin
1115       if (Nkind (Parent (E)) = N_Object_Declaration
1116             or else Nkind (Parent (E)) = N_Assignment_Statement)
1117         and then Comes_From_Source (Parent (E))
1118       then
1119          Temp :=
1120            Make_Defining_Identifier (Loc,
1121              New_Internal_Name ('T'));
1122
1123          New_N :=
1124            Make_Object_Declaration (Loc,
1125              Defining_Identifier => Temp,
1126              Object_Definition   => New_Occurrence_Of (Typ, Loc),
1127              Expression          => Relocate_Node (E));
1128          Insert_Before (Parent (E), New_N);
1129          Analyze (New_N);
1130
1131          Set_Expression (Parent (E), New_Occurrence_Of (Temp, Loc));
1132
1133       end if;
1134    end Expand_Atomic_Aggregate;
1135
1136    ----------------
1137    -- Freeze_All --
1138    ----------------
1139
1140    --  Note: the easy coding for this procedure would be to just build a
1141    --  single list of freeze nodes and then insert them and analyze them
1142    --  all at once. This won't work, because the analysis of earlier freeze
1143    --  nodes may recursively freeze types which would otherwise appear later
1144    --  on in the freeze list. So we must analyze and expand the freeze nodes
1145    --  as they are generated.
1146
1147    procedure Freeze_All (From : Entity_Id; After : in out Node_Id) is
1148       Loc   : constant Source_Ptr := Sloc (After);
1149       E     : Entity_Id;
1150       Decl  : Node_Id;
1151
1152       procedure Freeze_All_Ent (From : Entity_Id; After : in out Node_Id);
1153       --  This is the internal recursive routine that does freezing of entities
1154       --  (but NOT the analysis of default expressions, which should not be
1155       --  recursive, we don't want to analyze those till we are sure that ALL
1156       --  the types are frozen).
1157
1158       --------------------
1159       -- Freeze_All_Ent --
1160       --------------------
1161
1162       procedure Freeze_All_Ent
1163         (From  : Entity_Id;
1164          After : in out Node_Id)
1165       is
1166          E     : Entity_Id;
1167          Flist : List_Id;
1168          Lastn : Node_Id;
1169
1170          procedure Process_Flist;
1171          --  If freeze nodes are present, insert and analyze, and reset cursor
1172          --  for next insertion.
1173
1174          -------------------
1175          -- Process_Flist --
1176          -------------------
1177
1178          procedure Process_Flist is
1179          begin
1180             if Is_Non_Empty_List (Flist) then
1181                Lastn := Next (After);
1182                Insert_List_After_And_Analyze (After, Flist);
1183
1184                if Present (Lastn) then
1185                   After := Prev (Lastn);
1186                else
1187                   After := Last (List_Containing (After));
1188                end if;
1189             end if;
1190          end Process_Flist;
1191
1192       --  Start or processing for Freeze_All_Ent
1193
1194       begin
1195          E := From;
1196          while Present (E) loop
1197
1198             --  If the entity is an inner package which is not a package
1199             --  renaming, then its entities must be frozen at this point. Note
1200             --  that such entities do NOT get frozen at the end of the nested
1201             --  package itself (only library packages freeze).
1202
1203             --  Same is true for task declarations, where anonymous records
1204             --  created for entry parameters must be frozen.
1205
1206             if Ekind (E) = E_Package
1207               and then No (Renamed_Object (E))
1208               and then not Is_Child_Unit (E)
1209               and then not Is_Frozen (E)
1210             then
1211                Push_Scope (E);
1212                Install_Visible_Declarations (E);
1213                Install_Private_Declarations (E);
1214
1215                Freeze_All (First_Entity (E), After);
1216
1217                End_Package_Scope (E);
1218
1219             elsif Ekind (E) in Task_Kind
1220               and then
1221                 (Nkind (Parent (E)) = N_Task_Type_Declaration
1222                    or else
1223                  Nkind (Parent (E)) = N_Single_Task_Declaration)
1224             then
1225                Push_Scope (E);
1226                Freeze_All (First_Entity (E), After);
1227                End_Scope;
1228
1229             --  For a derived tagged type, we must ensure that all the
1230             --  primitive operations of the parent have been frozen, so that
1231             --  their addresses will be in the parent's dispatch table at the
1232             --  point it is inherited.
1233
1234             elsif Ekind (E) = E_Record_Type
1235               and then Is_Tagged_Type (E)
1236               and then Is_Tagged_Type (Etype (E))
1237               and then Is_Derived_Type (E)
1238             then
1239                declare
1240                   Prim_List : constant Elist_Id :=
1241                                Primitive_Operations (Etype (E));
1242
1243                   Prim : Elmt_Id;
1244                   Subp : Entity_Id;
1245
1246                begin
1247                   Prim  := First_Elmt (Prim_List);
1248
1249                   while Present (Prim) loop
1250                      Subp := Node (Prim);
1251
1252                      if Comes_From_Source (Subp)
1253                        and then not Is_Frozen (Subp)
1254                      then
1255                         Flist := Freeze_Entity (Subp, Loc);
1256                         Process_Flist;
1257                      end if;
1258
1259                      Next_Elmt (Prim);
1260                   end loop;
1261                end;
1262             end if;
1263
1264             if not Is_Frozen (E) then
1265                Flist := Freeze_Entity (E, Loc);
1266                Process_Flist;
1267             end if;
1268
1269             --  If an incomplete type is still not frozen, this may be a
1270             --  premature freezing because of a body declaration that follows.
1271             --  Indicate where the freezing took place.
1272
1273             --  If the freezing is caused by the end of the current declarative
1274             --  part, it is a Taft Amendment type, and there is no error.
1275
1276             if not Is_Frozen (E)
1277               and then Ekind (E) = E_Incomplete_Type
1278             then
1279                declare
1280                   Bod : constant Node_Id := Next (After);
1281
1282                begin
1283                   if (Nkind (Bod) = N_Subprogram_Body
1284                         or else Nkind (Bod) = N_Entry_Body
1285                         or else Nkind (Bod) = N_Package_Body
1286                         or else Nkind (Bod) = N_Protected_Body
1287                         or else Nkind (Bod) = N_Task_Body
1288                         or else Nkind (Bod) in N_Body_Stub)
1289                      and then
1290                        List_Containing (After) = List_Containing (Parent (E))
1291                   then
1292                      Error_Msg_Sloc := Sloc (Next (After));
1293                      Error_Msg_NE
1294                        ("type& is frozen# before its full declaration",
1295                          Parent (E), E);
1296                   end if;
1297                end;
1298             end if;
1299
1300             Next_Entity (E);
1301          end loop;
1302       end Freeze_All_Ent;
1303
1304    --  Start of processing for Freeze_All
1305
1306    begin
1307       Freeze_All_Ent (From, After);
1308
1309       --  Now that all types are frozen, we can deal with default expressions
1310       --  that require us to build a default expression functions. This is the
1311       --  point at which such functions are constructed (after all types that
1312       --  might be used in such expressions have been frozen).
1313
1314       --  We also add finalization chains to access types whose designated
1315       --  types are controlled. This is normally done when freezing the type,
1316       --  but this misses recursive type definitions where the later members
1317       --  of the recursion introduce controlled components.
1318
1319       --  Loop through entities
1320
1321       E := From;
1322       while Present (E) loop
1323          if Is_Subprogram (E) then
1324
1325             if not Default_Expressions_Processed (E) then
1326                Process_Default_Expressions (E, After);
1327             end if;
1328
1329             if not Has_Completion (E) then
1330                Decl := Unit_Declaration_Node (E);
1331
1332                if Nkind (Decl) = N_Subprogram_Renaming_Declaration then
1333                   Build_And_Analyze_Renamed_Body (Decl, E, After);
1334
1335                elsif Nkind (Decl) = N_Subprogram_Declaration
1336                  and then Present (Corresponding_Body (Decl))
1337                  and then
1338                    Nkind (Unit_Declaration_Node (Corresponding_Body (Decl)))
1339                                           = N_Subprogram_Renaming_Declaration
1340                then
1341                   Build_And_Analyze_Renamed_Body
1342                     (Decl, Corresponding_Body (Decl), After);
1343                end if;
1344             end if;
1345
1346          elsif Ekind (E) in Task_Kind
1347            and then
1348              (Nkind (Parent (E)) = N_Task_Type_Declaration
1349                 or else
1350               Nkind (Parent (E)) = N_Single_Task_Declaration)
1351          then
1352             declare
1353                Ent : Entity_Id;
1354             begin
1355                Ent := First_Entity (E);
1356
1357                while Present (Ent) loop
1358
1359                   if Is_Entry (Ent)
1360                     and then not Default_Expressions_Processed (Ent)
1361                   then
1362                      Process_Default_Expressions (Ent, After);
1363                   end if;
1364
1365                   Next_Entity (Ent);
1366                end loop;
1367             end;
1368
1369          elsif Is_Access_Type (E)
1370            and then Comes_From_Source (E)
1371            and then Ekind (Directly_Designated_Type (E)) = E_Incomplete_Type
1372            and then Needs_Finalization (Designated_Type (E))
1373            and then No (Associated_Final_Chain (E))
1374          then
1375             Build_Final_List (Parent (E), E);
1376          end if;
1377
1378          Next_Entity (E);
1379       end loop;
1380    end Freeze_All;
1381
1382    -----------------------
1383    -- Freeze_And_Append --
1384    -----------------------
1385
1386    procedure Freeze_And_Append
1387      (Ent    : Entity_Id;
1388       Loc    : Source_Ptr;
1389       Result : in out List_Id)
1390    is
1391       L : constant List_Id := Freeze_Entity (Ent, Loc);
1392    begin
1393       if Is_Non_Empty_List (L) then
1394          if Result = No_List then
1395             Result := L;
1396          else
1397             Append_List (L, Result);
1398          end if;
1399       end if;
1400    end Freeze_And_Append;
1401
1402    -------------------
1403    -- Freeze_Before --
1404    -------------------
1405
1406    procedure Freeze_Before (N : Node_Id; T : Entity_Id) is
1407       Freeze_Nodes : constant List_Id := Freeze_Entity (T, Sloc (N));
1408    begin
1409       if Is_Non_Empty_List (Freeze_Nodes) then
1410          Insert_Actions (N, Freeze_Nodes);
1411       end if;
1412    end Freeze_Before;
1413
1414    -------------------
1415    -- Freeze_Entity --
1416    -------------------
1417
1418    function Freeze_Entity (E : Entity_Id; Loc : Source_Ptr) return List_Id is
1419       Test_E : Entity_Id := E;
1420       Comp   : Entity_Id;
1421       F_Node : Node_Id;
1422       Result : List_Id;
1423       Indx   : Node_Id;
1424       Formal : Entity_Id;
1425       Atype  : Entity_Id;
1426
1427       Has_Default_Initialization : Boolean := False;
1428       --  This flag gets set to true for a variable with default initialization
1429
1430       procedure Check_Current_Instance (Comp_Decl : Node_Id);
1431       --  Check that an Access or Unchecked_Access attribute with a prefix
1432       --  which is the current instance type can only be applied when the type
1433       --  is limited.
1434
1435       function After_Last_Declaration return Boolean;
1436       --  If Loc is a freeze_entity that appears after the last declaration
1437       --  in the scope, inhibit error messages on late completion.
1438
1439       procedure Freeze_Record_Type (Rec : Entity_Id);
1440       --  Freeze each component, handle some representation clauses, and freeze
1441       --  primitive operations if this is a tagged type.
1442
1443       ----------------------------
1444       -- After_Last_Declaration --
1445       ----------------------------
1446
1447       function After_Last_Declaration return Boolean is
1448          Spec  : constant Node_Id := Parent (Current_Scope);
1449       begin
1450          if Nkind (Spec) = N_Package_Specification then
1451             if Present (Private_Declarations (Spec)) then
1452                return Loc >= Sloc (Last (Private_Declarations (Spec)));
1453             elsif Present (Visible_Declarations (Spec)) then
1454                return Loc >= Sloc (Last (Visible_Declarations (Spec)));
1455             else
1456                return False;
1457             end if;
1458          else
1459             return False;
1460          end if;
1461       end After_Last_Declaration;
1462
1463       ----------------------------
1464       -- Check_Current_Instance --
1465       ----------------------------
1466
1467       procedure Check_Current_Instance (Comp_Decl : Node_Id) is
1468
1469          Rec_Type : constant Entity_Id :=
1470                       Scope (Defining_Identifier (Comp_Decl));
1471
1472          Decl : constant Node_Id := Parent (Rec_Type);
1473
1474          function Process (N : Node_Id) return Traverse_Result;
1475          --  Process routine to apply check to given node
1476
1477          -------------
1478          -- Process --
1479          -------------
1480
1481          function Process (N : Node_Id) return Traverse_Result is
1482          begin
1483             case Nkind (N) is
1484                when N_Attribute_Reference =>
1485                   if (Attribute_Name (N) = Name_Access
1486                         or else
1487                       Attribute_Name (N) = Name_Unchecked_Access)
1488                     and then Is_Entity_Name (Prefix (N))
1489                     and then Is_Type (Entity (Prefix (N)))
1490                     and then Entity (Prefix (N)) = E
1491                   then
1492                      Error_Msg_N
1493                        ("current instance must be a limited type", Prefix (N));
1494                      return Abandon;
1495                   else
1496                      return OK;
1497                   end if;
1498
1499                when others => return OK;
1500             end case;
1501          end Process;
1502
1503          procedure Traverse is new Traverse_Proc (Process);
1504
1505       --  Start of processing for Check_Current_Instance
1506
1507       begin
1508          --  In Ada95, the (imprecise) rule is that the current instance of a
1509          --  limited type is aliased. In Ada2005, limitedness must be explicit:
1510          --  either a tagged type, or a limited record.
1511
1512          if Is_Limited_Type (Rec_Type)
1513            and then
1514              (Ada_Version < Ada_05
1515                or else Is_Tagged_Type (Rec_Type))
1516          then
1517             return;
1518
1519          elsif Nkind (Decl) = N_Full_Type_Declaration
1520            and then Limited_Present (Type_Definition (Decl))
1521          then
1522             return;
1523
1524          else
1525             Traverse (Comp_Decl);
1526          end if;
1527       end Check_Current_Instance;
1528
1529       ------------------------
1530       -- Freeze_Record_Type --
1531       ------------------------
1532
1533       procedure Freeze_Record_Type (Rec : Entity_Id) is
1534          Comp : Entity_Id;
1535          IR   : Node_Id;
1536          ADC  : Node_Id;
1537          Prev : Entity_Id;
1538
1539          Junk : Boolean;
1540          pragma Warnings (Off, Junk);
1541
1542          Unplaced_Component : Boolean := False;
1543          --  Set True if we find at least one component with no component
1544          --  clause (used to warn about useless Pack pragmas).
1545
1546          Placed_Component : Boolean := False;
1547          --  Set True if we find at least one component with a component
1548          --  clause (used to warn about useless Bit_Order pragmas).
1549
1550          function Check_Allocator (N : Node_Id) return Node_Id;
1551          --  If N is an allocator, possibly wrapped in one or more level of
1552          --  qualified expression(s), return the inner allocator node, else
1553          --  return Empty.
1554
1555          procedure Check_Itype (Typ : Entity_Id);
1556          --  If the component subtype is an access to a constrained subtype of
1557          --  an already frozen type, make the subtype frozen as well. It might
1558          --  otherwise be frozen in the wrong scope, and a freeze node on
1559          --  subtype has no effect. Similarly, if the component subtype is a
1560          --  regular (not protected) access to subprogram, set the anonymous
1561          --  subprogram type to frozen as well, to prevent an out-of-scope
1562          --  freeze node at some eventual point of call. Protected operations
1563          --  are handled elsewhere.
1564
1565          ---------------------
1566          -- Check_Allocator --
1567          ---------------------
1568
1569          function Check_Allocator (N : Node_Id) return Node_Id is
1570             Inner : Node_Id;
1571          begin
1572             Inner := N;
1573             loop
1574                if Nkind (Inner) = N_Allocator then
1575                   return Inner;
1576                elsif Nkind (Inner) = N_Qualified_Expression then
1577                   Inner := Expression (Inner);
1578                else
1579                   return Empty;
1580                end if;
1581             end loop;
1582          end Check_Allocator;
1583
1584          -----------------
1585          -- Check_Itype --
1586          -----------------
1587
1588          procedure Check_Itype (Typ : Entity_Id) is
1589             Desig : constant Entity_Id := Designated_Type (Typ);
1590
1591          begin
1592             if not Is_Frozen (Desig)
1593               and then Is_Frozen (Base_Type (Desig))
1594             then
1595                Set_Is_Frozen (Desig);
1596
1597                --  In addition, add an Itype_Reference to ensure that the
1598                --  access subtype is elaborated early enough. This cannot be
1599                --  done if the subtype may depend on discriminants.
1600
1601                if Ekind (Comp) = E_Component
1602                  and then Is_Itype (Etype (Comp))
1603                  and then not Has_Discriminants (Rec)
1604                then
1605                   IR := Make_Itype_Reference (Sloc (Comp));
1606                   Set_Itype (IR, Desig);
1607
1608                   if No (Result) then
1609                      Result := New_List (IR);
1610                   else
1611                      Append (IR, Result);
1612                   end if;
1613                end if;
1614
1615             elsif Ekind (Typ) = E_Anonymous_Access_Subprogram_Type
1616               and then Convention (Desig) /= Convention_Protected
1617             then
1618                Set_Is_Frozen (Desig);
1619             end if;
1620          end Check_Itype;
1621
1622       --  Start of processing for Freeze_Record_Type
1623
1624       begin
1625          --  If this is a subtype of a controlled type, declared without a
1626          --  constraint, the _controller may not appear in the component list
1627          --  if the parent was not frozen at the point of subtype declaration.
1628          --  Inherit the _controller component now.
1629
1630          if Rec /= Base_Type (Rec)
1631            and then Has_Controlled_Component (Rec)
1632          then
1633             if Nkind (Parent (Rec)) = N_Subtype_Declaration
1634               and then Is_Entity_Name (Subtype_Indication (Parent (Rec)))
1635             then
1636                Set_First_Entity (Rec, First_Entity (Base_Type (Rec)));
1637
1638             --  If this is an internal type without a declaration, as for
1639             --  record component, the base type may not yet be frozen, and its
1640             --  controller has not been created. Add an explicit freeze node
1641             --  for the itype, so it will be frozen after the base type. This
1642             --  freeze node is used to communicate with the expander, in order
1643             --  to create the controller for the enclosing record, and it is
1644             --  deleted afterwards (see exp_ch3). It must not be created when
1645             --  expansion is off, because it might appear in the wrong context
1646             --  for the back end.
1647
1648             elsif Is_Itype (Rec)
1649               and then Has_Delayed_Freeze (Base_Type (Rec))
1650               and then
1651                 Nkind (Associated_Node_For_Itype (Rec)) =
1652                                                      N_Component_Declaration
1653               and then Expander_Active
1654             then
1655                Ensure_Freeze_Node (Rec);
1656             end if;
1657          end if;
1658
1659          --  Freeze components and embedded subtypes
1660
1661          Comp := First_Entity (Rec);
1662          Prev := Empty;
1663          while Present (Comp) loop
1664
1665             --  First handle the (real) component case
1666
1667             if Ekind (Comp) = E_Component
1668               or else Ekind (Comp) = E_Discriminant
1669             then
1670                declare
1671                   CC : constant Node_Id := Component_Clause (Comp);
1672
1673                begin
1674                   --  Freezing a record type freezes the type of each of its
1675                   --  components. However, if the type of the component is
1676                   --  part of this record, we do not want or need a separate
1677                   --  Freeze_Node. Note that Is_Itype is wrong because that's
1678                   --  also set in private type cases. We also can't check for
1679                   --  the Scope being exactly Rec because of private types and
1680                   --  record extensions.
1681
1682                   if Is_Itype (Etype (Comp))
1683                     and then Is_Record_Type (Underlying_Type
1684                                              (Scope (Etype (Comp))))
1685                   then
1686                      Undelay_Type (Etype (Comp));
1687                   end if;
1688
1689                   Freeze_And_Append (Etype (Comp), Loc, Result);
1690
1691                   --  Check for error of component clause given for variable
1692                   --  sized type. We have to delay this test till this point,
1693                   --  since the component type has to be frozen for us to know
1694                   --  if it is variable length. We omit this test in a generic
1695                   --  context, it will be applied at instantiation time.
1696
1697                   if Present (CC) then
1698                      Placed_Component := True;
1699
1700                      if Inside_A_Generic then
1701                         null;
1702
1703                      elsif not
1704                        Size_Known_At_Compile_Time
1705                          (Underlying_Type (Etype (Comp)))
1706                      then
1707                         Error_Msg_N
1708                           ("component clause not allowed for variable " &
1709                            "length component", CC);
1710                      end if;
1711
1712                   else
1713                      Unplaced_Component := True;
1714                   end if;
1715
1716                   --  Case of component requires byte alignment
1717
1718                   if Must_Be_On_Byte_Boundary (Etype (Comp)) then
1719
1720                      --  Set the enclosing record to also require byte align
1721
1722                      Set_Must_Be_On_Byte_Boundary (Rec);
1723
1724                      --  Check for component clause that is inconsistent with
1725                      --  the required byte boundary alignment.
1726
1727                      if Present (CC)
1728                        and then Normalized_First_Bit (Comp) mod
1729                                   System_Storage_Unit /= 0
1730                      then
1731                         Error_Msg_N
1732                           ("component & must be byte aligned",
1733                            Component_Name (Component_Clause (Comp)));
1734                      end if;
1735                   end if;
1736
1737                   --  If component clause is present, then deal with the non-
1738                   --  default bit order case for Ada 95 mode. The required
1739                   --  processing for Ada 2005 mode is handled separately after
1740                   --  processing all components.
1741
1742                   --  We only do this processing for the base type, and in
1743                   --  fact that's important, since otherwise if there are
1744                   --  record subtypes, we could reverse the bits once for
1745                   --  each subtype, which would be incorrect.
1746
1747                   if Present (CC)
1748                     and then Reverse_Bit_Order (Rec)
1749                     and then Ekind (E) = E_Record_Type
1750                     and then Ada_Version <= Ada_95
1751                   then
1752                      declare
1753                         CFB : constant Uint    := Component_Bit_Offset (Comp);
1754                         CSZ : constant Uint    := Esize (Comp);
1755                         CLC : constant Node_Id := Component_Clause (Comp);
1756                         Pos : constant Node_Id := Position (CLC);
1757                         FB  : constant Node_Id := First_Bit (CLC);
1758
1759                         Storage_Unit_Offset : constant Uint :=
1760                                                 CFB / System_Storage_Unit;
1761
1762                         Start_Bit : constant Uint :=
1763                                       CFB mod System_Storage_Unit;
1764
1765                      begin
1766                         --  Cases where field goes over storage unit boundary
1767
1768                         if Start_Bit + CSZ > System_Storage_Unit then
1769
1770                            --  Allow multi-byte field but generate warning
1771
1772                            if Start_Bit mod System_Storage_Unit = 0
1773                              and then CSZ mod System_Storage_Unit = 0
1774                            then
1775                               Error_Msg_N
1776                                 ("multi-byte field specified with non-standard"
1777                                  & " Bit_Order?", CLC);
1778
1779                               if Bytes_Big_Endian then
1780                                  Error_Msg_N
1781                                    ("bytes are not reversed "
1782                                     & "(component is big-endian)?", CLC);
1783                               else
1784                                  Error_Msg_N
1785                                    ("bytes are not reversed "
1786                                     & "(component is little-endian)?", CLC);
1787                               end if;
1788
1789                            --  Do not allow non-contiguous field
1790
1791                            else
1792                               Error_Msg_N
1793                                 ("attempt to specify non-contiguous field "
1794                                  & "not permitted", CLC);
1795                               Error_Msg_N
1796                                 ("\caused by non-standard Bit_Order "
1797                                  & "specified", CLC);
1798                               Error_Msg_N
1799                                 ("\consider possibility of using "
1800                                  & "Ada 2005 mode here", CLC);
1801                            end if;
1802
1803                         --  Case where field fits in one storage unit
1804
1805                         else
1806                            --  Give warning if suspicious component clause
1807
1808                            if Intval (FB) >= System_Storage_Unit
1809                              and then Warn_On_Reverse_Bit_Order
1810                            then
1811                               Error_Msg_N
1812                                 ("?Bit_Order clause does not affect " &
1813                                  "byte ordering", Pos);
1814                               Error_Msg_Uint_1 :=
1815                                 Intval (Pos) + Intval (FB) /
1816                                   System_Storage_Unit;
1817                               Error_Msg_N
1818                                 ("?position normalized to ^ before bit " &
1819                                  "order interpreted", Pos);
1820                            end if;
1821
1822                            --  Here is where we fix up the Component_Bit_Offset
1823                            --  value to account for the reverse bit order.
1824                            --  Some examples of what needs to be done are:
1825
1826                            --    First_Bit .. Last_Bit     Component_Bit_Offset
1827                            --      old          new          old       new
1828
1829                            --     0 .. 0       7 .. 7         0         7
1830                            --     0 .. 1       6 .. 7         0         6
1831                            --     0 .. 2       5 .. 7         0         5
1832                            --     0 .. 7       0 .. 7         0         4
1833
1834                            --     1 .. 1       6 .. 6         1         6
1835                            --     1 .. 4       3 .. 6         1         3
1836                            --     4 .. 7       0 .. 3         4         0
1837
1838                            --  The general rule is that the first bit is
1839                            --  is obtained by subtracting the old ending bit
1840                            --  from storage_unit - 1.
1841
1842                            Set_Component_Bit_Offset
1843                              (Comp,
1844                               (Storage_Unit_Offset * System_Storage_Unit) +
1845                                 (System_Storage_Unit - 1) -
1846                                   (Start_Bit + CSZ - 1));
1847
1848                            Set_Normalized_First_Bit
1849                              (Comp,
1850                                 Component_Bit_Offset (Comp) mod
1851                                   System_Storage_Unit);
1852                         end if;
1853                      end;
1854                   end if;
1855                end;
1856             end if;
1857
1858             --  If the component is an Itype with Delayed_Freeze and is either
1859             --  a record or array subtype and its base type has not yet been
1860             --  frozen, we must remove this from the entity list of this
1861             --  record and put it on the entity list of the scope of its base
1862             --  type. Note that we know that this is not the type of a
1863             --  component since we cleared Has_Delayed_Freeze for it in the
1864             --  previous loop. Thus this must be the Designated_Type of an
1865             --  access type, which is the type of a component.
1866
1867             if Is_Itype (Comp)
1868               and then Is_Type (Scope (Comp))
1869               and then Is_Composite_Type (Comp)
1870               and then Base_Type (Comp) /= Comp
1871               and then Has_Delayed_Freeze (Comp)
1872               and then not Is_Frozen (Base_Type (Comp))
1873             then
1874                declare
1875                   Will_Be_Frozen : Boolean := False;
1876                   S              : Entity_Id;
1877
1878                begin
1879                   --  We have a pretty bad kludge here. Suppose Rec is subtype
1880                   --  being defined in a subprogram that's created as part of
1881                   --  the freezing of Rec'Base. In that case, we know that
1882                   --  Comp'Base must have already been frozen by the time we
1883                   --  get to elaborate this because Gigi doesn't elaborate any
1884                   --  bodies until it has elaborated all of the declarative
1885                   --  part. But Is_Frozen will not be set at this point because
1886                   --  we are processing code in lexical order.
1887
1888                   --  We detect this case by going up the Scope chain of Rec
1889                   --  and seeing if we have a subprogram scope before reaching
1890                   --  the top of the scope chain or that of Comp'Base. If we
1891                   --  do, then mark that Comp'Base will actually be frozen. If
1892                   --  so, we merely undelay it.
1893
1894                   S := Scope (Rec);
1895                   while Present (S) loop
1896                      if Is_Subprogram (S) then
1897                         Will_Be_Frozen := True;
1898                         exit;
1899                      elsif S = Scope (Base_Type (Comp)) then
1900                         exit;
1901                      end if;
1902
1903                      S := Scope (S);
1904                   end loop;
1905
1906                   if Will_Be_Frozen then
1907                      Undelay_Type (Comp);
1908                   else
1909                      if Present (Prev) then
1910                         Set_Next_Entity (Prev, Next_Entity (Comp));
1911                      else
1912                         Set_First_Entity (Rec, Next_Entity (Comp));
1913                      end if;
1914
1915                      --  Insert in entity list of scope of base type (which
1916                      --  must be an enclosing scope, because still unfrozen).
1917
1918                      Append_Entity (Comp, Scope (Base_Type (Comp)));
1919                   end if;
1920                end;
1921
1922             --  If the component is an access type with an allocator as default
1923             --  value, the designated type will be frozen by the corresponding
1924             --  expression in init_proc. In order to place the freeze node for
1925             --  the designated type before that for the current record type,
1926             --  freeze it now.
1927
1928             --  Same process if the component is an array of access types,
1929             --  initialized with an aggregate. If the designated type is
1930             --  private, it cannot contain allocators, and it is premature
1931             --  to freeze the type, so we check for this as well.
1932
1933             elsif Is_Access_Type (Etype (Comp))
1934               and then Present (Parent (Comp))
1935               and then Present (Expression (Parent (Comp)))
1936             then
1937                declare
1938                   Alloc : constant Node_Id :=
1939                             Check_Allocator (Expression (Parent (Comp)));
1940
1941                begin
1942                   if Present (Alloc) then
1943
1944                      --  If component is pointer to a classwide type, freeze
1945                      --  the specific type in the expression being allocated.
1946                      --  The expression may be a subtype indication, in which
1947                      --  case freeze the subtype mark.
1948
1949                      if Is_Class_Wide_Type
1950                           (Designated_Type (Etype (Comp)))
1951                      then
1952                         if Is_Entity_Name (Expression (Alloc)) then
1953                            Freeze_And_Append
1954                              (Entity (Expression (Alloc)), Loc, Result);
1955                         elsif
1956                           Nkind (Expression (Alloc)) = N_Subtype_Indication
1957                         then
1958                            Freeze_And_Append
1959                             (Entity (Subtype_Mark (Expression (Alloc))),
1960                               Loc, Result);
1961                         end if;
1962
1963                      elsif Is_Itype (Designated_Type (Etype (Comp))) then
1964                         Check_Itype (Etype (Comp));
1965
1966                      else
1967                         Freeze_And_Append
1968                           (Designated_Type (Etype (Comp)), Loc, Result);
1969                      end if;
1970                   end if;
1971                end;
1972
1973             elsif Is_Access_Type (Etype (Comp))
1974               and then Is_Itype (Designated_Type (Etype (Comp)))
1975             then
1976                Check_Itype (Etype (Comp));
1977
1978             elsif Is_Array_Type (Etype (Comp))
1979               and then Is_Access_Type (Component_Type (Etype (Comp)))
1980               and then Present (Parent (Comp))
1981               and then Nkind (Parent (Comp)) = N_Component_Declaration
1982               and then Present (Expression (Parent (Comp)))
1983               and then Nkind (Expression (Parent (Comp))) = N_Aggregate
1984               and then Is_Fully_Defined
1985                  (Designated_Type (Component_Type (Etype (Comp))))
1986             then
1987                Freeze_And_Append
1988                  (Designated_Type
1989                    (Component_Type (Etype (Comp))), Loc, Result);
1990             end if;
1991
1992             Prev := Comp;
1993             Next_Entity (Comp);
1994          end loop;
1995
1996          --  Deal with pragma Bit_Order
1997
1998          if Reverse_Bit_Order (Rec) and then Base_Type (Rec) = Rec then
1999             if not Placed_Component then
2000                ADC :=
2001                  Get_Attribute_Definition_Clause (Rec, Attribute_Bit_Order);
2002                Error_Msg_N
2003                  ("?Bit_Order specification has no effect", ADC);
2004                Error_Msg_N
2005                  ("\?since no component clauses were specified", ADC);
2006
2007             --  Here is where we do Ada 2005 processing for bit order (the Ada
2008             --  95 case was already taken care of above).
2009
2010             elsif Ada_Version >= Ada_05 then
2011                Adjust_Record_For_Reverse_Bit_Order (Rec);
2012             end if;
2013          end if;
2014
2015          --  Set OK_To_Reorder_Components depending on debug flags
2016
2017          if Rec = Base_Type (Rec)
2018            and then Convention (Rec) = Convention_Ada
2019          then
2020             if (Has_Discriminants (Rec) and then Debug_Flag_Dot_V)
2021                   or else
2022                (not Has_Discriminants (Rec) and then Debug_Flag_Dot_R)
2023             then
2024                Set_OK_To_Reorder_Components (Rec);
2025             end if;
2026          end if;
2027
2028          --  Check for useless pragma Pack when all components placed. We only
2029          --  do this check for record types, not subtypes, since a subtype may
2030          --  have all its components placed, and it still makes perfectly good
2031          --  sense to pack other subtypes or the parent type. We do not give
2032          --  this warning if Optimize_Alignment is set to Space, since the
2033          --  pragma Pack does have an effect in this case (it always resets
2034          --  the alignment to one).
2035
2036          if Ekind (Rec) = E_Record_Type
2037            and then Is_Packed (Rec)
2038            and then not Unplaced_Component
2039            and then Optimize_Alignment /= 'S'
2040          then
2041             --  Reset packed status. Probably not necessary, but we do it so
2042             --  that there is no chance of the back end doing something strange
2043             --  with this redundant indication of packing.
2044
2045             Set_Is_Packed (Rec, False);
2046
2047             --  Give warning if redundant constructs warnings on
2048
2049             if Warn_On_Redundant_Constructs then
2050                Error_Msg_N
2051                  ("?pragma Pack has no effect, no unplaced components",
2052                   Get_Rep_Pragma (Rec, Name_Pack));
2053             end if;
2054          end if;
2055
2056          --  If this is the record corresponding to a remote type, freeze the
2057          --  remote type here since that is what we are semantically freezing.
2058          --  This prevents the freeze node for that type in an inner scope.
2059
2060          --  Also, Check for controlled components and unchecked unions.
2061          --  Finally, enforce the restriction that access attributes with a
2062          --  current instance prefix can only apply to limited types.
2063
2064          if  Ekind (Rec) = E_Record_Type then
2065             if Present (Corresponding_Remote_Type (Rec)) then
2066                Freeze_And_Append
2067                  (Corresponding_Remote_Type (Rec), Loc, Result);
2068             end if;
2069
2070             Comp := First_Component (Rec);
2071             while Present (Comp) loop
2072                if Has_Controlled_Component (Etype (Comp))
2073                  or else (Chars (Comp) /= Name_uParent
2074                            and then Is_Controlled (Etype (Comp)))
2075                  or else (Is_Protected_Type (Etype (Comp))
2076                            and then Present
2077                              (Corresponding_Record_Type (Etype (Comp)))
2078                            and then Has_Controlled_Component
2079                              (Corresponding_Record_Type (Etype (Comp))))
2080                then
2081                   Set_Has_Controlled_Component (Rec);
2082                   exit;
2083                end if;
2084
2085                if Has_Unchecked_Union (Etype (Comp)) then
2086                   Set_Has_Unchecked_Union (Rec);
2087                end if;
2088
2089                if Has_Per_Object_Constraint (Comp) then
2090
2091                   --  Scan component declaration for likely misuses of current
2092                   --  instance, either in a constraint or a default expression.
2093
2094                   Check_Current_Instance (Parent (Comp));
2095                end if;
2096
2097                Next_Component (Comp);
2098             end loop;
2099          end if;
2100
2101          Set_Component_Alignment_If_Not_Set (Rec);
2102
2103          --  For first subtypes, check if there are any fixed-point fields with
2104          --  component clauses, where we must check the size. This is not done
2105          --  till the freeze point, since for fixed-point types, we do not know
2106          --  the size until the type is frozen. Similar processing applies to
2107          --  bit packed arrays.
2108
2109          if Is_First_Subtype (Rec) then
2110             Comp := First_Component (Rec);
2111
2112             while Present (Comp) loop
2113                if Present (Component_Clause (Comp))
2114                  and then (Is_Fixed_Point_Type (Etype (Comp))
2115                              or else
2116                            Is_Bit_Packed_Array (Etype (Comp)))
2117                then
2118                   Check_Size
2119                     (Component_Name (Component_Clause (Comp)),
2120                      Etype (Comp),
2121                      Esize (Comp),
2122                      Junk);
2123                end if;
2124
2125                Next_Component (Comp);
2126             end loop;
2127          end if;
2128
2129          --  Generate warning for applying C or C++ convention to a record
2130          --  with discriminants. This is suppressed for the unchecked union
2131          --  case, since the whole point in this case is interface C. We also
2132          --  do not generate this within instantiations, since we will have
2133          --  generated a message on the template.
2134
2135          if Has_Discriminants (E)
2136            and then not Is_Unchecked_Union (E)
2137            and then (Convention (E) = Convention_C
2138                        or else
2139                      Convention (E) = Convention_CPP)
2140            and then Comes_From_Source (E)
2141            and then not In_Instance
2142            and then not Has_Warnings_Off (E)
2143            and then not Has_Warnings_Off (Base_Type (E))
2144          then
2145             declare
2146                Cprag : constant Node_Id := Get_Rep_Pragma (E, Name_Convention);
2147                A2    : Node_Id;
2148
2149             begin
2150                if Present (Cprag) then
2151                   A2 := Next (First (Pragma_Argument_Associations (Cprag)));
2152
2153                   if Convention (E) = Convention_C then
2154                      Error_Msg_N
2155                        ("?variant record has no direct equivalent in C", A2);
2156                   else
2157                      Error_Msg_N
2158                        ("?variant record has no direct equivalent in C++", A2);
2159                   end if;
2160
2161                   Error_Msg_NE
2162                     ("\?use of convention for type& is dubious", A2, E);
2163                end if;
2164             end;
2165          end if;
2166       end Freeze_Record_Type;
2167
2168    --  Start of processing for Freeze_Entity
2169
2170    begin
2171       --  We are going to test for various reasons why this entity need not be
2172       --  frozen here, but in the case of an Itype that's defined within a
2173       --  record, that test actually applies to the record.
2174
2175       if Is_Itype (E) and then Is_Record_Type (Scope (E)) then
2176          Test_E := Scope (E);
2177       elsif Is_Itype (E) and then Present (Underlying_Type (Scope (E)))
2178         and then Is_Record_Type (Underlying_Type (Scope (E)))
2179       then
2180          Test_E := Underlying_Type (Scope (E));
2181       end if;
2182
2183       --  Do not freeze if already frozen since we only need one freeze node
2184
2185       if Is_Frozen (E) then
2186          return No_List;
2187
2188       --  It is improper to freeze an external entity within a generic because
2189       --  its freeze node will appear in a non-valid context. The entity will
2190       --  be frozen in the proper scope after the current generic is analyzed.
2191
2192       elsif Inside_A_Generic and then External_Ref_In_Generic (Test_E) then
2193          return No_List;
2194
2195       --  Do not freeze a global entity within an inner scope created during
2196       --  expansion. A call to subprogram E within some internal procedure
2197       --  (a stream attribute for example) might require freezing E, but the
2198       --  freeze node must appear in the same declarative part as E itself.
2199       --  The two-pass elaboration mechanism in gigi guarantees that E will
2200       --  be frozen before the inner call is elaborated. We exclude constants
2201       --  from this test, because deferred constants may be frozen early, and
2202       --  must be diagnosed (e.g. in the case of a deferred constant being used
2203       --  in a default expression). If the enclosing subprogram comes from
2204       --  source, or is a generic instance, then the freeze point is the one
2205       --  mandated by the language, and we freeze the entity. A subprogram that
2206       --  is a child unit body that acts as a spec does not have a spec that
2207       --  comes from source, but can only come from source.
2208
2209       elsif In_Open_Scopes (Scope (Test_E))
2210         and then Scope (Test_E) /= Current_Scope
2211         and then Ekind (Test_E) /= E_Constant
2212       then
2213          declare
2214             S : Entity_Id := Current_Scope;
2215
2216          begin
2217             while Present (S) loop
2218                if Is_Overloadable (S) then
2219                   if Comes_From_Source (S)
2220                     or else Is_Generic_Instance (S)
2221                     or else Is_Child_Unit (S)
2222                   then
2223                      exit;
2224                   else
2225                      return No_List;
2226                   end if;
2227                end if;
2228
2229                S := Scope (S);
2230             end loop;
2231          end;
2232
2233       --  Similarly, an inlined instance body may make reference to global
2234       --  entities, but these references cannot be the proper freezing point
2235       --  for them, and in the absence of inlining freezing will take place in
2236       --  their own scope. Normally instance bodies are analyzed after the
2237       --  enclosing compilation, and everything has been frozen at the proper
2238       --  place, but with front-end inlining an instance body is compiled
2239       --  before the end of the enclosing scope, and as a result out-of-order
2240       --  freezing must be prevented.
2241
2242       elsif Front_End_Inlining
2243         and then In_Instance_Body
2244         and then Present (Scope (Test_E))
2245       then
2246          declare
2247             S : Entity_Id := Scope (Test_E);
2248
2249          begin
2250             while Present (S) loop
2251                if Is_Generic_Instance (S) then
2252                   exit;
2253                else
2254                   S := Scope (S);
2255                end if;
2256             end loop;
2257
2258             if No (S) then
2259                return No_List;
2260             end if;
2261          end;
2262       end if;
2263
2264       --  Here to freeze the entity
2265
2266       Result := No_List;
2267       Set_Is_Frozen (E);
2268
2269       --  Case of entity being frozen is other than a type
2270
2271       if not Is_Type (E) then
2272
2273          --  If entity is exported or imported and does not have an external
2274          --  name, now is the time to provide the appropriate default name.
2275          --  Skip this if the entity is stubbed, since we don't need a name
2276          --  for any stubbed routine.
2277
2278          if (Is_Imported (E) or else Is_Exported (E))
2279            and then No (Interface_Name (E))
2280            and then Convention (E) /= Convention_Stubbed
2281          then
2282             Set_Encoded_Interface_Name
2283               (E, Get_Default_External_Name (E));
2284
2285          --  If entity is an atomic object appearing in a declaration and
2286          --  the expression is an aggregate, assign it to a temporary to
2287          --  ensure that the actual assignment is done atomically rather
2288          --  than component-wise (the assignment to the temp may be done
2289          --  component-wise, but that is harmless).
2290
2291          elsif Is_Atomic (E)
2292            and then Nkind (Parent (E)) = N_Object_Declaration
2293            and then Present (Expression (Parent (E)))
2294            and then Nkind (Expression (Parent (E))) = N_Aggregate
2295          then
2296             Expand_Atomic_Aggregate (Expression (Parent (E)), Etype (E));
2297          end if;
2298
2299          --  For a subprogram, freeze all parameter types and also the return
2300          --  type (RM 13.14(14)). However skip this for internal subprograms.
2301          --  This is also the point where any extra formal parameters are
2302          --  created since we now know whether the subprogram will use
2303          --  a foreign convention.
2304
2305          if Is_Subprogram (E) then
2306             if not Is_Internal (E) then
2307                declare
2308                   F_Type    : Entity_Id;
2309                   R_Type    : Entity_Id;
2310                   Warn_Node : Node_Id;
2311
2312                begin
2313                   --  Loop through formals
2314
2315                   Formal := First_Formal (E);
2316                   while Present (Formal) loop
2317                      F_Type := Etype (Formal);
2318                      Freeze_And_Append (F_Type, Loc, Result);
2319
2320                      if Is_Private_Type (F_Type)
2321                        and then Is_Private_Type (Base_Type (F_Type))
2322                        and then No (Full_View (Base_Type (F_Type)))
2323                        and then not Is_Generic_Type (F_Type)
2324                        and then not Is_Derived_Type (F_Type)
2325                      then
2326                         --  If the type of a formal is incomplete, subprogram
2327                         --  is being frozen prematurely. Within an instance
2328                         --  (but not within a wrapper package) this is an
2329                         --  an artifact of our need to regard the end of an
2330                         --  instantiation as a freeze point. Otherwise it is
2331                         --  a definite error.
2332
2333                         --  and then not Is_Wrapper_Package (Current_Scope) ???
2334
2335                         if In_Instance then
2336                            Set_Is_Frozen (E, False);
2337                            return No_List;
2338
2339                         elsif not After_Last_Declaration
2340                           and then not Freezing_Library_Level_Tagged_Type
2341                         then
2342                            Error_Msg_Node_1 := F_Type;
2343                            Error_Msg
2344                              ("type& must be fully defined before this point",
2345                                Loc);
2346                         end if;
2347                      end if;
2348
2349                      --  Check suspicious parameter for C function. These tests
2350                      --  apply only to exported/imported subprograms.
2351
2352                      if Warn_On_Export_Import
2353                        and then Comes_From_Source (E)
2354                        and then (Convention (E) = Convention_C
2355                                    or else
2356                                  Convention (E) = Convention_CPP)
2357                        and then (Is_Imported (E) or else Is_Exported (E))
2358                        and then Convention (E) /= Convention (Formal)
2359                        and then not Has_Warnings_Off (E)
2360                        and then not Has_Warnings_Off (F_Type)
2361                        and then not Has_Warnings_Off (Formal)
2362                      then
2363                         Error_Msg_Qual_Level := 1;
2364
2365                         --  Check suspicious use of fat C pointer
2366
2367                         if Is_Access_Type (F_Type)
2368                           and then Esize (F_Type) > Ttypes.System_Address_Size
2369                         then
2370                            Error_Msg_N
2371                              ("?type of & does not correspond "
2372                               & "to C pointer!", Formal);
2373
2374                         --  Check suspicious return of boolean
2375
2376                         elsif Root_Type (F_Type) = Standard_Boolean
2377                           and then Convention (F_Type) = Convention_Ada
2378                           and then not Has_Warnings_Off (F_Type)
2379                           and then not Has_Size_Clause (F_Type)
2380                         then
2381                            Error_Msg_N
2382                              ("?& is an 8-bit Ada Boolean, "
2383                               & "use char in C!", Formal);
2384
2385                         --  Check suspicious tagged type
2386
2387                         elsif (Is_Tagged_Type (F_Type)
2388                                 or else (Is_Access_Type (F_Type)
2389                                            and then
2390                                              Is_Tagged_Type
2391                                                (Designated_Type (F_Type))))
2392                           and then Convention (E) = Convention_C
2393                         then
2394                            Error_Msg_N
2395                              ("?& is a tagged type which does not "
2396                               & "correspond to any C type!", Formal);
2397
2398                         --  Check wrong convention subprogram pointer
2399
2400                         elsif Ekind (F_Type) = E_Access_Subprogram_Type
2401                           and then not Has_Foreign_Convention (F_Type)
2402                         then
2403                            Error_Msg_N
2404                              ("?subprogram pointer & should "
2405                               & "have foreign convention!", Formal);
2406                            Error_Msg_Sloc := Sloc (F_Type);
2407                            Error_Msg_NE
2408                              ("\?add Convention pragma to declaration of &#",
2409                               Formal, F_Type);
2410                         end if;
2411
2412                         Error_Msg_Qual_Level := 0;
2413                      end if;
2414
2415                      --  Check for unconstrained array in exported foreign
2416                      --  convention case.
2417
2418                      if Has_Foreign_Convention (E)
2419                        and then not Is_Imported (E)
2420                        and then Is_Array_Type (F_Type)
2421                        and then not Is_Constrained (F_Type)
2422                        and then Warn_On_Export_Import
2423                      then
2424                         Error_Msg_Qual_Level := 1;
2425
2426                         --  If this is an inherited operation, place the
2427                         --  warning on the derived type declaration, rather
2428                         --  than on the original subprogram.
2429
2430                         if Nkind (Original_Node (Parent (E))) =
2431                           N_Full_Type_Declaration
2432                         then
2433                            Warn_Node := Parent (E);
2434
2435                            if Formal = First_Formal (E) then
2436                               Error_Msg_NE
2437                                 ("?in inherited operation&", Warn_Node, E);
2438                            end if;
2439                         else
2440                            Warn_Node := Formal;
2441                         end if;
2442
2443                         Error_Msg_NE
2444                           ("?type of argument& is unconstrained array",
2445                            Warn_Node, Formal);
2446                         Error_Msg_NE
2447                           ("?foreign caller must pass bounds explicitly",
2448                            Warn_Node, Formal);
2449                         Error_Msg_Qual_Level := 0;
2450                      end if;
2451
2452                      if not From_With_Type (F_Type) then
2453                         if Is_Access_Type (F_Type) then
2454                            F_Type := Designated_Type (F_Type);
2455                         end if;
2456
2457                         --  If the formal is an anonymous_access_to_subprogram
2458                         --  freeze the  subprogram type as well, to prevent
2459                         --  scope anomalies in gigi, because there is no other
2460                         --  clear point at which it could be frozen.
2461
2462                         if Is_Itype (Etype (Formal))
2463                           and then Ekind (F_Type) = E_Subprogram_Type
2464                         then
2465                            Freeze_And_Append (F_Type, Loc, Result);
2466                         end if;
2467                      end if;
2468
2469                      Next_Formal (Formal);
2470                   end loop;
2471
2472                   --  Case of function: similar checks on return type
2473
2474                   if Ekind (E) = E_Function then
2475
2476                      --  Freeze return type
2477
2478                      R_Type := Etype (E);
2479                      Freeze_And_Append (R_Type, Loc, Result);
2480
2481                      --  Check suspicious return type for C function
2482
2483                      if Warn_On_Export_Import
2484                        and then (Convention (E) = Convention_C
2485                                    or else
2486                                  Convention (E) = Convention_CPP)
2487                        and then (Is_Imported (E) or else Is_Exported (E))
2488                      then
2489                         --  Check suspicious return of fat C pointer
2490
2491                         if Is_Access_Type (R_Type)
2492                           and then Esize (R_Type) > Ttypes.System_Address_Size
2493                           and then not Has_Warnings_Off (E)
2494                           and then not Has_Warnings_Off (R_Type)
2495                         then
2496                            Error_Msg_N
2497                              ("?return type of& does not "
2498                               & "correspond to C pointer!", E);
2499
2500                         --  Check suspicious return of boolean
2501
2502                         elsif Root_Type (R_Type) = Standard_Boolean
2503                           and then Convention (R_Type) = Convention_Ada
2504                           and then not Has_Warnings_Off (E)
2505                           and then not Has_Warnings_Off (R_Type)
2506                           and then not Has_Size_Clause (R_Type)
2507                         then
2508                            Error_Msg_N
2509                              ("?return type of & is an 8-bit "
2510                               & "Ada Boolean, use char in C!", E);
2511
2512                         --  Check suspicious return tagged type
2513
2514                         elsif (Is_Tagged_Type (R_Type)
2515                                 or else (Is_Access_Type (R_Type)
2516                                            and then
2517                                              Is_Tagged_Type
2518                                                (Designated_Type (R_Type))))
2519                           and then Convention (E) = Convention_C
2520                           and then not Has_Warnings_Off (E)
2521                           and then not Has_Warnings_Off (R_Type)
2522                         then
2523                            Error_Msg_N
2524                              ("?return type of & does not "
2525                               & "correspond to C type!", E);
2526
2527                         --  Check return of wrong convention subprogram pointer
2528
2529                         elsif Ekind (R_Type) = E_Access_Subprogram_Type
2530                           and then not Has_Foreign_Convention (R_Type)
2531                           and then not Has_Warnings_Off (E)
2532                           and then not Has_Warnings_Off (R_Type)
2533                         then
2534                            Error_Msg_N
2535                              ("?& should return a foreign "
2536                               & "convention subprogram pointer", E);
2537                            Error_Msg_Sloc := Sloc (R_Type);
2538                            Error_Msg_NE
2539                              ("\?add Convention pragma to declaration of& #",
2540                               E, R_Type);
2541                         end if;
2542                      end if;
2543
2544                      if Is_Array_Type (R_Type)
2545                        and then not Is_Constrained (R_Type)
2546                        and then not Is_Imported (E)
2547                        and then Has_Foreign_Convention (E)
2548                        and then Warn_On_Export_Import
2549                        and then not Has_Warnings_Off (E)
2550                        and then not Has_Warnings_Off (R_Type)
2551                      then
2552                         Error_Msg_N
2553                           ("?foreign convention function& should not " &
2554                            "return unconstrained array!", E);
2555                      end if;
2556                   end if;
2557                end;
2558             end if;
2559
2560             --  Must freeze its parent first if it is a derived subprogram
2561
2562             if Present (Alias (E)) then
2563                Freeze_And_Append (Alias (E), Loc, Result);
2564             end if;
2565
2566             --  We don't freeze internal subprograms, because we don't normally
2567             --  want addition of extra formals or mechanism setting to happen
2568             --  for those. However we do pass through predefined dispatching
2569             --  cases, since extra formals may be needed in some cases, such as
2570             --  for the stream 'Input function (build-in-place formals).
2571
2572             if not Is_Internal (E)
2573               or else Is_Predefined_Dispatching_Operation (E)
2574             then
2575                Freeze_Subprogram (E);
2576             end if;
2577
2578          --  Here for other than a subprogram or type
2579
2580          else
2581             --  If entity has a type, and it is not a generic unit, then
2582             --  freeze it first (RM 13.14(10)).
2583
2584             if Present (Etype (E))
2585               and then Ekind (E) /= E_Generic_Function
2586             then
2587                Freeze_And_Append (Etype (E), Loc, Result);
2588             end if;
2589
2590             --  Special processing for objects created by object declaration
2591
2592             if Nkind (Declaration_Node (E)) = N_Object_Declaration then
2593
2594                --  For object created by object declaration, perform required
2595                --  categorization (preelaborate and pure) checks. Defer these
2596                --  checks to freeze time since pragma Import inhibits default
2597                --  initialization and thus pragma Import affects these checks.
2598
2599                Validate_Object_Declaration (Declaration_Node (E));
2600
2601                --  If there is an address clause, check that it is valid
2602
2603                Check_Address_Clause (E);
2604
2605                --  If the object needs any kind of default initialization, an
2606                --  error must be issued if No_Default_Initialization applies.
2607                --  The check doesn't apply to imported objects, which are not
2608                --  ever default initialized, and is why the check is deferred
2609                --  until freezing, at which point we know if Import applies.
2610                --  Deferred constants are also exempted from this test because
2611                --  their completion is explicit, or through an import pragma.
2612
2613                if Ekind (E) = E_Constant
2614                  and then Present (Full_View (E))
2615                then
2616                   null;
2617
2618                elsif Comes_From_Source (E)
2619                  and then not Is_Imported (E)
2620                  and then not Has_Init_Expression (Declaration_Node (E))
2621                  and then
2622                    ((Has_Non_Null_Base_Init_Proc (Etype (E))
2623                       and then not No_Initialization (Declaration_Node (E))
2624                       and then not Is_Value_Type (Etype (E))
2625                       and then not Suppress_Init_Proc (Etype (E)))
2626                     or else
2627                       (Needs_Simple_Initialization (Etype (E))
2628                         and then not Is_Internal (E)))
2629                then
2630                   Has_Default_Initialization := True;
2631                   Check_Restriction
2632                     (No_Default_Initialization, Declaration_Node (E));
2633                end if;
2634
2635                --  Check that a Thread_Local_Storage variable does not have
2636                --  default initialization, and any explicit initialization must
2637                --  either be the null constant or a static constant.
2638
2639                if Has_Pragma_Thread_Local_Storage (E) then
2640                   declare
2641                      Decl : constant Node_Id := Declaration_Node (E);
2642                   begin
2643                      if Has_Default_Initialization
2644                        or else
2645                          (Has_Init_Expression (Decl)
2646                             and then
2647                              (No (Expression (Decl))
2648                                 or else not
2649                                   (Is_Static_Expression (Expression (Decl))
2650                                      or else
2651                                    Nkind (Expression (Decl)) = N_Null)))
2652                      then
2653                         Error_Msg_NE
2654                           ("Thread_Local_Storage variable& is "
2655                            & "improperly initialized", Decl, E);
2656                         Error_Msg_NE
2657                           ("\only allowed initialization is explicit "
2658                            & "NULL or static expression", Decl, E);
2659                      end if;
2660                   end;
2661                end if;
2662
2663                --  For imported objects, set Is_Public unless there is also an
2664                --  address clause, which means that there is no external symbol
2665                --  needed for the Import (Is_Public may still be set for other
2666                --  unrelated reasons). Note that we delayed this processing
2667                --  till freeze time so that we can be sure not to set the flag
2668                --  if there is an address clause. If there is such a clause,
2669                --  then the only purpose of the Import pragma is to suppress
2670                --  implicit initialization.
2671
2672                if Is_Imported (E)
2673                  and then No (Address_Clause (E))
2674                then
2675                   Set_Is_Public (E);
2676                end if;
2677
2678                --  For convention C objects of an enumeration type, warn if
2679                --  the size is not integer size and no explicit size given.
2680                --  Skip warning for Boolean, and Character, assume programmer
2681                --  expects 8-bit sizes for these cases.
2682
2683                if (Convention (E) = Convention_C
2684                     or else
2685                    Convention (E) = Convention_CPP)
2686                  and then Is_Enumeration_Type (Etype (E))
2687                  and then not Is_Character_Type (Etype (E))
2688                  and then not Is_Boolean_Type (Etype (E))
2689                  and then Esize (Etype (E)) < Standard_Integer_Size
2690                  and then not Has_Size_Clause (E)
2691                then
2692                   Error_Msg_Uint_1 := UI_From_Int (Standard_Integer_Size);
2693                   Error_Msg_N
2694                     ("?convention C enumeration object has size less than ^",
2695                      E);
2696                   Error_Msg_N ("\?use explicit size clause to set size", E);
2697                end if;
2698             end if;
2699
2700             --  Check that a constant which has a pragma Volatile[_Components]
2701             --  or Atomic[_Components] also has a pragma Import (RM C.6(13)).
2702
2703             --  Note: Atomic[_Components] also sets Volatile[_Components]
2704
2705             if Ekind (E) = E_Constant
2706               and then (Has_Volatile_Components (E) or else Is_Volatile (E))
2707               and then not Is_Imported (E)
2708             then
2709                --  Make sure we actually have a pragma, and have not merely
2710                --  inherited the indication from elsewhere (e.g. an address
2711                --  clause, which is not good enough in RM terms!)
2712
2713                if Has_Rep_Pragma (E, Name_Atomic)
2714                     or else
2715                   Has_Rep_Pragma (E, Name_Atomic_Components)
2716                then
2717                   Error_Msg_N
2718                     ("stand alone atomic constant must be " &
2719                      "imported (RM C.6(13))", E);
2720
2721                elsif Has_Rep_Pragma (E, Name_Volatile)
2722                        or else
2723                      Has_Rep_Pragma (E, Name_Volatile_Components)
2724                then
2725                   Error_Msg_N
2726                     ("stand alone volatile constant must be " &
2727                      "imported (RM C.6(13))", E);
2728                end if;
2729             end if;
2730
2731             --  Static objects require special handling
2732
2733             if (Ekind (E) = E_Constant or else Ekind (E) = E_Variable)
2734               and then Is_Statically_Allocated (E)
2735             then
2736                Freeze_Static_Object (E);
2737             end if;
2738
2739             --  Remaining step is to layout objects
2740
2741             if Ekind (E) = E_Variable
2742                  or else
2743                Ekind (E) = E_Constant
2744                  or else
2745                Ekind (E) = E_Loop_Parameter
2746                  or else
2747                Is_Formal (E)
2748             then
2749                Layout_Object (E);
2750             end if;
2751          end if;
2752
2753       --  Case of a type or subtype being frozen
2754
2755       else
2756          --  We used to check here that a full type must have preelaborable
2757          --  initialization if it completes a private type specified with
2758          --  pragma Preelaborable_Intialization, but that missed cases where
2759          --  the types occur within a generic package, since the freezing
2760          --  that occurs within a containing scope generally skips traversal
2761          --  of a generic unit's declarations (those will be frozen within
2762          --  instances). This check was moved to Analyze_Package_Specification.
2763
2764          --  The type may be defined in a generic unit. This can occur when
2765          --  freezing a generic function that returns the type (which is
2766          --  defined in a parent unit). It is clearly meaningless to freeze
2767          --  this type. However, if it is a subtype, its size may be determi-
2768          --  nable and used in subsequent checks, so might as well try to
2769          --  compute it.
2770
2771          if Present (Scope (E))
2772            and then Is_Generic_Unit (Scope (E))
2773          then
2774             Check_Compile_Time_Size (E);
2775             return No_List;
2776          end if;
2777
2778          --  Deal with special cases of freezing for subtype
2779
2780          if E /= Base_Type (E) then
2781
2782             --  Before we do anything else, a specialized test for the case of
2783             --  a size given for an array where the array needs to be packed,
2784             --  but was not so the size cannot be honored. This would of course
2785             --  be caught by the backend, and indeed we don't catch all cases.
2786             --  The point is that we can give a better error message in those
2787             --  cases that we do catch with the circuitry here. Also if pragma
2788             --  Implicit_Packing is set, this is where the packing occurs.
2789
2790             --  The reason we do this so early is that the processing in the
2791             --  automatic packing case affects the layout of the base type, so
2792             --  it must be done before we freeze the base type.
2793
2794             if Is_Array_Type (E) then
2795                declare
2796                   Lo, Hi : Node_Id;
2797                   Ctyp   : constant Entity_Id := Component_Type (E);
2798
2799                begin
2800                   --  Check enabling conditions. These are straightforward
2801                   --  except for the test for a limited composite type. This
2802                   --  eliminates the rare case of a array of limited components
2803                   --  where there are issues of whether or not we can go ahead
2804                   --  and pack the array (since we can't freely pack and unpack
2805                   --  arrays if they are limited).
2806
2807                   --  Note that we check the root type explicitly because the
2808                   --  whole point is we are doing this test before we have had
2809                   --  a chance to freeze the base type (and it is that freeze
2810                   --  action that causes stuff to be inherited).
2811
2812                   if Present (Size_Clause (E))
2813                     and then Known_Static_Esize (E)
2814                     and then not Is_Packed (E)
2815                     and then not Has_Pragma_Pack (E)
2816                     and then Number_Dimensions (E) = 1
2817                     and then not Has_Component_Size_Clause (E)
2818                     and then Known_Static_Esize (Ctyp)
2819                     and then not Is_Limited_Composite (E)
2820                     and then not Is_Packed (Root_Type (E))
2821                     and then not Has_Component_Size_Clause (Root_Type (E))
2822                   then
2823                      Get_Index_Bounds (First_Index (E), Lo, Hi);
2824
2825                      if Compile_Time_Known_Value (Lo)
2826                        and then Compile_Time_Known_Value (Hi)
2827                        and then Known_Static_RM_Size (Ctyp)
2828                        and then RM_Size (Ctyp) < 64
2829                      then
2830                         declare
2831                            Lov  : constant Uint      := Expr_Value (Lo);
2832                            Hiv  : constant Uint      := Expr_Value (Hi);
2833                            Len  : constant Uint      := UI_Max
2834                                                          (Uint_0,
2835                                                           Hiv - Lov + 1);
2836                            Rsiz : constant Uint      := RM_Size (Ctyp);
2837                            SZ   : constant Node_Id   := Size_Clause (E);
2838                            Btyp : constant Entity_Id := Base_Type (E);
2839
2840                         --  What we are looking for here is the situation where
2841                         --  the RM_Size given would be exactly right if there
2842                         --  was a pragma Pack (resulting in the component size
2843                         --  being the same as the RM_Size). Furthermore, the
2844                         --  component type size must be an odd size (not a
2845                         --  multiple of storage unit)
2846
2847                         begin
2848                            if RM_Size (E) = Len * Rsiz
2849                              and then Rsiz mod System_Storage_Unit /= 0
2850                            then
2851                               --  For implicit packing mode, just set the
2852                               --  component size silently
2853
2854                               if Implicit_Packing then
2855                                  Set_Component_Size       (Btyp, Rsiz);
2856                                  Set_Is_Bit_Packed_Array  (Btyp);
2857                                  Set_Is_Packed            (Btyp);
2858                                  Set_Has_Non_Standard_Rep (Btyp);
2859
2860                                  --  Otherwise give an error message
2861
2862                               else
2863                                  Error_Msg_NE
2864                                    ("size given for& too small", SZ, E);
2865                                  Error_Msg_N
2866                                    ("\use explicit pragma Pack "
2867                                     & "or use pragma Implicit_Packing", SZ);
2868                               end if;
2869                            end if;
2870                         end;
2871                      end if;
2872                   end if;
2873                end;
2874             end if;
2875
2876             --  If ancestor subtype present, freeze that first. Note that this
2877             --  will also get the base type frozen.
2878
2879             Atype := Ancestor_Subtype (E);
2880
2881             if Present (Atype) then
2882                Freeze_And_Append (Atype, Loc, Result);
2883
2884             --  Otherwise freeze the base type of the entity before freezing
2885             --  the entity itself (RM 13.14(15)).
2886
2887             elsif E /= Base_Type (E) then
2888                Freeze_And_Append (Base_Type (E), Loc, Result);
2889             end if;
2890
2891          --  For a derived type, freeze its parent type first (RM 13.14(15))
2892
2893          elsif Is_Derived_Type (E) then
2894             Freeze_And_Append (Etype (E), Loc, Result);
2895             Freeze_And_Append (First_Subtype (Etype (E)), Loc, Result);
2896          end if;
2897
2898          --  For array type, freeze index types and component type first
2899          --  before freezing the array (RM 13.14(15)).
2900
2901          if Is_Array_Type (E) then
2902             declare
2903                Ctyp : constant Entity_Id := Component_Type (E);
2904
2905                Non_Standard_Enum : Boolean := False;
2906                --  Set true if any of the index types is an enumeration type
2907                --  with a non-standard representation.
2908
2909             begin
2910                Freeze_And_Append (Ctyp, Loc, Result);
2911
2912                Indx := First_Index (E);
2913                while Present (Indx) loop
2914                   Freeze_And_Append (Etype (Indx), Loc, Result);
2915
2916                   if Is_Enumeration_Type (Etype (Indx))
2917                     and then Has_Non_Standard_Rep (Etype (Indx))
2918                   then
2919                      Non_Standard_Enum := True;
2920                   end if;
2921
2922                   Next_Index (Indx);
2923                end loop;
2924
2925                --  Processing that is done only for base types
2926
2927                if Ekind (E) = E_Array_Type then
2928
2929                   --  Propagate flags for component type
2930
2931                   if Is_Controlled (Component_Type (E))
2932                     or else Has_Controlled_Component (Ctyp)
2933                   then
2934                      Set_Has_Controlled_Component (E);
2935                   end if;
2936
2937                   if Has_Unchecked_Union (Component_Type (E)) then
2938                      Set_Has_Unchecked_Union (E);
2939                   end if;
2940
2941                   --  If packing was requested or if the component size was set
2942                   --  explicitly, then see if bit packing is required. This
2943                   --  processing is only done for base types, since all the
2944                   --  representation aspects involved are type-related. This
2945                   --  is not just an optimization, if we start processing the
2946                   --  subtypes, they interfere with the settings on the base
2947                   --  type (this is because Is_Packed has a slightly different
2948                   --  meaning before and after freezing).
2949
2950                   declare
2951                      Csiz : Uint;
2952                      Esiz : Uint;
2953
2954                   begin
2955                      if (Is_Packed (E) or else Has_Pragma_Pack (E))
2956                        and then not Has_Atomic_Components (E)
2957                        and then Known_Static_RM_Size (Ctyp)
2958                      then
2959                         Csiz := UI_Max (RM_Size (Ctyp), 1);
2960
2961                      elsif Known_Component_Size (E) then
2962                         Csiz := Component_Size (E);
2963
2964                      elsif not Known_Static_Esize (Ctyp) then
2965                         Csiz := Uint_0;
2966
2967                      else
2968                         Esiz := Esize (Ctyp);
2969
2970                         --  We can set the component size if it is less than
2971                         --  16, rounding it up to the next storage unit size.
2972
2973                         if Esiz <= 8 then
2974                            Csiz := Uint_8;
2975                         elsif Esiz <= 16 then
2976                            Csiz := Uint_16;
2977                         else
2978                            Csiz := Uint_0;
2979                         end if;
2980
2981                         --  Set component size up to match alignment if it
2982                         --  would otherwise be less than the alignment. This
2983                         --  deals with cases of types whose alignment exceeds
2984                         --  their size (padded types).
2985
2986                         if Csiz /= 0 then
2987                            declare
2988                               A : constant Uint := Alignment_In_Bits (Ctyp);
2989                            begin
2990                               if Csiz < A then
2991                                  Csiz := A;
2992                               end if;
2993                            end;
2994                         end if;
2995                      end if;
2996
2997                      --  Case of component size that may result in packing
2998
2999                      if 1 <= Csiz and then Csiz <= 64 then
3000                         declare
3001                            Ent         : constant Entity_Id :=
3002                                            First_Subtype (E);
3003                            Pack_Pragma : constant Node_Id :=
3004                                            Get_Rep_Pragma (Ent, Name_Pack);
3005                            Comp_Size_C : constant Node_Id :=
3006                                            Get_Attribute_Definition_Clause
3007                                              (Ent, Attribute_Component_Size);
3008                         begin
3009                            --  Warn if we have pack and component size so that
3010                            --  the pack is ignored.
3011
3012                            --  Note: here we must check for the presence of a
3013                            --  component size before checking for a Pack pragma
3014                            --  to deal with the case where the array type is a
3015                            --  derived type whose parent is currently private.
3016
3017                            if Present (Comp_Size_C)
3018                              and then Has_Pragma_Pack (Ent)
3019                            then
3020                               Error_Msg_Sloc := Sloc (Comp_Size_C);
3021                               Error_Msg_NE
3022                                 ("?pragma Pack for& ignored!",
3023                                  Pack_Pragma, Ent);
3024                               Error_Msg_N
3025                                 ("\?explicit component size given#!",
3026                                  Pack_Pragma);
3027                            end if;
3028
3029                            --  Set component size if not already set by a
3030                            --  component size clause.
3031
3032                            if not Present (Comp_Size_C) then
3033                               Set_Component_Size (E, Csiz);
3034                            end if;
3035
3036                            --  Check for base type of 8, 16, 32 bits, where an
3037                            --  unsigned subtype has a length one less than the
3038                            --  base type (e.g. Natural subtype of Integer).
3039
3040                            --  In such cases, if a component size was not set
3041                            --  explicitly, then generate a warning.
3042
3043                            if Has_Pragma_Pack (E)
3044                              and then not Present (Comp_Size_C)
3045                              and then
3046                                (Csiz = 7 or else Csiz = 15 or else Csiz = 31)
3047                              and then Esize (Base_Type (Ctyp)) = Csiz + 1
3048                            then
3049                               Error_Msg_Uint_1 := Csiz;
3050
3051                               if Present (Pack_Pragma) then
3052                                  Error_Msg_N
3053                                    ("?pragma Pack causes component size "
3054                                     & "to be ^!", Pack_Pragma);
3055                                  Error_Msg_N
3056                                    ("\?use Component_Size to set "
3057                                     & "desired value!", Pack_Pragma);
3058                               end if;
3059                            end if;
3060
3061                            --  Actual packing is not needed for 8, 16, 32, 64.
3062                            --  Also not needed for 24 if alignment is 1.
3063
3064                            if        Csiz = 8
3065                              or else Csiz = 16
3066                              or else Csiz = 32
3067                              or else Csiz = 64
3068                              or else (Csiz = 24 and then Alignment (Ctyp) = 1)
3069                            then
3070                               --  Here the array was requested to be packed,
3071                               --  but the packing request had no effect, so
3072                               --  Is_Packed is reset.
3073
3074                               --  Note: semantically this means that we lose
3075                               --  track of the fact that a derived type
3076                               --  inherited a pragma Pack that was non-
3077                               --  effective, but that seems fine.
3078
3079                               --  We regard a Pack pragma as a request to set
3080                               --  a representation characteristic, and this
3081                               --  request may be ignored.
3082
3083                               Set_Is_Packed (Base_Type (E), False);
3084
3085                               --  In all other cases, packing is indeed needed
3086
3087                            else
3088                               Set_Has_Non_Standard_Rep (Base_Type (E));
3089                               Set_Is_Bit_Packed_Array  (Base_Type (E));
3090                               Set_Is_Packed            (Base_Type (E));
3091                            end if;
3092                         end;
3093                      end if;
3094                   end;
3095
3096                --  Processing that is done only for subtypes
3097
3098                else
3099                   --  Acquire alignment from base type
3100
3101                   if Unknown_Alignment (E) then
3102                      Set_Alignment (E, Alignment (Base_Type (E)));
3103                      Adjust_Esize_Alignment (E);
3104                   end if;
3105                end if;
3106
3107                --  For bit-packed arrays, check the size
3108
3109                if Is_Bit_Packed_Array (E)
3110                  and then Known_RM_Size (E)
3111                then
3112                   declare
3113                      SizC : constant Node_Id := Size_Clause (E);
3114
3115                      Discard : Boolean;
3116                      pragma Warnings (Off, Discard);
3117
3118                   begin
3119                      --  It is not clear if it is possible to have no size
3120                      --  clause at this stage, but it is not worth worrying
3121                      --  about. Post error on the entity name in the size
3122                      --  clause if present, else on the type entity itself.
3123
3124                      if Present (SizC) then
3125                         Check_Size (Name (SizC), E, RM_Size (E), Discard);
3126                      else
3127                         Check_Size (E, E, RM_Size (E), Discard);
3128                      end if;
3129                   end;
3130                end if;
3131
3132                --  If any of the index types was an enumeration type with
3133                --  a non-standard rep clause, then we indicate that the
3134                --  array type is always packed (even if it is not bit packed).
3135
3136                if Non_Standard_Enum then
3137                   Set_Has_Non_Standard_Rep (Base_Type (E));
3138                   Set_Is_Packed            (Base_Type (E));
3139                end if;
3140
3141                Set_Component_Alignment_If_Not_Set (E);
3142
3143                --  If the array is packed, we must create the packed array
3144                --  type to be used to actually implement the type. This is
3145                --  only needed for real array types (not for string literal
3146                --  types, since they are present only for the front end).
3147
3148                if Is_Packed (E)
3149                  and then Ekind (E) /= E_String_Literal_Subtype
3150                then
3151                   Create_Packed_Array_Type (E);
3152                   Freeze_And_Append (Packed_Array_Type (E), Loc, Result);
3153
3154                   --  Size information of packed array type is copied to the
3155                   --  array type, since this is really the representation. But
3156                   --  do not override explicit existing size values. If the
3157                   --  ancestor subtype is constrained the packed_array_type
3158                   --  will be inherited from it, but the size may have been
3159                   --  provided already, and must not be overridden either.
3160
3161                   if not Has_Size_Clause (E)
3162                     and then
3163                       (No (Ancestor_Subtype (E))
3164                         or else not Has_Size_Clause (Ancestor_Subtype (E)))
3165                   then
3166                      Set_Esize     (E, Esize     (Packed_Array_Type (E)));
3167                      Set_RM_Size   (E, RM_Size   (Packed_Array_Type (E)));
3168                   end if;
3169
3170                   if not Has_Alignment_Clause (E) then
3171                      Set_Alignment (E, Alignment (Packed_Array_Type (E)));
3172                   end if;
3173                end if;
3174
3175                --  For non-packed arrays set the alignment of the array to the
3176                --  alignment of the component type if it is unknown. Skip this
3177                --  in atomic case (atomic arrays may need larger alignments).
3178
3179                if not Is_Packed (E)
3180                  and then Unknown_Alignment (E)
3181                  and then Known_Alignment (Ctyp)
3182                  and then Known_Static_Component_Size (E)
3183                  and then Known_Static_Esize (Ctyp)
3184                  and then Esize (Ctyp) = Component_Size (E)
3185                  and then not Is_Atomic (E)
3186                then
3187                   Set_Alignment (E, Alignment (Component_Type (E)));
3188                end if;
3189             end;
3190
3191          --  For a class-wide type, the corresponding specific type is
3192          --  frozen as well (RM 13.14(15))
3193
3194          elsif Is_Class_Wide_Type (E) then
3195             Freeze_And_Append (Root_Type (E), Loc, Result);
3196
3197             --  If the base type of the class-wide type is still incomplete,
3198             --  the class-wide remains unfrozen as well. This is legal when
3199             --  E is the formal of a primitive operation of some other type
3200             --  which is being frozen.
3201
3202             if not Is_Frozen (Root_Type (E)) then
3203                Set_Is_Frozen (E, False);
3204                return Result;
3205             end if;
3206
3207             --  If the Class_Wide_Type is an Itype (when type is the anonymous
3208             --  parent of a derived type) and it is a library-level entity,
3209             --  generate an itype reference for it. Otherwise, its first
3210             --  explicit reference may be in an inner scope, which will be
3211             --  rejected by the back-end.
3212
3213             if Is_Itype (E)
3214               and then Is_Compilation_Unit (Scope (E))
3215             then
3216                declare
3217                   Ref : constant Node_Id := Make_Itype_Reference (Loc);
3218
3219                begin
3220                   Set_Itype (Ref, E);
3221                   if No (Result) then
3222                      Result := New_List (Ref);
3223                   else
3224                      Append (Ref, Result);
3225                   end if;
3226                end;
3227             end if;
3228
3229             --  The equivalent type associated with a class-wide subtype needs
3230             --  to be frozen to ensure that its layout is done. Class-wide
3231             --  subtypes are currently only frozen on targets requiring
3232             --  front-end layout (see New_Class_Wide_Subtype and
3233             --  Make_CW_Equivalent_Type in exp_util.adb).
3234
3235             if Ekind (E) = E_Class_Wide_Subtype
3236               and then Present (Equivalent_Type (E))
3237             then
3238                Freeze_And_Append (Equivalent_Type (E), Loc, Result);
3239             end if;
3240
3241          --  For a record (sub)type, freeze all the component types (RM
3242          --  13.14(15). We test for E_Record_(sub)Type here, rather than using
3243          --  Is_Record_Type, because we don't want to attempt the freeze for
3244          --  the case of a private type with record extension (we will do that
3245          --  later when the full type is frozen).
3246
3247          elsif Ekind (E) = E_Record_Type
3248            or else  Ekind (E) = E_Record_Subtype
3249          then
3250             Freeze_Record_Type (E);
3251
3252          --  For a concurrent type, freeze corresponding record type. This
3253          --  does not correspond to any specific rule in the RM, but the
3254          --  record type is essentially part of the concurrent type.
3255          --  Freeze as well all local entities. This includes record types
3256          --  created for entry parameter blocks, and whatever local entities
3257          --  may appear in the private part.
3258
3259          elsif Is_Concurrent_Type (E) then
3260             if Present (Corresponding_Record_Type (E)) then
3261                Freeze_And_Append
3262                  (Corresponding_Record_Type (E), Loc, Result);
3263             end if;
3264
3265             Comp := First_Entity (E);
3266
3267             while Present (Comp) loop
3268                if Is_Type (Comp) then
3269                   Freeze_And_Append (Comp, Loc, Result);
3270
3271                elsif (Ekind (Comp)) /= E_Function then
3272                   if Is_Itype (Etype (Comp))
3273                     and then Underlying_Type (Scope (Etype (Comp))) = E
3274                   then
3275                      Undelay_Type (Etype (Comp));
3276                   end if;
3277
3278                   Freeze_And_Append (Etype (Comp), Loc, Result);
3279                end if;
3280
3281                Next_Entity (Comp);
3282             end loop;
3283
3284          --  Private types are required to point to the same freeze node as
3285          --  their corresponding full views. The freeze node itself has to
3286          --  point to the partial view of the entity (because from the partial
3287          --  view, we can retrieve the full view, but not the reverse).
3288          --  However, in order to freeze correctly, we need to freeze the full
3289          --  view. If we are freezing at the end of a scope (or within the
3290          --  scope of the private type), the partial and full views will have
3291          --  been swapped, the full view appears first in the entity chain and
3292          --  the swapping mechanism ensures that the pointers are properly set
3293          --  (on scope exit).
3294
3295          --  If we encounter the partial view before the full view (e.g. when
3296          --  freezing from another scope), we freeze the full view, and then
3297          --  set the pointers appropriately since we cannot rely on swapping to
3298          --  fix things up (subtypes in an outer scope might not get swapped).
3299
3300          elsif Is_Incomplete_Or_Private_Type (E)
3301            and then not Is_Generic_Type (E)
3302          then
3303             --  The construction of the dispatch table associated with library
3304             --  level tagged types forces freezing of all the primitives of the
3305             --  type, which may cause premature freezing of the partial view.
3306             --  For example:
3307
3308             --     package Pkg is
3309             --        type T is tagged private;
3310             --        type DT is new T with private;
3311             --        procedure Prim (X : in out T; Y : in out DT'class);
3312             --     private
3313             --        type T is tagged null record;
3314             --        Obj : T;
3315             --        type DT is new T with null record;
3316             --     end;
3317
3318             --  In this case the type will be frozen later by the usual
3319             --  mechanism: an object declaration, an instantiation, or the
3320             --  end of a declarative part.
3321
3322             if Is_Library_Level_Tagged_Type (E)
3323               and then not Present (Full_View (E))
3324             then
3325                Set_Is_Frozen (E, False);
3326                return Result;
3327
3328             --  Case of full view present
3329
3330             elsif Present (Full_View (E)) then
3331
3332                --  If full view has already been frozen, then no further
3333                --  processing is required
3334
3335                if Is_Frozen (Full_View (E)) then
3336
3337                   Set_Has_Delayed_Freeze (E, False);
3338                   Set_Freeze_Node (E, Empty);
3339                   Check_Debug_Info_Needed (E);
3340
3341                --  Otherwise freeze full view and patch the pointers so that
3342                --  the freeze node will elaborate both views in the back-end.
3343
3344                else
3345                   declare
3346                      Full : constant Entity_Id := Full_View (E);
3347
3348                   begin
3349                      if Is_Private_Type (Full)
3350                        and then Present (Underlying_Full_View (Full))
3351                      then
3352                         Freeze_And_Append
3353                           (Underlying_Full_View (Full), Loc, Result);
3354                      end if;
3355
3356                      Freeze_And_Append (Full, Loc, Result);
3357
3358                      if Has_Delayed_Freeze (E) then
3359                         F_Node := Freeze_Node (Full);
3360
3361                         if Present (F_Node) then
3362                            Set_Freeze_Node (E, F_Node);
3363                            Set_Entity (F_Node, E);
3364
3365                         else
3366                            --  {Incomplete,Private}_Subtypes with Full_Views
3367                            --  constrained by discriminants.
3368
3369                            Set_Has_Delayed_Freeze (E, False);
3370                            Set_Freeze_Node (E, Empty);
3371                         end if;
3372                      end if;
3373                   end;
3374
3375                   Check_Debug_Info_Needed (E);
3376                end if;
3377
3378                --  AI-117 requires that the convention of a partial view be the
3379                --  same as the convention of the full view. Note that this is a
3380                --  recognized breach of privacy, but it's essential for logical
3381                --  consistency of representation, and the lack of a rule in
3382                --  RM95 was an oversight.
3383
3384                Set_Convention (E, Convention (Full_View (E)));
3385
3386                Set_Size_Known_At_Compile_Time (E,
3387                  Size_Known_At_Compile_Time (Full_View (E)));
3388
3389                --  Size information is copied from the full view to the
3390                --  incomplete or private view for consistency.
3391
3392                --  We skip this is the full view is not a type. This is very
3393                --  strange of course, and can only happen as a result of
3394                --  certain illegalities, such as a premature attempt to derive
3395                --  from an incomplete type.
3396
3397                if Is_Type (Full_View (E)) then
3398                   Set_Size_Info (E, Full_View (E));
3399                   Set_RM_Size   (E, RM_Size (Full_View (E)));
3400                end if;
3401
3402                return Result;
3403
3404             --  Case of no full view present. If entity is derived or subtype,
3405             --  it is safe to freeze, correctness depends on the frozen status
3406             --  of parent. Otherwise it is either premature usage, or a Taft
3407             --  amendment type, so diagnosis is at the point of use and the
3408             --  type might be frozen later.
3409
3410             elsif E /= Base_Type (E)
3411               or else Is_Derived_Type (E)
3412             then
3413                null;
3414
3415             else
3416                Set_Is_Frozen (E, False);
3417                return No_List;
3418             end if;
3419
3420          --  For access subprogram, freeze types of all formals, the return
3421          --  type was already frozen, since it is the Etype of the function.
3422          --  Formal types can be tagged Taft amendment types, but otherwise
3423          --  they cannot be incomplete.
3424
3425          elsif Ekind (E) = E_Subprogram_Type then
3426             Formal := First_Formal (E);
3427
3428             while Present (Formal) loop
3429                if Ekind (Etype (Formal)) = E_Incomplete_Type
3430                  and then No (Full_View (Etype (Formal)))
3431                  and then not Is_Value_Type (Etype (Formal))
3432                then
3433                   if Is_Tagged_Type (Etype (Formal)) then
3434                      null;
3435                   else
3436                      Error_Msg_NE
3437                        ("invalid use of incomplete type&", E, Etype (Formal));
3438                   end if;
3439                end if;
3440
3441                Freeze_And_Append (Etype (Formal), Loc, Result);
3442                Next_Formal (Formal);
3443             end loop;
3444
3445             Freeze_Subprogram (E);
3446
3447          --  For access to a protected subprogram, freeze the equivalent type
3448          --  (however this is not set if we are not generating code or if this
3449          --  is an anonymous type used just for resolution).
3450
3451          elsif Is_Access_Protected_Subprogram_Type (E) then
3452             if Present (Equivalent_Type (E)) then
3453                Freeze_And_Append (Equivalent_Type (E), Loc, Result);
3454             end if;
3455          end if;
3456
3457          --  Generic types are never seen by the back-end, and are also not
3458          --  processed by the expander (since the expander is turned off for
3459          --  generic processing), so we never need freeze nodes for them.
3460
3461          if Is_Generic_Type (E) then
3462             return Result;
3463          end if;
3464
3465          --  Some special processing for non-generic types to complete
3466          --  representation details not known till the freeze point.
3467
3468          if Is_Fixed_Point_Type (E) then
3469             Freeze_Fixed_Point_Type (E);
3470
3471             --  Some error checks required for ordinary fixed-point type. Defer
3472             --  these till the freeze-point since we need the small and range
3473             --  values. We only do these checks for base types
3474
3475             if Is_Ordinary_Fixed_Point_Type (E)
3476               and then E = Base_Type (E)
3477             then
3478                if Small_Value (E) < Ureal_2_M_80 then
3479                   Error_Msg_Name_1 := Name_Small;
3480                   Error_Msg_N
3481                     ("`&''%` too small, minimum allowed is 2.0'*'*(-80)", E);
3482
3483                elsif Small_Value (E) > Ureal_2_80 then
3484                   Error_Msg_Name_1 := Name_Small;
3485                   Error_Msg_N
3486                     ("`&''%` too large, maximum allowed is 2.0'*'*80", E);
3487                end if;
3488
3489                if Expr_Value_R (Type_Low_Bound (E)) < Ureal_M_10_36 then
3490                   Error_Msg_Name_1 := Name_First;
3491                   Error_Msg_N
3492                     ("`&''%` too small, minimum allowed is -10.0'*'*36", E);
3493                end if;
3494
3495                if Expr_Value_R (Type_High_Bound (E)) > Ureal_10_36 then
3496                   Error_Msg_Name_1 := Name_Last;
3497                   Error_Msg_N
3498                     ("`&''%` too large, maximum allowed is 10.0'*'*36", E);
3499                end if;
3500             end if;
3501
3502          elsif Is_Enumeration_Type (E) then
3503             Freeze_Enumeration_Type (E);
3504
3505          elsif Is_Integer_Type (E) then
3506             Adjust_Esize_For_Alignment (E);
3507
3508          elsif Is_Access_Type (E) then
3509
3510             --  Check restriction for standard storage pool
3511
3512             if No (Associated_Storage_Pool (E)) then
3513                Check_Restriction (No_Standard_Storage_Pools, E);
3514             end if;
3515
3516             --  Deal with error message for pure access type. This is not an
3517             --  error in Ada 2005 if there is no pool (see AI-366).
3518
3519             if Is_Pure_Unit_Access_Type (E)
3520               and then (Ada_Version < Ada_05
3521                          or else not No_Pool_Assigned (E))
3522             then
3523                Error_Msg_N ("named access type not allowed in pure unit", E);
3524
3525                if Ada_Version >= Ada_05 then
3526                   Error_Msg_N
3527                     ("\would be legal if Storage_Size of 0 given?", E);
3528
3529                elsif No_Pool_Assigned (E) then
3530                   Error_Msg_N
3531                     ("\would be legal in Ada 2005?", E);
3532
3533                else
3534                   Error_Msg_N
3535                     ("\would be legal in Ada 2005 if "
3536                      & "Storage_Size of 0 given?", E);
3537                end if;
3538             end if;
3539          end if;
3540
3541          --  Case of composite types
3542
3543          if Is_Composite_Type (E) then
3544
3545             --  AI-117 requires that all new primitives of a tagged type must
3546             --  inherit the convention of the full view of the type. Inherited
3547             --  and overriding operations are defined to inherit the convention
3548             --  of their parent or overridden subprogram (also specified in
3549             --  AI-117), which will have occurred earlier (in Derive_Subprogram
3550             --  and New_Overloaded_Entity). Here we set the convention of
3551             --  primitives that are still convention Ada, which will ensure
3552             --  that any new primitives inherit the type's convention. Class-
3553             --  wide types can have a foreign convention inherited from their
3554             --  specific type, but are excluded from this since they don't have
3555             --  any associated primitives.
3556
3557             if Is_Tagged_Type (E)
3558               and then not Is_Class_Wide_Type (E)
3559               and then Convention (E) /= Convention_Ada
3560             then
3561                declare
3562                   Prim_List : constant Elist_Id := Primitive_Operations (E);
3563                   Prim      : Elmt_Id;
3564                begin
3565                   Prim := First_Elmt (Prim_List);
3566                   while Present (Prim) loop
3567                      if Convention (Node (Prim)) = Convention_Ada then
3568                         Set_Convention (Node (Prim), Convention (E));
3569                      end if;
3570
3571                      Next_Elmt (Prim);
3572                   end loop;
3573                end;
3574             end if;
3575          end if;
3576
3577          --  Now that all types from which E may depend are frozen, see if the
3578          --  size is known at compile time, if it must be unsigned, or if
3579          --  strict alignment is required
3580
3581          Check_Compile_Time_Size (E);
3582          Check_Unsigned_Type (E);
3583
3584          if Base_Type (E) = E then
3585             Check_Strict_Alignment (E);
3586          end if;
3587
3588          --  Do not allow a size clause for a type which does not have a size
3589          --  that is known at compile time
3590
3591          if Has_Size_Clause (E)
3592            and then not Size_Known_At_Compile_Time (E)
3593          then
3594             --  Suppress this message if errors posted on E, even if we are
3595             --  in all errors mode, since this is often a junk message
3596
3597             if not Error_Posted (E) then
3598                Error_Msg_N
3599                  ("size clause not allowed for variable length type",
3600                   Size_Clause (E));
3601             end if;
3602          end if;
3603
3604          --  Remaining process is to set/verify the representation information,
3605          --  in particular the size and alignment values. This processing is
3606          --  not required for generic types, since generic types do not play
3607          --  any part in code generation, and so the size and alignment values
3608          --  for such types are irrelevant.
3609
3610          if Is_Generic_Type (E) then
3611             return Result;
3612
3613          --  Otherwise we call the layout procedure
3614
3615          else
3616             Layout_Type (E);
3617          end if;
3618
3619          --  End of freeze processing for type entities
3620       end if;
3621
3622       --  Here is where we logically freeze the current entity. If it has a
3623       --  freeze node, then this is the point at which the freeze node is
3624       --  linked into the result list.
3625
3626       if Has_Delayed_Freeze (E) then
3627
3628          --  If a freeze node is already allocated, use it, otherwise allocate
3629          --  a new one. The preallocation happens in the case of anonymous base
3630          --  types, where we preallocate so that we can set First_Subtype_Link.
3631          --  Note that we reset the Sloc to the current freeze location.
3632
3633          if Present (Freeze_Node (E)) then
3634             F_Node := Freeze_Node (E);
3635             Set_Sloc (F_Node, Loc);
3636
3637          else
3638             F_Node := New_Node (N_Freeze_Entity, Loc);
3639             Set_Freeze_Node (E, F_Node);
3640             Set_Access_Types_To_Process (F_Node, No_Elist);
3641             Set_TSS_Elist (F_Node, No_Elist);
3642             Set_Actions (F_Node, No_List);
3643          end if;
3644
3645          Set_Entity (F_Node, E);
3646
3647          if Result = No_List then
3648             Result := New_List (F_Node);
3649          else
3650             Append (F_Node, Result);
3651          end if;
3652
3653          --  A final pass over record types with discriminants. If the type
3654          --  has an incomplete declaration, there may be constrained access
3655          --  subtypes declared elsewhere, which do not depend on the discrimi-
3656          --  nants of the type, and which are used as component types (i.e.
3657          --  the full view is a recursive type). The designated types of these
3658          --  subtypes can only be elaborated after the type itself, and they
3659          --  need an itype reference.
3660
3661          if Ekind (E) = E_Record_Type
3662            and then Has_Discriminants (E)
3663          then
3664             declare
3665                Comp : Entity_Id;
3666                IR   : Node_Id;
3667                Typ  : Entity_Id;
3668
3669             begin
3670                Comp := First_Component (E);
3671
3672                while Present (Comp) loop
3673                   Typ  := Etype (Comp);
3674
3675                   if Ekind (Comp) = E_Component
3676                     and then Is_Access_Type (Typ)
3677                     and then Scope (Typ) /= E
3678                     and then Base_Type (Designated_Type (Typ)) = E
3679                     and then Is_Itype (Designated_Type (Typ))
3680                   then
3681                      IR := Make_Itype_Reference (Sloc (Comp));
3682                      Set_Itype (IR, Designated_Type (Typ));
3683                      Append (IR, Result);
3684                   end if;
3685
3686                   Next_Component (Comp);
3687                end loop;
3688             end;
3689          end if;
3690       end if;
3691
3692       --  When a type is frozen, the first subtype of the type is frozen as
3693       --  well (RM 13.14(15)). This has to be done after freezing the type,
3694       --  since obviously the first subtype depends on its own base type.
3695
3696       if Is_Type (E) then
3697          Freeze_And_Append (First_Subtype (E), Loc, Result);
3698
3699          --  If we just froze a tagged non-class wide record, then freeze the
3700          --  corresponding class-wide type. This must be done after the tagged
3701          --  type itself is frozen, because the class-wide type refers to the
3702          --  tagged type which generates the class.
3703
3704          if Is_Tagged_Type (E)
3705            and then not Is_Class_Wide_Type (E)
3706            and then Present (Class_Wide_Type (E))
3707          then
3708             Freeze_And_Append (Class_Wide_Type (E), Loc, Result);
3709          end if;
3710       end if;
3711
3712       Check_Debug_Info_Needed (E);
3713
3714       --  Special handling for subprograms
3715
3716       if Is_Subprogram (E) then
3717
3718          --  If subprogram has address clause then reset Is_Public flag, since
3719          --  we do not want the backend to generate external references.
3720
3721          if Present (Address_Clause (E))
3722            and then not Is_Library_Level_Entity (E)
3723          then
3724             Set_Is_Public (E, False);
3725
3726          --  If no address clause and not intrinsic, then for imported
3727          --  subprogram in main unit, generate descriptor if we are in
3728          --  Propagate_Exceptions mode.
3729
3730          elsif Propagate_Exceptions
3731            and then Is_Imported (E)
3732            and then not Is_Intrinsic_Subprogram (E)
3733            and then Convention (E) /= Convention_Stubbed
3734          then
3735             if Result = No_List then
3736                Result := Empty_List;
3737             end if;
3738          end if;
3739       end if;
3740
3741       return Result;
3742    end Freeze_Entity;
3743
3744    -----------------------------
3745    -- Freeze_Enumeration_Type --
3746    -----------------------------
3747
3748    procedure Freeze_Enumeration_Type (Typ : Entity_Id) is
3749    begin
3750       --  By default, if no size clause is present, an enumeration type with
3751       --  Convention C is assumed to interface to a C enum, and has integer
3752       --  size. This applies to types. For subtypes, verify that its base
3753       --  type has no size clause either.
3754
3755       if Has_Foreign_Convention (Typ)
3756         and then not Has_Size_Clause (Typ)
3757         and then not Has_Size_Clause (Base_Type (Typ))
3758         and then Esize (Typ) < Standard_Integer_Size
3759       then
3760          Init_Esize (Typ, Standard_Integer_Size);
3761
3762       else
3763          --  If the enumeration type interfaces to C, and it has a size clause
3764          --  that specifies less than int size, it warrants a warning. The
3765          --  user may intend the C type to be an enum or a char, so this is
3766          --  not by itself an error that the Ada compiler can detect, but it
3767          --  it is a worth a heads-up. For Boolean and Character types we
3768          --  assume that the programmer has the proper C type in mind.
3769
3770          if Convention (Typ) = Convention_C
3771            and then Has_Size_Clause (Typ)
3772            and then Esize (Typ) /= Esize (Standard_Integer)
3773            and then not Is_Boolean_Type (Typ)
3774            and then not Is_Character_Type (Typ)
3775          then
3776             Error_Msg_N
3777               ("C enum types have the size of a C int?", Size_Clause (Typ));
3778          end if;
3779
3780          Adjust_Esize_For_Alignment (Typ);
3781       end if;
3782    end Freeze_Enumeration_Type;
3783
3784    -----------------------
3785    -- Freeze_Expression --
3786    -----------------------
3787
3788    procedure Freeze_Expression (N : Node_Id) is
3789       In_Spec_Exp : constant Boolean := In_Spec_Expression;
3790       Typ         : Entity_Id;
3791       Nam         : Entity_Id;
3792       Desig_Typ   : Entity_Id;
3793       P           : Node_Id;
3794       Parent_P    : Node_Id;
3795
3796       Freeze_Outside : Boolean := False;
3797       --  This flag is set true if the entity must be frozen outside the
3798       --  current subprogram. This happens in the case of expander generated
3799       --  subprograms (_Init_Proc, _Input, _Output, _Read, _Write) which do
3800       --  not freeze all entities like other bodies, but which nevertheless
3801       --  may reference entities that have to be frozen before the body and
3802       --  obviously cannot be frozen inside the body.
3803
3804       function In_Exp_Body (N : Node_Id) return Boolean;
3805       --  Given an N_Handled_Sequence_Of_Statements node N, determines whether
3806       --  it is the handled statement sequence of an expander-generated
3807       --  subprogram (init proc, stream subprogram, or renaming as body).
3808       --  If so, this is not a freezing context.
3809
3810       -----------------
3811       -- In_Exp_Body --
3812       -----------------
3813
3814       function In_Exp_Body (N : Node_Id) return Boolean is
3815          P  : Node_Id;
3816          Id : Entity_Id;
3817
3818       begin
3819          if Nkind (N) = N_Subprogram_Body then
3820             P := N;
3821          else
3822             P := Parent (N);
3823          end if;
3824
3825          if Nkind (P) /= N_Subprogram_Body then
3826             return False;
3827
3828          else
3829             Id := Defining_Unit_Name (Specification (P));
3830
3831             if Nkind (Id) = N_Defining_Identifier
3832               and then (Is_Init_Proc (Id)              or else
3833                         Is_TSS (Id, TSS_Stream_Input)  or else
3834                         Is_TSS (Id, TSS_Stream_Output) or else
3835                         Is_TSS (Id, TSS_Stream_Read)   or else
3836                         Is_TSS (Id, TSS_Stream_Write)  or else
3837                         Nkind (Original_Node (P)) =
3838                           N_Subprogram_Renaming_Declaration)
3839             then
3840                return True;
3841             else
3842                return False;
3843             end if;
3844          end if;
3845       end In_Exp_Body;
3846
3847    --  Start of processing for Freeze_Expression
3848
3849    begin
3850       --  Immediate return if freezing is inhibited. This flag is set by the
3851       --  analyzer to stop freezing on generated expressions that would cause
3852       --  freezing if they were in the source program, but which are not
3853       --  supposed to freeze, since they are created.
3854
3855       if Must_Not_Freeze (N) then
3856          return;
3857       end if;
3858
3859       --  If expression is non-static, then it does not freeze in a default
3860       --  expression, see section "Handling of Default Expressions" in the
3861       --  spec of package Sem for further details. Note that we have to
3862       --  make sure that we actually have a real expression (if we have
3863       --  a subtype indication, we can't test Is_Static_Expression!)
3864
3865       if In_Spec_Exp
3866         and then Nkind (N) in N_Subexpr
3867         and then not Is_Static_Expression (N)
3868       then
3869          return;
3870       end if;
3871
3872       --  Freeze type of expression if not frozen already
3873
3874       Typ := Empty;
3875
3876       if Nkind (N) in N_Has_Etype then
3877          if not Is_Frozen (Etype (N)) then
3878             Typ := Etype (N);
3879
3880          --  Base type may be an derived numeric type that is frozen at
3881          --  the point of declaration, but first_subtype is still unfrozen.
3882
3883          elsif not Is_Frozen (First_Subtype (Etype (N))) then
3884             Typ := First_Subtype (Etype (N));
3885          end if;
3886       end if;
3887
3888       --  For entity name, freeze entity if not frozen already. A special
3889       --  exception occurs for an identifier that did not come from source.
3890       --  We don't let such identifiers freeze a non-internal entity, i.e.
3891       --  an entity that did come from source, since such an identifier was
3892       --  generated by the expander, and cannot have any semantic effect on
3893       --  the freezing semantics. For example, this stops the parameter of
3894       --  an initialization procedure from freezing the variable.
3895
3896       if Is_Entity_Name (N)
3897         and then not Is_Frozen (Entity (N))
3898         and then (Nkind (N) /= N_Identifier
3899                    or else Comes_From_Source (N)
3900                    or else not Comes_From_Source (Entity (N)))
3901       then
3902          Nam := Entity (N);
3903       else
3904          Nam := Empty;
3905       end if;
3906
3907       --  For an allocator freeze designated type if not frozen already
3908
3909       --  For an aggregate whose component type is an access type, freeze the
3910       --  designated type now, so that its freeze does not appear within the
3911       --  loop that might be created in the expansion of the aggregate. If the
3912       --  designated type is a private type without full view, the expression
3913       --  cannot contain an allocator, so the type is not frozen.
3914
3915       Desig_Typ := Empty;
3916
3917       case Nkind (N) is
3918          when N_Allocator =>
3919             Desig_Typ := Designated_Type (Etype (N));
3920
3921          when N_Aggregate =>
3922             if Is_Array_Type (Etype (N))
3923               and then Is_Access_Type (Component_Type (Etype (N)))
3924             then
3925                Desig_Typ := Designated_Type (Component_Type (Etype (N)));
3926             end if;
3927
3928          when N_Selected_Component |
3929             N_Indexed_Component    |
3930             N_Slice                =>
3931
3932             if Is_Access_Type (Etype (Prefix (N))) then
3933                Desig_Typ := Designated_Type (Etype (Prefix (N)));
3934             end if;
3935
3936          when others =>
3937             null;
3938       end case;
3939
3940       if Desig_Typ /= Empty
3941         and then (Is_Frozen (Desig_Typ)
3942                    or else (not Is_Fully_Defined (Desig_Typ)))
3943       then
3944          Desig_Typ := Empty;
3945       end if;
3946
3947       --  All done if nothing needs freezing
3948
3949       if No (Typ)
3950         and then No (Nam)
3951         and then No (Desig_Typ)
3952       then
3953          return;
3954       end if;
3955
3956       --  Loop for looking at the right place to insert the freeze nodes
3957       --  exiting from the loop when it is appropriate to insert the freeze
3958       --  node before the current node P.
3959
3960       --  Also checks some special exceptions to the freezing rules. These
3961       --  cases result in a direct return, bypassing the freeze action.
3962
3963       P := N;
3964       loop
3965          Parent_P := Parent (P);
3966
3967          --  If we don't have a parent, then we are not in a well-formed tree.
3968          --  This is an unusual case, but there are some legitimate situations
3969          --  in which this occurs, notably when the expressions in the range of
3970          --  a type declaration are resolved. We simply ignore the freeze
3971          --  request in this case. Is this right ???
3972
3973          if No (Parent_P) then
3974             return;
3975          end if;
3976
3977          --  See if we have got to an appropriate point in the tree
3978
3979          case Nkind (Parent_P) is
3980
3981             --  A special test for the exception of (RM 13.14(8)) for the case
3982             --  of per-object expressions (RM 3.8(18)) occurring in component
3983             --  definition or a discrete subtype definition. Note that we test
3984             --  for a component declaration which includes both cases we are
3985             --  interested in, and furthermore the tree does not have explicit
3986             --  nodes for either of these two constructs.
3987
3988             when N_Component_Declaration =>
3989
3990                --  The case we want to test for here is an identifier that is
3991                --  a per-object expression, this is either a discriminant that
3992                --  appears in a context other than the component declaration
3993                --  or it is a reference to the type of the enclosing construct.
3994
3995                --  For either of these cases, we skip the freezing
3996
3997                if not In_Spec_Expression
3998                  and then Nkind (N) = N_Identifier
3999                  and then (Present (Entity (N)))
4000                then
4001                   --  We recognize the discriminant case by just looking for
4002                   --  a reference to a discriminant. It can only be one for
4003                   --  the enclosing construct. Skip freezing in this case.
4004
4005                   if Ekind (Entity (N)) = E_Discriminant then
4006                      return;
4007
4008                   --  For the case of a reference to the enclosing record,
4009                   --  (or task or protected type), we look for a type that
4010                   --  matches the current scope.
4011
4012                   elsif Entity (N) = Current_Scope then
4013                      return;
4014                   end if;
4015                end if;
4016
4017             --  If we have an enumeration literal that appears as the choice in
4018             --  the aggregate of an enumeration representation clause, then
4019             --  freezing does not occur (RM 13.14(10)).
4020
4021             when N_Enumeration_Representation_Clause =>
4022
4023                --  The case we are looking for is an enumeration literal
4024
4025                if (Nkind (N) = N_Identifier or Nkind (N) = N_Character_Literal)
4026                  and then Is_Enumeration_Type (Etype (N))
4027                then
4028                   --  If enumeration literal appears directly as the choice,
4029                   --  do not freeze (this is the normal non-overloaded case)
4030
4031                   if Nkind (Parent (N)) = N_Component_Association
4032                     and then First (Choices (Parent (N))) = N
4033                   then
4034                      return;
4035
4036                   --  If enumeration literal appears as the name of function
4037                   --  which is the choice, then also do not freeze. This
4038                   --  happens in the overloaded literal case, where the
4039                   --  enumeration literal is temporarily changed to a function
4040                   --  call for overloading analysis purposes.
4041
4042                   elsif Nkind (Parent (N)) = N_Function_Call
4043                      and then
4044                        Nkind (Parent (Parent (N))) = N_Component_Association
4045                      and then
4046                        First (Choices (Parent (Parent (N)))) = Parent (N)
4047                   then
4048                      return;
4049                   end if;
4050                end if;
4051
4052             --  Normally if the parent is a handled sequence of statements,
4053             --  then the current node must be a statement, and that is an
4054             --  appropriate place to insert a freeze node.
4055
4056             when N_Handled_Sequence_Of_Statements =>
4057
4058                --  An exception occurs when the sequence of statements is for
4059                --  an expander generated body that did not do the usual freeze
4060                --  all operation. In this case we usually want to freeze
4061                --  outside this body, not inside it, and we skip past the
4062                --  subprogram body that we are inside.
4063
4064                if In_Exp_Body (Parent_P) then
4065
4066                   --  However, we *do* want to freeze at this point if we have
4067                   --  an entity to freeze, and that entity is declared *inside*
4068                   --  the body of the expander generated procedure. This case
4069                   --  is recognized by the scope of the type, which is either
4070                   --  the spec for some enclosing body, or (in the case of
4071                   --  init_procs, for which there are no separate specs) the
4072                   --  current scope.
4073
4074                   declare
4075                      Subp : constant Node_Id := Parent (Parent_P);
4076                      Cspc : Entity_Id;
4077
4078                   begin
4079                      if Nkind (Subp) = N_Subprogram_Body then
4080                         Cspc := Corresponding_Spec (Subp);
4081
4082                         if (Present (Typ) and then Scope (Typ) = Cspc)
4083                              or else
4084                            (Present (Nam) and then Scope (Nam) = Cspc)
4085                         then
4086                            exit;
4087
4088                         elsif Present (Typ)
4089                           and then Scope (Typ) = Current_Scope
4090                           and then Current_Scope = Defining_Entity (Subp)
4091                         then
4092                            exit;
4093                         end if;
4094                      end if;
4095                   end;
4096
4097                   --  If not that exception to the exception, then this is
4098                   --  where we delay the freeze till outside the body.
4099
4100                   Parent_P := Parent (Parent_P);
4101                   Freeze_Outside := True;
4102
4103                --  Here if normal case where we are in handled statement
4104                --  sequence and want to do the insertion right there.
4105
4106                else
4107                   exit;
4108                end if;
4109
4110             --  If parent is a body or a spec or a block, then the current node
4111             --  is a statement or declaration and we can insert the freeze node
4112             --  before it.
4113
4114             when N_Package_Specification |
4115                  N_Package_Body          |
4116                  N_Subprogram_Body       |
4117                  N_Task_Body             |
4118                  N_Protected_Body        |
4119                  N_Entry_Body            |
4120                  N_Block_Statement       => exit;
4121
4122             --  The expander is allowed to define types in any statements list,
4123             --  so any of the following parent nodes also mark a freezing point
4124             --  if the actual node is in a list of statements or declarations.
4125
4126             when N_Exception_Handler          |
4127                  N_If_Statement               |
4128                  N_Elsif_Part                 |
4129                  N_Case_Statement_Alternative |
4130                  N_Compilation_Unit_Aux       |
4131                  N_Selective_Accept           |
4132                  N_Accept_Alternative         |
4133                  N_Delay_Alternative          |
4134                  N_Conditional_Entry_Call     |
4135                  N_Entry_Call_Alternative     |
4136                  N_Triggering_Alternative     |
4137                  N_Abortable_Part             |
4138                  N_Freeze_Entity              =>
4139
4140                exit when Is_List_Member (P);
4141
4142             --  Note: The N_Loop_Statement is a special case. A type that
4143             --  appears in the source can never be frozen in a loop (this
4144             --  occurs only because of a loop expanded by the expander), so we
4145             --  keep on going. Otherwise we terminate the search. Same is true
4146             --  of any entity which comes from source. (if they have predefined
4147             --  type, that type does not appear to come from source, but the
4148             --  entity should not be frozen here).
4149
4150             when N_Loop_Statement =>
4151                exit when not Comes_From_Source (Etype (N))
4152                  and then (No (Nam) or else not Comes_From_Source (Nam));
4153
4154             --  For all other cases, keep looking at parents
4155
4156             when others =>
4157                null;
4158          end case;
4159
4160          --  We fall through the case if we did not yet find the proper
4161          --  place in the free for inserting the freeze node, so climb!
4162
4163          P := Parent_P;
4164       end loop;
4165
4166       --  If the expression appears in a record or an initialization procedure,
4167       --  the freeze nodes are collected and attached to the current scope, to
4168       --  be inserted and analyzed on exit from the scope, to insure that
4169       --  generated entities appear in the correct scope. If the expression is
4170       --  a default for a discriminant specification, the scope is still void.
4171       --  The expression can also appear in the discriminant part of a private
4172       --  or concurrent type.
4173
4174       --  If the expression appears in a constrained subcomponent of an
4175       --  enclosing record declaration, the freeze nodes must be attached to
4176       --  the outer record type so they can eventually be placed in the
4177       --  enclosing declaration list.
4178
4179       --  The other case requiring this special handling is if we are in a
4180       --  default expression, since in that case we are about to freeze a
4181       --  static type, and the freeze scope needs to be the outer scope, not
4182       --  the scope of the subprogram with the default parameter.
4183
4184       --  For default expressions and other spec expressions in generic units,
4185       --  the Move_Freeze_Nodes mechanism (see sem_ch12.adb) takes care of
4186       --  placing them at the proper place, after the generic unit.
4187
4188       if (In_Spec_Exp and not Inside_A_Generic)
4189         or else Freeze_Outside
4190         or else (Is_Type (Current_Scope)
4191                   and then (not Is_Concurrent_Type (Current_Scope)
4192                              or else not Has_Completion (Current_Scope)))
4193         or else Ekind (Current_Scope) = E_Void
4194       then
4195          declare
4196             Loc          : constant Source_Ptr := Sloc (Current_Scope);
4197             Freeze_Nodes : List_Id := No_List;
4198             Pos          : Int := Scope_Stack.Last;
4199
4200          begin
4201             if Present (Desig_Typ) then
4202                Freeze_And_Append (Desig_Typ, Loc, Freeze_Nodes);
4203             end if;
4204
4205             if Present (Typ) then
4206                Freeze_And_Append (Typ, Loc, Freeze_Nodes);
4207             end if;
4208
4209             if Present (Nam) then
4210                Freeze_And_Append (Nam, Loc, Freeze_Nodes);
4211             end if;
4212
4213             --  The current scope may be that of a constrained component of
4214             --  an enclosing record declaration, which is above the current
4215             --  scope in the scope stack.
4216
4217             if Is_Record_Type (Scope (Current_Scope)) then
4218                Pos := Pos - 1;
4219             end if;
4220
4221             if Is_Non_Empty_List (Freeze_Nodes) then
4222                if No (Scope_Stack.Table (Pos).Pending_Freeze_Actions) then
4223                   Scope_Stack.Table (Pos).Pending_Freeze_Actions :=
4224                       Freeze_Nodes;
4225                else
4226                   Append_List (Freeze_Nodes, Scope_Stack.Table
4227                                    (Pos).Pending_Freeze_Actions);
4228                end if;
4229             end if;
4230          end;
4231
4232          return;
4233       end if;
4234
4235       --  Now we have the right place to do the freezing. First, a special
4236       --  adjustment, if we are in spec-expression analysis mode, these freeze
4237       --  actions must not be thrown away (normally all inserted actions are
4238       --  thrown away in this mode. However, the freeze actions are from static
4239       --  expressions and one of the important reasons we are doing this
4240       --  special analysis is to get these freeze actions. Therefore we turn
4241       --  off the In_Spec_Expression mode to propagate these freeze actions.
4242       --  This also means they get properly analyzed and expanded.
4243
4244       In_Spec_Expression := False;
4245
4246       --  Freeze the designated type of an allocator (RM 13.14(13))
4247
4248       if Present (Desig_Typ) then
4249          Freeze_Before (P, Desig_Typ);
4250       end if;
4251
4252       --  Freeze type of expression (RM 13.14(10)). Note that we took care of
4253       --  the enumeration representation clause exception in the loop above.
4254
4255       if Present (Typ) then
4256          Freeze_Before (P, Typ);
4257       end if;
4258
4259       --  Freeze name if one is present (RM 13.14(11))
4260
4261       if Present (Nam) then
4262          Freeze_Before (P, Nam);
4263       end if;
4264
4265       --  Restore In_Spec_Expression flag
4266
4267       In_Spec_Expression := In_Spec_Exp;
4268    end Freeze_Expression;
4269
4270    -----------------------------
4271    -- Freeze_Fixed_Point_Type --
4272    -----------------------------
4273
4274    --  Certain fixed-point types and subtypes, including implicit base types
4275    --  and declared first subtypes, have not yet set up a range. This is
4276    --  because the range cannot be set until the Small and Size values are
4277    --  known, and these are not known till the type is frozen.
4278
4279    --  To signal this case, Scalar_Range contains an unanalyzed syntactic range
4280    --  whose bounds are unanalyzed real literals. This routine will recognize
4281    --  this case, and transform this range node into a properly typed range
4282    --  with properly analyzed and resolved values.
4283
4284    procedure Freeze_Fixed_Point_Type (Typ : Entity_Id) is
4285       Rng   : constant Node_Id    := Scalar_Range (Typ);
4286       Lo    : constant Node_Id    := Low_Bound (Rng);
4287       Hi    : constant Node_Id    := High_Bound (Rng);
4288       Btyp  : constant Entity_Id  := Base_Type (Typ);
4289       Brng  : constant Node_Id    := Scalar_Range (Btyp);
4290       BLo   : constant Node_Id    := Low_Bound (Brng);
4291       BHi   : constant Node_Id    := High_Bound (Brng);
4292       Small : constant Ureal      := Small_Value (Typ);
4293       Loval : Ureal;
4294       Hival : Ureal;
4295       Atype : Entity_Id;
4296
4297       Actual_Size : Nat;
4298
4299       function Fsize (Lov, Hiv : Ureal) return Nat;
4300       --  Returns size of type with given bounds. Also leaves these
4301       --  bounds set as the current bounds of the Typ.
4302
4303       -----------
4304       -- Fsize --
4305       -----------
4306
4307       function Fsize (Lov, Hiv : Ureal) return Nat is
4308       begin
4309          Set_Realval (Lo, Lov);
4310          Set_Realval (Hi, Hiv);
4311          return Minimum_Size (Typ);
4312       end Fsize;
4313
4314    --  Start of processing for Freeze_Fixed_Point_Type
4315
4316    begin
4317       --  If Esize of a subtype has not previously been set, set it now
4318
4319       if Unknown_Esize (Typ) then
4320          Atype := Ancestor_Subtype (Typ);
4321
4322          if Present (Atype) then
4323             Set_Esize (Typ, Esize (Atype));
4324          else
4325             Set_Esize (Typ, Esize (Base_Type (Typ)));
4326          end if;
4327       end if;
4328
4329       --  Immediate return if the range is already analyzed. This means that
4330       --  the range is already set, and does not need to be computed by this
4331       --  routine.
4332
4333       if Analyzed (Rng) then
4334          return;
4335       end if;
4336
4337       --  Immediate return if either of the bounds raises Constraint_Error
4338
4339       if Raises_Constraint_Error (Lo)
4340         or else Raises_Constraint_Error (Hi)
4341       then
4342          return;
4343       end if;
4344
4345       Loval := Realval (Lo);
4346       Hival := Realval (Hi);
4347
4348       --  Ordinary fixed-point case
4349
4350       if Is_Ordinary_Fixed_Point_Type (Typ) then
4351
4352          --  For the ordinary fixed-point case, we are allowed to fudge the
4353          --  end-points up or down by small. Generally we prefer to fudge up,
4354          --  i.e. widen the bounds for non-model numbers so that the end points
4355          --  are included. However there are cases in which this cannot be
4356          --  done, and indeed cases in which we may need to narrow the bounds.
4357          --  The following circuit makes the decision.
4358
4359          --  Note: our terminology here is that Incl_EP means that the bounds
4360          --  are widened by Small if necessary to include the end points, and
4361          --  Excl_EP means that the bounds are narrowed by Small to exclude the
4362          --  end-points if this reduces the size.
4363
4364          --  Note that in the Incl case, all we care about is including the
4365          --  end-points. In the Excl case, we want to narrow the bounds as
4366          --  much as permitted by the RM, to give the smallest possible size.
4367
4368          Fudge : declare
4369             Loval_Incl_EP : Ureal;
4370             Hival_Incl_EP : Ureal;
4371
4372             Loval_Excl_EP : Ureal;
4373             Hival_Excl_EP : Ureal;
4374
4375             Size_Incl_EP  : Nat;
4376             Size_Excl_EP  : Nat;
4377
4378             Model_Num     : Ureal;
4379             First_Subt    : Entity_Id;
4380             Actual_Lo     : Ureal;
4381             Actual_Hi     : Ureal;
4382
4383          begin
4384             --  First step. Base types are required to be symmetrical. Right
4385             --  now, the base type range is a copy of the first subtype range.
4386             --  This will be corrected before we are done, but right away we
4387             --  need to deal with the case where both bounds are non-negative.
4388             --  In this case, we set the low bound to the negative of the high
4389             --  bound, to make sure that the size is computed to include the
4390             --  required sign. Note that we do not need to worry about the
4391             --  case of both bounds negative, because the sign will be dealt
4392             --  with anyway. Furthermore we can't just go making such a bound
4393             --  symmetrical, since in a twos-complement system, there is an
4394             --  extra negative value which could not be accommodated on the
4395             --  positive side.
4396
4397             if Typ = Btyp
4398               and then not UR_Is_Negative (Loval)
4399               and then Hival > Loval
4400             then
4401                Loval := -Hival;
4402                Set_Realval (Lo, Loval);
4403             end if;
4404
4405             --  Compute the fudged bounds. If the number is a model number,
4406             --  then we do nothing to include it, but we are allowed to backoff
4407             --  to the next adjacent model number when we exclude it. If it is
4408             --  not a model number then we straddle the two values with the
4409             --  model numbers on either side.
4410
4411             Model_Num := UR_Trunc (Loval / Small) * Small;
4412
4413             if Loval = Model_Num then
4414                Loval_Incl_EP := Model_Num;
4415             else
4416                Loval_Incl_EP := Model_Num - Small;
4417             end if;
4418
4419             --  The low value excluding the end point is Small greater, but
4420             --  we do not do this exclusion if the low value is positive,
4421             --  since it can't help the size and could actually hurt by
4422             --  crossing the high bound.
4423
4424             if UR_Is_Negative (Loval_Incl_EP) then
4425                Loval_Excl_EP := Loval_Incl_EP + Small;
4426
4427                --  If the value went from negative to zero, then we have the
4428                --  case where Loval_Incl_EP is the model number just below
4429                --  zero, so we want to stick to the negative value for the
4430                --  base type to maintain the condition that the size will
4431                --  include signed values.
4432
4433                if Typ = Btyp
4434                  and then UR_Is_Zero (Loval_Excl_EP)
4435                then
4436                   Loval_Excl_EP := Loval_Incl_EP;
4437                end if;
4438
4439             else
4440                Loval_Excl_EP := Loval_Incl_EP;
4441             end if;
4442
4443             --  Similar processing for upper bound and high value
4444
4445             Model_Num := UR_Trunc (Hival / Small) * Small;
4446
4447             if Hival = Model_Num then
4448                Hival_Incl_EP := Model_Num;
4449             else
4450                Hival_Incl_EP := Model_Num + Small;
4451             end if;
4452
4453             if UR_Is_Positive (Hival_Incl_EP) then
4454                Hival_Excl_EP := Hival_Incl_EP - Small;
4455             else
4456                Hival_Excl_EP := Hival_Incl_EP;
4457             end if;
4458
4459             --  One further adjustment is needed. In the case of subtypes, we
4460             --  cannot go outside the range of the base type, or we get
4461             --  peculiarities, and the base type range is already set. This
4462             --  only applies to the Incl values, since clearly the Excl values
4463             --  are already as restricted as they are allowed to be.
4464
4465             if Typ /= Btyp then
4466                Loval_Incl_EP := UR_Max (Loval_Incl_EP, Realval (BLo));
4467                Hival_Incl_EP := UR_Min (Hival_Incl_EP, Realval (BHi));
4468             end if;
4469
4470             --  Get size including and excluding end points
4471
4472             Size_Incl_EP := Fsize (Loval_Incl_EP, Hival_Incl_EP);
4473             Size_Excl_EP := Fsize (Loval_Excl_EP, Hival_Excl_EP);
4474
4475             --  No need to exclude end-points if it does not reduce size
4476
4477             if Fsize (Loval_Incl_EP, Hival_Excl_EP) = Size_Excl_EP then
4478                Loval_Excl_EP := Loval_Incl_EP;
4479             end if;
4480
4481             if Fsize (Loval_Excl_EP, Hival_Incl_EP) = Size_Excl_EP then
4482                Hival_Excl_EP := Hival_Incl_EP;
4483             end if;
4484
4485             --  Now we set the actual size to be used. We want to use the
4486             --  bounds fudged up to include the end-points but only if this
4487             --  can be done without violating a specifically given size
4488             --  size clause or causing an unacceptable increase in size.
4489
4490             --  Case of size clause given
4491
4492             if Has_Size_Clause (Typ) then
4493
4494                --  Use the inclusive size only if it is consistent with
4495                --  the explicitly specified size.
4496
4497                if Size_Incl_EP <= RM_Size (Typ) then
4498                   Actual_Lo   := Loval_Incl_EP;
4499                   Actual_Hi   := Hival_Incl_EP;
4500                   Actual_Size := Size_Incl_EP;
4501
4502                --  If the inclusive size is too large, we try excluding
4503                --  the end-points (will be caught later if does not work).
4504
4505                else
4506                   Actual_Lo   := Loval_Excl_EP;
4507                   Actual_Hi   := Hival_Excl_EP;
4508                   Actual_Size := Size_Excl_EP;
4509                end if;
4510
4511             --  Case of size clause not given
4512
4513             else
4514                --  If we have a base type whose corresponding first subtype
4515                --  has an explicit size that is large enough to include our
4516                --  end-points, then do so. There is no point in working hard
4517                --  to get a base type whose size is smaller than the specified
4518                --  size of the first subtype.
4519
4520                First_Subt := First_Subtype (Typ);
4521
4522                if Has_Size_Clause (First_Subt)
4523                  and then Size_Incl_EP <= Esize (First_Subt)
4524                then
4525                   Actual_Size := Size_Incl_EP;
4526                   Actual_Lo   := Loval_Incl_EP;
4527                   Actual_Hi   := Hival_Incl_EP;
4528
4529                --  If excluding the end-points makes the size smaller and
4530                --  results in a size of 8,16,32,64, then we take the smaller
4531                --  size. For the 64 case, this is compulsory. For the other
4532                --  cases, it seems reasonable. We like to include end points
4533                --  if we can, but not at the expense of moving to the next
4534                --  natural boundary of size.
4535
4536                elsif Size_Incl_EP /= Size_Excl_EP
4537                  and then
4538                     (Size_Excl_EP = 8  or else
4539                      Size_Excl_EP = 16 or else
4540                      Size_Excl_EP = 32 or else
4541                      Size_Excl_EP = 64)
4542                then
4543                   Actual_Size := Size_Excl_EP;
4544                   Actual_Lo   := Loval_Excl_EP;
4545                   Actual_Hi   := Hival_Excl_EP;
4546
4547                --  Otherwise we can definitely include the end points
4548
4549                else
4550                   Actual_Size := Size_Incl_EP;
4551                   Actual_Lo   := Loval_Incl_EP;
4552                   Actual_Hi   := Hival_Incl_EP;
4553                end if;
4554
4555                --  One pathological case: normally we never fudge a low bound
4556                --  down, since it would seem to increase the size (if it has
4557                --  any effect), but for ranges containing single value, or no
4558                --  values, the high bound can be small too large. Consider:
4559
4560                --    type t is delta 2.0**(-14)
4561                --      range 131072.0 .. 0;
4562
4563                --  That lower bound is *just* outside the range of 32 bits, and
4564                --  does need fudging down in this case. Note that the bounds
4565                --  will always have crossed here, since the high bound will be
4566                --  fudged down if necessary, as in the case of:
4567
4568                --    type t is delta 2.0**(-14)
4569                --      range 131072.0 .. 131072.0;
4570
4571                --  So we detect the situation by looking for crossed bounds,
4572                --  and if the bounds are crossed, and the low bound is greater
4573                --  than zero, we will always back it off by small, since this
4574                --  is completely harmless.
4575
4576                if Actual_Lo > Actual_Hi then
4577                   if UR_Is_Positive (Actual_Lo) then
4578                      Actual_Lo   := Loval_Incl_EP - Small;
4579                      Actual_Size := Fsize (Actual_Lo, Actual_Hi);
4580
4581                   --  And of course, we need to do exactly the same parallel
4582                   --  fudge for flat ranges in the negative region.
4583
4584                   elsif UR_Is_Negative (Actual_Hi) then
4585                      Actual_Hi := Hival_Incl_EP + Small;
4586                      Actual_Size := Fsize (Actual_Lo, Actual_Hi);
4587                   end if;
4588                end if;
4589             end if;
4590
4591             Set_Realval (Lo, Actual_Lo);
4592             Set_Realval (Hi, Actual_Hi);
4593          end Fudge;
4594
4595       --  For the decimal case, none of this fudging is required, since there
4596       --  are no end-point problems in the decimal case (the end-points are
4597       --  always included).
4598
4599       else
4600          Actual_Size := Fsize (Loval, Hival);
4601       end if;
4602
4603       --  At this stage, the actual size has been calculated and the proper
4604       --  required bounds are stored in the low and high bounds.
4605
4606       if Actual_Size > 64 then
4607          Error_Msg_Uint_1 := UI_From_Int (Actual_Size);
4608          Error_Msg_N
4609            ("size required (^) for type& too large, maximum allowed is 64",
4610             Typ);
4611          Actual_Size := 64;
4612       end if;
4613
4614       --  Check size against explicit given size
4615
4616       if Has_Size_Clause (Typ) then
4617          if Actual_Size > RM_Size (Typ) then
4618             Error_Msg_Uint_1 := RM_Size (Typ);
4619             Error_Msg_Uint_2 := UI_From_Int (Actual_Size);
4620             Error_Msg_NE
4621               ("size given (^) for type& too small, minimum allowed is ^",
4622                Size_Clause (Typ), Typ);
4623
4624          else
4625             Actual_Size := UI_To_Int (Esize (Typ));
4626          end if;
4627
4628       --  Increase size to next natural boundary if no size clause given
4629
4630       else
4631          if Actual_Size <= 8 then
4632             Actual_Size := 8;
4633          elsif Actual_Size <= 16 then
4634             Actual_Size := 16;
4635          elsif Actual_Size <= 32 then
4636             Actual_Size := 32;
4637          else
4638             Actual_Size := 64;
4639          end if;
4640
4641          Init_Esize (Typ, Actual_Size);
4642          Adjust_Esize_For_Alignment (Typ);
4643       end if;
4644
4645       --  If we have a base type, then expand the bounds so that they extend to
4646       --  the full width of the allocated size in bits, to avoid junk range
4647       --  checks on intermediate computations.
4648
4649       if Base_Type (Typ) = Typ then
4650          Set_Realval (Lo, -(Small * (Uint_2 ** (Actual_Size - 1))));
4651          Set_Realval (Hi,  (Small * (Uint_2 ** (Actual_Size - 1) - 1)));
4652       end if;
4653
4654       --  Final step is to reanalyze the bounds using the proper type
4655       --  and set the Corresponding_Integer_Value fields of the literals.
4656
4657       Set_Etype (Lo, Empty);
4658       Set_Analyzed (Lo, False);
4659       Analyze (Lo);
4660
4661       --  Resolve with universal fixed if the base type, and the base type if
4662       --  it is a subtype. Note we can't resolve the base type with itself,
4663       --  that would be a reference before definition.
4664
4665       if Typ = Btyp then
4666          Resolve (Lo, Universal_Fixed);
4667       else
4668          Resolve (Lo, Btyp);
4669       end if;
4670
4671       --  Set corresponding integer value for bound
4672
4673       Set_Corresponding_Integer_Value
4674         (Lo, UR_To_Uint (Realval (Lo) / Small));
4675
4676       --  Similar processing for high bound
4677
4678       Set_Etype (Hi, Empty);
4679       Set_Analyzed (Hi, False);
4680       Analyze (Hi);
4681
4682       if Typ = Btyp then
4683          Resolve (Hi, Universal_Fixed);
4684       else
4685          Resolve (Hi, Btyp);
4686       end if;
4687
4688       Set_Corresponding_Integer_Value
4689         (Hi, UR_To_Uint (Realval (Hi) / Small));
4690
4691       --  Set type of range to correspond to bounds
4692
4693       Set_Etype (Rng, Etype (Lo));
4694
4695       --  Set Esize to calculated size if not set already
4696
4697       if Unknown_Esize (Typ) then
4698          Init_Esize (Typ, Actual_Size);
4699       end if;
4700
4701       --  Set RM_Size if not already set. If already set, check value
4702
4703       declare
4704          Minsiz : constant Uint := UI_From_Int (Minimum_Size (Typ));
4705
4706       begin
4707          if RM_Size (Typ) /= Uint_0 then
4708             if RM_Size (Typ) < Minsiz then
4709                Error_Msg_Uint_1 := RM_Size (Typ);
4710                Error_Msg_Uint_2 := Minsiz;
4711                Error_Msg_NE
4712                  ("size given (^) for type& too small, minimum allowed is ^",
4713                   Size_Clause (Typ), Typ);
4714             end if;
4715
4716          else
4717             Set_RM_Size (Typ, Minsiz);
4718          end if;
4719       end;
4720    end Freeze_Fixed_Point_Type;
4721
4722    ------------------
4723    -- Freeze_Itype --
4724    ------------------
4725
4726    procedure Freeze_Itype (T : Entity_Id; N : Node_Id) is
4727       L : List_Id;
4728
4729    begin
4730       Set_Has_Delayed_Freeze (T);
4731       L := Freeze_Entity (T, Sloc (N));
4732
4733       if Is_Non_Empty_List (L) then
4734          Insert_Actions (N, L);
4735       end if;
4736    end Freeze_Itype;
4737
4738    --------------------------
4739    -- Freeze_Static_Object --
4740    --------------------------
4741
4742    procedure Freeze_Static_Object (E : Entity_Id) is
4743
4744       Cannot_Be_Static : exception;
4745       --  Exception raised if the type of a static object cannot be made
4746       --  static. This happens if the type depends on non-global objects.
4747
4748       procedure Ensure_Expression_Is_SA (N : Node_Id);
4749       --  Called to ensure that an expression used as part of a type definition
4750       --  is statically allocatable, which means that the expression type is
4751       --  statically allocatable, and the expression is either static, or a
4752       --  reference to a library level constant.
4753
4754       procedure Ensure_Type_Is_SA (Typ : Entity_Id);
4755       --  Called to mark a type as static, checking that it is possible
4756       --  to set the type as static. If it is not possible, then the
4757       --  exception Cannot_Be_Static is raised.
4758
4759       -----------------------------
4760       -- Ensure_Expression_Is_SA --
4761       -----------------------------
4762
4763       procedure Ensure_Expression_Is_SA (N : Node_Id) is
4764          Ent : Entity_Id;
4765
4766       begin
4767          Ensure_Type_Is_SA (Etype (N));
4768
4769          if Is_Static_Expression (N) then
4770             return;
4771
4772          elsif Nkind (N) = N_Identifier then
4773             Ent := Entity (N);
4774
4775             if Present (Ent)
4776               and then Ekind (Ent) = E_Constant
4777               and then Is_Library_Level_Entity (Ent)
4778             then
4779                return;
4780             end if;
4781          end if;
4782
4783          raise Cannot_Be_Static;
4784       end Ensure_Expression_Is_SA;
4785
4786       -----------------------
4787       -- Ensure_Type_Is_SA --
4788       -----------------------
4789
4790       procedure Ensure_Type_Is_SA (Typ : Entity_Id) is
4791          N : Node_Id;
4792          C : Entity_Id;
4793
4794       begin
4795          --  If type is library level, we are all set
4796
4797          if Is_Library_Level_Entity (Typ) then
4798             return;
4799          end if;
4800
4801          --  We are also OK if the type already marked as statically allocated,
4802          --  which means we processed it before.
4803
4804          if Is_Statically_Allocated (Typ) then
4805             return;
4806          end if;
4807
4808          --  Mark type as statically allocated
4809
4810          Set_Is_Statically_Allocated (Typ);
4811
4812          --  Check that it is safe to statically allocate this type
4813
4814          if Is_Scalar_Type (Typ) or else Is_Real_Type (Typ) then
4815             Ensure_Expression_Is_SA (Type_Low_Bound (Typ));
4816             Ensure_Expression_Is_SA (Type_High_Bound (Typ));
4817
4818          elsif Is_Array_Type (Typ) then
4819             N := First_Index (Typ);
4820             while Present (N) loop
4821                Ensure_Type_Is_SA (Etype (N));
4822                Next_Index (N);
4823             end loop;
4824
4825             Ensure_Type_Is_SA (Component_Type (Typ));
4826
4827          elsif Is_Access_Type (Typ) then
4828             if Ekind (Designated_Type (Typ)) = E_Subprogram_Type then
4829
4830                declare
4831                   F : Entity_Id;
4832                   T : constant Entity_Id := Etype (Designated_Type (Typ));
4833
4834                begin
4835                   if T /= Standard_Void_Type then
4836                      Ensure_Type_Is_SA (T);
4837                   end if;
4838
4839                   F := First_Formal (Designated_Type (Typ));
4840
4841                   while Present (F) loop
4842                      Ensure_Type_Is_SA (Etype (F));
4843                      Next_Formal (F);
4844                   end loop;
4845                end;
4846
4847             else
4848                Ensure_Type_Is_SA (Designated_Type (Typ));
4849             end if;
4850
4851          elsif Is_Record_Type (Typ) then
4852             C := First_Entity (Typ);
4853             while Present (C) loop
4854                if Ekind (C) = E_Discriminant
4855                  or else Ekind (C) = E_Component
4856                then
4857                   Ensure_Type_Is_SA (Etype (C));
4858
4859                elsif Is_Type (C) then
4860                   Ensure_Type_Is_SA (C);
4861                end if;
4862
4863                Next_Entity (C);
4864             end loop;
4865
4866          elsif Ekind (Typ) = E_Subprogram_Type then
4867             Ensure_Type_Is_SA (Etype (Typ));
4868
4869             C := First_Formal (Typ);
4870             while Present (C) loop
4871                Ensure_Type_Is_SA (Etype (C));
4872                Next_Formal (C);
4873             end loop;
4874
4875          else
4876             raise Cannot_Be_Static;
4877          end if;
4878       end Ensure_Type_Is_SA;
4879
4880    --  Start of processing for Freeze_Static_Object
4881
4882    begin
4883       Ensure_Type_Is_SA (Etype (E));
4884
4885    exception
4886       when Cannot_Be_Static =>
4887
4888          --  If the object that cannot be static is imported or exported,
4889          --  then we give an error message saying that this object cannot
4890          --  be imported or exported.
4891
4892          if Is_Imported (E) then
4893             Error_Msg_N
4894               ("& cannot be imported (local type is not constant)", E);
4895
4896          --  Otherwise must be exported, something is wrong if compiler
4897          --  is marking something as statically allocated which cannot be).
4898
4899          else pragma Assert (Is_Exported (E));
4900             Error_Msg_N
4901               ("& cannot be exported (local type is not constant)", E);
4902          end if;
4903    end Freeze_Static_Object;
4904
4905    -----------------------
4906    -- Freeze_Subprogram --
4907    -----------------------
4908
4909    procedure Freeze_Subprogram (E : Entity_Id) is
4910       Retype : Entity_Id;
4911       F      : Entity_Id;
4912
4913    begin
4914       --  Subprogram may not have an address clause unless it is imported
4915
4916       if Present (Address_Clause (E)) then
4917          if not Is_Imported (E) then
4918             Error_Msg_N
4919               ("address clause can only be given " &
4920                "for imported subprogram",
4921                Name (Address_Clause (E)));
4922          end if;
4923       end if;
4924
4925       --  Reset the Pure indication on an imported subprogram unless an
4926       --  explicit Pure_Function pragma was present. We do this because
4927       --  otherwise it is an insidious error to call a non-pure function from
4928       --  pure unit and have calls mysteriously optimized away. What happens
4929       --  here is that the Import can bypass the normal check to ensure that
4930       --  pure units call only pure subprograms.
4931
4932       if Is_Imported (E)
4933         and then Is_Pure (E)
4934         and then not Has_Pragma_Pure_Function (E)
4935       then
4936          Set_Is_Pure (E, False);
4937       end if;
4938
4939       --  For non-foreign convention subprograms, this is where we create
4940       --  the extra formals (for accessibility level and constrained bit
4941       --  information). We delay this till the freeze point precisely so
4942       --  that we know the convention!
4943
4944       if not Has_Foreign_Convention (E) then
4945          Create_Extra_Formals (E);
4946          Set_Mechanisms (E);
4947
4948          --  If this is convention Ada and a Valued_Procedure, that's odd
4949
4950          if Ekind (E) = E_Procedure
4951            and then Is_Valued_Procedure (E)
4952            and then Convention (E) = Convention_Ada
4953            and then Warn_On_Export_Import
4954          then
4955             Error_Msg_N
4956               ("?Valued_Procedure has no effect for convention Ada", E);
4957             Set_Is_Valued_Procedure (E, False);
4958          end if;
4959
4960       --  Case of foreign convention
4961
4962       else
4963          Set_Mechanisms (E);
4964
4965          --  For foreign conventions, warn about return of an
4966          --  unconstrained array.
4967
4968          --  Note: we *do* allow a return by descriptor for the VMS case,
4969          --  though here there is probably more to be done ???
4970
4971          if Ekind (E) = E_Function then
4972             Retype := Underlying_Type (Etype (E));
4973
4974             --  If no return type, probably some other error, e.g. a
4975             --  missing full declaration, so ignore.
4976
4977             if No (Retype) then
4978                null;
4979
4980             --  If the return type is generic, we have emitted a warning
4981             --  earlier on, and there is nothing else to check here. Specific
4982             --  instantiations may lead to erroneous behavior.
4983
4984             elsif Is_Generic_Type (Etype (E)) then
4985                null;
4986
4987             elsif Is_Array_Type (Retype)
4988               and then not Is_Constrained (Retype)
4989               and then Mechanism (E) not in Descriptor_Codes
4990               and then Warn_On_Export_Import
4991             then
4992                Error_Msg_N
4993                 ("?foreign convention function& should not return " &
4994                   "unconstrained array", E);
4995                return;
4996             end if;
4997          end if;
4998
4999          --  If any of the formals for an exported foreign convention
5000          --  subprogram have defaults, then emit an appropriate warning since
5001          --  this is odd (default cannot be used from non-Ada code)
5002
5003          if Is_Exported (E) then
5004             F := First_Formal (E);
5005             while Present (F) loop
5006                if Warn_On_Export_Import
5007                  and then Present (Default_Value (F))
5008                then
5009                   Error_Msg_N
5010                     ("?parameter cannot be defaulted in non-Ada call",
5011                      Default_Value (F));
5012                end if;
5013
5014                Next_Formal (F);
5015             end loop;
5016          end if;
5017       end if;
5018
5019       --  For VMS, descriptor mechanisms for parameters are allowed only
5020       --  for imported/exported subprograms.  Moreover, the NCA descriptor
5021       --  is not allowed for parameters of exported subprograms.
5022
5023       if OpenVMS_On_Target then
5024          if Is_Exported (E) then
5025             F := First_Formal (E);
5026             while Present (F) loop
5027                if Mechanism (F) = By_Descriptor_NCA then
5028                   Error_Msg_N
5029                     ("'N'C'A' descriptor for parameter not permitted", F);
5030                   Error_Msg_N
5031                     ("\can only be used for imported subprogram", F);
5032                end if;
5033
5034                Next_Formal (F);
5035             end loop;
5036
5037          elsif not Is_Imported (E) then
5038             F := First_Formal (E);
5039             while Present (F) loop
5040                if Mechanism (F) in Descriptor_Codes then
5041                   Error_Msg_N
5042                     ("descriptor mechanism for parameter not permitted", F);
5043                   Error_Msg_N
5044                     ("\can only be used for imported/exported subprogram", F);
5045                end if;
5046
5047                Next_Formal (F);
5048             end loop;
5049          end if;
5050       end if;
5051
5052       --  Pragma Inline_Always is disallowed for dispatching subprograms
5053       --  because the address of such subprograms is saved in the dispatch
5054       --  table to support dispatching calls, and dispatching calls cannot
5055       --  be inlined. This is consistent with the restriction against using
5056       --  'Access or 'Address on an Inline_Always subprogram.
5057
5058       if Is_Dispatching_Operation (E)
5059         and then Has_Pragma_Inline_Always (E)
5060       then
5061          Error_Msg_N
5062            ("pragma Inline_Always not allowed for dispatching subprograms", E);
5063       end if;
5064
5065       --  Because of the implicit representation of inherited predefined
5066       --  operators in the front-end, the overriding status of the operation
5067       --  may be affected when a full view of a type is analyzed, and this is
5068       --  not captured by the analysis of the corresponding type declaration.
5069       --  Therefore the correctness of a not-overriding indicator must be
5070       --  rechecked when the subprogram is frozen.
5071
5072       if Nkind (E) = N_Defining_Operator_Symbol
5073         and then not Error_Posted (Parent (E))
5074       then
5075          Check_Overriding_Indicator (E, Empty, Is_Primitive (E));
5076       end if;
5077    end Freeze_Subprogram;
5078
5079    ----------------------
5080    -- Is_Fully_Defined --
5081    ----------------------
5082
5083    function Is_Fully_Defined (T : Entity_Id) return Boolean is
5084    begin
5085       if Ekind (T) = E_Class_Wide_Type then
5086          return Is_Fully_Defined (Etype (T));
5087
5088       elsif Is_Array_Type (T) then
5089          return Is_Fully_Defined (Component_Type (T));
5090
5091       elsif Is_Record_Type (T)
5092         and not Is_Private_Type (T)
5093       then
5094          --  Verify that the record type has no components with private types
5095          --  without completion.
5096
5097          declare
5098             Comp : Entity_Id;
5099
5100          begin
5101             Comp := First_Component (T);
5102
5103             while Present (Comp) loop
5104                if not Is_Fully_Defined (Etype (Comp)) then
5105                   return False;
5106                end if;
5107
5108                Next_Component (Comp);
5109             end loop;
5110             return True;
5111          end;
5112
5113       else
5114          return not Is_Private_Type (T)
5115            or else Present (Full_View (Base_Type (T)));
5116       end if;
5117    end Is_Fully_Defined;
5118
5119    ---------------------------------
5120    -- Process_Default_Expressions --
5121    ---------------------------------
5122
5123    procedure Process_Default_Expressions
5124      (E     : Entity_Id;
5125       After : in out Node_Id)
5126    is
5127       Loc    : constant Source_Ptr := Sloc (E);
5128       Dbody  : Node_Id;
5129       Formal : Node_Id;
5130       Dcopy  : Node_Id;
5131       Dnam   : Entity_Id;
5132
5133    begin
5134       Set_Default_Expressions_Processed (E);
5135
5136       --  A subprogram instance and its associated anonymous subprogram share
5137       --  their signature. The default expression functions are defined in the
5138       --  wrapper packages for the anonymous subprogram, and should not be
5139       --  generated again for the instance.
5140
5141       if Is_Generic_Instance (E)
5142         and then Present (Alias (E))
5143         and then Default_Expressions_Processed (Alias (E))
5144       then
5145          return;
5146       end if;
5147
5148       Formal := First_Formal (E);
5149       while Present (Formal) loop
5150          if Present (Default_Value (Formal)) then
5151
5152             --  We work with a copy of the default expression because we
5153             --  do not want to disturb the original, since this would mess
5154             --  up the conformance checking.
5155
5156             Dcopy := New_Copy_Tree (Default_Value (Formal));
5157
5158             --  The analysis of the expression may generate insert actions,
5159             --  which of course must not be executed. We wrap those actions
5160             --  in a procedure that is not called, and later on eliminated.
5161             --  The following cases have no side-effects, and are analyzed
5162             --  directly.
5163
5164             if Nkind (Dcopy) = N_Identifier
5165               or else Nkind (Dcopy) = N_Expanded_Name
5166               or else Nkind (Dcopy) = N_Integer_Literal
5167               or else (Nkind (Dcopy) = N_Real_Literal
5168                         and then not Vax_Float (Etype (Dcopy)))
5169               or else Nkind (Dcopy) = N_Character_Literal
5170               or else Nkind (Dcopy) = N_String_Literal
5171               or else Known_Null (Dcopy)
5172               or else (Nkind (Dcopy) = N_Attribute_Reference
5173                         and then
5174                        Attribute_Name (Dcopy) = Name_Null_Parameter)
5175             then
5176
5177                --  If there is no default function, we must still do a full
5178                --  analyze call on the default value, to ensure that all error
5179                --  checks are performed, e.g. those associated with static
5180                --  evaluation. Note: this branch will always be taken if the
5181                --  analyzer is turned off (but we still need the error checks).
5182
5183                --  Note: the setting of parent here is to meet the requirement
5184                --  that we can only analyze the expression while attached to
5185                --  the tree. Really the requirement is that the parent chain
5186                --  be set, we don't actually need to be in the tree.
5187
5188                Set_Parent (Dcopy, Declaration_Node (Formal));
5189                Analyze (Dcopy);
5190
5191                --  Default expressions are resolved with their own type if the
5192                --  context is generic, to avoid anomalies with private types.
5193
5194                if Ekind (Scope (E)) = E_Generic_Package then
5195                   Resolve (Dcopy);
5196                else
5197                   Resolve (Dcopy, Etype (Formal));
5198                end if;
5199
5200                --  If that resolved expression will raise constraint error,
5201                --  then flag the default value as raising constraint error.
5202                --  This allows a proper error message on the calls.
5203
5204                if Raises_Constraint_Error (Dcopy) then
5205                   Set_Raises_Constraint_Error (Default_Value (Formal));
5206                end if;
5207
5208             --  If the default is a parameterless call, we use the name of
5209             --  the called function directly, and there is no body to build.
5210
5211             elsif Nkind (Dcopy) = N_Function_Call
5212               and then No (Parameter_Associations (Dcopy))
5213             then
5214                null;
5215
5216             --  Else construct and analyze the body of a wrapper procedure
5217             --  that contains an object declaration to hold the expression.
5218             --  Given that this is done only to complete the analysis, it
5219             --  simpler to build a procedure than a function which might
5220             --  involve secondary stack expansion.
5221
5222             else
5223                Dnam :=
5224                  Make_Defining_Identifier (Loc, New_Internal_Name ('D'));
5225
5226                Dbody :=
5227                  Make_Subprogram_Body (Loc,
5228                    Specification =>
5229                      Make_Procedure_Specification (Loc,
5230                        Defining_Unit_Name => Dnam),
5231
5232                    Declarations => New_List (
5233                      Make_Object_Declaration (Loc,
5234                        Defining_Identifier =>
5235                          Make_Defining_Identifier (Loc,
5236                            New_Internal_Name ('T')),
5237                          Object_Definition =>
5238                            New_Occurrence_Of (Etype (Formal), Loc),
5239                          Expression => New_Copy_Tree (Dcopy))),
5240
5241                    Handled_Statement_Sequence =>
5242                      Make_Handled_Sequence_Of_Statements (Loc,
5243                        Statements => New_List));
5244
5245                Set_Scope (Dnam, Scope (E));
5246                Set_Assignment_OK (First (Declarations (Dbody)));
5247                Set_Is_Eliminated (Dnam);
5248                Insert_After (After, Dbody);
5249                Analyze (Dbody);
5250                After := Dbody;
5251             end if;
5252          end if;
5253
5254          Next_Formal (Formal);
5255       end loop;
5256    end Process_Default_Expressions;
5257
5258    ----------------------------------------
5259    -- Set_Component_Alignment_If_Not_Set --
5260    ----------------------------------------
5261
5262    procedure Set_Component_Alignment_If_Not_Set (Typ : Entity_Id) is
5263    begin
5264       --  Ignore if not base type, subtypes don't need anything
5265
5266       if Typ /= Base_Type (Typ) then
5267          return;
5268       end if;
5269
5270       --  Do not override existing representation
5271
5272       if Is_Packed (Typ) then
5273          return;
5274
5275       elsif Has_Specified_Layout (Typ) then
5276          return;
5277
5278       elsif Component_Alignment (Typ) /= Calign_Default then
5279          return;
5280
5281       else
5282          Set_Component_Alignment
5283            (Typ, Scope_Stack.Table
5284                   (Scope_Stack.Last).Component_Alignment_Default);
5285       end if;
5286    end Set_Component_Alignment_If_Not_Set;
5287
5288    ------------------
5289    -- Undelay_Type --
5290    ------------------
5291
5292    procedure Undelay_Type (T : Entity_Id) is
5293    begin
5294       Set_Has_Delayed_Freeze (T, False);
5295       Set_Freeze_Node (T, Empty);
5296
5297       --  Since we don't want T to have a Freeze_Node, we don't want its
5298       --  Full_View or Corresponding_Record_Type to have one either.
5299
5300       --  ??? Fundamentally, this whole handling is a kludge. What we really
5301       --  want is to be sure that for an Itype that's part of record R and is a
5302       --  subtype of type T, that it's frozen after the later of the freeze
5303       --  points of R and T. We have no way of doing that directly, so what we
5304       --  do is force most such Itypes to be frozen as part of freezing R via
5305       --  this procedure and only delay the ones that need to be delayed
5306       --  (mostly the designated types of access types that are defined as part
5307       --  of the record).
5308
5309       if Is_Private_Type (T)
5310         and then Present (Full_View (T))
5311         and then Is_Itype (Full_View (T))
5312         and then Is_Record_Type (Scope (Full_View (T)))
5313       then
5314          Undelay_Type (Full_View (T));
5315       end if;
5316
5317       if Is_Concurrent_Type (T)
5318         and then Present (Corresponding_Record_Type (T))
5319         and then Is_Itype (Corresponding_Record_Type (T))
5320         and then Is_Record_Type (Scope (Corresponding_Record_Type (T)))
5321       then
5322          Undelay_Type (Corresponding_Record_Type (T));
5323       end if;
5324    end Undelay_Type;
5325
5326    ------------------
5327    -- Warn_Overlay --
5328    ------------------
5329
5330    procedure Warn_Overlay
5331      (Expr : Node_Id;
5332       Typ  : Entity_Id;
5333       Nam  : Entity_Id)
5334    is
5335       Ent : constant Entity_Id := Entity (Nam);
5336       --  The object to which the address clause applies
5337
5338       Init : Node_Id;
5339       Old  : Entity_Id := Empty;
5340       Decl : Node_Id;
5341
5342    begin
5343       --  No warning if address clause overlay warnings are off
5344
5345       if not Address_Clause_Overlay_Warnings then
5346          return;
5347       end if;
5348
5349       --  No warning if there is an explicit initialization
5350
5351       Init := Original_Node (Expression (Declaration_Node (Ent)));
5352
5353       if Present (Init) and then Comes_From_Source (Init) then
5354          return;
5355       end if;
5356
5357       --  We only give the warning for non-imported entities of a type for
5358       --  which a non-null base init proc is defined, or for objects of access
5359       --  types with implicit null initialization, or when Initialize_Scalars
5360       --  applies and the type is scalar or a string type (the latter being
5361       --  tested for because predefined String types are initialized by inline
5362       --  code rather than by an init_proc).
5363
5364       if Present (Expr)
5365         and then not Is_Imported (Ent)
5366         and then (Has_Non_Null_Base_Init_Proc (Typ)
5367                     or else Is_Access_Type (Typ)
5368                     or else (Init_Or_Norm_Scalars
5369                               and then (Is_Scalar_Type (Typ)
5370                                          or else Is_String_Type (Typ))))
5371       then
5372          if Nkind (Expr) = N_Attribute_Reference
5373            and then Is_Entity_Name (Prefix (Expr))
5374          then
5375             Old := Entity (Prefix (Expr));
5376
5377          elsif Is_Entity_Name (Expr)
5378            and then Ekind (Entity (Expr)) = E_Constant
5379          then
5380             Decl := Declaration_Node (Entity (Expr));
5381
5382             if Nkind (Decl) = N_Object_Declaration
5383               and then Present (Expression (Decl))
5384               and then Nkind (Expression (Decl)) = N_Attribute_Reference
5385               and then Is_Entity_Name (Prefix (Expression (Decl)))
5386             then
5387                Old := Entity (Prefix (Expression (Decl)));
5388
5389             elsif Nkind (Expr) = N_Function_Call then
5390                return;
5391             end if;
5392
5393          --  A function call (most likely to To_Address) is probably not an
5394          --  overlay, so skip warning. Ditto if the function call was inlined
5395          --  and transformed into an entity.
5396
5397          elsif Nkind (Original_Node (Expr)) = N_Function_Call then
5398             return;
5399          end if;
5400
5401          Decl := Next (Parent (Expr));
5402
5403          --  If a pragma Import follows, we assume that it is for the current
5404          --  target of the address clause, and skip the warning.
5405
5406          if Present (Decl)
5407            and then Nkind (Decl) = N_Pragma
5408            and then Pragma_Name (Decl) = Name_Import
5409          then
5410             return;
5411          end if;
5412
5413          if Present (Old) then
5414             Error_Msg_Node_2 := Old;
5415             Error_Msg_N
5416               ("default initialization of & may modify &?",
5417                Nam);
5418          else
5419             Error_Msg_N
5420               ("default initialization of & may modify overlaid storage?",
5421                Nam);
5422          end if;
5423
5424          --  Add friendly warning if initialization comes from a packed array
5425          --  component.
5426
5427          if Is_Record_Type (Typ)  then
5428             declare
5429                Comp : Entity_Id;
5430
5431             begin
5432                Comp := First_Component (Typ);
5433
5434                while Present (Comp) loop
5435                   if Nkind (Parent (Comp)) = N_Component_Declaration
5436                     and then Present (Expression (Parent (Comp)))
5437                   then
5438                      exit;
5439                   elsif Is_Array_Type (Etype (Comp))
5440                      and then Present (Packed_Array_Type (Etype (Comp)))
5441                   then
5442                      Error_Msg_NE
5443                        ("\packed array component& " &
5444                         "will be initialized to zero?",
5445                         Nam, Comp);
5446                      exit;
5447                   else
5448                      Next_Component (Comp);
5449                   end if;
5450                end loop;
5451             end;
5452          end if;
5453
5454          Error_Msg_N
5455            ("\use pragma Import for & to " &
5456             "suppress initialization (RM B.1(24))?",
5457             Nam);
5458       end if;
5459    end Warn_Overlay;
5460
5461 end Freeze;