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-2018, Free Software Foundation, Inc.         --
10--                                                                          --
11-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12-- terms of the  GNU General Public License as published  by the Free Soft- --
13-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17-- for  more details.  You should have  received  a copy of the GNU General --
18-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19-- http://www.gnu.org/licenses for a complete copy of the license.          --
20--                                                                          --
21-- GNAT was originally developed  by the GNAT team at  New York University. --
22-- Extensive contributions were provided by Ada Core Technologies Inc.      --
23--                                                                          --
24------------------------------------------------------------------------------
25
26with Aspects;   use Aspects;
27with Atree;     use Atree;
28with Checks;    use Checks;
29with Contracts; use Contracts;
30with Debug;     use Debug;
31with Einfo;     use Einfo;
32with Elists;    use Elists;
33with Errout;    use Errout;
34with Exp_Ch3;   use Exp_Ch3;
35with Exp_Ch7;   use Exp_Ch7;
36with Exp_Disp;  use Exp_Disp;
37with Exp_Pakd;  use Exp_Pakd;
38with Exp_Util;  use Exp_Util;
39with Exp_Tss;   use Exp_Tss;
40with Ghost;     use Ghost;
41with Layout;    use Layout;
42with Lib;       use Lib;
43with Namet;     use Namet;
44with Nlists;    use Nlists;
45with Nmake;     use Nmake;
46with Opt;       use Opt;
47with Restrict;  use Restrict;
48with Rident;    use Rident;
49with Rtsfind;   use Rtsfind;
50with Sem;       use Sem;
51with Sem_Aux;   use Sem_Aux;
52with Sem_Cat;   use Sem_Cat;
53with Sem_Ch6;   use Sem_Ch6;
54with Sem_Ch7;   use Sem_Ch7;
55with Sem_Ch8;   use Sem_Ch8;
56with Sem_Ch13;  use Sem_Ch13;
57with Sem_Eval;  use Sem_Eval;
58with Sem_Mech;  use Sem_Mech;
59with Sem_Prag;  use Sem_Prag;
60with Sem_Res;   use Sem_Res;
61with Sem_Util;  use Sem_Util;
62with Sinfo;     use Sinfo;
63with Snames;    use Snames;
64with Stand;     use Stand;
65with Targparm;  use Targparm;
66with Tbuild;    use Tbuild;
67with Ttypes;    use Ttypes;
68with Uintp;     use Uintp;
69with Urealp;    use Urealp;
70with Warnsw;    use Warnsw;
71
72package body Freeze is
73
74   -----------------------
75   -- Local Subprograms --
76   -----------------------
77
78   procedure Adjust_Esize_For_Alignment (Typ : Entity_Id);
79   --  Typ is a type that is being frozen. If no size clause is given,
80   --  but a default Esize has been computed, then this default Esize is
81   --  adjusted up if necessary to be consistent with a given alignment,
82   --  but never to a value greater than Long_Long_Integer'Size. This
83   --  is used for all discrete types and for fixed-point types.
84
85   procedure Build_And_Analyze_Renamed_Body
86     (Decl  : Node_Id;
87      New_S : Entity_Id;
88      After : in out Node_Id);
89   --  Build body for a renaming declaration, insert in tree and analyze
90
91   procedure Check_Address_Clause (E : Entity_Id);
92   --  Apply legality checks to address clauses for object declarations,
93   --  at the point the object is frozen. Also ensure any initialization is
94   --  performed only after the object has been frozen.
95
96   procedure Check_Component_Storage_Order
97     (Encl_Type        : Entity_Id;
98      Comp             : Entity_Id;
99      ADC              : Node_Id;
100      Comp_ADC_Present : out Boolean);
101   --  For an Encl_Type that has a Scalar_Storage_Order attribute definition
102   --  clause, verify that the component type has an explicit and compatible
103   --  attribute/aspect. For arrays, Comp is Empty; for records, it is the
104   --  entity of the component under consideration. For an Encl_Type that
105   --  does not have a Scalar_Storage_Order attribute definition clause,
106   --  verify that the component also does not have such a clause.
107   --  ADC is the attribute definition clause if present (or Empty). On return,
108   --  Comp_ADC_Present is set True if the component has a Scalar_Storage_Order
109   --  attribute definition clause.
110
111   procedure Check_Debug_Info_Needed (T : Entity_Id);
112   --  As each entity is frozen, this routine is called to deal with the
113   --  setting of Debug_Info_Needed for the entity. This flag is set if
114   --  the entity comes from source, or if we are in Debug_Generated_Code
115   --  mode or if the -gnatdV debug flag is set. However, it never sets
116   --  the flag if Debug_Info_Off is set. This procedure also ensures that
117   --  subsidiary entities have the flag set as required.
118
119   procedure Check_Expression_Function (N : Node_Id; Nam : Entity_Id);
120   --  When an expression function is frozen by a use of it, the expression
121   --  itself is frozen. Check that the expression does not include references
122   --  to deferred constants without completion. We report this at the freeze
123   --  point of the function, to provide a better error message.
124   --
125   --  In most cases the expression itself is frozen by the time the function
126   --  itself is frozen, because the formals will be frozen by then. However,
127   --  Attribute references to outer types are freeze points for those types;
128   --  this routine generates the required freeze nodes for them.
129
130   procedure Check_Inherited_Conditions (R : Entity_Id);
131   --  For a tagged derived type, create wrappers for inherited operations
132   --  that have a class-wide condition, so it can be properly rewritten if
133   --  it involves calls to other overriding primitives.
134
135   procedure Check_Strict_Alignment (E : Entity_Id);
136   --  E is a base type. If E is tagged or has a component that is aliased
137   --  or tagged or contains something this is aliased or tagged, set
138   --  Strict_Alignment.
139
140   procedure Check_Unsigned_Type (E : Entity_Id);
141   pragma Inline (Check_Unsigned_Type);
142   --  If E is a fixed-point or discrete type, then all the necessary work
143   --  to freeze it is completed except for possible setting of the flag
144   --  Is_Unsigned_Type, which is done by this procedure. The call has no
145   --  effect if the entity E is not a discrete or fixed-point type.
146
147   procedure Freeze_And_Append
148     (Ent    : Entity_Id;
149      N      : Node_Id;
150      Result : in out List_Id);
151   --  Freezes Ent using Freeze_Entity, and appends the resulting list of
152   --  nodes to Result, modifying Result from No_List if necessary. N has
153   --  the same usage as in Freeze_Entity.
154
155   procedure Freeze_Enumeration_Type (Typ : Entity_Id);
156   --  Freeze enumeration type. The Esize field is set as processing
157   --  proceeds (i.e. set by default when the type is declared and then
158   --  adjusted by rep clauses. What this procedure does is to make sure
159   --  that if a foreign convention is specified, and no specific size
160   --  is given, then the size must be at least Integer'Size.
161
162   procedure Freeze_Static_Object (E : Entity_Id);
163   --  If an object is frozen which has Is_Statically_Allocated set, then
164   --  all referenced types must also be marked with this flag. This routine
165   --  is in charge of meeting this requirement for the object entity E.
166
167   procedure Freeze_Subprogram (E : Entity_Id);
168   --  Perform freezing actions for a subprogram (create extra formals,
169   --  and set proper default mechanism values). Note that this routine
170   --  is not called for internal subprograms, for which neither of these
171   --  actions is needed (or desirable, we do not want for example to have
172   --  these extra formals present in initialization procedures, where they
173   --  would serve no purpose). In this call E is either a subprogram or
174   --  a subprogram type (i.e. an access to a subprogram).
175
176   function Is_Fully_Defined (T : Entity_Id) return Boolean;
177   --  True if T is not private and has no private components, or has a full
178   --  view. Used to determine whether the designated type of an access type
179   --  should be frozen when the access type is frozen. This is done when an
180   --  allocator is frozen, or an expression that may involve attributes of
181   --  the designated type. Otherwise freezing the access type does not freeze
182   --  the designated type.
183
184   procedure Process_Default_Expressions
185     (E     : Entity_Id;
186      After : in out Node_Id);
187   --  This procedure is called for each subprogram to complete processing of
188   --  default expressions at the point where all types are known to be frozen.
189   --  The expressions must be analyzed in full, to make sure that all error
190   --  processing is done (they have only been pre-analyzed). If the expression
191   --  is not an entity or literal, its analysis may generate code which must
192   --  not be executed. In that case we build a function body to hold that
193   --  code. This wrapper function serves no other purpose (it used to be
194   --  called to evaluate the default, but now the default is inlined at each
195   --  point of call).
196
197   procedure Set_Component_Alignment_If_Not_Set (Typ : Entity_Id);
198   --  Typ is a record or array type that is being frozen. This routine sets
199   --  the default component alignment from the scope stack values if the
200   --  alignment is otherwise not specified.
201
202   procedure Set_SSO_From_Default (T : Entity_Id);
203   --  T is a record or array type that is being frozen. If it is a base type,
204   --  and if SSO_Set_Low/High_By_Default is set, then Reverse_Storage order
205   --  will be set appropriately. Note that an explicit occurrence of aspect
206   --  Scalar_Storage_Order or an explicit setting of this aspect with an
207   --  attribute definition clause occurs, then these two flags are reset in
208   --  any case, so call will have no effect.
209
210   procedure Undelay_Type (T : Entity_Id);
211   --  T is a type of a component that we know to be an Itype. We don't want
212   --  this to have a Freeze_Node, so ensure it doesn't. Do the same for any
213   --  Full_View or Corresponding_Record_Type.
214
215   procedure Warn_Overlay (Expr : Node_Id; Typ : Entity_Id; Nam : Node_Id);
216   --  Expr is the expression for an address clause for entity Nam whose type
217   --  is Typ. If Typ has a default initialization, and there is no explicit
218   --  initialization in the source declaration, check whether the address
219   --  clause might cause overlaying of an entity, and emit a warning on the
220   --  side effect that the initialization will cause.
221
222   -------------------------------
223   -- Adjust_Esize_For_Alignment --
224   -------------------------------
225
226   procedure Adjust_Esize_For_Alignment (Typ : Entity_Id) is
227      Align : Uint;
228
229   begin
230      if Known_Esize (Typ) and then Known_Alignment (Typ) then
231         Align := Alignment_In_Bits (Typ);
232
233         if Align > Esize (Typ)
234           and then Align <= Standard_Long_Long_Integer_Size
235         then
236            Set_Esize (Typ, Align);
237         end if;
238      end if;
239   end Adjust_Esize_For_Alignment;
240
241   ------------------------------------
242   -- Build_And_Analyze_Renamed_Body --
243   ------------------------------------
244
245   procedure Build_And_Analyze_Renamed_Body
246     (Decl  : Node_Id;
247      New_S : Entity_Id;
248      After : in out Node_Id)
249   is
250      Body_Decl    : constant Node_Id := Unit_Declaration_Node (New_S);
251      Ent          : constant Entity_Id := Defining_Entity (Decl);
252      Body_Node    : Node_Id;
253      Renamed_Subp : Entity_Id;
254
255   begin
256      --  If the renamed subprogram is intrinsic, there is no need for a
257      --  wrapper body: we set the alias that will be called and expanded which
258      --  completes the declaration. This transformation is only legal if the
259      --  renamed entity has already been elaborated.
260
261      --  Note that it is legal for a renaming_as_body to rename an intrinsic
262      --  subprogram, as long as the renaming occurs before the new entity
263      --  is frozen (RM 8.5.4 (5)).
264
265      if Nkind (Body_Decl) = N_Subprogram_Renaming_Declaration
266        and then Is_Entity_Name (Name (Body_Decl))
267      then
268         Renamed_Subp := Entity (Name (Body_Decl));
269      else
270         Renamed_Subp := Empty;
271      end if;
272
273      if Present (Renamed_Subp)
274        and then Is_Intrinsic_Subprogram (Renamed_Subp)
275        and then
276          (not In_Same_Source_Unit (Renamed_Subp, Ent)
277            or else Sloc (Renamed_Subp) < Sloc (Ent))
278
279        --  We can make the renaming entity intrinsic if the renamed function
280        --  has an interface name, or if it is one of the shift/rotate
281        --  operations known to the compiler.
282
283        and then
284          (Present (Interface_Name (Renamed_Subp))
285            or else Nam_In (Chars (Renamed_Subp), Name_Rotate_Left,
286                                                  Name_Rotate_Right,
287                                                  Name_Shift_Left,
288                                                  Name_Shift_Right,
289                                                  Name_Shift_Right_Arithmetic))
290      then
291         Set_Interface_Name (Ent, Interface_Name (Renamed_Subp));
292
293         if Present (Alias (Renamed_Subp)) then
294            Set_Alias (Ent, Alias (Renamed_Subp));
295         else
296            Set_Alias (Ent, Renamed_Subp);
297         end if;
298
299         Set_Is_Intrinsic_Subprogram (Ent);
300         Set_Has_Completion (Ent);
301
302      else
303         Body_Node := Build_Renamed_Body (Decl, New_S);
304         Insert_After (After, Body_Node);
305         Mark_Rewrite_Insertion (Body_Node);
306         Analyze (Body_Node);
307         After := Body_Node;
308      end if;
309   end Build_And_Analyze_Renamed_Body;
310
311   ------------------------
312   -- Build_Renamed_Body --
313   ------------------------
314
315   function Build_Renamed_Body
316     (Decl  : Node_Id;
317      New_S : Entity_Id) return Node_Id
318   is
319      Loc : constant Source_Ptr := Sloc (New_S);
320      --  We use for the source location of the renamed body, the location of
321      --  the spec entity. It might seem more natural to use the location of
322      --  the renaming declaration itself, but that would be wrong, since then
323      --  the body we create would look as though it was created far too late,
324      --  and this could cause problems with elaboration order analysis,
325      --  particularly in connection with instantiations.
326
327      N          : constant Node_Id := Unit_Declaration_Node (New_S);
328      Nam        : constant Node_Id := Name (N);
329      Old_S      : Entity_Id;
330      Spec       : constant Node_Id := New_Copy_Tree (Specification (Decl));
331      Actuals    : List_Id := No_List;
332      Call_Node  : Node_Id;
333      Call_Name  : Node_Id;
334      Body_Node  : Node_Id;
335      Formal     : Entity_Id;
336      O_Formal   : Entity_Id;
337      Param_Spec : Node_Id;
338
339      Pref : Node_Id := Empty;
340      --  If the renamed entity is a primitive operation given in prefix form,
341      --  the prefix is the target object and it has to be added as the first
342      --  actual in the generated call.
343
344   begin
345      --  Determine the entity being renamed, which is the target of the call
346      --  statement. If the name is an explicit dereference, this is a renaming
347      --  of a subprogram type rather than a subprogram. The name itself is
348      --  fully analyzed.
349
350      if Nkind (Nam) = N_Selected_Component then
351         Old_S := Entity (Selector_Name (Nam));
352
353      elsif Nkind (Nam) = N_Explicit_Dereference then
354         Old_S := Etype (Nam);
355
356      elsif Nkind (Nam) = N_Indexed_Component then
357         if Is_Entity_Name (Prefix (Nam)) then
358            Old_S := Entity (Prefix (Nam));
359         else
360            Old_S := Entity (Selector_Name (Prefix (Nam)));
361         end if;
362
363      elsif Nkind (Nam) = N_Character_Literal then
364         Old_S := Etype (New_S);
365
366      else
367         Old_S := Entity (Nam);
368      end if;
369
370      if Is_Entity_Name (Nam) then
371
372         --  If the renamed entity is a predefined operator, retain full name
373         --  to ensure its visibility.
374
375         if Ekind (Old_S) = E_Operator
376           and then Nkind (Nam) = N_Expanded_Name
377         then
378            Call_Name := New_Copy (Name (N));
379         else
380            Call_Name := New_Occurrence_Of (Old_S, Loc);
381         end if;
382
383      else
384         if Nkind (Nam) = N_Selected_Component
385           and then Present (First_Formal (Old_S))
386           and then
387             (Is_Controlling_Formal (First_Formal (Old_S))
388                or else Is_Class_Wide_Type (Etype (First_Formal (Old_S))))
389         then
390
391            --  Retrieve the target object, to be added as a first actual
392            --  in the call.
393
394            Call_Name := New_Occurrence_Of (Old_S, Loc);
395            Pref := Prefix (Nam);
396
397         else
398            Call_Name := New_Copy (Name (N));
399         end if;
400
401         --  Original name may have been overloaded, but is fully resolved now
402
403         Set_Is_Overloaded (Call_Name, False);
404      end if;
405
406      --  For simple renamings, subsequent calls can be expanded directly as
407      --  calls to the renamed entity. The body must be generated in any case
408      --  for calls that may appear elsewhere. This is not done in the case
409      --  where the subprogram is an instantiation because the actual proper
410      --  body has not been built yet.
411
412      if Ekind_In (Old_S, E_Function, E_Procedure)
413        and then Nkind (Decl) = N_Subprogram_Declaration
414        and then not Is_Generic_Instance (Old_S)
415      then
416         Set_Body_To_Inline (Decl, Old_S);
417      end if;
418
419      --  Check whether the return type is a limited view. If the subprogram
420      --  is already frozen the generated body may have a non-limited view
421      --  of the type, that must be used, because it is the one in the spec
422      --  of the renaming declaration.
423
424      if Ekind (Old_S) = E_Function
425        and then Is_Entity_Name (Result_Definition (Spec))
426      then
427         declare
428            Ret_Type : constant Entity_Id := Etype (Result_Definition (Spec));
429         begin
430            if Has_Non_Limited_View (Ret_Type) then
431               Set_Result_Definition
432                 (Spec, New_Occurrence_Of (Non_Limited_View (Ret_Type), Loc));
433            end if;
434         end;
435      end if;
436
437      --  The body generated for this renaming is an internal artifact, and
438      --  does not  constitute a freeze point for the called entity.
439
440      Set_Must_Not_Freeze (Call_Name);
441
442      Formal := First_Formal (Defining_Entity (Decl));
443
444      if Present (Pref) then
445         declare
446            Pref_Type : constant Entity_Id := Etype (Pref);
447            Form_Type : constant Entity_Id := Etype (First_Formal (Old_S));
448
449         begin
450            --  The controlling formal may be an access parameter, or the
451            --  actual may be an access value, so adjust accordingly.
452
453            if Is_Access_Type (Pref_Type)
454              and then not Is_Access_Type (Form_Type)
455            then
456               Actuals := New_List
457                 (Make_Explicit_Dereference (Loc, Relocate_Node (Pref)));
458
459            elsif Is_Access_Type (Form_Type)
460              and then not Is_Access_Type (Pref)
461            then
462               Actuals :=
463                 New_List (
464                   Make_Attribute_Reference (Loc,
465                     Attribute_Name => Name_Access,
466                     Prefix         => Relocate_Node (Pref)));
467            else
468               Actuals := New_List (Pref);
469            end if;
470         end;
471
472      elsif Present (Formal) then
473         Actuals := New_List;
474
475      else
476         Actuals := No_List;
477      end if;
478
479      if Present (Formal) then
480         while Present (Formal) loop
481            Append (New_Occurrence_Of (Formal, Loc), Actuals);
482            Next_Formal (Formal);
483         end loop;
484      end if;
485
486      --  If the renamed entity is an entry, inherit its profile. For other
487      --  renamings as bodies, both profiles must be subtype conformant, so it
488      --  is not necessary to replace the profile given in the declaration.
489      --  However, default values that are aggregates are rewritten when
490      --  partially analyzed, so we recover the original aggregate to insure
491      --  that subsequent conformity checking works. Similarly, if the default
492      --  expression was constant-folded, recover the original expression.
493
494      Formal := First_Formal (Defining_Entity (Decl));
495
496      if Present (Formal) then
497         O_Formal := First_Formal (Old_S);
498         Param_Spec := First (Parameter_Specifications (Spec));
499         while Present (Formal) loop
500            if Is_Entry (Old_S) then
501               if Nkind (Parameter_Type (Param_Spec)) /=
502                                                    N_Access_Definition
503               then
504                  Set_Etype (Formal, Etype (O_Formal));
505                  Set_Entity (Parameter_Type (Param_Spec), Etype (O_Formal));
506               end if;
507
508            elsif Nkind (Default_Value (O_Formal)) = N_Aggregate
509              or else Nkind (Original_Node (Default_Value (O_Formal))) /=
510                                           Nkind (Default_Value (O_Formal))
511            then
512               Set_Expression (Param_Spec,
513                 New_Copy_Tree (Original_Node (Default_Value (O_Formal))));
514            end if;
515
516            Next_Formal (Formal);
517            Next_Formal (O_Formal);
518            Next (Param_Spec);
519         end loop;
520      end if;
521
522      --  If the renamed entity is a function, the generated body contains a
523      --  return statement. Otherwise, build a procedure call. If the entity is
524      --  an entry, subsequent analysis of the call will transform it into the
525      --  proper entry or protected operation call. If the renamed entity is
526      --  a character literal, return it directly.
527
528      if Ekind (Old_S) = E_Function
529        or else Ekind (Old_S) = E_Operator
530        or else (Ekind (Old_S) = E_Subprogram_Type
531                  and then Etype (Old_S) /= Standard_Void_Type)
532      then
533         Call_Node :=
534           Make_Simple_Return_Statement (Loc,
535              Expression =>
536                Make_Function_Call (Loc,
537                  Name                   => Call_Name,
538                  Parameter_Associations => Actuals));
539
540      elsif Ekind (Old_S) = E_Enumeration_Literal then
541         Call_Node :=
542           Make_Simple_Return_Statement (Loc,
543              Expression => New_Occurrence_Of (Old_S, Loc));
544
545      elsif Nkind (Nam) = N_Character_Literal then
546         Call_Node :=
547           Make_Simple_Return_Statement (Loc, Expression => Call_Name);
548
549      else
550         Call_Node :=
551           Make_Procedure_Call_Statement (Loc,
552             Name                   => Call_Name,
553             Parameter_Associations => Actuals);
554      end if;
555
556      --  Create entities for subprogram body and formals
557
558      Set_Defining_Unit_Name (Spec,
559        Make_Defining_Identifier (Loc, Chars => Chars (New_S)));
560
561      Param_Spec := First (Parameter_Specifications (Spec));
562      while Present (Param_Spec) loop
563         Set_Defining_Identifier (Param_Spec,
564           Make_Defining_Identifier (Loc,
565             Chars => Chars (Defining_Identifier (Param_Spec))));
566         Next (Param_Spec);
567      end loop;
568
569      Body_Node :=
570        Make_Subprogram_Body (Loc,
571          Specification => Spec,
572          Declarations => New_List,
573          Handled_Statement_Sequence =>
574            Make_Handled_Sequence_Of_Statements (Loc,
575              Statements => New_List (Call_Node)));
576
577      if Nkind (Decl) /= N_Subprogram_Declaration then
578         Rewrite (N,
579           Make_Subprogram_Declaration (Loc,
580             Specification => Specification (N)));
581      end if;
582
583      --  Link the body to the entity whose declaration it completes. If
584      --  the body is analyzed when the renamed entity is frozen, it may
585      --  be necessary to restore the proper scope (see package Exp_Ch13).
586
587      if Nkind (N) = N_Subprogram_Renaming_Declaration
588        and then Present (Corresponding_Spec (N))
589      then
590         Set_Corresponding_Spec (Body_Node, Corresponding_Spec (N));
591      else
592         Set_Corresponding_Spec (Body_Node, New_S);
593      end if;
594
595      return Body_Node;
596   end Build_Renamed_Body;
597
598   --------------------------
599   -- Check_Address_Clause --
600   --------------------------
601
602   procedure Check_Address_Clause (E : Entity_Id) is
603      Addr       : constant Node_Id   := Address_Clause (E);
604      Typ        : constant Entity_Id := Etype (E);
605      Decl       : Node_Id;
606      Expr       : Node_Id;
607      Init       : Node_Id;
608      Lhs        : Node_Id;
609      Tag_Assign : Node_Id;
610
611   begin
612      if Present (Addr) then
613
614         --  For a deferred constant, the initialization value is on full view
615
616         if Ekind (E) = E_Constant and then Present (Full_View (E)) then
617            Decl := Declaration_Node (Full_View (E));
618         else
619            Decl := Declaration_Node (E);
620         end if;
621
622         Expr := Expression (Addr);
623
624         if Needs_Constant_Address (Decl, Typ) then
625            Check_Constant_Address_Clause (Expr, E);
626
627            --  Has_Delayed_Freeze was set on E when the address clause was
628            --  analyzed, and must remain set because we want the address
629            --  clause to be elaborated only after any entity it references
630            --  has been elaborated.
631         end if;
632
633         --  If Rep_Clauses are to be ignored, remove address clause from
634         --  list attached to entity, because it may be illegal for gigi,
635         --  for example by breaking order of elaboration..
636
637         if Ignore_Rep_Clauses then
638            declare
639               Rep : Node_Id;
640
641            begin
642               Rep := First_Rep_Item (E);
643
644               if Rep = Addr then
645                  Set_First_Rep_Item (E, Next_Rep_Item (Addr));
646
647               else
648                  while Present (Rep)
649                    and then Next_Rep_Item (Rep) /= Addr
650                  loop
651                     Rep := Next_Rep_Item (Rep);
652                  end loop;
653               end if;
654
655               if Present (Rep) then
656                  Set_Next_Rep_Item (Rep, Next_Rep_Item (Addr));
657               end if;
658            end;
659
660            --  And now remove the address clause
661
662            Kill_Rep_Clause (Addr);
663
664         elsif not Error_Posted (Expr)
665           and then not Needs_Finalization (Typ)
666         then
667            Warn_Overlay (Expr, Typ, Name (Addr));
668         end if;
669
670         Init := Expression (Decl);
671
672         --  If a variable, or a non-imported constant, overlays a constant
673         --  object and has an initialization value, then the initialization
674         --  may end up writing into read-only memory. Detect the cases of
675         --  statically identical values and remove the initialization. In
676         --  the other cases, give a warning. We will give other warnings
677         --  later for the variable if it is assigned.
678
679         if (Ekind (E) = E_Variable
680              or else (Ekind (E) = E_Constant
681                        and then not Is_Imported (E)))
682           and then Overlays_Constant (E)
683           and then Present (Init)
684         then
685            declare
686               O_Ent : Entity_Id;
687               Off   : Boolean;
688
689            begin
690               Find_Overlaid_Entity (Addr, O_Ent, Off);
691
692               if Ekind (O_Ent) = E_Constant
693                 and then Etype (O_Ent) = Typ
694                 and then Present (Constant_Value (O_Ent))
695                 and then Compile_Time_Compare
696                            (Init,
697                             Constant_Value (O_Ent),
698                             Assume_Valid => True) = EQ
699               then
700                  Set_No_Initialization (Decl);
701                  return;
702
703               elsif Comes_From_Source (Init)
704                 and then Address_Clause_Overlay_Warnings
705               then
706                  Error_Msg_Sloc := Sloc (Addr);
707                  Error_Msg_NE
708                    ("??constant& may be modified via address clause#",
709                     Decl, O_Ent);
710               end if;
711            end;
712         end if;
713
714         --  Remove side effects from initial expression, except in the case
715         --  of a build-in-place call, which has its own later expansion.
716
717         if Present (Init)
718           and then (Nkind (Init) /= N_Function_Call
719             or else not Is_Expanded_Build_In_Place_Call (Init))
720         then
721
722            --  Capture initialization value at point of declaration, and make
723            --  explicit assignment legal, because object may be a constant.
724
725            Remove_Side_Effects (Init);
726            Lhs := New_Occurrence_Of (E, Sloc (Decl));
727            Set_Assignment_OK (Lhs);
728
729            --  Move initialization to freeze actions, once the object has
730            --  been frozen and the address clause alignment check has been
731            --  performed.
732
733            Append_Freeze_Action (E,
734              Make_Assignment_Statement (Sloc (Decl),
735                Name       => Lhs,
736                Expression => Expression (Decl)));
737
738            Set_No_Initialization (Decl);
739
740            --  If the objet is tagged, check whether the tag must be
741            --  reassigned explicitly.
742
743            Tag_Assign := Make_Tag_Assignment (Decl);
744            if Present (Tag_Assign) then
745               Append_Freeze_Action (E, Tag_Assign);
746            end if;
747         end if;
748      end if;
749   end Check_Address_Clause;
750
751   -----------------------------
752   -- Check_Compile_Time_Size --
753   -----------------------------
754
755   procedure Check_Compile_Time_Size (T : Entity_Id) is
756
757      procedure Set_Small_Size (T : Entity_Id; S : Uint);
758      --  Sets the compile time known size (64 bits or less) in the RM_Size
759      --  field of T, checking for a size clause that was given which attempts
760      --  to give a smaller size.
761
762      function Size_Known (T : Entity_Id) return Boolean;
763      --  Recursive function that does all the work
764
765      function Static_Discriminated_Components (T : Entity_Id) return Boolean;
766      --  If T is a constrained subtype, its size is not known if any of its
767      --  discriminant constraints is not static and it is not a null record.
768      --  The test is conservative and doesn't check that the components are
769      --  in fact constrained by non-static discriminant values. Could be made
770      --  more precise ???
771
772      --------------------
773      -- Set_Small_Size --
774      --------------------
775
776      procedure Set_Small_Size (T : Entity_Id; S : Uint) is
777      begin
778         if S > 64 then
779            return;
780
781         --  Check for bad size clause given
782
783         elsif Has_Size_Clause (T) then
784            if RM_Size (T) < S then
785               Error_Msg_Uint_1 := S;
786               Error_Msg_NE
787                 ("size for& too small, minimum allowed is ^",
788                  Size_Clause (T), T);
789            end if;
790
791         --  Set size if not set already
792
793         elsif Unknown_RM_Size (T) then
794            Set_RM_Size (T, S);
795         end if;
796      end Set_Small_Size;
797
798      ----------------
799      -- Size_Known --
800      ----------------
801
802      function Size_Known (T : Entity_Id) return Boolean is
803         Index : Entity_Id;
804         Comp  : Entity_Id;
805         Ctyp  : Entity_Id;
806         Low   : Node_Id;
807         High  : Node_Id;
808
809      begin
810         if Size_Known_At_Compile_Time (T) then
811            return True;
812
813         --  Always True for elementary types, even generic formal elementary
814         --  types. We used to return False in the latter case, but the size
815         --  is known at compile time, even in the template, we just do not
816         --  know the exact size but that's not the point of this routine.
817
818         elsif Is_Elementary_Type (T) or else Is_Task_Type (T) then
819            return True;
820
821         --  Array types
822
823         elsif Is_Array_Type (T) then
824
825            --  String literals always have known size, and we can set it
826
827            if Ekind (T) = E_String_Literal_Subtype then
828               Set_Small_Size
829                 (T, Component_Size (T) * String_Literal_Length (T));
830               return True;
831
832            --  Unconstrained types never have known at compile time size
833
834            elsif not Is_Constrained (T) then
835               return False;
836
837            --  Don't do any recursion on type with error posted, since we may
838            --  have a malformed type that leads us into a loop.
839
840            elsif Error_Posted (T) then
841               return False;
842
843            --  Otherwise if component size unknown, then array size unknown
844
845            elsif not Size_Known (Component_Type (T)) then
846               return False;
847            end if;
848
849            --  Check for all indexes static, and also compute possible size
850            --  (in case it is not greater than 64 and may be packable).
851
852            declare
853               Size : Uint := Component_Size (T);
854               Dim  : Uint;
855
856            begin
857               Index := First_Index (T);
858               while Present (Index) loop
859                  if Nkind (Index) = N_Range then
860                     Get_Index_Bounds (Index, Low, High);
861
862                  elsif Error_Posted (Scalar_Range (Etype (Index))) then
863                     return False;
864
865                  else
866                     Low  := Type_Low_Bound (Etype (Index));
867                     High := Type_High_Bound (Etype (Index));
868                  end if;
869
870                  if not Compile_Time_Known_Value (Low)
871                    or else not Compile_Time_Known_Value (High)
872                    or else Etype (Index) = Any_Type
873                  then
874                     return False;
875
876                  else
877                     Dim := Expr_Value (High) - Expr_Value (Low) + 1;
878
879                     if Dim >= 0 then
880                        Size := Size * Dim;
881                     else
882                        Size := Uint_0;
883                     end if;
884                  end if;
885
886                  Next_Index (Index);
887               end loop;
888
889               Set_Small_Size (T, Size);
890               return True;
891            end;
892
893         --  For non-generic private types, go to underlying type if present
894
895         elsif Is_Private_Type (T)
896           and then not Is_Generic_Type (T)
897           and then Present (Underlying_Type (T))
898         then
899            --  Don't do any recursion on type with error posted, since we may
900            --  have a malformed type that leads us into a loop.
901
902            if Error_Posted (T) then
903               return False;
904            else
905               return Size_Known (Underlying_Type (T));
906            end if;
907
908         --  Record types
909
910         elsif Is_Record_Type (T) then
911
912            --  A class-wide type is never considered to have a known size
913
914            if Is_Class_Wide_Type (T) then
915               return False;
916
917            --  A subtype of a variant record must not have non-static
918            --  discriminated components.
919
920            elsif T /= Base_Type (T)
921              and then not Static_Discriminated_Components (T)
922            then
923               return False;
924
925            --  Don't do any recursion on type with error posted, since we may
926            --  have a malformed type that leads us into a loop.
927
928            elsif Error_Posted (T) then
929               return False;
930            end if;
931
932            --  Now look at the components of the record
933
934            declare
935               --  The following two variables are used to keep track of the
936               --  size of packed records if we can tell the size of the packed
937               --  record in the front end. Packed_Size_Known is True if so far
938               --  we can figure out the size. It is initialized to True for a
939               --  packed record, unless the record has discriminants or atomic
940               --  components or independent components.
941
942               --  The reason we eliminate the discriminated case is that
943               --  we don't know the way the back end lays out discriminated
944               --  packed records. If Packed_Size_Known is True, then
945               --  Packed_Size is the size in bits so far.
946
947               Packed_Size_Known : Boolean :=
948                 Is_Packed (T)
949                   and then not Has_Discriminants (T)
950                   and then not Has_Atomic_Components (T)
951                   and then not Has_Independent_Components (T);
952
953               Packed_Size : Uint := Uint_0;
954               --  Size in bits so far
955
956            begin
957               --  Test for variant part present
958
959               if Has_Discriminants (T)
960                 and then Present (Parent (T))
961                 and then Nkind (Parent (T)) = N_Full_Type_Declaration
962                 and then Nkind (Type_Definition (Parent (T))) =
963                                               N_Record_Definition
964                 and then not Null_Present (Type_Definition (Parent (T)))
965                 and then
966                   Present (Variant_Part
967                              (Component_List (Type_Definition (Parent (T)))))
968               then
969                  --  If variant part is present, and type is unconstrained,
970                  --  then we must have defaulted discriminants, or a size
971                  --  clause must be present for the type, or else the size
972                  --  is definitely not known at compile time.
973
974                  if not Is_Constrained (T)
975                    and then
976                      No (Discriminant_Default_Value (First_Discriminant (T)))
977                    and then Unknown_RM_Size (T)
978                  then
979                     return False;
980                  end if;
981               end if;
982
983               --  Loop through components
984
985               Comp := First_Component_Or_Discriminant (T);
986               while Present (Comp) loop
987                  Ctyp := Etype (Comp);
988
989                  --  We do not know the packed size if there is a component
990                  --  clause present (we possibly could, but this would only
991                  --  help in the case of a record with partial rep clauses.
992                  --  That's because in the case of full rep clauses, the
993                  --  size gets figured out anyway by a different circuit).
994
995                  if Present (Component_Clause (Comp)) then
996                     Packed_Size_Known := False;
997                  end if;
998
999                  --  We do not know the packed size for an atomic/VFA type
1000                  --  or component, or an independent type or component, or a
1001                  --  by-reference type or aliased component (because packing
1002                  --  does not touch these).
1003
1004                  if        Is_Atomic_Or_VFA (Ctyp)
1005                    or else Is_Atomic_Or_VFA (Comp)
1006                    or else Is_Independent (Ctyp)
1007                    or else Is_Independent (Comp)
1008                    or else Is_By_Reference_Type (Ctyp)
1009                    or else Is_Aliased (Comp)
1010                  then
1011                     Packed_Size_Known := False;
1012                  end if;
1013
1014                  --  We need to identify a component that is an array where
1015                  --  the index type is an enumeration type with non-standard
1016                  --  representation, and some bound of the type depends on a
1017                  --  discriminant.
1018
1019                  --  This is because gigi computes the size by doing a
1020                  --  substitution of the appropriate discriminant value in
1021                  --  the size expression for the base type, and gigi is not
1022                  --  clever enough to evaluate the resulting expression (which
1023                  --  involves a call to rep_to_pos) at compile time.
1024
1025                  --  It would be nice if gigi would either recognize that
1026                  --  this expression can be computed at compile time, or
1027                  --  alternatively figured out the size from the subtype
1028                  --  directly, where all the information is at hand ???
1029
1030                  if Is_Array_Type (Etype (Comp))
1031                    and then Present (Packed_Array_Impl_Type (Etype (Comp)))
1032                  then
1033                     declare
1034                        Ocomp  : constant Entity_Id :=
1035                                   Original_Record_Component (Comp);
1036                        OCtyp  : constant Entity_Id := Etype (Ocomp);
1037                        Ind    : Node_Id;
1038                        Indtyp : Entity_Id;
1039                        Lo, Hi : Node_Id;
1040
1041                     begin
1042                        Ind := First_Index (OCtyp);
1043                        while Present (Ind) loop
1044                           Indtyp := Etype (Ind);
1045
1046                           if Is_Enumeration_Type (Indtyp)
1047                             and then Has_Non_Standard_Rep (Indtyp)
1048                           then
1049                              Lo := Type_Low_Bound  (Indtyp);
1050                              Hi := Type_High_Bound (Indtyp);
1051
1052                              if Is_Entity_Name (Lo)
1053                                and then Ekind (Entity (Lo)) = E_Discriminant
1054                              then
1055                                 return False;
1056
1057                              elsif Is_Entity_Name (Hi)
1058                                and then Ekind (Entity (Hi)) = E_Discriminant
1059                              then
1060                                 return False;
1061                              end if;
1062                           end if;
1063
1064                           Next_Index (Ind);
1065                        end loop;
1066                     end;
1067                  end if;
1068
1069                  --  Clearly size of record is not known if the size of one of
1070                  --  the components is not known.
1071
1072                  if not Size_Known (Ctyp) then
1073                     return False;
1074                  end if;
1075
1076                  --  Accumulate packed size if possible
1077
1078                  if Packed_Size_Known then
1079
1080                     --  We can deal with elementary types, small packed arrays
1081                     --  if the representation is a modular type and also small
1082                     --  record types (if the size is not greater than 64, but
1083                     --  the condition is checked by Set_Small_Size).
1084
1085                     if Is_Elementary_Type (Ctyp)
1086                       or else (Is_Array_Type (Ctyp)
1087                                 and then Present
1088                                            (Packed_Array_Impl_Type (Ctyp))
1089                                 and then Is_Modular_Integer_Type
1090                                            (Packed_Array_Impl_Type (Ctyp)))
1091                       or else Is_Record_Type (Ctyp)
1092                     then
1093                        --  If RM_Size is known and static, then we can keep
1094                        --  accumulating the packed size.
1095
1096                        if Known_Static_RM_Size (Ctyp) then
1097
1098                           Packed_Size := Packed_Size + RM_Size (Ctyp);
1099
1100                        --  If we have a field whose RM_Size is not known then
1101                        --  we can't figure out the packed size here.
1102
1103                        else
1104                           Packed_Size_Known := False;
1105                        end if;
1106
1107                     --  For other types we can't figure out the packed size
1108
1109                     else
1110                        Packed_Size_Known := False;
1111                     end if;
1112                  end if;
1113
1114                  Next_Component_Or_Discriminant (Comp);
1115               end loop;
1116
1117               if Packed_Size_Known then
1118                  Set_Small_Size (T, Packed_Size);
1119               end if;
1120
1121               return True;
1122            end;
1123
1124         --  All other cases, size not known at compile time
1125
1126         else
1127            return False;
1128         end if;
1129      end Size_Known;
1130
1131      -------------------------------------
1132      -- Static_Discriminated_Components --
1133      -------------------------------------
1134
1135      function Static_Discriminated_Components
1136        (T : Entity_Id) return Boolean
1137      is
1138         Constraint : Elmt_Id;
1139
1140      begin
1141         if Has_Discriminants (T)
1142           and then Present (Discriminant_Constraint (T))
1143           and then Present (First_Component (T))
1144         then
1145            Constraint := First_Elmt (Discriminant_Constraint (T));
1146            while Present (Constraint) loop
1147               if not Compile_Time_Known_Value (Node (Constraint)) then
1148                  return False;
1149               end if;
1150
1151               Next_Elmt (Constraint);
1152            end loop;
1153         end if;
1154
1155         return True;
1156      end Static_Discriminated_Components;
1157
1158   --  Start of processing for Check_Compile_Time_Size
1159
1160   begin
1161      Set_Size_Known_At_Compile_Time (T, Size_Known (T));
1162   end Check_Compile_Time_Size;
1163
1164   -----------------------------------
1165   -- Check_Component_Storage_Order --
1166   -----------------------------------
1167
1168   procedure Check_Component_Storage_Order
1169     (Encl_Type        : Entity_Id;
1170      Comp             : Entity_Id;
1171      ADC              : Node_Id;
1172      Comp_ADC_Present : out Boolean)
1173   is
1174      Comp_Base : Entity_Id;
1175      Comp_ADC  : Node_Id;
1176      Encl_Base : Entity_Id;
1177      Err_Node  : Node_Id;
1178
1179      Component_Aliased : Boolean;
1180
1181      Comp_Byte_Aligned : Boolean := False;
1182      --  Set for the record case, True if Comp is aligned on byte boundaries
1183      --  (in which case it is allowed to have different storage order).
1184
1185      Comp_SSO_Differs  : Boolean;
1186      --  Set True when the component is a nested composite, and it does not
1187      --  have the same scalar storage order as Encl_Type.
1188
1189   begin
1190      --  Record case
1191
1192      if Present (Comp) then
1193         Err_Node  := Comp;
1194         Comp_Base := Etype (Comp);
1195
1196         if Is_Tag (Comp) then
1197            Comp_Byte_Aligned := True;
1198            Component_Aliased := False;
1199
1200         else
1201            --  If a component clause is present, check if the component starts
1202            --  and ends on byte boundaries. Otherwise conservatively assume it
1203            --  does so only in the case where the record is not packed.
1204
1205            if Present (Component_Clause (Comp)) then
1206               Comp_Byte_Aligned :=
1207                 (Normalized_First_Bit (Comp) mod System_Storage_Unit = 0)
1208                   and then
1209                 (Esize (Comp) mod System_Storage_Unit = 0);
1210            else
1211               Comp_Byte_Aligned := not Is_Packed (Encl_Type);
1212            end if;
1213
1214            Component_Aliased := Is_Aliased (Comp);
1215         end if;
1216
1217      --  Array case
1218
1219      else
1220         Err_Node  := Encl_Type;
1221         Comp_Base := Component_Type (Encl_Type);
1222
1223         Component_Aliased := Has_Aliased_Components (Encl_Type);
1224      end if;
1225
1226      --  Note: the Reverse_Storage_Order flag is set on the base type, but
1227      --  the attribute definition clause is attached to the first subtype.
1228      --  Also, if the base type is incomplete or private, go to full view
1229      --  if known
1230
1231      Encl_Base := Base_Type (Encl_Type);
1232      if Present (Underlying_Type (Encl_Base)) then
1233         Encl_Base := Underlying_Type (Encl_Base);
1234      end if;
1235
1236      Comp_Base := Base_Type (Comp_Base);
1237      if Present (Underlying_Type (Comp_Base)) then
1238         Comp_Base := Underlying_Type (Comp_Base);
1239      end if;
1240
1241      Comp_ADC :=
1242        Get_Attribute_Definition_Clause
1243          (First_Subtype (Comp_Base), Attribute_Scalar_Storage_Order);
1244      Comp_ADC_Present := Present (Comp_ADC);
1245
1246      --  Case of record or array component: check storage order compatibility.
1247      --  But, if the record has Complex_Representation, then it is treated as
1248      --  a scalar in the back end so the storage order is irrelevant.
1249
1250      if (Is_Record_Type (Comp_Base)
1251            and then not Has_Complex_Representation (Comp_Base))
1252        or else Is_Array_Type (Comp_Base)
1253      then
1254         Comp_SSO_Differs :=
1255           Reverse_Storage_Order (Encl_Base) /=
1256             Reverse_Storage_Order (Comp_Base);
1257
1258         --  Parent and extension must have same storage order
1259
1260         if Present (Comp) and then Chars (Comp) = Name_uParent then
1261            if Comp_SSO_Differs then
1262               Error_Msg_N
1263                 ("record extension must have same scalar storage order as "
1264                  & "parent", Err_Node);
1265            end if;
1266
1267         --  If component and composite SSO differs, check that component
1268         --  falls on byte boundaries and isn't bit packed.
1269
1270         elsif Comp_SSO_Differs then
1271
1272            --  Component SSO differs from enclosing composite:
1273
1274            --  Reject if composite is a bit-packed array, as it is rewritten
1275            --  into an array of scalars.
1276
1277            if Is_Bit_Packed_Array (Encl_Base) then
1278               Error_Msg_N
1279                 ("type of packed array must have same scalar storage order "
1280                  & "as component", Err_Node);
1281
1282            --  Reject if not byte aligned
1283
1284            elsif Is_Record_Type (Encl_Base)
1285              and then not Comp_Byte_Aligned
1286            then
1287               Error_Msg_N
1288                 ("type of non-byte-aligned component must have same scalar "
1289                  & "storage order as enclosing composite", Err_Node);
1290
1291            --  Warn if specified only for the outer composite
1292
1293            elsif Present (ADC) and then No (Comp_ADC) then
1294               Error_Msg_NE
1295                 ("scalar storage order specified for & does not apply to "
1296                  & "component?", Err_Node, Encl_Base);
1297            end if;
1298         end if;
1299
1300      --  Enclosing type has explicit SSO: non-composite component must not
1301      --  be aliased.
1302
1303      elsif Present (ADC) and then Component_Aliased then
1304         Error_Msg_N
1305           ("aliased component not permitted for type with explicit "
1306            & "Scalar_Storage_Order", Err_Node);
1307      end if;
1308   end Check_Component_Storage_Order;
1309
1310   -----------------------------
1311   -- Check_Debug_Info_Needed --
1312   -----------------------------
1313
1314   procedure Check_Debug_Info_Needed (T : Entity_Id) is
1315   begin
1316      if Debug_Info_Off (T) then
1317         return;
1318
1319      elsif Comes_From_Source (T)
1320        or else Debug_Generated_Code
1321        or else Debug_Flag_VV
1322        or else Needs_Debug_Info (T)
1323      then
1324         Set_Debug_Info_Needed (T);
1325      end if;
1326   end Check_Debug_Info_Needed;
1327
1328   -------------------------------
1329   -- Check_Expression_Function --
1330   -------------------------------
1331
1332   procedure Check_Expression_Function (N : Node_Id; Nam : Entity_Id) is
1333      function Find_Constant (Nod : Node_Id) return Traverse_Result;
1334      --  Function to search for deferred constant
1335
1336      -------------------
1337      -- Find_Constant --
1338      -------------------
1339
1340      function Find_Constant (Nod : Node_Id) return Traverse_Result is
1341      begin
1342         --  When a constant is initialized with the result of a dispatching
1343         --  call, the constant declaration is rewritten as a renaming of the
1344         --  displaced function result. This scenario is not a premature use of
1345         --  a constant even though the Has_Completion flag is not set.
1346
1347         if Is_Entity_Name (Nod)
1348           and then Present (Entity (Nod))
1349           and then Ekind (Entity (Nod)) = E_Constant
1350           and then Scope (Entity (Nod)) = Current_Scope
1351           and then Nkind (Declaration_Node (Entity (Nod))) =
1352                                                         N_Object_Declaration
1353           and then not Is_Imported (Entity (Nod))
1354           and then not Has_Completion (Entity (Nod))
1355           and then not Is_Frozen (Entity (Nod))
1356         then
1357            Error_Msg_NE
1358              ("premature use of& in call or instance", N, Entity (Nod));
1359
1360         elsif Nkind (Nod) = N_Attribute_Reference then
1361            Analyze (Prefix (Nod));
1362
1363            if Is_Entity_Name (Prefix (Nod))
1364              and then Is_Type (Entity (Prefix (Nod)))
1365            then
1366               Freeze_Before (N, Entity (Prefix (Nod)));
1367            end if;
1368         end if;
1369
1370         return OK;
1371      end Find_Constant;
1372
1373      procedure Check_Deferred is new Traverse_Proc (Find_Constant);
1374
1375      --  Local variables
1376
1377      Decl : Node_Id;
1378
1379   --  Start of processing for Check_Expression_Function
1380
1381   begin
1382      Decl := Original_Node (Unit_Declaration_Node (Nam));
1383
1384      --  The subprogram body created for the expression function is not
1385      --  itself a freeze point.
1386
1387      if Scope (Nam) = Current_Scope
1388        and then Nkind (Decl) = N_Expression_Function
1389        and then Nkind (N) /= N_Subprogram_Body
1390      then
1391         Check_Deferred (Expression (Decl));
1392      end if;
1393   end Check_Expression_Function;
1394
1395   --------------------------------
1396   -- Check_Inherited_Conditions --
1397   --------------------------------
1398
1399   procedure Check_Inherited_Conditions (R : Entity_Id) is
1400      Prim_Ops      : constant Elist_Id := Primitive_Operations (R);
1401      Decls         : List_Id;
1402      Needs_Wrapper : Boolean;
1403      Op_Node       : Elmt_Id;
1404      Par_Prim      : Entity_Id;
1405      Prim          : Entity_Id;
1406
1407      procedure Build_Inherited_Condition_Pragmas (Subp : Entity_Id);
1408      --  Build corresponding pragmas for an operation whose ancestor has
1409      --  class-wide pre/postconditions. If the operation is inherited, the
1410      --  pragmas force the creation of a wrapper for the inherited operation.
1411      --  If the ancestor is being overridden, the pragmas are constructed only
1412      --  to verify their legality, in case they contain calls to other
1413      --  primitives that may haven been overridden.
1414
1415      ---------------------------------------
1416      -- Build_Inherited_Condition_Pragmas --
1417      ---------------------------------------
1418
1419      procedure Build_Inherited_Condition_Pragmas (Subp : Entity_Id) is
1420         A_Post   : Node_Id;
1421         A_Pre    : Node_Id;
1422         New_Prag : Node_Id;
1423
1424      begin
1425         A_Pre := Get_Class_Wide_Pragma (Par_Prim, Pragma_Precondition);
1426
1427         if Present (A_Pre) then
1428            New_Prag := New_Copy_Tree (A_Pre);
1429            Build_Class_Wide_Expression
1430              (Prag          => New_Prag,
1431               Subp          => Prim,
1432               Par_Subp      => Par_Prim,
1433               Adjust_Sloc   => False,
1434               Needs_Wrapper => Needs_Wrapper);
1435
1436            if Needs_Wrapper
1437              and then not Comes_From_Source (Subp)
1438              and then Expander_Active
1439            then
1440               Append (New_Prag, Decls);
1441            end if;
1442         end if;
1443
1444         A_Post := Get_Class_Wide_Pragma (Par_Prim, Pragma_Postcondition);
1445
1446         if Present (A_Post) then
1447            New_Prag := New_Copy_Tree (A_Post);
1448            Build_Class_Wide_Expression
1449              (Prag           => New_Prag,
1450               Subp           => Prim,
1451               Par_Subp       => Par_Prim,
1452               Adjust_Sloc    => False,
1453               Needs_Wrapper  => Needs_Wrapper);
1454
1455            if Needs_Wrapper
1456              and then not Comes_From_Source (Subp)
1457              and then Expander_Active
1458            then
1459               Append (New_Prag, Decls);
1460            end if;
1461         end if;
1462      end Build_Inherited_Condition_Pragmas;
1463
1464   --  Start of processing for Check_Inherited_Conditions
1465
1466   begin
1467      Op_Node := First_Elmt (Prim_Ops);
1468      while Present (Op_Node) loop
1469         Prim := Node (Op_Node);
1470
1471         --  Map the overridden primitive to the overriding one. This takes
1472         --  care of all overridings and is done only once.
1473
1474         if Present (Overridden_Operation (Prim))
1475           and then Comes_From_Source (Prim)
1476         then
1477            Par_Prim := Overridden_Operation (Prim);
1478            Update_Primitives_Mapping (Par_Prim, Prim);
1479         end if;
1480
1481         Next_Elmt (Op_Node);
1482      end loop;
1483
1484      --  Perform validity checks on the inherited conditions of overriding
1485      --  operations, for conformance with LSP, and apply SPARK-specific
1486      --  restrictions on inherited conditions.
1487
1488      Op_Node := First_Elmt (Prim_Ops);
1489      while Present (Op_Node) loop
1490         Prim := Node (Op_Node);
1491
1492         if Present (Overridden_Operation (Prim))
1493           and then Comes_From_Source (Prim)
1494         then
1495            Par_Prim := Overridden_Operation (Prim);
1496
1497            --  Analyze the contract items of the overridden operation, before
1498            --  they are rewritten as pragmas.
1499
1500            Analyze_Entry_Or_Subprogram_Contract (Par_Prim);
1501
1502            --  In GNATprove mode this is where we can collect the inherited
1503            --  conditions, because we do not create the Check pragmas that
1504            --  normally convey the the modified class-wide conditions on
1505            --  overriding operations.
1506
1507            if GNATprove_Mode then
1508               Collect_Inherited_Class_Wide_Conditions (Prim);
1509
1510            --  Otherwise build the corresponding pragmas to check for legality
1511            --  of the inherited condition.
1512
1513            else
1514               Build_Inherited_Condition_Pragmas (Prim);
1515            end if;
1516         end if;
1517
1518         Next_Elmt (Op_Node);
1519      end loop;
1520
1521      --  Now examine the inherited operations to check whether they require
1522      --  a wrapper to handle inherited conditions that call other primitives,
1523      --  so that LSP can be verified/enforced.
1524
1525      Op_Node := First_Elmt (Prim_Ops);
1526      Needs_Wrapper := False;
1527
1528      while Present (Op_Node) loop
1529         Decls := Empty_List;
1530         Prim  := Node (Op_Node);
1531
1532         if not Comes_From_Source (Prim) and then Present (Alias (Prim)) then
1533            Par_Prim := Alias (Prim);
1534
1535            --  Analyze the contract items of the parent operation, and
1536            --  determine whether a wrapper is needed. This is determined
1537            --  when the condition is rewritten in sem_prag, using the
1538            --  mapping between overridden and overriding operations built
1539            --  in the loop above.
1540
1541            Analyze_Entry_Or_Subprogram_Contract (Par_Prim);
1542            Build_Inherited_Condition_Pragmas (Prim);
1543         end if;
1544
1545         if Needs_Wrapper
1546           and then not Is_Abstract_Subprogram (Par_Prim)
1547           and then Expander_Active
1548         then
1549            --  We need to build a new primitive that overrides the inherited
1550            --  one, and whose inherited expression has been updated above.
1551            --  These expressions are the arguments of pragmas that are part
1552            --  of the declarations of the wrapper. The wrapper holds a single
1553            --  statement that is a call to the class-wide clone, where the
1554            --  controlling actuals are conversions to the corresponding type
1555            --  in the parent primitive:
1556
1557            --    procedure New_Prim (F1 : T1; ...);
1558            --    procedure New_Prim (F1 : T1; ...) is
1559            --       pragma Check (Precondition, Expr);
1560            --    begin
1561            --       Par_Prim_Clone (Par_Type (F1), ...);
1562            --    end;
1563
1564            --  If the primitive is a function the statement is a return
1565            --  statement with a call.
1566
1567            declare
1568               Loc      : constant Source_Ptr := Sloc (R);
1569               Par_R    : constant Node_Id    := Parent (R);
1570               New_Body : Node_Id;
1571               New_Decl : Node_Id;
1572               New_Spec : Node_Id;
1573
1574            begin
1575               New_Spec := Build_Overriding_Spec (Par_Prim, R);
1576               New_Decl :=
1577                 Make_Subprogram_Declaration (Loc,
1578                   Specification => New_Spec);
1579
1580               --  Insert the declaration and the body of the wrapper after
1581               --  type declaration that generates inherited operation. For
1582               --  a null procedure, the declaration implies a null body.
1583
1584               if Nkind (New_Spec) = N_Procedure_Specification
1585                 and then Null_Present (New_Spec)
1586               then
1587                  Insert_After_And_Analyze (Par_R, New_Decl);
1588
1589               else
1590                  --  Build body as wrapper to a call to the already built
1591                  --  class-wide clone.
1592
1593                  New_Body :=
1594                    Build_Class_Wide_Clone_Call
1595                      (Loc, Decls, Par_Prim, New_Spec);
1596
1597                  Insert_List_After_And_Analyze
1598                    (Par_R, New_List (New_Decl, New_Body));
1599               end if;
1600            end;
1601
1602            Needs_Wrapper := False;
1603         end if;
1604
1605         Next_Elmt (Op_Node);
1606      end loop;
1607   end Check_Inherited_Conditions;
1608
1609   ----------------------------
1610   -- Check_Strict_Alignment --
1611   ----------------------------
1612
1613   procedure Check_Strict_Alignment (E : Entity_Id) is
1614      Comp  : Entity_Id;
1615
1616   begin
1617      if Is_Tagged_Type (E) or else Is_Concurrent_Type (E) then
1618         Set_Strict_Alignment (E);
1619
1620      elsif Is_Array_Type (E) then
1621         Set_Strict_Alignment (E, Strict_Alignment (Component_Type (E)));
1622
1623      elsif Is_Record_Type (E) then
1624         if Is_Limited_Record (E) then
1625            Set_Strict_Alignment (E);
1626            return;
1627         end if;
1628
1629         Comp := First_Component (E);
1630         while Present (Comp) loop
1631            if not Is_Type (Comp)
1632              and then (Strict_Alignment (Etype (Comp))
1633                         or else Is_Aliased (Comp))
1634            then
1635               Set_Strict_Alignment (E);
1636               return;
1637            end if;
1638
1639            Next_Component (Comp);
1640         end loop;
1641      end if;
1642   end Check_Strict_Alignment;
1643
1644   -------------------------
1645   -- Check_Unsigned_Type --
1646   -------------------------
1647
1648   procedure Check_Unsigned_Type (E : Entity_Id) is
1649      Ancestor : Entity_Id;
1650      Lo_Bound : Node_Id;
1651      Btyp     : Entity_Id;
1652
1653   begin
1654      if not Is_Discrete_Or_Fixed_Point_Type (E) then
1655         return;
1656      end if;
1657
1658      --  Do not attempt to analyze case where range was in error
1659
1660      if No (Scalar_Range (E)) or else Error_Posted (Scalar_Range (E)) then
1661         return;
1662      end if;
1663
1664      --  The situation that is nontrivial is something like:
1665
1666      --     subtype x1 is integer range -10 .. +10;
1667      --     subtype x2 is x1 range 0 .. V1;
1668      --     subtype x3 is x2 range V2 .. V3;
1669      --     subtype x4 is x3 range V4 .. V5;
1670
1671      --  where Vn are variables. Here the base type is signed, but we still
1672      --  know that x4 is unsigned because of the lower bound of x2.
1673
1674      --  The only way to deal with this is to look up the ancestor chain
1675
1676      Ancestor := E;
1677      loop
1678         if Ancestor = Any_Type or else Etype (Ancestor) = Any_Type then
1679            return;
1680         end if;
1681
1682         Lo_Bound := Type_Low_Bound (Ancestor);
1683
1684         if Compile_Time_Known_Value (Lo_Bound) then
1685            if Expr_Rep_Value (Lo_Bound) >= 0 then
1686               Set_Is_Unsigned_Type (E, True);
1687            end if;
1688
1689            return;
1690
1691         else
1692            Ancestor := Ancestor_Subtype (Ancestor);
1693
1694            --  If no ancestor had a static lower bound, go to base type
1695
1696            if No (Ancestor) then
1697
1698               --  Note: the reason we still check for a compile time known
1699               --  value for the base type is that at least in the case of
1700               --  generic formals, we can have bounds that fail this test,
1701               --  and there may be other cases in error situations.
1702
1703               Btyp := Base_Type (E);
1704
1705               if Btyp = Any_Type or else Etype (Btyp) = Any_Type then
1706                  return;
1707               end if;
1708
1709               Lo_Bound := Type_Low_Bound (Base_Type (E));
1710
1711               if Compile_Time_Known_Value (Lo_Bound)
1712                 and then Expr_Rep_Value (Lo_Bound) >= 0
1713               then
1714                  Set_Is_Unsigned_Type (E, True);
1715               end if;
1716
1717               return;
1718            end if;
1719         end if;
1720      end loop;
1721   end Check_Unsigned_Type;
1722
1723   -----------------------------
1724   -- Is_Atomic_VFA_Aggregate --
1725   -----------------------------
1726
1727   function Is_Atomic_VFA_Aggregate (N : Node_Id) return Boolean is
1728      Loc   : constant Source_Ptr := Sloc (N);
1729      New_N : Node_Id;
1730      Par   : Node_Id;
1731      Temp  : Entity_Id;
1732      Typ   : Entity_Id;
1733
1734   begin
1735      Par := Parent (N);
1736
1737      --  Array may be qualified, so find outer context
1738
1739      if Nkind (Par) = N_Qualified_Expression then
1740         Par := Parent (Par);
1741      end if;
1742
1743      if not Comes_From_Source (Par) then
1744         return False;
1745      end if;
1746
1747      case Nkind (Par) is
1748         when N_Assignment_Statement =>
1749            Typ := Etype (Name (Par));
1750
1751            if not Is_Atomic_Or_VFA (Typ)
1752              and then not (Is_Entity_Name (Name (Par))
1753                             and then Is_Atomic_Or_VFA (Entity (Name (Par))))
1754            then
1755               return False;
1756            end if;
1757
1758         when N_Object_Declaration =>
1759            Typ := Etype (Defining_Identifier (Par));
1760
1761            if not Is_Atomic_Or_VFA (Typ)
1762              and then not Is_Atomic_Or_VFA (Defining_Identifier (Par))
1763            then
1764               return False;
1765            end if;
1766
1767         when others =>
1768            return False;
1769      end case;
1770
1771      Temp := Make_Temporary (Loc, 'T', N);
1772      New_N :=
1773        Make_Object_Declaration (Loc,
1774          Defining_Identifier => Temp,
1775          Object_Definition   => New_Occurrence_Of (Typ, Loc),
1776          Expression          => Relocate_Node (N));
1777      Insert_Before (Par, New_N);
1778      Analyze (New_N);
1779
1780      Set_Expression (Par, New_Occurrence_Of (Temp, Loc));
1781      return True;
1782   end Is_Atomic_VFA_Aggregate;
1783
1784   -----------------------------------------------
1785   -- Explode_Initialization_Compound_Statement --
1786   -----------------------------------------------
1787
1788   procedure Explode_Initialization_Compound_Statement (E : Entity_Id) is
1789      Init_Stmts : constant Node_Id := Initialization_Statements (E);
1790
1791   begin
1792      if Present (Init_Stmts)
1793        and then Nkind (Init_Stmts) = N_Compound_Statement
1794      then
1795         Insert_List_Before (Init_Stmts, Actions (Init_Stmts));
1796
1797         --  Note that we rewrite Init_Stmts into a NULL statement, rather than
1798         --  just removing it, because Freeze_All may rely on this particular
1799         --  Node_Id still being present in the enclosing list to know where to
1800         --  stop freezing.
1801
1802         Rewrite (Init_Stmts, Make_Null_Statement (Sloc (Init_Stmts)));
1803
1804         Set_Initialization_Statements (E, Empty);
1805      end if;
1806   end Explode_Initialization_Compound_Statement;
1807
1808   ----------------
1809   -- Freeze_All --
1810   ----------------
1811
1812   --  Note: the easy coding for this procedure would be to just build a
1813   --  single list of freeze nodes and then insert them and analyze them
1814   --  all at once. This won't work, because the analysis of earlier freeze
1815   --  nodes may recursively freeze types which would otherwise appear later
1816   --  on in the freeze list. So we must analyze and expand the freeze nodes
1817   --  as they are generated.
1818
1819   procedure Freeze_All (From : Entity_Id; After : in out Node_Id) is
1820      procedure Freeze_All_Ent (From : Entity_Id; After : in out Node_Id);
1821      --  This is the internal recursive routine that does freezing of entities
1822      --  (but NOT the analysis of default expressions, which should not be
1823      --  recursive, we don't want to analyze those till we are sure that ALL
1824      --  the types are frozen).
1825
1826      --------------------
1827      -- Freeze_All_Ent --
1828      --------------------
1829
1830      procedure Freeze_All_Ent (From : Entity_Id; After : in out Node_Id) is
1831         E     : Entity_Id;
1832         Flist : List_Id;
1833         Lastn : Node_Id;
1834
1835         procedure Process_Flist;
1836         --  If freeze nodes are present, insert and analyze, and reset cursor
1837         --  for next insertion.
1838
1839         -------------------
1840         -- Process_Flist --
1841         -------------------
1842
1843         procedure Process_Flist is
1844         begin
1845            if Is_Non_Empty_List (Flist) then
1846               Lastn := Next (After);
1847               Insert_List_After_And_Analyze (After, Flist);
1848
1849               if Present (Lastn) then
1850                  After := Prev (Lastn);
1851               else
1852                  After := Last (List_Containing (After));
1853               end if;
1854            end if;
1855         end Process_Flist;
1856
1857      --  Start of processing for Freeze_All_Ent
1858
1859      begin
1860         E := From;
1861         while Present (E) loop
1862
1863            --  If the entity is an inner package which is not a package
1864            --  renaming, then its entities must be frozen at this point. Note
1865            --  that such entities do NOT get frozen at the end of the nested
1866            --  package itself (only library packages freeze).
1867
1868            --  Same is true for task declarations, where anonymous records
1869            --  created for entry parameters must be frozen.
1870
1871            if Ekind (E) = E_Package
1872              and then No (Renamed_Object (E))
1873              and then not Is_Child_Unit (E)
1874              and then not Is_Frozen (E)
1875            then
1876               Push_Scope (E);
1877
1878               Install_Visible_Declarations (E);
1879               Install_Private_Declarations (E);
1880               Freeze_All (First_Entity (E), After);
1881
1882               End_Package_Scope (E);
1883
1884               if Is_Generic_Instance (E)
1885                 and then Has_Delayed_Freeze (E)
1886               then
1887                  Set_Has_Delayed_Freeze (E, False);
1888                  Expand_N_Package_Declaration (Unit_Declaration_Node (E));
1889               end if;
1890
1891            elsif Ekind (E) in Task_Kind
1892              and then Nkind_In (Parent (E), N_Single_Task_Declaration,
1893                                             N_Task_Type_Declaration)
1894            then
1895               Push_Scope (E);
1896               Freeze_All (First_Entity (E), After);
1897               End_Scope;
1898
1899            --  For a derived tagged type, we must ensure that all the
1900            --  primitive operations of the parent have been frozen, so that
1901            --  their addresses will be in the parent's dispatch table at the
1902            --  point it is inherited.
1903
1904            elsif Ekind (E) = E_Record_Type
1905              and then Is_Tagged_Type (E)
1906              and then Is_Tagged_Type (Etype (E))
1907              and then Is_Derived_Type (E)
1908            then
1909               declare
1910                  Prim_List : constant Elist_Id :=
1911                               Primitive_Operations (Etype (E));
1912
1913                  Prim : Elmt_Id;
1914                  Subp : Entity_Id;
1915
1916               begin
1917                  Prim := First_Elmt (Prim_List);
1918                  while Present (Prim) loop
1919                     Subp := Node (Prim);
1920
1921                     if Comes_From_Source (Subp)
1922                       and then not Is_Frozen (Subp)
1923                     then
1924                        Flist := Freeze_Entity (Subp, After);
1925                        Process_Flist;
1926                     end if;
1927
1928                     Next_Elmt (Prim);
1929                  end loop;
1930               end;
1931            end if;
1932
1933            if not Is_Frozen (E) then
1934               Flist := Freeze_Entity (E, After);
1935               Process_Flist;
1936
1937            --  If already frozen, and there are delayed aspects, this is where
1938            --  we do the visibility check for these aspects (see Sem_Ch13 spec
1939            --  for a description of how we handle aspect visibility).
1940
1941            elsif Has_Delayed_Aspects (E) then
1942
1943               --  Retrieve the visibility to the discriminants in order to
1944               --  analyze properly the aspects.
1945
1946               Push_Scope_And_Install_Discriminants (E);
1947
1948               declare
1949                  Ritem : Node_Id;
1950
1951               begin
1952                  Ritem := First_Rep_Item (E);
1953                  while Present (Ritem) loop
1954                     if Nkind (Ritem) = N_Aspect_Specification
1955                       and then Entity (Ritem) = E
1956                       and then Is_Delayed_Aspect (Ritem)
1957                     then
1958                        Check_Aspect_At_End_Of_Declarations (Ritem);
1959                     end if;
1960
1961                     Ritem := Next_Rep_Item (Ritem);
1962                  end loop;
1963               end;
1964
1965               Uninstall_Discriminants_And_Pop_Scope (E);
1966            end if;
1967
1968            --  If an incomplete type is still not frozen, this may be a
1969            --  premature freezing because of a body declaration that follows.
1970            --  Indicate where the freezing took place. Freezing will happen
1971            --  if the body comes from source, but not if it is internally
1972            --  generated, for example as the body of a type invariant.
1973
1974            --  If the freezing is caused by the end of the current declarative
1975            --  part, it is a Taft Amendment type, and there is no error.
1976
1977            if not Is_Frozen (E)
1978              and then Ekind (E) = E_Incomplete_Type
1979            then
1980               declare
1981                  Bod : constant Node_Id := Next (After);
1982
1983               begin
1984                  --  The presence of a body freezes all entities previously
1985                  --  declared in the current list of declarations, but this
1986                  --  does not apply if the body does not come from source.
1987                  --  A type invariant is transformed into a subprogram body
1988                  --  which is placed at the end of the private part of the
1989                  --  current package, but this body does not freeze incomplete
1990                  --  types that may be declared in this private part.
1991
1992                  if (Nkind_In (Bod, N_Entry_Body,
1993                                     N_Package_Body,
1994                                     N_Protected_Body,
1995                                     N_Subprogram_Body,
1996                                     N_Task_Body)
1997                        or else Nkind (Bod) in N_Body_Stub)
1998                    and then
1999                      List_Containing (After) = List_Containing (Parent (E))
2000                    and then Comes_From_Source (Bod)
2001                  then
2002                     Error_Msg_Sloc := Sloc (Next (After));
2003                     Error_Msg_NE
2004                       ("type& is frozen# before its full declaration",
2005                         Parent (E), E);
2006                  end if;
2007               end;
2008            end if;
2009
2010            Next_Entity (E);
2011         end loop;
2012      end Freeze_All_Ent;
2013
2014      --  Local variables
2015
2016      Decl : Node_Id;
2017      E    : Entity_Id;
2018      Item : Entity_Id;
2019
2020   --  Start of processing for Freeze_All
2021
2022   begin
2023      Freeze_All_Ent (From, After);
2024
2025      --  Now that all types are frozen, we can deal with default expressions
2026      --  that require us to build a default expression functions. This is the
2027      --  point at which such functions are constructed (after all types that
2028      --  might be used in such expressions have been frozen).
2029
2030      --  For subprograms that are renaming_as_body, we create the wrapper
2031      --  bodies as needed.
2032
2033      --  We also add finalization chains to access types whose designated
2034      --  types are controlled. This is normally done when freezing the type,
2035      --  but this misses recursive type definitions where the later members
2036      --  of the recursion introduce controlled components.
2037
2038      --  Loop through entities
2039
2040      E := From;
2041      while Present (E) loop
2042         if Is_Subprogram (E) then
2043            if not Default_Expressions_Processed (E) then
2044               Process_Default_Expressions (E, After);
2045            end if;
2046
2047            if not Has_Completion (E) then
2048               Decl := Unit_Declaration_Node (E);
2049
2050               if Nkind (Decl) = N_Subprogram_Renaming_Declaration then
2051                  if Error_Posted (Decl) then
2052                     Set_Has_Completion (E);
2053                  else
2054                     Build_And_Analyze_Renamed_Body (Decl, E, After);
2055                  end if;
2056
2057               elsif Nkind (Decl) = N_Subprogram_Declaration
2058                 and then Present (Corresponding_Body (Decl))
2059                 and then
2060                   Nkind (Unit_Declaration_Node (Corresponding_Body (Decl))) =
2061                     N_Subprogram_Renaming_Declaration
2062               then
2063                  Build_And_Analyze_Renamed_Body
2064                    (Decl, Corresponding_Body (Decl), After);
2065               end if;
2066            end if;
2067
2068         --  Freeze the default expressions of entries, entry families, and
2069         --  protected subprograms.
2070
2071         elsif Is_Concurrent_Type (E) then
2072            Item := First_Entity (E);
2073            while Present (Item) loop
2074               if (Is_Entry (Item) or else Is_Subprogram (Item))
2075                 and then not Default_Expressions_Processed (Item)
2076               then
2077                  Process_Default_Expressions (Item, After);
2078               end if;
2079
2080               Next_Entity (Item);
2081            end loop;
2082         end if;
2083
2084         --  Historical note: We used to create a finalization master for an
2085         --  access type whose designated type is not controlled, but contains
2086         --  private controlled compoments. This form of postprocessing is no
2087         --  longer needed because the finalization master is now created when
2088         --  the access type is frozen (see Exp_Ch3.Freeze_Type).
2089
2090         Next_Entity (E);
2091      end loop;
2092   end Freeze_All;
2093
2094   -----------------------
2095   -- Freeze_And_Append --
2096   -----------------------
2097
2098   procedure Freeze_And_Append
2099     (Ent    : Entity_Id;
2100      N      : Node_Id;
2101      Result : in out List_Id)
2102   is
2103      L : constant List_Id := Freeze_Entity (Ent, N);
2104   begin
2105      if Is_Non_Empty_List (L) then
2106         if Result = No_List then
2107            Result := L;
2108         else
2109            Append_List (L, Result);
2110         end if;
2111      end if;
2112   end Freeze_And_Append;
2113
2114   -------------------
2115   -- Freeze_Before --
2116   -------------------
2117
2118   procedure Freeze_Before
2119     (N                 : Node_Id;
2120      T                 : Entity_Id;
2121      Do_Freeze_Profile : Boolean := True)
2122   is
2123      --  Freeze T, then insert the generated Freeze nodes before the node N.
2124      --  Flag Freeze_Profile is used when T is an overloadable entity, and
2125      --  indicates whether its profile should be frozen at the same time.
2126
2127      Freeze_Nodes : constant List_Id :=
2128                       Freeze_Entity (T, N, Do_Freeze_Profile);
2129      Pack         : constant Entity_Id := Scope (T);
2130
2131   begin
2132      if Ekind (T) = E_Function then
2133         Check_Expression_Function (N, T);
2134      end if;
2135
2136      if Is_Non_Empty_List (Freeze_Nodes) then
2137
2138         --  If the entity is a type declared in an inner package, it may be
2139         --  frozen by an outer declaration before the package itself is
2140         --  frozen. Install the package scope to analyze the freeze nodes,
2141         --  which may include generated subprograms such as predicate
2142         --  functions, etc.
2143
2144         if Is_Type (T) and then From_Nested_Package (T) then
2145            Push_Scope (Pack);
2146            Install_Visible_Declarations (Pack);
2147            Install_Private_Declarations (Pack);
2148            Insert_Actions (N, Freeze_Nodes);
2149            End_Package_Scope (Pack);
2150
2151         else
2152            Insert_Actions (N, Freeze_Nodes);
2153         end if;
2154      end if;
2155   end Freeze_Before;
2156
2157   -------------------
2158   -- Freeze_Entity --
2159   -------------------
2160
2161   --  WARNING: This routine manages Ghost regions. Return statements must be
2162   --  replaced by gotos which jump to the end of the routine and restore the
2163   --  Ghost mode.
2164
2165   function Freeze_Entity
2166     (E                 : Entity_Id;
2167      N                 : Node_Id;
2168      Do_Freeze_Profile : Boolean := True) return List_Id
2169   is
2170      Loc    : constant Source_Ptr := Sloc (N);
2171      Atype  : Entity_Id;
2172      Comp   : Entity_Id;
2173      F_Node : Node_Id;
2174      Formal : Entity_Id;
2175      Indx   : Node_Id;
2176
2177      Has_Default_Initialization : Boolean := False;
2178      --  This flag gets set to true for a variable with default initialization
2179
2180      Result : List_Id := No_List;
2181      --  List of freezing actions, left at No_List if none
2182
2183      Test_E : Entity_Id := E;
2184      --  This could use a comment ???
2185
2186      procedure Add_To_Result (N : Node_Id);
2187      --  N is a freezing action to be appended to the Result
2188
2189      function After_Last_Declaration return Boolean;
2190      --  If Loc is a freeze_entity that appears after the last declaration
2191      --  in the scope, inhibit error messages on late completion.
2192
2193      procedure Check_Current_Instance (Comp_Decl : Node_Id);
2194      --  Check that an Access or Unchecked_Access attribute with a prefix
2195      --  which is the current instance type can only be applied when the type
2196      --  is limited.
2197
2198      procedure Check_Suspicious_Convention (Rec_Type : Entity_Id);
2199      --  Give a warning for pragma Convention with language C or C++ applied
2200      --  to a discriminated record type. This is suppressed for the unchecked
2201      --  union case, since the whole point in this case is interface C. We
2202      --  also do not generate this within instantiations, since we will have
2203      --  generated a message on the template.
2204
2205      procedure Check_Suspicious_Modulus (Utype : Entity_Id);
2206      --  Give warning for modulus of 8, 16, 32, or 64 given as an explicit
2207      --  integer literal without an explicit corresponding size clause. The
2208      --  caller has checked that Utype is a modular integer type.
2209
2210      procedure Freeze_Array_Type (Arr : Entity_Id);
2211      --  Freeze array type, including freezing index and component types
2212
2213      procedure Freeze_Object_Declaration (E : Entity_Id);
2214      --  Perform checks and generate freeze node if needed for a constant or
2215      --  variable declared by an object declaration.
2216
2217      function Freeze_Generic_Entities (Pack : Entity_Id) return List_Id;
2218      --  Create Freeze_Generic_Entity nodes for types declared in a generic
2219      --  package. Recurse on inner generic packages.
2220
2221      function Freeze_Profile (E : Entity_Id) return Boolean;
2222      --  Freeze formals and return type of subprogram. If some type in the
2223      --  profile is incomplete and we are in an instance, freezing of the
2224      --  entity will take place elsewhere, and the function returns False.
2225
2226      procedure Freeze_Record_Type (Rec : Entity_Id);
2227      --  Freeze record type, including freezing component types, and freezing
2228      --  primitive operations if this is a tagged type.
2229
2230      function Has_Boolean_Aspect_Import (E : Entity_Id) return Boolean;
2231      --  Determine whether an arbitrary entity is subject to Boolean aspect
2232      --  Import and its value is specified as True.
2233
2234      procedure Inherit_Freeze_Node
2235        (Fnod : Node_Id;
2236         Typ  : Entity_Id);
2237      --  Set type Typ's freeze node to refer to Fnode. This routine ensures
2238      --  that any attributes attached to Typ's original node are preserved.
2239
2240      procedure Wrap_Imported_Subprogram (E : Entity_Id);
2241      --  If E is an entity for an imported subprogram with pre/post-conditions
2242      --  then this procedure will create a wrapper to ensure that proper run-
2243      --  time checking of the pre/postconditions. See body for details.
2244
2245      -------------------
2246      -- Add_To_Result --
2247      -------------------
2248
2249      procedure Add_To_Result (N : Node_Id) is
2250      begin
2251         if No (Result) then
2252            Result := New_List (N);
2253         else
2254            Append (N, Result);
2255         end if;
2256      end Add_To_Result;
2257
2258      ----------------------------
2259      -- After_Last_Declaration --
2260      ----------------------------
2261
2262      function After_Last_Declaration return Boolean is
2263         Spec : constant Node_Id := Parent (Current_Scope);
2264
2265      begin
2266         if Nkind (Spec) = N_Package_Specification then
2267            if Present (Private_Declarations (Spec)) then
2268               return Loc >= Sloc (Last (Private_Declarations (Spec)));
2269            elsif Present (Visible_Declarations (Spec)) then
2270               return Loc >= Sloc (Last (Visible_Declarations (Spec)));
2271            else
2272               return False;
2273            end if;
2274
2275         else
2276            return False;
2277         end if;
2278      end After_Last_Declaration;
2279
2280      ----------------------------
2281      -- Check_Current_Instance --
2282      ----------------------------
2283
2284      procedure Check_Current_Instance (Comp_Decl : Node_Id) is
2285
2286         function Is_Aliased_View_Of_Type (Typ : Entity_Id) return Boolean;
2287         --  Determine whether Typ is compatible with the rules for aliased
2288         --  views of types as defined in RM 3.10 in the various dialects.
2289
2290         function Process (N : Node_Id) return Traverse_Result;
2291         --  Process routine to apply check to given node
2292
2293         -----------------------------
2294         -- Is_Aliased_View_Of_Type --
2295         -----------------------------
2296
2297         function Is_Aliased_View_Of_Type (Typ : Entity_Id) return Boolean is
2298            Typ_Decl : constant Node_Id := Parent (Typ);
2299
2300         begin
2301            --  Common case
2302
2303            if Nkind (Typ_Decl) = N_Full_Type_Declaration
2304              and then Limited_Present (Type_Definition (Typ_Decl))
2305            then
2306               return True;
2307
2308            --  The following paragraphs describe what a legal aliased view of
2309            --  a type is in the various dialects of Ada.
2310
2311            --  Ada 95
2312
2313            --  The current instance of a limited type, and a formal parameter
2314            --  or generic formal object of a tagged type.
2315
2316            --  Ada 95 limited type
2317            --    * Type with reserved word "limited"
2318            --    * A protected or task type
2319            --    * A composite type with limited component
2320
2321            elsif Ada_Version <= Ada_95 then
2322               return Is_Limited_Type (Typ);
2323
2324            --  Ada 2005
2325
2326            --  The current instance of a limited tagged type, a protected
2327            --  type, a task type, or a type that has the reserved word
2328            --  "limited" in its full definition ... a formal parameter or
2329            --  generic formal object of a tagged type.
2330
2331            --  Ada 2005 limited type
2332            --    * Type with reserved word "limited", "synchronized", "task"
2333            --      or "protected"
2334            --    * A composite type with limited component
2335            --    * A derived type whose parent is a non-interface limited type
2336
2337            elsif Ada_Version = Ada_2005 then
2338               return
2339                 (Is_Limited_Type (Typ) and then Is_Tagged_Type (Typ))
2340                   or else
2341                     (Is_Derived_Type (Typ)
2342                       and then not Is_Interface (Etype (Typ))
2343                       and then Is_Limited_Type (Etype (Typ)));
2344
2345            --  Ada 2012 and beyond
2346
2347            --  The current instance of an immutably limited type ... a formal
2348            --  parameter or generic formal object of a tagged type.
2349
2350            --  Ada 2012 limited type
2351            --    * Type with reserved word "limited", "synchronized", "task"
2352            --      or "protected"
2353            --    * A composite type with limited component
2354            --    * A derived type whose parent is a non-interface limited type
2355            --    * An incomplete view
2356
2357            --  Ada 2012 immutably limited type
2358            --    * Explicitly limited record type
2359            --    * Record extension with "limited" present
2360            --    * Non-formal limited private type that is either tagged
2361            --      or has at least one access discriminant with a default
2362            --      expression
2363            --    * Task type, protected type or synchronized interface
2364            --    * Type derived from immutably limited type
2365
2366            else
2367               return
2368                 Is_Immutably_Limited_Type (Typ)
2369                   or else Is_Incomplete_Type (Typ);
2370            end if;
2371         end Is_Aliased_View_Of_Type;
2372
2373         -------------
2374         -- Process --
2375         -------------
2376
2377         function Process (N : Node_Id) return Traverse_Result is
2378         begin
2379            case Nkind (N) is
2380               when N_Attribute_Reference =>
2381                  if Nam_In (Attribute_Name (N), Name_Access,
2382                                                 Name_Unchecked_Access)
2383                    and then Is_Entity_Name (Prefix (N))
2384                    and then Is_Type (Entity (Prefix (N)))
2385                    and then Entity (Prefix (N)) = E
2386                  then
2387                     if Ada_Version < Ada_2012 then
2388                        Error_Msg_N
2389                          ("current instance must be a limited type",
2390                           Prefix (N));
2391                     else
2392                        Error_Msg_N
2393                          ("current instance must be an immutably limited "
2394                           & "type (RM-2012, 7.5 (8.1/3))", Prefix (N));
2395                     end if;
2396
2397                     return Abandon;
2398
2399                  else
2400                     return OK;
2401                  end if;
2402
2403               when others =>
2404                  return OK;
2405            end case;
2406         end Process;
2407
2408         procedure Traverse is new Traverse_Proc (Process);
2409
2410         --  Local variables
2411
2412         Rec_Type : constant Entity_Id :=
2413                      Scope (Defining_Identifier (Comp_Decl));
2414
2415      --  Start of processing for Check_Current_Instance
2416
2417      begin
2418         if not Is_Aliased_View_Of_Type (Rec_Type) then
2419            Traverse (Comp_Decl);
2420         end if;
2421      end Check_Current_Instance;
2422
2423      ---------------------------------
2424      -- Check_Suspicious_Convention --
2425      ---------------------------------
2426
2427      procedure Check_Suspicious_Convention (Rec_Type : Entity_Id) is
2428      begin
2429         if Has_Discriminants (Rec_Type)
2430           and then Is_Base_Type (Rec_Type)
2431           and then not Is_Unchecked_Union (Rec_Type)
2432           and then (Convention (Rec_Type) = Convention_C
2433                       or else
2434                     Convention (Rec_Type) = Convention_CPP)
2435           and then Comes_From_Source (Rec_Type)
2436           and then not In_Instance
2437           and then not Has_Warnings_Off (Rec_Type)
2438         then
2439            declare
2440               Cprag : constant Node_Id :=
2441                         Get_Rep_Pragma (Rec_Type, Name_Convention);
2442               A2    : Node_Id;
2443
2444            begin
2445               if Present (Cprag) then
2446                  A2 := Next (First (Pragma_Argument_Associations (Cprag)));
2447
2448                  if Convention (Rec_Type) = Convention_C then
2449                     Error_Msg_N
2450                       ("?x?discriminated record has no direct equivalent in "
2451                        & "C", A2);
2452                  else
2453                     Error_Msg_N
2454                       ("?x?discriminated record has no direct equivalent in "
2455                        & "C++", A2);
2456                  end if;
2457
2458                  Error_Msg_NE
2459                    ("\?x?use of convention for type& is dubious",
2460                     A2, Rec_Type);
2461               end if;
2462            end;
2463         end if;
2464      end Check_Suspicious_Convention;
2465
2466      ------------------------------
2467      -- Check_Suspicious_Modulus --
2468      ------------------------------
2469
2470      procedure Check_Suspicious_Modulus (Utype : Entity_Id) is
2471         Decl : constant Node_Id := Declaration_Node (Underlying_Type (Utype));
2472
2473      begin
2474         if not Warn_On_Suspicious_Modulus_Value then
2475            return;
2476         end if;
2477
2478         if Nkind (Decl) = N_Full_Type_Declaration then
2479            declare
2480               Tdef : constant Node_Id := Type_Definition (Decl);
2481
2482            begin
2483               if Nkind (Tdef) = N_Modular_Type_Definition then
2484                  declare
2485                     Modulus : constant Node_Id :=
2486                                 Original_Node (Expression (Tdef));
2487
2488                  begin
2489                     if Nkind (Modulus) = N_Integer_Literal then
2490                        declare
2491                           Modv : constant Uint := Intval (Modulus);
2492                           Sizv : constant Uint := RM_Size (Utype);
2493
2494                        begin
2495                           --  First case, modulus and size are the same. This
2496                           --  happens if you have something like mod 32, with
2497                           --  an explicit size of 32, this is for sure a case
2498                           --  where the warning is given, since it is seems
2499                           --  very unlikely that someone would want e.g. a
2500                           --  five bit type stored in 32 bits. It is much
2501                           --  more likely they wanted a 32-bit type.
2502
2503                           if Modv = Sizv then
2504                              null;
2505
2506                           --  Second case, the modulus is 32 or 64 and no
2507                           --  size clause is present. This is a less clear
2508                           --  case for giving the warning, but in the case
2509                           --  of 32/64 (5-bit or 6-bit types) these seem rare
2510                           --  enough that it is a likely error (and in any
2511                           --  case using 2**5 or 2**6 in these cases seems
2512                           --  clearer. We don't include 8 or 16 here, simply
2513                           --  because in practice 3-bit and 4-bit types are
2514                           --  more common and too many false positives if
2515                           --  we warn in these cases.
2516
2517                           elsif not Has_Size_Clause (Utype)
2518                             and then (Modv = Uint_32 or else Modv = Uint_64)
2519                           then
2520                              null;
2521
2522                           --  No warning needed
2523
2524                           else
2525                              return;
2526                           end if;
2527
2528                           --  If we fall through, give warning
2529
2530                           Error_Msg_Uint_1 := Modv;
2531                           Error_Msg_N
2532                             ("?M?2 '*'*^' may have been intended here",
2533                              Modulus);
2534                        end;
2535                     end if;
2536                  end;
2537               end if;
2538            end;
2539         end if;
2540      end Check_Suspicious_Modulus;
2541
2542      -----------------------
2543      -- Freeze_Array_Type --
2544      -----------------------
2545
2546      procedure Freeze_Array_Type (Arr : Entity_Id) is
2547         FS     : constant Entity_Id := First_Subtype (Arr);
2548         Ctyp   : constant Entity_Id := Component_Type (Arr);
2549         Clause : Entity_Id;
2550
2551         Non_Standard_Enum : Boolean := False;
2552         --  Set true if any of the index types is an enumeration type with a
2553         --  non-standard representation.
2554
2555      begin
2556         Freeze_And_Append (Ctyp, N, Result);
2557
2558         Indx := First_Index (Arr);
2559         while Present (Indx) loop
2560            Freeze_And_Append (Etype (Indx), N, Result);
2561
2562            if Is_Enumeration_Type (Etype (Indx))
2563              and then Has_Non_Standard_Rep (Etype (Indx))
2564            then
2565               Non_Standard_Enum := True;
2566            end if;
2567
2568            Next_Index (Indx);
2569         end loop;
2570
2571         --  Processing that is done only for base types
2572
2573         if Ekind (Arr) = E_Array_Type then
2574
2575            --  Deal with default setting of reverse storage order
2576
2577            Set_SSO_From_Default (Arr);
2578
2579            --  Propagate flags for component type
2580
2581            if Is_Controlled (Component_Type (Arr))
2582              or else Has_Controlled_Component (Ctyp)
2583            then
2584               Set_Has_Controlled_Component (Arr);
2585            end if;
2586
2587            if Has_Unchecked_Union (Component_Type (Arr)) then
2588               Set_Has_Unchecked_Union (Arr);
2589            end if;
2590
2591            --  The array type requires its own invariant procedure in order to
2592            --  verify the component invariant over all elements. In GNATprove
2593            --  mode, the component invariants are checked by other means. They
2594            --  should not be added to the array type invariant procedure, so
2595            --  that the procedure can be used to check the array type
2596            --  invariants if any.
2597
2598            if Has_Invariants (Component_Type (Arr))
2599              and then not GNATprove_Mode
2600            then
2601               Set_Has_Own_Invariants (Arr);
2602
2603               --  The array type is an implementation base type. Propagate the
2604               --  same property to the first subtype.
2605
2606               if Is_Itype (Arr) then
2607                  Set_Has_Own_Invariants (First_Subtype (Arr));
2608               end if;
2609            end if;
2610
2611            --  Warn for pragma Pack overriding foreign convention
2612
2613            if Has_Foreign_Convention (Ctyp)
2614              and then Has_Pragma_Pack (Arr)
2615            then
2616               declare
2617                  CN : constant Name_Id :=
2618                         Get_Convention_Name (Convention (Ctyp));
2619                  PP : constant Node_Id :=
2620                         Get_Pragma (First_Subtype (Arr), Pragma_Pack);
2621               begin
2622                  if Present (PP) then
2623                     Error_Msg_Name_1 := CN;
2624                     Error_Msg_Sloc := Sloc (Arr);
2625                     Error_Msg_N
2626                       ("pragma Pack affects convention % components #??", PP);
2627                     Error_Msg_Name_1 := CN;
2628                     Error_Msg_N
2629                       ("\array components may not have % compatible "
2630                        & "representation??", PP);
2631                  end if;
2632               end;
2633            end if;
2634
2635            --  If packing was requested or if the component size was
2636            --  set explicitly, then see if bit packing is required. This
2637            --  processing is only done for base types, since all of the
2638            --  representation aspects involved are type-related.
2639
2640            --  This is not just an optimization, if we start processing the
2641            --  subtypes, they interfere with the settings on the base type
2642            --  (this is because Is_Packed has a slightly different meaning
2643            --  before and after freezing).
2644
2645            declare
2646               Csiz : Uint;
2647               Esiz : Uint;
2648
2649            begin
2650               if (Is_Packed (Arr) or else Has_Pragma_Pack (Arr))
2651                 and then Known_Static_RM_Size (Ctyp)
2652                 and then not Has_Component_Size_Clause (Arr)
2653               then
2654                  Csiz := UI_Max (RM_Size (Ctyp), 1);
2655
2656               elsif Known_Component_Size (Arr) then
2657                  Csiz := Component_Size (Arr);
2658
2659               elsif not Known_Static_Esize (Ctyp) then
2660                  Csiz := Uint_0;
2661
2662               else
2663                  Esiz := Esize (Ctyp);
2664
2665                  --  We can set the component size if it is less than 16,
2666                  --  rounding it up to the next storage unit size.
2667
2668                  if Esiz <= 8 then
2669                     Csiz := Uint_8;
2670                  elsif Esiz <= 16 then
2671                     Csiz := Uint_16;
2672                  else
2673                     Csiz := Uint_0;
2674                  end if;
2675
2676                  --  Set component size up to match alignment if it would
2677                  --  otherwise be less than the alignment. This deals with
2678                  --  cases of types whose alignment exceeds their size (the
2679                  --  padded type cases).
2680
2681                  if Csiz /= 0 then
2682                     declare
2683                        A : constant Uint := Alignment_In_Bits (Ctyp);
2684                     begin
2685                        if Csiz < A then
2686                           Csiz := A;
2687                        end if;
2688                     end;
2689                  end if;
2690               end if;
2691
2692               --  Case of component size that may result in bit packing
2693
2694               if 1 <= Csiz and then Csiz <= 64 then
2695                  declare
2696                     Ent         : constant Entity_Id :=
2697                                     First_Subtype (Arr);
2698                     Pack_Pragma : constant Node_Id :=
2699                                     Get_Rep_Pragma (Ent, Name_Pack);
2700                     Comp_Size_C : constant Node_Id :=
2701                                     Get_Attribute_Definition_Clause
2702                                       (Ent, Attribute_Component_Size);
2703
2704                  begin
2705                     --  Warn if we have pack and component size so that the
2706                     --  pack is ignored.
2707
2708                     --  Note: here we must check for the presence of a
2709                     --  component size before checking for a Pack pragma to
2710                     --  deal with the case where the array type is a derived
2711                     --  type whose parent is currently private.
2712
2713                     if Present (Comp_Size_C)
2714                       and then Has_Pragma_Pack (Ent)
2715                       and then Warn_On_Redundant_Constructs
2716                     then
2717                        Error_Msg_Sloc := Sloc (Comp_Size_C);
2718                        Error_Msg_NE
2719                          ("?r?pragma Pack for& ignored!", Pack_Pragma, Ent);
2720                        Error_Msg_N
2721                          ("\?r?explicit component size given#!", Pack_Pragma);
2722                        Set_Is_Packed (Base_Type (Ent), False);
2723                        Set_Is_Bit_Packed_Array (Base_Type (Ent), False);
2724                     end if;
2725
2726                     --  Set component size if not already set by a component
2727                     --  size clause.
2728
2729                     if not Present (Comp_Size_C) then
2730                        Set_Component_Size (Arr, Csiz);
2731                     end if;
2732
2733                     --  Check for base type of 8, 16, 32 bits, where an
2734                     --  unsigned subtype has a length one less than the
2735                     --  base type (e.g. Natural subtype of Integer).
2736
2737                     --  In such cases, if a component size was not set
2738                     --  explicitly, then generate a warning.
2739
2740                     if Has_Pragma_Pack (Arr)
2741                       and then not Present (Comp_Size_C)
2742                       and then (Csiz = 7 or else Csiz = 15 or else Csiz = 31)
2743                       and then Esize (Base_Type (Ctyp)) = Csiz + 1
2744                     then
2745                        Error_Msg_Uint_1 := Csiz;
2746
2747                        if Present (Pack_Pragma) then
2748                           Error_Msg_N
2749                             ("??pragma Pack causes component size to be ^!",
2750                              Pack_Pragma);
2751                           Error_Msg_N
2752                             ("\??use Component_Size to set desired value!",
2753                              Pack_Pragma);
2754                        end if;
2755                     end if;
2756
2757                     --  Bit packing is never needed for 8, 16, 32, 64
2758
2759                     if Addressable (Csiz) then
2760
2761                        --  If the Esize of the component is known and equal to
2762                        --  the component size then even packing is not needed.
2763
2764                        if Known_Static_Esize (Component_Type (Arr))
2765                          and then Esize (Component_Type (Arr)) = Csiz
2766                        then
2767                           --  Here the array was requested to be packed, but
2768                           --  the packing request had no effect whatsoever,
2769                           --  so flag Is_Packed is reset.
2770
2771                           --  Note: semantically this means that we lose track
2772                           --  of the fact that a derived type inherited pragma
2773                           --  Pack that was non-effective, but that is fine.
2774
2775                           --  We regard a Pack pragma as a request to set a
2776                           --  representation characteristic, and this request
2777                           --  may be ignored.
2778
2779                           Set_Is_Packed            (Base_Type (Arr), False);
2780                           Set_Has_Non_Standard_Rep (Base_Type (Arr), False);
2781                        else
2782                           Set_Is_Packed            (Base_Type (Arr), True);
2783                           Set_Has_Non_Standard_Rep (Base_Type (Arr), True);
2784                        end if;
2785
2786                        Set_Is_Bit_Packed_Array (Base_Type (Arr), False);
2787
2788                     --  Bit packing is not needed for multiples of the storage
2789                     --  unit if the type is composite because the back end can
2790                     --  byte pack composite types.
2791
2792                     elsif Csiz mod System_Storage_Unit = 0
2793                       and then Is_Composite_Type (Ctyp)
2794                     then
2795                        Set_Is_Packed            (Base_Type (Arr), True);
2796                        Set_Has_Non_Standard_Rep (Base_Type (Arr), True);
2797                        Set_Is_Bit_Packed_Array  (Base_Type (Arr), False);
2798
2799                     --  In all other cases, bit packing is needed
2800
2801                     else
2802                        Set_Is_Packed            (Base_Type (Arr), True);
2803                        Set_Has_Non_Standard_Rep (Base_Type (Arr), True);
2804                        Set_Is_Bit_Packed_Array  (Base_Type (Arr), True);
2805                     end if;
2806                  end;
2807               end if;
2808            end;
2809
2810            --  Check for Aliased or Atomic_Components/Atomic/VFA with
2811            --  unsuitable packing or explicit component size clause given.
2812
2813            if (Has_Aliased_Components (Arr)
2814                 or else Has_Atomic_Components (Arr)
2815                 or else Is_Atomic_Or_VFA (Ctyp))
2816              and then
2817                (Has_Component_Size_Clause (Arr) or else Is_Packed (Arr))
2818            then
2819               Alias_Atomic_Check : declare
2820
2821                  procedure Complain_CS (T : String);
2822                  --  Outputs error messages for incorrect CS clause or pragma
2823                  --  Pack for aliased or atomic/VFA components (T is "aliased"
2824                  --  or "atomic/vfa");
2825
2826                  -----------------
2827                  -- Complain_CS --
2828                  -----------------
2829
2830                  procedure Complain_CS (T : String) is
2831                  begin
2832                     if Has_Component_Size_Clause (Arr) then
2833                        Clause :=
2834                          Get_Attribute_Definition_Clause
2835                            (FS, Attribute_Component_Size);
2836
2837                        Error_Msg_N
2838                          ("incorrect component size for "
2839                           & T & " components", Clause);
2840                        Error_Msg_Uint_1 := Esize (Ctyp);
2841                        Error_Msg_N
2842                          ("\only allowed value is^", Clause);
2843
2844                     else
2845                        Error_Msg_N
2846                          ("cannot pack " & T & " components",
2847                           Get_Rep_Pragma (FS, Name_Pack));
2848                     end if;
2849                  end Complain_CS;
2850
2851                  --  Start of processing for Alias_Atomic_Check
2852
2853               begin
2854                  --  If object size of component type isn't known, we cannot
2855                  --  be sure so we defer to the back end.
2856
2857                  if not Known_Static_Esize (Ctyp) then
2858                     null;
2859
2860                  --  Case where component size has no effect. First check for
2861                  --  object size of component type multiple of the storage
2862                  --  unit size.
2863
2864                  elsif Esize (Ctyp) mod System_Storage_Unit = 0
2865
2866                    --  OK in both packing case and component size case if RM
2867                    --  size is known and static and same as the object size.
2868
2869                    and then
2870                      ((Known_Static_RM_Size (Ctyp)
2871                         and then Esize (Ctyp) = RM_Size (Ctyp))
2872
2873                        --  Or if we have an explicit component size clause and
2874                        --  the component size and object size are equal.
2875
2876                        or else
2877                          (Has_Component_Size_Clause (Arr)
2878                            and then Component_Size (Arr) = Esize (Ctyp)))
2879                  then
2880                     null;
2881
2882                  elsif Has_Aliased_Components (Arr) then
2883                     Complain_CS ("aliased");
2884
2885                  elsif Has_Atomic_Components (Arr)
2886                    or else Is_Atomic (Ctyp)
2887                  then
2888                     Complain_CS ("atomic");
2889
2890                  elsif Is_Volatile_Full_Access (Ctyp) then
2891                     Complain_CS ("volatile full access");
2892                  end if;
2893               end Alias_Atomic_Check;
2894            end if;
2895
2896            --  Check for Independent_Components/Independent with unsuitable
2897            --  packing or explicit component size clause given.
2898
2899            if (Has_Independent_Components (Arr) or else Is_Independent (Ctyp))
2900                  and then
2901               (Has_Component_Size_Clause  (Arr) or else Is_Packed (Arr))
2902            then
2903               begin
2904                  --  If object size of component type isn't known, we cannot
2905                  --  be sure so we defer to the back end.
2906
2907                  if not Known_Static_Esize (Ctyp) then
2908                     null;
2909
2910                  --  Case where component size has no effect. First check for
2911                  --  object size of component type multiple of the storage
2912                  --  unit size.
2913
2914                  elsif Esize (Ctyp) mod System_Storage_Unit = 0
2915
2916                    --  OK in both packing case and component size case if RM
2917                    --  size is known and multiple of the storage unit size.
2918
2919                    and then
2920                      ((Known_Static_RM_Size (Ctyp)
2921                         and then RM_Size (Ctyp) mod System_Storage_Unit = 0)
2922
2923                        --  Or if we have an explicit component size clause and
2924                        --  the component size is larger than the object size.
2925
2926                        or else
2927                          (Has_Component_Size_Clause (Arr)
2928                            and then Component_Size (Arr) >= Esize (Ctyp)))
2929                  then
2930                     null;
2931
2932                  else
2933                     if Has_Component_Size_Clause (Arr) then
2934                        Clause :=
2935                          Get_Attribute_Definition_Clause
2936                            (FS, Attribute_Component_Size);
2937
2938                        Error_Msg_N
2939                          ("incorrect component size for "
2940                           & "independent components", Clause);
2941                        Error_Msg_Uint_1 := Esize (Ctyp);
2942                        Error_Msg_N
2943                          ("\minimum allowed is^", Clause);
2944
2945                     else
2946                        Error_Msg_N
2947                          ("cannot pack independent components",
2948                           Get_Rep_Pragma (FS, Name_Pack));
2949                     end if;
2950                  end if;
2951               end;
2952            end if;
2953
2954            --  Warn for case of atomic type
2955
2956            Clause := Get_Rep_Pragma (FS, Name_Atomic);
2957
2958            if Present (Clause)
2959              and then not Addressable (Component_Size (FS))
2960            then
2961               Error_Msg_NE
2962                 ("non-atomic components of type& may not be "
2963                  & "accessible by separate tasks??", Clause, Arr);
2964
2965               if Has_Component_Size_Clause (Arr) then
2966                  Error_Msg_Sloc := Sloc (Get_Attribute_Definition_Clause
2967                                           (FS, Attribute_Component_Size));
2968                  Error_Msg_N ("\because of component size clause#??", Clause);
2969
2970               elsif Has_Pragma_Pack (Arr) then
2971                  Error_Msg_Sloc := Sloc (Get_Rep_Pragma (FS, Name_Pack));
2972                  Error_Msg_N ("\because of pragma Pack#??", Clause);
2973               end if;
2974            end if;
2975
2976            --  Check for scalar storage order
2977
2978            declare
2979               Dummy : Boolean;
2980            begin
2981               Check_Component_Storage_Order
2982                 (Encl_Type        => Arr,
2983                  Comp             => Empty,
2984                  ADC              => Get_Attribute_Definition_Clause
2985                                        (First_Subtype (Arr),
2986                                         Attribute_Scalar_Storage_Order),
2987                  Comp_ADC_Present => Dummy);
2988            end;
2989
2990         --  Processing that is done only for subtypes
2991
2992         else
2993            --  Acquire alignment from base type
2994
2995            if Unknown_Alignment (Arr) then
2996               Set_Alignment (Arr, Alignment (Base_Type (Arr)));
2997               Adjust_Esize_Alignment (Arr);
2998            end if;
2999         end if;
3000
3001         --  Specific checks for bit-packed arrays
3002
3003         if Is_Bit_Packed_Array (Arr) then
3004
3005            --  Check number of elements for bit-packed arrays that come from
3006            --  source and have compile time known ranges. The bit-packed
3007            --  arrays circuitry does not support arrays with more than
3008            --  Integer'Last + 1 elements, and when this restriction is
3009            --  violated, causes incorrect data access.
3010
3011            --  For the case where this is not compile time known, a run-time
3012            --  check should be generated???
3013
3014            if Comes_From_Source (Arr) and then Is_Constrained (Arr) then
3015               declare
3016                  Elmts : Uint;
3017                  Index : Node_Id;
3018                  Ilen  : Node_Id;
3019                  Ityp  : Entity_Id;
3020
3021               begin
3022                  Elmts := Uint_1;
3023                  Index := First_Index (Arr);
3024                  while Present (Index) loop
3025                     Ityp := Etype (Index);
3026
3027                     --  Never generate an error if any index is of a generic
3028                     --  type. We will check this in instances.
3029
3030                     if Is_Generic_Type (Ityp) then
3031                        Elmts := Uint_0;
3032                        exit;
3033                     end if;
3034
3035                     Ilen :=
3036                       Make_Attribute_Reference (Loc,
3037                         Prefix         => New_Occurrence_Of (Ityp, Loc),
3038                         Attribute_Name => Name_Range_Length);
3039                     Analyze_And_Resolve (Ilen);
3040
3041                     --  No attempt is made to check number of elements if not
3042                     --  compile time known.
3043
3044                     if Nkind (Ilen) /= N_Integer_Literal then
3045                        Elmts := Uint_0;
3046                        exit;
3047                     end if;
3048
3049                     Elmts := Elmts * Intval (Ilen);
3050                     Next_Index (Index);
3051                  end loop;
3052
3053                  if Elmts > Intval (High_Bound
3054                                       (Scalar_Range (Standard_Integer))) + 1
3055                  then
3056                     Error_Msg_N
3057                       ("bit packed array type may not have "
3058                        & "more than Integer''Last+1 elements", Arr);
3059                  end if;
3060               end;
3061            end if;
3062
3063            --  Check size
3064
3065            if Known_RM_Size (Arr) then
3066               declare
3067                  SizC    : constant Node_Id := Size_Clause (Arr);
3068                  Discard : Boolean;
3069
3070               begin
3071                  --  It is not clear if it is possible to have no size clause
3072                  --  at this stage, but it is not worth worrying about. Post
3073                  --  error on the entity name in the size clause if present,
3074                  --  else on the type entity itself.
3075
3076                  if Present (SizC) then
3077                     Check_Size (Name (SizC), Arr, RM_Size (Arr), Discard);
3078                  else
3079                     Check_Size (Arr, Arr, RM_Size (Arr), Discard);
3080                  end if;
3081               end;
3082            end if;
3083         end if;
3084
3085         --  If any of the index types was an enumeration type with a non-
3086         --  standard rep clause, then we indicate that the array type is
3087         --  always packed (even if it is not bit-packed).
3088
3089         if Non_Standard_Enum then
3090            Set_Has_Non_Standard_Rep (Base_Type (Arr));
3091            Set_Is_Packed            (Base_Type (Arr));
3092         end if;
3093
3094         Set_Component_Alignment_If_Not_Set (Arr);
3095
3096         --  If the array is packed and bit-packed or packed to eliminate holes
3097         --  in the non-contiguous enumeration index types, we must create the
3098         --  packed array type to be used to actually implement the type. This
3099         --  is only needed for real array types (not for string literal types,
3100         --  since they are present only for the front end).
3101
3102         if Is_Packed (Arr)
3103           and then (Is_Bit_Packed_Array (Arr) or else Non_Standard_Enum)
3104           and then Ekind (Arr) /= E_String_Literal_Subtype
3105         then
3106            Create_Packed_Array_Impl_Type (Arr);
3107            Freeze_And_Append (Packed_Array_Impl_Type (Arr), N, Result);
3108
3109            --  Make sure that we have the necessary routines to implement the
3110            --  packing, and complain now if not. Note that we only test this
3111            --  for constrained array types.
3112
3113            if Is_Constrained (Arr)
3114              and then Is_Bit_Packed_Array (Arr)
3115              and then Present (Packed_Array_Impl_Type (Arr))
3116              and then Is_Array_Type (Packed_Array_Impl_Type (Arr))
3117            then
3118               declare
3119                  CS : constant Uint  := Component_Size (Arr);
3120                  RE : constant RE_Id := Get_Id (UI_To_Int (CS));
3121
3122               begin
3123                  if RE /= RE_Null
3124                    and then not RTE_Available (RE)
3125                  then
3126                     Error_Msg_CRT
3127                       ("packing of " & UI_Image (CS) & "-bit components",
3128                        First_Subtype (Etype (Arr)));
3129
3130                     --  Cancel the packing
3131
3132                     Set_Is_Packed (Base_Type (Arr), False);
3133                     Set_Is_Bit_Packed_Array (Base_Type (Arr), False);
3134                     Set_Packed_Array_Impl_Type (Arr, Empty);
3135                     goto Skip_Packed;
3136                  end if;
3137               end;
3138            end if;
3139
3140            --  Size information of packed array type is copied to the array
3141            --  type, since this is really the representation. But do not
3142            --  override explicit existing size values. If the ancestor subtype
3143            --  is constrained the Packed_Array_Impl_Type will be inherited
3144            --  from it, but the size may have been provided already, and
3145            --  must not be overridden either.
3146
3147            if not Has_Size_Clause (Arr)
3148              and then
3149                (No (Ancestor_Subtype (Arr))
3150                  or else not Has_Size_Clause (Ancestor_Subtype (Arr)))
3151            then
3152               Set_Esize     (Arr, Esize     (Packed_Array_Impl_Type (Arr)));
3153               Set_RM_Size   (Arr, RM_Size   (Packed_Array_Impl_Type (Arr)));
3154            end if;
3155
3156            if not Has_Alignment_Clause (Arr) then
3157               Set_Alignment (Arr, Alignment (Packed_Array_Impl_Type (Arr)));
3158            end if;
3159         end if;
3160
3161         <<Skip_Packed>>
3162
3163         --  For non-packed arrays set the alignment of the array to the
3164         --  alignment of the component type if it is unknown. Skip this
3165         --  in atomic/VFA case (atomic/VFA arrays may need larger alignments).
3166
3167         if not Is_Packed (Arr)
3168           and then Unknown_Alignment (Arr)
3169           and then Known_Alignment (Ctyp)
3170           and then Known_Static_Component_Size (Arr)
3171           and then Known_Static_Esize (Ctyp)
3172           and then Esize (Ctyp) = Component_Size (Arr)
3173           and then not Is_Atomic_Or_VFA (Arr)
3174         then
3175            Set_Alignment (Arr, Alignment (Component_Type (Arr)));
3176         end if;
3177
3178         --  A Ghost type cannot have a component of protected or task type
3179         --  (SPARK RM 6.9(19)).
3180
3181         if Is_Ghost_Entity (Arr) and then Is_Concurrent_Type (Ctyp) then
3182            Error_Msg_N
3183              ("ghost array type & cannot have concurrent component type",
3184               Arr);
3185         end if;
3186      end Freeze_Array_Type;
3187
3188      -------------------------------
3189      -- Freeze_Object_Declaration --
3190      -------------------------------
3191
3192      procedure Freeze_Object_Declaration (E : Entity_Id) is
3193      begin
3194         --  Abstract type allowed only for C++ imported variables or constants
3195
3196         --  Note: we inhibit this check for objects that do not come from
3197         --  source because there is at least one case (the expansion of
3198         --  x'Class'Input where x is abstract) where we legitimately
3199         --  generate an abstract object.
3200
3201         if Is_Abstract_Type (Etype (E))
3202           and then Comes_From_Source (Parent (E))
3203           and then not (Is_Imported (E) and then Is_CPP_Class (Etype (E)))
3204         then
3205            Error_Msg_N ("type of object cannot be abstract",
3206                         Object_Definition (Parent (E)));
3207
3208            if Is_CPP_Class (Etype (E)) then
3209               Error_Msg_NE
3210                 ("\} may need a cpp_constructor",
3211                  Object_Definition (Parent (E)), Etype (E));
3212
3213            elsif Present (Expression (Parent (E))) then
3214               Error_Msg_N --  CODEFIX
3215                 ("\maybe a class-wide type was meant",
3216                  Object_Definition (Parent (E)));
3217            end if;
3218         end if;
3219
3220         --  For object created by object declaration, perform required
3221         --  categorization (preelaborate and pure) checks. Defer these
3222         --  checks to freeze time since pragma Import inhibits default
3223         --  initialization and thus pragma Import affects these checks.
3224
3225         Validate_Object_Declaration (Declaration_Node (E));
3226
3227         --  If there is an address clause, check that it is valid
3228         --  and if need be move initialization to the freeze node.
3229
3230         Check_Address_Clause (E);
3231
3232         --  Similar processing is needed for aspects that may affect
3233         --  object layout, like Alignment, if there is an initialization
3234         --  expression. We don't do this if there is a pragma Linker_Section,
3235         --  because it would prevent the back end from statically initializing
3236         --  the object; we don't want elaboration code in that case.
3237
3238         if Has_Delayed_Aspects (E)
3239           and then Expander_Active
3240           and then Is_Array_Type (Etype (E))
3241           and then Present (Expression (Parent (E)))
3242           and then No (Linker_Section_Pragma (E))
3243         then
3244            declare
3245               Decl : constant Node_Id := Parent (E);
3246               Lhs  : constant Node_Id := New_Occurrence_Of (E, Loc);
3247
3248            begin
3249
3250               --  Capture initialization value at point of declaration, and
3251               --  make explicit assignment legal, because object may be a
3252               --  constant.
3253
3254               Remove_Side_Effects (Expression (Decl));
3255               Set_Assignment_OK (Lhs);
3256
3257               --  Move initialization to freeze actions.
3258
3259               Append_Freeze_Action (E,
3260                 Make_Assignment_Statement (Loc,
3261                   Name       => Lhs,
3262                   Expression => Expression (Decl)));
3263
3264               Set_No_Initialization (Decl);
3265               --  Set_Is_Frozen (E, False);
3266            end;
3267         end if;
3268
3269         --  Reset Is_True_Constant for non-constant aliased object. We
3270         --  consider that the fact that a non-constant object is aliased may
3271         --  indicate that some funny business is going on, e.g. an aliased
3272         --  object is passed by reference to a procedure which captures the
3273         --  address of the object, which is later used to assign a new value,
3274         --  even though the compiler thinks that it is not modified. Such
3275         --  code is highly dubious, but we choose to make it "work" for
3276         --  non-constant aliased objects.
3277
3278         --  Note that we used to do this for all aliased objects, whether or
3279         --  not constant, but this caused anomalies down the line because we
3280         --  ended up with static objects that were not Is_True_Constant. Not
3281         --  resetting Is_True_Constant for (aliased) constant objects ensures
3282         --  that this anomaly never occurs.
3283
3284         --  However, we don't do that for internal entities. We figure that if
3285         --  we deliberately set Is_True_Constant for an internal entity, e.g.
3286         --  a dispatch table entry, then we mean it.
3287
3288         if Ekind (E) /= E_Constant
3289           and then (Is_Aliased (E) or else Is_Aliased (Etype (E)))
3290           and then not Is_Internal_Name (Chars (E))
3291         then
3292            Set_Is_True_Constant (E, False);
3293         end if;
3294
3295         --  If the object needs any kind of default initialization, an error
3296         --  must be issued if No_Default_Initialization applies. The check
3297         --  doesn't apply to imported objects, which are not ever default
3298         --  initialized, and is why the check is deferred until freezing, at
3299         --  which point we know if Import applies. Deferred constants are also
3300         --  exempted from this test because their completion is explicit, or
3301         --  through an import pragma.
3302
3303         if Ekind (E) = E_Constant and then Present (Full_View (E)) then
3304            null;
3305
3306         elsif Comes_From_Source (E)
3307           and then not Is_Imported (E)
3308           and then not Has_Init_Expression (Declaration_Node (E))
3309           and then
3310             ((Has_Non_Null_Base_Init_Proc (Etype (E))
3311                and then not No_Initialization (Declaration_Node (E))
3312                and then not Initialization_Suppressed (Etype (E)))
3313              or else
3314                (Needs_Simple_Initialization (Etype (E))
3315                  and then not Is_Internal (E)))
3316         then
3317            Has_Default_Initialization := True;
3318            Check_Restriction
3319              (No_Default_Initialization, Declaration_Node (E));
3320         end if;
3321
3322         --  Check that a Thread_Local_Storage variable does not have
3323         --  default initialization, and any explicit initialization must
3324         --  either be the null constant or a static constant.
3325
3326         if Has_Pragma_Thread_Local_Storage (E) then
3327            declare
3328               Decl : constant Node_Id := Declaration_Node (E);
3329            begin
3330               if Has_Default_Initialization
3331                 or else
3332                   (Has_Init_Expression (Decl)
3333                     and then
3334                      (No (Expression (Decl))
3335                        or else not
3336                          (Is_OK_Static_Expression (Expression (Decl))
3337                            or else Nkind (Expression (Decl)) = N_Null)))
3338               then
3339                  Error_Msg_NE
3340                    ("Thread_Local_Storage variable& is "
3341                     & "improperly initialized", Decl, E);
3342                  Error_Msg_NE
3343                    ("\only allowed initialization is explicit "
3344                     & "NULL or static expression", Decl, E);
3345               end if;
3346            end;
3347         end if;
3348
3349         --  For imported objects, set Is_Public unless there is also an
3350         --  address clause, which means that there is no external symbol
3351         --  needed for the Import (Is_Public may still be set for other
3352         --  unrelated reasons). Note that we delayed this processing
3353         --  till freeze time so that we can be sure not to set the flag
3354         --  if there is an address clause. If there is such a clause,
3355         --  then the only purpose of the Import pragma is to suppress
3356         --  implicit initialization.
3357
3358         if Is_Imported (E) and then No (Address_Clause (E)) then
3359            Set_Is_Public (E);
3360         end if;
3361
3362         --  For source objects that are not Imported and are library
3363         --  level, if no linker section pragma was given inherit the
3364         --  appropriate linker section from the corresponding type.
3365
3366         if Comes_From_Source (E)
3367           and then not Is_Imported (E)
3368           and then Is_Library_Level_Entity (E)
3369           and then No (Linker_Section_Pragma (E))
3370         then
3371            Set_Linker_Section_Pragma
3372              (E, Linker_Section_Pragma (Etype (E)));
3373         end if;
3374
3375         --  For convention C objects of an enumeration type, warn if the
3376         --  size is not integer size and no explicit size given. Skip
3377         --  warning for Boolean, and Character, assume programmer expects
3378         --  8-bit sizes for these cases.
3379
3380         if (Convention (E) = Convention_C
3381               or else
3382             Convention (E) = Convention_CPP)
3383           and then Is_Enumeration_Type (Etype (E))
3384           and then not Is_Character_Type (Etype (E))
3385           and then not Is_Boolean_Type (Etype (E))
3386           and then Esize (Etype (E)) < Standard_Integer_Size
3387           and then not Has_Size_Clause (E)
3388         then
3389            Error_Msg_Uint_1 := UI_From_Int (Standard_Integer_Size);
3390            Error_Msg_N
3391              ("??convention C enumeration object has size less than ^", E);
3392            Error_Msg_N ("\??use explicit size clause to set size", E);
3393         end if;
3394      end Freeze_Object_Declaration;
3395
3396      -----------------------------
3397      -- Freeze_Generic_Entities --
3398      -----------------------------
3399
3400      function Freeze_Generic_Entities (Pack : Entity_Id) return List_Id is
3401         E     : Entity_Id;
3402         F     : Node_Id;
3403         Flist : List_Id;
3404
3405      begin
3406         Flist := New_List;
3407         E := First_Entity (Pack);
3408         while Present (E) loop
3409            if Is_Type (E) and then not Is_Generic_Type (E) then
3410               F := Make_Freeze_Generic_Entity (Sloc (Pack));
3411               Set_Entity (F, E);
3412               Append_To (Flist, F);
3413
3414            elsif Ekind (E) = E_Generic_Package then
3415               Append_List_To (Flist, Freeze_Generic_Entities (E));
3416            end if;
3417
3418            Next_Entity (E);
3419         end loop;
3420
3421         return Flist;
3422      end Freeze_Generic_Entities;
3423
3424      --------------------
3425      -- Freeze_Profile --
3426      --------------------
3427
3428      function Freeze_Profile (E : Entity_Id) return Boolean is
3429         F_Type    : Entity_Id;
3430         R_Type    : Entity_Id;
3431         Warn_Node : Node_Id;
3432
3433      begin
3434         --  Loop through formals
3435
3436         Formal := First_Formal (E);
3437         while Present (Formal) loop
3438            F_Type := Etype (Formal);
3439
3440            --  AI05-0151: incomplete types can appear in a profile. By the
3441            --  time the entity is frozen, the full view must be available,
3442            --  unless it is a limited view.
3443
3444            if Is_Incomplete_Type (F_Type)
3445              and then Present (Full_View (F_Type))
3446              and then not From_Limited_With (F_Type)
3447            then
3448               F_Type := Full_View (F_Type);
3449               Set_Etype (Formal, F_Type);
3450            end if;
3451
3452            if not From_Limited_With (F_Type) then
3453               Freeze_And_Append (F_Type, N, Result);
3454            end if;
3455
3456            if Is_Private_Type (F_Type)
3457              and then Is_Private_Type (Base_Type (F_Type))
3458              and then No (Full_View (Base_Type (F_Type)))
3459              and then not Is_Generic_Type (F_Type)
3460              and then not Is_Derived_Type (F_Type)
3461            then
3462               --  If the type of a formal is incomplete, subprogram is being
3463               --  frozen prematurely. Within an instance (but not within a
3464               --  wrapper package) this is an artifact of our need to regard
3465               --  the end of an instantiation as a freeze point. Otherwise it
3466               --  is a definite error.
3467
3468               if In_Instance then
3469                  Set_Is_Frozen (E, False);
3470                  Result := No_List;
3471                  return False;
3472
3473               elsif not After_Last_Declaration
3474                 and then not Freezing_Library_Level_Tagged_Type
3475               then
3476                  Error_Msg_Node_1 := F_Type;
3477                  Error_Msg
3478                    ("type & must be fully defined before this point", Loc);
3479               end if;
3480            end if;
3481
3482            --  Check suspicious parameter for C function. These tests apply
3483            --  only to exported/imported subprograms.
3484
3485            if Warn_On_Export_Import
3486              and then Comes_From_Source (E)
3487              and then (Convention (E) = Convention_C
3488                          or else
3489                        Convention (E) = Convention_CPP)
3490              and then (Is_Imported (E) or else Is_Exported (E))
3491              and then Convention (E) /= Convention (Formal)
3492              and then not Has_Warnings_Off (E)
3493              and then not Has_Warnings_Off (F_Type)
3494              and then not Has_Warnings_Off (Formal)
3495            then
3496               --  Qualify mention of formals with subprogram name
3497
3498               Error_Msg_Qual_Level := 1;
3499
3500               --  Check suspicious use of fat C pointer
3501
3502               if Is_Access_Type (F_Type)
3503                 and then Esize (F_Type) > Ttypes.System_Address_Size
3504               then
3505                  Error_Msg_N
3506                    ("?x?type of & does not correspond to C pointer!", Formal);
3507
3508               --  Check suspicious return of boolean
3509
3510               elsif Root_Type (F_Type) = Standard_Boolean
3511                 and then Convention (F_Type) = Convention_Ada
3512                 and then not Has_Warnings_Off (F_Type)
3513                 and then not Has_Size_Clause (F_Type)
3514               then
3515                  Error_Msg_N
3516                    ("& is an 8-bit Ada Boolean?x?", Formal);
3517                  Error_Msg_N
3518                    ("\use appropriate corresponding type in C "
3519                     & "(e.g. char)?x?", Formal);
3520
3521               --  Check suspicious tagged type
3522
3523               elsif (Is_Tagged_Type (F_Type)
3524                       or else
3525                        (Is_Access_Type (F_Type)
3526                          and then Is_Tagged_Type (Designated_Type (F_Type))))
3527                 and then Convention (E) = Convention_C
3528               then
3529                  Error_Msg_N
3530                    ("?x?& involves a tagged type which does not "
3531                     & "correspond to any C type!", Formal);
3532
3533               --  Check wrong convention subprogram pointer
3534
3535               elsif Ekind (F_Type) = E_Access_Subprogram_Type
3536                 and then not Has_Foreign_Convention (F_Type)
3537               then
3538                  Error_Msg_N
3539                    ("?x?subprogram pointer & should "
3540                     & "have foreign convention!", Formal);
3541                  Error_Msg_Sloc := Sloc (F_Type);
3542                  Error_Msg_NE
3543                    ("\?x?add Convention pragma to declaration of &#",
3544                     Formal, F_Type);
3545               end if;
3546
3547               --  Turn off name qualification after message output
3548
3549               Error_Msg_Qual_Level := 0;
3550            end if;
3551
3552            --  Check for unconstrained array in exported foreign convention
3553            --  case.
3554
3555            if Has_Foreign_Convention (E)
3556              and then not Is_Imported (E)
3557              and then Is_Array_Type (F_Type)
3558              and then not Is_Constrained (F_Type)
3559              and then Warn_On_Export_Import
3560            then
3561               Error_Msg_Qual_Level := 1;
3562
3563               --  If this is an inherited operation, place the warning on
3564               --  the derived type declaration, rather than on the original
3565               --  subprogram.
3566
3567               if Nkind (Original_Node (Parent (E))) = N_Full_Type_Declaration
3568               then
3569                  Warn_Node := Parent (E);
3570
3571                  if Formal = First_Formal (E) then
3572                     Error_Msg_NE ("??in inherited operation&", Warn_Node, E);
3573                  end if;
3574               else
3575                  Warn_Node := Formal;
3576               end if;
3577
3578               Error_Msg_NE ("?x?type of argument& is unconstrained array",
3579                  Warn_Node, Formal);
3580               Error_Msg_NE ("?x?foreign caller must pass bounds explicitly",
3581                  Warn_Node, Formal);
3582               Error_Msg_Qual_Level := 0;
3583            end if;
3584
3585            if not From_Limited_With (F_Type) then
3586               if Is_Access_Type (F_Type) then
3587                  F_Type := Designated_Type (F_Type);
3588               end if;
3589
3590               --  If the formal is an anonymous_access_to_subprogram
3591               --  freeze the  subprogram type as well, to prevent
3592               --  scope anomalies in gigi, because there is no other
3593               --  clear point at which it could be frozen.
3594
3595               if Is_Itype (Etype (Formal))
3596                 and then Ekind (F_Type) = E_Subprogram_Type
3597               then
3598                  Freeze_And_Append (F_Type, N, Result);
3599               end if;
3600            end if;
3601
3602            Next_Formal (Formal);
3603         end loop;
3604
3605         --  Case of function: similar checks on return type
3606
3607         if Ekind (E) = E_Function then
3608
3609            --  Freeze return type
3610
3611            R_Type := Etype (E);
3612
3613            --  AI05-0151: the return type may have been incomplete at the
3614            --  point of declaration. Replace it with the full view, unless the
3615            --  current type is a limited view. In that case the full view is
3616            --  in a different unit, and gigi finds the non-limited view after
3617            --  the other unit is elaborated.
3618
3619            if Ekind (R_Type) = E_Incomplete_Type
3620              and then Present (Full_View (R_Type))
3621              and then not From_Limited_With (R_Type)
3622            then
3623               R_Type := Full_View (R_Type);
3624               Set_Etype (E, R_Type);
3625            end if;
3626
3627            Freeze_And_Append (R_Type, N, Result);
3628
3629            --  Check suspicious return type for C function
3630
3631            if Warn_On_Export_Import
3632              and then (Convention (E) = Convention_C
3633                          or else
3634                        Convention (E) = Convention_CPP)
3635              and then (Is_Imported (E) or else Is_Exported (E))
3636            then
3637               --  Check suspicious return of fat C pointer
3638
3639               if Is_Access_Type (R_Type)
3640                 and then Esize (R_Type) > Ttypes.System_Address_Size
3641                 and then not Has_Warnings_Off (E)
3642                 and then not Has_Warnings_Off (R_Type)
3643               then
3644                  Error_Msg_N
3645                    ("?x?return type of& does not correspond to C pointer!",
3646                     E);
3647
3648               --  Check suspicious return of boolean
3649
3650               elsif Root_Type (R_Type) = Standard_Boolean
3651                 and then Convention (R_Type) = Convention_Ada
3652                 and then not Has_Warnings_Off (E)
3653                 and then not Has_Warnings_Off (R_Type)
3654                 and then not Has_Size_Clause (R_Type)
3655               then
3656                  declare
3657                     N : constant Node_Id :=
3658                           Result_Definition (Declaration_Node (E));
3659                  begin
3660                     Error_Msg_NE
3661                       ("return type of & is an 8-bit Ada Boolean?x?", N, E);
3662                     Error_Msg_NE
3663                       ("\use appropriate corresponding type in C "
3664                        & "(e.g. char)?x?", N, E);
3665                  end;
3666
3667               --  Check suspicious return tagged type
3668
3669               elsif (Is_Tagged_Type (R_Type)
3670                       or else (Is_Access_Type (R_Type)
3671                                 and then
3672                                   Is_Tagged_Type
3673                                     (Designated_Type (R_Type))))
3674                 and then Convention (E) = Convention_C
3675                 and then not Has_Warnings_Off (E)
3676                 and then not Has_Warnings_Off (R_Type)
3677               then
3678                  Error_Msg_N ("?x?return type of & does not "
3679                     & "correspond to C type!", E);
3680
3681               --  Check return of wrong convention subprogram pointer
3682
3683               elsif Ekind (R_Type) = E_Access_Subprogram_Type
3684                 and then not Has_Foreign_Convention (R_Type)
3685                 and then not Has_Warnings_Off (E)
3686                 and then not Has_Warnings_Off (R_Type)
3687               then
3688                  Error_Msg_N ("?x?& should return a foreign "
3689                     & "convention subprogram pointer", E);
3690                  Error_Msg_Sloc := Sloc (R_Type);
3691                  Error_Msg_NE
3692                    ("\?x?add Convention pragma to declaration of& #",
3693                     E, R_Type);
3694               end if;
3695            end if;
3696
3697            --  Give warning for suspicious return of a result of an
3698            --  unconstrained array type in a foreign convention function.
3699
3700            if Has_Foreign_Convention (E)
3701
3702              --  We are looking for a return of unconstrained array
3703
3704              and then Is_Array_Type (R_Type)
3705              and then not Is_Constrained (R_Type)
3706
3707              --  Exclude imported routines, the warning does not belong on
3708              --  the import, but rather on the routine definition.
3709
3710              and then not Is_Imported (E)
3711
3712              --  Check that general warning is enabled, and that it is not
3713              --  suppressed for this particular case.
3714
3715              and then Warn_On_Export_Import
3716              and then not Has_Warnings_Off (E)
3717              and then not Has_Warnings_Off (R_Type)
3718            then
3719               Error_Msg_N
3720                 ("?x?foreign convention function& should not return "
3721                  & "unconstrained array!", E);
3722            end if;
3723         end if;
3724
3725         --  Check suspicious use of Import in pure unit (cases where the RM
3726         --  allows calls to be omitted).
3727
3728         if Is_Imported (E)
3729
3730           --  It might be suspicious if the compilation unit has the Pure
3731           --  aspect/pragma.
3732
3733           and then Has_Pragma_Pure (Cunit_Entity (Current_Sem_Unit))
3734
3735           --  The RM allows omission of calls only in the case of
3736           --  library-level subprograms (see RM-10.2.1(18)).
3737
3738           and then Is_Library_Level_Entity (E)
3739
3740           --  Ignore internally generated entity. This happens in some cases
3741           --  of subprograms in specs, where we generate an implied body.
3742
3743           and then Comes_From_Source (Import_Pragma (E))
3744
3745           --  Assume run-time knows what it is doing
3746
3747           and then not GNAT_Mode
3748
3749           --  Assume explicit Pure_Function means import is pure
3750
3751           and then not Has_Pragma_Pure_Function (E)
3752
3753           --  Don't need warning in relaxed semantics mode
3754
3755           and then not Relaxed_RM_Semantics
3756
3757           --  Assume convention Intrinsic is OK, since this is specialized.
3758           --  This deals with the DEC unit current_exception.ads
3759
3760           and then Convention (E) /= Convention_Intrinsic
3761
3762           --  Assume that ASM interface knows what it is doing. This deals
3763           --  with e.g. unsigned.ads in the AAMP back end.
3764
3765           and then Convention (E) /= Convention_Assembler
3766         then
3767            Error_Msg_N
3768              ("pragma Import in Pure unit??", Import_Pragma (E));
3769            Error_Msg_NE
3770              ("\calls to & may be omitted (RM 10.2.1(18/3))??",
3771               Import_Pragma (E), E);
3772         end if;
3773
3774         return True;
3775      end Freeze_Profile;
3776
3777      ------------------------
3778      -- Freeze_Record_Type --
3779      ------------------------
3780
3781      procedure Freeze_Record_Type (Rec : Entity_Id) is
3782         ADC  : Node_Id;
3783         Comp : Entity_Id;
3784         IR   : Node_Id;
3785         Prev : Entity_Id;
3786
3787         Junk : Boolean;
3788         pragma Warnings (Off, Junk);
3789
3790         Aliased_Component : Boolean := False;
3791         --  Set True if we find at least one component which is aliased. This
3792         --  is used to prevent Implicit_Packing of the record, since packing
3793         --  cannot modify the size of alignment of an aliased component.
3794
3795         All_Elem_Components : Boolean := True;
3796         --  True if all components are of a type whose underlying type is
3797         --  elementary.
3798
3799         All_Sized_Components : Boolean := True;
3800         --  True if all components have a known RM_Size
3801
3802         All_Storage_Unit_Components : Boolean := True;
3803         --  True if all components have an RM_Size that is a multiple of the
3804         --  storage unit.
3805
3806         Elem_Component_Total_Esize : Uint := Uint_0;
3807         --  Accumulates total Esize values of all elementary components. Used
3808         --  for processing of Implicit_Packing.
3809
3810         Placed_Component : Boolean := False;
3811         --  Set True if we find at least one component with a component
3812         --  clause (used to warn about useless Bit_Order pragmas, and also
3813         --  to detect cases where Implicit_Packing may have an effect).
3814
3815         Rec_Pushed : Boolean := False;
3816         --  Set True if the record type scope Rec has been pushed on the scope
3817         --  stack. Needed for the analysis of delayed aspects specified to the
3818         --  components of Rec.
3819
3820         Sized_Component_Total_RM_Size : Uint := Uint_0;
3821         --  Accumulates total RM_Size values of all sized components. Used
3822         --  for processing of Implicit_Packing.
3823
3824         Sized_Component_Total_Round_RM_Size : Uint := Uint_0;
3825         --  Accumulates total RM_Size values of all sized components, rounded
3826         --  individually to a multiple of the storage unit.
3827
3828         SSO_ADC : Node_Id;
3829         --  Scalar_Storage_Order attribute definition clause for the record
3830
3831         SSO_ADC_Component : Boolean := False;
3832         --  Set True if we find at least one component whose type has a
3833         --  Scalar_Storage_Order attribute definition clause.
3834
3835         Unplaced_Component : Boolean := False;
3836         --  Set True if we find at least one component with no component
3837         --  clause (used to warn about useless Pack pragmas).
3838
3839         function Check_Allocator (N : Node_Id) return Node_Id;
3840         --  If N is an allocator, possibly wrapped in one or more level of
3841         --  qualified expression(s), return the inner allocator node, else
3842         --  return Empty.
3843
3844         procedure Check_Itype (Typ : Entity_Id);
3845         --  If the component subtype is an access to a constrained subtype of
3846         --  an already frozen type, make the subtype frozen as well. It might
3847         --  otherwise be frozen in the wrong scope, and a freeze node on
3848         --  subtype has no effect. Similarly, if the component subtype is a
3849         --  regular (not protected) access to subprogram, set the anonymous
3850         --  subprogram type to frozen as well, to prevent an out-of-scope
3851         --  freeze node at some eventual point of call. Protected operations
3852         --  are handled elsewhere.
3853
3854         procedure Freeze_Choices_In_Variant_Part (VP : Node_Id);
3855         --  Make sure that all types mentioned in Discrete_Choices of the
3856         --  variants referenceed by the Variant_Part VP are frozen. This is
3857         --  a recursive routine to deal with nested variants.
3858
3859         ---------------------
3860         -- Check_Allocator --
3861         ---------------------
3862
3863         function Check_Allocator (N : Node_Id) return Node_Id is
3864            Inner : Node_Id;
3865         begin
3866            Inner := N;
3867            loop
3868               if Nkind (Inner) = N_Allocator then
3869                  return Inner;
3870               elsif Nkind (Inner) = N_Qualified_Expression then
3871                  Inner := Expression (Inner);
3872               else
3873                  return Empty;
3874               end if;
3875            end loop;
3876         end Check_Allocator;
3877
3878         -----------------
3879         -- Check_Itype --
3880         -----------------
3881
3882         procedure Check_Itype (Typ : Entity_Id) is
3883            Desig : constant Entity_Id := Designated_Type (Typ);
3884
3885         begin
3886            if not Is_Frozen (Desig)
3887              and then Is_Frozen (Base_Type (Desig))
3888            then
3889               Set_Is_Frozen (Desig);
3890
3891               --  In addition, add an Itype_Reference to ensure that the
3892               --  access subtype is elaborated early enough. This cannot be
3893               --  done if the subtype may depend on discriminants.
3894
3895               if Ekind (Comp) = E_Component
3896                 and then Is_Itype (Etype (Comp))
3897                 and then not Has_Discriminants (Rec)
3898               then
3899                  IR := Make_Itype_Reference (Sloc (Comp));
3900                  Set_Itype (IR, Desig);
3901                  Add_To_Result (IR);
3902               end if;
3903
3904            elsif Ekind (Typ) = E_Anonymous_Access_Subprogram_Type
3905              and then Convention (Desig) /= Convention_Protected
3906            then
3907               Set_Is_Frozen (Desig);
3908            end if;
3909         end Check_Itype;
3910
3911         ------------------------------------
3912         -- Freeze_Choices_In_Variant_Part --
3913         ------------------------------------
3914
3915         procedure Freeze_Choices_In_Variant_Part (VP : Node_Id) is
3916            pragma Assert (Nkind (VP) = N_Variant_Part);
3917
3918            Variant : Node_Id;
3919            Choice  : Node_Id;
3920            CL      : Node_Id;
3921
3922         begin
3923            --  Loop through variants
3924
3925            Variant := First_Non_Pragma (Variants (VP));
3926            while Present (Variant) loop
3927
3928               --  Loop through choices, checking that all types are frozen
3929
3930               Choice := First_Non_Pragma (Discrete_Choices (Variant));
3931               while Present (Choice) loop
3932                  if Nkind (Choice) in N_Has_Etype
3933                    and then Present (Etype (Choice))
3934                  then
3935                     Freeze_And_Append (Etype (Choice), N, Result);
3936                  end if;
3937
3938                  Next_Non_Pragma (Choice);
3939               end loop;
3940
3941               --  Check for nested variant part to process
3942
3943               CL := Component_List (Variant);
3944
3945               if not Null_Present (CL) then
3946                  if Present (Variant_Part (CL)) then
3947                     Freeze_Choices_In_Variant_Part (Variant_Part (CL));
3948                  end if;
3949               end if;
3950
3951               Next_Non_Pragma (Variant);
3952            end loop;
3953         end Freeze_Choices_In_Variant_Part;
3954
3955      --  Start of processing for Freeze_Record_Type
3956
3957      begin
3958         --  Deal with delayed aspect specifications for components. The
3959         --  analysis of the aspect is required to be delayed to the freeze
3960         --  point, thus we analyze the pragma or attribute definition
3961         --  clause in the tree at this point. We also analyze the aspect
3962         --  specification node at the freeze point when the aspect doesn't
3963         --  correspond to pragma/attribute definition clause.
3964
3965         Comp := First_Entity (Rec);
3966         while Present (Comp) loop
3967            if Ekind (Comp) = E_Component
3968              and then Has_Delayed_Aspects (Comp)
3969            then
3970               if not Rec_Pushed then
3971                  Push_Scope (Rec);
3972                  Rec_Pushed := True;
3973
3974                  --  The visibility to the discriminants must be restored in
3975                  --  order to properly analyze the aspects.
3976
3977                  if Has_Discriminants (Rec) then
3978                     Install_Discriminants (Rec);
3979                  end if;
3980               end if;
3981
3982               Analyze_Aspects_At_Freeze_Point (Comp);
3983            end if;
3984
3985            Next_Entity (Comp);
3986         end loop;
3987
3988         --  Pop the scope if Rec scope has been pushed on the scope stack
3989         --  during the delayed aspect analysis process.
3990
3991         if Rec_Pushed then
3992            if Has_Discriminants (Rec) then
3993               Uninstall_Discriminants (Rec);
3994            end if;
3995
3996            Pop_Scope;
3997         end if;
3998
3999         --  Freeze components and embedded subtypes
4000
4001         Comp := First_Entity (Rec);
4002         Prev := Empty;
4003         while Present (Comp) loop
4004            if Is_Aliased (Comp) then
4005               Aliased_Component := True;
4006            end if;
4007
4008            --  Handle the component and discriminant case
4009
4010            if Ekind_In (Comp, E_Component, E_Discriminant) then
4011               declare
4012                  CC : constant Node_Id := Component_Clause (Comp);
4013
4014               begin
4015                  --  Freezing a record type freezes the type of each of its
4016                  --  components. However, if the type of the component is
4017                  --  part of this record, we do not want or need a separate
4018                  --  Freeze_Node. Note that Is_Itype is wrong because that's
4019                  --  also set in private type cases. We also can't check for
4020                  --  the Scope being exactly Rec because of private types and
4021                  --  record extensions.
4022
4023                  if Is_Itype (Etype (Comp))
4024                    and then Is_Record_Type (Underlying_Type
4025                                               (Scope (Etype (Comp))))
4026                  then
4027                     Undelay_Type (Etype (Comp));
4028                  end if;
4029
4030                  Freeze_And_Append (Etype (Comp), N, Result);
4031
4032                  --  Warn for pragma Pack overriding foreign convention
4033
4034                  if Has_Foreign_Convention (Etype (Comp))
4035                    and then Has_Pragma_Pack (Rec)
4036
4037                    --  Don't warn for aliased components, since override
4038                    --  cannot happen in that case.
4039
4040                    and then not Is_Aliased (Comp)
4041                  then
4042                     declare
4043                        CN : constant Name_Id :=
4044                               Get_Convention_Name (Convention (Etype (Comp)));
4045                        PP : constant Node_Id :=
4046                               Get_Pragma (Rec, Pragma_Pack);
4047                     begin
4048                        if Present (PP) then
4049                           Error_Msg_Name_1 := CN;
4050                           Error_Msg_Sloc := Sloc (Comp);
4051                           Error_Msg_N
4052                             ("pragma Pack affects convention % component#??",
4053                              PP);
4054                           Error_Msg_Name_1 := CN;
4055                           Error_Msg_NE
4056                             ("\component & may not have % compatible "
4057                              & "representation??", PP, Comp);
4058                        end if;
4059                     end;
4060                  end if;
4061
4062                  --  Check for error of component clause given for variable
4063                  --  sized type. We have to delay this test till this point,
4064                  --  since the component type has to be frozen for us to know
4065                  --  if it is variable length.
4066
4067                  if Present (CC) then
4068                     Placed_Component := True;
4069
4070                     --  We omit this test in a generic context, it will be
4071                     --  applied at instantiation time.
4072
4073                     if Inside_A_Generic then
4074                        null;
4075
4076                     --  Also omit this test in CodePeer mode, since we do not
4077                     --  have sufficient info on size and rep clauses.
4078
4079                     elsif CodePeer_Mode then
4080                        null;
4081
4082                     --  Omit check if component has a generic type. This can
4083                     --  happen in an instantiation within a generic in ASIS
4084                     --  mode, where we force freeze actions without full
4085                     --  expansion.
4086
4087                     elsif Is_Generic_Type (Etype (Comp)) then
4088                        null;
4089
4090                     --  Do the check
4091
4092                     elsif not
4093                       Size_Known_At_Compile_Time
4094                         (Underlying_Type (Etype (Comp)))
4095                     then
4096                        Error_Msg_N
4097                          ("component clause not allowed for variable " &
4098                           "length component", CC);
4099                     end if;
4100
4101                  else
4102                     Unplaced_Component := True;
4103                  end if;
4104
4105                  --  Case of component requires byte alignment
4106
4107                  if Must_Be_On_Byte_Boundary (Etype (Comp)) then
4108
4109                     --  Set the enclosing record to also require byte align
4110
4111                     Set_Must_Be_On_Byte_Boundary (Rec);
4112
4113                     --  Check for component clause that is inconsistent with
4114                     --  the required byte boundary alignment.
4115
4116                     if Present (CC)
4117                       and then Normalized_First_Bit (Comp) mod
4118                                  System_Storage_Unit /= 0
4119                     then
4120                        Error_Msg_N
4121                          ("component & must be byte aligned",
4122                           Component_Name (Component_Clause (Comp)));
4123                     end if;
4124                  end if;
4125               end;
4126            end if;
4127
4128            --  Gather data for possible Implicit_Packing later. Note that at
4129            --  this stage we might be dealing with a real component, or with
4130            --  an implicit subtype declaration.
4131
4132            if Known_Static_RM_Size (Etype (Comp)) then
4133               declare
4134                  Comp_Type : constant Entity_Id := Etype (Comp);
4135                  Comp_Size : constant Uint := RM_Size (Comp_Type);
4136                  SSU       : constant Int := Ttypes.System_Storage_Unit;
4137
4138               begin
4139                  Sized_Component_Total_RM_Size :=
4140                    Sized_Component_Total_RM_Size + Comp_Size;
4141
4142                  Sized_Component_Total_Round_RM_Size :=
4143                    Sized_Component_Total_Round_RM_Size +
4144                      (Comp_Size + SSU - 1) / SSU * SSU;
4145
4146                  if Present (Underlying_Type (Comp_Type))
4147                    and then Is_Elementary_Type (Underlying_Type (Comp_Type))
4148                  then
4149                     Elem_Component_Total_Esize :=
4150                       Elem_Component_Total_Esize + Esize (Comp_Type);
4151                  else
4152                     All_Elem_Components := False;
4153
4154                     if Comp_Size mod SSU /= 0 then
4155                        All_Storage_Unit_Components := False;
4156                     end if;
4157                  end if;
4158               end;
4159            else
4160               All_Sized_Components := False;
4161            end if;
4162
4163            --  If the component is an Itype with Delayed_Freeze and is either
4164            --  a record or array subtype and its base type has not yet been
4165            --  frozen, we must remove this from the entity list of this record
4166            --  and put it on the entity list of the scope of its base type.
4167            --  Note that we know that this is not the type of a component
4168            --  since we cleared Has_Delayed_Freeze for it in the previous
4169            --  loop. Thus this must be the Designated_Type of an access type,
4170            --  which is the type of a component.
4171
4172            if Is_Itype (Comp)
4173              and then Is_Type (Scope (Comp))
4174              and then Is_Composite_Type (Comp)
4175              and then Base_Type (Comp) /= Comp
4176              and then Has_Delayed_Freeze (Comp)
4177              and then not Is_Frozen (Base_Type (Comp))
4178            then
4179               declare
4180                  Will_Be_Frozen : Boolean := False;
4181                  S              : Entity_Id;
4182
4183               begin
4184                  --  We have a difficult case to handle here. Suppose Rec is
4185                  --  subtype being defined in a subprogram that's created as
4186                  --  part of the freezing of Rec'Base. In that case, we know
4187                  --  that Comp'Base must have already been frozen by the time
4188                  --  we get to elaborate this because Gigi doesn't elaborate
4189                  --  any bodies until it has elaborated all of the declarative
4190                  --  part. But Is_Frozen will not be set at this point because
4191                  --  we are processing code in lexical order.
4192
4193                  --  We detect this case by going up the Scope chain of Rec
4194                  --  and seeing if we have a subprogram scope before reaching
4195                  --  the top of the scope chain or that of Comp'Base. If we
4196                  --  do, then mark that Comp'Base will actually be frozen. If
4197                  --  so, we merely undelay it.
4198
4199                  S := Scope (Rec);
4200                  while Present (S) loop
4201                     if Is_Subprogram (S) then
4202                        Will_Be_Frozen := True;
4203                        exit;
4204                     elsif S = Scope (Base_Type (Comp)) then
4205                        exit;
4206                     end if;
4207
4208                     S := Scope (S);
4209                  end loop;
4210
4211                  if Will_Be_Frozen then
4212                     Undelay_Type (Comp);
4213
4214                  else
4215                     if Present (Prev) then
4216                        Set_Next_Entity (Prev, Next_Entity (Comp));
4217                     else
4218                        Set_First_Entity (Rec, Next_Entity (Comp));
4219                     end if;
4220
4221                     --  Insert in entity list of scope of base type (which
4222                     --  must be an enclosing scope, because still unfrozen).
4223
4224                     Append_Entity (Comp, Scope (Base_Type (Comp)));
4225                  end if;
4226               end;
4227
4228            --  If the component is an access type with an allocator as default
4229            --  value, the designated type will be frozen by the corresponding
4230            --  expression in init_proc. In order to place the freeze node for
4231            --  the designated type before that for the current record type,
4232            --  freeze it now.
4233
4234            --  Same process if the component is an array of access types,
4235            --  initialized with an aggregate. If the designated type is
4236            --  private, it cannot contain allocators, and it is premature
4237            --  to freeze the type, so we check for this as well.
4238
4239            elsif Is_Access_Type (Etype (Comp))
4240              and then Present (Parent (Comp))
4241              and then Present (Expression (Parent (Comp)))
4242            then
4243               declare
4244                  Alloc : constant Node_Id :=
4245                            Check_Allocator (Expression (Parent (Comp)));
4246
4247               begin
4248                  if Present (Alloc) then
4249
4250                     --  If component is pointer to a class-wide type, freeze
4251                     --  the specific type in the expression being allocated.
4252                     --  The expression may be a subtype indication, in which
4253                     --  case freeze the subtype mark.
4254
4255                     if Is_Class_Wide_Type
4256                          (Designated_Type (Etype (Comp)))
4257                     then
4258                        if Is_Entity_Name (Expression (Alloc)) then
4259                           Freeze_And_Append
4260                             (Entity (Expression (Alloc)), N, Result);
4261
4262                        elsif Nkind (Expression (Alloc)) = N_Subtype_Indication
4263                        then
4264                           Freeze_And_Append
4265                            (Entity (Subtype_Mark (Expression (Alloc))),
4266                             N, Result);
4267                        end if;
4268
4269                     elsif Is_Itype (Designated_Type (Etype (Comp))) then
4270                        Check_Itype (Etype (Comp));
4271
4272                     else
4273                        Freeze_And_Append
4274                          (Designated_Type (Etype (Comp)), N, Result);
4275                     end if;
4276                  end if;
4277               end;
4278
4279            elsif Is_Access_Type (Etype (Comp))
4280              and then Is_Itype (Designated_Type (Etype (Comp)))
4281            then
4282               Check_Itype (Etype (Comp));
4283
4284            --  Freeze the designated type when initializing a component with
4285            --  an aggregate in case the aggregate contains allocators.
4286
4287            --     type T is ...;
4288            --     type T_Ptr is access all T;
4289            --     type T_Array is array ... of T_Ptr;
4290
4291            --     type Rec is record
4292            --        Comp : T_Array := (others => ...);
4293            --     end record;
4294
4295            elsif Is_Array_Type (Etype (Comp))
4296              and then Is_Access_Type (Component_Type (Etype (Comp)))
4297            then
4298               declare
4299                  Comp_Par  : constant Node_Id   := Parent (Comp);
4300                  Desig_Typ : constant Entity_Id :=
4301                                Designated_Type
4302                                  (Component_Type (Etype (Comp)));
4303
4304               begin
4305                  --  The only case when this sort of freezing is not done is
4306                  --  when the designated type is class-wide and the root type
4307                  --  is the record owning the component. This scenario results
4308                  --  in a circularity because the class-wide type requires
4309                  --  primitives that have not been created yet as the root
4310                  --  type is in the process of being frozen.
4311
4312                  --     type Rec is tagged;
4313                  --     type Rec_Ptr is access all Rec'Class;
4314                  --     type Rec_Array is array ... of Rec_Ptr;
4315
4316                  --     type Rec is record
4317                  --        Comp : Rec_Array := (others => ...);
4318                  --     end record;
4319
4320                  if Is_Class_Wide_Type (Desig_Typ)
4321                    and then Root_Type (Desig_Typ) = Rec
4322                  then
4323                     null;
4324
4325                  elsif Is_Fully_Defined (Desig_Typ)
4326                    and then Present (Comp_Par)
4327                    and then Nkind (Comp_Par) = N_Component_Declaration
4328                    and then Present (Expression (Comp_Par))
4329                    and then Nkind (Expression (Comp_Par)) = N_Aggregate
4330                  then
4331                     Freeze_And_Append (Desig_Typ, N, Result);
4332                  end if;
4333               end;
4334            end if;
4335
4336            Prev := Comp;
4337            Next_Entity (Comp);
4338         end loop;
4339
4340         SSO_ADC :=
4341           Get_Attribute_Definition_Clause
4342             (Rec, Attribute_Scalar_Storage_Order);
4343
4344         --  If the record type has Complex_Representation, then it is treated
4345         --  as a scalar in the back end so the storage order is irrelevant.
4346
4347         if Has_Complex_Representation (Rec) then
4348            if Present (SSO_ADC) then
4349               Error_Msg_N
4350                 ("??storage order has no effect with Complex_Representation",
4351                  SSO_ADC);
4352            end if;
4353
4354         else
4355            --  Deal with default setting of reverse storage order
4356
4357            Set_SSO_From_Default (Rec);
4358
4359            --  Check consistent attribute setting on component types
4360
4361            declare
4362               Comp_ADC_Present : Boolean;
4363            begin
4364               Comp := First_Component (Rec);
4365               while Present (Comp) loop
4366                  Check_Component_Storage_Order
4367                    (Encl_Type        => Rec,
4368                     Comp             => Comp,
4369                     ADC              => SSO_ADC,
4370                     Comp_ADC_Present => Comp_ADC_Present);
4371                  SSO_ADC_Component := SSO_ADC_Component or Comp_ADC_Present;
4372                  Next_Component (Comp);
4373               end loop;
4374            end;
4375
4376            --  Now deal with reverse storage order/bit order issues
4377
4378            if Present (SSO_ADC) then
4379
4380               --  Check compatibility of Scalar_Storage_Order with Bit_Order,
4381               --  if the former is specified.
4382
4383               if Reverse_Bit_Order (Rec) /= Reverse_Storage_Order (Rec) then
4384
4385                  --  Note: report error on Rec, not on SSO_ADC, as ADC may
4386                  --  apply to some ancestor type.
4387
4388                  Error_Msg_Sloc := Sloc (SSO_ADC);
4389                  Error_Msg_N
4390                    ("scalar storage order for& specified# inconsistent with "
4391                     & "bit order", Rec);
4392               end if;
4393
4394               --  Warn if there is a Scalar_Storage_Order attribute definition
4395               --  clause but no component clause, no component that itself has
4396               --  such an attribute definition, and no pragma Pack.
4397
4398               if not (Placed_Component
4399                         or else
4400                       SSO_ADC_Component
4401                         or else
4402                       Is_Packed (Rec))
4403               then
4404                  Error_Msg_N
4405                    ("??scalar storage order specified but no component "
4406                     & "clause", SSO_ADC);
4407               end if;
4408            end if;
4409         end if;
4410
4411         --  Deal with Bit_Order aspect
4412
4413         ADC := Get_Attribute_Definition_Clause (Rec, Attribute_Bit_Order);
4414
4415         if Present (ADC) and then Base_Type (Rec) = Rec then
4416            if not (Placed_Component
4417                     or else Present (SSO_ADC)
4418                     or else Is_Packed (Rec))
4419            then
4420               --  Warn if clause has no effect when no component clause is
4421               --  present, but suppress warning if the Bit_Order is required
4422               --  due to the presence of a Scalar_Storage_Order attribute.
4423
4424               Error_Msg_N
4425                 ("??bit order specification has no effect", ADC);
4426               Error_Msg_N
4427                 ("\??since no component clauses were specified", ADC);
4428
4429            --  Here is where we do the processing to adjust component clauses
4430            --  for reversed bit order, when not using reverse SSO. If an error
4431            --  has been reported on Rec already (such as SSO incompatible with
4432            --  bit order), don't bother adjusting as this may generate extra
4433            --  noise.
4434
4435            elsif Reverse_Bit_Order (Rec)
4436              and then not Reverse_Storage_Order (Rec)
4437              and then not Error_Posted (Rec)
4438            then
4439               Adjust_Record_For_Reverse_Bit_Order (Rec);
4440
4441            --  Case where we have both an explicit Bit_Order and the same
4442            --  Scalar_Storage_Order: leave record untouched, the back-end
4443            --  will take care of required layout conversions.
4444
4445            else
4446               null;
4447
4448            end if;
4449         end if;
4450
4451         --  Complete error checking on record representation clause (e.g.
4452         --  overlap of components). This is called after adjusting the
4453         --  record for reverse bit order.
4454
4455         declare
4456            RRC : constant Node_Id := Get_Record_Representation_Clause (Rec);
4457         begin
4458            if Present (RRC) then
4459               Check_Record_Representation_Clause (RRC);
4460            end if;
4461         end;
4462
4463         --  Check for useless pragma Pack when all components placed. We only
4464         --  do this check for record types, not subtypes, since a subtype may
4465         --  have all its components placed, and it still makes perfectly good
4466         --  sense to pack other subtypes or the parent type. We do not give
4467         --  this warning if Optimize_Alignment is set to Space, since the
4468         --  pragma Pack does have an effect in this case (it always resets
4469         --  the alignment to one).
4470
4471         if Ekind (Rec) = E_Record_Type
4472           and then Is_Packed (Rec)
4473           and then not Unplaced_Component
4474           and then Optimize_Alignment /= 'S'
4475         then
4476            --  Reset packed status. Probably not necessary, but we do it so
4477            --  that there is no chance of the back end doing something strange
4478            --  with this redundant indication of packing.
4479
4480            Set_Is_Packed (Rec, False);
4481
4482            --  Give warning if redundant constructs warnings on
4483
4484            if Warn_On_Redundant_Constructs then
4485               Error_Msg_N -- CODEFIX
4486                 ("??pragma Pack has no effect, no unplaced components",
4487                  Get_Rep_Pragma (Rec, Name_Pack));
4488            end if;
4489         end if;
4490
4491         --  If this is the record corresponding to a remote type, freeze the
4492         --  remote type here since that is what we are semantically freezing.
4493         --  This prevents the freeze node for that type in an inner scope.
4494
4495         if Ekind (Rec) = E_Record_Type then
4496            if Present (Corresponding_Remote_Type (Rec)) then
4497               Freeze_And_Append (Corresponding_Remote_Type (Rec), N, Result);
4498            end if;
4499
4500            --  Check for controlled components, unchecked unions, and type
4501            --  invariants.
4502
4503            Comp := First_Component (Rec);
4504            while Present (Comp) loop
4505
4506               --  Do not set Has_Controlled_Component on a class-wide
4507               --  equivalent type. See Make_CW_Equivalent_Type.
4508
4509               if not Is_Class_Wide_Equivalent_Type (Rec)
4510                 and then
4511                   (Has_Controlled_Component (Etype (Comp))
4512                     or else
4513                       (Chars (Comp) /= Name_uParent
4514                         and then Is_Controlled (Etype (Comp)))
4515                     or else
4516                       (Is_Protected_Type (Etype (Comp))
4517                         and then
4518                           Present (Corresponding_Record_Type (Etype (Comp)))
4519                         and then
4520                           Has_Controlled_Component
4521                             (Corresponding_Record_Type (Etype (Comp)))))
4522               then
4523                  Set_Has_Controlled_Component (Rec);
4524               end if;
4525
4526               if Has_Unchecked_Union (Etype (Comp)) then
4527                  Set_Has_Unchecked_Union (Rec);
4528               end if;
4529
4530               --  The record type requires its own invariant procedure in
4531               --  order to verify the invariant of each individual component.
4532               --  Do not consider internal components such as _parent because
4533               --  parent class-wide invariants are always inherited.
4534               --  In GNATprove mode, the component invariants are checked by
4535               --  other means. They should not be added to the record type
4536               --  invariant procedure, so that the procedure can be used to
4537               --  check the recordy type invariants if any.
4538
4539               if Comes_From_Source (Comp)
4540                 and then Has_Invariants (Etype (Comp))
4541                   and then not GNATprove_Mode
4542               then
4543                  Set_Has_Own_Invariants (Rec);
4544               end if;
4545
4546               --  Scan component declaration for likely misuses of current
4547               --  instance, either in a constraint or a default expression.
4548
4549               if Has_Per_Object_Constraint (Comp) then
4550                  Check_Current_Instance (Parent (Comp));
4551               end if;
4552
4553               Next_Component (Comp);
4554            end loop;
4555         end if;
4556
4557         --  Enforce the restriction that access attributes with a current
4558         --  instance prefix can only apply to limited types. This comment
4559         --  is floating here, but does not seem to belong here???
4560
4561         --  Set component alignment if not otherwise already set
4562
4563         Set_Component_Alignment_If_Not_Set (Rec);
4564
4565         --  For first subtypes, check if there are any fixed-point fields with
4566         --  component clauses, where we must check the size. This is not done
4567         --  till the freeze point since for fixed-point types, we do not know
4568         --  the size until the type is frozen. Similar processing applies to
4569         --  bit-packed arrays.
4570
4571         if Is_First_Subtype (Rec) then
4572            Comp := First_Component (Rec);
4573            while Present (Comp) loop
4574               if Present (Component_Clause (Comp))
4575                 and then (Is_Fixed_Point_Type (Etype (Comp))
4576                            or else Is_Bit_Packed_Array (Etype (Comp)))
4577               then
4578                  Check_Size
4579                    (Component_Name (Component_Clause (Comp)),
4580                     Etype (Comp),
4581                     Esize (Comp),
4582                     Junk);
4583               end if;
4584
4585               Next_Component (Comp);
4586            end loop;
4587         end if;
4588
4589         --  See if Size is too small as is (and implicit packing might help)
4590
4591         if not Is_Packed (Rec)
4592
4593           --  No implicit packing if even one component is explicitly placed
4594
4595           and then not Placed_Component
4596
4597           --  Or even one component is aliased
4598
4599           and then not Aliased_Component
4600
4601           --  Must have size clause and all sized components
4602
4603           and then Has_Size_Clause (Rec)
4604           and then All_Sized_Components
4605
4606           --  Do not try implicit packing on records with discriminants, too
4607           --  complicated, especially in the variant record case.
4608
4609           and then not Has_Discriminants (Rec)
4610
4611           --  We want to implicitly pack if the specified size of the record
4612           --  is less than the sum of the object sizes (no point in packing
4613           --  if this is not the case), if we can compute it, i.e. if we have
4614           --  only elementary components. Otherwise, we have at least one
4615           --  composite component and we want to implicitly pack only if bit
4616           --  packing is required for it, as we are sure in this case that
4617           --  the back end cannot do the expected layout without packing.
4618
4619           and then
4620              ((All_Elem_Components
4621                 and then RM_Size (Rec) < Elem_Component_Total_Esize)
4622             or else
4623               (not All_Elem_Components
4624                 and then not All_Storage_Unit_Components
4625                 and then RM_Size (Rec) < Sized_Component_Total_Round_RM_Size))
4626
4627           --  And the total RM size cannot be greater than the specified size
4628           --  since otherwise packing will not get us where we have to be.
4629
4630           and then Sized_Component_Total_RM_Size <= RM_Size (Rec)
4631
4632           --  Never do implicit packing in CodePeer or SPARK modes since
4633           --  we don't do any packing in these modes, since this generates
4634           --  over-complex code that confuses static analysis, and in
4635           --  general, neither CodePeer not GNATprove care about the
4636           --  internal representation of objects.
4637
4638           and then not (CodePeer_Mode or GNATprove_Mode)
4639         then
4640            --  If implicit packing enabled, do it
4641
4642            if Implicit_Packing then
4643               Set_Is_Packed (Rec);
4644
4645               --  Otherwise flag the size clause
4646
4647            else
4648               declare
4649                  Sz : constant Node_Id := Size_Clause (Rec);
4650               begin
4651                  Error_Msg_NE -- CODEFIX
4652                    ("size given for& too small", Sz, Rec);
4653                  Error_Msg_N -- CODEFIX
4654                    ("\use explicit pragma Pack "
4655                     & "or use pragma Implicit_Packing", Sz);
4656               end;
4657            end if;
4658         end if;
4659
4660         --  The following checks are relevant only when SPARK_Mode is on as
4661         --  they are not standard Ada legality rules.
4662
4663         if SPARK_Mode = On then
4664
4665            --  A discriminated type cannot be effectively volatile
4666            --  (SPARK RM 7.1.3(5)).
4667
4668            if Is_Effectively_Volatile (Rec) then
4669               if Has_Discriminants (Rec) then
4670                  Error_Msg_N ("discriminated type & cannot be volatile", Rec);
4671               end if;
4672
4673            --  A non-effectively volatile record type cannot contain
4674            --  effectively volatile components (SPARK RM 7.1.3(6)).
4675
4676            else
4677               Comp := First_Component (Rec);
4678               while Present (Comp) loop
4679                  if Comes_From_Source (Comp)
4680                    and then Is_Effectively_Volatile (Etype (Comp))
4681                  then
4682                     Error_Msg_Name_1 := Chars (Rec);
4683                     Error_Msg_N
4684                       ("component & of non-volatile type % cannot be "
4685                        & "volatile", Comp);
4686                  end if;
4687
4688                  Next_Component (Comp);
4689               end loop;
4690            end if;
4691
4692            --  A type which does not yield a synchronized object cannot have
4693            --  a component that yields a synchronized object (SPARK RM 9.5).
4694
4695            if not Yields_Synchronized_Object (Rec) then
4696               Comp := First_Component (Rec);
4697               while Present (Comp) loop
4698                  if Comes_From_Source (Comp)
4699                    and then Yields_Synchronized_Object (Etype (Comp))
4700                  then
4701                     Error_Msg_Name_1 := Chars (Rec);
4702                     Error_Msg_N
4703                       ("component & of non-synchronized type % cannot be "
4704                        & "synchronized", Comp);
4705                  end if;
4706
4707                  Next_Component (Comp);
4708               end loop;
4709            end if;
4710
4711            --  A Ghost type cannot have a component of protected or task type
4712            --  (SPARK RM 6.9(19)).
4713
4714            if Is_Ghost_Entity (Rec) then
4715               Comp := First_Component (Rec);
4716               while Present (Comp) loop
4717                  if Comes_From_Source (Comp)
4718                    and then Is_Concurrent_Type (Etype (Comp))
4719                  then
4720                     Error_Msg_Name_1 := Chars (Rec);
4721                     Error_Msg_N
4722                       ("component & of ghost type % cannot be concurrent",
4723                        Comp);
4724                  end if;
4725
4726                  Next_Component (Comp);
4727               end loop;
4728            end if;
4729         end if;
4730
4731         --  Make sure that if we have an iterator aspect, then we have
4732         --  either Constant_Indexing or Variable_Indexing.
4733
4734         declare
4735            Iterator_Aspect : Node_Id;
4736
4737         begin
4738            Iterator_Aspect := Find_Aspect (Rec, Aspect_Iterator_Element);
4739
4740            if No (Iterator_Aspect) then
4741               Iterator_Aspect := Find_Aspect (Rec, Aspect_Default_Iterator);
4742            end if;
4743
4744            if Present (Iterator_Aspect) then
4745               if Has_Aspect (Rec, Aspect_Constant_Indexing)
4746                    or else
4747                  Has_Aspect (Rec, Aspect_Variable_Indexing)
4748               then
4749                  null;
4750               else
4751                  Error_Msg_N
4752                    ("Iterator_Element requires indexing aspect",
4753                     Iterator_Aspect);
4754               end if;
4755            end if;
4756         end;
4757
4758         --  All done if not a full record definition
4759
4760         if Ekind (Rec) /= E_Record_Type then
4761            return;
4762         end if;
4763
4764         --  Finally we need to check the variant part to make sure that
4765         --  all types within choices are properly frozen as part of the
4766         --  freezing of the record type.
4767
4768         Check_Variant_Part : declare
4769            D : constant Node_Id := Declaration_Node (Rec);
4770            T : Node_Id;
4771            C : Node_Id;
4772
4773         begin
4774            --  Find component list
4775
4776            C := Empty;
4777
4778            if Nkind (D) = N_Full_Type_Declaration then
4779               T := Type_Definition (D);
4780
4781               if Nkind (T) = N_Record_Definition then
4782                  C := Component_List (T);
4783
4784               elsif Nkind (T) = N_Derived_Type_Definition
4785                 and then Present (Record_Extension_Part (T))
4786               then
4787                  C := Component_List (Record_Extension_Part (T));
4788               end if;
4789            end if;
4790
4791            --  Case of variant part present
4792
4793            if Present (C) and then Present (Variant_Part (C)) then
4794               Freeze_Choices_In_Variant_Part (Variant_Part (C));
4795            end if;
4796
4797            --  Note: we used to call Check_Choices here, but it is too early,
4798            --  since predicated subtypes are frozen here, but their freezing
4799            --  actions are in Analyze_Freeze_Entity, which has not been called
4800            --  yet for entities frozen within this procedure, so we moved that
4801            --  call to the Analyze_Freeze_Entity for the record type.
4802
4803         end Check_Variant_Part;
4804
4805         --  Check that all the primitives of an interface type are abstract
4806         --  or null procedures.
4807
4808         if Is_Interface (Rec)
4809           and then not Error_Posted (Parent (Rec))
4810         then
4811            declare
4812               Elmt : Elmt_Id;
4813               Subp : Entity_Id;
4814
4815            begin
4816               Elmt := First_Elmt (Primitive_Operations (Rec));
4817               while Present (Elmt) loop
4818                  Subp := Node (Elmt);
4819
4820                  if not Is_Abstract_Subprogram (Subp)
4821
4822                     --  Avoid reporting the error on inherited primitives
4823
4824                    and then Comes_From_Source (Subp)
4825                  then
4826                     Error_Msg_Name_1 := Chars (Subp);
4827
4828                     if Ekind (Subp) = E_Procedure then
4829                        if not Null_Present (Parent (Subp)) then
4830                           Error_Msg_N
4831                             ("interface procedure % must be abstract or null",
4832                              Parent (Subp));
4833                        end if;
4834                     else
4835                        Error_Msg_N
4836                          ("interface function % must be abstract",
4837                           Parent (Subp));
4838                     end if;
4839                  end if;
4840
4841                  Next_Elmt (Elmt);
4842               end loop;
4843            end;
4844         end if;
4845
4846         --  For a derived tagged type, check whether inherited primitives
4847         --  might require a wrapper to handle class-wide conditions.
4848
4849         if Is_Tagged_Type (Rec) and then Is_Derived_Type (Rec) then
4850            Check_Inherited_Conditions (Rec);
4851         end if;
4852      end Freeze_Record_Type;
4853
4854      -------------------------------
4855      -- Has_Boolean_Aspect_Import --
4856      -------------------------------
4857
4858      function Has_Boolean_Aspect_Import (E : Entity_Id) return Boolean is
4859         Decl : constant Node_Id := Declaration_Node (E);
4860         Asp  : Node_Id;
4861         Expr : Node_Id;
4862
4863      begin
4864         if Has_Aspects (Decl) then
4865            Asp := First (Aspect_Specifications (Decl));
4866            while Present (Asp) loop
4867               Expr := Expression (Asp);
4868
4869               --  The value of aspect Import is True when the expression is
4870               --  either missing or it is explicitly set to True.
4871
4872               if Get_Aspect_Id (Asp) = Aspect_Import
4873                 and then (No (Expr)
4874                            or else (Compile_Time_Known_Value (Expr)
4875                                      and then Is_True (Expr_Value (Expr))))
4876               then
4877                  return True;
4878               end if;
4879
4880               Next (Asp);
4881            end loop;
4882         end if;
4883
4884         return False;
4885      end Has_Boolean_Aspect_Import;
4886
4887      -------------------------
4888      -- Inherit_Freeze_Node --
4889      -------------------------
4890
4891      procedure Inherit_Freeze_Node
4892        (Fnod : Node_Id;
4893         Typ  : Entity_Id)
4894      is
4895         Typ_Fnod : constant Node_Id := Freeze_Node (Typ);
4896
4897      begin
4898         Set_Freeze_Node (Typ, Fnod);
4899         Set_Entity (Fnod, Typ);
4900
4901         --  The input type had an existing node. Propagate relevant attributes
4902         --  from the old freeze node to the inherited freeze node.
4903
4904         --  ??? if both freeze nodes have attributes, would they differ?
4905
4906         if Present (Typ_Fnod) then
4907
4908            --  Attribute Access_Types_To_Process
4909
4910            if Present (Access_Types_To_Process (Typ_Fnod))
4911              and then No (Access_Types_To_Process (Fnod))
4912            then
4913               Set_Access_Types_To_Process (Fnod,
4914                 Access_Types_To_Process (Typ_Fnod));
4915            end if;
4916
4917            --  Attribute Actions
4918
4919            if Present (Actions (Typ_Fnod)) and then No (Actions (Fnod)) then
4920               Set_Actions (Fnod, Actions (Typ_Fnod));
4921            end if;
4922
4923            --  Attribute First_Subtype_Link
4924
4925            if Present (First_Subtype_Link (Typ_Fnod))
4926              and then No (First_Subtype_Link (Fnod))
4927            then
4928               Set_First_Subtype_Link (Fnod, First_Subtype_Link (Typ_Fnod));
4929            end if;
4930
4931            --  Attribute TSS_Elist
4932
4933            if Present (TSS_Elist (Typ_Fnod))
4934              and then No (TSS_Elist (Fnod))
4935            then
4936               Set_TSS_Elist (Fnod, TSS_Elist (Typ_Fnod));
4937            end if;
4938         end if;
4939      end Inherit_Freeze_Node;
4940
4941      ------------------------------
4942      -- Wrap_Imported_Subprogram --
4943      ------------------------------
4944
4945      --  The issue here is that our normal approach of checking preconditions
4946      --  and postconditions does not work for imported procedures, since we
4947      --  are not generating code for the body. To get around this we create
4948      --  a wrapper, as shown by the following example:
4949
4950      --    procedure K (A : Integer);
4951      --    pragma Import (C, K);
4952
4953      --  The spec is rewritten by removing the effects of pragma Import, but
4954      --  leaving the convention unchanged, as though the source had said:
4955
4956      --    procedure K (A : Integer);
4957      --    pragma Convention (C, K);
4958
4959      --  and we create a body, added to the entity K freeze actions, which
4960      --  looks like:
4961
4962      --    procedure K (A : Integer) is
4963      --       procedure K (A : Integer);
4964      --       pragma Import (C, K);
4965      --    begin
4966      --       K (A);
4967      --    end K;
4968
4969      --  Now the contract applies in the normal way to the outer procedure,
4970      --  and the inner procedure has no contracts, so there is no problem
4971      --  in just calling it to get the original effect.
4972
4973      --  In the case of a function, we create an appropriate return statement
4974      --  for the subprogram body that calls the inner procedure.
4975
4976      procedure Wrap_Imported_Subprogram (E : Entity_Id) is
4977         function Copy_Import_Pragma return Node_Id;
4978         --  Obtain a copy of the Import_Pragma which belongs to subprogram E
4979
4980         ------------------------
4981         -- Copy_Import_Pragma --
4982         ------------------------
4983
4984         function Copy_Import_Pragma return Node_Id is
4985
4986            --  The subprogram should have an import pragma, otherwise it does
4987            --  need a wrapper.
4988
4989            Prag : constant Node_Id := Import_Pragma (E);
4990            pragma Assert (Present (Prag));
4991
4992            --  Save all semantic fields of the pragma
4993
4994            Save_Asp  : constant Node_Id := Corresponding_Aspect (Prag);
4995            Save_From : constant Boolean := From_Aspect_Specification (Prag);
4996            Save_Prag : constant Node_Id := Next_Pragma (Prag);
4997            Save_Rep  : constant Node_Id := Next_Rep_Item (Prag);
4998
4999            Result : Node_Id;
5000
5001         begin
5002            --  Reset all semantic fields. This avoids a potential infinite
5003            --  loop when the pragma comes from an aspect as the duplication
5004            --  will copy the aspect, then copy the corresponding pragma and
5005            --  so on.
5006
5007            Set_Corresponding_Aspect      (Prag, Empty);
5008            Set_From_Aspect_Specification (Prag, False);
5009            Set_Next_Pragma               (Prag, Empty);
5010            Set_Next_Rep_Item             (Prag, Empty);
5011
5012            Result := Copy_Separate_Tree (Prag);
5013
5014            --  Restore the original semantic fields
5015
5016            Set_Corresponding_Aspect      (Prag, Save_Asp);
5017            Set_From_Aspect_Specification (Prag, Save_From);
5018            Set_Next_Pragma               (Prag, Save_Prag);
5019            Set_Next_Rep_Item             (Prag, Save_Rep);
5020
5021            return Result;
5022         end Copy_Import_Pragma;
5023
5024         --  Local variables
5025
5026         Loc   : constant Source_Ptr := Sloc (E);
5027         CE    : constant Name_Id    := Chars (E);
5028         Bod   : Node_Id;
5029         Forml : Entity_Id;
5030         Parms : List_Id;
5031         Prag  : Node_Id;
5032         Spec  : Node_Id;
5033         Stmt  : Node_Id;
5034
5035      --  Start of processing for Wrap_Imported_Subprogram
5036
5037      begin
5038         --  Nothing to do if not imported
5039
5040         if not Is_Imported (E) then
5041            return;
5042
5043         --  Test enabling conditions for wrapping
5044
5045         elsif Is_Subprogram (E)
5046           and then Present (Contract (E))
5047           and then Present (Pre_Post_Conditions (Contract (E)))
5048           and then not GNATprove_Mode
5049         then
5050            --  Here we do the wrap
5051
5052            --  Note on calls to Copy_Separate_Tree. The trees we are copying
5053            --  here are fully analyzed, but we definitely want fully syntactic
5054            --  unanalyzed trees in the body we construct, so that the analysis
5055            --  generates the right visibility, and that is exactly what the
5056            --  calls to Copy_Separate_Tree give us.
5057
5058            Prag := Copy_Import_Pragma;
5059
5060            --  Fix up spec so it is no longer imported and has convention Ada
5061
5062            Set_Has_Completion (E, False);
5063            Set_Import_Pragma  (E, Empty);
5064            Set_Interface_Name (E, Empty);
5065            Set_Is_Imported    (E, False);
5066            Set_Convention     (E, Convention_Ada);
5067
5068            --  Grab the subprogram declaration and specification
5069
5070            Spec := Declaration_Node (E);
5071
5072            --  Build parameter list that we need
5073
5074            Parms := New_List;
5075            Forml := First_Formal (E);
5076            while Present (Forml) loop
5077               Append_To (Parms, Make_Identifier (Loc, Chars (Forml)));
5078               Next_Formal (Forml);
5079            end loop;
5080
5081            --  Build the call
5082
5083            if Ekind_In (E, E_Function, E_Generic_Function) then
5084               Stmt :=
5085                 Make_Simple_Return_Statement (Loc,
5086                   Expression =>
5087                     Make_Function_Call (Loc,
5088                       Name                   => Make_Identifier (Loc, CE),
5089                       Parameter_Associations => Parms));
5090
5091            else
5092               Stmt :=
5093                 Make_Procedure_Call_Statement (Loc,
5094                   Name                   => Make_Identifier (Loc, CE),
5095                   Parameter_Associations => Parms);
5096            end if;
5097
5098            --  Now build the body
5099
5100            Bod :=
5101              Make_Subprogram_Body (Loc,
5102                Specification              =>
5103                  Copy_Separate_Tree (Spec),
5104                Declarations               => New_List (
5105                  Make_Subprogram_Declaration (Loc,
5106                    Specification => Copy_Separate_Tree (Spec)),
5107                  Prag),
5108                Handled_Statement_Sequence =>
5109                  Make_Handled_Sequence_Of_Statements (Loc,
5110                    Statements => New_List (Stmt),
5111                    End_Label  => Make_Identifier (Loc, CE)));
5112
5113            --  Append the body to freeze result
5114
5115            Add_To_Result (Bod);
5116            return;
5117
5118         --  Case of imported subprogram that does not get wrapped
5119
5120         else
5121            --  Set Is_Public. All imported entities need an external symbol
5122            --  created for them since they are always referenced from another
5123            --  object file. Note this used to be set when we set Is_Imported
5124            --  back in Sem_Prag, but now we delay it to this point, since we
5125            --  don't want to set this flag if we wrap an imported subprogram.
5126
5127            Set_Is_Public (E);
5128         end if;
5129      end Wrap_Imported_Subprogram;
5130
5131      --  Local variables
5132
5133      Saved_GM : constant Ghost_Mode_Type := Ghost_Mode;
5134      --  Save the Ghost mode to restore on exit
5135
5136   --  Start of processing for Freeze_Entity
5137
5138   begin
5139      --  The entity being frozen may be subject to pragma Ghost. Set the mode
5140      --  now to ensure that any nodes generated during freezing are properly
5141      --  flagged as Ghost.
5142
5143      Set_Ghost_Mode (E);
5144
5145      --  We are going to test for various reasons why this entity need not be
5146      --  frozen here, but in the case of an Itype that's defined within a
5147      --  record, that test actually applies to the record.
5148
5149      if Is_Itype (E) and then Is_Record_Type (Scope (E)) then
5150         Test_E := Scope (E);
5151      elsif Is_Itype (E) and then Present (Underlying_Type (Scope (E)))
5152        and then Is_Record_Type (Underlying_Type (Scope (E)))
5153      then
5154         Test_E := Underlying_Type (Scope (E));
5155      end if;
5156
5157      --  Do not freeze if already frozen since we only need one freeze node
5158
5159      if Is_Frozen (E) then
5160         Result := No_List;
5161         goto Leave;
5162
5163      elsif Ekind (E) = E_Generic_Package then
5164         Result := Freeze_Generic_Entities (E);
5165         goto Leave;
5166
5167      --  It is improper to freeze an external entity within a generic because
5168      --  its freeze node will appear in a non-valid context. The entity will
5169      --  be frozen in the proper scope after the current generic is analyzed.
5170      --  However, aspects must be analyzed because they may be queried later
5171      --  within the generic itself, and the corresponding pragma or attribute
5172      --  definition has not been analyzed yet.
5173
5174      elsif Inside_A_Generic and then External_Ref_In_Generic (Test_E) then
5175         if Has_Delayed_Aspects (E) then
5176            Analyze_Aspects_At_Freeze_Point (E);
5177         end if;
5178
5179         Result := No_List;
5180         goto Leave;
5181
5182      --  AI05-0213: A formal incomplete type does not freeze the actual. In
5183      --  the instance, the same applies to the subtype renaming the actual.
5184
5185      elsif Is_Private_Type (E)
5186        and then Is_Generic_Actual_Type (E)
5187        and then No (Full_View (Base_Type (E)))
5188        and then Ada_Version >= Ada_2012
5189      then
5190         Result := No_List;
5191         goto Leave;
5192
5193      --  Formal subprograms are never frozen
5194
5195      elsif Is_Formal_Subprogram (E) then
5196         Result := No_List;
5197         goto Leave;
5198
5199      --  Generic types are never frozen as they lack delayed semantic checks
5200
5201      elsif Is_Generic_Type (E) then
5202         Result := No_List;
5203         goto Leave;
5204
5205      --  Do not freeze a global entity within an inner scope created during
5206      --  expansion. A call to subprogram E within some internal procedure
5207      --  (a stream attribute for example) might require freezing E, but the
5208      --  freeze node must appear in the same declarative part as E itself.
5209      --  The two-pass elaboration mechanism in gigi guarantees that E will
5210      --  be frozen before the inner call is elaborated. We exclude constants
5211      --  from this test, because deferred constants may be frozen early, and
5212      --  must be diagnosed (e.g. in the case of a deferred constant being used
5213      --  in a default expression). If the enclosing subprogram comes from
5214      --  source, or is a generic instance, then the freeze point is the one
5215      --  mandated by the language, and we freeze the entity. A subprogram that
5216      --  is a child unit body that acts as a spec does not have a spec that
5217      --  comes from source, but can only come from source.
5218
5219      elsif In_Open_Scopes (Scope (Test_E))
5220        and then Scope (Test_E) /= Current_Scope
5221        and then Ekind (Test_E) /= E_Constant
5222      then
5223         declare
5224            S : Entity_Id;
5225
5226         begin
5227            S := Current_Scope;
5228            while Present (S) loop
5229               if Is_Overloadable (S) then
5230                  if Comes_From_Source (S)
5231                    or else Is_Generic_Instance (S)
5232                    or else Is_Child_Unit (S)
5233                  then
5234                     exit;
5235                  else
5236                     Result := No_List;
5237                     goto Leave;
5238                  end if;
5239               end if;
5240
5241               S := Scope (S);
5242            end loop;
5243         end;
5244
5245      --  Similarly, an inlined instance body may make reference to global
5246      --  entities, but these references cannot be the proper freezing point
5247      --  for them, and in the absence of inlining freezing will take place in
5248      --  their own scope. Normally instance bodies are analyzed after the
5249      --  enclosing compilation, and everything has been frozen at the proper
5250      --  place, but with front-end inlining an instance body is compiled
5251      --  before the end of the enclosing scope, and as a result out-of-order
5252      --  freezing must be prevented.
5253
5254      elsif Front_End_Inlining
5255        and then In_Instance_Body
5256        and then Present (Scope (Test_E))
5257      then
5258         declare
5259            S : Entity_Id;
5260
5261         begin
5262            S := Scope (Test_E);
5263            while Present (S) loop
5264               if Is_Generic_Instance (S) then
5265                  exit;
5266               else
5267                  S := Scope (S);
5268               end if;
5269            end loop;
5270
5271            if No (S) then
5272               Result := No_List;
5273               goto Leave;
5274            end if;
5275         end;
5276      end if;
5277
5278      --  Add checks to detect proper initialization of scalars that may appear
5279      --  as subprogram parameters.
5280
5281      if Is_Subprogram (E) and then Check_Validity_Of_Parameters then
5282         Apply_Parameter_Validity_Checks (E);
5283      end if;
5284
5285      --  Deal with delayed aspect specifications. The analysis of the aspect
5286      --  is required to be delayed to the freeze point, thus we analyze the
5287      --  pragma or attribute definition clause in the tree at this point. We
5288      --  also analyze the aspect specification node at the freeze point when
5289      --  the aspect doesn't correspond to pragma/attribute definition clause.
5290      --  In addition, a derived type may have inherited aspects that were
5291      --  delayed in the parent, so these must also be captured now.
5292
5293      if Has_Delayed_Aspects (E)
5294        or else May_Inherit_Delayed_Rep_Aspects (E)
5295      then
5296         Analyze_Aspects_At_Freeze_Point (E);
5297      end if;
5298
5299      --  Here to freeze the entity
5300
5301      Set_Is_Frozen (E);
5302
5303      --  Case of entity being frozen is other than a type
5304
5305      if not Is_Type (E) then
5306
5307         --  If entity is exported or imported and does not have an external
5308         --  name, now is the time to provide the appropriate default name.
5309         --  Skip this if the entity is stubbed, since we don't need a name
5310         --  for any stubbed routine. For the case on intrinsics, if no
5311         --  external name is specified, then calls will be handled in
5312         --  Exp_Intr.Expand_Intrinsic_Call, and no name is needed. If an
5313         --  external name is provided, then Expand_Intrinsic_Call leaves
5314         --  calls in place for expansion by GIGI.
5315
5316         if (Is_Imported (E) or else Is_Exported (E))
5317           and then No (Interface_Name (E))
5318           and then Convention (E) /= Convention_Stubbed
5319           and then Convention (E) /= Convention_Intrinsic
5320         then
5321            Set_Encoded_Interface_Name
5322              (E, Get_Default_External_Name (E));
5323
5324         --  If entity is an atomic object appearing in a declaration and
5325         --  the expression is an aggregate, assign it to a temporary to
5326         --  ensure that the actual assignment is done atomically rather
5327         --  than component-wise (the assignment to the temp may be done
5328         --  component-wise, but that is harmless).
5329
5330         elsif Is_Atomic_Or_VFA (E)
5331           and then Nkind (Parent (E)) = N_Object_Declaration
5332           and then Present (Expression (Parent (E)))
5333           and then Nkind (Expression (Parent (E))) = N_Aggregate
5334           and then Is_Atomic_VFA_Aggregate (Expression (Parent (E)))
5335         then
5336            null;
5337         end if;
5338
5339         --  Subprogram case
5340
5341         if Is_Subprogram (E) then
5342
5343            --  Check for needing to wrap imported subprogram
5344
5345            Wrap_Imported_Subprogram (E);
5346
5347            --  Freeze all parameter types and the return type (RM 13.14(14)).
5348            --  However skip this for internal subprograms. This is also where
5349            --  any extra formal parameters are created since we now know
5350            --  whether the subprogram will use a foreign convention.
5351
5352            --  In Ada 2012, freezing a subprogram does not always freeze the
5353            --  corresponding profile (see AI05-019). An attribute reference
5354            --  is not a freezing point of the profile. Flag Do_Freeze_Profile
5355            --  indicates whether the profile should be frozen now.
5356            --  Other constructs that should not freeze ???
5357
5358            --  This processing doesn't apply to internal entities (see below)
5359
5360            if not Is_Internal (E) and then Do_Freeze_Profile then
5361               if not Freeze_Profile (E) then
5362                  goto Leave;
5363               end if;
5364            end if;
5365
5366            --  Must freeze its parent first if it is a derived subprogram
5367
5368            if Present (Alias (E)) then
5369               Freeze_And_Append (Alias (E), N, Result);
5370            end if;
5371
5372            --  We don't freeze internal subprograms, because we don't normally
5373            --  want addition of extra formals or mechanism setting to happen
5374            --  for those. However we do pass through predefined dispatching
5375            --  cases, since extra formals may be needed in some cases, such as
5376            --  for the stream 'Input function (build-in-place formals).
5377
5378            if not Is_Internal (E)
5379              or else Is_Predefined_Dispatching_Operation (E)
5380            then
5381               Freeze_Subprogram (E);
5382            end if;
5383
5384            --  If warning on suspicious contracts then check for the case of
5385            --  a postcondition other than False for a No_Return subprogram.
5386
5387            if No_Return (E)
5388              and then Warn_On_Suspicious_Contract
5389              and then Present (Contract (E))
5390            then
5391               declare
5392                  Prag : Node_Id := Pre_Post_Conditions (Contract (E));
5393                  Exp  : Node_Id;
5394
5395               begin
5396                  while Present (Prag) loop
5397                     if Nam_In (Pragma_Name_Unmapped (Prag),
5398                                Name_Post,
5399                                Name_Postcondition,
5400                                Name_Refined_Post)
5401                     then
5402                        Exp :=
5403                          Expression
5404                            (First (Pragma_Argument_Associations (Prag)));
5405
5406                        if Nkind (Exp) /= N_Identifier
5407                          or else Chars (Exp) /= Name_False
5408                        then
5409                           Error_Msg_NE
5410                             ("useless postcondition, & is marked "
5411                              & "No_Return?T?", Exp, E);
5412                        end if;
5413                     end if;
5414
5415                     Prag := Next_Pragma (Prag);
5416                  end loop;
5417               end;
5418            end if;
5419
5420         --  Here for other than a subprogram or type
5421
5422         else
5423            --  If entity has a type, and it is not a generic unit, then
5424            --  freeze it first (RM 13.14(10)).
5425
5426            if Present (Etype (E))
5427              and then Ekind (E) /= E_Generic_Function
5428            then
5429               Freeze_And_Append (Etype (E), N, Result);
5430
5431               --  For an object of an anonymous array type, aspects on the
5432               --  object declaration apply to the type itself. This is the
5433               --  case for Atomic_Components, Volatile_Components, and
5434               --  Independent_Components. In these cases analysis of the
5435               --  generated pragma will mark the anonymous types accordingly,
5436               --  and the object itself does not require a freeze node.
5437
5438               if Ekind (E) = E_Variable
5439                 and then Is_Itype (Etype (E))
5440                 and then Is_Array_Type (Etype (E))
5441                 and then Has_Delayed_Aspects (E)
5442               then
5443                  Set_Has_Delayed_Aspects (E, False);
5444                  Set_Has_Delayed_Freeze (E, False);
5445                  Set_Freeze_Node (E, Empty);
5446               end if;
5447            end if;
5448
5449            --  Special processing for objects created by object declaration
5450
5451            if Nkind (Declaration_Node (E)) = N_Object_Declaration then
5452               Freeze_Object_Declaration (E);
5453            end if;
5454
5455            --  Check that a constant which has a pragma Volatile[_Components]
5456            --  or Atomic[_Components] also has a pragma Import (RM C.6(13)).
5457
5458            --  Note: Atomic[_Components] also sets Volatile[_Components]
5459
5460            if Ekind (E) = E_Constant
5461              and then (Has_Volatile_Components (E) or else Is_Volatile (E))
5462              and then not Is_Imported (E)
5463              and then not Has_Boolean_Aspect_Import (E)
5464            then
5465               --  Make sure we actually have a pragma, and have not merely
5466               --  inherited the indication from elsewhere (e.g. an address
5467               --  clause, which is not good enough in RM terms).
5468
5469               if Has_Rep_Pragma (E, Name_Atomic)
5470                    or else
5471                  Has_Rep_Pragma (E, Name_Atomic_Components)
5472               then
5473                  Error_Msg_N
5474                    ("stand alone atomic constant must be " &
5475                     "imported (RM C.6(13))", E);
5476
5477               elsif Has_Rep_Pragma (E, Name_Volatile)
5478                       or else
5479                     Has_Rep_Pragma (E, Name_Volatile_Components)
5480               then
5481                  Error_Msg_N
5482                    ("stand alone volatile constant must be " &
5483                     "imported (RM C.6(13))", E);
5484               end if;
5485            end if;
5486
5487            --  Static objects require special handling
5488
5489            if (Ekind (E) = E_Constant or else Ekind (E) = E_Variable)
5490              and then Is_Statically_Allocated (E)
5491            then
5492               Freeze_Static_Object (E);
5493            end if;
5494
5495            --  Remaining step is to layout objects
5496
5497            if Ekind_In (E, E_Variable, E_Constant, E_Loop_Parameter)
5498              or else Is_Formal (E)
5499            then
5500               Layout_Object (E);
5501            end if;
5502
5503            --  For an object that does not have delayed freezing, and whose
5504            --  initialization actions have been captured in a compound
5505            --  statement, move them back now directly within the enclosing
5506            --  statement sequence.
5507
5508            if Ekind_In (E, E_Constant, E_Variable)
5509              and then not Has_Delayed_Freeze (E)
5510            then
5511               Explode_Initialization_Compound_Statement (E);
5512            end if;
5513
5514            --  Do not generate a freeze node for a generic unit
5515
5516            if Is_Generic_Unit (E) then
5517               Result := No_List;
5518               goto Leave;
5519            end if;
5520         end if;
5521
5522      --  Case of a type or subtype being frozen
5523
5524      else
5525         --  Verify several SPARK legality rules related to Ghost types now
5526         --  that the type is frozen.
5527
5528         Check_Ghost_Type (E);
5529
5530         --  We used to check here that a full type must have preelaborable
5531         --  initialization if it completes a private type specified with
5532         --  pragma Preelaborable_Initialization, but that missed cases where
5533         --  the types occur within a generic package, since the freezing
5534         --  that occurs within a containing scope generally skips traversal
5535         --  of a generic unit's declarations (those will be frozen within
5536         --  instances). This check was moved to Analyze_Package_Specification.
5537
5538         --  The type may be defined in a generic unit. This can occur when
5539         --  freezing a generic function that returns the type (which is
5540         --  defined in a parent unit). It is clearly meaningless to freeze
5541         --  this type. However, if it is a subtype, its size may be determi-
5542         --  nable and used in subsequent checks, so might as well try to
5543         --  compute it.
5544
5545         --  In Ada 2012, Freeze_Entities is also used in the front end to
5546         --  trigger the analysis of aspect expressions, so in this case we
5547         --  want to continue the freezing process.
5548
5549         --  Is_Generic_Unit (Scope (E)) is dubious here, do we want instead
5550         --  In_Generic_Scope (E)???
5551
5552         if Present (Scope (E))
5553           and then Is_Generic_Unit (Scope (E))
5554           and then
5555             (not Has_Predicates (E)
5556               and then not Has_Delayed_Freeze (E))
5557         then
5558            Check_Compile_Time_Size (E);
5559            Result := No_List;
5560            goto Leave;
5561         end if;
5562
5563         --  Check for error of Type_Invariant'Class applied to an untagged
5564         --  type (check delayed to freeze time when full type is available).
5565
5566         declare
5567            Prag : constant Node_Id := Get_Pragma (E, Pragma_Invariant);
5568         begin
5569            if Present (Prag)
5570              and then Class_Present (Prag)
5571              and then not Is_Tagged_Type (E)
5572            then
5573               Error_Msg_NE
5574                 ("Type_Invariant''Class cannot be specified for &", Prag, E);
5575               Error_Msg_N
5576                 ("\can only be specified for a tagged type", Prag);
5577            end if;
5578         end;
5579
5580         --  Deal with special cases of freezing for subtype
5581
5582         if E /= Base_Type (E) then
5583
5584            --  Before we do anything else, a specific test for the case of a
5585            --  size given for an array where the array would need to be packed
5586            --  in order for the size to be honored, but is not. This is the
5587            --  case where implicit packing may apply. The reason we do this so
5588            --  early is that, if we have implicit packing, the layout of the
5589            --  base type is affected, so we must do this before we freeze the
5590            --  base type.
5591
5592            --  We could do this processing only if implicit packing is enabled
5593            --  since in all other cases, the error would be caught by the back
5594            --  end. However, we choose to do the check even if we do not have
5595            --  implicit packing enabled, since this allows us to give a more
5596            --  useful error message (advising use of pragma Implicit_Packing
5597            --  or pragma Pack).
5598
5599            if Is_Array_Type (E) then
5600               declare
5601                  Ctyp : constant Entity_Id := Component_Type (E);
5602                  Rsiz : constant Uint      := RM_Size (Ctyp);
5603                  SZ   : constant Node_Id   := Size_Clause (E);
5604                  Btyp : constant Entity_Id := Base_Type (E);
5605
5606                  Lo   : Node_Id;
5607                  Hi   : Node_Id;
5608                  Indx : Node_Id;
5609
5610                  Dim       : Uint;
5611                  Num_Elmts : Uint := Uint_1;
5612                  --  Number of elements in array
5613
5614               begin
5615                  --  Check enabling conditions. These are straightforward
5616                  --  except for the test for a limited composite type. This
5617                  --  eliminates the rare case of a array of limited components
5618                  --  where there are issues of whether or not we can go ahead
5619                  --  and pack the array (since we can't freely pack and unpack
5620                  --  arrays if they are limited).
5621
5622                  --  Note that we check the root type explicitly because the
5623                  --  whole point is we are doing this test before we have had
5624                  --  a chance to freeze the base type (and it is that freeze
5625                  --  action that causes stuff to be inherited).
5626
5627                  --  The conditions on the size are identical to those used in
5628                  --  Freeze_Array_Type to set the Is_Packed flag.
5629
5630                  if Has_Size_Clause (E)
5631                    and then Known_Static_RM_Size (E)
5632                    and then not Is_Packed (E)
5633                    and then not Has_Pragma_Pack (E)
5634                    and then not Has_Component_Size_Clause (E)
5635                    and then Known_Static_RM_Size (Ctyp)
5636                    and then Rsiz <= 64
5637                    and then not (Addressable (Rsiz)
5638                                   and then Known_Static_Esize (Ctyp)
5639                                   and then Esize (Ctyp) = Rsiz)
5640                    and then not (Rsiz mod System_Storage_Unit = 0
5641                                   and then Is_Composite_Type (Ctyp))
5642                    and then not Is_Limited_Composite (E)
5643                    and then not Is_Packed (Root_Type (E))
5644                    and then not Has_Component_Size_Clause (Root_Type (E))
5645                    and then not (CodePeer_Mode or GNATprove_Mode)
5646                  then
5647                     --  Compute number of elements in array
5648
5649                     Indx := First_Index (E);
5650                     while Present (Indx) loop
5651                        Get_Index_Bounds (Indx, Lo, Hi);
5652
5653                        if not (Compile_Time_Known_Value (Lo)
5654                                  and then
5655                                Compile_Time_Known_Value (Hi))
5656                        then
5657                           goto No_Implicit_Packing;
5658                        end if;
5659
5660                        Dim := Expr_Value (Hi) - Expr_Value (Lo) + 1;
5661
5662                        if Dim >= 0 then
5663                           Num_Elmts := Num_Elmts * Dim;
5664                        else
5665                           Num_Elmts := Uint_0;
5666                        end if;
5667
5668                        Next_Index (Indx);
5669                     end loop;
5670
5671                     --  What we are looking for here is the situation where
5672                     --  the RM_Size given would be exactly right if there was
5673                     --  a pragma Pack, resulting in the component size being
5674                     --  the RM_Size of the component type.
5675
5676                     if RM_Size (E) = Num_Elmts * Rsiz then
5677
5678                        --  For implicit packing mode, just set the component
5679                        --  size and Freeze_Array_Type will do the rest.
5680
5681                        if Implicit_Packing then
5682                           Set_Component_Size (Btyp, Rsiz);
5683
5684                        --  Otherwise give an error message
5685
5686                        else
5687                           Error_Msg_NE
5688                             ("size given for& too small", SZ, E);
5689                           Error_Msg_N -- CODEFIX
5690                             ("\use explicit pragma Pack or use pragma "
5691                              & "Implicit_Packing", SZ);
5692                        end if;
5693                     end if;
5694                  end if;
5695               end;
5696            end if;
5697
5698            <<No_Implicit_Packing>>
5699
5700            --  If ancestor subtype present, freeze that first. Note that this
5701            --  will also get the base type frozen. Need RM reference ???
5702
5703            Atype := Ancestor_Subtype (E);
5704
5705            if Present (Atype) then
5706               Freeze_And_Append (Atype, N, Result);
5707
5708            --  No ancestor subtype present
5709
5710            else
5711               --  See if we have a nearest ancestor that has a predicate.
5712               --  That catches the case of derived type with a predicate.
5713               --  Need RM reference here ???
5714
5715               Atype := Nearest_Ancestor (E);
5716
5717               if Present (Atype) and then Has_Predicates (Atype) then
5718                  Freeze_And_Append (Atype, N, Result);
5719               end if;
5720
5721               --  Freeze base type before freezing the entity (RM 13.14(15))
5722
5723               if E /= Base_Type (E) then
5724                  Freeze_And_Append (Base_Type (E), N, Result);
5725               end if;
5726            end if;
5727
5728            --  A subtype inherits all the type-related representation aspects
5729            --  from its parents (RM 13.1(8)).
5730
5731            Inherit_Aspects_At_Freeze_Point (E);
5732
5733         --  For a derived type, freeze its parent type first (RM 13.14(15))
5734
5735         elsif Is_Derived_Type (E) then
5736            Freeze_And_Append (Etype (E), N, Result);
5737            Freeze_And_Append (First_Subtype (Etype (E)), N, Result);
5738
5739            --  A derived type inherits each type-related representation aspect
5740            --  of its parent type that was directly specified before the
5741            --  declaration of the derived type (RM 13.1(15)).
5742
5743            Inherit_Aspects_At_Freeze_Point (E);
5744         end if;
5745
5746         --  Check for incompatible size and alignment for record type
5747
5748         if Warn_On_Size_Alignment
5749           and then Is_Record_Type (E)
5750           and then Has_Size_Clause (E) and then Has_Alignment_Clause (E)
5751
5752           --  If explicit Object_Size clause given assume that the programmer
5753           --  knows what he is doing, and expects the compiler behavior.
5754
5755           and then not Has_Object_Size_Clause (E)
5756
5757           --  Check for size not a multiple of alignment
5758
5759           and then RM_Size (E) mod (Alignment (E) * System_Storage_Unit) /= 0
5760         then
5761            declare
5762               SC    : constant Node_Id := Size_Clause (E);
5763               AC    : constant Node_Id := Alignment_Clause (E);
5764               Loc   : Node_Id;
5765               Abits : constant Uint := Alignment (E) * System_Storage_Unit;
5766
5767            begin
5768               if Present (SC) and then Present (AC) then
5769
5770                  --  Give a warning
5771
5772                  if Sloc (SC) > Sloc (AC) then
5773                     Loc := SC;
5774                     Error_Msg_NE
5775                       ("?Z?size is not a multiple of alignment for &",
5776                        Loc, E);
5777                     Error_Msg_Sloc := Sloc (AC);
5778                     Error_Msg_Uint_1 := Alignment (E);
5779                     Error_Msg_N ("\?Z?alignment of ^ specified #", Loc);
5780
5781                  else
5782                     Loc := AC;
5783                     Error_Msg_NE
5784                       ("?Z?size is not a multiple of alignment for &",
5785                        Loc, E);
5786                     Error_Msg_Sloc := Sloc (SC);
5787                     Error_Msg_Uint_1 := RM_Size (E);
5788                     Error_Msg_N ("\?Z?size of ^ specified #", Loc);
5789                  end if;
5790
5791                  Error_Msg_Uint_1 := ((RM_Size (E) / Abits) + 1) * Abits;
5792                  Error_Msg_N ("\?Z?Object_Size will be increased to ^", Loc);
5793               end if;
5794            end;
5795         end if;
5796
5797         --  Array type
5798
5799         if Is_Array_Type (E) then
5800            Freeze_Array_Type (E);
5801
5802         --  For a class-wide type, the corresponding specific type is
5803         --  frozen as well (RM 13.14(15))
5804
5805         elsif Is_Class_Wide_Type (E) then
5806            Freeze_And_Append (Root_Type (E), N, Result);
5807
5808            --  If the base type of the class-wide type is still incomplete,
5809            --  the class-wide remains unfrozen as well. This is legal when
5810            --  E is the formal of a primitive operation of some other type
5811            --  which is being frozen.
5812
5813            if not Is_Frozen (Root_Type (E)) then
5814               Set_Is_Frozen (E, False);
5815               goto Leave;
5816            end if;
5817
5818            --  The equivalent type associated with a class-wide subtype needs
5819            --  to be frozen to ensure that its layout is done.
5820
5821            if Ekind (E) = E_Class_Wide_Subtype
5822              and then Present (Equivalent_Type (E))
5823            then
5824               Freeze_And_Append (Equivalent_Type (E), N, Result);
5825            end if;
5826
5827            --  Generate an itype reference for a library-level class-wide type
5828            --  at the freeze point. Otherwise the first explicit reference to
5829            --  the type may appear in an inner scope which will be rejected by
5830            --  the back-end.
5831
5832            if Is_Itype (E)
5833              and then Is_Compilation_Unit (Scope (E))
5834            then
5835               declare
5836                  Ref : constant Node_Id := Make_Itype_Reference (Loc);
5837
5838               begin
5839                  Set_Itype (Ref, E);
5840
5841                  --  From a gigi point of view, a class-wide subtype derives
5842                  --  from its record equivalent type. As a result, the itype
5843                  --  reference must appear after the freeze node of the
5844                  --  equivalent type or gigi will reject the reference.
5845
5846                  if Ekind (E) = E_Class_Wide_Subtype
5847                    and then Present (Equivalent_Type (E))
5848                  then
5849                     Insert_After (Freeze_Node (Equivalent_Type (E)), Ref);
5850                  else
5851                     Add_To_Result (Ref);
5852                  end if;
5853               end;
5854            end if;
5855
5856         --  For a record type or record subtype, freeze all component types
5857         --  (RM 13.14(15)). We test for E_Record_(sub)Type here, rather than
5858         --  using Is_Record_Type, because we don't want to attempt the freeze
5859         --  for the case of a private type with record extension (we will do
5860         --  that later when the full type is frozen).
5861
5862         elsif Ekind_In (E, E_Record_Type, E_Record_Subtype) then
5863            if not In_Generic_Scope (E) then
5864               Freeze_Record_Type (E);
5865            end if;
5866
5867            --  Report a warning if a discriminated record base type has a
5868            --  convention with language C or C++ applied to it. This check is
5869            --  done even within generic scopes (but not in instantiations),
5870            --  which is why we don't do it as part of Freeze_Record_Type.
5871
5872            Check_Suspicious_Convention (E);
5873
5874         --  For a concurrent type, freeze corresponding record type. This does
5875         --  not correspond to any specific rule in the RM, but the record type
5876         --  is essentially part of the concurrent type. Also freeze all local
5877         --  entities. This includes record types created for entry parameter
5878         --  blocks and whatever local entities may appear in the private part.
5879
5880         elsif Is_Concurrent_Type (E) then
5881            if Present (Corresponding_Record_Type (E)) then
5882               Freeze_And_Append (Corresponding_Record_Type (E), N, Result);
5883            end if;
5884
5885            Comp := First_Entity (E);
5886            while Present (Comp) loop
5887               if Is_Type (Comp) then
5888                  Freeze_And_Append (Comp, N, Result);
5889
5890               elsif (Ekind (Comp)) /= E_Function then
5891
5892                  --  The guard on the presence of the Etype seems to be needed
5893                  --  for some CodePeer (-gnatcC) cases, but not clear why???
5894
5895                  if Present (Etype (Comp)) then
5896                     if Is_Itype (Etype (Comp))
5897                       and then Underlying_Type (Scope (Etype (Comp))) = E
5898                     then
5899                        Undelay_Type (Etype (Comp));
5900                     end if;
5901
5902                     Freeze_And_Append (Etype (Comp), N, Result);
5903                  end if;
5904               end if;
5905
5906               Next_Entity (Comp);
5907            end loop;
5908
5909         --  Private types are required to point to the same freeze node as
5910         --  their corresponding full views. The freeze node itself has to
5911         --  point to the partial view of the entity (because from the partial
5912         --  view, we can retrieve the full view, but not the reverse).
5913         --  However, in order to freeze correctly, we need to freeze the full
5914         --  view. If we are freezing at the end of a scope (or within the
5915         --  scope) of the private type, the partial and full views will have
5916         --  been swapped, the full view appears first in the entity chain and
5917         --  the swapping mechanism ensures that the pointers are properly set
5918         --  (on scope exit).
5919
5920         --  If we encounter the partial view before the full view (e.g. when
5921         --  freezing from another scope), we freeze the full view, and then
5922         --  set the pointers appropriately since we cannot rely on swapping to
5923         --  fix things up (subtypes in an outer scope might not get swapped).
5924
5925         --  If the full view is itself private, the above requirements apply
5926         --  to the underlying full view instead of the full view. But there is
5927         --  no swapping mechanism for the underlying full view so we need to
5928         --  set the pointers appropriately in both cases.
5929
5930         elsif Is_Incomplete_Or_Private_Type (E)
5931           and then not Is_Generic_Type (E)
5932         then
5933            --  The construction of the dispatch table associated with library
5934            --  level tagged types forces freezing of all the primitives of the
5935            --  type, which may cause premature freezing of the partial view.
5936            --  For example:
5937
5938            --     package Pkg is
5939            --        type T is tagged private;
5940            --        type DT is new T with private;
5941            --        procedure Prim (X : in out T; Y : in out DT'Class);
5942            --     private
5943            --        type T is tagged null record;
5944            --        Obj : T;
5945            --        type DT is new T with null record;
5946            --     end;
5947
5948            --  In this case the type will be frozen later by the usual
5949            --  mechanism: an object declaration, an instantiation, or the
5950            --  end of a declarative part.
5951
5952            if Is_Library_Level_Tagged_Type (E)
5953              and then not Present (Full_View (E))
5954            then
5955               Set_Is_Frozen (E, False);
5956               goto Leave;
5957
5958            --  Case of full view present
5959
5960            elsif Present (Full_View (E)) then
5961
5962               --  If full view has already been frozen, then no further
5963               --  processing is required
5964
5965               if Is_Frozen (Full_View (E)) then
5966                  Set_Has_Delayed_Freeze (E, False);
5967                  Set_Freeze_Node (E, Empty);
5968
5969               --  Otherwise freeze full view and patch the pointers so that
5970               --  the freeze node will elaborate both views in the back end.
5971               --  However, if full view is itself private, freeze underlying
5972               --  full view instead and patch the pointers so that the freeze
5973               --  node will elaborate the three views in the back end.
5974
5975               else
5976                  declare
5977                     Full : Entity_Id := Full_View (E);
5978
5979                  begin
5980                     if Is_Private_Type (Full)
5981                       and then Present (Underlying_Full_View (Full))
5982                     then
5983                        Full := Underlying_Full_View (Full);
5984                     end if;
5985
5986                     Freeze_And_Append (Full, N, Result);
5987
5988                     if Full /= Full_View (E)
5989                       and then Has_Delayed_Freeze (Full_View (E))
5990                     then
5991                        F_Node := Freeze_Node (Full);
5992
5993                        if Present (F_Node) then
5994                           Inherit_Freeze_Node
5995                             (Fnod => F_Node,
5996                              Typ  => Full_View (E));
5997                        else
5998                           Set_Has_Delayed_Freeze (Full_View (E), False);
5999                           Set_Freeze_Node (Full_View (E), Empty);
6000                        end if;
6001                     end if;
6002
6003                     if Has_Delayed_Freeze (E) then
6004                        F_Node := Freeze_Node (Full_View (E));
6005
6006                        if Present (F_Node) then
6007                           Inherit_Freeze_Node
6008                             (Fnod => F_Node,
6009                              Typ  => E);
6010                        else
6011                           --  {Incomplete,Private}_Subtypes with Full_Views
6012                           --  constrained by discriminants.
6013
6014                           Set_Has_Delayed_Freeze (E, False);
6015                           Set_Freeze_Node (E, Empty);
6016                        end if;
6017                     end if;
6018                  end;
6019               end if;
6020
6021               Check_Debug_Info_Needed (E);
6022
6023               --  AI-117 requires that the convention of a partial view be the
6024               --  same as the convention of the full view. Note that this is a
6025               --  recognized breach of privacy, but it's essential for logical
6026               --  consistency of representation, and the lack of a rule in
6027               --  RM95 was an oversight.
6028
6029               Set_Convention (E, Convention (Full_View (E)));
6030
6031               Set_Size_Known_At_Compile_Time (E,
6032                 Size_Known_At_Compile_Time (Full_View (E)));
6033
6034               --  Size information is copied from the full view to the
6035               --  incomplete or private view for consistency.
6036
6037               --  We skip this is the full view is not a type. This is very
6038               --  strange of course, and can only happen as a result of
6039               --  certain illegalities, such as a premature attempt to derive
6040               --  from an incomplete type.
6041
6042               if Is_Type (Full_View (E)) then
6043                  Set_Size_Info (E, Full_View (E));
6044                  Set_RM_Size   (E, RM_Size (Full_View (E)));
6045               end if;
6046
6047               goto Leave;
6048
6049            --  Case of underlying full view present
6050
6051            elsif Is_Private_Type (E)
6052              and then Present (Underlying_Full_View (E))
6053            then
6054               if not Is_Frozen (Underlying_Full_View (E)) then
6055                  Freeze_And_Append (Underlying_Full_View (E), N, Result);
6056               end if;
6057
6058               --  Patch the pointers so that the freeze node will elaborate
6059               --  both views in the back end.
6060
6061               if Has_Delayed_Freeze (E) then
6062                  F_Node := Freeze_Node (Underlying_Full_View (E));
6063
6064                  if Present (F_Node) then
6065                     Inherit_Freeze_Node
6066                       (Fnod => F_Node,
6067                        Typ  => E);
6068                  else
6069                     Set_Has_Delayed_Freeze (E, False);
6070                     Set_Freeze_Node (E, Empty);
6071                  end if;
6072               end if;
6073
6074               Check_Debug_Info_Needed (E);
6075
6076               goto Leave;
6077
6078            --  Case of no full view present. If entity is derived or subtype,
6079            --  it is safe to freeze, correctness depends on the frozen status
6080            --  of parent. Otherwise it is either premature usage, or a Taft
6081            --  amendment type, so diagnosis is at the point of use and the
6082            --  type might be frozen later.
6083
6084            elsif E /= Base_Type (E) or else Is_Derived_Type (E) then
6085               null;
6086
6087            else
6088               Set_Is_Frozen (E, False);
6089               Result := No_List;
6090               goto Leave;
6091            end if;
6092
6093         --  For access subprogram, freeze types of all formals, the return
6094         --  type was already frozen, since it is the Etype of the function.
6095         --  Formal types can be tagged Taft amendment types, but otherwise
6096         --  they cannot be incomplete.
6097
6098         elsif Ekind (E) = E_Subprogram_Type then
6099            Formal := First_Formal (E);
6100            while Present (Formal) loop
6101               if Ekind (Etype (Formal)) = E_Incomplete_Type
6102                 and then No (Full_View (Etype (Formal)))
6103               then
6104                  if Is_Tagged_Type (Etype (Formal)) then
6105                     null;
6106
6107                  --  AI05-151: Incomplete types are allowed in access to
6108                  --  subprogram specifications.
6109
6110                  elsif Ada_Version < Ada_2012 then
6111                     Error_Msg_NE
6112                       ("invalid use of incomplete type&", E, Etype (Formal));
6113                  end if;
6114               end if;
6115
6116               Freeze_And_Append (Etype (Formal), N, Result);
6117               Next_Formal (Formal);
6118            end loop;
6119
6120            Freeze_Subprogram (E);
6121
6122         --  For access to a protected subprogram, freeze the equivalent type
6123         --  (however this is not set if we are not generating code or if this
6124         --  is an anonymous type used just for resolution).
6125
6126         elsif Is_Access_Protected_Subprogram_Type (E) then
6127            if Present (Equivalent_Type (E)) then
6128               Freeze_And_Append (Equivalent_Type (E), N, Result);
6129            end if;
6130         end if;
6131
6132         --  Generic types are never seen by the back-end, and are also not
6133         --  processed by the expander (since the expander is turned off for
6134         --  generic processing), so we never need freeze nodes for them.
6135
6136         if Is_Generic_Type (E) then
6137            goto Leave;
6138         end if;
6139
6140         --  Some special processing for non-generic types to complete
6141         --  representation details not known till the freeze point.
6142
6143         if Is_Fixed_Point_Type (E) then
6144            Freeze_Fixed_Point_Type (E);
6145
6146            --  Some error checks required for ordinary fixed-point type. Defer
6147            --  these till the freeze-point since we need the small and range
6148            --  values. We only do these checks for base types
6149
6150            if Is_Ordinary_Fixed_Point_Type (E) and then Is_Base_Type (E) then
6151               if Small_Value (E) < Ureal_2_M_80 then
6152                  Error_Msg_Name_1 := Name_Small;
6153                  Error_Msg_N
6154                    ("`&''%` too small, minimum allowed is 2.0'*'*(-80)", E);
6155
6156               elsif Small_Value (E) > Ureal_2_80 then
6157                  Error_Msg_Name_1 := Name_Small;
6158                  Error_Msg_N
6159                    ("`&''%` too large, maximum allowed is 2.0'*'*80", E);
6160               end if;
6161
6162               if Expr_Value_R (Type_Low_Bound (E)) < Ureal_M_10_36 then
6163                  Error_Msg_Name_1 := Name_First;
6164                  Error_Msg_N
6165                    ("`&''%` too small, minimum allowed is -10.0'*'*36", E);
6166               end if;
6167
6168               if Expr_Value_R (Type_High_Bound (E)) > Ureal_10_36 then
6169                  Error_Msg_Name_1 := Name_Last;
6170                  Error_Msg_N
6171                    ("`&''%` too large, maximum allowed is 10.0'*'*36", E);
6172               end if;
6173            end if;
6174
6175         elsif Is_Enumeration_Type (E) then
6176            Freeze_Enumeration_Type (E);
6177
6178         elsif Is_Integer_Type (E) then
6179            Adjust_Esize_For_Alignment (E);
6180
6181            if Is_Modular_Integer_Type (E)
6182              and then Warn_On_Suspicious_Modulus_Value
6183            then
6184               Check_Suspicious_Modulus (E);
6185            end if;
6186
6187         --  The pool applies to named and anonymous access types, but not
6188         --  to subprogram and to  internal types generated for 'Access
6189         --  references.
6190
6191         elsif Is_Access_Type (E)
6192           and then not Is_Access_Subprogram_Type (E)
6193           and then Ekind (E) /= E_Access_Attribute_Type
6194         then
6195            --  If a pragma Default_Storage_Pool applies, and this type has no
6196            --  Storage_Pool or Storage_Size clause (which must have occurred
6197            --  before the freezing point), then use the default. This applies
6198            --  only to base types.
6199
6200            --  None of this applies to access to subprograms, for which there
6201            --  are clearly no pools.
6202
6203            if Present (Default_Pool)
6204              and then Is_Base_Type (E)
6205              and then not Has_Storage_Size_Clause (E)
6206              and then No (Associated_Storage_Pool (E))
6207            then
6208               --  Case of pragma Default_Storage_Pool (null)
6209
6210               if Nkind (Default_Pool) = N_Null then
6211                  Set_No_Pool_Assigned (E);
6212
6213               --  Case of pragma Default_Storage_Pool (storage_pool_NAME)
6214
6215               else
6216                  Set_Associated_Storage_Pool (E, Entity (Default_Pool));
6217               end if;
6218            end if;
6219
6220            --  Check restriction for standard storage pool
6221
6222            if No (Associated_Storage_Pool (E)) then
6223               Check_Restriction (No_Standard_Storage_Pools, E);
6224            end if;
6225
6226            --  Deal with error message for pure access type. This is not an
6227            --  error in Ada 2005 if there is no pool (see AI-366).
6228
6229            if Is_Pure_Unit_Access_Type (E)
6230              and then (Ada_Version < Ada_2005
6231                         or else not No_Pool_Assigned (E))
6232              and then not Is_Generic_Unit (Scope (E))
6233            then
6234               Error_Msg_N ("named access type not allowed in pure unit", E);
6235
6236               if Ada_Version >= Ada_2005 then
6237                  Error_Msg_N
6238                    ("\would be legal if Storage_Size of 0 given??", E);
6239
6240               elsif No_Pool_Assigned (E) then
6241                  Error_Msg_N
6242                    ("\would be legal in Ada 2005??", E);
6243
6244               else
6245                  Error_Msg_N
6246                    ("\would be legal in Ada 2005 if "
6247                     & "Storage_Size of 0 given??", E);
6248               end if;
6249            end if;
6250         end if;
6251
6252         --  Case of composite types
6253
6254         if Is_Composite_Type (E) then
6255
6256            --  AI-117 requires that all new primitives of a tagged type must
6257            --  inherit the convention of the full view of the type. Inherited
6258            --  and overriding operations are defined to inherit the convention
6259            --  of their parent or overridden subprogram (also specified in
6260            --  AI-117), which will have occurred earlier (in Derive_Subprogram
6261            --  and New_Overloaded_Entity). Here we set the convention of
6262            --  primitives that are still convention Ada, which will ensure
6263            --  that any new primitives inherit the type's convention. Class-
6264            --  wide types can have a foreign convention inherited from their
6265            --  specific type, but are excluded from this since they don't have
6266            --  any associated primitives.
6267
6268            if Is_Tagged_Type (E)
6269              and then not Is_Class_Wide_Type (E)
6270              and then Convention (E) /= Convention_Ada
6271            then
6272               declare
6273                  Prim_List : constant Elist_Id := Primitive_Operations (E);
6274                  Prim      : Elmt_Id;
6275
6276               begin
6277                  Prim := First_Elmt (Prim_List);
6278                  while Present (Prim) loop
6279                     if Convention (Node (Prim)) = Convention_Ada then
6280                        Set_Convention (Node (Prim), Convention (E));
6281                     end if;
6282
6283                     Next_Elmt (Prim);
6284                  end loop;
6285               end;
6286            end if;
6287
6288            --  If the type is a simple storage pool type, then this is where
6289            --  we attempt to locate and validate its Allocate, Deallocate, and
6290            --  Storage_Size operations (the first is required, and the latter
6291            --  two are optional). We also verify that the full type for a
6292            --  private type is allowed to be a simple storage pool type.
6293
6294            if Present (Get_Rep_Pragma (E, Name_Simple_Storage_Pool_Type))
6295              and then (Is_Base_Type (E) or else Has_Private_Declaration (E))
6296            then
6297               --  If the type is marked Has_Private_Declaration, then this is
6298               --  a full type for a private type that was specified with the
6299               --  pragma Simple_Storage_Pool_Type, and here we ensure that the
6300               --  pragma is allowed for the full type (for example, it can't
6301               --  be an array type, or a nonlimited record type).
6302
6303               if Has_Private_Declaration (E) then
6304                  if (not Is_Record_Type (E) or else not Is_Limited_View (E))
6305                    and then not Is_Private_Type (E)
6306                  then
6307                     Error_Msg_Name_1 := Name_Simple_Storage_Pool_Type;
6308                     Error_Msg_N
6309                       ("pragma% can only apply to full type that is an " &
6310                        "explicitly limited type", E);
6311                  end if;
6312               end if;
6313
6314               Validate_Simple_Pool_Ops : declare
6315                  Pool_Type    : Entity_Id renames E;
6316                  Address_Type : constant Entity_Id := RTE (RE_Address);
6317                  Stg_Cnt_Type : constant Entity_Id := RTE (RE_Storage_Count);
6318
6319                  procedure Validate_Simple_Pool_Op_Formal
6320                    (Pool_Op        : Entity_Id;
6321                     Pool_Op_Formal : in out Entity_Id;
6322                     Expected_Mode  : Formal_Kind;
6323                     Expected_Type  : Entity_Id;
6324                     Formal_Name    : String;
6325                     OK_Formal      : in out Boolean);
6326                  --  Validate one formal Pool_Op_Formal of the candidate pool
6327                  --  operation Pool_Op. The formal must be of Expected_Type
6328                  --  and have mode Expected_Mode. OK_Formal will be set to
6329                  --  False if the formal doesn't match. If OK_Formal is False
6330                  --  on entry, then the formal will effectively be ignored
6331                  --  (because validation of the pool op has already failed).
6332                  --  Upon return, Pool_Op_Formal will be updated to the next
6333                  --  formal, if any.
6334
6335                  procedure Validate_Simple_Pool_Operation
6336                    (Op_Name : Name_Id);
6337                  --  Search for and validate a simple pool operation with the
6338                  --  name Op_Name. If the name is Allocate, then there must be
6339                  --  exactly one such primitive operation for the simple pool
6340                  --  type. If the name is Deallocate or Storage_Size, then
6341                  --  there can be at most one such primitive operation. The
6342                  --  profile of the located primitive must conform to what
6343                  --  is expected for each operation.
6344
6345                  ------------------------------------
6346                  -- Validate_Simple_Pool_Op_Formal --
6347                  ------------------------------------
6348
6349                  procedure Validate_Simple_Pool_Op_Formal
6350                    (Pool_Op        : Entity_Id;
6351                     Pool_Op_Formal : in out Entity_Id;
6352                     Expected_Mode  : Formal_Kind;
6353                     Expected_Type  : Entity_Id;
6354                     Formal_Name    : String;
6355                     OK_Formal      : in out Boolean)
6356                  is
6357                  begin
6358                     --  If OK_Formal is False on entry, then simply ignore
6359                     --  the formal, because an earlier formal has already
6360                     --  been flagged.
6361
6362                     if not OK_Formal then
6363                        return;
6364
6365                     --  If no formal is passed in, then issue an error for a
6366                     --  missing formal.
6367
6368                     elsif not Present (Pool_Op_Formal) then
6369                        Error_Msg_NE
6370                          ("simple storage pool op missing formal " &
6371                           Formal_Name & " of type&", Pool_Op, Expected_Type);
6372                        OK_Formal := False;
6373
6374                        return;
6375                     end if;
6376
6377                     if Etype (Pool_Op_Formal) /= Expected_Type then
6378
6379                        --  If the pool type was expected for this formal, then
6380                        --  this will not be considered a candidate operation
6381                        --  for the simple pool, so we unset OK_Formal so that
6382                        --  the op and any later formals will be ignored.
6383
6384                        if Expected_Type = Pool_Type then
6385                           OK_Formal := False;
6386
6387                           return;
6388
6389                        else
6390                           Error_Msg_NE
6391                             ("wrong type for formal " & Formal_Name &
6392                              " of simple storage pool op; expected type&",
6393                              Pool_Op_Formal, Expected_Type);
6394                        end if;
6395                     end if;
6396
6397                     --  Issue error if formal's mode is not the expected one
6398
6399                     if Ekind (Pool_Op_Formal) /= Expected_Mode then
6400                        Error_Msg_N
6401                          ("wrong mode for formal of simple storage pool op",
6402                           Pool_Op_Formal);
6403                     end if;
6404
6405                     --  Advance to the next formal
6406
6407                     Next_Formal (Pool_Op_Formal);
6408                  end Validate_Simple_Pool_Op_Formal;
6409
6410                  ------------------------------------
6411                  -- Validate_Simple_Pool_Operation --
6412                  ------------------------------------
6413
6414                  procedure Validate_Simple_Pool_Operation
6415                    (Op_Name : Name_Id)
6416                  is
6417                     Op       : Entity_Id;
6418                     Found_Op : Entity_Id := Empty;
6419                     Formal   : Entity_Id;
6420                     Is_OK    : Boolean;
6421
6422                  begin
6423                     pragma Assert
6424                       (Nam_In (Op_Name, Name_Allocate,
6425                                         Name_Deallocate,
6426                                         Name_Storage_Size));
6427
6428                     Error_Msg_Name_1 := Op_Name;
6429
6430                     --  For each homonym declared immediately in the scope
6431                     --  of the simple storage pool type, determine whether
6432                     --  the homonym is an operation of the pool type, and,
6433                     --  if so, check that its profile is as expected for
6434                     --  a simple pool operation of that name.
6435
6436                     Op := Get_Name_Entity_Id (Op_Name);
6437                     while Present (Op) loop
6438                        if Ekind_In (Op, E_Function, E_Procedure)
6439                          and then Scope (Op) = Current_Scope
6440                        then
6441                           Formal := First_Entity (Op);
6442
6443                           Is_OK := True;
6444
6445                           --  The first parameter must be of the pool type
6446                           --  in order for the operation to qualify.
6447
6448                           if Op_Name = Name_Storage_Size then
6449                              Validate_Simple_Pool_Op_Formal
6450                                (Op, Formal, E_In_Parameter, Pool_Type,
6451                                 "Pool", Is_OK);
6452                           else
6453                              Validate_Simple_Pool_Op_Formal
6454                                (Op, Formal, E_In_Out_Parameter, Pool_Type,
6455                                 "Pool", Is_OK);
6456                           end if;
6457
6458                           --  If another operation with this name has already
6459                           --  been located for the type, then flag an error,
6460                           --  since we only allow the type to have a single
6461                           --  such primitive.
6462
6463                           if Present (Found_Op) and then Is_OK then
6464                              Error_Msg_NE
6465                                ("only one % operation allowed for " &
6466                                 "simple storage pool type&", Op, Pool_Type);
6467                           end if;
6468
6469                           --  In the case of Allocate and Deallocate, a formal
6470                           --  of type System.Address is required.
6471
6472                           if Op_Name = Name_Allocate then
6473                              Validate_Simple_Pool_Op_Formal
6474                                (Op, Formal, E_Out_Parameter,
6475                                  Address_Type, "Storage_Address", Is_OK);
6476
6477                           elsif Op_Name = Name_Deallocate then
6478                              Validate_Simple_Pool_Op_Formal
6479                                (Op, Formal, E_In_Parameter,
6480                                 Address_Type, "Storage_Address", Is_OK);
6481                           end if;
6482
6483                           --  In the case of Allocate and Deallocate, formals
6484                           --  of type Storage_Count are required as the third
6485                           --  and fourth parameters.
6486
6487                           if Op_Name /= Name_Storage_Size then
6488                              Validate_Simple_Pool_Op_Formal
6489                                (Op, Formal, E_In_Parameter,
6490                                 Stg_Cnt_Type, "Size_In_Storage_Units", Is_OK);
6491                              Validate_Simple_Pool_Op_Formal
6492                                (Op, Formal, E_In_Parameter,
6493                                 Stg_Cnt_Type, "Alignment", Is_OK);
6494                           end if;
6495
6496                           --  If no mismatched formals have been found (Is_OK)
6497                           --  and no excess formals are present, then this
6498                           --  operation has been validated, so record it.
6499
6500                           if not Present (Formal) and then Is_OK then
6501                              Found_Op := Op;
6502                           end if;
6503                        end if;
6504
6505                        Op := Homonym (Op);
6506                     end loop;
6507
6508                     --  There must be a valid Allocate operation for the type,
6509                     --  so issue an error if none was found.
6510
6511                     if Op_Name = Name_Allocate
6512                       and then not Present (Found_Op)
6513                     then
6514                        Error_Msg_N ("missing % operation for simple " &
6515                                     "storage pool type", Pool_Type);
6516
6517                     elsif Present (Found_Op) then
6518
6519                        --  Simple pool operations can't be abstract
6520
6521                        if Is_Abstract_Subprogram (Found_Op) then
6522                           Error_Msg_N
6523                             ("simple storage pool operation must not be " &
6524                              "abstract", Found_Op);
6525                        end if;
6526
6527                        --  The Storage_Size operation must be a function with
6528                        --  Storage_Count as its result type.
6529
6530                        if Op_Name = Name_Storage_Size then
6531                           if Ekind (Found_Op) = E_Procedure then
6532                              Error_Msg_N
6533                                ("% operation must be a function", Found_Op);
6534
6535                           elsif Etype (Found_Op) /= Stg_Cnt_Type then
6536                              Error_Msg_NE
6537                                ("wrong result type for%, expected type&",
6538                                 Found_Op, Stg_Cnt_Type);
6539                           end if;
6540
6541                        --  Allocate and Deallocate must be procedures
6542
6543                        elsif Ekind (Found_Op) = E_Function then
6544                           Error_Msg_N
6545                             ("% operation must be a procedure", Found_Op);
6546                        end if;
6547                     end if;
6548                  end Validate_Simple_Pool_Operation;
6549
6550               --  Start of processing for Validate_Simple_Pool_Ops
6551
6552               begin
6553                  Validate_Simple_Pool_Operation (Name_Allocate);
6554                  Validate_Simple_Pool_Operation (Name_Deallocate);
6555                  Validate_Simple_Pool_Operation (Name_Storage_Size);
6556               end Validate_Simple_Pool_Ops;
6557            end if;
6558         end if;
6559
6560         --  Now that all types from which E may depend are frozen, see if the
6561         --  size is known at compile time, if it must be unsigned, or if
6562         --  strict alignment is required
6563
6564         Check_Compile_Time_Size (E);
6565         Check_Unsigned_Type (E);
6566
6567         if Base_Type (E) = E then
6568            Check_Strict_Alignment (E);
6569         end if;
6570
6571         --  Do not allow a size clause for a type which does not have a size
6572         --  that is known at compile time
6573
6574         if Has_Size_Clause (E)
6575           and then not Size_Known_At_Compile_Time (E)
6576         then
6577            --  Suppress this message if errors posted on E, even if we are
6578            --  in all errors mode, since this is often a junk message
6579
6580            if not Error_Posted (E) then
6581               Error_Msg_N
6582                 ("size clause not allowed for variable length type",
6583                  Size_Clause (E));
6584            end if;
6585         end if;
6586
6587         --  Now we set/verify the representation information, in particular
6588         --  the size and alignment values. This processing is not required for
6589         --  generic types, since generic types do not play any part in code
6590         --  generation, and so the size and alignment values for such types
6591         --  are irrelevant. Ditto for types declared within a generic unit,
6592         --  which may have components that depend on generic parameters, and
6593         --  that will be recreated in an instance.
6594
6595         if Inside_A_Generic then
6596            null;
6597
6598         --  Otherwise we call the layout procedure
6599
6600         else
6601            Layout_Type (E);
6602         end if;
6603
6604         --  If this is an access to subprogram whose designated type is itself
6605         --  a subprogram type, the return type of this anonymous subprogram
6606         --  type must be decorated as well.
6607
6608         if Ekind (E) = E_Anonymous_Access_Subprogram_Type
6609           and then Ekind (Designated_Type (E)) = E_Subprogram_Type
6610         then
6611            Layout_Type (Etype (Designated_Type (E)));
6612         end if;
6613
6614         --  If the type has a Defaut_Value/Default_Component_Value aspect,
6615         --  this is where we analye the expression (after the type is frozen,
6616         --  since in the case of Default_Value, we are analyzing with the
6617         --  type itself, and we treat Default_Component_Value similarly for
6618         --  the sake of uniformity).
6619
6620         if Is_First_Subtype (E) and then Has_Default_Aspect (E) then
6621            declare
6622               Nam : Name_Id;
6623               Exp : Node_Id;
6624               Typ : Entity_Id;
6625
6626            begin
6627               if Is_Scalar_Type (E) then
6628                  Nam := Name_Default_Value;
6629                  Typ := E;
6630                  Exp := Default_Aspect_Value (Typ);
6631               else
6632                  Nam := Name_Default_Component_Value;
6633                  Typ := Component_Type (E);
6634                  Exp := Default_Aspect_Component_Value (E);
6635               end if;
6636
6637               Analyze_And_Resolve (Exp, Typ);
6638
6639               if Etype (Exp) /= Any_Type then
6640                  if not Is_OK_Static_Expression (Exp) then
6641                     Error_Msg_Name_1 := Nam;
6642                     Flag_Non_Static_Expr
6643                       ("aspect% requires static expression", Exp);
6644                  end if;
6645               end if;
6646            end;
6647         end if;
6648
6649         --  End of freeze processing for type entities
6650      end if;
6651
6652      --  Here is where we logically freeze the current entity. If it has a
6653      --  freeze node, then this is the point at which the freeze node is
6654      --  linked into the result list.
6655
6656      if Has_Delayed_Freeze (E) then
6657
6658         --  If a freeze node is already allocated, use it, otherwise allocate
6659         --  a new one. The preallocation happens in the case of anonymous base
6660         --  types, where we preallocate so that we can set First_Subtype_Link.
6661         --  Note that we reset the Sloc to the current freeze location.
6662
6663         if Present (Freeze_Node (E)) then
6664            F_Node := Freeze_Node (E);
6665            Set_Sloc (F_Node, Loc);
6666
6667         else
6668            F_Node := New_Node (N_Freeze_Entity, Loc);
6669            Set_Freeze_Node (E, F_Node);
6670            Set_Access_Types_To_Process (F_Node, No_Elist);
6671            Set_TSS_Elist (F_Node, No_Elist);
6672            Set_Actions (F_Node, No_List);
6673         end if;
6674
6675         Set_Entity (F_Node, E);
6676         Add_To_Result (F_Node);
6677
6678         --  A final pass over record types with discriminants. If the type
6679         --  has an incomplete declaration, there may be constrained access
6680         --  subtypes declared elsewhere, which do not depend on the discrimi-
6681         --  nants of the type, and which are used as component types (i.e.
6682         --  the full view is a recursive type). The designated types of these
6683         --  subtypes can only be elaborated after the type itself, and they
6684         --  need an itype reference.
6685
6686         if Ekind (E) = E_Record_Type and then Has_Discriminants (E) then
6687            declare
6688               Comp : Entity_Id;
6689               IR   : Node_Id;
6690               Typ  : Entity_Id;
6691
6692            begin
6693               Comp := First_Component (E);
6694               while Present (Comp) loop
6695                  Typ  := Etype (Comp);
6696
6697                  if Ekind (Comp) = E_Component
6698                    and then Is_Access_Type (Typ)
6699                    and then Scope (Typ) /= E
6700                    and then Base_Type (Designated_Type (Typ)) = E
6701                    and then Is_Itype (Designated_Type (Typ))
6702                  then
6703                     IR := Make_Itype_Reference (Sloc (Comp));
6704                     Set_Itype (IR, Designated_Type (Typ));
6705                     Append (IR, Result);
6706                  end if;
6707
6708                  Next_Component (Comp);
6709               end loop;
6710            end;
6711         end if;
6712      end if;
6713
6714      --  When a type is frozen, the first subtype of the type is frozen as
6715      --  well (RM 13.14(15)). This has to be done after freezing the type,
6716      --  since obviously the first subtype depends on its own base type.
6717
6718      if Is_Type (E) then
6719         Freeze_And_Append (First_Subtype (E), N, Result);
6720
6721         --  If we just froze a tagged non-class wide record, then freeze the
6722         --  corresponding class-wide type. This must be done after the tagged
6723         --  type itself is frozen, because the class-wide type refers to the
6724         --  tagged type which generates the class.
6725
6726         if Is_Tagged_Type (E)
6727           and then not Is_Class_Wide_Type (E)
6728           and then Present (Class_Wide_Type (E))
6729         then
6730            Freeze_And_Append (Class_Wide_Type (E), N, Result);
6731         end if;
6732      end if;
6733
6734      Check_Debug_Info_Needed (E);
6735
6736      --  Special handling for subprograms
6737
6738      if Is_Subprogram (E) then
6739
6740         --  If subprogram has address clause then reset Is_Public flag, since
6741         --  we do not want the backend to generate external references.
6742
6743         if Present (Address_Clause (E))
6744           and then not Is_Library_Level_Entity (E)
6745         then
6746            Set_Is_Public (E, False);
6747         end if;
6748      end if;
6749
6750   <<Leave>>
6751      Restore_Ghost_Mode (Saved_GM);
6752
6753      return Result;
6754   end Freeze_Entity;
6755
6756   -----------------------------
6757   -- Freeze_Enumeration_Type --
6758   -----------------------------
6759
6760   procedure Freeze_Enumeration_Type (Typ : Entity_Id) is
6761   begin
6762      --  By default, if no size clause is present, an enumeration type with
6763      --  Convention C is assumed to interface to a C enum, and has integer
6764      --  size. This applies to types. For subtypes, verify that its base
6765      --  type has no size clause either. Treat other foreign conventions
6766      --  in the same way, and also make sure alignment is set right.
6767
6768      if Has_Foreign_Convention (Typ)
6769        and then not Has_Size_Clause (Typ)
6770        and then not Has_Size_Clause (Base_Type (Typ))
6771        and then Esize (Typ) < Standard_Integer_Size
6772
6773        --  Don't do this if Short_Enums on target
6774
6775        and then not Target_Short_Enums
6776      then
6777         Init_Esize (Typ, Standard_Integer_Size);
6778         Set_Alignment (Typ, Alignment (Standard_Integer));
6779
6780      --  Normal Ada case or size clause present or not Long_C_Enums on target
6781
6782      else
6783         --  If the enumeration type interfaces to C, and it has a size clause
6784         --  that specifies less than int size, it warrants a warning. The
6785         --  user may intend the C type to be an enum or a char, so this is
6786         --  not by itself an error that the Ada compiler can detect, but it
6787         --  it is a worth a heads-up. For Boolean and Character types we
6788         --  assume that the programmer has the proper C type in mind.
6789
6790         if Convention (Typ) = Convention_C
6791           and then Has_Size_Clause (Typ)
6792           and then Esize (Typ) /= Esize (Standard_Integer)
6793           and then not Is_Boolean_Type (Typ)
6794           and then not Is_Character_Type (Typ)
6795
6796           --  Don't do this if Short_Enums on target
6797
6798           and then not Target_Short_Enums
6799         then
6800            Error_Msg_N
6801              ("C enum types have the size of a C int??", Size_Clause (Typ));
6802         end if;
6803
6804         Adjust_Esize_For_Alignment (Typ);
6805      end if;
6806   end Freeze_Enumeration_Type;
6807
6808   -----------------------
6809   -- Freeze_Expression --
6810   -----------------------
6811
6812   procedure Freeze_Expression (N : Node_Id) is
6813      In_Spec_Exp : constant Boolean := In_Spec_Expression;
6814      Typ         : Entity_Id;
6815      Nam         : Entity_Id;
6816      Desig_Typ   : Entity_Id;
6817      P           : Node_Id;
6818      Parent_P    : Node_Id;
6819
6820      Freeze_Outside : Boolean := False;
6821      --  This flag is set true if the entity must be frozen outside the
6822      --  current subprogram. This happens in the case of expander generated
6823      --  subprograms (_Init_Proc, _Input, _Output, _Read, _Write) which do
6824      --  not freeze all entities like other bodies, but which nevertheless
6825      --  may reference entities that have to be frozen before the body and
6826      --  obviously cannot be frozen inside the body.
6827
6828      function Find_Aggregate_Component_Desig_Type return Entity_Id;
6829      --  If the expression is an array aggregate, the type of the component
6830      --  expressions is also frozen. If the component type is an access type
6831      --  and the expressions include allocators, the designed type is frozen
6832      --  as well.
6833
6834      function In_Expanded_Body (N : Node_Id) return Boolean;
6835      --  Given an N_Handled_Sequence_Of_Statements node N, determines whether
6836      --  it is the handled statement sequence of an expander-generated
6837      --  subprogram (init proc, stream subprogram, or renaming as body).
6838      --  If so, this is not a freezing context.
6839
6840      -----------------------------------------
6841      -- Find_Aggregate_Component_Desig_Type --
6842      -----------------------------------------
6843
6844      function Find_Aggregate_Component_Desig_Type return Entity_Id is
6845         Assoc : Node_Id;
6846         Exp   : Node_Id;
6847
6848      begin
6849         if Present (Expressions (N)) then
6850            Exp := First (Expressions (N));
6851            while Present (Exp) loop
6852               if Nkind (Exp) = N_Allocator then
6853                  return Designated_Type (Component_Type (Etype (N)));
6854               end if;
6855
6856               Next (Exp);
6857            end loop;
6858         end if;
6859
6860         if Present (Component_Associations (N)) then
6861            Assoc := First  (Component_Associations (N));
6862            while Present (Assoc) loop
6863               if Nkind (Expression (Assoc)) = N_Allocator then
6864                  return Designated_Type (Component_Type (Etype (N)));
6865               end if;
6866
6867               Next (Assoc);
6868            end loop;
6869         end if;
6870
6871         return Empty;
6872      end Find_Aggregate_Component_Desig_Type;
6873
6874      ----------------------
6875      -- In_Expanded_Body --
6876      ----------------------
6877
6878      function In_Expanded_Body (N : Node_Id) return Boolean is
6879         P  : Node_Id;
6880         Id : Entity_Id;
6881
6882      begin
6883         if Nkind (N) = N_Subprogram_Body then
6884            P := N;
6885         else
6886            P := Parent (N);
6887         end if;
6888
6889         if Nkind (P) /= N_Subprogram_Body then
6890            return False;
6891
6892         else
6893            Id := Defining_Unit_Name (Specification (P));
6894
6895            --  The following are expander-created bodies, or bodies that
6896            --  are not freeze points.
6897
6898            if Nkind (Id) = N_Defining_Identifier
6899              and then (Is_Init_Proc (Id)
6900                         or else Is_TSS (Id, TSS_Stream_Input)
6901                         or else Is_TSS (Id, TSS_Stream_Output)
6902                         or else Is_TSS (Id, TSS_Stream_Read)
6903                         or else Is_TSS (Id, TSS_Stream_Write)
6904                         or else Nkind_In (Original_Node (P),
6905                                           N_Subprogram_Renaming_Declaration,
6906                                           N_Expression_Function))
6907            then
6908               return True;
6909            else
6910               return False;
6911            end if;
6912         end if;
6913      end In_Expanded_Body;
6914
6915   --  Start of processing for Freeze_Expression
6916
6917   begin
6918      --  Immediate return if freezing is inhibited. This flag is set by the
6919      --  analyzer to stop freezing on generated expressions that would cause
6920      --  freezing if they were in the source program, but which are not
6921      --  supposed to freeze, since they are created.
6922
6923      if Must_Not_Freeze (N) then
6924         return;
6925      end if;
6926
6927      --  If expression is non-static, then it does not freeze in a default
6928      --  expression, see section "Handling of Default Expressions" in the
6929      --  spec of package Sem for further details. Note that we have to make
6930      --  sure that we actually have a real expression (if we have a subtype
6931      --  indication, we can't test Is_OK_Static_Expression). However, we
6932      --  exclude the case of the prefix of an attribute of a static scalar
6933      --  subtype from this early return, because static subtype attributes
6934      --  should always cause freezing, even in default expressions, but
6935      --  the attribute may not have been marked as static yet (because in
6936      --  Resolve_Attribute, the call to Eval_Attribute follows the call of
6937      --  Freeze_Expression on the prefix).
6938
6939      if In_Spec_Exp
6940        and then Nkind (N) in N_Subexpr
6941        and then not Is_OK_Static_Expression (N)
6942        and then (Nkind (Parent (N)) /= N_Attribute_Reference
6943                   or else not (Is_Entity_Name (N)
6944                                 and then Is_Type (Entity (N))
6945                                 and then Is_OK_Static_Subtype (Entity (N))))
6946      then
6947         return;
6948      end if;
6949
6950      --  Freeze type of expression if not frozen already
6951
6952      Typ := Empty;
6953
6954      if Nkind (N) in N_Has_Etype then
6955         if not Is_Frozen (Etype (N)) then
6956            Typ := Etype (N);
6957
6958         --  Base type may be an derived numeric type that is frozen at
6959         --  the point of declaration, but first_subtype is still unfrozen.
6960
6961         elsif not Is_Frozen (First_Subtype (Etype (N))) then
6962            Typ := First_Subtype (Etype (N));
6963         end if;
6964      end if;
6965
6966      --  For entity name, freeze entity if not frozen already. A special
6967      --  exception occurs for an identifier that did not come from source.
6968      --  We don't let such identifiers freeze a non-internal entity, i.e.
6969      --  an entity that did come from source, since such an identifier was
6970      --  generated by the expander, and cannot have any semantic effect on
6971      --  the freezing semantics. For example, this stops the parameter of
6972      --  an initialization procedure from freezing the variable.
6973
6974      if Is_Entity_Name (N)
6975        and then not Is_Frozen (Entity (N))
6976        and then (Nkind (N) /= N_Identifier
6977                   or else Comes_From_Source (N)
6978                   or else not Comes_From_Source (Entity (N)))
6979      then
6980         Nam := Entity (N);
6981
6982         if Present (Nam) and then Ekind (Nam) = E_Function then
6983            Check_Expression_Function (N, Nam);
6984         end if;
6985
6986      else
6987         Nam := Empty;
6988      end if;
6989
6990      --  For an allocator freeze designated type if not frozen already
6991
6992      --  For an aggregate whose component type is an access type, freeze the
6993      --  designated type now, so that its freeze does not appear within the
6994      --  loop that might be created in the expansion of the aggregate. If the
6995      --  designated type is a private type without full view, the expression
6996      --  cannot contain an allocator, so the type is not frozen.
6997
6998      --  For a function, we freeze the entity when the subprogram declaration
6999      --  is frozen, but a function call may appear in an initialization proc.
7000      --  before the declaration is frozen. We need to generate the extra
7001      --  formals, if any, to ensure that the expansion of the call includes
7002      --  the proper actuals. This only applies to Ada subprograms, not to
7003      --  imported ones.
7004
7005      Desig_Typ := Empty;
7006
7007      case Nkind (N) is
7008         when N_Allocator =>
7009            Desig_Typ := Designated_Type (Etype (N));
7010
7011         when N_Aggregate =>
7012            if Is_Array_Type (Etype (N))
7013              and then Is_Access_Type (Component_Type (Etype (N)))
7014            then
7015
7016               --  Check whether aggregate includes allocators.
7017
7018               Desig_Typ := Find_Aggregate_Component_Desig_Type;
7019            end if;
7020
7021         when N_Indexed_Component
7022            | N_Selected_Component
7023            | N_Slice
7024         =>
7025            if Is_Access_Type (Etype (Prefix (N))) then
7026               Desig_Typ := Designated_Type (Etype (Prefix (N)));
7027            end if;
7028
7029         when N_Identifier =>
7030            if Present (Nam)
7031              and then Ekind (Nam) = E_Function
7032              and then Nkind (Parent (N)) = N_Function_Call
7033              and then Convention (Nam) = Convention_Ada
7034            then
7035               Create_Extra_Formals (Nam);
7036            end if;
7037
7038         when others =>
7039            null;
7040      end case;
7041
7042      if Desig_Typ /= Empty
7043        and then (Is_Frozen (Desig_Typ)
7044                   or else (not Is_Fully_Defined (Desig_Typ)))
7045      then
7046         Desig_Typ := Empty;
7047      end if;
7048
7049      --  All done if nothing needs freezing
7050
7051      if No (Typ)
7052        and then No (Nam)
7053        and then No (Desig_Typ)
7054      then
7055         return;
7056      end if;
7057
7058      --  Examine the enclosing context by climbing the parent chain. The
7059      --  traversal serves two purposes - to detect scenarios where freezeing
7060      --  is not needed and to find the proper insertion point for the freeze
7061      --  nodes. Although somewhat similar to Insert_Actions, this traversal
7062      --  is freezing semantics-sensitive. Inserting freeze nodes blindly in
7063      --  the tree may result in types being frozen too early.
7064
7065      P := N;
7066      loop
7067         Parent_P := Parent (P);
7068
7069         --  If we don't have a parent, then we are not in a well-formed tree.
7070         --  This is an unusual case, but there are some legitimate situations
7071         --  in which this occurs, notably when the expressions in the range of
7072         --  a type declaration are resolved. We simply ignore the freeze
7073         --  request in this case. Is this right ???
7074
7075         if No (Parent_P) then
7076            return;
7077         end if;
7078
7079         --  See if we have got to an appropriate point in the tree
7080
7081         case Nkind (Parent_P) is
7082
7083            --  A special test for the exception of (RM 13.14(8)) for the case
7084            --  of per-object expressions (RM 3.8(18)) occurring in component
7085            --  definition or a discrete subtype definition. Note that we test
7086            --  for a component declaration which includes both cases we are
7087            --  interested in, and furthermore the tree does not have explicit
7088            --  nodes for either of these two constructs.
7089
7090            when N_Component_Declaration =>
7091
7092               --  The case we want to test for here is an identifier that is
7093               --  a per-object expression, this is either a discriminant that
7094               --  appears in a context other than the component declaration
7095               --  or it is a reference to the type of the enclosing construct.
7096
7097               --  For either of these cases, we skip the freezing
7098
7099               if not In_Spec_Expression
7100                 and then Nkind (N) = N_Identifier
7101                 and then (Present (Entity (N)))
7102               then
7103                  --  We recognize the discriminant case by just looking for
7104                  --  a reference to a discriminant. It can only be one for
7105                  --  the enclosing construct. Skip freezing in this case.
7106
7107                  if Ekind (Entity (N)) = E_Discriminant then
7108                     return;
7109
7110                  --  For the case of a reference to the enclosing record,
7111                  --  (or task or protected type), we look for a type that
7112                  --  matches the current scope.
7113
7114                  elsif Entity (N) = Current_Scope then
7115                     return;
7116                  end if;
7117               end if;
7118
7119            --  If we have an enumeration literal that appears as the choice in
7120            --  the aggregate of an enumeration representation clause, then
7121            --  freezing does not occur (RM 13.14(10)).
7122
7123            when N_Enumeration_Representation_Clause =>
7124
7125               --  The case we are looking for is an enumeration literal
7126
7127               if (Nkind (N) = N_Identifier or Nkind (N) = N_Character_Literal)
7128                 and then Is_Enumeration_Type (Etype (N))
7129               then
7130                  --  If enumeration literal appears directly as the choice,
7131                  --  do not freeze (this is the normal non-overloaded case)
7132
7133                  if Nkind (Parent (N)) = N_Component_Association
7134                    and then First (Choices (Parent (N))) = N
7135                  then
7136                     return;
7137
7138                  --  If enumeration literal appears as the name of function
7139                  --  which is the choice, then also do not freeze. This
7140                  --  happens in the overloaded literal case, where the
7141                  --  enumeration literal is temporarily changed to a function
7142                  --  call for overloading analysis purposes.
7143
7144                  elsif Nkind (Parent (N)) = N_Function_Call
7145                     and then
7146                       Nkind (Parent (Parent (N))) = N_Component_Association
7147                     and then
7148                       First (Choices (Parent (Parent (N)))) = Parent (N)
7149                  then
7150                     return;
7151                  end if;
7152               end if;
7153
7154            --  Normally if the parent is a handled sequence of statements,
7155            --  then the current node must be a statement, and that is an
7156            --  appropriate place to insert a freeze node.
7157
7158            when N_Handled_Sequence_Of_Statements =>
7159
7160               --  An exception occurs when the sequence of statements is for
7161               --  an expander generated body that did not do the usual freeze
7162               --  all operation. In this case we usually want to freeze
7163               --  outside this body, not inside it, and we skip past the
7164               --  subprogram body that we are inside.
7165
7166               if In_Expanded_Body (Parent_P) then
7167                  declare
7168                     Subp : constant Node_Id := Parent (Parent_P);
7169                     Spec : Entity_Id;
7170
7171                  begin
7172                     --  Freeze the entity only when it is declared inside the
7173                     --  body of the expander generated procedure. This case
7174                     --  is recognized by the scope of the entity or its type,
7175                     --  which is either the spec for some enclosing body, or
7176                     --  (in the case of init_procs, for which there are no
7177                     --  separate specs) the current scope.
7178
7179                     if Nkind (Subp) = N_Subprogram_Body then
7180                        Spec := Corresponding_Spec (Subp);
7181
7182                        if (Present (Typ) and then Scope (Typ) = Spec)
7183                             or else
7184                           (Present (Nam) and then Scope (Nam) = Spec)
7185                        then
7186                           exit;
7187
7188                        elsif Present (Typ)
7189                          and then Scope (Typ) = Current_Scope
7190                          and then Defining_Entity (Subp) = Current_Scope
7191                        then
7192                           exit;
7193                        end if;
7194                     end if;
7195
7196                     --  An expression function may act as a completion of
7197                     --  a function declaration. As such, it can reference
7198                     --  entities declared between the two views:
7199
7200                     --     Hidden [];                             -- 1
7201                     --     function F return ...;
7202                     --     private
7203                     --        function Hidden return ...;
7204                     --        function F return ... is (Hidden);  -- 2
7205
7206                     --  Refering to the example above, freezing the expression
7207                     --  of F (2) would place Hidden's freeze node (1) in the
7208                     --  wrong place. Avoid explicit freezing and let the usual
7209                     --  scenarios do the job - for example, reaching the end
7210                     --  of the private declarations, or a call to F.
7211
7212                     if Nkind (Original_Node (Subp)) =
7213                                                N_Expression_Function
7214                     then
7215                        null;
7216
7217                     --  Freeze outside the body
7218
7219                     else
7220                        Parent_P := Parent (Parent_P);
7221                        Freeze_Outside := True;
7222                     end if;
7223                  end;
7224
7225               --  Here if normal case where we are in handled statement
7226               --  sequence and want to do the insertion right there.
7227
7228               else
7229                  exit;
7230               end if;
7231
7232            --  If parent is a body or a spec or a block, then the current node
7233            --  is a statement or declaration and we can insert the freeze node
7234            --  before it.
7235
7236            when N_Block_Statement
7237               | N_Entry_Body
7238               | N_Package_Body
7239               | N_Package_Specification
7240               | N_Protected_Body
7241               | N_Subprogram_Body
7242               | N_Task_Body
7243            =>
7244               exit;
7245
7246            --  The expander is allowed to define types in any statements list,
7247            --  so any of the following parent nodes also mark a freezing point
7248            --  if the actual node is in a list of statements or declarations.
7249
7250            when N_Abortable_Part
7251               | N_Accept_Alternative
7252               | N_And_Then
7253               | N_Case_Statement_Alternative
7254               | N_Compilation_Unit_Aux
7255               | N_Conditional_Entry_Call
7256               | N_Delay_Alternative
7257               | N_Elsif_Part
7258               | N_Entry_Call_Alternative
7259               | N_Exception_Handler
7260               | N_Extended_Return_Statement
7261               | N_Freeze_Entity
7262               | N_If_Statement
7263               | N_Or_Else
7264               | N_Selective_Accept
7265               | N_Triggering_Alternative
7266            =>
7267               exit when Is_List_Member (P);
7268
7269            --  Freeze nodes produced by an expression coming from the Actions
7270            --  list of a N_Expression_With_Actions node must remain within the
7271            --  Actions list. Inserting the freeze nodes further up the tree
7272            --  may lead to use before declaration issues in the case of array
7273            --  types.
7274
7275            when N_Expression_With_Actions =>
7276               if Is_List_Member (P)
7277                 and then List_Containing (P) = Actions (Parent_P)
7278               then
7279                  exit;
7280               end if;
7281
7282            --  Note: N_Loop_Statement is a special case. A type that appears
7283            --  in the source can never be frozen in a loop (this occurs only
7284            --  because of a loop expanded by the expander), so we keep on
7285            --  going. Otherwise we terminate the search. Same is true of any
7286            --  entity which comes from source. (if they have predefined type,
7287            --  that type does not appear to come from source, but the entity
7288            --  should not be frozen here).
7289
7290            when N_Loop_Statement =>
7291               exit when not Comes_From_Source (Etype (N))
7292                 and then (No (Nam) or else not Comes_From_Source (Nam));
7293
7294            --  For all other cases, keep looking at parents
7295
7296            when others =>
7297               null;
7298         end case;
7299
7300         --  We fall through the case if we did not yet find the proper
7301         --  place in the free for inserting the freeze node, so climb.
7302
7303         P := Parent_P;
7304      end loop;
7305
7306      --  If the expression appears in a record or an initialization procedure,
7307      --  the freeze nodes are collected and attached to the current scope, to
7308      --  be inserted and analyzed on exit from the scope, to insure that
7309      --  generated entities appear in the correct scope. If the expression is
7310      --  a default for a discriminant specification, the scope is still void.
7311      --  The expression can also appear in the discriminant part of a private
7312      --  or concurrent type.
7313
7314      --  If the expression appears in a constrained subcomponent of an
7315      --  enclosing record declaration, the freeze nodes must be attached to
7316      --  the outer record type so they can eventually be placed in the
7317      --  enclosing declaration list.
7318
7319      --  The other case requiring this special handling is if we are in a
7320      --  default expression, since in that case we are about to freeze a
7321      --  static type, and the freeze scope needs to be the outer scope, not
7322      --  the scope of the subprogram with the default parameter.
7323
7324      --  For default expressions and other spec expressions in generic units,
7325      --  the Move_Freeze_Nodes mechanism (see sem_ch12.adb) takes care of
7326      --  placing them at the proper place, after the generic unit.
7327
7328      if (In_Spec_Exp and not Inside_A_Generic)
7329        or else Freeze_Outside
7330        or else (Is_Type (Current_Scope)
7331                  and then (not Is_Concurrent_Type (Current_Scope)
7332                             or else not Has_Completion (Current_Scope)))
7333        or else Ekind (Current_Scope) = E_Void
7334      then
7335         declare
7336            N            : constant Node_Id := Current_Scope;
7337            Freeze_Nodes : List_Id          := No_List;
7338            Pos          : Int              := Scope_Stack.Last;
7339
7340         begin
7341            if Present (Desig_Typ) then
7342               Freeze_And_Append (Desig_Typ, N, Freeze_Nodes);
7343            end if;
7344
7345            if Present (Typ) then
7346               Freeze_And_Append (Typ, N, Freeze_Nodes);
7347            end if;
7348
7349            if Present (Nam) then
7350               Freeze_And_Append (Nam, N, Freeze_Nodes);
7351            end if;
7352
7353            --  The current scope may be that of a constrained component of
7354            --  an enclosing record declaration, or of a loop of an enclosing
7355            --  quantified expression, which is above the current scope in the
7356            --  scope stack. Indeed in the context of a quantified expression,
7357            --  a scope is created and pushed above the current scope in order
7358            --  to emulate the loop-like behavior of the quantified expression.
7359            --  If the expression is within a top-level pragma, as for a pre-
7360            --  condition on a library-level subprogram, nothing to do.
7361
7362            if not Is_Compilation_Unit (Current_Scope)
7363              and then (Is_Record_Type (Scope (Current_Scope))
7364                         or else Nkind (Parent (Current_Scope)) =
7365                                                     N_Quantified_Expression)
7366            then
7367               Pos := Pos - 1;
7368            end if;
7369
7370            if Is_Non_Empty_List (Freeze_Nodes) then
7371               if No (Scope_Stack.Table (Pos).Pending_Freeze_Actions) then
7372                  Scope_Stack.Table (Pos).Pending_Freeze_Actions :=
7373                    Freeze_Nodes;
7374               else
7375                  Append_List (Freeze_Nodes,
7376                    Scope_Stack.Table (Pos).Pending_Freeze_Actions);
7377               end if;
7378            end if;
7379         end;
7380
7381         return;
7382      end if;
7383
7384      --  Now we have the right place to do the freezing. First, a special
7385      --  adjustment, if we are in spec-expression analysis mode, these freeze
7386      --  actions must not be thrown away (normally all inserted actions are
7387      --  thrown away in this mode. However, the freeze actions are from static
7388      --  expressions and one of the important reasons we are doing this
7389      --  special analysis is to get these freeze actions. Therefore we turn
7390      --  off the In_Spec_Expression mode to propagate these freeze actions.
7391      --  This also means they get properly analyzed and expanded.
7392
7393      In_Spec_Expression := False;
7394
7395      --  Freeze the designated type of an allocator (RM 13.14(13))
7396
7397      if Present (Desig_Typ) then
7398         Freeze_Before (P, Desig_Typ);
7399      end if;
7400
7401      --  Freeze type of expression (RM 13.14(10)). Note that we took care of
7402      --  the enumeration representation clause exception in the loop above.
7403
7404      if Present (Typ) then
7405         Freeze_Before (P, Typ);
7406      end if;
7407
7408      --  Freeze name if one is present (RM 13.14(11))
7409
7410      if Present (Nam) then
7411         Freeze_Before (P, Nam);
7412      end if;
7413
7414      --  Restore In_Spec_Expression flag
7415
7416      In_Spec_Expression := In_Spec_Exp;
7417   end Freeze_Expression;
7418
7419   -----------------------------
7420   -- Freeze_Fixed_Point_Type --
7421   -----------------------------
7422
7423   --  Certain fixed-point types and subtypes, including implicit base types
7424   --  and declared first subtypes, have not yet set up a range. This is
7425   --  because the range cannot be set until the Small and Size values are
7426   --  known, and these are not known till the type is frozen.
7427
7428   --  To signal this case, Scalar_Range contains an unanalyzed syntactic range
7429   --  whose bounds are unanalyzed real literals. This routine will recognize
7430   --  this case, and transform this range node into a properly typed range
7431   --  with properly analyzed and resolved values.
7432
7433   procedure Freeze_Fixed_Point_Type (Typ : Entity_Id) is
7434      Rng   : constant Node_Id    := Scalar_Range (Typ);
7435      Lo    : constant Node_Id    := Low_Bound (Rng);
7436      Hi    : constant Node_Id    := High_Bound (Rng);
7437      Btyp  : constant Entity_Id  := Base_Type (Typ);
7438      Brng  : constant Node_Id    := Scalar_Range (Btyp);
7439      BLo   : constant Node_Id    := Low_Bound (Brng);
7440      BHi   : constant Node_Id    := High_Bound (Brng);
7441      Small : constant Ureal      := Small_Value (Typ);
7442      Loval : Ureal;
7443      Hival : Ureal;
7444      Atype : Entity_Id;
7445
7446      Orig_Lo : Ureal;
7447      Orig_Hi : Ureal;
7448      --  Save original bounds (for shaving tests)
7449
7450      Actual_Size : Nat;
7451      --  Actual size chosen
7452
7453      function Fsize (Lov, Hiv : Ureal) return Nat;
7454      --  Returns size of type with given bounds. Also leaves these
7455      --  bounds set as the current bounds of the Typ.
7456
7457      -----------
7458      -- Fsize --
7459      -----------
7460
7461      function Fsize (Lov, Hiv : Ureal) return Nat is
7462      begin
7463         Set_Realval (Lo, Lov);
7464         Set_Realval (Hi, Hiv);
7465         return Minimum_Size (Typ);
7466      end Fsize;
7467
7468   --  Start of processing for Freeze_Fixed_Point_Type
7469
7470   begin
7471      --  If Esize of a subtype has not previously been set, set it now
7472
7473      if Unknown_Esize (Typ) then
7474         Atype := Ancestor_Subtype (Typ);
7475
7476         if Present (Atype) then
7477            Set_Esize (Typ, Esize (Atype));
7478         else
7479            Set_Esize (Typ, Esize (Base_Type (Typ)));
7480         end if;
7481      end if;
7482
7483      --  Immediate return if the range is already analyzed. This means that
7484      --  the range is already set, and does not need to be computed by this
7485      --  routine.
7486
7487      if Analyzed (Rng) then
7488         return;
7489      end if;
7490
7491      --  Immediate return if either of the bounds raises Constraint_Error
7492
7493      if Raises_Constraint_Error (Lo)
7494        or else Raises_Constraint_Error (Hi)
7495      then
7496         return;
7497      end if;
7498
7499      Loval := Realval (Lo);
7500      Hival := Realval (Hi);
7501
7502      Orig_Lo := Loval;
7503      Orig_Hi := Hival;
7504
7505      --  Ordinary fixed-point case
7506
7507      if Is_Ordinary_Fixed_Point_Type (Typ) then
7508
7509         --  For the ordinary fixed-point case, we are allowed to fudge the
7510         --  end-points up or down by small. Generally we prefer to fudge up,
7511         --  i.e. widen the bounds for non-model numbers so that the end points
7512         --  are included. However there are cases in which this cannot be
7513         --  done, and indeed cases in which we may need to narrow the bounds.
7514         --  The following circuit makes the decision.
7515
7516         --  Note: our terminology here is that Incl_EP means that the bounds
7517         --  are widened by Small if necessary to include the end points, and
7518         --  Excl_EP means that the bounds are narrowed by Small to exclude the
7519         --  end-points if this reduces the size.
7520
7521         --  Note that in the Incl case, all we care about is including the
7522         --  end-points. In the Excl case, we want to narrow the bounds as
7523         --  much as permitted by the RM, to give the smallest possible size.
7524
7525         Fudge : declare
7526            Loval_Incl_EP : Ureal;
7527            Hival_Incl_EP : Ureal;
7528
7529            Loval_Excl_EP : Ureal;
7530            Hival_Excl_EP : Ureal;
7531
7532            Size_Incl_EP  : Nat;
7533            Size_Excl_EP  : Nat;
7534
7535            Model_Num     : Ureal;
7536            First_Subt    : Entity_Id;
7537            Actual_Lo     : Ureal;
7538            Actual_Hi     : Ureal;
7539
7540         begin
7541            --  First step. Base types are required to be symmetrical. Right
7542            --  now, the base type range is a copy of the first subtype range.
7543            --  This will be corrected before we are done, but right away we
7544            --  need to deal with the case where both bounds are non-negative.
7545            --  In this case, we set the low bound to the negative of the high
7546            --  bound, to make sure that the size is computed to include the
7547            --  required sign. Note that we do not need to worry about the
7548            --  case of both bounds negative, because the sign will be dealt
7549            --  with anyway. Furthermore we can't just go making such a bound
7550            --  symmetrical, since in a twos-complement system, there is an
7551            --  extra negative value which could not be accommodated on the
7552            --  positive side.
7553
7554            if Typ = Btyp
7555              and then not UR_Is_Negative (Loval)
7556              and then Hival > Loval
7557            then
7558               Loval := -Hival;
7559               Set_Realval (Lo, Loval);
7560            end if;
7561
7562            --  Compute the fudged bounds. If the number is a model number,
7563            --  then we do nothing to include it, but we are allowed to backoff
7564            --  to the next adjacent model number when we exclude it. If it is
7565            --  not a model number then we straddle the two values with the
7566            --  model numbers on either side.
7567
7568            Model_Num := UR_Trunc (Loval / Small) * Small;
7569
7570            if Loval = Model_Num then
7571               Loval_Incl_EP := Model_Num;
7572            else
7573               Loval_Incl_EP := Model_Num - Small;
7574            end if;
7575
7576            --  The low value excluding the end point is Small greater, but
7577            --  we do not do this exclusion if the low value is positive,
7578            --  since it can't help the size and could actually hurt by
7579            --  crossing the high bound.
7580
7581            if UR_Is_Negative (Loval_Incl_EP) then
7582               Loval_Excl_EP := Loval_Incl_EP + Small;
7583
7584               --  If the value went from negative to zero, then we have the
7585               --  case where Loval_Incl_EP is the model number just below
7586               --  zero, so we want to stick to the negative value for the
7587               --  base type to maintain the condition that the size will
7588               --  include signed values.
7589
7590               if Typ = Btyp
7591                 and then UR_Is_Zero (Loval_Excl_EP)
7592               then
7593                  Loval_Excl_EP := Loval_Incl_EP;
7594               end if;
7595
7596            else
7597               Loval_Excl_EP := Loval_Incl_EP;
7598            end if;
7599
7600            --  Similar processing for upper bound and high value
7601
7602            Model_Num := UR_Trunc (Hival / Small) * Small;
7603
7604            if Hival = Model_Num then
7605               Hival_Incl_EP := Model_Num;
7606            else
7607               Hival_Incl_EP := Model_Num + Small;
7608            end if;
7609
7610            if UR_Is_Positive (Hival_Incl_EP) then
7611               Hival_Excl_EP := Hival_Incl_EP - Small;
7612            else
7613               Hival_Excl_EP := Hival_Incl_EP;
7614            end if;
7615
7616            --  One further adjustment is needed. In the case of subtypes, we
7617            --  cannot go outside the range of the base type, or we get
7618            --  peculiarities, and the base type range is already set. This
7619            --  only applies to the Incl values, since clearly the Excl values
7620            --  are already as restricted as they are allowed to be.
7621
7622            if Typ /= Btyp then
7623               Loval_Incl_EP := UR_Max (Loval_Incl_EP, Realval (BLo));
7624               Hival_Incl_EP := UR_Min (Hival_Incl_EP, Realval (BHi));
7625            end if;
7626
7627            --  Get size including and excluding end points
7628
7629            Size_Incl_EP := Fsize (Loval_Incl_EP, Hival_Incl_EP);
7630            Size_Excl_EP := Fsize (Loval_Excl_EP, Hival_Excl_EP);
7631
7632            --  No need to exclude end-points if it does not reduce size
7633
7634            if Fsize (Loval_Incl_EP, Hival_Excl_EP) = Size_Excl_EP then
7635               Loval_Excl_EP := Loval_Incl_EP;
7636            end if;
7637
7638            if Fsize (Loval_Excl_EP, Hival_Incl_EP) = Size_Excl_EP then
7639               Hival_Excl_EP := Hival_Incl_EP;
7640            end if;
7641
7642            --  Now we set the actual size to be used. We want to use the
7643            --  bounds fudged up to include the end-points but only if this
7644            --  can be done without violating a specifically given size
7645            --  size clause or causing an unacceptable increase in size.
7646
7647            --  Case of size clause given
7648
7649            if Has_Size_Clause (Typ) then
7650
7651               --  Use the inclusive size only if it is consistent with
7652               --  the explicitly specified size.
7653
7654               if Size_Incl_EP <= RM_Size (Typ) then
7655                  Actual_Lo   := Loval_Incl_EP;
7656                  Actual_Hi   := Hival_Incl_EP;
7657                  Actual_Size := Size_Incl_EP;
7658
7659               --  If the inclusive size is too large, we try excluding
7660               --  the end-points (will be caught later if does not work).
7661
7662               else
7663                  Actual_Lo   := Loval_Excl_EP;
7664                  Actual_Hi   := Hival_Excl_EP;
7665                  Actual_Size := Size_Excl_EP;
7666               end if;
7667
7668            --  Case of size clause not given
7669
7670            else
7671               --  If we have a base type whose corresponding first subtype
7672               --  has an explicit size that is large enough to include our
7673               --  end-points, then do so. There is no point in working hard
7674               --  to get a base type whose size is smaller than the specified
7675               --  size of the first subtype.
7676
7677               First_Subt := First_Subtype (Typ);
7678
7679               if Has_Size_Clause (First_Subt)
7680                 and then Size_Incl_EP <= Esize (First_Subt)
7681               then
7682                  Actual_Size := Size_Incl_EP;
7683                  Actual_Lo   := Loval_Incl_EP;
7684                  Actual_Hi   := Hival_Incl_EP;
7685
7686               --  If excluding the end-points makes the size smaller and
7687               --  results in a size of 8,16,32,64, then we take the smaller
7688               --  size. For the 64 case, this is compulsory. For the other
7689               --  cases, it seems reasonable. We like to include end points
7690               --  if we can, but not at the expense of moving to the next
7691               --  natural boundary of size.
7692
7693               elsif Size_Incl_EP /= Size_Excl_EP
7694                 and then Addressable (Size_Excl_EP)
7695               then
7696                  Actual_Size := Size_Excl_EP;
7697                  Actual_Lo   := Loval_Excl_EP;
7698                  Actual_Hi   := Hival_Excl_EP;
7699
7700               --  Otherwise we can definitely include the end points
7701
7702               else
7703                  Actual_Size := Size_Incl_EP;
7704                  Actual_Lo   := Loval_Incl_EP;
7705                  Actual_Hi   := Hival_Incl_EP;
7706               end if;
7707
7708               --  One pathological case: normally we never fudge a low bound
7709               --  down, since it would seem to increase the size (if it has
7710               --  any effect), but for ranges containing single value, or no
7711               --  values, the high bound can be small too large. Consider:
7712
7713               --    type t is delta 2.0**(-14)
7714               --      range 131072.0 .. 0;
7715
7716               --  That lower bound is *just* outside the range of 32 bits, and
7717               --  does need fudging down in this case. Note that the bounds
7718               --  will always have crossed here, since the high bound will be
7719               --  fudged down if necessary, as in the case of:
7720
7721               --    type t is delta 2.0**(-14)
7722               --      range 131072.0 .. 131072.0;
7723
7724               --  So we detect the situation by looking for crossed bounds,
7725               --  and if the bounds are crossed, and the low bound is greater
7726               --  than zero, we will always back it off by small, since this
7727               --  is completely harmless.
7728
7729               if Actual_Lo > Actual_Hi then
7730                  if UR_Is_Positive (Actual_Lo) then
7731                     Actual_Lo   := Loval_Incl_EP - Small;
7732                     Actual_Size := Fsize (Actual_Lo, Actual_Hi);
7733
7734                  --  And of course, we need to do exactly the same parallel
7735                  --  fudge for flat ranges in the negative region.
7736
7737                  elsif UR_Is_Negative (Actual_Hi) then
7738                     Actual_Hi := Hival_Incl_EP + Small;
7739                     Actual_Size := Fsize (Actual_Lo, Actual_Hi);
7740                  end if;
7741               end if;
7742            end if;
7743
7744            Set_Realval (Lo, Actual_Lo);
7745            Set_Realval (Hi, Actual_Hi);
7746         end Fudge;
7747
7748      --  For the decimal case, none of this fudging is required, since there
7749      --  are no end-point problems in the decimal case (the end-points are
7750      --  always included).
7751
7752      else
7753         Actual_Size := Fsize (Loval, Hival);
7754      end if;
7755
7756      --  At this stage, the actual size has been calculated and the proper
7757      --  required bounds are stored in the low and high bounds.
7758
7759      if Actual_Size > 64 then
7760         Error_Msg_Uint_1 := UI_From_Int (Actual_Size);
7761         Error_Msg_N
7762           ("size required (^) for type& too large, maximum allowed is 64",
7763            Typ);
7764         Actual_Size := 64;
7765      end if;
7766
7767      --  Check size against explicit given size
7768
7769      if Has_Size_Clause (Typ) then
7770         if Actual_Size > RM_Size (Typ) then
7771            Error_Msg_Uint_1 := RM_Size (Typ);
7772            Error_Msg_Uint_2 := UI_From_Int (Actual_Size);
7773            Error_Msg_NE
7774              ("size given (^) for type& too small, minimum allowed is ^",
7775               Size_Clause (Typ), Typ);
7776
7777         else
7778            Actual_Size := UI_To_Int (Esize (Typ));
7779         end if;
7780
7781      --  Increase size to next natural boundary if no size clause given
7782
7783      else
7784         if Actual_Size <= 8 then
7785            Actual_Size := 8;
7786         elsif Actual_Size <= 16 then
7787            Actual_Size := 16;
7788         elsif Actual_Size <= 32 then
7789            Actual_Size := 32;
7790         else
7791            Actual_Size := 64;
7792         end if;
7793
7794         Init_Esize (Typ, Actual_Size);
7795         Adjust_Esize_For_Alignment (Typ);
7796      end if;
7797
7798      --  If we have a base type, then expand the bounds so that they extend to
7799      --  the full width of the allocated size in bits, to avoid junk range
7800      --  checks on intermediate computations.
7801
7802      if Base_Type (Typ) = Typ then
7803         Set_Realval (Lo, -(Small * (Uint_2 ** (Actual_Size - 1))));
7804         Set_Realval (Hi,  (Small * (Uint_2 ** (Actual_Size - 1) - 1)));
7805      end if;
7806
7807      --  Final step is to reanalyze the bounds using the proper type
7808      --  and set the Corresponding_Integer_Value fields of the literals.
7809
7810      Set_Etype (Lo, Empty);
7811      Set_Analyzed (Lo, False);
7812      Analyze (Lo);
7813
7814      --  Resolve with universal fixed if the base type, and the base type if
7815      --  it is a subtype. Note we can't resolve the base type with itself,
7816      --  that would be a reference before definition.
7817
7818      if Typ = Btyp then
7819         Resolve (Lo, Universal_Fixed);
7820      else
7821         Resolve (Lo, Btyp);
7822      end if;
7823
7824      --  Set corresponding integer value for bound
7825
7826      Set_Corresponding_Integer_Value
7827        (Lo, UR_To_Uint (Realval (Lo) / Small));
7828
7829      --  Similar processing for high bound
7830
7831      Set_Etype (Hi, Empty);
7832      Set_Analyzed (Hi, False);
7833      Analyze (Hi);
7834
7835      if Typ = Btyp then
7836         Resolve (Hi, Universal_Fixed);
7837      else
7838         Resolve (Hi, Btyp);
7839      end if;
7840
7841      Set_Corresponding_Integer_Value
7842        (Hi, UR_To_Uint (Realval (Hi) / Small));
7843
7844      --  Set type of range to correspond to bounds
7845
7846      Set_Etype (Rng, Etype (Lo));
7847
7848      --  Set Esize to calculated size if not set already
7849
7850      if Unknown_Esize (Typ) then
7851         Init_Esize (Typ, Actual_Size);
7852      end if;
7853
7854      --  Set RM_Size if not already set. If already set, check value
7855
7856      declare
7857         Minsiz : constant Uint := UI_From_Int (Minimum_Size (Typ));
7858
7859      begin
7860         if RM_Size (Typ) /= Uint_0 then
7861            if RM_Size (Typ) < Minsiz then
7862               Error_Msg_Uint_1 := RM_Size (Typ);
7863               Error_Msg_Uint_2 := Minsiz;
7864               Error_Msg_NE
7865                 ("size given (^) for type& too small, minimum allowed is ^",
7866                  Size_Clause (Typ), Typ);
7867            end if;
7868
7869         else
7870            Set_RM_Size (Typ, Minsiz);
7871         end if;
7872      end;
7873
7874      --  Check for shaving
7875
7876      if Comes_From_Source (Typ) then
7877
7878         --  In SPARK mode the given bounds must be strictly representable
7879
7880         if SPARK_Mode = On then
7881            if Orig_Lo < Expr_Value_R (Lo) then
7882               Error_Msg_NE
7883                 ("declared low bound of type & is outside type range",
7884                  Lo, Typ);
7885            end if;
7886
7887            if Orig_Hi > Expr_Value_R (Hi) then
7888               Error_Msg_NE
7889                 ("declared high bound of type & is outside type range",
7890                  Hi, Typ);
7891            end if;
7892
7893         else
7894            if Orig_Lo < Expr_Value_R (Lo) then
7895               Error_Msg_N
7896                 ("declared low bound of type & is outside type range??", Typ);
7897               Error_Msg_N
7898                 ("\low bound adjusted up by delta (RM 3.5.9(13))??", Typ);
7899            end if;
7900
7901            if Orig_Hi > Expr_Value_R (Hi) then
7902               Error_Msg_N
7903                 ("declared high bound of type & is outside type range??",
7904                  Typ);
7905               Error_Msg_N
7906                 ("\high bound adjusted down by delta (RM 3.5.9(13))??", Typ);
7907            end if;
7908         end if;
7909      end if;
7910   end Freeze_Fixed_Point_Type;
7911
7912   ------------------
7913   -- Freeze_Itype --
7914   ------------------
7915
7916   procedure Freeze_Itype (T : Entity_Id; N : Node_Id) is
7917      L : List_Id;
7918
7919   begin
7920      Set_Has_Delayed_Freeze (T);
7921      L := Freeze_Entity (T, N);
7922
7923      if Is_Non_Empty_List (L) then
7924         Insert_Actions (N, L);
7925      end if;
7926   end Freeze_Itype;
7927
7928   --------------------------
7929   -- Freeze_Static_Object --
7930   --------------------------
7931
7932   procedure Freeze_Static_Object (E : Entity_Id) is
7933
7934      Cannot_Be_Static : exception;
7935      --  Exception raised if the type of a static object cannot be made
7936      --  static. This happens if the type depends on non-global objects.
7937
7938      procedure Ensure_Expression_Is_SA (N : Node_Id);
7939      --  Called to ensure that an expression used as part of a type definition
7940      --  is statically allocatable, which means that the expression type is
7941      --  statically allocatable, and the expression is either static, or a
7942      --  reference to a library level constant.
7943
7944      procedure Ensure_Type_Is_SA (Typ : Entity_Id);
7945      --  Called to mark a type as static, checking that it is possible
7946      --  to set the type as static. If it is not possible, then the
7947      --  exception Cannot_Be_Static is raised.
7948
7949      -----------------------------
7950      -- Ensure_Expression_Is_SA --
7951      -----------------------------
7952
7953      procedure Ensure_Expression_Is_SA (N : Node_Id) is
7954         Ent : Entity_Id;
7955
7956      begin
7957         Ensure_Type_Is_SA (Etype (N));
7958
7959         if Is_OK_Static_Expression (N) then
7960            return;
7961
7962         elsif Nkind (N) = N_Identifier then
7963            Ent := Entity (N);
7964
7965            if Present (Ent)
7966              and then Ekind (Ent) = E_Constant
7967              and then Is_Library_Level_Entity (Ent)
7968            then
7969               return;
7970            end if;
7971         end if;
7972
7973         raise Cannot_Be_Static;
7974      end Ensure_Expression_Is_SA;
7975
7976      -----------------------
7977      -- Ensure_Type_Is_SA --
7978      -----------------------
7979
7980      procedure Ensure_Type_Is_SA (Typ : Entity_Id) is
7981         N : Node_Id;
7982         C : Entity_Id;
7983
7984      begin
7985         --  If type is library level, we are all set
7986
7987         if Is_Library_Level_Entity (Typ) then
7988            return;
7989         end if;
7990
7991         --  We are also OK if the type already marked as statically allocated,
7992         --  which means we processed it before.
7993
7994         if Is_Statically_Allocated (Typ) then
7995            return;
7996         end if;
7997
7998         --  Mark type as statically allocated
7999
8000         Set_Is_Statically_Allocated (Typ);
8001
8002         --  Check that it is safe to statically allocate this type
8003
8004         if Is_Scalar_Type (Typ) or else Is_Real_Type (Typ) then
8005            Ensure_Expression_Is_SA (Type_Low_Bound (Typ));
8006            Ensure_Expression_Is_SA (Type_High_Bound (Typ));
8007
8008         elsif Is_Array_Type (Typ) then
8009            N := First_Index (Typ);
8010            while Present (N) loop
8011               Ensure_Type_Is_SA (Etype (N));
8012               Next_Index (N);
8013            end loop;
8014
8015            Ensure_Type_Is_SA (Component_Type (Typ));
8016
8017         elsif Is_Access_Type (Typ) then
8018            if Ekind (Designated_Type (Typ)) = E_Subprogram_Type then
8019
8020               declare
8021                  F : Entity_Id;
8022                  T : constant Entity_Id := Etype (Designated_Type (Typ));
8023
8024               begin
8025                  if T /= Standard_Void_Type then
8026                     Ensure_Type_Is_SA (T);
8027                  end if;
8028
8029                  F := First_Formal (Designated_Type (Typ));
8030                  while Present (F) loop
8031                     Ensure_Type_Is_SA (Etype (F));
8032                     Next_Formal (F);
8033                  end loop;
8034               end;
8035
8036            else
8037               Ensure_Type_Is_SA (Designated_Type (Typ));
8038            end if;
8039
8040         elsif Is_Record_Type (Typ) then
8041            C := First_Entity (Typ);
8042            while Present (C) loop
8043               if Ekind (C) = E_Discriminant
8044                 or else Ekind (C) = E_Component
8045               then
8046                  Ensure_Type_Is_SA (Etype (C));
8047
8048               elsif Is_Type (C) then
8049                  Ensure_Type_Is_SA (C);
8050               end if;
8051
8052               Next_Entity (C);
8053            end loop;
8054
8055         elsif Ekind (Typ) = E_Subprogram_Type then
8056            Ensure_Type_Is_SA (Etype (Typ));
8057
8058            C := First_Formal (Typ);
8059            while Present (C) loop
8060               Ensure_Type_Is_SA (Etype (C));
8061               Next_Formal (C);
8062            end loop;
8063
8064         else
8065            raise Cannot_Be_Static;
8066         end if;
8067      end Ensure_Type_Is_SA;
8068
8069   --  Start of processing for Freeze_Static_Object
8070
8071   begin
8072      Ensure_Type_Is_SA (Etype (E));
8073
8074   exception
8075      when Cannot_Be_Static =>
8076
8077         --  If the object that cannot be static is imported or exported, then
8078         --  issue an error message saying that this object cannot be imported
8079         --  or exported. If it has an address clause it is an overlay in the
8080         --  current partition and the static requirement is not relevant.
8081         --  Do not issue any error message when ignoring rep clauses.
8082
8083         if Ignore_Rep_Clauses then
8084            null;
8085
8086         elsif Is_Imported (E) then
8087            if No (Address_Clause (E)) then
8088               Error_Msg_N
8089                 ("& cannot be imported (local type is not constant)", E);
8090            end if;
8091
8092         --  Otherwise must be exported, something is wrong if compiler
8093         --  is marking something as statically allocated which cannot be).
8094
8095         else pragma Assert (Is_Exported (E));
8096            Error_Msg_N
8097              ("& cannot be exported (local type is not constant)", E);
8098         end if;
8099   end Freeze_Static_Object;
8100
8101   -----------------------
8102   -- Freeze_Subprogram --
8103   -----------------------
8104
8105   procedure Freeze_Subprogram (E : Entity_Id) is
8106      procedure Set_Profile_Convention (Subp_Id : Entity_Id);
8107      --  Set the conventions of all anonymous access-to-subprogram formals and
8108      --  result subtype of subprogram Subp_Id to the convention of Subp_Id.
8109
8110      ----------------------------
8111      -- Set_Profile_Convention --
8112      ----------------------------
8113
8114      procedure Set_Profile_Convention (Subp_Id : Entity_Id) is
8115         Conv : constant Convention_Id := Convention (Subp_Id);
8116
8117         procedure Set_Type_Convention (Typ : Entity_Id);
8118         --  Set the convention of anonymous access-to-subprogram type Typ and
8119         --  its designated type to Conv.
8120
8121         -------------------------
8122         -- Set_Type_Convention --
8123         -------------------------
8124
8125         procedure Set_Type_Convention (Typ : Entity_Id) is
8126         begin
8127            --  Set the convention on both the anonymous access-to-subprogram
8128            --  type and the subprogram type it points to because both types
8129            --  participate in conformance-related checks.
8130
8131            if Ekind (Typ) = E_Anonymous_Access_Subprogram_Type then
8132               Set_Convention (Typ, Conv);
8133               Set_Convention (Designated_Type (Typ), Conv);
8134            end if;
8135         end Set_Type_Convention;
8136
8137         --  Local variables
8138
8139         Formal : Entity_Id;
8140
8141      --  Start of processing for Set_Profile_Convention
8142
8143      begin
8144         Formal := First_Formal (Subp_Id);
8145         while Present (Formal) loop
8146            Set_Type_Convention (Etype (Formal));
8147            Next_Formal (Formal);
8148         end loop;
8149
8150         if Ekind (Subp_Id) = E_Function then
8151            Set_Type_Convention (Etype (Subp_Id));
8152         end if;
8153      end Set_Profile_Convention;
8154
8155      --  Local variables
8156
8157      F      : Entity_Id;
8158      Retype : Entity_Id;
8159
8160   --  Start of processing for Freeze_Subprogram
8161
8162   begin
8163      --  Subprogram may not have an address clause unless it is imported
8164
8165      if Present (Address_Clause (E)) then
8166         if not Is_Imported (E) then
8167            Error_Msg_N
8168              ("address clause can only be given for imported subprogram",
8169               Name (Address_Clause (E)));
8170         end if;
8171      end if;
8172
8173      --  Reset the Pure indication on an imported subprogram unless an
8174      --  explicit Pure_Function pragma was present or the subprogram is an
8175      --  intrinsic. We do this because otherwise it is an insidious error
8176      --  to call a non-pure function from pure unit and have calls
8177      --  mysteriously optimized away. What happens here is that the Import
8178      --  can bypass the normal check to ensure that pure units call only pure
8179      --  subprograms.
8180
8181      --  The reason for the intrinsic exception is that in general, intrinsic
8182      --  functions (such as shifts) are pure anyway. The only exceptions are
8183      --  the intrinsics in GNAT.Source_Info, and that unit is not marked Pure
8184      --  in any case, so no problem arises.
8185
8186      if Is_Imported (E)
8187        and then Is_Pure (E)
8188        and then not Has_Pragma_Pure_Function (E)
8189        and then not Is_Intrinsic_Subprogram (E)
8190      then
8191         Set_Is_Pure (E, False);
8192      end if;
8193
8194      --  We also reset the Pure indication on a subprogram with an Address
8195      --  parameter, because the parameter may be used as a pointer and the
8196      --  referenced data may change even if the address value does not.
8197
8198      --  Note that if the programmer gave an explicit Pure_Function pragma,
8199      --  then we believe the programmer, and leave the subprogram Pure. We
8200      --  also suppress this check on run-time files.
8201
8202      if Is_Pure (E)
8203        and then Is_Subprogram (E)
8204        and then not Has_Pragma_Pure_Function (E)
8205        and then not Is_Internal_Unit (Current_Sem_Unit)
8206      then
8207         Check_Function_With_Address_Parameter (E);
8208      end if;
8209
8210      --  Ensure that all anonymous access-to-subprogram types inherit the
8211      --  convention of their related subprogram (RM 6.3.1 13.1/3). This is
8212      --  not done for a defaulted convention Ada because those types also
8213      --  default to Ada. Convention Protected must not be propagated when
8214      --  the subprogram is an entry because this would be illegal. The only
8215      --  way to force convention Protected on these kinds of types is to
8216      --  include keyword "protected" in the access definition.
8217
8218      if Convention (E) /= Convention_Ada
8219        and then Convention (E) /= Convention_Protected
8220      then
8221         Set_Profile_Convention (E);
8222      end if;
8223
8224      --  For non-foreign convention subprograms, this is where we create
8225      --  the extra formals (for accessibility level and constrained bit
8226      --  information). We delay this till the freeze point precisely so
8227      --  that we know the convention.
8228
8229      if not Has_Foreign_Convention (E) then
8230         if No (Extra_Formals (E)) then
8231            Create_Extra_Formals (E);
8232         end if;
8233
8234         Set_Mechanisms (E);
8235
8236         --  If this is convention Ada and a Valued_Procedure, that's odd
8237
8238         if Ekind (E) = E_Procedure
8239           and then Is_Valued_Procedure (E)
8240           and then Convention (E) = Convention_Ada
8241           and then Warn_On_Export_Import
8242         then
8243            Error_Msg_N
8244              ("??Valued_Procedure has no effect for convention Ada", E);
8245            Set_Is_Valued_Procedure (E, False);
8246         end if;
8247
8248      --  Case of foreign convention
8249
8250      else
8251         Set_Mechanisms (E);
8252
8253         --  For foreign conventions, warn about return of unconstrained array
8254
8255         if Ekind (E) = E_Function then
8256            Retype := Underlying_Type (Etype (E));
8257
8258            --  If no return type, probably some other error, e.g. a
8259            --  missing full declaration, so ignore.
8260
8261            if No (Retype) then
8262               null;
8263
8264            --  If the return type is generic, we have emitted a warning
8265            --  earlier on, and there is nothing else to check here. Specific
8266            --  instantiations may lead to erroneous behavior.
8267
8268            elsif Is_Generic_Type (Etype (E)) then
8269               null;
8270
8271            --  Display warning if returning unconstrained array
8272
8273            elsif Is_Array_Type (Retype)
8274              and then not Is_Constrained (Retype)
8275
8276               --  Check appropriate warning is enabled (should we check for
8277               --  Warnings (Off) on specific entities here, probably so???)
8278
8279              and then Warn_On_Export_Import
8280            then
8281               Error_Msg_N
8282                ("?x?foreign convention function& should not return " &
8283                  "unconstrained array", E);
8284               return;
8285            end if;
8286         end if;
8287
8288         --  If any of the formals for an exported foreign convention
8289         --  subprogram have defaults, then emit an appropriate warning since
8290         --  this is odd (default cannot be used from non-Ada code)
8291
8292         if Is_Exported (E) then
8293            F := First_Formal (E);
8294            while Present (F) loop
8295               if Warn_On_Export_Import
8296                 and then Present (Default_Value (F))
8297               then
8298                  Error_Msg_N
8299                    ("?x?parameter cannot be defaulted in non-Ada call",
8300                     Default_Value (F));
8301               end if;
8302
8303               Next_Formal (F);
8304            end loop;
8305         end if;
8306      end if;
8307
8308      --  Pragma Inline_Always is disallowed for dispatching subprograms
8309      --  because the address of such subprograms is saved in the dispatch
8310      --  table to support dispatching calls, and dispatching calls cannot
8311      --  be inlined. This is consistent with the restriction against using
8312      --  'Access or 'Address on an Inline_Always subprogram.
8313
8314      if Is_Dispatching_Operation (E)
8315        and then Has_Pragma_Inline_Always (E)
8316      then
8317         Error_Msg_N
8318           ("pragma Inline_Always not allowed for dispatching subprograms", E);
8319      end if;
8320
8321      --  Because of the implicit representation of inherited predefined
8322      --  operators in the front-end, the overriding status of the operation
8323      --  may be affected when a full view of a type is analyzed, and this is
8324      --  not captured by the analysis of the corresponding type declaration.
8325      --  Therefore the correctness of a not-overriding indicator must be
8326      --  rechecked when the subprogram is frozen.
8327
8328      if Nkind (E) = N_Defining_Operator_Symbol
8329        and then not Error_Posted (Parent (E))
8330      then
8331         Check_Overriding_Indicator (E, Empty, Is_Primitive (E));
8332      end if;
8333
8334      if Modify_Tree_For_C
8335        and then Nkind (Parent (E)) = N_Function_Specification
8336        and then Is_Array_Type (Etype (E))
8337        and then Is_Constrained (Etype (E))
8338        and then not Is_Unchecked_Conversion_Instance (E)
8339        and then not Rewritten_For_C (E)
8340      then
8341         Build_Procedure_Form (Unit_Declaration_Node (E));
8342      end if;
8343   end Freeze_Subprogram;
8344
8345   ----------------------
8346   -- Is_Fully_Defined --
8347   ----------------------
8348
8349   function Is_Fully_Defined (T : Entity_Id) return Boolean is
8350   begin
8351      if Ekind (T) = E_Class_Wide_Type then
8352         return Is_Fully_Defined (Etype (T));
8353
8354      elsif Is_Array_Type (T) then
8355         return Is_Fully_Defined (Component_Type (T));
8356
8357      elsif Is_Record_Type (T)
8358        and not Is_Private_Type (T)
8359      then
8360         --  Verify that the record type has no components with private types
8361         --  without completion.
8362
8363         declare
8364            Comp : Entity_Id;
8365
8366         begin
8367            Comp := First_Component (T);
8368            while Present (Comp) loop
8369               if not Is_Fully_Defined (Etype (Comp)) then
8370                  return False;
8371               end if;
8372
8373               Next_Component (Comp);
8374            end loop;
8375            return True;
8376         end;
8377
8378      --  For the designated type of an access to subprogram, all types in
8379      --  the profile must be fully defined.
8380
8381      elsif Ekind (T) = E_Subprogram_Type then
8382         declare
8383            F : Entity_Id;
8384
8385         begin
8386            F := First_Formal (T);
8387            while Present (F) loop
8388               if not Is_Fully_Defined (Etype (F)) then
8389                  return False;
8390               end if;
8391
8392               Next_Formal (F);
8393            end loop;
8394
8395            return Is_Fully_Defined (Etype (T));
8396         end;
8397
8398      else
8399         return not Is_Private_Type (T)
8400           or else Present (Full_View (Base_Type (T)));
8401      end if;
8402   end Is_Fully_Defined;
8403
8404   ---------------------------------
8405   -- Process_Default_Expressions --
8406   ---------------------------------
8407
8408   procedure Process_Default_Expressions
8409     (E     : Entity_Id;
8410      After : in out Node_Id)
8411   is
8412      Loc    : constant Source_Ptr := Sloc (E);
8413      Dbody  : Node_Id;
8414      Formal : Node_Id;
8415      Dcopy  : Node_Id;
8416      Dnam   : Entity_Id;
8417
8418   begin
8419      Set_Default_Expressions_Processed (E);
8420
8421      --  A subprogram instance and its associated anonymous subprogram share
8422      --  their signature. The default expression functions are defined in the
8423      --  wrapper packages for the anonymous subprogram, and should not be
8424      --  generated again for the instance.
8425
8426      if Is_Generic_Instance (E)
8427        and then Present (Alias (E))
8428        and then Default_Expressions_Processed (Alias (E))
8429      then
8430         return;
8431      end if;
8432
8433      Formal := First_Formal (E);
8434      while Present (Formal) loop
8435         if Present (Default_Value (Formal)) then
8436
8437            --  We work with a copy of the default expression because we
8438            --  do not want to disturb the original, since this would mess
8439            --  up the conformance checking.
8440
8441            Dcopy := New_Copy_Tree (Default_Value (Formal));
8442
8443            --  The analysis of the expression may generate insert actions,
8444            --  which of course must not be executed. We wrap those actions
8445            --  in a procedure that is not called, and later on eliminated.
8446            --  The following cases have no side effects, and are analyzed
8447            --  directly.
8448
8449            if Nkind (Dcopy) = N_Identifier
8450              or else Nkind_In (Dcopy, N_Expanded_Name,
8451                                       N_Integer_Literal,
8452                                       N_Character_Literal,
8453                                       N_String_Literal,
8454                                       N_Real_Literal)
8455              or else (Nkind (Dcopy) = N_Attribute_Reference
8456                        and then Attribute_Name (Dcopy) = Name_Null_Parameter)
8457              or else Known_Null (Dcopy)
8458            then
8459               --  If there is no default function, we must still do a full
8460               --  analyze call on the default value, to ensure that all error
8461               --  checks are performed, e.g. those associated with static
8462               --  evaluation. Note: this branch will always be taken if the
8463               --  analyzer is turned off (but we still need the error checks).
8464
8465               --  Note: the setting of parent here is to meet the requirement
8466               --  that we can only analyze the expression while attached to
8467               --  the tree. Really the requirement is that the parent chain
8468               --  be set, we don't actually need to be in the tree.
8469
8470               Set_Parent (Dcopy, Declaration_Node (Formal));
8471               Analyze (Dcopy);
8472
8473               --  Default expressions are resolved with their own type if the
8474               --  context is generic, to avoid anomalies with private types.
8475
8476               if Ekind (Scope (E)) = E_Generic_Package then
8477                  Resolve (Dcopy);
8478               else
8479                  Resolve (Dcopy, Etype (Formal));
8480               end if;
8481
8482               --  If that resolved expression will raise constraint error,
8483               --  then flag the default value as raising constraint error.
8484               --  This allows a proper error message on the calls.
8485
8486               if Raises_Constraint_Error (Dcopy) then
8487                  Set_Raises_Constraint_Error (Default_Value (Formal));
8488               end if;
8489
8490            --  If the default is a parameterless call, we use the name of
8491            --  the called function directly, and there is no body to build.
8492
8493            elsif Nkind (Dcopy) = N_Function_Call
8494              and then No (Parameter_Associations (Dcopy))
8495            then
8496               null;
8497
8498            --  Else construct and analyze the body of a wrapper procedure
8499            --  that contains an object declaration to hold the expression.
8500            --  Given that this is done only to complete the analysis, it is
8501            --  simpler to build a procedure than a function which might
8502            --  involve secondary stack expansion.
8503
8504            else
8505               Dnam := Make_Temporary (Loc, 'D');
8506
8507               Dbody :=
8508                 Make_Subprogram_Body (Loc,
8509                   Specification =>
8510                     Make_Procedure_Specification (Loc,
8511                       Defining_Unit_Name => Dnam),
8512
8513                   Declarations => New_List (
8514                     Make_Object_Declaration (Loc,
8515                       Defining_Identifier => Make_Temporary (Loc, 'T'),
8516                       Object_Definition   =>
8517                         New_Occurrence_Of (Etype (Formal), Loc),
8518                       Expression          => New_Copy_Tree (Dcopy))),
8519
8520                   Handled_Statement_Sequence =>
8521                     Make_Handled_Sequence_Of_Statements (Loc,
8522                       Statements => Empty_List));
8523
8524               Set_Scope (Dnam, Scope (E));
8525               Set_Assignment_OK (First (Declarations (Dbody)));
8526               Set_Is_Eliminated (Dnam);
8527               Insert_After (After, Dbody);
8528               Analyze (Dbody);
8529               After := Dbody;
8530            end if;
8531         end if;
8532
8533         Next_Formal (Formal);
8534      end loop;
8535   end Process_Default_Expressions;
8536
8537   ----------------------------------------
8538   -- Set_Component_Alignment_If_Not_Set --
8539   ----------------------------------------
8540
8541   procedure Set_Component_Alignment_If_Not_Set (Typ : Entity_Id) is
8542   begin
8543      --  Ignore if not base type, subtypes don't need anything
8544
8545      if Typ /= Base_Type (Typ) then
8546         return;
8547      end if;
8548
8549      --  Do not override existing representation
8550
8551      if Is_Packed (Typ) then
8552         return;
8553
8554      elsif Has_Specified_Layout (Typ) then
8555         return;
8556
8557      elsif Component_Alignment (Typ) /= Calign_Default then
8558         return;
8559
8560      else
8561         Set_Component_Alignment
8562           (Typ, Scope_Stack.Table
8563                  (Scope_Stack.Last).Component_Alignment_Default);
8564      end if;
8565   end Set_Component_Alignment_If_Not_Set;
8566
8567   --------------------------
8568   -- Set_SSO_From_Default --
8569   --------------------------
8570
8571   procedure Set_SSO_From_Default (T : Entity_Id) is
8572      Reversed : Boolean;
8573
8574   begin
8575      --  Set default SSO for an array or record base type, except in case of
8576      --  a type extension (which always inherits the SSO of its parent type).
8577
8578      if Is_Base_Type (T)
8579        and then (Is_Array_Type (T)
8580                   or else (Is_Record_Type (T)
8581                             and then not (Is_Tagged_Type (T)
8582                                            and then Is_Derived_Type (T))))
8583      then
8584         Reversed :=
8585            (Bytes_Big_Endian     and then SSO_Set_Low_By_Default (T))
8586              or else
8587            (not Bytes_Big_Endian and then SSO_Set_High_By_Default (T));
8588
8589         if (SSO_Set_Low_By_Default (T) or else SSO_Set_High_By_Default (T))
8590
8591           --  For a record type, if bit order is specified explicitly,
8592           --  then do not set SSO from default if not consistent. Note that
8593           --  we do not want to look at a Bit_Order attribute definition
8594           --  for a parent: if we were to inherit Bit_Order, then both
8595           --  SSO_Set_*_By_Default flags would have been cleared already
8596           --  (by Inherit_Aspects_At_Freeze_Point).
8597
8598           and then not
8599             (Is_Record_Type (T)
8600               and then
8601                 Has_Rep_Item (T, Name_Bit_Order, Check_Parents => False)
8602               and then Reverse_Bit_Order (T) /= Reversed)
8603         then
8604            --  If flags cause reverse storage order, then set the result. Note
8605            --  that we would have ignored the pragma setting the non default
8606            --  storage order in any case, hence the assertion at this point.
8607
8608            pragma Assert
8609              (not Reversed or else Support_Nondefault_SSO_On_Target);
8610
8611            Set_Reverse_Storage_Order (T, Reversed);
8612
8613            --  For a record type, also set reversed bit order. Note: if a bit
8614            --  order has been specified explicitly, then this is a no-op.
8615
8616            if Is_Record_Type (T) then
8617               Set_Reverse_Bit_Order (T, Reversed);
8618            end if;
8619         end if;
8620      end if;
8621   end Set_SSO_From_Default;
8622
8623   ------------------
8624   -- Undelay_Type --
8625   ------------------
8626
8627   procedure Undelay_Type (T : Entity_Id) is
8628   begin
8629      Set_Has_Delayed_Freeze (T, False);
8630      Set_Freeze_Node (T, Empty);
8631
8632      --  Since we don't want T to have a Freeze_Node, we don't want its
8633      --  Full_View or Corresponding_Record_Type to have one either.
8634
8635      --  ??? Fundamentally, this whole handling is unpleasant. What we really
8636      --  want is to be sure that for an Itype that's part of record R and is a
8637      --  subtype of type T, that it's frozen after the later of the freeze
8638      --  points of R and T. We have no way of doing that directly, so what we
8639      --  do is force most such Itypes to be frozen as part of freezing R via
8640      --  this procedure and only delay the ones that need to be delayed
8641      --  (mostly the designated types of access types that are defined as part
8642      --  of the record).
8643
8644      if Is_Private_Type (T)
8645        and then Present (Full_View (T))
8646        and then Is_Itype (Full_View (T))
8647        and then Is_Record_Type (Scope (Full_View (T)))
8648      then
8649         Undelay_Type (Full_View (T));
8650      end if;
8651
8652      if Is_Concurrent_Type (T)
8653        and then Present (Corresponding_Record_Type (T))
8654        and then Is_Itype (Corresponding_Record_Type (T))
8655        and then Is_Record_Type (Scope (Corresponding_Record_Type (T)))
8656      then
8657         Undelay_Type (Corresponding_Record_Type (T));
8658      end if;
8659   end Undelay_Type;
8660
8661   ------------------
8662   -- Warn_Overlay --
8663   ------------------
8664
8665   procedure Warn_Overlay (Expr : Node_Id; Typ : Entity_Id; Nam : Entity_Id) is
8666      Ent : constant Entity_Id := Entity (Nam);
8667      --  The object to which the address clause applies
8668
8669      Init : Node_Id;
8670      Old  : Entity_Id := Empty;
8671      Decl : Node_Id;
8672
8673   begin
8674      --  No warning if address clause overlay warnings are off
8675
8676      if not Address_Clause_Overlay_Warnings then
8677         return;
8678      end if;
8679
8680      --  No warning if there is an explicit initialization
8681
8682      Init := Original_Node (Expression (Declaration_Node (Ent)));
8683
8684      if Present (Init) and then Comes_From_Source (Init) then
8685         return;
8686      end if;
8687
8688      --  We only give the warning for non-imported entities of a type for
8689      --  which a non-null base init proc is defined, or for objects of access
8690      --  types with implicit null initialization, or when Normalize_Scalars
8691      --  applies and the type is scalar or a string type (the latter being
8692      --  tested for because predefined String types are initialized by inline
8693      --  code rather than by an init_proc). Note that we do not give the
8694      --  warning for Initialize_Scalars, since we suppressed initialization
8695      --  in this case. Also, do not warn if Suppress_Initialization is set.
8696
8697      if Present (Expr)
8698        and then not Is_Imported (Ent)
8699        and then not Initialization_Suppressed (Typ)
8700        and then (Has_Non_Null_Base_Init_Proc (Typ)
8701                   or else Is_Access_Type (Typ)
8702                   or else (Normalize_Scalars
8703                             and then (Is_Scalar_Type (Typ)
8704                                        or else Is_String_Type (Typ))))
8705      then
8706         if Nkind (Expr) = N_Attribute_Reference
8707           and then Is_Entity_Name (Prefix (Expr))
8708         then
8709            Old := Entity (Prefix (Expr));
8710
8711         elsif Is_Entity_Name (Expr)
8712           and then Ekind (Entity (Expr)) = E_Constant
8713         then
8714            Decl := Declaration_Node (Entity (Expr));
8715
8716            if Nkind (Decl) = N_Object_Declaration
8717              and then Present (Expression (Decl))
8718              and then Nkind (Expression (Decl)) = N_Attribute_Reference
8719              and then Is_Entity_Name (Prefix (Expression (Decl)))
8720            then
8721               Old := Entity (Prefix (Expression (Decl)));
8722
8723            elsif Nkind (Expr) = N_Function_Call then
8724               return;
8725            end if;
8726
8727         --  A function call (most likely to To_Address) is probably not an
8728         --  overlay, so skip warning. Ditto if the function call was inlined
8729         --  and transformed into an entity.
8730
8731         elsif Nkind (Original_Node (Expr)) = N_Function_Call then
8732            return;
8733         end if;
8734
8735         --  If a pragma Import follows, we assume that it is for the current
8736         --  target of the address clause, and skip the warning. There may be
8737         --  a source pragma or an aspect that specifies import and generates
8738         --  the corresponding pragma. These will indicate that the entity is
8739         --  imported and that is checked above so that the spurious warning
8740         --  (generated when the entity is frozen) will be suppressed. The
8741         --  pragma may be attached to the aspect, so it is not yet a list
8742         --  member.
8743
8744         if Is_List_Member (Parent (Expr)) then
8745            Decl := Next (Parent (Expr));
8746
8747            if Present (Decl)
8748              and then Nkind (Decl) = N_Pragma
8749              and then Pragma_Name (Decl) = Name_Import
8750            then
8751               return;
8752            end if;
8753         end if;
8754
8755         --  Otherwise give warning message
8756
8757         if Present (Old) then
8758            Error_Msg_Node_2 := Old;
8759            Error_Msg_N
8760              ("default initialization of & may modify &??",
8761               Nam);
8762         else
8763            Error_Msg_N
8764              ("default initialization of & may modify overlaid storage??",
8765               Nam);
8766         end if;
8767
8768         --  Add friendly warning if initialization comes from a packed array
8769         --  component.
8770
8771         if Is_Record_Type (Typ) then
8772            declare
8773               Comp : Entity_Id;
8774
8775            begin
8776               Comp := First_Component (Typ);
8777               while Present (Comp) loop
8778                  if Nkind (Parent (Comp)) = N_Component_Declaration
8779                    and then Present (Expression (Parent (Comp)))
8780                  then
8781                     exit;
8782                  elsif Is_Array_Type (Etype (Comp))
8783                     and then Present (Packed_Array_Impl_Type (Etype (Comp)))
8784                  then
8785                     Error_Msg_NE
8786                       ("\packed array component& " &
8787                        "will be initialized to zero??",
8788                        Nam, Comp);
8789                     exit;
8790                  else
8791                     Next_Component (Comp);
8792                  end if;
8793               end loop;
8794            end;
8795         end if;
8796
8797         Error_Msg_N
8798           ("\use pragma Import for & to " &
8799            "suppress initialization (RM B.1(24))??",
8800            Nam);
8801      end if;
8802   end Warn_Overlay;
8803
8804end Freeze;
8805