* gcc-interface/gigi.h (build_atomic_load): Adjust prototype.
[platform/upstream/linaro-gcc.git] / gcc / ada / gcc-interface / decl.c
1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                                 D E C L                                  *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *          Copyright (C) 1992-2015, 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 along with GCC; see the file COPYING3.  If not see        *
19  * <http://www.gnu.org/licenses/>.                                          *
20  *                                                                          *
21  * GNAT was originally developed  by the GNAT team at  New York University. *
22  * Extensive contributions were provided by Ada Core Technologies Inc.      *
23  *                                                                          *
24  ****************************************************************************/
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "hash-set.h"
31 #include "machmode.h"
32 #include "vec.h"
33 #include "double-int.h"
34 #include "input.h"
35 #include "alias.h"
36 #include "symtab.h"
37 #include "wide-int.h"
38 #include "inchash.h"
39 #include "tree.h"
40 #include "fold-const.h"
41 #include "stringpool.h"
42 #include "stor-layout.h"
43 #include "flags.h"
44 #include "toplev.h"
45 #include "ggc.h"
46 #include "target.h"
47 #include "tree-inline.h"
48 #include "diagnostic-core.h"
49
50 #include "ada.h"
51 #include "types.h"
52 #include "atree.h"
53 #include "elists.h"
54 #include "namet.h"
55 #include "nlists.h"
56 #include "repinfo.h"
57 #include "snames.h"
58 #include "stringt.h"
59 #include "uintp.h"
60 #include "fe.h"
61 #include "sinfo.h"
62 #include "einfo.h"
63 #include "ada-tree.h"
64 #include "gigi.h"
65
66 /* "stdcall" and "thiscall" conventions should be processed in a specific way
67    on 32-bit x86/Windows only.  The macros below are helpers to avoid having
68    to check for a Windows specific attribute throughout this unit.  */
69
70 #if TARGET_DLLIMPORT_DECL_ATTRIBUTES
71 #ifdef TARGET_64BIT
72 #define Has_Stdcall_Convention(E) \
73   (!TARGET_64BIT && Convention (E) == Convention_Stdcall)
74 #define Has_Thiscall_Convention(E) \
75   (!TARGET_64BIT && is_cplusplus_method (E))
76 #else
77 #define Has_Stdcall_Convention(E) (Convention (E) == Convention_Stdcall)
78 #define Has_Thiscall_Convention(E) (is_cplusplus_method (E))
79 #endif
80 #else
81 #define Has_Stdcall_Convention(E) 0
82 #define Has_Thiscall_Convention(E) 0
83 #endif
84
85 #define STDCALL_PREFIX "_imp__"
86
87 /* Stack realignment is necessary for functions with foreign conventions when
88    the ABI doesn't mandate as much as what the compiler assumes - that is, up
89    to PREFERRED_STACK_BOUNDARY.
90
91    Such realignment can be requested with a dedicated function type attribute
92    on the targets that support it.  We define FOREIGN_FORCE_REALIGN_STACK to
93    characterize the situations where the attribute should be set.  We rely on
94    compiler configuration settings for 'main' to decide.  */
95
96 #ifdef MAIN_STACK_BOUNDARY
97 #define FOREIGN_FORCE_REALIGN_STACK \
98   (MAIN_STACK_BOUNDARY < PREFERRED_STACK_BOUNDARY)
99 #else
100 #define FOREIGN_FORCE_REALIGN_STACK 0
101 #endif
102
103 struct incomplete
104 {
105   struct incomplete *next;
106   tree old_type;
107   Entity_Id full_type;
108 };
109
110 /* These variables are used to defer recursively expanding incomplete types
111    while we are processing an array, a record or a subprogram type.  */
112 static int defer_incomplete_level = 0;
113 static struct incomplete *defer_incomplete_list;
114
115 /* This variable is used to delay expanding From_Limited_With types until the
116    end of the spec.  */
117 static struct incomplete *defer_limited_with;
118
119 typedef struct subst_pair_d {
120   tree discriminant;
121   tree replacement;
122 } subst_pair;
123
124
125 typedef struct variant_desc_d {
126   /* The type of the variant.  */
127   tree type;
128
129   /* The associated field.  */
130   tree field;
131
132   /* The value of the qualifier.  */
133   tree qual;
134
135   /* The type of the variant after transformation.  */
136   tree new_type;
137 } variant_desc;
138
139
140 /* A hash table used to cache the result of annotate_value.  */
141
142 struct value_annotation_hasher : ggc_cache_hasher<tree_int_map *>
143 {
144   static inline hashval_t
145   hash (tree_int_map *m)
146   {
147     return htab_hash_pointer (m->base.from);
148   }
149
150   static inline bool
151   equal (tree_int_map *a, tree_int_map *b)
152   {
153     return a->base.from == b->base.from;
154   }
155
156   static void
157   handle_cache_entry (tree_int_map *&m)
158   {
159     extern void gt_ggc_mx (tree_int_map *&);
160     if (m == HTAB_EMPTY_ENTRY || m == HTAB_DELETED_ENTRY)
161       return;
162     else if (ggc_marked_p (m->base.from))
163       gt_ggc_mx (m);
164     else
165       m = static_cast<tree_int_map *> (HTAB_DELETED_ENTRY);
166   }
167 };
168
169 static GTY ((cache)) hash_table<value_annotation_hasher> *annotate_value_cache;
170
171 static bool allocatable_size_p (tree, bool);
172 static void prepend_one_attribute (struct attrib **,
173                                    enum attr_type, tree, tree, Node_Id);
174 static void prepend_one_attribute_pragma (struct attrib **, Node_Id);
175 static void prepend_attributes (struct attrib **, Entity_Id);
176 static tree elaborate_expression (Node_Id, Entity_Id, tree, bool, bool, bool);
177 static bool type_has_variable_size (tree);
178 static tree elaborate_expression_1 (tree, Entity_Id, tree, bool, bool);
179 static tree elaborate_expression_2 (tree, Entity_Id, tree, bool, bool,
180                                     unsigned int);
181 static tree gnat_to_gnu_component_type (Entity_Id, bool, bool);
182 static tree gnat_to_gnu_param (Entity_Id, Mechanism_Type, Entity_Id, bool,
183                                bool *);
184 static tree gnat_to_gnu_field (Entity_Id, tree, int, bool, bool);
185 static bool is_from_limited_with_of_main (Entity_Id);
186 static tree change_qualified_type (tree, int);
187 static bool same_discriminant_p (Entity_Id, Entity_Id);
188 static bool array_type_has_nonaliased_component (tree, Entity_Id);
189 static bool compile_time_known_address_p (Node_Id);
190 static bool cannot_be_superflat_p (Node_Id);
191 static bool constructor_address_p (tree);
192 static int compare_field_bitpos (const PTR, const PTR);
193 static bool components_to_record (tree, Node_Id, tree, int, bool, bool, bool,
194                                   bool, bool, bool, bool, bool, tree, tree *);
195 static Uint annotate_value (tree);
196 static void annotate_rep (Entity_Id, tree);
197 static tree build_position_list (tree, bool, tree, tree, unsigned int, tree);
198 static vec<subst_pair> build_subst_list (Entity_Id, Entity_Id, bool);
199 static vec<variant_desc> build_variant_list (tree,
200                                                    vec<subst_pair> ,
201                                                    vec<variant_desc> );
202 static tree validate_size (Uint, tree, Entity_Id, enum tree_code, bool, bool);
203 static void set_rm_size (Uint, tree, Entity_Id);
204 static unsigned int validate_alignment (Uint, Entity_Id, unsigned int);
205 static void check_ok_for_atomic_type (tree, Entity_Id, bool);
206 static tree create_field_decl_from (tree, tree, tree, tree, tree,
207                                     vec<subst_pair> );
208 static tree create_rep_part (tree, tree, tree);
209 static tree get_rep_part (tree);
210 static tree create_variant_part_from (tree, vec<variant_desc> , tree,
211                                       tree, vec<subst_pair> );
212 static void copy_and_substitute_in_size (tree, tree, vec<subst_pair> );
213 static void add_parallel_type_for_packed_array (tree, Entity_Id);
214
215 /* The relevant constituents of a subprogram binding to a GCC builtin.  Used
216    to pass around calls performing profile compatibility checks.  */
217
218 typedef struct {
219   Entity_Id gnat_entity;  /* The Ada subprogram entity.  */
220   tree ada_fntype;        /* The corresponding GCC type node.  */
221   tree btin_fntype;       /* The GCC builtin function type node.  */
222 } intrin_binding_t;
223
224 static bool intrin_profiles_compatible_p (intrin_binding_t *);
225 \f
226 /* Given GNAT_ENTITY, a GNAT defining identifier node, which denotes some Ada
227    entity, return the equivalent GCC tree for that entity (a ..._DECL node)
228    and associate the ..._DECL node with the input GNAT defining identifier.
229
230    If GNAT_ENTITY is a variable or a constant declaration, GNU_EXPR gives its
231    initial value (in GCC tree form).  This is optional for a variable.  For
232    a renamed entity, GNU_EXPR gives the object being renamed.
233
234    DEFINITION is nonzero if this call is intended for a definition.  This is
235    used for separate compilation where it is necessary to know whether an
236    external declaration or a definition must be created if the GCC equivalent
237    was not created previously.  The value of 1 is normally used for a nonzero
238    DEFINITION, but a value of 2 is used in special circumstances, defined in
239    the code.  */
240
241 tree
242 gnat_to_gnu_entity (Entity_Id gnat_entity, tree gnu_expr, int definition)
243 {
244   /* Contains the kind of the input GNAT node.  */
245   const Entity_Kind kind = Ekind (gnat_entity);
246   /* True if this is a type.  */
247   const bool is_type = IN (kind, Type_Kind);
248   /* True if debug info is requested for this entity.  */
249   const bool debug_info_p = Needs_Debug_Info (gnat_entity);
250   /* True if this entity is to be considered as imported.  */
251   const bool imported_p
252     = (Is_Imported (gnat_entity) && No (Address_Clause (gnat_entity)));
253   /* For a type, contains the equivalent GNAT node to be used in gigi.  */
254   Entity_Id gnat_equiv_type = Empty;
255   /* Temporary used to walk the GNAT tree.  */
256   Entity_Id gnat_temp;
257   /* Contains the GCC DECL node which is equivalent to the input GNAT node.
258      This node will be associated with the GNAT node by calling at the end
259      of the `switch' statement.  */
260   tree gnu_decl = NULL_TREE;
261   /* Contains the GCC type to be used for the GCC node.  */
262   tree gnu_type = NULL_TREE;
263   /* Contains the GCC size tree to be used for the GCC node.  */
264   tree gnu_size = NULL_TREE;
265   /* Contains the GCC name to be used for the GCC node.  */
266   tree gnu_entity_name;
267   /* True if we have already saved gnu_decl as a GNAT association.  */
268   bool saved = false;
269   /* True if we incremented defer_incomplete_level.  */
270   bool this_deferred = false;
271   /* True if we incremented force_global.  */
272   bool this_global = false;
273   /* True if we should check to see if elaborated during processing.  */
274   bool maybe_present = false;
275   /* True if we made GNU_DECL and its type here.  */
276   bool this_made_decl = false;
277   /* Size and alignment of the GCC node, if meaningful.  */
278   unsigned int esize = 0, align = 0;
279   /* Contains the list of attributes directly attached to the entity.  */
280   struct attrib *attr_list = NULL;
281
282   /* Since a use of an Itype is a definition, process it as such if it
283      is not in a with'ed unit.  */
284   if (!definition
285       && is_type
286       && Is_Itype (gnat_entity)
287       && !present_gnu_tree (gnat_entity)
288       && In_Extended_Main_Code_Unit (gnat_entity))
289     {
290       /* Ensure that we are in a subprogram mentioned in the Scope chain of
291          this entity, our current scope is global, or we encountered a task
292          or entry (where we can't currently accurately check scoping).  */
293       if (!current_function_decl
294           || DECL_ELABORATION_PROC_P (current_function_decl))
295         {
296           process_type (gnat_entity);
297           return get_gnu_tree (gnat_entity);
298         }
299
300       for (gnat_temp = Scope (gnat_entity);
301            Present (gnat_temp);
302            gnat_temp = Scope (gnat_temp))
303         {
304           if (Is_Type (gnat_temp))
305             gnat_temp = Underlying_Type (gnat_temp);
306
307           if (Ekind (gnat_temp) == E_Subprogram_Body)
308             gnat_temp
309               = Corresponding_Spec (Parent (Declaration_Node (gnat_temp)));
310
311           if (IN (Ekind (gnat_temp), Subprogram_Kind)
312               && Present (Protected_Body_Subprogram (gnat_temp)))
313             gnat_temp = Protected_Body_Subprogram (gnat_temp);
314
315           if (Ekind (gnat_temp) == E_Entry
316               || Ekind (gnat_temp) == E_Entry_Family
317               || Ekind (gnat_temp) == E_Task_Type
318               || (IN (Ekind (gnat_temp), Subprogram_Kind)
319                   && present_gnu_tree (gnat_temp)
320                   && (current_function_decl
321                       == gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0))))
322             {
323               process_type (gnat_entity);
324               return get_gnu_tree (gnat_entity);
325             }
326         }
327
328       /* This abort means the Itype has an incorrect scope, i.e. that its
329          scope does not correspond to the subprogram it is declared in.  */
330       gcc_unreachable ();
331     }
332
333   /* If we've already processed this entity, return what we got last time.
334      If we are defining the node, we should not have already processed it.
335      In that case, we will abort below when we try to save a new GCC tree
336      for this object.  We also need to handle the case of getting a dummy
337      type when a Full_View exists but be careful so as not to trigger its
338      premature elaboration.  */
339   if ((!definition || (is_type && imported_p))
340       && present_gnu_tree (gnat_entity))
341     {
342       gnu_decl = get_gnu_tree (gnat_entity);
343
344       if (TREE_CODE (gnu_decl) == TYPE_DECL
345           && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_decl))
346           && IN (kind, Incomplete_Or_Private_Kind)
347           && Present (Full_View (gnat_entity))
348           && (present_gnu_tree (Full_View (gnat_entity))
349               || No (Freeze_Node (Full_View (gnat_entity)))))
350         {
351           gnu_decl
352             = gnat_to_gnu_entity (Full_View (gnat_entity), NULL_TREE, 0);
353           save_gnu_tree (gnat_entity, NULL_TREE, false);
354           save_gnu_tree (gnat_entity, gnu_decl, false);
355         }
356
357       return gnu_decl;
358     }
359
360   /* If this is a numeric or enumeral type, or an access type, a nonzero Esize
361      must be specified unless it was specified by the programmer.  Exceptions
362      are for access-to-protected-subprogram types and all access subtypes, as
363      another GNAT type is used to lay out the GCC type for them.  */
364   gcc_assert (!Unknown_Esize (gnat_entity)
365               || Has_Size_Clause (gnat_entity)
366               || (!IN (kind, Numeric_Kind)
367                   && !IN (kind, Enumeration_Kind)
368                   && (!IN (kind, Access_Kind)
369                       || kind == E_Access_Protected_Subprogram_Type
370                       || kind == E_Anonymous_Access_Protected_Subprogram_Type
371                       || kind == E_Access_Subtype
372                       || type_annotate_only)));
373
374   /* The RM size must be specified for all discrete and fixed-point types.  */
375   gcc_assert (!(IN (kind, Discrete_Or_Fixed_Point_Kind)
376                 && Unknown_RM_Size (gnat_entity)));
377
378   /* If we get here, it means we have not yet done anything with this entity.
379      If we are not defining it, it must be a type or an entity that is defined
380      elsewhere or externally, otherwise we should have defined it already.  */
381   gcc_assert (definition
382               || type_annotate_only
383               || is_type
384               || kind == E_Discriminant
385               || kind == E_Component
386               || kind == E_Label
387               || (kind == E_Constant && Present (Full_View (gnat_entity)))
388               || Is_Public (gnat_entity));
389
390   /* Get the name of the entity and set up the line number and filename of
391      the original definition for use in any decl we make.  Make sure we do not
392      inherit another source location.  */
393   gnu_entity_name = get_entity_name (gnat_entity);
394   if (Sloc (gnat_entity) != No_Location
395       && !renaming_from_generic_instantiation_p (gnat_entity))
396     Sloc_to_locus (Sloc (gnat_entity), &input_location);
397
398   /* For cases when we are not defining (i.e., we are referencing from
399      another compilation unit) public entities, show we are at global level
400      for the purpose of computing scopes.  Don't do this for components or
401      discriminants since the relevant test is whether or not the record is
402      being defined.  */
403   if (!definition
404       && kind != E_Component
405       && kind != E_Discriminant
406       && Is_Public (gnat_entity)
407       && !Is_Statically_Allocated (gnat_entity))
408     force_global++, this_global = true;
409
410   /* Handle any attributes directly attached to the entity.  */
411   if (Has_Gigi_Rep_Item (gnat_entity))
412     prepend_attributes (&attr_list, gnat_entity);
413
414   /* Do some common processing for types.  */
415   if (is_type)
416     {
417       /* Compute the equivalent type to be used in gigi.  */
418       gnat_equiv_type = Gigi_Equivalent_Type (gnat_entity);
419
420       /* Machine_Attributes on types are expected to be propagated to
421          subtypes.  The corresponding Gigi_Rep_Items are only attached
422          to the first subtype though, so we handle the propagation here.  */
423       if (Base_Type (gnat_entity) != gnat_entity
424           && !Is_First_Subtype (gnat_entity)
425           && Has_Gigi_Rep_Item (First_Subtype (Base_Type (gnat_entity))))
426         prepend_attributes (&attr_list,
427                             First_Subtype (Base_Type (gnat_entity)));
428
429       /* Compute a default value for the size of an elementary type.  */
430       if (Known_Esize (gnat_entity) && Is_Elementary_Type (gnat_entity))
431         {
432           unsigned int max_esize;
433
434           gcc_assert (UI_Is_In_Int_Range (Esize (gnat_entity)));
435           esize = UI_To_Int (Esize (gnat_entity));
436
437           if (IN (kind, Float_Kind))
438             max_esize = fp_prec_to_size (LONG_DOUBLE_TYPE_SIZE);
439           else if (IN (kind, Access_Kind))
440             max_esize = POINTER_SIZE * 2;
441           else
442             max_esize = LONG_LONG_TYPE_SIZE;
443
444           if (esize > max_esize)
445            esize = max_esize;
446         }
447     }
448
449   switch (kind)
450     {
451     case E_Constant:
452       /* If this is a use of a deferred constant without address clause,
453          get its full definition.  */
454       if (!definition
455           && No (Address_Clause (gnat_entity))
456           && Present (Full_View (gnat_entity)))
457         {
458           gnu_decl
459             = gnat_to_gnu_entity (Full_View (gnat_entity), gnu_expr, 0);
460           saved = true;
461           break;
462         }
463
464       /* If we have an external constant that we are not defining, get the
465          expression that is was defined to represent.  We may throw it away
466          later if it is not a constant.  But do not retrieve the expression
467          if it is an allocator because the designated type might be dummy
468          at this point.  */
469       if (!definition
470           && !No_Initialization (Declaration_Node (gnat_entity))
471           && Present (Expression (Declaration_Node (gnat_entity)))
472           && Nkind (Expression (Declaration_Node (gnat_entity)))
473              != N_Allocator)
474         {
475           bool went_into_elab_proc = false;
476           int save_force_global = force_global;
477
478           /* The expression may contain N_Expression_With_Actions nodes and
479              thus object declarations from other units.  In this case, even
480              though the expression will eventually be discarded since not a
481              constant, the declarations would be stuck either in the global
482              varpool or in the current scope.  Therefore we force the local
483              context and create a fake scope that we'll zap at the end.  */
484           if (!current_function_decl)
485             {
486               current_function_decl = get_elaboration_procedure ();
487               went_into_elab_proc = true;
488             }
489           force_global = 0;
490           gnat_pushlevel ();
491
492           gnu_expr = gnat_to_gnu (Expression (Declaration_Node (gnat_entity)));
493
494           gnat_zaplevel ();
495           force_global = save_force_global;
496           if (went_into_elab_proc)
497             current_function_decl = NULL_TREE;
498         }
499
500       /* Ignore deferred constant definitions without address clause since
501          they are processed fully in the front-end.  If No_Initialization
502          is set, this is not a deferred constant but a constant whose value
503          is built manually.  And constants that are renamings are handled
504          like variables.  */
505       if (definition
506           && !gnu_expr
507           && No (Address_Clause (gnat_entity))
508           && !No_Initialization (Declaration_Node (gnat_entity))
509           && No (Renamed_Object (gnat_entity)))
510         {
511           gnu_decl = error_mark_node;
512           saved = true;
513           break;
514         }
515
516       /* Ignore constant definitions already marked with the error node.  See
517          the N_Object_Declaration case of gnat_to_gnu for the rationale.  */
518       if (definition
519           && gnu_expr
520           && present_gnu_tree (gnat_entity)
521           && get_gnu_tree (gnat_entity) == error_mark_node)
522         {
523           maybe_present = true;
524           break;
525         }
526
527       goto object;
528
529     case E_Exception:
530       goto object;
531
532     case E_Component:
533     case E_Discriminant:
534       {
535         /* The GNAT record where the component was defined.  */
536         Entity_Id gnat_record = Underlying_Type (Scope (gnat_entity));
537
538         /* If the entity is a discriminant of an extended tagged type used to
539            rename a discriminant of the parent type, return the latter.  */
540         if (Is_Tagged_Type (gnat_record)
541             && Present (Corresponding_Discriminant (gnat_entity)))
542           {
543             gnu_decl
544               = gnat_to_gnu_entity (Corresponding_Discriminant (gnat_entity),
545                                     gnu_expr, definition);
546             saved = true;
547             break;
548           }
549
550         /* If the entity is an inherited component (in the case of extended
551            tagged record types), just return the original entity, which must
552            be a FIELD_DECL.  Likewise for discriminants.  If the entity is a
553            non-girder discriminant (in the case of derived untagged record
554            types), return the stored discriminant it renames.  */
555         else if (Present (Original_Record_Component (gnat_entity))
556                  && Original_Record_Component (gnat_entity) != gnat_entity)
557           {
558             gnu_decl
559               = gnat_to_gnu_entity (Original_Record_Component (gnat_entity),
560                                     gnu_expr, definition);
561             saved = true;
562             break;
563           }
564
565         /* Otherwise, if we are not defining this and we have no GCC type
566            for the containing record, make one for it.  Then we should
567            have made our own equivalent.  */
568         else if (!definition && !present_gnu_tree (gnat_record))
569           {
570             /* ??? If this is in a record whose scope is a protected
571                type and we have an Original_Record_Component, use it.
572                This is a workaround for major problems in protected type
573                handling.  */
574             Entity_Id Scop = Scope (Scope (gnat_entity));
575             if (Is_Protected_Type (Underlying_Type (Scop))
576                 && Present (Original_Record_Component (gnat_entity)))
577               {
578                 gnu_decl
579                   = gnat_to_gnu_entity (Original_Record_Component
580                                         (gnat_entity),
581                                         gnu_expr, 0);
582                 saved = true;
583                 break;
584               }
585
586             gnat_to_gnu_entity (Scope (gnat_entity), NULL_TREE, 0);
587             gnu_decl = get_gnu_tree (gnat_entity);
588             saved = true;
589             break;
590           }
591
592         else
593           /* Here we have no GCC type and this is a reference rather than a
594              definition.  This should never happen.  Most likely the cause is
595              reference before declaration in the GNAT tree for gnat_entity.  */
596           gcc_unreachable ();
597       }
598
599     case E_Loop_Parameter:
600     case E_Out_Parameter:
601     case E_Variable:
602
603       /* Simple variables, loop variables, Out parameters and exceptions.  */
604     object:
605       {
606         /* Always create a variable for volatile objects and variables seen
607            constant but with a Linker_Section pragma.  */
608         bool const_flag
609           = ((kind == E_Constant || kind == E_Variable)
610              && Is_True_Constant (gnat_entity)
611              && !(kind == E_Variable
612                   && Present (Linker_Section_Pragma (gnat_entity)))
613              && !Treat_As_Volatile (gnat_entity)
614              && (((Nkind (Declaration_Node (gnat_entity))
615                    == N_Object_Declaration)
616                   && Present (Expression (Declaration_Node (gnat_entity))))
617                  || Present (Renamed_Object (gnat_entity))
618                  || imported_p));
619         bool inner_const_flag = const_flag;
620         bool static_p = Is_Statically_Allocated (gnat_entity);
621         bool mutable_p = false;
622         bool used_by_ref = false;
623         tree gnu_ext_name = NULL_TREE;
624         tree renamed_obj = NULL_TREE;
625         tree gnu_object_size;
626
627         if (Present (Renamed_Object (gnat_entity)) && !definition)
628           {
629             if (kind == E_Exception)
630               gnu_expr = gnat_to_gnu_entity (Renamed_Entity (gnat_entity),
631                                              NULL_TREE, 0);
632             else
633               gnu_expr = gnat_to_gnu (Renamed_Object (gnat_entity));
634           }
635
636         /* Get the type after elaborating the renamed object.  */
637         gnu_type = gnat_to_gnu_type (Etype (gnat_entity));
638
639         /* If this is a standard exception definition, then use the standard
640            exception type.  This is necessary to make sure that imported and
641            exported views of exceptions are properly merged in LTO mode.  */
642         if (TREE_CODE (TYPE_NAME (gnu_type)) == TYPE_DECL
643             && DECL_NAME (TYPE_NAME (gnu_type)) == exception_data_name_id)
644           gnu_type = except_type_node;
645
646         /* For a debug renaming declaration, build a debug-only entity.  */
647         if (Present (Debug_Renaming_Link (gnat_entity)))
648           {
649             /* Force a non-null value to make sure the symbol is retained.  */
650             tree value = build1 (INDIRECT_REF, gnu_type,
651                                  build1 (NOP_EXPR,
652                                          build_pointer_type (gnu_type),
653                                          integer_minus_one_node));
654             gnu_decl = build_decl (input_location,
655                                    VAR_DECL, gnu_entity_name, gnu_type);
656             SET_DECL_VALUE_EXPR (gnu_decl, value);
657             DECL_HAS_VALUE_EXPR_P (gnu_decl) = 1;
658             gnat_pushdecl (gnu_decl, gnat_entity);
659             break;
660           }
661
662         /* If this is a loop variable, its type should be the base type.
663            This is because the code for processing a loop determines whether
664            a normal loop end test can be done by comparing the bounds of the
665            loop against those of the base type, which is presumed to be the
666            size used for computation.  But this is not correct when the size
667            of the subtype is smaller than the type.  */
668         if (kind == E_Loop_Parameter)
669           gnu_type = get_base_type (gnu_type);
670
671         /* Reject non-renamed objects whose type is an unconstrained array or
672            any object whose type is a dummy type or void.  */
673         if ((TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE
674              && No (Renamed_Object (gnat_entity)))
675             || TYPE_IS_DUMMY_P (gnu_type)
676             || TREE_CODE (gnu_type) == VOID_TYPE)
677           {
678             gcc_assert (type_annotate_only);
679             if (this_global)
680               force_global--;
681             return error_mark_node;
682           }
683
684         /* If an alignment is specified, use it if valid.  Note that exceptions
685            are objects but don't have an alignment.  We must do this before we
686            validate the size, since the alignment can affect the size.  */
687         if (kind != E_Exception && Known_Alignment (gnat_entity))
688           {
689             gcc_assert (Present (Alignment (gnat_entity)));
690
691             align = validate_alignment (Alignment (gnat_entity), gnat_entity,
692                                         TYPE_ALIGN (gnu_type));
693
694             /* No point in changing the type if there is an address clause
695                as the final type of the object will be a reference type.  */
696             if (Present (Address_Clause (gnat_entity)))
697               align = 0;
698             else
699               {
700                 tree orig_type = gnu_type;
701
702                 gnu_type
703                   = maybe_pad_type (gnu_type, NULL_TREE, align, gnat_entity,
704                                     false, false, definition, true);
705
706                 /* If a padding record was made, declare it now since it will
707                    never be declared otherwise.  This is necessary to ensure
708                    that its subtrees are properly marked.  */
709                 if (gnu_type != orig_type && !DECL_P (TYPE_NAME (gnu_type)))
710                   create_type_decl (TYPE_NAME (gnu_type), gnu_type, true,
711                                     debug_info_p, gnat_entity);
712               }
713           }
714
715         /* If we are defining the object, see if it has a Size and validate it
716            if so.  If we are not defining the object and a Size clause applies,
717            simply retrieve the value.  We don't want to ignore the clause and
718            it is expected to have been validated already.  Then get the new
719            type, if any.  */
720         if (definition)
721           gnu_size = validate_size (Esize (gnat_entity), gnu_type,
722                                     gnat_entity, VAR_DECL, false,
723                                     Has_Size_Clause (gnat_entity));
724         else if (Has_Size_Clause (gnat_entity))
725           gnu_size = UI_To_gnu (Esize (gnat_entity), bitsizetype);
726
727         if (gnu_size)
728           {
729             gnu_type
730               = make_type_from_size (gnu_type, gnu_size,
731                                      Has_Biased_Representation (gnat_entity));
732
733             if (operand_equal_p (TYPE_SIZE (gnu_type), gnu_size, 0))
734               gnu_size = NULL_TREE;
735           }
736
737         /* If this object has self-referential size, it must be a record with
738            a default discriminant.  We are supposed to allocate an object of
739            the maximum size in this case, unless it is a constant with an
740            initializing expression, in which case we can get the size from
741            that.  Note that the resulting size may still be a variable, so
742            this may end up with an indirect allocation.  */
743         if (No (Renamed_Object (gnat_entity))
744             && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
745           {
746             if (gnu_expr && kind == E_Constant)
747               {
748                 tree size = TYPE_SIZE (TREE_TYPE (gnu_expr));
749                 if (CONTAINS_PLACEHOLDER_P (size))
750                   {
751                     /* If the initializing expression is itself a constant,
752                        despite having a nominal type with self-referential
753                        size, we can get the size directly from it.  */
754                     if (TREE_CODE (gnu_expr) == COMPONENT_REF
755                         && TYPE_IS_PADDING_P
756                            (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
757                         && TREE_CODE (TREE_OPERAND (gnu_expr, 0)) == VAR_DECL
758                         && (TREE_READONLY (TREE_OPERAND (gnu_expr, 0))
759                             || DECL_READONLY_ONCE_ELAB
760                                (TREE_OPERAND (gnu_expr, 0))))
761                       gnu_size = DECL_SIZE (TREE_OPERAND (gnu_expr, 0));
762                     else
763                       gnu_size
764                         = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, gnu_expr);
765                   }
766                 else
767                   gnu_size = size;
768               }
769             /* We may have no GNU_EXPR because No_Initialization is
770                set even though there's an Expression.  */
771             else if (kind == E_Constant
772                      && (Nkind (Declaration_Node (gnat_entity))
773                          == N_Object_Declaration)
774                      && Present (Expression (Declaration_Node (gnat_entity))))
775               gnu_size
776                 = TYPE_SIZE (gnat_to_gnu_type
777                              (Etype
778                               (Expression (Declaration_Node (gnat_entity)))));
779             else
780               {
781                 gnu_size = max_size (TYPE_SIZE (gnu_type), true);
782                 mutable_p = true;
783               }
784
785             /* If we are at global level and the size isn't constant, call
786                elaborate_expression_1 to make a variable for it rather than
787                calculating it each time.  */
788             if (global_bindings_p () && !TREE_CONSTANT (gnu_size))
789               gnu_size = elaborate_expression_1 (gnu_size, gnat_entity,
790                                                  get_identifier ("SIZE"),
791                                                  definition, false);
792           }
793
794         /* If the size is zero byte, make it one byte since some linkers have
795            troubles with zero-sized objects.  If the object will have a
796            template, that will make it nonzero so don't bother.  Also avoid
797            doing that for an object renaming or an object with an address
798            clause, as we would lose useful information on the view size
799            (e.g. for null array slices) and we are not allocating the object
800            here anyway.  */
801         if (((gnu_size
802               && integer_zerop (gnu_size)
803               && !TREE_OVERFLOW (gnu_size))
804              || (TYPE_SIZE (gnu_type)
805                  && integer_zerop (TYPE_SIZE (gnu_type))
806                  && !TREE_OVERFLOW (TYPE_SIZE (gnu_type))))
807             && !Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
808             && No (Renamed_Object (gnat_entity))
809             && No (Address_Clause (gnat_entity)))
810           gnu_size = bitsize_unit_node;
811
812         /* If this is an object with no specified size and alignment, and
813            if either it is atomic or we are not optimizing alignment for
814            space and it is composite and not an exception, an Out parameter
815            or a reference to another object, and the size of its type is a
816            constant, set the alignment to the smallest one which is not
817            smaller than the size, with an appropriate cap.  */
818         if (!gnu_size && align == 0
819             && (Is_Atomic_Or_VFA (gnat_entity)
820                 || (!Optimize_Alignment_Space (gnat_entity)
821                     && kind != E_Exception
822                     && kind != E_Out_Parameter
823                     && Is_Composite_Type (Etype (gnat_entity))
824                     && !Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
825                     && !Is_Exported (gnat_entity)
826                     && !imported_p
827                     && No (Renamed_Object (gnat_entity))
828                     && No (Address_Clause (gnat_entity))))
829             && TREE_CODE (TYPE_SIZE (gnu_type)) == INTEGER_CST)
830           {
831             unsigned int size_cap, align_cap;
832
833             /* No point in promoting the alignment if this doesn't prevent
834                BLKmode access to the object, in particular block copy, as
835                this will for example disable the NRV optimization for it.
836                No point in jumping through all the hoops needed in order
837                to support BIGGEST_ALIGNMENT if we don't really have to.
838                So we cap to the smallest alignment that corresponds to
839                a known efficient memory access pattern of the target.  */
840             if (Is_Atomic_Or_VFA (gnat_entity))
841               {
842                 size_cap = UINT_MAX;
843                 align_cap = BIGGEST_ALIGNMENT;
844               }
845             else
846               {
847                 size_cap = MAX_FIXED_MODE_SIZE;
848                 align_cap = get_mode_alignment (ptr_mode);
849               }
850
851             if (!tree_fits_uhwi_p (TYPE_SIZE (gnu_type))
852                 || compare_tree_int (TYPE_SIZE (gnu_type), size_cap) > 0)
853               align = 0;
854             else if (compare_tree_int (TYPE_SIZE (gnu_type), align_cap) > 0)
855               align = align_cap;
856             else
857               align = ceil_pow2 (tree_to_uhwi (TYPE_SIZE (gnu_type)));
858
859             /* But make sure not to under-align the object.  */
860             if (align <= TYPE_ALIGN (gnu_type))
861               align = 0;
862
863             /* And honor the minimum valid atomic alignment, if any.  */
864 #ifdef MINIMUM_ATOMIC_ALIGNMENT
865             else if (align < MINIMUM_ATOMIC_ALIGNMENT)
866               align = MINIMUM_ATOMIC_ALIGNMENT;
867 #endif
868           }
869
870         /* If the object is set to have atomic components, find the component
871            type and validate it.
872
873            ??? Note that we ignore Has_Volatile_Components on objects; it's
874            not at all clear what to do in that case.  */
875         if (Has_Atomic_Components (gnat_entity))
876           {
877             tree gnu_inner = (TREE_CODE (gnu_type) == ARRAY_TYPE
878                               ? TREE_TYPE (gnu_type) : gnu_type);
879
880             while (TREE_CODE (gnu_inner) == ARRAY_TYPE
881                    && TYPE_MULTI_ARRAY_P (gnu_inner))
882               gnu_inner = TREE_TYPE (gnu_inner);
883
884             check_ok_for_atomic_type (gnu_inner, gnat_entity, true);
885           }
886
887         /* Now check if the type of the object allows atomic access.  Note
888            that we must test the type, even if this object has size and
889            alignment to allow such access, because we will be going inside
890            the padded record to assign to the object.  We could fix this by
891            always copying via an intermediate value, but it's not clear it's
892            worth the effort.  */
893         if (Is_Atomic_Or_VFA (gnat_entity))
894           check_ok_for_atomic_type (gnu_type, gnat_entity, false);
895
896         /* If this is an aliased object with an unconstrained nominal subtype,
897            make a type that includes the template.  */
898         if (Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
899             && Is_Array_Type (Underlying_Type (Etype (gnat_entity)))
900             && !type_annotate_only)
901           {
902             tree gnu_array
903               = gnat_to_gnu_type (Base_Type (Etype (gnat_entity)));
904             gnu_type
905               = build_unc_object_type_from_ptr (TREE_TYPE (gnu_array),
906                                                 gnu_type,
907                                                 concat_name (gnu_entity_name,
908                                                              "UNC"),
909                                                 debug_info_p);
910           }
911
912         /* ??? If this is an object of CW type initialized to a value, try to
913            ensure that the object is sufficient aligned for this value, but
914            without pessimizing the allocation.  This is a kludge necessary
915            because we don't support dynamic alignment.  */
916         if (align == 0
917             && Ekind (Etype (gnat_entity)) == E_Class_Wide_Subtype
918             && No (Renamed_Object (gnat_entity))
919             && No (Address_Clause (gnat_entity)))
920           align = get_target_system_allocator_alignment () * BITS_PER_UNIT;
921
922 #ifdef MINIMUM_ATOMIC_ALIGNMENT
923         /* If the size is a constant and no alignment is specified, force
924            the alignment to be the minimum valid atomic alignment.  The
925            restriction on constant size avoids problems with variable-size
926            temporaries; if the size is variable, there's no issue with
927            atomic access.  Also don't do this for a constant, since it isn't
928            necessary and can interfere with constant replacement.  Finally,
929            do not do it for Out parameters since that creates an
930            size inconsistency with In parameters.  */
931         if (align == 0
932             && MINIMUM_ATOMIC_ALIGNMENT > TYPE_ALIGN (gnu_type)
933             && !FLOAT_TYPE_P (gnu_type)
934             && !const_flag && No (Renamed_Object (gnat_entity))
935             && !imported_p && No (Address_Clause (gnat_entity))
936             && kind != E_Out_Parameter
937             && (gnu_size ? TREE_CODE (gnu_size) == INTEGER_CST
938                 : TREE_CODE (TYPE_SIZE (gnu_type)) == INTEGER_CST))
939           align = MINIMUM_ATOMIC_ALIGNMENT;
940 #endif
941
942         /* Make a new type with the desired size and alignment, if needed.
943            But do not take into account alignment promotions to compute the
944            size of the object.  */
945         gnu_object_size = gnu_size ? gnu_size : TYPE_SIZE (gnu_type);
946         if (gnu_size || align > 0)
947           {
948             tree orig_type = gnu_type;
949
950             gnu_type = maybe_pad_type (gnu_type, gnu_size, align, gnat_entity,
951                                        false, false, definition, true);
952
953             /* If a padding record was made, declare it now since it will
954                never be declared otherwise.  This is necessary to ensure
955                that its subtrees are properly marked.  */
956             if (gnu_type != orig_type && !DECL_P (TYPE_NAME (gnu_type)))
957               create_type_decl (TYPE_NAME (gnu_type), gnu_type, true,
958                                 debug_info_p, gnat_entity);
959           }
960
961         /* If this is a renaming, avoid as much as possible to create a new
962            object.  However, in several cases, creating it is required.
963            This processing needs to be applied to the raw expression so
964            as to make it more likely to rename the underlying object.  */
965         if (Present (Renamed_Object (gnat_entity)))
966           {
967             bool create_normal_object = false;
968
969             /* If the renamed object had padding, strip off the reference
970                to the inner object and reset our type.  */
971             if ((TREE_CODE (gnu_expr) == COMPONENT_REF
972                  && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
973                 /* Strip useless conversions around the object.  */
974                 || gnat_useless_type_conversion (gnu_expr))
975               {
976                 gnu_expr = TREE_OPERAND (gnu_expr, 0);
977                 gnu_type = TREE_TYPE (gnu_expr);
978               }
979
980             /* Or else, if the renamed object has an unconstrained type with
981                default discriminant, use the padded type.  */
982             else if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_expr))
983                      && TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_expr)))
984                         == gnu_type
985                      && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
986               gnu_type = TREE_TYPE (gnu_expr);
987
988             /* Case 1: If this is a constant renaming stemming from a function
989                call, treat it as a normal object whose initial value is what is
990                being renamed.  RM 3.3 says that the result of evaluating a
991                function call is a constant object.  Treat constant literals
992                the same way.  As a consequence, it can be the inner object of
993                a constant renaming.  In this case, the renaming must be fully
994                instantiated, i.e. it cannot be a mere reference to (part of) an
995                existing object.  */
996             if (const_flag)
997               {
998                 tree inner_object = gnu_expr;
999                 while (handled_component_p (inner_object))
1000                   inner_object = TREE_OPERAND (inner_object, 0);
1001                 if (TREE_CODE (inner_object) == CALL_EXPR
1002                     || CONSTANT_CLASS_P (inner_object))
1003                   create_normal_object = true;
1004               }
1005
1006             /* Otherwise, see if we can proceed with a stabilized version of
1007                the renamed entity or if we need to make a new object.  */
1008             if (!create_normal_object)
1009               {
1010                 tree maybe_stable_expr = NULL_TREE;
1011                 bool stable = false;
1012
1013                 /* Case 2: If the renaming entity need not be materialized and
1014                    the renamed expression is something we can stabilize, use
1015                    that for the renaming.  At the global level, we can only do
1016                    this if we know no SAVE_EXPRs need be made, because the
1017                    expression we return might be used in arbitrary conditional
1018                    branches so we must force the evaluation of the SAVE_EXPRs
1019                    immediately and this requires a proper function context.
1020                    Note that an external constant is at the global level.  */
1021                 if (!Materialize_Entity (gnat_entity)
1022                     && (!((!definition && kind == E_Constant)
1023                           || global_bindings_p ())
1024                         || (staticp (gnu_expr)
1025                             && !TREE_SIDE_EFFECTS (gnu_expr))))
1026                   {
1027                     maybe_stable_expr
1028                       = gnat_stabilize_reference (gnu_expr, true, &stable);
1029
1030                     if (stable)
1031                       {
1032                         /* ??? No DECL_EXPR is created so we need to mark
1033                            the expression manually lest it is shared.  */
1034                         if ((!definition && kind == E_Constant)
1035                             || global_bindings_p ())
1036                           MARK_VISITED (maybe_stable_expr);
1037                         gnu_decl = maybe_stable_expr;
1038                         save_gnu_tree (gnat_entity, gnu_decl, true);
1039                         saved = true;
1040                         annotate_object (gnat_entity, gnu_type, NULL_TREE,
1041                                          false);
1042                         /* This assertion will fail if the renamed object
1043                            isn't aligned enough as to make it possible to
1044                            honor the alignment set on the renaming.  */
1045                         if (align)
1046                           {
1047                             unsigned int renamed_align
1048                               = DECL_P (gnu_decl)
1049                                 ? DECL_ALIGN (gnu_decl)
1050                                 : TYPE_ALIGN (TREE_TYPE (gnu_decl));
1051                             gcc_assert (renamed_align >= align);
1052                           }
1053                         break;
1054                       }
1055
1056                     /* The stabilization failed.  Keep maybe_stable_expr
1057                        untouched here to let the pointer case below know
1058                        about that failure.  */
1059                   }
1060
1061                 /* Case 3: Make this into a constant pointer to the object we
1062                    are to rename and attach the object to the pointer if it is
1063                    something we can stabilize.
1064
1065                    From the proper scope, attached objects will be referenced
1066                    directly instead of indirectly via the pointer to avoid
1067                    subtle aliasing problems with non-addressable entities.
1068                    They have to be stable because we must not evaluate the
1069                    variables in the expression every time the renaming is used.
1070                    The pointer is called a "renaming" pointer in this case.
1071
1072                    In the rare cases where we cannot stabilize the renamed
1073                    object, we just make a "bare" pointer and the renamed
1074                    object will always be accessed indirectly through it.
1075
1076                    Note that we need to preserve the volatility of the renamed
1077                    object through the indirection.  */
1078                 if (TREE_THIS_VOLATILE (gnu_expr) && !TYPE_VOLATILE (gnu_type))
1079                   gnu_type
1080                     = change_qualified_type (gnu_type, TYPE_QUAL_VOLATILE);
1081                 gnu_type = build_reference_type (gnu_type);
1082                 inner_const_flag = TREE_READONLY (gnu_expr);
1083                 const_flag = true;
1084
1085                 /* If the previous attempt at stabilizing failed, there is
1086                    no point in trying again and we reuse the result without
1087                    attaching it to the pointer.  In this case it will only
1088                    be used as the initializing expression of the pointer and
1089                    thus needs no special treatment with regard to multiple
1090                    evaluations.
1091
1092                    Otherwise, try to stabilize and attach the expression to
1093                    the pointer if the stabilization succeeds.
1094
1095                    Note that this might introduce SAVE_EXPRs and we don't
1096                    check whether we are at the global level or not.  This
1097                    is fine since we are building a pointer initializer and
1098                    neither the pointer nor the initializing expression can
1099                    be accessed before the pointer elaboration has taken
1100                    place in a correct program.
1101
1102                    These SAVE_EXPRs will be evaluated at the right place
1103                    by either the evaluation of the initializer for the
1104                    non-global case or the elaboration code for the global
1105                    case, and will be attached to the elaboration procedure
1106                    in the latter case.  */
1107                 if (!maybe_stable_expr)
1108                   {
1109                     maybe_stable_expr
1110                       = gnat_stabilize_reference (gnu_expr, true, &stable);
1111
1112                     if (stable)
1113                       renamed_obj = maybe_stable_expr;
1114                   }
1115
1116                 if (type_annotate_only
1117                     && TREE_CODE (maybe_stable_expr) == ERROR_MARK)
1118                   gnu_expr = NULL_TREE;
1119                 else
1120                   gnu_expr
1121                     = build_unary_op (ADDR_EXPR, gnu_type, maybe_stable_expr);
1122
1123                 gnu_size = NULL_TREE;
1124                 used_by_ref = true;
1125               }
1126           }
1127
1128         /* Make a volatile version of this object's type if we are to make
1129            the object volatile.  We also interpret 13.3(19) conservatively
1130            and disallow any optimizations for such a non-constant object.  */
1131         if ((Treat_As_Volatile (gnat_entity)
1132              || (!const_flag
1133                  && gnu_type != except_type_node
1134                  && (Is_Exported (gnat_entity)
1135                      || imported_p
1136                      || Present (Address_Clause (gnat_entity)))))
1137             && !TYPE_VOLATILE (gnu_type))
1138           {
1139             const int quals
1140               = TYPE_QUAL_VOLATILE
1141                 | (Is_Atomic_Or_VFA (gnat_entity) ? TYPE_QUAL_ATOMIC : 0);
1142             gnu_type = change_qualified_type (gnu_type, quals);
1143           }
1144
1145         /* If we are defining an aliased object whose nominal subtype is
1146            unconstrained, the object is a record that contains both the
1147            template and the object.  If there is an initializer, it will
1148            have already been converted to the right type, but we need to
1149            create the template if there is no initializer.  */
1150         if (definition
1151             && !gnu_expr
1152             && TREE_CODE (gnu_type) == RECORD_TYPE
1153             && (TYPE_CONTAINS_TEMPLATE_P (gnu_type)
1154                 /* Beware that padding might have been introduced above.  */
1155                 || (TYPE_PADDING_P (gnu_type)
1156                     && TREE_CODE (TREE_TYPE (TYPE_FIELDS (gnu_type)))
1157                        == RECORD_TYPE
1158                     && TYPE_CONTAINS_TEMPLATE_P
1159                        (TREE_TYPE (TYPE_FIELDS (gnu_type))))))
1160           {
1161             tree template_field
1162               = TYPE_PADDING_P (gnu_type)
1163                 ? TYPE_FIELDS (TREE_TYPE (TYPE_FIELDS (gnu_type)))
1164                 : TYPE_FIELDS (gnu_type);
1165             vec<constructor_elt, va_gc> *v;
1166             vec_alloc (v, 1);
1167             tree t = build_template (TREE_TYPE (template_field),
1168                                      TREE_TYPE (DECL_CHAIN (template_field)),
1169                                      NULL_TREE);
1170             CONSTRUCTOR_APPEND_ELT (v, template_field, t);
1171             gnu_expr = gnat_build_constructor (gnu_type, v);
1172           }
1173
1174         /* Convert the expression to the type of the object except in the
1175            case where the object's type is unconstrained or the object's type
1176            is a padded record whose field is of self-referential size.  In
1177            the former case, converting will generate unnecessary evaluations
1178            of the CONSTRUCTOR to compute the size and in the latter case, we
1179            want to only copy the actual data.  Also don't convert to a record
1180            type with a variant part from a record type without one, to keep
1181            the object simpler.  */
1182         if (gnu_expr
1183             && TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE
1184             && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))
1185             && !(TYPE_IS_PADDING_P (gnu_type)
1186                  && CONTAINS_PLACEHOLDER_P
1187                     (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS (gnu_type)))))
1188             && !(TREE_CODE (gnu_type) == RECORD_TYPE
1189                  && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
1190                  && get_variant_part (gnu_type) != NULL_TREE
1191                  && get_variant_part (TREE_TYPE (gnu_expr)) == NULL_TREE))
1192           gnu_expr = convert (gnu_type, gnu_expr);
1193
1194         /* If this is a pointer that doesn't have an initializing expression,
1195            initialize it to NULL, unless the object is imported.  */
1196         if (definition
1197             && (POINTER_TYPE_P (gnu_type) || TYPE_IS_FAT_POINTER_P (gnu_type))
1198             && !gnu_expr
1199             && !Is_Imported (gnat_entity))
1200           gnu_expr = integer_zero_node;
1201
1202         /* If we are defining the object and it has an Address clause, we must
1203            either get the address expression from the saved GCC tree for the
1204            object if it has a Freeze node, or elaborate the address expression
1205            here since the front-end has guaranteed that the elaboration has no
1206            effects in this case.  */
1207         if (definition && Present (Address_Clause (gnat_entity)))
1208           {
1209             Node_Id gnat_expr = Expression (Address_Clause (gnat_entity));
1210             tree gnu_address
1211               = present_gnu_tree (gnat_entity)
1212                 ? get_gnu_tree (gnat_entity) : gnat_to_gnu (gnat_expr);
1213
1214             save_gnu_tree (gnat_entity, NULL_TREE, false);
1215
1216             /* Ignore the size.  It's either meaningless or was handled
1217                above.  */
1218             gnu_size = NULL_TREE;
1219             /* Convert the type of the object to a reference type that can
1220                alias everything as per 13.3(19).  */
1221             gnu_type
1222               = build_reference_type_for_mode (gnu_type, ptr_mode, true);
1223             gnu_address = convert (gnu_type, gnu_address);
1224             used_by_ref = true;
1225             const_flag
1226               = !Is_Public (gnat_entity)
1227                 || compile_time_known_address_p (gnat_expr);
1228
1229             /* If this is a deferred constant, the initializer is attached to
1230                the full view.  */
1231             if (kind == E_Constant && Present (Full_View (gnat_entity)))
1232               gnu_expr
1233                 = gnat_to_gnu
1234                     (Expression (Declaration_Node (Full_View (gnat_entity))));
1235
1236             /* If we don't have an initializing expression for the underlying
1237                variable, the initializing expression for the pointer is the
1238                specified address.  Otherwise, we have to make a COMPOUND_EXPR
1239                to assign both the address and the initial value.  */
1240             if (!gnu_expr)
1241               gnu_expr = gnu_address;
1242             else
1243               gnu_expr
1244                 = build2 (COMPOUND_EXPR, gnu_type,
1245                           build_binary_op
1246                           (MODIFY_EXPR, NULL_TREE,
1247                            build_unary_op (INDIRECT_REF, NULL_TREE,
1248                                            gnu_address),
1249                            gnu_expr),
1250                           gnu_address);
1251           }
1252
1253         /* If it has an address clause and we are not defining it, mark it
1254            as an indirect object.  Likewise for Stdcall objects that are
1255            imported.  */
1256         if ((!definition && Present (Address_Clause (gnat_entity)))
1257             || (Is_Imported (gnat_entity)
1258                 && Has_Stdcall_Convention (gnat_entity)))
1259           {
1260             /* Convert the type of the object to a reference type that can
1261                alias everything as per 13.3(19).  */
1262             gnu_type
1263               = build_reference_type_for_mode (gnu_type, ptr_mode, true);
1264             gnu_size = NULL_TREE;
1265
1266             /* No point in taking the address of an initializing expression
1267                that isn't going to be used.  */
1268             gnu_expr = NULL_TREE;
1269
1270             /* If it has an address clause whose value is known at compile
1271                time, make the object a CONST_DECL.  This will avoid a
1272                useless dereference.  */
1273             if (Present (Address_Clause (gnat_entity)))
1274               {
1275                 Node_Id gnat_address
1276                   = Expression (Address_Clause (gnat_entity));
1277
1278                 if (compile_time_known_address_p (gnat_address))
1279                   {
1280                     gnu_expr = gnat_to_gnu (gnat_address);
1281                     const_flag = true;
1282                   }
1283               }
1284
1285             used_by_ref = true;
1286           }
1287
1288         /* If we are at top level and this object is of variable size,
1289            make the actual type a hidden pointer to the real type and
1290            make the initializer be a memory allocation and initialization.
1291            Likewise for objects we aren't defining (presumed to be
1292            external references from other packages), but there we do
1293            not set up an initialization.
1294
1295            If the object's size overflows, make an allocator too, so that
1296            Storage_Error gets raised.  Note that we will never free
1297            such memory, so we presume it never will get allocated.  */
1298         if (!allocatable_size_p (TYPE_SIZE_UNIT (gnu_type),
1299                                  global_bindings_p ()
1300                                  || !definition
1301                                  || static_p)
1302             || (gnu_size
1303                 && !allocatable_size_p (convert (sizetype,
1304                                                  size_binop
1305                                                  (CEIL_DIV_EXPR, gnu_size,
1306                                                   bitsize_unit_node)),
1307                                         global_bindings_p ()
1308                                         || !definition
1309                                         || static_p)))
1310           {
1311             gnu_type = build_reference_type (gnu_type);
1312             gnu_size = NULL_TREE;
1313             used_by_ref = true;
1314
1315             /* In case this was a aliased object whose nominal subtype is
1316                unconstrained, the pointer above will be a thin pointer and
1317                build_allocator will automatically make the template.
1318
1319                If we have a template initializer only (that we made above),
1320                pretend there is none and rely on what build_allocator creates
1321                again anyway.  Otherwise (if we have a full initializer), get
1322                the data part and feed that to build_allocator.
1323
1324                If we are elaborating a mutable object, tell build_allocator to
1325                ignore a possibly simpler size from the initializer, if any, as
1326                we must allocate the maximum possible size in this case.  */
1327             if (definition && !imported_p)
1328               {
1329                 tree gnu_alloc_type = TREE_TYPE (gnu_type);
1330
1331                 if (TREE_CODE (gnu_alloc_type) == RECORD_TYPE
1332                     && TYPE_CONTAINS_TEMPLATE_P (gnu_alloc_type))
1333                   {
1334                     gnu_alloc_type
1335                       = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_alloc_type)));
1336
1337                     if (TREE_CODE (gnu_expr) == CONSTRUCTOR
1338                         && 1 == vec_safe_length (CONSTRUCTOR_ELTS (gnu_expr)))
1339                       gnu_expr = 0;
1340                     else
1341                       gnu_expr
1342                         = build_component_ref
1343                             (gnu_expr, NULL_TREE,
1344                              DECL_CHAIN (TYPE_FIELDS (TREE_TYPE (gnu_expr))),
1345                              false);
1346                   }
1347
1348                 if (TREE_CODE (TYPE_SIZE_UNIT (gnu_alloc_type)) == INTEGER_CST
1349                     && !valid_constant_size_p (TYPE_SIZE_UNIT (gnu_alloc_type)))
1350                   post_error ("?`Storage_Error` will be raised at run time!",
1351                               gnat_entity);
1352
1353                 gnu_expr
1354                   = build_allocator (gnu_alloc_type, gnu_expr, gnu_type,
1355                                      Empty, Empty, gnat_entity, mutable_p);
1356                 const_flag = true;
1357               }
1358             else
1359               {
1360                 gnu_expr = NULL_TREE;
1361                 const_flag = false;
1362               }
1363           }
1364
1365         /* If this object would go into the stack and has an alignment larger
1366            than the largest stack alignment the back-end can honor, resort to
1367            a variable of "aligning type".  */
1368         if (!global_bindings_p () && !static_p && definition
1369             && !imported_p && TYPE_ALIGN (gnu_type) > BIGGEST_ALIGNMENT)
1370           {
1371             /* Create the new variable.  No need for extra room before the
1372                aligned field as this is in automatic storage.  */
1373             tree gnu_new_type
1374               = make_aligning_type (gnu_type, TYPE_ALIGN (gnu_type),
1375                                     TYPE_SIZE_UNIT (gnu_type),
1376                                     BIGGEST_ALIGNMENT, 0, gnat_entity);
1377             tree gnu_new_var
1378               = create_var_decl (create_concat_name (gnat_entity, "ALIGN"),
1379                                  NULL_TREE, gnu_new_type, NULL_TREE, false,
1380                                  false, false, false, NULL, gnat_entity);
1381
1382             /* Initialize the aligned field if we have an initializer.  */
1383             if (gnu_expr)
1384               add_stmt_with_node
1385                 (build_binary_op (MODIFY_EXPR, NULL_TREE,
1386                                   build_component_ref
1387                                   (gnu_new_var, NULL_TREE,
1388                                    TYPE_FIELDS (gnu_new_type), false),
1389                                   gnu_expr),
1390                  gnat_entity);
1391
1392             /* And setup this entity as a reference to the aligned field.  */
1393             gnu_type = build_reference_type (gnu_type);
1394             gnu_expr
1395               = build_unary_op
1396                 (ADDR_EXPR, gnu_type,
1397                  build_component_ref (gnu_new_var, NULL_TREE,
1398                                       TYPE_FIELDS (gnu_new_type), false));
1399
1400             gnu_size = NULL_TREE;
1401             used_by_ref = true;
1402             const_flag = true;
1403           }
1404
1405         /* If this is an aliased object with an unconstrained nominal subtype,
1406            we make its type a thin reference, i.e. the reference counterpart
1407            of a thin pointer, so that it points to the array part.  This is
1408            aimed at making it easier for the debugger to decode the object.
1409            Note that we have to do that this late because of the couple of
1410            allocation adjustments that might be made just above.  */
1411         if (Is_Constr_Subt_For_UN_Aliased (Etype (gnat_entity))
1412             && Is_Array_Type (Underlying_Type (Etype (gnat_entity)))
1413             && !type_annotate_only)
1414           {
1415             tree gnu_array
1416               = gnat_to_gnu_type (Base_Type (Etype (gnat_entity)));
1417
1418             /* In case the object with the template has already been allocated
1419                just above, we have nothing to do here.  */
1420             if (!TYPE_IS_THIN_POINTER_P (gnu_type))
1421               {
1422                 tree gnu_unc_var
1423                    = create_var_decl (concat_name (gnu_entity_name, "UNC"),
1424                                       NULL_TREE, gnu_type, gnu_expr,
1425                                       const_flag, Is_Public (gnat_entity),
1426                                       imported_p || !definition, static_p,
1427                                       NULL, gnat_entity);
1428                 gnu_expr
1429                   = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_unc_var);
1430                 TREE_CONSTANT (gnu_expr) = 1;
1431
1432                 gnu_size = NULL_TREE;
1433                 used_by_ref = true;
1434                 inner_const_flag = TREE_READONLY (gnu_unc_var);
1435                 const_flag = true;
1436               }
1437
1438             gnu_type
1439               = build_reference_type (TYPE_OBJECT_RECORD_TYPE (gnu_array));
1440           }
1441
1442         if (const_flag)
1443           gnu_type = change_qualified_type (gnu_type, TYPE_QUAL_CONST);
1444
1445         /* Convert the expression to the type of the object except in the
1446            case where the object's type is unconstrained or the object's type
1447            is a padded record whose field is of self-referential size.  In
1448            the former case, converting will generate unnecessary evaluations
1449            of the CONSTRUCTOR to compute the size and in the latter case, we
1450            want to only copy the actual data.  Also don't convert to a record
1451            type with a variant part from a record type without one, to keep
1452            the object simpler.  */
1453         if (gnu_expr
1454             && TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE
1455             && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))
1456             && !(TYPE_IS_PADDING_P (gnu_type)
1457                  && CONTAINS_PLACEHOLDER_P
1458                     (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS (gnu_type)))))
1459             && !(TREE_CODE (gnu_type) == RECORD_TYPE
1460                  && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
1461                  && get_variant_part (gnu_type) != NULL_TREE
1462                  && get_variant_part (TREE_TYPE (gnu_expr)) == NULL_TREE))
1463           gnu_expr = convert (gnu_type, gnu_expr);
1464
1465         /* If this name is external or a name was specified, use it, but don't
1466            use the Interface_Name with an address clause (see cd30005).  */
1467         if ((Present (Interface_Name (gnat_entity))
1468              && No (Address_Clause (gnat_entity)))
1469             || (Is_Public (gnat_entity)
1470                 && (!Is_Imported (gnat_entity) || Is_Exported (gnat_entity))))
1471           gnu_ext_name = create_concat_name (gnat_entity, NULL);
1472
1473         /* If this is an aggregate constant initialized to a constant, force it
1474            to be statically allocated.  This saves an initialization copy.  */
1475         if (!static_p
1476             && const_flag
1477             && gnu_expr && TREE_CONSTANT (gnu_expr)
1478             && AGGREGATE_TYPE_P (gnu_type)
1479             && tree_fits_uhwi_p (TYPE_SIZE_UNIT (gnu_type))
1480             && !(TYPE_IS_PADDING_P (gnu_type)
1481                  && !tree_fits_uhwi_p (TYPE_SIZE_UNIT
1482                                        (TREE_TYPE (TYPE_FIELDS (gnu_type))))))
1483           static_p = true;
1484
1485         /* Deal with a pragma Linker_Section on a constant or variable.  */
1486         if ((kind == E_Constant || kind == E_Variable)
1487             && Present (Linker_Section_Pragma (gnat_entity)))
1488           prepend_one_attribute_pragma (&attr_list,
1489                                         Linker_Section_Pragma (gnat_entity));
1490
1491         /* Now create the variable or the constant and set various flags.  */
1492         gnu_decl
1493           = create_var_decl_1 (gnu_entity_name, gnu_ext_name, gnu_type,
1494                                gnu_expr, const_flag, Is_Public (gnat_entity),
1495                                imported_p || !definition, static_p,
1496                                !renamed_obj, attr_list, gnat_entity);
1497         DECL_BY_REF_P (gnu_decl) = used_by_ref;
1498         DECL_POINTS_TO_READONLY_P (gnu_decl) = used_by_ref && inner_const_flag;
1499         DECL_CAN_NEVER_BE_NULL_P (gnu_decl) = Can_Never_Be_Null (gnat_entity);
1500
1501         /* If we are defining an Out parameter and optimization isn't enabled,
1502            create a fake PARM_DECL for debugging purposes and make it point to
1503            the VAR_DECL.  Suppress debug info for the latter but make sure it
1504            will live in memory so that it can be accessed from within the
1505            debugger through the PARM_DECL.  */
1506         if (kind == E_Out_Parameter
1507             && definition
1508             && debug_info_p
1509             && !optimize
1510             && !flag_generate_lto)
1511           {
1512             tree param = create_param_decl (gnu_entity_name, gnu_type, false);
1513             gnat_pushdecl (param, gnat_entity);
1514             SET_DECL_VALUE_EXPR (param, gnu_decl);
1515             DECL_HAS_VALUE_EXPR_P (param) = 1;
1516             DECL_IGNORED_P (gnu_decl) = 1;
1517             TREE_ADDRESSABLE (gnu_decl) = 1;
1518           }
1519
1520         /* If this is a loop parameter, set the corresponding flag.  */
1521         else if (kind == E_Loop_Parameter)
1522           DECL_LOOP_PARM_P (gnu_decl) = 1;
1523
1524         /* If this is a renaming pointer, attach the renamed object to it and
1525            register it if we are at the global level and the renamed object
1526            is a non-constant reference.  Note that an external constant is at
1527            the global level.  */
1528         if (renamed_obj)
1529           {
1530             SET_DECL_RENAMED_OBJECT (gnu_decl, renamed_obj);
1531
1532             if (((!definition && kind == E_Constant) || global_bindings_p ())
1533                 && !gnat_constant_reference_p (renamed_obj))
1534               {
1535                 DECL_GLOBAL_NONCONSTANT_RENAMING_P (gnu_decl) = 1;
1536                 record_global_nonconstant_renaming (gnu_decl);
1537               }
1538           }
1539
1540         /* If this is a constant and we are defining it or it generates a real
1541            symbol at the object level and we are referencing it, we may want
1542            or need to have a true variable to represent it:
1543              - if optimization isn't enabled, for debugging purposes,
1544              - if the constant is public and not overlaid on something else,
1545              - if its address is taken,
1546              - if either itself or its type is aliased.  */
1547         if (TREE_CODE (gnu_decl) == CONST_DECL
1548             && (definition || Sloc (gnat_entity) > Standard_Location)
1549             && ((!optimize && debug_info_p)
1550                 || (Is_Public (gnat_entity)
1551                     && No (Address_Clause (gnat_entity)))
1552                 || Address_Taken (gnat_entity)
1553                 || Is_Aliased (gnat_entity)
1554                 || Is_Aliased (Etype (gnat_entity))))
1555           {
1556             tree gnu_corr_var
1557               = create_true_var_decl (gnu_entity_name, gnu_ext_name, gnu_type,
1558                                       gnu_expr, true, Is_Public (gnat_entity),
1559                                       !definition, static_p, attr_list,
1560                                       gnat_entity);
1561
1562             SET_DECL_CONST_CORRESPONDING_VAR (gnu_decl, gnu_corr_var);
1563
1564             /* As debugging information will be generated for the variable,
1565                do not generate debugging information for the constant.  */
1566             if (debug_info_p)
1567               DECL_IGNORED_P (gnu_decl) = 1;
1568             else
1569               DECL_IGNORED_P (gnu_corr_var) = 1;
1570           }
1571
1572         /* If this is a constant, even if we don't need a true variable, we
1573            may need to avoid returning the initializer in every case.  That
1574            can happen for the address of a (constant) constructor because,
1575            upon dereferencing it, the constructor will be reinjected in the
1576            tree, which may not be valid in every case; see lvalue_required_p
1577            for more details.  */
1578         if (TREE_CODE (gnu_decl) == CONST_DECL)
1579           DECL_CONST_ADDRESS_P (gnu_decl) = constructor_address_p (gnu_expr);
1580
1581         /* If this object is declared in a block that contains a block with an
1582            exception handler, and we aren't using the GCC exception mechanism,
1583            we must force this variable in memory in order to avoid an invalid
1584            optimization.  */
1585         if (Exception_Mechanism != Back_End_Exceptions
1586             && Has_Nested_Block_With_Handler (Scope (gnat_entity)))
1587           TREE_ADDRESSABLE (gnu_decl) = 1;
1588
1589         /* If this is a local variable with non-BLKmode and aggregate type,
1590            and optimization isn't enabled, then force it in memory so that
1591            a register won't be allocated to it with possible subparts left
1592            uninitialized and reaching the register allocator.  */
1593         else if (TREE_CODE (gnu_decl) == VAR_DECL
1594                  && !DECL_EXTERNAL (gnu_decl)
1595                  && !TREE_STATIC (gnu_decl)
1596                  && DECL_MODE (gnu_decl) != BLKmode
1597                  && AGGREGATE_TYPE_P (TREE_TYPE (gnu_decl))
1598                  && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_decl))
1599                  && !optimize)
1600           TREE_ADDRESSABLE (gnu_decl) = 1;
1601
1602         /* If we are defining an object with variable size or an object with
1603            fixed size that will be dynamically allocated, and we are using the
1604            setjmp/longjmp exception mechanism, update the setjmp buffer.  */
1605         if (definition
1606             && Exception_Mechanism == Setjmp_Longjmp
1607             && get_block_jmpbuf_decl ()
1608             && DECL_SIZE_UNIT (gnu_decl)
1609             && (TREE_CODE (DECL_SIZE_UNIT (gnu_decl)) != INTEGER_CST
1610                 || (flag_stack_check == GENERIC_STACK_CHECK
1611                     && compare_tree_int (DECL_SIZE_UNIT (gnu_decl),
1612                                          STACK_CHECK_MAX_VAR_SIZE) > 0)))
1613           add_stmt_with_node (build_call_n_expr
1614                               (update_setjmp_buf_decl, 1,
1615                                build_unary_op (ADDR_EXPR, NULL_TREE,
1616                                                get_block_jmpbuf_decl ())),
1617                               gnat_entity);
1618
1619         /* Back-annotate Esize and Alignment of the object if not already
1620            known.  Note that we pick the values of the type, not those of
1621            the object, to shield ourselves from low-level platform-dependent
1622            adjustments like alignment promotion.  This is both consistent with
1623            all the treatment above, where alignment and size are set on the
1624            type of the object and not on the object directly, and makes it
1625            possible to support all confirming representation clauses.  */
1626         annotate_object (gnat_entity, TREE_TYPE (gnu_decl), gnu_object_size,
1627                          used_by_ref);
1628       }
1629       break;
1630
1631     case E_Void:
1632       /* Return a TYPE_DECL for "void" that we previously made.  */
1633       gnu_decl = TYPE_NAME (void_type_node);
1634       break;
1635
1636     case E_Enumeration_Type:
1637       /* A special case: for the types Character and Wide_Character in
1638          Standard, we do not list all the literals.  So if the literals
1639          are not specified, make this an unsigned integer type.  */
1640       if (No (First_Literal (gnat_entity)))
1641         {
1642           gnu_type = make_unsigned_type (esize);
1643           TYPE_NAME (gnu_type) = gnu_entity_name;
1644
1645           /* Set TYPE_STRING_FLAG for Character and Wide_Character types.
1646              This is needed by the DWARF-2 back-end to distinguish between
1647              unsigned integer types and character types.  */
1648           TYPE_STRING_FLAG (gnu_type) = 1;
1649         }
1650       else
1651         {
1652           /* We have a list of enumeral constants in First_Literal.  We make a
1653              CONST_DECL for each one and build into GNU_LITERAL_LIST the list
1654              to be placed into TYPE_FIELDS.  Each node is itself a TREE_LIST
1655              whose TREE_VALUE is the literal name and whose TREE_PURPOSE is the
1656              value of the literal.  But when we have a regular boolean type, we
1657              simplify this a little by using a BOOLEAN_TYPE.  */
1658           const bool is_boolean = Is_Boolean_Type (gnat_entity)
1659                                   && !Has_Non_Standard_Rep (gnat_entity);
1660           const bool is_unsigned = Is_Unsigned_Type (gnat_entity);
1661           tree gnu_list = NULL_TREE;
1662           Entity_Id gnat_literal;
1663
1664           gnu_type = make_node (is_boolean ? BOOLEAN_TYPE : ENUMERAL_TYPE);
1665           TYPE_PRECISION (gnu_type) = esize;
1666           TYPE_UNSIGNED (gnu_type) = is_unsigned;
1667           set_min_and_max_values_for_integral_type (gnu_type, esize,
1668                                                     TYPE_SIGN (gnu_type));
1669           process_attributes (&gnu_type, &attr_list, true, gnat_entity);
1670           layout_type (gnu_type);
1671
1672           for (gnat_literal = First_Literal (gnat_entity);
1673                Present (gnat_literal);
1674                gnat_literal = Next_Literal (gnat_literal))
1675             {
1676               tree gnu_value
1677                 = UI_To_gnu (Enumeration_Rep (gnat_literal), gnu_type);
1678               tree gnu_literal
1679                 = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
1680                                    gnu_type, gnu_value, true, false, false,
1681                                    false, NULL, gnat_literal);
1682               /* Do not generate debug info for individual enumerators.  */
1683               DECL_IGNORED_P (gnu_literal) = 1;
1684               save_gnu_tree (gnat_literal, gnu_literal, false);
1685               gnu_list
1686                 = tree_cons (DECL_NAME (gnu_literal), gnu_value, gnu_list);
1687             }
1688
1689           if (!is_boolean)
1690             TYPE_VALUES (gnu_type) = nreverse (gnu_list);
1691
1692           /* Note that the bounds are updated at the end of this function
1693              to avoid an infinite recursion since they refer to the type.  */
1694           goto discrete_type;
1695         }
1696       break;
1697
1698     case E_Signed_Integer_Type:
1699     case E_Ordinary_Fixed_Point_Type:
1700     case E_Decimal_Fixed_Point_Type:
1701       /* For integer types, just make a signed type the appropriate number
1702          of bits.  */
1703       gnu_type = make_signed_type (esize);
1704       goto discrete_type;
1705
1706     case E_Modular_Integer_Type:
1707       {
1708         /* For modular types, make the unsigned type of the proper number
1709            of bits and then set up the modulus, if required.  */
1710         tree gnu_modulus, gnu_high = NULL_TREE;
1711
1712         /* Packed Array Impl. Types are supposed to be subtypes only.  */
1713         gcc_assert (!Is_Packed_Array_Impl_Type (gnat_entity));
1714
1715         gnu_type = make_unsigned_type (esize);
1716
1717         /* Get the modulus in this type.  If it overflows, assume it is because
1718            it is equal to 2**Esize.  Note that there is no overflow checking
1719            done on unsigned type, so we detect the overflow by looking for
1720            a modulus of zero, which is otherwise invalid.  */
1721         gnu_modulus = UI_To_gnu (Modulus (gnat_entity), gnu_type);
1722
1723         if (!integer_zerop (gnu_modulus))
1724           {
1725             TYPE_MODULAR_P (gnu_type) = 1;
1726             SET_TYPE_MODULUS (gnu_type, gnu_modulus);
1727             gnu_high = fold_build2 (MINUS_EXPR, gnu_type, gnu_modulus,
1728                                     convert (gnu_type, integer_one_node));
1729           }
1730
1731         /* If the upper bound is not maximal, make an extra subtype.  */
1732         if (gnu_high
1733             && !tree_int_cst_equal (gnu_high, TYPE_MAX_VALUE (gnu_type)))
1734           {
1735             tree gnu_subtype = make_unsigned_type (esize);
1736             SET_TYPE_RM_MAX_VALUE (gnu_subtype, gnu_high);
1737             TREE_TYPE (gnu_subtype) = gnu_type;
1738             TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1;
1739             TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "UMT");
1740             gnu_type = gnu_subtype;
1741           }
1742       }
1743       goto discrete_type;
1744
1745     case E_Signed_Integer_Subtype:
1746     case E_Enumeration_Subtype:
1747     case E_Modular_Integer_Subtype:
1748     case E_Ordinary_Fixed_Point_Subtype:
1749     case E_Decimal_Fixed_Point_Subtype:
1750
1751       /* For integral subtypes, we make a new INTEGER_TYPE.  Note that we do
1752          not want to call create_range_type since we would like each subtype
1753          node to be distinct.  ??? Historically this was in preparation for
1754          when memory aliasing is implemented, but that's obsolete now given
1755          the call to relate_alias_sets below.
1756
1757          The TREE_TYPE field of the INTEGER_TYPE points to the base type;
1758          this fact is used by the arithmetic conversion functions.
1759
1760          We elaborate the Ancestor_Subtype if it is not in the current unit
1761          and one of our bounds is non-static.  We do this to ensure consistent
1762          naming in the case where several subtypes share the same bounds, by
1763          elaborating the first such subtype first, thus using its name.  */
1764
1765       if (!definition
1766           && Present (Ancestor_Subtype (gnat_entity))
1767           && !In_Extended_Main_Code_Unit (Ancestor_Subtype (gnat_entity))
1768           && (!Compile_Time_Known_Value (Type_Low_Bound (gnat_entity))
1769               || !Compile_Time_Known_Value (Type_High_Bound (gnat_entity))))
1770         gnat_to_gnu_entity (Ancestor_Subtype (gnat_entity), gnu_expr, 0);
1771
1772       /* Set the precision to the Esize except for bit-packed arrays.  */
1773       if (Is_Packed_Array_Impl_Type (gnat_entity)
1774           && Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)))
1775         esize = UI_To_Int (RM_Size (gnat_entity));
1776
1777       /* This should be an unsigned type if the base type is unsigned or
1778          if the lower bound is constant and non-negative or if the type
1779          is biased.  */
1780       if (Is_Unsigned_Type (Etype (gnat_entity))
1781           || Is_Unsigned_Type (gnat_entity)
1782           || Has_Biased_Representation (gnat_entity))
1783         gnu_type = make_unsigned_type (esize);
1784       else
1785         gnu_type = make_signed_type (esize);
1786       TREE_TYPE (gnu_type) = get_unpadded_type (Etype (gnat_entity));
1787
1788       SET_TYPE_RM_MIN_VALUE
1789         (gnu_type, elaborate_expression (Type_Low_Bound (gnat_entity),
1790                                          gnat_entity, get_identifier ("L"),
1791                                          definition, true,
1792                                          Needs_Debug_Info (gnat_entity)));
1793
1794       SET_TYPE_RM_MAX_VALUE
1795         (gnu_type, elaborate_expression (Type_High_Bound (gnat_entity),
1796                                          gnat_entity, get_identifier ("U"),
1797                                          definition, true,
1798                                          Needs_Debug_Info (gnat_entity)));
1799
1800       TYPE_BIASED_REPRESENTATION_P (gnu_type)
1801         = Has_Biased_Representation (gnat_entity);
1802
1803       /* Inherit our alias set from what we're a subtype of.  Subtypes
1804          are not different types and a pointer can designate any instance
1805          within a subtype hierarchy.  */
1806       relate_alias_sets (gnu_type, TREE_TYPE (gnu_type), ALIAS_SET_COPY);
1807
1808       /* One of the above calls might have caused us to be elaborated,
1809          so don't blow up if so.  */
1810       if (present_gnu_tree (gnat_entity))
1811         {
1812           maybe_present = true;
1813           break;
1814         }
1815
1816       /* Attach the TYPE_STUB_DECL in case we have a parallel type.  */
1817       TYPE_STUB_DECL (gnu_type)
1818         = create_type_stub_decl (gnu_entity_name, gnu_type);
1819
1820       /* For a packed array, make the original array type a parallel type.  */
1821       if (debug_info_p && Is_Packed_Array_Impl_Type (gnat_entity))
1822         add_parallel_type_for_packed_array (gnu_type, gnat_entity);
1823
1824     discrete_type:
1825
1826       /* We have to handle clauses that under-align the type specially.  */
1827       if ((Present (Alignment_Clause (gnat_entity))
1828            || (Is_Packed_Array_Impl_Type (gnat_entity)
1829                && Present
1830                   (Alignment_Clause (Original_Array_Type (gnat_entity)))))
1831           && UI_Is_In_Int_Range (Alignment (gnat_entity)))
1832         {
1833           align = UI_To_Int (Alignment (gnat_entity)) * BITS_PER_UNIT;
1834           if (align >= TYPE_ALIGN (gnu_type))
1835             align = 0;
1836         }
1837
1838       /* If the type we are dealing with represents a bit-packed array,
1839          we need to have the bits left justified on big-endian targets
1840          and right justified on little-endian targets.  We also need to
1841          ensure that when the value is read (e.g. for comparison of two
1842          such values), we only get the good bits, since the unused bits
1843          are uninitialized.  Both goals are accomplished by wrapping up
1844          the modular type in an enclosing record type.  */
1845       if (Is_Packed_Array_Impl_Type (gnat_entity)
1846           && Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)))
1847         {
1848           tree gnu_field_type, gnu_field;
1849
1850           /* Set the RM size before wrapping up the original type.  */
1851           SET_TYPE_RM_SIZE (gnu_type,
1852                             UI_To_gnu (RM_Size (gnat_entity), bitsizetype));
1853           TYPE_PACKED_ARRAY_TYPE_P (gnu_type) = 1;
1854
1855           /* Create a stripped-down declaration, mainly for debugging.  */
1856           create_type_decl (gnu_entity_name, gnu_type, true, debug_info_p,
1857                             gnat_entity);
1858
1859           /* Now save it and build the enclosing record type.  */
1860           gnu_field_type = gnu_type;
1861
1862           gnu_type = make_node (RECORD_TYPE);
1863           TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "JM");
1864           TYPE_PACKED (gnu_type) = 1;
1865           TYPE_SIZE (gnu_type) = TYPE_SIZE (gnu_field_type);
1866           TYPE_SIZE_UNIT (gnu_type) = TYPE_SIZE_UNIT (gnu_field_type);
1867           SET_TYPE_ADA_SIZE (gnu_type, TYPE_RM_SIZE (gnu_field_type));
1868
1869           /* Propagate the alignment of the modular type to the record type,
1870              unless there is an alignment clause that under-aligns the type.
1871              This means that bit-packed arrays are given "ceil" alignment for
1872              their size by default, which may seem counter-intuitive but makes
1873              it possible to overlay them on modular types easily.  */
1874           TYPE_ALIGN (gnu_type)
1875             = align > 0 ? align : TYPE_ALIGN (gnu_field_type);
1876
1877           relate_alias_sets (gnu_type, gnu_field_type, ALIAS_SET_COPY);
1878
1879           /* Don't declare the field as addressable since we won't be taking
1880              its address and this would prevent create_field_decl from making
1881              a bitfield.  */
1882           gnu_field
1883             = create_field_decl (get_identifier ("OBJECT"), gnu_field_type,
1884                                  gnu_type, NULL_TREE, bitsize_zero_node, 1, 0);
1885
1886           /* Do not emit debug info until after the parallel type is added.  */
1887           finish_record_type (gnu_type, gnu_field, 2, false);
1888           compute_record_mode (gnu_type);
1889           TYPE_JUSTIFIED_MODULAR_P (gnu_type) = 1;
1890
1891           if (debug_info_p)
1892             {
1893               /* Make the original array type a parallel type.  */
1894               add_parallel_type_for_packed_array (gnu_type, gnat_entity);
1895
1896               rest_of_record_type_compilation (gnu_type);
1897             }
1898         }
1899
1900       /* If the type we are dealing with has got a smaller alignment than the
1901          natural one, we need to wrap it up in a record type and misalign the
1902          latter; we reuse the padding machinery for this purpose.  Note that,
1903          even if the record type is marked as packed because of misalignment,
1904          we don't pack the field so as to give it the size of the type.  */
1905       else if (align > 0)
1906         {
1907           tree gnu_field_type, gnu_field;
1908
1909           /* Set the RM size before wrapping up the type.  */
1910           SET_TYPE_RM_SIZE (gnu_type,
1911                             UI_To_gnu (RM_Size (gnat_entity), bitsizetype));
1912
1913           /* Create a stripped-down declaration, mainly for debugging.  */
1914           create_type_decl (gnu_entity_name, gnu_type, true, debug_info_p,
1915                             gnat_entity);
1916
1917           /* Now save it and build the enclosing record type.  */
1918           gnu_field_type = gnu_type;
1919
1920           gnu_type = make_node (RECORD_TYPE);
1921           TYPE_NAME (gnu_type) = create_concat_name (gnat_entity, "PAD");
1922           TYPE_PACKED (gnu_type) = 1;
1923           TYPE_SIZE (gnu_type) = TYPE_SIZE (gnu_field_type);
1924           TYPE_SIZE_UNIT (gnu_type) = TYPE_SIZE_UNIT (gnu_field_type);
1925           SET_TYPE_ADA_SIZE (gnu_type, TYPE_RM_SIZE (gnu_field_type));
1926           TYPE_ALIGN (gnu_type) = align;
1927           relate_alias_sets (gnu_type, gnu_field_type, ALIAS_SET_COPY);
1928
1929           /* Don't declare the field as addressable since we won't be taking
1930              its address and this would prevent create_field_decl from making
1931              a bitfield.  */
1932           gnu_field
1933             = create_field_decl (get_identifier ("F"), gnu_field_type,
1934                                  gnu_type, TYPE_SIZE (gnu_field_type),
1935                                  bitsize_zero_node, 0, 0);
1936
1937           finish_record_type (gnu_type, gnu_field, 2, debug_info_p);
1938           compute_record_mode (gnu_type);
1939           TYPE_PADDING_P (gnu_type) = 1;
1940         }
1941
1942       break;
1943
1944     case E_Floating_Point_Type:
1945       /* The type of the Low and High bounds can be our type if this is
1946          a type from Standard, so set them at the end of the function.  */
1947       gnu_type = make_node (REAL_TYPE);
1948       TYPE_PRECISION (gnu_type) = fp_size_to_prec (esize);
1949       layout_type (gnu_type);
1950       break;
1951
1952     case E_Floating_Point_Subtype:
1953       /* See the E_Signed_Integer_Subtype case for the rationale.  */
1954       if (!definition
1955           && Present (Ancestor_Subtype (gnat_entity))
1956           && !In_Extended_Main_Code_Unit (Ancestor_Subtype (gnat_entity))
1957           && (!Compile_Time_Known_Value (Type_Low_Bound (gnat_entity))
1958               || !Compile_Time_Known_Value (Type_High_Bound (gnat_entity))))
1959         gnat_to_gnu_entity (Ancestor_Subtype (gnat_entity), gnu_expr, 0);
1960
1961       gnu_type = make_node (REAL_TYPE);
1962       TREE_TYPE (gnu_type) = get_unpadded_type (Etype (gnat_entity));
1963       TYPE_PRECISION (gnu_type) = fp_size_to_prec (esize);
1964       TYPE_GCC_MIN_VALUE (gnu_type)
1965         = TYPE_GCC_MIN_VALUE (TREE_TYPE (gnu_type));
1966       TYPE_GCC_MAX_VALUE (gnu_type)
1967         = TYPE_GCC_MAX_VALUE (TREE_TYPE (gnu_type));
1968       layout_type (gnu_type);
1969
1970       SET_TYPE_RM_MIN_VALUE
1971         (gnu_type, elaborate_expression (Type_Low_Bound (gnat_entity),
1972                                          gnat_entity, get_identifier ("L"),
1973                                          definition, true,
1974                                          Needs_Debug_Info (gnat_entity)));
1975
1976       SET_TYPE_RM_MAX_VALUE
1977         (gnu_type, elaborate_expression (Type_High_Bound (gnat_entity),
1978                                          gnat_entity, get_identifier ("U"),
1979                                          definition, true,
1980                                          Needs_Debug_Info (gnat_entity)));
1981
1982       /* Inherit our alias set from what we're a subtype of, as for
1983          integer subtypes.  */
1984       relate_alias_sets (gnu_type, TREE_TYPE (gnu_type), ALIAS_SET_COPY);
1985
1986       /* One of the above calls might have caused us to be elaborated,
1987          so don't blow up if so.  */
1988       maybe_present = true;
1989       break;
1990
1991       /* Array Types and Subtypes
1992
1993          Unconstrained array types are represented by E_Array_Type and
1994          constrained array types are represented by E_Array_Subtype.  There
1995          are no actual objects of an unconstrained array type; all we have
1996          are pointers to that type.
1997
1998          The following fields are defined on array types and subtypes:
1999
2000                 Component_Type     Component type of the array.
2001                 Number_Dimensions  Number of dimensions (an int).
2002                 First_Index        Type of first index.  */
2003
2004     case E_Array_Type:
2005       {
2006         const bool convention_fortran_p
2007           = (Convention (gnat_entity) == Convention_Fortran);
2008         const int ndim = Number_Dimensions (gnat_entity);
2009         tree gnu_template_type;
2010         tree gnu_ptr_template;
2011         tree gnu_template_reference, gnu_template_fields, gnu_fat_type;
2012         tree *gnu_index_types = XALLOCAVEC (tree, ndim);
2013         tree *gnu_temp_fields = XALLOCAVEC (tree, ndim);
2014         tree gnu_max_size = size_one_node, gnu_max_size_unit, tem, t;
2015         Entity_Id gnat_index, gnat_name;
2016         int index;
2017         tree comp_type;
2018
2019         /* Create the type for the component now, as it simplifies breaking
2020            type reference loops.  */
2021         comp_type
2022           = gnat_to_gnu_component_type (gnat_entity, definition, debug_info_p);
2023         if (present_gnu_tree (gnat_entity))
2024           {
2025             /* As a side effect, the type may have been translated.  */
2026             maybe_present = true;
2027             break;
2028           }
2029
2030         /* We complete an existing dummy fat pointer type in place.  This both
2031            avoids further complex adjustments in update_pointer_to and yields
2032            better debugging information in DWARF by leveraging the support for
2033            incomplete declarations of "tagged" types in the DWARF back-end.  */
2034         gnu_type = get_dummy_type (gnat_entity);
2035         if (gnu_type && TYPE_POINTER_TO (gnu_type))
2036           {
2037             gnu_fat_type = TYPE_MAIN_VARIANT (TYPE_POINTER_TO (gnu_type));
2038             TYPE_NAME (gnu_fat_type) = NULL_TREE;
2039             /* Save the contents of the dummy type for update_pointer_to.  */
2040             TYPE_POINTER_TO (gnu_type) = copy_type (gnu_fat_type);
2041             gnu_ptr_template =
2042               TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_fat_type)));
2043             gnu_template_type = TREE_TYPE (gnu_ptr_template);
2044           }
2045         else
2046           {
2047             gnu_fat_type = make_node (RECORD_TYPE);
2048             gnu_template_type = make_node (RECORD_TYPE);
2049             gnu_ptr_template = build_pointer_type (gnu_template_type);
2050           }
2051
2052         /* Make a node for the array.  If we are not defining the array
2053            suppress expanding incomplete types.  */
2054         gnu_type = make_node (UNCONSTRAINED_ARRAY_TYPE);
2055
2056         if (!definition)
2057           {
2058             defer_incomplete_level++;
2059             this_deferred = true;
2060           }
2061
2062         /* Build the fat pointer type.  Use a "void *" object instead of
2063            a pointer to the array type since we don't have the array type
2064            yet (it will reference the fat pointer via the bounds).  */
2065         tem
2066           = create_field_decl (get_identifier ("P_ARRAY"), ptr_void_type_node,
2067                                gnu_fat_type, NULL_TREE, NULL_TREE, 0, 0);
2068         DECL_CHAIN (tem)
2069           = create_field_decl (get_identifier ("P_BOUNDS"), gnu_ptr_template,
2070                                gnu_fat_type, NULL_TREE, NULL_TREE, 0, 0);
2071
2072         if (COMPLETE_TYPE_P (gnu_fat_type))
2073           {
2074             /* We are going to lay it out again so reset the alias set.  */
2075             alias_set_type alias_set = TYPE_ALIAS_SET (gnu_fat_type);
2076             TYPE_ALIAS_SET (gnu_fat_type) = -1;
2077             finish_fat_pointer_type (gnu_fat_type, tem);
2078             TYPE_ALIAS_SET (gnu_fat_type) = alias_set;
2079             for (t = gnu_fat_type; t; t = TYPE_NEXT_VARIANT (t))
2080               {
2081                 TYPE_FIELDS (t) = tem;
2082                 SET_TYPE_UNCONSTRAINED_ARRAY (t, gnu_type);
2083               }
2084           }
2085         else
2086           {
2087             finish_fat_pointer_type (gnu_fat_type, tem);
2088             SET_TYPE_UNCONSTRAINED_ARRAY (gnu_fat_type, gnu_type);
2089           }
2090
2091         /* Build a reference to the template from a PLACEHOLDER_EXPR that
2092            is the fat pointer.  This will be used to access the individual
2093            fields once we build them.  */
2094         tem = build3 (COMPONENT_REF, gnu_ptr_template,
2095                       build0 (PLACEHOLDER_EXPR, gnu_fat_type),
2096                       DECL_CHAIN (TYPE_FIELDS (gnu_fat_type)), NULL_TREE);
2097         gnu_template_reference
2098           = build_unary_op (INDIRECT_REF, gnu_template_type, tem);
2099         TREE_READONLY (gnu_template_reference) = 1;
2100         TREE_THIS_NOTRAP (gnu_template_reference) = 1;
2101
2102         /* Now create the GCC type for each index and add the fields for that
2103            index to the template.  */
2104         for (index = (convention_fortran_p ? ndim - 1 : 0),
2105              gnat_index = First_Index (gnat_entity);
2106              0 <= index && index < ndim;
2107              index += (convention_fortran_p ? - 1 : 1),
2108              gnat_index = Next_Index (gnat_index))
2109           {
2110             char field_name[16];
2111             tree gnu_index_base_type
2112               = get_unpadded_type (Base_Type (Etype (gnat_index)));
2113             tree gnu_lb_field, gnu_hb_field, gnu_orig_min, gnu_orig_max;
2114             tree gnu_min, gnu_max, gnu_high;
2115
2116             /* Make the FIELD_DECLs for the low and high bounds of this
2117                type and then make extractions of these fields from the
2118                template.  */
2119             sprintf (field_name, "LB%d", index);
2120             gnu_lb_field = create_field_decl (get_identifier (field_name),
2121                                               gnu_index_base_type,
2122                                               gnu_template_type, NULL_TREE,
2123                                               NULL_TREE, 0, 0);
2124             Sloc_to_locus (Sloc (gnat_entity),
2125                            &DECL_SOURCE_LOCATION (gnu_lb_field));
2126
2127             field_name[0] = 'U';
2128             gnu_hb_field = create_field_decl (get_identifier (field_name),
2129                                               gnu_index_base_type,
2130                                               gnu_template_type, NULL_TREE,
2131                                               NULL_TREE, 0, 0);
2132             Sloc_to_locus (Sloc (gnat_entity),
2133                            &DECL_SOURCE_LOCATION (gnu_hb_field));
2134
2135             gnu_temp_fields[index] = chainon (gnu_lb_field, gnu_hb_field);
2136
2137             /* We can't use build_component_ref here since the template type
2138                isn't complete yet.  */
2139             gnu_orig_min = build3 (COMPONENT_REF, gnu_index_base_type,
2140                                    gnu_template_reference, gnu_lb_field,
2141                                    NULL_TREE);
2142             gnu_orig_max = build3 (COMPONENT_REF, gnu_index_base_type,
2143                                    gnu_template_reference, gnu_hb_field,
2144                                    NULL_TREE);
2145             TREE_READONLY (gnu_orig_min) = TREE_READONLY (gnu_orig_max) = 1;
2146
2147             gnu_min = convert (sizetype, gnu_orig_min);
2148             gnu_max = convert (sizetype, gnu_orig_max);
2149
2150             /* Compute the size of this dimension.  See the E_Array_Subtype
2151                case below for the rationale.  */
2152             gnu_high
2153               = build3 (COND_EXPR, sizetype,
2154                         build2 (GE_EXPR, boolean_type_node,
2155                                 gnu_orig_max, gnu_orig_min),
2156                         gnu_max,
2157                         size_binop (MINUS_EXPR, gnu_min, size_one_node));
2158
2159             /* Make a range type with the new range in the Ada base type.
2160                Then make an index type with the size range in sizetype.  */
2161             gnu_index_types[index]
2162               = create_index_type (gnu_min, gnu_high,
2163                                    create_range_type (gnu_index_base_type,
2164                                                       gnu_orig_min,
2165                                                       gnu_orig_max),
2166                                    gnat_entity);
2167
2168             /* Update the maximum size of the array in elements.  */
2169             if (gnu_max_size)
2170               {
2171                 tree gnu_index_type = get_unpadded_type (Etype (gnat_index));
2172                 tree gnu_min
2173                   = convert (sizetype, TYPE_MIN_VALUE (gnu_index_type));
2174                 tree gnu_max
2175                   = convert (sizetype, TYPE_MAX_VALUE (gnu_index_type));
2176                 tree gnu_this_max
2177                   = size_binop (PLUS_EXPR, size_one_node,
2178                                 size_binop (MINUS_EXPR, gnu_max, gnu_min));
2179
2180                 if (TREE_CODE (gnu_this_max) == INTEGER_CST
2181                     && TREE_OVERFLOW (gnu_this_max))
2182                   gnu_max_size = NULL_TREE;
2183                 else
2184                   gnu_max_size
2185                     = size_binop (MULT_EXPR, gnu_max_size, gnu_this_max);
2186               }
2187
2188             TYPE_NAME (gnu_index_types[index])
2189               = create_concat_name (gnat_entity, field_name);
2190           }
2191
2192         /* Install all the fields into the template.  */
2193         TYPE_NAME (gnu_template_type)
2194           = create_concat_name (gnat_entity, "XUB");
2195         gnu_template_fields = NULL_TREE;
2196         for (index = 0; index < ndim; index++)
2197           gnu_template_fields
2198             = chainon (gnu_template_fields, gnu_temp_fields[index]);
2199         finish_record_type (gnu_template_type, gnu_template_fields, 0,
2200                             debug_info_p);
2201         TYPE_READONLY (gnu_template_type) = 1;
2202
2203         /* If Component_Size is not already specified, annotate it with the
2204            size of the component.  */
2205         if (Unknown_Component_Size (gnat_entity))
2206           Set_Component_Size (gnat_entity,
2207                               annotate_value (TYPE_SIZE (comp_type)));
2208
2209         /* Compute the maximum size of the array in units and bits.  */
2210         if (gnu_max_size)
2211           {
2212             gnu_max_size_unit = size_binop (MULT_EXPR, gnu_max_size,
2213                                             TYPE_SIZE_UNIT (comp_type));
2214             gnu_max_size = size_binop (MULT_EXPR,
2215                                        convert (bitsizetype, gnu_max_size),
2216                                        TYPE_SIZE (comp_type));
2217           }
2218         else
2219           gnu_max_size_unit = NULL_TREE;
2220
2221         /* Now build the array type.  */
2222         tem = comp_type;
2223         for (index = ndim - 1; index >= 0; index--)
2224           {
2225             tem = build_nonshared_array_type (tem, gnu_index_types[index]);
2226             if (Reverse_Storage_Order (gnat_entity) && !GNAT_Mode)
2227               sorry ("non-default Scalar_Storage_Order");
2228             TYPE_MULTI_ARRAY_P (tem) = (index > 0);
2229             if (array_type_has_nonaliased_component (tem, gnat_entity))
2230               TYPE_NONALIASED_COMPONENT (tem) = 1;
2231           }
2232
2233         /* If an alignment is specified, use it if valid.  But ignore it
2234            for the original type of packed array types.  If the alignment
2235            was requested with an explicit alignment clause, state so.  */
2236         if (No (Packed_Array_Impl_Type (gnat_entity))
2237             && Known_Alignment (gnat_entity))
2238           {
2239             TYPE_ALIGN (tem)
2240               = validate_alignment (Alignment (gnat_entity), gnat_entity,
2241                                     TYPE_ALIGN (tem));
2242             if (Present (Alignment_Clause (gnat_entity)))
2243               TYPE_USER_ALIGN (tem) = 1;
2244           }
2245
2246         TYPE_CONVENTION_FORTRAN_P (tem) = convention_fortran_p;
2247
2248         if (Treat_As_Volatile (gnat_entity))
2249           tem = change_qualified_type (tem, TYPE_QUAL_VOLATILE);
2250
2251         /* Adjust the type of the pointer-to-array field of the fat pointer
2252            and record the aliasing relationships if necessary.  */
2253         TREE_TYPE (TYPE_FIELDS (gnu_fat_type)) = build_pointer_type (tem);
2254         if (TYPE_ALIAS_SET_KNOWN_P (gnu_fat_type))
2255           record_component_aliases (gnu_fat_type);
2256
2257         /* The result type is an UNCONSTRAINED_ARRAY_TYPE that indicates the
2258            corresponding fat pointer.  */
2259         TREE_TYPE (gnu_type) = gnu_fat_type;
2260         TYPE_POINTER_TO (gnu_type) = gnu_fat_type;
2261         TYPE_REFERENCE_TO (gnu_type) = gnu_fat_type;
2262         SET_TYPE_MODE (gnu_type, BLKmode);
2263         TYPE_ALIGN (gnu_type) = TYPE_ALIGN (tem);
2264
2265         /* If the maximum size doesn't overflow, use it.  */
2266         if (gnu_max_size
2267             && TREE_CODE (gnu_max_size) == INTEGER_CST
2268             && !TREE_OVERFLOW (gnu_max_size)
2269             && TREE_CODE (gnu_max_size_unit) == INTEGER_CST
2270             && !TREE_OVERFLOW (gnu_max_size_unit))
2271           {
2272             TYPE_SIZE (tem) = size_binop (MIN_EXPR, gnu_max_size,
2273                                           TYPE_SIZE (tem));
2274             TYPE_SIZE_UNIT (tem) = size_binop (MIN_EXPR, gnu_max_size_unit,
2275                                                TYPE_SIZE_UNIT (tem));
2276           }
2277
2278         create_type_decl (create_concat_name (gnat_entity, "XUA"), tem,
2279                           !Comes_From_Source (gnat_entity), debug_info_p,
2280                           gnat_entity);
2281
2282         /* Give the fat pointer type a name.  If this is a packed array, tell
2283            the debugger how to interpret the underlying bits.  */
2284         if (Present (Packed_Array_Impl_Type (gnat_entity)))
2285           gnat_name = Packed_Array_Impl_Type (gnat_entity);
2286         else
2287           gnat_name = gnat_entity;
2288         create_type_decl (create_concat_name (gnat_name, "XUP"), gnu_fat_type,
2289                           !Comes_From_Source (gnat_entity), debug_info_p,
2290                           gnat_entity);
2291
2292         /* Create the type to be designated by thin pointers: a record type for
2293            the array and its template.  We used to shift the fields to have the
2294            template at a negative offset, but this was somewhat of a kludge; we
2295            now shift thin pointer values explicitly but only those which have a
2296            TYPE_UNCONSTRAINED_ARRAY attached to the designated RECORD_TYPE.  */
2297         tem = build_unc_object_type (gnu_template_type, tem,
2298                                      create_concat_name (gnat_name, "XUT"),
2299                                      debug_info_p);
2300
2301         SET_TYPE_UNCONSTRAINED_ARRAY (tem, gnu_type);
2302         TYPE_OBJECT_RECORD_TYPE (gnu_type) = tem;
2303       }
2304       break;
2305
2306     case E_Array_Subtype:
2307
2308       /* This is the actual data type for array variables.  Multidimensional
2309          arrays are implemented as arrays of arrays.  Note that arrays which
2310          have sparse enumeration subtypes as index components create sparse
2311          arrays, which is obviously space inefficient but so much easier to
2312          code for now.
2313
2314          Also note that the subtype never refers to the unconstrained array
2315          type, which is somewhat at variance with Ada semantics.
2316
2317          First check to see if this is simply a renaming of the array type.
2318          If so, the result is the array type.  */
2319
2320       gnu_type = TYPE_MAIN_VARIANT (gnat_to_gnu_type (Etype (gnat_entity)));
2321       if (!Is_Constrained (gnat_entity))
2322         ;
2323       else
2324         {
2325           Entity_Id gnat_index, gnat_base_index;
2326           const bool convention_fortran_p
2327             = (Convention (gnat_entity) == Convention_Fortran);
2328           const int ndim = Number_Dimensions (gnat_entity);
2329           tree gnu_base_type = gnu_type;
2330           tree *gnu_index_types = XALLOCAVEC (tree, ndim);
2331           tree gnu_max_size = size_one_node, gnu_max_size_unit;
2332           bool need_index_type_struct = false;
2333           int index;
2334
2335           /* First create the GCC type for each index and find out whether
2336              special types are needed for debugging information.  */
2337           for (index = (convention_fortran_p ? ndim - 1 : 0),
2338                gnat_index = First_Index (gnat_entity),
2339                gnat_base_index
2340                  = First_Index (Implementation_Base_Type (gnat_entity));
2341                0 <= index && index < ndim;
2342                index += (convention_fortran_p ? - 1 : 1),
2343                gnat_index = Next_Index (gnat_index),
2344                gnat_base_index = Next_Index (gnat_base_index))
2345             {
2346               tree gnu_index_type = get_unpadded_type (Etype (gnat_index));
2347               tree gnu_index_base_type = get_base_type (gnu_index_type);
2348               tree gnu_orig_min
2349                 = convert (gnu_index_base_type,
2350                            TYPE_MIN_VALUE (gnu_index_type));
2351               tree gnu_orig_max
2352                 = convert (gnu_index_base_type,
2353                            TYPE_MAX_VALUE (gnu_index_type));
2354               tree gnu_min = convert (sizetype, gnu_orig_min);
2355               tree gnu_max = convert (sizetype, gnu_orig_max);
2356               tree gnu_base_index_type
2357                 = get_unpadded_type (Etype (gnat_base_index));
2358               tree gnu_base_index_base_type
2359                 = get_base_type (gnu_base_index_type);
2360               tree gnu_base_orig_min
2361                 = convert (gnu_base_index_base_type,
2362                            TYPE_MIN_VALUE (gnu_base_index_type));
2363               tree gnu_base_orig_max
2364                 = convert (gnu_base_index_base_type,
2365                            TYPE_MAX_VALUE (gnu_base_index_type));
2366               tree gnu_high;
2367
2368               /* See if the base array type is already flat.  If it is, we
2369                  are probably compiling an ACATS test but it will cause the
2370                  code below to malfunction if we don't handle it specially.  */
2371               if (TREE_CODE (gnu_base_orig_min) == INTEGER_CST
2372                   && TREE_CODE (gnu_base_orig_max) == INTEGER_CST
2373                   && tree_int_cst_lt (gnu_base_orig_max, gnu_base_orig_min))
2374                 {
2375                   gnu_min = size_one_node;
2376                   gnu_max = size_zero_node;
2377                   gnu_high = gnu_max;
2378                 }
2379
2380               /* Similarly, if one of the values overflows in sizetype and the
2381                  range is null, use 1..0 for the sizetype bounds.  */
2382               else if (TREE_CODE (gnu_min) == INTEGER_CST
2383                        && TREE_CODE (gnu_max) == INTEGER_CST
2384                        && (TREE_OVERFLOW (gnu_min) || TREE_OVERFLOW (gnu_max))
2385                        && tree_int_cst_lt (gnu_orig_max, gnu_orig_min))
2386                 {
2387                   gnu_min = size_one_node;
2388                   gnu_max = size_zero_node;
2389                   gnu_high = gnu_max;
2390                 }
2391
2392               /* If the minimum and maximum values both overflow in sizetype,
2393                  but the difference in the original type does not overflow in
2394                  sizetype, ignore the overflow indication.  */
2395               else if (TREE_CODE (gnu_min) == INTEGER_CST
2396                        && TREE_CODE (gnu_max) == INTEGER_CST
2397                        && TREE_OVERFLOW (gnu_min) && TREE_OVERFLOW (gnu_max)
2398                        && !TREE_OVERFLOW
2399                            (convert (sizetype,
2400                                      fold_build2 (MINUS_EXPR, gnu_index_type,
2401                                                   gnu_orig_max,
2402                                                   gnu_orig_min))))
2403                 {
2404                   TREE_OVERFLOW (gnu_min) = 0;
2405                   TREE_OVERFLOW (gnu_max) = 0;
2406                   gnu_high = gnu_max;
2407                 }
2408
2409               /* Compute the size of this dimension in the general case.  We
2410                  need to provide GCC with an upper bound to use but have to
2411                  deal with the "superflat" case.  There are three ways to do
2412                  this.  If we can prove that the array can never be superflat,
2413                  we can just use the high bound of the index type.  */
2414               else if ((Nkind (gnat_index) == N_Range
2415                         && cannot_be_superflat_p (gnat_index))
2416                        /* Bit-Packed Array Impl. Types are never superflat.  */
2417                        || (Is_Packed_Array_Impl_Type (gnat_entity)
2418                            && Is_Bit_Packed_Array
2419                               (Original_Array_Type (gnat_entity))))
2420                 gnu_high = gnu_max;
2421
2422               /* Otherwise, if the high bound is constant but the low bound is
2423                  not, we use the expression (hb >= lb) ? lb : hb + 1 for the
2424                  lower bound.  Note that the comparison must be done in the
2425                  original type to avoid any overflow during the conversion.  */
2426               else if (TREE_CODE (gnu_max) == INTEGER_CST
2427                        && TREE_CODE (gnu_min) != INTEGER_CST)
2428                 {
2429                   gnu_high = gnu_max;
2430                   gnu_min
2431                     = build_cond_expr (sizetype,
2432                                        build_binary_op (GE_EXPR,
2433                                                         boolean_type_node,
2434                                                         gnu_orig_max,
2435                                                         gnu_orig_min),
2436                                        gnu_min,
2437                                        int_const_binop (PLUS_EXPR, gnu_max,
2438                                                         size_one_node));
2439                 }
2440
2441               /* Finally we use (hb >= lb) ? hb : lb - 1 for the upper bound
2442                  in all the other cases.  Note that, here as well as above,
2443                  the condition used in the comparison must be equivalent to
2444                  the condition (length != 0).  This is relied upon in order
2445                  to optimize array comparisons in compare_arrays.  Moreover
2446                  we use int_const_binop for the shift by 1 if the bound is
2447                  constant to avoid any unwanted overflow.  */
2448               else
2449                 gnu_high
2450                   = build_cond_expr (sizetype,
2451                                      build_binary_op (GE_EXPR,
2452                                                       boolean_type_node,
2453                                                       gnu_orig_max,
2454                                                       gnu_orig_min),
2455                                      gnu_max,
2456                                      TREE_CODE (gnu_min) == INTEGER_CST
2457                                      ? int_const_binop (MINUS_EXPR, gnu_min,
2458                                                         size_one_node)
2459                                      : size_binop (MINUS_EXPR, gnu_min,
2460                                                    size_one_node));
2461
2462               /* Reuse the index type for the range type.  Then make an index
2463                  type with the size range in sizetype.  */
2464               gnu_index_types[index]
2465                 = create_index_type (gnu_min, gnu_high, gnu_index_type,
2466                                      gnat_entity);
2467
2468               /* Update the maximum size of the array in elements.  Here we
2469                  see if any constraint on the index type of the base type
2470                  can be used in the case of self-referential bound on the
2471                  index type of the subtype.  We look for a non-"infinite"
2472                  and non-self-referential bound from any type involved and
2473                  handle each bound separately.  */
2474               if (gnu_max_size)
2475                 {
2476                   tree gnu_base_min = convert (sizetype, gnu_base_orig_min);
2477                   tree gnu_base_max = convert (sizetype, gnu_base_orig_max);
2478                   tree gnu_base_index_base_type
2479                     = get_base_type (gnu_base_index_type);
2480                   tree gnu_base_base_min
2481                     = convert (sizetype,
2482                                TYPE_MIN_VALUE (gnu_base_index_base_type));
2483                   tree gnu_base_base_max
2484                     = convert (sizetype,
2485                                TYPE_MAX_VALUE (gnu_base_index_base_type));
2486
2487                   if (!CONTAINS_PLACEHOLDER_P (gnu_min)
2488                       || !(TREE_CODE (gnu_base_min) == INTEGER_CST
2489                            && !TREE_OVERFLOW (gnu_base_min)))
2490                     gnu_base_min = gnu_min;
2491
2492                   if (!CONTAINS_PLACEHOLDER_P (gnu_max)
2493                       || !(TREE_CODE (gnu_base_max) == INTEGER_CST
2494                            && !TREE_OVERFLOW (gnu_base_max)))
2495                     gnu_base_max = gnu_max;
2496
2497                   if ((TREE_CODE (gnu_base_min) == INTEGER_CST
2498                        && TREE_OVERFLOW (gnu_base_min))
2499                       || operand_equal_p (gnu_base_min, gnu_base_base_min, 0)
2500                       || (TREE_CODE (gnu_base_max) == INTEGER_CST
2501                           && TREE_OVERFLOW (gnu_base_max))
2502                       || operand_equal_p (gnu_base_max, gnu_base_base_max, 0))
2503                     gnu_max_size = NULL_TREE;
2504                   else
2505                     {
2506                       tree gnu_this_max;
2507
2508                       /* Use int_const_binop if the bounds are constant to
2509                          avoid any unwanted overflow.  */
2510                       if (TREE_CODE (gnu_base_min) == INTEGER_CST
2511                           && TREE_CODE (gnu_base_max) == INTEGER_CST)
2512                         gnu_this_max
2513                           = int_const_binop (PLUS_EXPR, size_one_node,
2514                                              int_const_binop (MINUS_EXPR,
2515                                                               gnu_base_max,
2516                                                               gnu_base_min));
2517                       else
2518                         gnu_this_max
2519                           = size_binop (PLUS_EXPR, size_one_node,
2520                                         size_binop (MINUS_EXPR,
2521                                                     gnu_base_max,
2522                                                     gnu_base_min));
2523
2524                       gnu_max_size
2525                         = size_binop (MULT_EXPR, gnu_max_size, gnu_this_max);
2526                     }
2527                 }
2528
2529               /* We need special types for debugging information to point to
2530                  the index types if they have variable bounds, are not integer
2531                  types or are biased.  */
2532               if (TREE_CODE (gnu_orig_min) != INTEGER_CST
2533                   || TREE_CODE (gnu_orig_max) != INTEGER_CST
2534                   || TREE_CODE (gnu_index_type) != INTEGER_TYPE
2535                   || (TREE_TYPE (gnu_index_type)
2536                       && TREE_CODE (TREE_TYPE (gnu_index_type))
2537                          != INTEGER_TYPE)
2538                   || TYPE_BIASED_REPRESENTATION_P (gnu_index_type))
2539                 need_index_type_struct = true;
2540             }
2541
2542           /* Then flatten: create the array of arrays.  For an array type
2543              used to implement a packed array, get the component type from
2544              the original array type since the representation clauses that
2545              can affect it are on the latter.  */
2546           if (Is_Packed_Array_Impl_Type (gnat_entity)
2547               && !Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)))
2548             {
2549               gnu_type = gnat_to_gnu_type (Original_Array_Type (gnat_entity));
2550               for (index = ndim - 1; index >= 0; index--)
2551                 gnu_type = TREE_TYPE (gnu_type);
2552
2553               /* One of the above calls might have caused us to be elaborated,
2554                  so don't blow up if so.  */
2555               if (present_gnu_tree (gnat_entity))
2556                 {
2557                   maybe_present = true;
2558                   break;
2559                 }
2560             }
2561           else
2562             {
2563               gnu_type = gnat_to_gnu_component_type (gnat_entity, definition,
2564                                                      debug_info_p);
2565
2566               /* One of the above calls might have caused us to be elaborated,
2567                  so don't blow up if so.  */
2568               if (present_gnu_tree (gnat_entity))
2569                 {
2570                   maybe_present = true;
2571                   break;
2572                 }
2573             }
2574
2575           /* Compute the maximum size of the array in units and bits.  */
2576           if (gnu_max_size)
2577             {
2578               gnu_max_size_unit = size_binop (MULT_EXPR, gnu_max_size,
2579                                               TYPE_SIZE_UNIT (gnu_type));
2580               gnu_max_size = size_binop (MULT_EXPR,
2581                                          convert (bitsizetype, gnu_max_size),
2582                                          TYPE_SIZE (gnu_type));
2583             }
2584           else
2585             gnu_max_size_unit = NULL_TREE;
2586
2587           /* Now build the array type.  */
2588           for (index = ndim - 1; index >= 0; index --)
2589             {
2590               gnu_type = build_nonshared_array_type (gnu_type,
2591                                                      gnu_index_types[index]);
2592               TYPE_MULTI_ARRAY_P (gnu_type) = (index > 0);
2593               if (array_type_has_nonaliased_component (gnu_type, gnat_entity))
2594                 TYPE_NONALIASED_COMPONENT (gnu_type) = 1;
2595             }
2596
2597           /* Attach the TYPE_STUB_DECL in case we have a parallel type.  */
2598           TYPE_STUB_DECL (gnu_type)
2599             = create_type_stub_decl (gnu_entity_name, gnu_type);
2600
2601           /* If we are at file level and this is a multi-dimensional array,
2602              we need to make a variable corresponding to the stride of the
2603              inner dimensions.   */
2604           if (global_bindings_p () && ndim > 1)
2605             {
2606               tree gnu_st_name = get_identifier ("ST");
2607               tree gnu_arr_type;
2608
2609               for (gnu_arr_type = TREE_TYPE (gnu_type);
2610                    TREE_CODE (gnu_arr_type) == ARRAY_TYPE;
2611                    gnu_arr_type = TREE_TYPE (gnu_arr_type),
2612                    gnu_st_name = concat_name (gnu_st_name, "ST"))
2613                 {
2614                   tree eltype = TREE_TYPE (gnu_arr_type);
2615
2616                   TYPE_SIZE (gnu_arr_type)
2617                     = elaborate_expression_1 (TYPE_SIZE (gnu_arr_type),
2618                                               gnat_entity, gnu_st_name,
2619                                               definition, false);
2620
2621                   /* ??? For now, store the size as a multiple of the
2622                      alignment of the element type in bytes so that we
2623                      can see the alignment from the tree.  */
2624                   TYPE_SIZE_UNIT (gnu_arr_type)
2625                     = elaborate_expression_2 (TYPE_SIZE_UNIT (gnu_arr_type),
2626                                               gnat_entity,
2627                                               concat_name (gnu_st_name, "A_U"),
2628                                               definition, false,
2629                                               TYPE_ALIGN (eltype));
2630
2631                   /* ??? create_type_decl is not invoked on the inner types so
2632                      the MULT_EXPR node built above will never be marked.  */
2633                   MARK_VISITED (TYPE_SIZE_UNIT (gnu_arr_type));
2634                 }
2635             }
2636
2637           /* If we need to write out a record type giving the names of the
2638              bounds for debugging purposes, do it now and make the record
2639              type a parallel type.  This is not needed for a packed array
2640              since the bounds are conveyed by the original array type.  */
2641           if (need_index_type_struct
2642               && debug_info_p
2643               && !Is_Packed_Array_Impl_Type (gnat_entity))
2644             {
2645               tree gnu_bound_rec = make_node (RECORD_TYPE);
2646               tree gnu_field_list = NULL_TREE;
2647               tree gnu_field;
2648
2649               TYPE_NAME (gnu_bound_rec)
2650                 = create_concat_name (gnat_entity, "XA");
2651
2652               for (index = ndim - 1; index >= 0; index--)
2653                 {
2654                   tree gnu_index = TYPE_INDEX_TYPE (gnu_index_types[index]);
2655                   tree gnu_index_name = TYPE_IDENTIFIER (gnu_index);
2656
2657                   /* Make sure to reference the types themselves, and not just
2658                      their names, as the debugger may fall back on them.  */
2659                   gnu_field = create_field_decl (gnu_index_name, gnu_index,
2660                                                  gnu_bound_rec, NULL_TREE,
2661                                                  NULL_TREE, 0, 0);
2662                   DECL_CHAIN (gnu_field) = gnu_field_list;
2663                   gnu_field_list = gnu_field;
2664                 }
2665
2666               finish_record_type (gnu_bound_rec, gnu_field_list, 0, true);
2667               add_parallel_type (gnu_type, gnu_bound_rec);
2668             }
2669
2670           /* If this is a packed array type, make the original array type a
2671              parallel type.  Otherwise, do it for the base array type if it
2672              isn't artificial to make sure it is kept in the debug info.  */
2673           if (debug_info_p)
2674             {
2675               if (Is_Packed_Array_Impl_Type (gnat_entity))
2676                 add_parallel_type_for_packed_array (gnu_type, gnat_entity);
2677               else
2678                 {
2679                   tree gnu_base_decl
2680                     = gnat_to_gnu_entity (Etype (gnat_entity), NULL_TREE, 0);
2681                   if (!DECL_ARTIFICIAL (gnu_base_decl))
2682                     add_parallel_type (gnu_type,
2683                                        TREE_TYPE (TREE_TYPE (gnu_base_decl)));
2684                 }
2685             }
2686
2687           TYPE_CONVENTION_FORTRAN_P (gnu_type) = convention_fortran_p;
2688           TYPE_PACKED_ARRAY_TYPE_P (gnu_type)
2689             = (Is_Packed_Array_Impl_Type (gnat_entity)
2690                && Is_Bit_Packed_Array (Original_Array_Type (gnat_entity)));
2691
2692           /* If the size is self-referential and the maximum size doesn't
2693              overflow, use it.  */
2694           if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type))
2695               && gnu_max_size
2696               && !(TREE_CODE (gnu_max_size) == INTEGER_CST
2697                    && TREE_OVERFLOW (gnu_max_size))
2698               && !(TREE_CODE (gnu_max_size_unit) == INTEGER_CST
2699                    && TREE_OVERFLOW (gnu_max_size_unit)))
2700             {
2701               TYPE_SIZE (gnu_type) = size_binop (MIN_EXPR, gnu_max_size,
2702                                                  TYPE_SIZE (gnu_type));
2703               TYPE_SIZE_UNIT (gnu_type)
2704                 = size_binop (MIN_EXPR, gnu_max_size_unit,
2705                               TYPE_SIZE_UNIT (gnu_type));
2706             }
2707
2708           /* Set our alias set to that of our base type.  This gives all
2709              array subtypes the same alias set.  */
2710           relate_alias_sets (gnu_type, gnu_base_type, ALIAS_SET_COPY);
2711
2712           /* If this is a packed type, make this type the same as the packed
2713              array type, but do some adjusting in the type first.  */
2714           if (Present (Packed_Array_Impl_Type (gnat_entity)))
2715             {
2716               Entity_Id gnat_index;
2717               tree gnu_inner;
2718
2719               /* First finish the type we had been making so that we output
2720                  debugging information for it.  */
2721               process_attributes (&gnu_type, &attr_list, false, gnat_entity);
2722               if (Treat_As_Volatile (gnat_entity))
2723                 {
2724                   const int quals
2725                     = TYPE_QUAL_VOLATILE
2726                       | (Is_Atomic_Or_VFA (gnat_entity) ? TYPE_QUAL_ATOMIC : 0);
2727                   gnu_type = change_qualified_type (gnu_type, quals);
2728                 }
2729               /* Make it artificial only if the base type was artificial too.
2730                  That's sort of "morally" true and will make it possible for
2731                  the debugger to look it up by name in DWARF, which is needed
2732                  in order to decode the packed array type.  */
2733               gnu_decl
2734                 = create_type_decl (gnu_entity_name, gnu_type,
2735                                     !Comes_From_Source (Etype (gnat_entity))
2736                                     && !Comes_From_Source (gnat_entity),
2737                                     debug_info_p, gnat_entity);
2738
2739               /* Save it as our equivalent in case the call below elaborates
2740                  this type again.  */
2741               save_gnu_tree (gnat_entity, gnu_decl, false);
2742
2743               gnu_decl
2744                 = gnat_to_gnu_entity (Packed_Array_Impl_Type (gnat_entity),
2745                                       NULL_TREE, 0);
2746               this_made_decl = true;
2747               gnu_type = TREE_TYPE (gnu_decl);
2748               save_gnu_tree (gnat_entity, NULL_TREE, false);
2749
2750               gnu_inner = gnu_type;
2751               while (TREE_CODE (gnu_inner) == RECORD_TYPE
2752                      && (TYPE_JUSTIFIED_MODULAR_P (gnu_inner)
2753                          || TYPE_PADDING_P (gnu_inner)))
2754                 gnu_inner = TREE_TYPE (TYPE_FIELDS (gnu_inner));
2755
2756               /* We need to attach the index type to the type we just made so
2757                  that the actual bounds can later be put into a template.  */
2758               if ((TREE_CODE (gnu_inner) == ARRAY_TYPE
2759                    && !TYPE_ACTUAL_BOUNDS (gnu_inner))
2760                   || (TREE_CODE (gnu_inner) == INTEGER_TYPE
2761                       && !TYPE_HAS_ACTUAL_BOUNDS_P (gnu_inner)))
2762                 {
2763                   if (TREE_CODE (gnu_inner) == INTEGER_TYPE)
2764                     {
2765                       /* The TYPE_ACTUAL_BOUNDS field is overloaded with the
2766                          TYPE_MODULUS for modular types so we make an extra
2767                          subtype if necessary.  */
2768                       if (TYPE_MODULAR_P (gnu_inner))
2769                         {
2770                           tree gnu_subtype
2771                             = make_unsigned_type (TYPE_PRECISION (gnu_inner));
2772                           TREE_TYPE (gnu_subtype) = gnu_inner;
2773                           TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1;
2774                           SET_TYPE_RM_MIN_VALUE (gnu_subtype,
2775                                                  TYPE_MIN_VALUE (gnu_inner));
2776                           SET_TYPE_RM_MAX_VALUE (gnu_subtype,
2777                                                  TYPE_MAX_VALUE (gnu_inner));
2778                           gnu_inner = gnu_subtype;
2779                         }
2780
2781                       TYPE_HAS_ACTUAL_BOUNDS_P (gnu_inner) = 1;
2782
2783 #ifdef ENABLE_CHECKING
2784                       /* Check for other cases of overloading.  */
2785                       gcc_assert (!TYPE_ACTUAL_BOUNDS (gnu_inner));
2786 #endif
2787                     }
2788
2789                   for (gnat_index = First_Index (gnat_entity);
2790                        Present (gnat_index);
2791                        gnat_index = Next_Index (gnat_index))
2792                     SET_TYPE_ACTUAL_BOUNDS
2793                       (gnu_inner,
2794                        tree_cons (NULL_TREE,
2795                                   get_unpadded_type (Etype (gnat_index)),
2796                                   TYPE_ACTUAL_BOUNDS (gnu_inner)));
2797
2798                   if (Convention (gnat_entity) != Convention_Fortran)
2799                     SET_TYPE_ACTUAL_BOUNDS
2800                       (gnu_inner, nreverse (TYPE_ACTUAL_BOUNDS (gnu_inner)));
2801
2802                   if (TREE_CODE (gnu_type) == RECORD_TYPE
2803                       && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
2804                     TREE_TYPE (TYPE_FIELDS (gnu_type)) = gnu_inner;
2805                 }
2806             }
2807
2808           else
2809             /* Abort if packed array with no Packed_Array_Impl_Type.  */
2810             gcc_assert (!Is_Packed (gnat_entity));
2811         }
2812       break;
2813
2814     case E_String_Literal_Subtype:
2815       /* Create the type for a string literal.  */
2816       {
2817         Entity_Id gnat_full_type
2818           = (IN (Ekind (Etype (gnat_entity)), Private_Kind)
2819              && Present (Full_View (Etype (gnat_entity)))
2820              ? Full_View (Etype (gnat_entity)) : Etype (gnat_entity));
2821         tree gnu_string_type = get_unpadded_type (gnat_full_type);
2822         tree gnu_string_array_type
2823           = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_string_type))));
2824         tree gnu_string_index_type
2825           = get_base_type (TREE_TYPE (TYPE_INDEX_TYPE
2826                                       (TYPE_DOMAIN (gnu_string_array_type))));
2827         tree gnu_lower_bound
2828           = convert (gnu_string_index_type,
2829                      gnat_to_gnu (String_Literal_Low_Bound (gnat_entity)));
2830         tree gnu_length
2831           = UI_To_gnu (String_Literal_Length (gnat_entity),
2832                        gnu_string_index_type);
2833         tree gnu_upper_bound
2834           = build_binary_op (PLUS_EXPR, gnu_string_index_type,
2835                              gnu_lower_bound,
2836                              int_const_binop (MINUS_EXPR, gnu_length,
2837                                               convert (gnu_string_index_type,
2838                                                        integer_one_node)));
2839         tree gnu_index_type
2840           = create_index_type (convert (sizetype, gnu_lower_bound),
2841                                convert (sizetype, gnu_upper_bound),
2842                                create_range_type (gnu_string_index_type,
2843                                                   gnu_lower_bound,
2844                                                   gnu_upper_bound),
2845                                gnat_entity);
2846
2847         gnu_type
2848           = build_nonshared_array_type (gnat_to_gnu_type
2849                                         (Component_Type (gnat_entity)),
2850                                         gnu_index_type);
2851         if (array_type_has_nonaliased_component (gnu_type, gnat_entity))
2852           TYPE_NONALIASED_COMPONENT (gnu_type) = 1;
2853         relate_alias_sets (gnu_type, gnu_string_type, ALIAS_SET_COPY);
2854       }
2855       break;
2856
2857     /* Record Types and Subtypes
2858
2859        The following fields are defined on record types:
2860
2861                 Has_Discriminants       True if the record has discriminants
2862                 First_Discriminant      Points to head of list of discriminants
2863                 First_Entity            Points to head of list of fields
2864                 Is_Tagged_Type          True if the record is tagged
2865
2866        Implementation of Ada records and discriminated records:
2867
2868        A record type definition is transformed into the equivalent of a C
2869        struct definition.  The fields that are the discriminants which are
2870        found in the Full_Type_Declaration node and the elements of the
2871        Component_List found in the Record_Type_Definition node.  The
2872        Component_List can be a recursive structure since each Variant of
2873        the Variant_Part of the Component_List has a Component_List.
2874
2875        Processing of a record type definition comprises starting the list of
2876        field declarations here from the discriminants and the calling the
2877        function components_to_record to add the rest of the fields from the
2878        component list and return the gnu type node.  The function
2879        components_to_record will call itself recursively as it traverses
2880        the tree.  */
2881
2882     case E_Record_Type:
2883       if (Has_Complex_Representation (gnat_entity))
2884         {
2885           gnu_type
2886             = build_complex_type
2887               (get_unpadded_type
2888                (Etype (Defining_Entity
2889                        (First (Component_Items
2890                                (Component_List
2891                                 (Type_Definition
2892                                  (Declaration_Node (gnat_entity)))))))));
2893
2894           break;
2895         }
2896
2897       {
2898         Node_Id full_definition = Declaration_Node (gnat_entity);
2899         Node_Id record_definition = Type_Definition (full_definition);
2900         Node_Id gnat_constr;
2901         Entity_Id gnat_field;
2902         tree gnu_field, gnu_field_list = NULL_TREE;
2903         tree gnu_get_parent;
2904         /* Set PACKED in keeping with gnat_to_gnu_field.  */
2905         const int packed
2906           = Is_Packed (gnat_entity)
2907             ? 1
2908             : Component_Alignment (gnat_entity) == Calign_Storage_Unit
2909               ? -1
2910               : (Known_Alignment (gnat_entity)
2911                  || (Strict_Alignment (gnat_entity)
2912                      && Known_RM_Size (gnat_entity)))
2913                 ? -2
2914                 : 0;
2915         const bool has_discr = Has_Discriminants (gnat_entity);
2916         const bool has_rep = Has_Specified_Layout (gnat_entity);
2917         const bool is_extension
2918           = (Is_Tagged_Type (gnat_entity)
2919              && Nkind (record_definition) == N_Derived_Type_Definition);
2920         const bool is_unchecked_union = Is_Unchecked_Union (gnat_entity);
2921         bool all_rep = has_rep;
2922
2923         /* See if all fields have a rep clause.  Stop when we find one
2924            that doesn't.  */
2925         if (all_rep)
2926           for (gnat_field = First_Entity (gnat_entity);
2927                Present (gnat_field);
2928                gnat_field = Next_Entity (gnat_field))
2929             if ((Ekind (gnat_field) == E_Component
2930                  || Ekind (gnat_field) == E_Discriminant)
2931                 && No (Component_Clause (gnat_field)))
2932               {
2933                 all_rep = false;
2934                 break;
2935               }
2936
2937         /* If this is a record extension, go a level further to find the
2938            record definition.  Also, verify we have a Parent_Subtype.  */
2939         if (is_extension)
2940           {
2941             if (!type_annotate_only
2942                 || Present (Record_Extension_Part (record_definition)))
2943               record_definition = Record_Extension_Part (record_definition);
2944
2945             gcc_assert (type_annotate_only
2946                         || Present (Parent_Subtype (gnat_entity)));
2947           }
2948
2949         /* Make a node for the record.  If we are not defining the record,
2950            suppress expanding incomplete types.  */
2951         gnu_type = make_node (tree_code_for_record_type (gnat_entity));
2952         TYPE_NAME (gnu_type) = gnu_entity_name;
2953         TYPE_PACKED (gnu_type) = (packed != 0) || has_rep;
2954         if (Reverse_Storage_Order (gnat_entity) && !GNAT_Mode)
2955           sorry ("non-default Scalar_Storage_Order");
2956         process_attributes (&gnu_type, &attr_list, true, gnat_entity);
2957
2958         if (!definition)
2959           {
2960             defer_incomplete_level++;
2961             this_deferred = true;
2962           }
2963
2964         /* If both a size and rep clause was specified, put the size in
2965            the record type now so that it can get the proper mode.  */
2966         if (has_rep && Known_RM_Size (gnat_entity))
2967           TYPE_SIZE (gnu_type)
2968             = UI_To_gnu (RM_Size (gnat_entity), bitsizetype);
2969
2970         /* Always set the alignment here so that it can be used to
2971            set the mode, if it is making the alignment stricter.  If
2972            it is invalid, it will be checked again below.  If this is to
2973            be Atomic, choose a default alignment of a word unless we know
2974            the size and it's smaller.  */
2975         if (Known_Alignment (gnat_entity))
2976           TYPE_ALIGN (gnu_type)
2977             = validate_alignment (Alignment (gnat_entity), gnat_entity, 0);
2978         else if (Is_Atomic_Or_VFA (gnat_entity) && Known_Esize (gnat_entity))
2979           {
2980             unsigned int size = UI_To_Int (Esize (gnat_entity));
2981             TYPE_ALIGN (gnu_type)
2982               = size >= BITS_PER_WORD ? BITS_PER_WORD : ceil_pow2 (size);
2983           }
2984         /* If a type needs strict alignment, the minimum size will be the
2985            type size instead of the RM size (see validate_size).  Cap the
2986            alignment, lest it causes this type size to become too large.  */
2987         else if (Strict_Alignment (gnat_entity) && Known_RM_Size (gnat_entity))
2988           {
2989             unsigned int raw_size = UI_To_Int (RM_Size (gnat_entity));
2990             unsigned int raw_align = raw_size & -raw_size;
2991             if (raw_align < BIGGEST_ALIGNMENT)
2992               TYPE_ALIGN (gnu_type) = raw_align;
2993           }
2994         else
2995           TYPE_ALIGN (gnu_type) = 0;
2996
2997         /* If we have a Parent_Subtype, make a field for the parent.  If
2998            this record has rep clauses, force the position to zero.  */
2999         if (Present (Parent_Subtype (gnat_entity)))
3000           {
3001             Entity_Id gnat_parent = Parent_Subtype (gnat_entity);
3002             tree gnu_dummy_parent_type = make_node (RECORD_TYPE);
3003             tree gnu_parent;
3004
3005             /* A major complexity here is that the parent subtype will
3006                reference our discriminants in its Stored_Constraint list.
3007                But those must reference the parent component of this record
3008                which is precisely of the parent subtype we have not built yet!
3009                To break the circle we first build a dummy COMPONENT_REF which
3010                represents the "get to the parent" operation and initialize
3011                each of those discriminants to a COMPONENT_REF of the above
3012                dummy parent referencing the corresponding discriminant of the
3013                base type of the parent subtype.  */
3014             gnu_get_parent = build3 (COMPONENT_REF, gnu_dummy_parent_type,
3015                                      build0 (PLACEHOLDER_EXPR, gnu_type),
3016                                      build_decl (input_location,
3017                                                  FIELD_DECL, NULL_TREE,
3018                                                  gnu_dummy_parent_type),
3019                                      NULL_TREE);
3020
3021             if (has_discr)
3022               for (gnat_field = First_Stored_Discriminant (gnat_entity);
3023                    Present (gnat_field);
3024                    gnat_field = Next_Stored_Discriminant (gnat_field))
3025                 if (Present (Corresponding_Discriminant (gnat_field)))
3026                   {
3027                     tree gnu_field
3028                       = gnat_to_gnu_field_decl (Corresponding_Discriminant
3029                                                 (gnat_field));
3030                     save_gnu_tree
3031                       (gnat_field,
3032                        build3 (COMPONENT_REF, TREE_TYPE (gnu_field),
3033                                gnu_get_parent, gnu_field, NULL_TREE),
3034                        true);
3035                   }
3036
3037             /* Then we build the parent subtype.  If it has discriminants but
3038                the type itself has unknown discriminants, this means that it
3039                doesn't contain information about how the discriminants are
3040                derived from those of the ancestor type, so it cannot be used
3041                directly.  Instead it is built by cloning the parent subtype
3042                of the underlying record view of the type, for which the above
3043                derivation of discriminants has been made explicit.  */
3044             if (Has_Discriminants (gnat_parent)
3045                 && Has_Unknown_Discriminants (gnat_entity))
3046               {
3047                 Entity_Id gnat_uview = Underlying_Record_View (gnat_entity);
3048
3049                 /* If we are defining the type, the underlying record
3050                    view must already have been elaborated at this point.
3051                    Otherwise do it now as its parent subtype cannot be
3052                    technically elaborated on its own.  */
3053                 if (definition)
3054                   gcc_assert (present_gnu_tree (gnat_uview));
3055                 else
3056                   gnat_to_gnu_entity (gnat_uview, NULL_TREE, 0);
3057
3058                 gnu_parent = gnat_to_gnu_type (Parent_Subtype (gnat_uview));
3059
3060                 /* Substitute the "get to the parent" of the type for that
3061                    of its underlying record view in the cloned type.  */
3062                 for (gnat_field = First_Stored_Discriminant (gnat_uview);
3063                      Present (gnat_field);
3064                      gnat_field = Next_Stored_Discriminant (gnat_field))
3065                   if (Present (Corresponding_Discriminant (gnat_field)))
3066                     {
3067                       tree gnu_field = gnat_to_gnu_field_decl (gnat_field);
3068                       tree gnu_ref
3069                         = build3 (COMPONENT_REF, TREE_TYPE (gnu_field),
3070                                   gnu_get_parent, gnu_field, NULL_TREE);
3071                       gnu_parent
3072                         = substitute_in_type (gnu_parent, gnu_field, gnu_ref);
3073                     }
3074               }
3075             else
3076               gnu_parent = gnat_to_gnu_type (gnat_parent);
3077
3078             /* Finally we fix up both kinds of twisted COMPONENT_REF we have
3079                initially built.  The discriminants must reference the fields
3080                of the parent subtype and not those of its base type for the
3081                placeholder machinery to properly work.  */
3082             if (has_discr)
3083               {
3084                 /* The actual parent subtype is the full view.  */
3085                 if (IN (Ekind (gnat_parent), Private_Kind))
3086                   {
3087                     if (Present (Full_View (gnat_parent)))
3088                       gnat_parent = Full_View (gnat_parent);
3089                     else
3090                       gnat_parent = Underlying_Full_View (gnat_parent);
3091                   }
3092
3093                 for (gnat_field = First_Stored_Discriminant (gnat_entity);
3094                      Present (gnat_field);
3095                      gnat_field = Next_Stored_Discriminant (gnat_field))
3096                   if (Present (Corresponding_Discriminant (gnat_field)))
3097                     {
3098                       Entity_Id field;
3099                       for (field = First_Stored_Discriminant (gnat_parent);
3100                            Present (field);
3101                            field = Next_Stored_Discriminant (field))
3102                         if (same_discriminant_p (gnat_field, field))
3103                           break;
3104                       gcc_assert (Present (field));
3105                       TREE_OPERAND (get_gnu_tree (gnat_field), 1)
3106                         = gnat_to_gnu_field_decl (field);
3107                     }
3108               }
3109
3110             /* The "get to the parent" COMPONENT_REF must be given its
3111                proper type...  */
3112             TREE_TYPE (gnu_get_parent) = gnu_parent;
3113
3114             /* ...and reference the _Parent field of this record.  */
3115             gnu_field
3116               = create_field_decl (parent_name_id,
3117                                    gnu_parent, gnu_type,
3118                                    has_rep
3119                                    ? TYPE_SIZE (gnu_parent) : NULL_TREE,
3120                                    has_rep
3121                                    ? bitsize_zero_node : NULL_TREE,
3122                                    0, 1);
3123             DECL_INTERNAL_P (gnu_field) = 1;
3124             TREE_OPERAND (gnu_get_parent, 1) = gnu_field;
3125             TYPE_FIELDS (gnu_type) = gnu_field;
3126           }
3127
3128         /* Make the fields for the discriminants and put them into the record
3129            unless it's an Unchecked_Union.  */
3130         if (has_discr)
3131           for (gnat_field = First_Stored_Discriminant (gnat_entity);
3132                Present (gnat_field);
3133                gnat_field = Next_Stored_Discriminant (gnat_field))
3134             {
3135               /* If this is a record extension and this discriminant is the
3136                  renaming of another discriminant, we've handled it above.  */
3137               if (Present (Parent_Subtype (gnat_entity))
3138                   && Present (Corresponding_Discriminant (gnat_field)))
3139                 continue;
3140
3141               gnu_field
3142                 = gnat_to_gnu_field (gnat_field, gnu_type, packed, definition,
3143                                      debug_info_p);
3144
3145               /* Make an expression using a PLACEHOLDER_EXPR from the
3146                  FIELD_DECL node just created and link that with the
3147                  corresponding GNAT defining identifier.  */
3148               save_gnu_tree (gnat_field,
3149                              build3 (COMPONENT_REF, TREE_TYPE (gnu_field),
3150                                      build0 (PLACEHOLDER_EXPR, gnu_type),
3151                                      gnu_field, NULL_TREE),
3152                              true);
3153
3154               if (!is_unchecked_union)
3155                 {
3156                   DECL_CHAIN (gnu_field) = gnu_field_list;
3157                   gnu_field_list = gnu_field;
3158                 }
3159             }
3160
3161         /* If we have a derived untagged type that renames discriminants in
3162            the root type, the (stored) discriminants are a just copy of the
3163            discriminants of the root type.  This means that any constraints
3164            added by the renaming in the derivation are disregarded as far
3165            as the layout of the derived type is concerned.  To rescue them,
3166            we change the type of the (stored) discriminants to a subtype
3167            with the bounds of the type of the visible discriminants.  */
3168         if (has_discr
3169             && !is_extension
3170             && Stored_Constraint (gnat_entity) != No_Elist)
3171           for (gnat_constr = First_Elmt (Stored_Constraint (gnat_entity));
3172                gnat_constr != No_Elmt;
3173                gnat_constr = Next_Elmt (gnat_constr))
3174             if (Nkind (Node (gnat_constr)) == N_Identifier
3175                 /* Ignore access discriminants.  */
3176                 && !Is_Access_Type (Etype (Node (gnat_constr)))
3177                 && Ekind (Entity (Node (gnat_constr))) == E_Discriminant)
3178               {
3179                 Entity_Id gnat_discr = Entity (Node (gnat_constr));
3180                 tree gnu_discr_type, gnu_ref;
3181
3182                 /* If the scope of the discriminant is not the record type,
3183                    this means that we're processing the implicit full view
3184                    of a type derived from a private discriminated type: in
3185                    this case, the Stored_Constraint list is simply copied
3186                    from the partial view, see Build_Derived_Private_Type.
3187                    So we need to retrieve the corresponding discriminant
3188                    of the implicit full view, otherwise we will abort.  */
3189                 if (Scope (gnat_discr) != gnat_entity)
3190                   {
3191                     Entity_Id field;
3192                     for (field = First_Entity (gnat_entity);
3193                          Present (field);
3194                          field = Next_Entity (field))
3195                       if (Ekind (field) == E_Discriminant
3196                           && same_discriminant_p (gnat_discr, field))
3197                         break;
3198                     gcc_assert (Present (field));
3199                     gnat_discr = field;
3200                   }
3201
3202                 gnu_discr_type = gnat_to_gnu_type (Etype (gnat_discr));
3203                 gnu_ref
3204                   = gnat_to_gnu_entity (Original_Record_Component (gnat_discr),
3205                                         NULL_TREE, 0);
3206
3207                 /* GNU_REF must be an expression using a PLACEHOLDER_EXPR built
3208                    just above for one of the stored discriminants.  */
3209                 gcc_assert (TREE_TYPE (TREE_OPERAND (gnu_ref, 0)) == gnu_type);
3210
3211                 if (gnu_discr_type != TREE_TYPE (gnu_ref))
3212                   {
3213                     const unsigned prec = TYPE_PRECISION (TREE_TYPE (gnu_ref));
3214                     tree gnu_subtype
3215                       = TYPE_UNSIGNED (TREE_TYPE (gnu_ref))
3216                         ? make_unsigned_type (prec) : make_signed_type (prec);
3217                     TREE_TYPE (gnu_subtype) = TREE_TYPE (gnu_ref);
3218                     TYPE_EXTRA_SUBTYPE_P (gnu_subtype) = 1;
3219                     SET_TYPE_RM_MIN_VALUE (gnu_subtype,
3220                                            TYPE_MIN_VALUE (gnu_discr_type));
3221                     SET_TYPE_RM_MAX_VALUE (gnu_subtype,
3222                                            TYPE_MAX_VALUE (gnu_discr_type));
3223                     TREE_TYPE (gnu_ref)
3224                       = TREE_TYPE (TREE_OPERAND (gnu_ref, 1)) = gnu_subtype;
3225                   }
3226               }
3227
3228         /* Add the fields into the record type and finish it up.  */
3229         components_to_record (gnu_type, Component_List (record_definition),
3230                               gnu_field_list, packed, definition, false,
3231                               all_rep, is_unchecked_union,
3232                               !Comes_From_Source (gnat_entity), debug_info_p,
3233                               false, OK_To_Reorder_Components (gnat_entity),
3234                               all_rep ? NULL_TREE : bitsize_zero_node, NULL);
3235
3236         /* Fill in locations of fields.  */
3237         annotate_rep (gnat_entity, gnu_type);
3238
3239         /* If there are any entities in the chain corresponding to components
3240            that we did not elaborate, ensure we elaborate their types if they
3241            are Itypes.  */
3242         for (gnat_temp = First_Entity (gnat_entity);
3243              Present (gnat_temp);
3244              gnat_temp = Next_Entity (gnat_temp))
3245           if ((Ekind (gnat_temp) == E_Component
3246                || Ekind (gnat_temp) == E_Discriminant)
3247               && Is_Itype (Etype (gnat_temp))
3248               && !present_gnu_tree (gnat_temp))
3249             gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
3250
3251         /* If this is a record type associated with an exception definition,
3252            equate its fields to those of the standard exception type.  This
3253            will make it possible to convert between them.  */
3254         if (gnu_entity_name == exception_data_name_id)
3255           {
3256             tree gnu_std_field;
3257             for (gnu_field = TYPE_FIELDS (gnu_type),
3258                  gnu_std_field = TYPE_FIELDS (except_type_node);
3259                  gnu_field;
3260                  gnu_field = DECL_CHAIN (gnu_field),
3261                  gnu_std_field = DECL_CHAIN (gnu_std_field))
3262               SET_DECL_ORIGINAL_FIELD_TO_FIELD (gnu_field, gnu_std_field);
3263             gcc_assert (!gnu_std_field);
3264           }
3265       }
3266       break;
3267
3268     case E_Class_Wide_Subtype:
3269       /* If an equivalent type is present, that is what we should use.
3270          Otherwise, fall through to handle this like a record subtype
3271          since it may have constraints.  */
3272       if (gnat_equiv_type != gnat_entity)
3273         {
3274           gnu_decl = gnat_to_gnu_entity (gnat_equiv_type, NULL_TREE, 0);
3275           maybe_present = true;
3276           break;
3277         }
3278
3279       /* ... fall through ... */
3280
3281     case E_Record_Subtype:
3282       /* If Cloned_Subtype is Present it means this record subtype has
3283          identical layout to that type or subtype and we should use
3284          that GCC type for this one.  The front end guarantees that
3285          the component list is shared.  */
3286       if (Present (Cloned_Subtype (gnat_entity)))
3287         {
3288           gnu_decl = gnat_to_gnu_entity (Cloned_Subtype (gnat_entity),
3289                                          NULL_TREE, 0);
3290           maybe_present = true;
3291           break;
3292         }
3293
3294       /* Otherwise, first ensure the base type is elaborated.  Then, if we are
3295          changing the type, make a new type with each field having the type of
3296          the field in the new subtype but the position computed by transforming
3297          every discriminant reference according to the constraints.  We don't
3298          see any difference between private and non-private type here since
3299          derivations from types should have been deferred until the completion
3300          of the private type.  */
3301       else
3302         {
3303           Entity_Id gnat_base_type = Implementation_Base_Type (gnat_entity);
3304           tree gnu_base_type;
3305
3306           if (!definition)
3307             {
3308               defer_incomplete_level++;
3309               this_deferred = true;
3310             }
3311
3312           gnu_base_type
3313             = TYPE_MAIN_VARIANT (gnat_to_gnu_type (gnat_base_type));
3314
3315           if (present_gnu_tree (gnat_entity))
3316             {
3317               maybe_present = true;
3318               break;
3319             }
3320
3321           /* If this is a record subtype associated with a dispatch table,
3322              strip the suffix.  This is necessary to make sure 2 different
3323              subtypes associated with the imported and exported views of a
3324              dispatch table are properly merged in LTO mode.  */
3325           if (Is_Dispatch_Table_Entity (gnat_entity))
3326             {
3327               char *p;
3328               Get_Encoded_Name (gnat_entity);
3329               p = strchr (Name_Buffer, '_');
3330               gcc_assert (p);
3331               strcpy (p+2, "dtS");
3332               gnu_entity_name = get_identifier (Name_Buffer);
3333             }
3334
3335           /* When the subtype has discriminants and these discriminants affect
3336              the initial shape it has inherited, factor them in.  But for an
3337              Unchecked_Union (it must be an Itype), just return the type.
3338              We can't just test Is_Constrained because private subtypes without
3339              discriminants of types with discriminants with default expressions
3340              are Is_Constrained but aren't constrained!  */
3341           if (IN (Ekind (gnat_base_type), Record_Kind)
3342               && !Is_Unchecked_Union (gnat_base_type)
3343               && !Is_For_Access_Subtype (gnat_entity)
3344               && Has_Discriminants (gnat_entity)
3345               && Is_Constrained (gnat_entity)
3346               && Stored_Constraint (gnat_entity) != No_Elist)
3347             {
3348               vec<subst_pair> gnu_subst_list
3349                 = build_subst_list (gnat_entity, gnat_base_type, definition);
3350               tree gnu_unpad_base_type, gnu_rep_part, gnu_variant_part;
3351               tree gnu_pos_list, gnu_field_list = NULL_TREE;
3352               bool selected_variant = false, all_constant_pos = true;
3353               Entity_Id gnat_field;
3354               vec<variant_desc> gnu_variant_list;
3355
3356               gnu_type = make_node (RECORD_TYPE);
3357               TYPE_NAME (gnu_type) = gnu_entity_name;
3358               TYPE_PACKED (gnu_type) = TYPE_PACKED (gnu_base_type);
3359               process_attributes (&gnu_type, &attr_list, true, gnat_entity);
3360
3361               /* Set the size, alignment and alias set of the new type to
3362                  match that of the old one, doing required substitutions.  */
3363               copy_and_substitute_in_size (gnu_type, gnu_base_type,
3364                                            gnu_subst_list);
3365
3366               if (TYPE_IS_PADDING_P (gnu_base_type))
3367                 gnu_unpad_base_type = TREE_TYPE (TYPE_FIELDS (gnu_base_type));
3368               else
3369                 gnu_unpad_base_type = gnu_base_type;
3370
3371               /* Look for REP and variant parts in the base type.  */
3372               gnu_rep_part = get_rep_part (gnu_unpad_base_type);
3373               gnu_variant_part = get_variant_part (gnu_unpad_base_type);
3374
3375               /* If there is a variant part, we must compute whether the
3376                  constraints statically select a particular variant.  If
3377                  so, we simply drop the qualified union and flatten the
3378                  list of fields.  Otherwise we'll build a new qualified
3379                  union for the variants that are still relevant.  */
3380               if (gnu_variant_part)
3381                 {
3382                   variant_desc *v;
3383                   unsigned int i;
3384
3385                   gnu_variant_list
3386                     = build_variant_list (TREE_TYPE (gnu_variant_part),
3387                                           gnu_subst_list,
3388                                           vNULL);
3389
3390                   /* If all the qualifiers are unconditionally true, the
3391                      innermost variant is statically selected.  */
3392                   selected_variant = true;
3393                   FOR_EACH_VEC_ELT (gnu_variant_list, i, v)
3394                     if (!integer_onep (v->qual))
3395                       {
3396                         selected_variant = false;
3397                         break;
3398                       }
3399
3400                   /* Otherwise, create the new variants.  */
3401                   if (!selected_variant)
3402                     FOR_EACH_VEC_ELT (gnu_variant_list, i, v)
3403                       {
3404                         tree old_variant = v->type;
3405                         tree new_variant = make_node (RECORD_TYPE);
3406                         tree suffix
3407                           = concat_name (DECL_NAME (gnu_variant_part),
3408                                          IDENTIFIER_POINTER
3409                                          (DECL_NAME (v->field)));
3410                         TYPE_NAME (new_variant)
3411                           = concat_name (TYPE_NAME (gnu_type),
3412                                          IDENTIFIER_POINTER (suffix));
3413                         copy_and_substitute_in_size (new_variant, old_variant,
3414                                                      gnu_subst_list);
3415                         v->new_type = new_variant;
3416                       }
3417                 }
3418               else
3419                 {
3420                   gnu_variant_list.create (0);
3421                   selected_variant = false;
3422                 }
3423
3424               /* Make a list of fields and their position in the base type.  */
3425               gnu_pos_list
3426                 = build_position_list (gnu_unpad_base_type,
3427                                        gnu_variant_list.exists ()
3428                                        && !selected_variant,
3429                                        size_zero_node, bitsize_zero_node,
3430                                        BIGGEST_ALIGNMENT, NULL_TREE);
3431
3432               /* Now go down every component in the subtype and compute its
3433                  size and position from those of the component in the base
3434                  type and from the constraints of the subtype.  */
3435               for (gnat_field = First_Entity (gnat_entity);
3436                    Present (gnat_field);
3437                    gnat_field = Next_Entity (gnat_field))
3438                 if ((Ekind (gnat_field) == E_Component
3439                      || Ekind (gnat_field) == E_Discriminant)
3440                     && !(Present (Corresponding_Discriminant (gnat_field))
3441                          && Is_Tagged_Type (gnat_base_type))
3442                     && Underlying_Type
3443                        (Scope (Original_Record_Component (gnat_field)))
3444                        == gnat_base_type)
3445                   {
3446                     Name_Id gnat_name = Chars (gnat_field);
3447                     Entity_Id gnat_old_field
3448                       = Original_Record_Component (gnat_field);
3449                     tree gnu_old_field
3450                       = gnat_to_gnu_field_decl (gnat_old_field);
3451                     tree gnu_context = DECL_CONTEXT (gnu_old_field);
3452                     tree gnu_field, gnu_field_type, gnu_size, gnu_pos;
3453                     tree gnu_cont_type, gnu_last = NULL_TREE;
3454
3455                     /* If the type is the same, retrieve the GCC type from the
3456                        old field to take into account possible adjustments.  */
3457                     if (Etype (gnat_field) == Etype (gnat_old_field))
3458                       gnu_field_type = TREE_TYPE (gnu_old_field);
3459                     else
3460                       gnu_field_type = gnat_to_gnu_type (Etype (gnat_field));
3461
3462                     /* If there was a component clause, the field types must be
3463                        the same for the type and subtype, so copy the data from
3464                        the old field to avoid recomputation here.  Also if the
3465                        field is justified modular and the optimization in
3466                        gnat_to_gnu_field was applied.  */
3467                     if (Present (Component_Clause (gnat_old_field))
3468                         || (TREE_CODE (gnu_field_type) == RECORD_TYPE
3469                             && TYPE_JUSTIFIED_MODULAR_P (gnu_field_type)
3470                             && TREE_TYPE (TYPE_FIELDS (gnu_field_type))
3471                                == TREE_TYPE (gnu_old_field)))
3472                       {
3473                         gnu_size = DECL_SIZE (gnu_old_field);
3474                         gnu_field_type = TREE_TYPE (gnu_old_field);
3475                       }
3476
3477                     /* If the old field was packed and of constant size, we
3478                        have to get the old size here, as it might differ from
3479                        what the Etype conveys and the latter might overlap
3480                        onto the following field.  Try to arrange the type for
3481                        possible better packing along the way.  */
3482                     else if (DECL_PACKED (gnu_old_field)
3483                              && TREE_CODE (DECL_SIZE (gnu_old_field))
3484                                 == INTEGER_CST)
3485                       {
3486                         gnu_size = DECL_SIZE (gnu_old_field);
3487                         if (RECORD_OR_UNION_TYPE_P (gnu_field_type)
3488                             && !TYPE_FAT_POINTER_P (gnu_field_type)
3489                             && tree_fits_uhwi_p (TYPE_SIZE (gnu_field_type)))
3490                           gnu_field_type
3491                             = make_packable_type (gnu_field_type, true);
3492                       }
3493
3494                     else
3495                       gnu_size = TYPE_SIZE (gnu_field_type);
3496
3497                     /* If the context of the old field is the base type or its
3498                        REP part (if any), put the field directly in the new
3499                        type; otherwise look up the context in the variant list
3500                        and put the field either in the new type if there is a
3501                        selected variant or in one of the new variants.  */
3502                     if (gnu_context == gnu_unpad_base_type
3503                         || (gnu_rep_part
3504                             && gnu_context == TREE_TYPE (gnu_rep_part)))
3505                       gnu_cont_type = gnu_type;
3506                     else
3507                       {
3508                         variant_desc *v;
3509                         unsigned int i;
3510                         tree rep_part;
3511
3512                         FOR_EACH_VEC_ELT (gnu_variant_list, i, v)
3513                           if (gnu_context == v->type
3514                               || ((rep_part = get_rep_part (v->type))
3515                                   && gnu_context == TREE_TYPE (rep_part)))
3516                             break;
3517                         if (v)
3518                           {
3519                             if (selected_variant)
3520                               gnu_cont_type = gnu_type;
3521                             else
3522                               gnu_cont_type = v->new_type;
3523                           }
3524                         else
3525                           /* The front-end may pass us "ghost" components if
3526                              it fails to recognize that a constrained subtype
3527                              is statically constrained.  Discard them.  */
3528                           continue;
3529                       }
3530
3531                     /* Now create the new field modeled on the old one.  */
3532                     gnu_field
3533                       = create_field_decl_from (gnu_old_field, gnu_field_type,
3534                                                 gnu_cont_type, gnu_size,
3535                                                 gnu_pos_list, gnu_subst_list);
3536                     gnu_pos = DECL_FIELD_OFFSET (gnu_field);
3537
3538                     /* Put it in one of the new variants directly.  */
3539                     if (gnu_cont_type != gnu_type)
3540                       {
3541                         DECL_CHAIN (gnu_field) = TYPE_FIELDS (gnu_cont_type);
3542                         TYPE_FIELDS (gnu_cont_type) = gnu_field;
3543                       }
3544
3545                     /* To match the layout crafted in components_to_record,
3546                        if this is the _Tag or _Parent field, put it before
3547                        any other fields.  */
3548                     else if (gnat_name == Name_uTag
3549                              || gnat_name == Name_uParent)
3550                       gnu_field_list = chainon (gnu_field_list, gnu_field);
3551
3552                     /* Similarly, if this is the _Controller field, put
3553                        it before the other fields except for the _Tag or
3554                        _Parent field.  */
3555                     else if (gnat_name == Name_uController && gnu_last)
3556                       {
3557                         DECL_CHAIN (gnu_field) = DECL_CHAIN (gnu_last);
3558                         DECL_CHAIN (gnu_last) = gnu_field;
3559                       }
3560
3561                     /* Otherwise, if this is a regular field, put it after
3562                        the other fields.  */
3563                     else
3564                       {
3565                         DECL_CHAIN (gnu_field) = gnu_field_list;
3566                         gnu_field_list = gnu_field;
3567                         if (!gnu_last)
3568                           gnu_last = gnu_field;
3569                         if (TREE_CODE (gnu_pos) != INTEGER_CST)
3570                           all_constant_pos = false;
3571                       }
3572
3573                     save_gnu_tree (gnat_field, gnu_field, false);
3574                   }
3575
3576               /* If there is a variant list, a selected variant and the fields
3577                  all have a constant position, put them in order of increasing
3578                  position to match that of constant CONSTRUCTORs.  Likewise if
3579                  there is no variant list but a REP part, since the latter has
3580                  been flattened in the process.  */
3581               if (((gnu_variant_list.exists () && selected_variant)
3582                    || (!gnu_variant_list.exists () && gnu_rep_part))
3583                   && all_constant_pos)
3584                 {
3585                   const int len = list_length (gnu_field_list);
3586                   tree *field_arr = XALLOCAVEC (tree, len), t;
3587                   int i;
3588
3589                   for (t = gnu_field_list, i = 0; t; t = DECL_CHAIN (t), i++)
3590                     field_arr[i] = t;
3591
3592                   qsort (field_arr, len, sizeof (tree), compare_field_bitpos);
3593
3594                   gnu_field_list = NULL_TREE;
3595                   for (i = 0; i < len; i++)
3596                     {
3597                       DECL_CHAIN (field_arr[i]) = gnu_field_list;
3598                       gnu_field_list = field_arr[i];
3599                     }
3600                 }
3601
3602               /* If there is a variant list and no selected variant, we need
3603                  to create the nest of variant parts from the old nest.  */
3604               else if (gnu_variant_list.exists () && !selected_variant)
3605                 {
3606                   tree new_variant_part
3607                     = create_variant_part_from (gnu_variant_part,
3608                                                 gnu_variant_list, gnu_type,
3609                                                 gnu_pos_list, gnu_subst_list);
3610                   DECL_CHAIN (new_variant_part) = gnu_field_list;
3611                   gnu_field_list = new_variant_part;
3612                 }
3613
3614               /* Now go through the entities again looking for Itypes that
3615                  we have not elaborated but should (e.g., Etypes of fields
3616                  that have Original_Components).  */
3617               for (gnat_field = First_Entity (gnat_entity);
3618                    Present (gnat_field); gnat_field = Next_Entity (gnat_field))
3619                 if ((Ekind (gnat_field) == E_Discriminant
3620                      || Ekind (gnat_field) == E_Component)
3621                     && !present_gnu_tree (Etype (gnat_field)))
3622                   gnat_to_gnu_entity (Etype (gnat_field), NULL_TREE, 0);
3623
3624               /* Do not emit debug info for the type yet since we're going to
3625                  modify it below.  */
3626               finish_record_type (gnu_type, nreverse (gnu_field_list), 2,
3627                                   false);
3628               compute_record_mode (gnu_type);
3629
3630               /* Fill in locations of fields.  */
3631               annotate_rep (gnat_entity, gnu_type);
3632
3633               /* If debugging information is being written for the type, write
3634                  a record that shows what we are a subtype of and also make a
3635                  variable that indicates our size, if still variable.  */
3636               if (debug_info_p)
3637                 {
3638                   tree gnu_subtype_marker = make_node (RECORD_TYPE);
3639                   tree gnu_unpad_base_name
3640                     = TYPE_IDENTIFIER (gnu_unpad_base_type);
3641                   tree gnu_size_unit = TYPE_SIZE_UNIT (gnu_type);
3642
3643                   TYPE_NAME (gnu_subtype_marker)
3644                     = create_concat_name (gnat_entity, "XVS");
3645                   finish_record_type (gnu_subtype_marker,
3646                                       create_field_decl (gnu_unpad_base_name,
3647                                                          build_reference_type
3648                                                          (gnu_unpad_base_type),
3649                                                          gnu_subtype_marker,
3650                                                          NULL_TREE, NULL_TREE,
3651                                                          0, 0),
3652                                       0, true);
3653
3654                   add_parallel_type (gnu_type, gnu_subtype_marker);
3655
3656                   if (definition
3657                       && TREE_CODE (gnu_size_unit) != INTEGER_CST
3658                       && !CONTAINS_PLACEHOLDER_P (gnu_size_unit))
3659                     TYPE_SIZE_UNIT (gnu_subtype_marker)
3660                       = create_var_decl (create_concat_name (gnat_entity,
3661                                                              "XVZ"),
3662                                          NULL_TREE, sizetype, gnu_size_unit,
3663                                          false, false, false, false, NULL,
3664                                          gnat_entity);
3665                 }
3666
3667               gnu_variant_list.release ();
3668               gnu_subst_list.release ();
3669
3670               /* Now we can finalize it.  */
3671               rest_of_record_type_compilation (gnu_type);
3672             }
3673
3674           /* Otherwise, go down all the components in the new type and make
3675              them equivalent to those in the base type.  */
3676           else
3677             {
3678               gnu_type = gnu_base_type;
3679
3680               for (gnat_temp = First_Entity (gnat_entity);
3681                    Present (gnat_temp);
3682                    gnat_temp = Next_Entity (gnat_temp))
3683                 if ((Ekind (gnat_temp) == E_Discriminant
3684                      && !Is_Unchecked_Union (gnat_base_type))
3685                     || Ekind (gnat_temp) == E_Component)
3686                   save_gnu_tree (gnat_temp,
3687                                  gnat_to_gnu_field_decl
3688                                  (Original_Record_Component (gnat_temp)),
3689                                  false);
3690             }
3691         }
3692       break;
3693
3694     case E_Access_Subprogram_Type:
3695       /* Use the special descriptor type for dispatch tables if needed,
3696          that is to say for the Prim_Ptr of a-tags.ads and its clones.
3697          Note that we are only required to do so for static tables in
3698          order to be compatible with the C++ ABI, but Ada 2005 allows
3699          to extend library level tagged types at the local level so
3700          we do it in the non-static case as well.  */
3701       if (TARGET_VTABLE_USES_DESCRIPTORS
3702           && Is_Dispatch_Table_Entity (gnat_entity))
3703         {
3704             gnu_type = fdesc_type_node;
3705             gnu_size = TYPE_SIZE (gnu_type);
3706             break;
3707         }
3708
3709       /* ... fall through ... */
3710
3711     case E_Anonymous_Access_Subprogram_Type:
3712       /* If we are not defining this entity, and we have incomplete
3713          entities being processed above us, make a dummy type and
3714          fill it in later.  */
3715       if (!definition && defer_incomplete_level != 0)
3716         {
3717           struct incomplete *p = XNEW (struct incomplete);
3718
3719           gnu_type
3720             = build_pointer_type
3721               (make_dummy_type (Directly_Designated_Type (gnat_entity)));
3722           gnu_decl = create_type_decl (gnu_entity_name, gnu_type,
3723                                        !Comes_From_Source (gnat_entity),
3724                                        debug_info_p, gnat_entity);
3725           this_made_decl = true;
3726           gnu_type = TREE_TYPE (gnu_decl);
3727           save_gnu_tree (gnat_entity, gnu_decl, false);
3728           saved = true;
3729
3730           p->old_type = TREE_TYPE (gnu_type);
3731           p->full_type = Directly_Designated_Type (gnat_entity);
3732           p->next = defer_incomplete_list;
3733           defer_incomplete_list = p;
3734           break;
3735         }
3736
3737       /* ... fall through ... */
3738
3739     case E_Allocator_Type:
3740     case E_Access_Type:
3741     case E_Access_Attribute_Type:
3742     case E_Anonymous_Access_Type:
3743     case E_General_Access_Type:
3744       {
3745         /* The designated type and its equivalent type for gigi.  */
3746         Entity_Id gnat_desig_type = Directly_Designated_Type (gnat_entity);
3747         Entity_Id gnat_desig_equiv = Gigi_Equivalent_Type (gnat_desig_type);
3748         /* Whether it comes from a limited with.  */
3749         bool is_from_limited_with
3750           = (IN (Ekind (gnat_desig_equiv), Incomplete_Kind)
3751              && From_Limited_With (gnat_desig_equiv));
3752         /* The "full view" of the designated type.  If this is an incomplete
3753            entity from a limited with, treat its non-limited view as the full
3754            view.  Otherwise, if this is an incomplete or private type, use the
3755            full view.  In the former case, we might point to a private type,
3756            in which case, we need its full view.  Also, we want to look at the
3757            actual type used for the representation, so this takes a total of
3758            three steps.  */
3759         Entity_Id gnat_desig_full_direct_first
3760           = (is_from_limited_with
3761              ? Non_Limited_View (gnat_desig_equiv)
3762              : (IN (Ekind (gnat_desig_equiv), Incomplete_Or_Private_Kind)
3763                 ? Full_View (gnat_desig_equiv) : Empty));
3764         Entity_Id gnat_desig_full_direct
3765           = ((is_from_limited_with
3766               && Present (gnat_desig_full_direct_first)
3767               && IN (Ekind (gnat_desig_full_direct_first), Private_Kind))
3768              ? Full_View (gnat_desig_full_direct_first)
3769              : gnat_desig_full_direct_first);
3770         Entity_Id gnat_desig_full
3771           = Gigi_Equivalent_Type (gnat_desig_full_direct);
3772         /* The type actually used to represent the designated type, either
3773            gnat_desig_full or gnat_desig_equiv.  */
3774         Entity_Id gnat_desig_rep;
3775         /* True if this is a pointer to an unconstrained array.  */
3776         bool is_unconstrained_array;
3777         /* We want to know if we'll be seeing the freeze node for any
3778            incomplete type we may be pointing to.  */
3779         bool in_main_unit
3780           = (Present (gnat_desig_full)
3781              ? In_Extended_Main_Code_Unit (gnat_desig_full)
3782              : In_Extended_Main_Code_Unit (gnat_desig_type));
3783         /* True if we make a dummy type here.  */
3784         bool made_dummy = false;
3785         /* The mode to be used for the pointer type.  */
3786         machine_mode p_mode = mode_for_size (esize, MODE_INT, 0);
3787         /* The GCC type used for the designated type.  */
3788         tree gnu_desig_type = NULL_TREE;
3789
3790         if (!targetm.valid_pointer_mode (p_mode))
3791           p_mode = ptr_mode;
3792
3793         /* If either the designated type or its full view is an unconstrained
3794            array subtype, replace it with the type it's a subtype of.  This
3795            avoids problems with multiple copies of unconstrained array types.
3796            Likewise, if the designated type is a subtype of an incomplete
3797            record type, use the parent type to avoid order of elaboration
3798            issues.  This can lose some code efficiency, but there is no
3799            alternative.  */
3800         if (Ekind (gnat_desig_equiv) == E_Array_Subtype
3801             && !Is_Constrained (gnat_desig_equiv))
3802           gnat_desig_equiv = Etype (gnat_desig_equiv);
3803         if (Present (gnat_desig_full)
3804             && ((Ekind (gnat_desig_full) == E_Array_Subtype
3805                  && !Is_Constrained (gnat_desig_full))
3806                 || (Ekind (gnat_desig_full) == E_Record_Subtype
3807                     && Ekind (Etype (gnat_desig_full)) == E_Record_Type)))
3808           gnat_desig_full = Etype (gnat_desig_full);
3809
3810         /* Set the type that's actually the representation of the designated
3811            type and also flag whether we have a unconstrained array.  */
3812         gnat_desig_rep
3813           = Present (gnat_desig_full) ? gnat_desig_full : gnat_desig_equiv;
3814         is_unconstrained_array
3815           = Is_Array_Type (gnat_desig_rep) && !Is_Constrained (gnat_desig_rep);
3816
3817         /* If we are pointing to an incomplete type whose completion is an
3818            unconstrained array, make dummy fat and thin pointer types to it.
3819            Likewise if the type itself is dummy or an unconstrained array.  */
3820         if (is_unconstrained_array
3821             && (Present (gnat_desig_full)
3822                 || (present_gnu_tree (gnat_desig_equiv)
3823                     && TYPE_IS_DUMMY_P
3824                        (TREE_TYPE (get_gnu_tree (gnat_desig_equiv))))
3825                 || (!in_main_unit
3826                     && defer_incomplete_level != 0
3827                     && !present_gnu_tree (gnat_desig_equiv))
3828                 || (in_main_unit
3829                     && is_from_limited_with
3830                     && Present (Freeze_Node (gnat_desig_equiv)))))
3831           {
3832             if (present_gnu_tree (gnat_desig_rep))
3833               gnu_desig_type = TREE_TYPE (get_gnu_tree (gnat_desig_rep));
3834             else
3835               {
3836                 gnu_desig_type = make_dummy_type (gnat_desig_rep);
3837                 made_dummy = true;
3838               }
3839
3840             /* If the call above got something that has a pointer, the pointer
3841                is our type.  This could have happened either because the type
3842                was elaborated or because somebody else executed the code.  */
3843             if (!TYPE_POINTER_TO (gnu_desig_type))
3844               build_dummy_unc_pointer_types (gnat_desig_equiv, gnu_desig_type);
3845             gnu_type = TYPE_POINTER_TO (gnu_desig_type);
3846           }
3847
3848         /* If we already know what the full type is, use it.  */
3849         else if (Present (gnat_desig_full)
3850                  && present_gnu_tree (gnat_desig_full))
3851           gnu_desig_type = TREE_TYPE (get_gnu_tree (gnat_desig_full));
3852
3853         /* Get the type of the thing we are to point to and build a pointer to
3854            it.  If it is a reference to an incomplete or private type with a
3855            full view that is a record, make a dummy type node and get the
3856            actual type later when we have verified it is safe.  */
3857         else if ((!in_main_unit
3858                   && !present_gnu_tree (gnat_desig_equiv)
3859                   && Present (gnat_desig_full)
3860                   && !present_gnu_tree (gnat_desig_full)
3861                   && Is_Record_Type (gnat_desig_full))
3862                  /* Likewise if we are pointing to a record or array and we are
3863                     to defer elaborating incomplete types.  We do this as this
3864                     access type may be the full view of a private type.  Note
3865                     that the unconstrained array case is handled above.  */
3866                  || ((!in_main_unit || imported_p)
3867                      && defer_incomplete_level != 0
3868                      && !present_gnu_tree (gnat_desig_equiv)
3869                      && (Is_Record_Type (gnat_desig_rep)
3870                          || Is_Array_Type (gnat_desig_rep)))
3871                  /* If this is a reference from a limited_with type back to our
3872                     main unit and there's a freeze node for it, either we have
3873                     already processed the declaration and made the dummy type,
3874                     in which case we just reuse the latter, or we have not yet,
3875                     in which case we make the dummy type and it will be reused
3876                     when the declaration is finally processed.  In both cases,
3877                     the pointer eventually created below will be automatically
3878                     adjusted when the freeze node is processed.  Note that the
3879                     unconstrained array case is handled above.  */
3880                  ||  (in_main_unit
3881                       && is_from_limited_with
3882                       && Present (Freeze_Node (gnat_desig_rep))))
3883           {
3884             gnu_desig_type = make_dummy_type (gnat_desig_equiv);
3885             made_dummy = true;
3886           }
3887
3888         /* Otherwise handle the case of a pointer to itself.  */
3889         else if (gnat_desig_equiv == gnat_entity)
3890           {
3891             gnu_type
3892               = build_pointer_type_for_mode (void_type_node, p_mode,
3893                                              No_Strict_Aliasing (gnat_entity));
3894             TREE_TYPE (gnu_type) = TYPE_POINTER_TO (gnu_type) = gnu_type;
3895           }
3896
3897         /* If expansion is disabled, the equivalent type of a concurrent type
3898            is absent, so build a dummy pointer type.  */
3899         else if (type_annotate_only && No (gnat_desig_equiv))
3900           gnu_type = ptr_void_type_node;
3901
3902         /* Finally, handle the default case where we can just elaborate our
3903            designated type.  */
3904         else
3905           gnu_desig_type = gnat_to_gnu_type (gnat_desig_equiv);
3906
3907         /* It is possible that a call to gnat_to_gnu_type above resolved our
3908            type.  If so, just return it.  */
3909         if (present_gnu_tree (gnat_entity))
3910           {
3911             maybe_present = true;
3912             break;
3913           }
3914
3915         /* If we haven't done it yet, build the pointer type the usual way.  */
3916         if (!gnu_type)
3917           {
3918             /* Modify the designated type if we are pointing only to constant
3919                objects, but don't do it for unconstrained arrays.  */
3920             if (Is_Access_Constant (gnat_entity)
3921                 && TREE_CODE (gnu_desig_type) != UNCONSTRAINED_ARRAY_TYPE)
3922               {
3923                 gnu_desig_type
3924                   = change_qualified_type (gnu_desig_type, TYPE_QUAL_CONST);
3925
3926                 /* Some extra processing is required if we are building a
3927                    pointer to an incomplete type (in the GCC sense).  We might
3928                    have such a type if we just made a dummy, or directly out
3929                    of the call to gnat_to_gnu_type above if we are processing
3930                    an access type for a record component designating the
3931                    record type itself.  */
3932                 if (TYPE_MODE (gnu_desig_type) == VOIDmode)
3933                   {
3934                     /* We must ensure that the pointer to variant we make will
3935                        be processed by update_pointer_to when the initial type
3936                        is completed.  Pretend we made a dummy and let further
3937                        processing act as usual.  */
3938                     made_dummy = true;
3939
3940                     /* We must ensure that update_pointer_to will not retrieve
3941                        the dummy variant when building a properly qualified
3942                        version of the complete type.  We take advantage of the
3943                        fact that get_qualified_type is requiring TYPE_NAMEs to
3944                        match to influence build_qualified_type and then also
3945                        update_pointer_to here.  */
3946                     TYPE_NAME (gnu_desig_type)
3947                       = create_concat_name (gnat_desig_type, "INCOMPLETE_CST");
3948                   }
3949               }
3950
3951             gnu_type
3952               = build_pointer_type_for_mode (gnu_desig_type, p_mode,
3953                                              No_Strict_Aliasing (gnat_entity));
3954           }
3955
3956         /* If we are not defining this object and we have made a dummy pointer,
3957            save our current definition, evaluate the actual type, and replace
3958            the tentative type we made with the actual one.  If we are to defer
3959            actually looking up the actual type, make an entry in the deferred
3960            list.  If this is from a limited with, we may have to defer to the
3961            end of the current unit.  */
3962         if ((!in_main_unit || is_from_limited_with) && made_dummy)
3963           {
3964             tree gnu_old_desig_type;
3965
3966             if (TYPE_IS_FAT_POINTER_P (gnu_type))
3967               {
3968                 gnu_old_desig_type = TYPE_UNCONSTRAINED_ARRAY (gnu_type);
3969                 if (esize == POINTER_SIZE)
3970                   gnu_type = build_pointer_type
3971                              (TYPE_OBJECT_RECORD_TYPE (gnu_old_desig_type));
3972               }
3973             else
3974               gnu_old_desig_type = TREE_TYPE (gnu_type);
3975
3976             process_attributes (&gnu_type, &attr_list, false, gnat_entity);
3977             gnu_decl = create_type_decl (gnu_entity_name, gnu_type,
3978                                          !Comes_From_Source (gnat_entity),
3979                                          debug_info_p, gnat_entity);
3980             this_made_decl = true;
3981             gnu_type = TREE_TYPE (gnu_decl);
3982             save_gnu_tree (gnat_entity, gnu_decl, false);
3983             saved = true;
3984
3985             /* Note that the call to gnat_to_gnu_type on gnat_desig_equiv might
3986                update gnu_old_desig_type directly, in which case it will not be
3987                a dummy type any more when we get into update_pointer_to.
3988
3989                This can happen e.g. when the designated type is a record type,
3990                because their elaboration starts with an initial node from
3991                make_dummy_type, which may be the same node as the one we got.
3992
3993                Besides, variants of this non-dummy type might have been created
3994                along the way.  update_pointer_to is expected to properly take
3995                care of those situations.  */
3996             if (defer_incomplete_level == 0 && !is_from_limited_with)
3997               {
3998                 update_pointer_to (TYPE_MAIN_VARIANT (gnu_old_desig_type),
3999                                    gnat_to_gnu_type (gnat_desig_equiv));
4000               }
4001             else
4002               {
4003                 struct incomplete *p = XNEW (struct incomplete);
4004                 struct incomplete **head
4005                   = (is_from_limited_with
4006                      ? &defer_limited_with : &defer_incomplete_list);
4007                 p->old_type = gnu_old_desig_type;
4008                 p->full_type = gnat_desig_equiv;
4009                 p->next = *head;
4010                 *head = p;
4011               }
4012           }
4013       }
4014       break;
4015
4016     case E_Access_Protected_Subprogram_Type:
4017     case E_Anonymous_Access_Protected_Subprogram_Type:
4018       if (type_annotate_only && No (gnat_equiv_type))
4019         gnu_type = ptr_void_type_node;
4020       else
4021         {
4022           /* The run-time representation is the equivalent type.  */
4023           gnu_type = gnat_to_gnu_type (gnat_equiv_type);
4024           maybe_present = true;
4025         }
4026
4027       if (Is_Itype (Directly_Designated_Type (gnat_entity))
4028           && !present_gnu_tree (Directly_Designated_Type (gnat_entity))
4029           && No (Freeze_Node (Directly_Designated_Type (gnat_entity)))
4030           && !Is_Record_Type (Scope (Directly_Designated_Type (gnat_entity))))
4031         gnat_to_gnu_entity (Directly_Designated_Type (gnat_entity),
4032                             NULL_TREE, 0);
4033
4034       break;
4035
4036     case E_Access_Subtype:
4037
4038       /* We treat this as identical to its base type; any constraint is
4039          meaningful only to the front-end.
4040
4041          The designated type must be elaborated as well, if it does
4042          not have its own freeze node.  Designated (sub)types created
4043          for constrained components of records with discriminants are
4044          not frozen by the front-end and thus not elaborated by gigi,
4045          because their use may appear before the base type is frozen,
4046          and because it is not clear that they are needed anywhere in
4047          gigi.  With the current model, there is no correct place where
4048          they could be elaborated.  */
4049
4050       gnu_type = gnat_to_gnu_type (Etype (gnat_entity));
4051       if (Is_Itype (Directly_Designated_Type (gnat_entity))
4052           && !present_gnu_tree (Directly_Designated_Type (gnat_entity))
4053           && Is_Frozen (Directly_Designated_Type (gnat_entity))
4054           && No (Freeze_Node (Directly_Designated_Type (gnat_entity))))
4055         {
4056           /* If we are not defining this entity, and we have incomplete
4057              entities being processed above us, make a dummy type and
4058              elaborate it later.  */
4059           if (!definition && defer_incomplete_level != 0)
4060             {
4061               struct incomplete *p = XNEW (struct incomplete);
4062
4063               p->old_type
4064                 = make_dummy_type (Directly_Designated_Type (gnat_entity));
4065               p->full_type = Directly_Designated_Type (gnat_entity);
4066               p->next = defer_incomplete_list;
4067               defer_incomplete_list = p;
4068             }
4069           else if (!IN (Ekind (Base_Type
4070                                (Directly_Designated_Type (gnat_entity))),
4071                         Incomplete_Or_Private_Kind))
4072             gnat_to_gnu_entity (Directly_Designated_Type (gnat_entity),
4073                                 NULL_TREE, 0);
4074         }
4075
4076       maybe_present = true;
4077       break;
4078
4079     /* Subprogram Entities
4080
4081        The following access functions are defined for subprograms:
4082
4083                 Etype           Return type or Standard_Void_Type.
4084                 First_Formal    The first formal parameter.
4085                 Is_Imported     Indicates that the subprogram has appeared in
4086                                 an INTERFACE or IMPORT pragma.  For now we
4087                                 assume that the external language is C.
4088                 Is_Exported     Likewise but for an EXPORT pragma.
4089                 Is_Inlined      True if the subprogram is to be inlined.
4090
4091        Each parameter is first checked by calling must_pass_by_ref on its
4092        type to determine if it is passed by reference.  For parameters which
4093        are copied in, if they are Ada In Out or Out parameters, their return
4094        value becomes part of a record which becomes the return type of the
4095        function (C function - note that this applies only to Ada procedures
4096        so there is no Ada return type).  Additional code to store back the
4097        parameters will be generated on the caller side.  This transformation
4098        is done here, not in the front-end.
4099
4100        The intended result of the transformation can be seen from the
4101        equivalent source rewritings that follow:
4102
4103                                                 struct temp {int a,b};
4104        procedure P (A,B: In Out ...) is         temp P (int A,B)
4105        begin                                    {
4106          ..                                       ..
4107        end P;                                     return {A,B};
4108                                                 }
4109
4110                                                 temp t;
4111        P(X,Y);                                  t = P(X,Y);
4112                                                 X = t.a , Y = t.b;
4113
4114        For subprogram types we need to perform mainly the same conversions to
4115        GCC form that are needed for procedures and function declarations.  The
4116        only difference is that at the end, we make a type declaration instead
4117        of a function declaration.  */
4118
4119     case E_Subprogram_Type:
4120     case E_Function:
4121     case E_Procedure:
4122       {
4123         /* The type returned by a function or else Standard_Void_Type for a
4124            procedure.  */
4125         Entity_Id gnat_return_type = Etype (gnat_entity);
4126         tree gnu_return_type;
4127         /* The first GCC parameter declaration (a PARM_DECL node).  The
4128            PARM_DECL nodes are chained through the DECL_CHAIN field, so this
4129            actually is the head of this parameter list.  */
4130         tree gnu_param_list = NULL_TREE;
4131         /* Non-null for subprograms containing parameters passed by copy-in
4132            copy-out (Ada In Out or Out parameters not passed by reference),
4133            in which case it is the list of nodes used to specify the values
4134            of the In Out/Out parameters that are returned as a record upon
4135            procedure return.  The TREE_PURPOSE of an element of this list is
4136            a field of the record and the TREE_VALUE is the PARM_DECL
4137            corresponding to that field.  This list will be saved in the
4138            TYPE_CI_CO_LIST field of the FUNCTION_TYPE node we create.  */
4139         tree gnu_cico_list = NULL_TREE;
4140         /* List of fields in return type of procedure with copy-in copy-out
4141            parameters.  */
4142         tree gnu_field_list = NULL_TREE;
4143         /* If an import pragma asks to map this subprogram to a GCC builtin,
4144            this is the builtin DECL node.  */
4145         tree gnu_builtin_decl = NULL_TREE;
4146         tree gnu_ext_name = create_concat_name (gnat_entity, NULL);
4147         Entity_Id gnat_param;
4148         enum inline_status_t inline_status
4149           = Has_Pragma_No_Inline (gnat_entity)
4150             ? is_suppressed
4151             : Has_Pragma_Inline_Always (gnat_entity)
4152               ? is_required
4153               : (Is_Inlined (gnat_entity) ? is_enabled : is_disabled);
4154         bool public_flag = Is_Public (gnat_entity) || imported_p;
4155         /* Subprograms marked both Intrinsic and Always_Inline need not
4156            have a body of their own.  */
4157         bool extern_flag
4158           = ((Is_Public (gnat_entity) && !definition)
4159              || imported_p
4160              || (Convention (gnat_entity) == Convention_Intrinsic
4161                  && Has_Pragma_Inline_Always (gnat_entity)));
4162         bool artificial_flag = !Comes_From_Source (gnat_entity);
4163        /* The semantics of "pure" in Ada essentially matches that of "const"
4164           in the back-end.  In particular, both properties are orthogonal to
4165           the "nothrow" property if the EH circuitry is explicit in the
4166           internal representation of the back-end.  If we are to completely
4167           hide the EH circuitry from it, we need to declare that calls to pure
4168           Ada subprograms that can throw have side effects since they can
4169           trigger an "abnormal" transfer of control flow; thus they can be
4170           neither "const" nor "pure" in the back-end sense.  */
4171         bool const_flag
4172           = (Exception_Mechanism == Back_End_Exceptions
4173              && Is_Pure (gnat_entity));
4174         bool noreturn_flag = No_Return (gnat_entity);
4175         bool return_by_direct_ref_p = false;
4176         bool return_by_invisi_ref_p = false;
4177         bool return_unconstrained_p = false;
4178         int parmnum;
4179
4180         /* A parameter may refer to this type, so defer completion of any
4181            incomplete types.  */
4182         if (kind == E_Subprogram_Type && !definition)
4183           {
4184             defer_incomplete_level++;
4185             this_deferred = true;
4186           }
4187
4188         /* If the subprogram has an alias, it is probably inherited, so
4189            we can use the original one.  If the original "subprogram"
4190            is actually an enumeration literal, it may be the first use
4191            of its type, so we must elaborate that type now.  */
4192         if (Present (Alias (gnat_entity)))
4193           {
4194             if (Ekind (Alias (gnat_entity)) == E_Enumeration_Literal)
4195               gnat_to_gnu_entity (Etype (Alias (gnat_entity)), NULL_TREE, 0);
4196
4197             gnu_decl = gnat_to_gnu_entity (Alias (gnat_entity), gnu_expr, 0);
4198
4199             /* Elaborate any Itypes in the parameters of this entity.  */
4200             for (gnat_temp = First_Formal_With_Extras (gnat_entity);
4201                  Present (gnat_temp);
4202                  gnat_temp = Next_Formal_With_Extras (gnat_temp))
4203               if (Is_Itype (Etype (gnat_temp)))
4204                 gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
4205
4206             break;
4207           }
4208
4209         /* If this subprogram is expectedly bound to a GCC builtin, fetch the
4210            corresponding DECL node.  Proper generation of calls later on need
4211            proper parameter associations so we don't "break;" here.  */
4212         if (Convention (gnat_entity) == Convention_Intrinsic
4213             && Present (Interface_Name (gnat_entity)))
4214           {
4215             gnu_builtin_decl = builtin_decl_for (gnu_ext_name);
4216
4217             /* Inability to find the builtin decl most often indicates a
4218                genuine mistake, but imports of unregistered intrinsics are
4219                sometimes issued on purpose to allow hooking in alternate
4220                bodies.  We post a warning conditioned on Wshadow in this case,
4221                to let developers be notified on demand without risking false
4222                positives with common default sets of options.  */
4223
4224             if (gnu_builtin_decl == NULL_TREE && warn_shadow)
4225               post_error ("?gcc intrinsic not found for&!", gnat_entity);
4226           }
4227
4228         /* ??? What if we don't find the builtin node above ? warn ? err ?
4229            In the current state we neither warn nor err, and calls will just
4230            be handled as for regular subprograms.  */
4231
4232         /* Look into the return type and get its associated GCC tree.  If it
4233            is not void, compute various flags for the subprogram type.  */
4234         if (Ekind (gnat_return_type) == E_Void)
4235           gnu_return_type = void_type_node;
4236         else
4237           {
4238             /* Ada 2012 (AI05-0151): Incomplete types coming from a limited
4239                context may now appear in parameter and result profiles.  If
4240                we are only annotating types, break circularities here.  */
4241             if (type_annotate_only
4242                 && is_from_limited_with_of_main (gnat_return_type))
4243               gnu_return_type = ptr_void_type_node;
4244             else
4245               gnu_return_type = gnat_to_gnu_type (gnat_return_type);
4246
4247             /* If this function returns by reference, make the actual return
4248                type the pointer type and make a note of that.  */
4249             if (Returns_By_Ref (gnat_entity))
4250               {
4251                 gnu_return_type = build_pointer_type (gnu_return_type);
4252                 return_by_direct_ref_p = true;
4253               }
4254
4255             /* If the return type is an unconstrained array type, the return
4256                value will be allocated on the secondary stack so the actual
4257                return type is the fat pointer type.  */
4258             else if (TREE_CODE (gnu_return_type) == UNCONSTRAINED_ARRAY_TYPE)
4259               {
4260                 gnu_return_type = TREE_TYPE (gnu_return_type);
4261                 return_unconstrained_p = true;
4262               }
4263
4264             /* Likewise, if the return type requires a transient scope, the
4265                return value will also be allocated on the secondary stack so
4266                the actual return type is the pointer type.  */
4267             else if (Requires_Transient_Scope (gnat_return_type))
4268               {
4269                 gnu_return_type = build_pointer_type (gnu_return_type);
4270                 return_unconstrained_p = true;
4271               }
4272
4273             /* If the Mechanism is By_Reference, ensure this function uses the
4274                target's by-invisible-reference mechanism, which may not be the
4275                same as above (e.g. it might be passing an extra parameter).  */
4276             else if (kind == E_Function
4277                      && Mechanism (gnat_entity) == By_Reference)
4278               return_by_invisi_ref_p = true;
4279
4280             /* Likewise, if the return type is itself By_Reference.  */
4281             else if (TYPE_IS_BY_REFERENCE_P (gnu_return_type))
4282               return_by_invisi_ref_p = true;
4283
4284             /* If the type is a padded type and the underlying type would not
4285                be passed by reference or the function has a foreign convention,
4286                return the underlying type.  */
4287             else if (TYPE_IS_PADDING_P (gnu_return_type)
4288                      && (!default_pass_by_ref
4289                           (TREE_TYPE (TYPE_FIELDS (gnu_return_type)))
4290                          || Has_Foreign_Convention (gnat_entity)))
4291               gnu_return_type = TREE_TYPE (TYPE_FIELDS (gnu_return_type));
4292
4293             /* If the return type is unconstrained, that means it must have a
4294                maximum size.  Use the padded type as the effective return type.
4295                And ensure the function uses the target's by-invisible-reference
4296                mechanism to avoid copying too much data when it returns.  */
4297             if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_return_type)))
4298               {
4299                 tree orig_type = gnu_return_type;
4300
4301                 gnu_return_type
4302                   = maybe_pad_type (gnu_return_type,
4303                                     max_size (TYPE_SIZE (gnu_return_type),
4304                                               true),
4305                                     0, gnat_entity, false, false, false, true);
4306
4307                 /* Declare it now since it will never be declared otherwise.
4308                    This is necessary to ensure that its subtrees are properly
4309                    marked.  */
4310                 if (gnu_return_type != orig_type
4311                     && !DECL_P (TYPE_NAME (gnu_return_type)))
4312                   create_type_decl (TYPE_NAME (gnu_return_type),
4313                                     gnu_return_type, true, debug_info_p,
4314                                     gnat_entity);
4315
4316                 return_by_invisi_ref_p = true;
4317               }
4318
4319             /* If the return type has a size that overflows, we cannot have
4320                a function that returns that type.  This usage doesn't make
4321                sense anyway, so give an error here.  */
4322             if (TYPE_SIZE_UNIT (gnu_return_type)
4323                 && TREE_CODE (TYPE_SIZE_UNIT (gnu_return_type)) == INTEGER_CST
4324                 && !valid_constant_size_p (TYPE_SIZE_UNIT (gnu_return_type)))
4325               {
4326                 post_error ("cannot return type whose size overflows",
4327                             gnat_entity);
4328                 gnu_return_type = copy_node (gnu_return_type);
4329                 TYPE_SIZE (gnu_return_type) = bitsize_zero_node;
4330                 TYPE_SIZE_UNIT (gnu_return_type) = size_zero_node;
4331                 TYPE_MAIN_VARIANT (gnu_return_type) = gnu_return_type;
4332                 TYPE_NEXT_VARIANT (gnu_return_type) = NULL_TREE;
4333               }
4334           }
4335
4336         /* Loop over the parameters and get their associated GCC tree.  While
4337            doing this, build a copy-in copy-out structure if we need one.  */
4338         for (gnat_param = First_Formal_With_Extras (gnat_entity), parmnum = 0;
4339              Present (gnat_param);
4340              gnat_param = Next_Formal_With_Extras (gnat_param), parmnum++)
4341           {
4342             Entity_Id gnat_param_type = Etype (gnat_param);
4343             tree gnu_param_name = get_entity_name (gnat_param);
4344             tree gnu_param_type, gnu_param, gnu_field;
4345             Mechanism_Type mech = Mechanism (gnat_param);
4346             bool copy_in_copy_out = false, fake_param_type;
4347
4348             /* Ada 2012 (AI05-0151): Incomplete types coming from a limited
4349                context may now appear in parameter and result profiles.  If
4350                we are only annotating types, break circularities here.  */
4351             if (type_annotate_only
4352                 && is_from_limited_with_of_main (gnat_param_type))
4353               {
4354                 gnu_param_type = ptr_void_type_node;
4355                 fake_param_type = true;
4356               }
4357             else
4358               {
4359                 gnu_param_type = gnat_to_gnu_type (gnat_param_type);
4360                 fake_param_type = false;
4361               }
4362
4363             /* Builtins are expanded inline and there is no real call sequence
4364                involved.  So the type expected by the underlying expander is
4365                always the type of each argument "as is".  */
4366             if (gnu_builtin_decl)
4367               mech = By_Copy;
4368             /* Handle the first parameter of a valued procedure specially.  */
4369             else if (Is_Valued_Procedure (gnat_entity) && parmnum == 0)
4370               mech = By_Copy_Return;
4371             /* Otherwise, see if a Mechanism was supplied that forced this
4372                parameter to be passed one way or another.  */
4373             else if (mech == Default
4374                      || mech == By_Copy
4375                      || mech == By_Reference)
4376               ;
4377             else if (mech > 0)
4378               {
4379                 if (TREE_CODE (gnu_param_type) == UNCONSTRAINED_ARRAY_TYPE
4380                     || TREE_CODE (TYPE_SIZE (gnu_param_type)) != INTEGER_CST
4381                     || 0 < compare_tree_int (TYPE_SIZE (gnu_param_type),
4382                                              mech))
4383                   mech = By_Reference;
4384                 else
4385                   mech = By_Copy;
4386               }
4387             else
4388               {
4389                 post_error ("unsupported mechanism for&", gnat_param);
4390                 mech = Default;
4391               }
4392
4393             /* Do not call gnat_to_gnu_param for a fake parameter type since
4394                it will try to use the real type again.  */
4395             if (fake_param_type)
4396               {
4397                 if (Ekind (gnat_param) == E_Out_Parameter)
4398                   gnu_param = NULL_TREE;
4399                 else
4400                   {
4401                     gnu_param
4402                       = create_param_decl (gnu_param_name, gnu_param_type,
4403                                            false);
4404                     Set_Mechanism (gnat_param,
4405                                    mech == Default ? By_Copy : mech);
4406                     if (Ekind (gnat_param) == E_In_Out_Parameter)
4407                       copy_in_copy_out = true;
4408                   }
4409               }
4410             else
4411               gnu_param
4412                 = gnat_to_gnu_param (gnat_param, mech, gnat_entity,
4413                                      Has_Foreign_Convention (gnat_entity),
4414                                      &copy_in_copy_out);
4415
4416             /* We are returned either a PARM_DECL or a type if no parameter
4417                needs to be passed; in either case, adjust the type.  */
4418             if (DECL_P (gnu_param))
4419               gnu_param_type = TREE_TYPE (gnu_param);
4420             else
4421               {
4422                 gnu_param_type = gnu_param;
4423                 gnu_param = NULL_TREE;
4424               }
4425
4426             /* The failure of this assertion will very likely come from an
4427                order of elaboration issue for the type of the parameter.  */
4428             gcc_assert (kind == E_Subprogram_Type
4429                         || !TYPE_IS_DUMMY_P (gnu_param_type)
4430                         || type_annotate_only);
4431
4432             if (gnu_param)
4433               {
4434                 gnu_param_list = chainon (gnu_param, gnu_param_list);
4435                 Sloc_to_locus (Sloc (gnat_param),
4436                                &DECL_SOURCE_LOCATION (gnu_param));
4437                 save_gnu_tree (gnat_param, gnu_param, false);
4438
4439                 /* If a parameter is a pointer, this function may modify
4440                    memory through it and thus shouldn't be considered
4441                    a const function.  Also, the memory may be modified
4442                    between two calls, so they can't be CSE'ed.  The latter
4443                    case also handles by-ref parameters.  */
4444                 if (POINTER_TYPE_P (gnu_param_type)
4445                     || TYPE_IS_FAT_POINTER_P (gnu_param_type))
4446                   const_flag = false;
4447               }
4448
4449             if (copy_in_copy_out)
4450               {
4451                 if (!gnu_cico_list)
4452                   {
4453                     tree gnu_new_ret_type = make_node (RECORD_TYPE);
4454
4455                     /* If this is a function, we also need a field for the
4456                        return value to be placed.  */
4457                     if (TREE_CODE (gnu_return_type) != VOID_TYPE)
4458                       {
4459                         gnu_field
4460                           = create_field_decl (get_identifier ("RETVAL"),
4461                                                gnu_return_type,
4462                                                gnu_new_ret_type, NULL_TREE,
4463                                                NULL_TREE, 0, 0);
4464                         Sloc_to_locus (Sloc (gnat_entity),
4465                                        &DECL_SOURCE_LOCATION (gnu_field));
4466                         gnu_field_list = gnu_field;
4467                         gnu_cico_list
4468                           = tree_cons (gnu_field, void_type_node, NULL_TREE);
4469                       }
4470
4471                     gnu_return_type = gnu_new_ret_type;
4472                     TYPE_NAME (gnu_return_type) = get_identifier ("RETURN");
4473                     /* Set a default alignment to speed up accesses.  But we
4474                        shouldn't increase the size of the structure too much,
4475                        lest it doesn't fit in return registers anymore.  */
4476                     TYPE_ALIGN (gnu_return_type)
4477                       = get_mode_alignment (ptr_mode);
4478                   }
4479
4480                 gnu_field
4481                   = create_field_decl (gnu_param_name, gnu_param_type,
4482                                        gnu_return_type, NULL_TREE, NULL_TREE,
4483                                        0, 0);
4484                 Sloc_to_locus (Sloc (gnat_param),
4485                                &DECL_SOURCE_LOCATION (gnu_field));
4486                 DECL_CHAIN (gnu_field) = gnu_field_list;
4487                 gnu_field_list = gnu_field;
4488                 gnu_cico_list
4489                   = tree_cons (gnu_field, gnu_param, gnu_cico_list);
4490               }
4491           }
4492
4493         if (gnu_cico_list)
4494           {
4495             /* If we have a CICO list but it has only one entry, we convert
4496                this function into a function that returns this object.  */
4497             if (list_length (gnu_cico_list) == 1)
4498               gnu_return_type = TREE_TYPE (TREE_PURPOSE (gnu_cico_list));
4499
4500             /* Do not finalize the return type if the subprogram is stubbed
4501                since structures are incomplete for the back-end.  */
4502             else if (Convention (gnat_entity) != Convention_Stubbed)
4503               {
4504                 finish_record_type (gnu_return_type, nreverse (gnu_field_list),
4505                                     0, false);
4506
4507                 /* Try to promote the mode of the return type if it is passed
4508                    in registers, again to speed up accesses.  */
4509                 if (TYPE_MODE (gnu_return_type) == BLKmode
4510                     && !targetm.calls.return_in_memory (gnu_return_type,
4511                                                         NULL_TREE))
4512                   {
4513                     unsigned int size
4514                       = TREE_INT_CST_LOW (TYPE_SIZE (gnu_return_type));
4515                     unsigned int i = BITS_PER_UNIT;
4516                     machine_mode mode;
4517
4518                     while (i < size)
4519                       i <<= 1;
4520                     mode = mode_for_size (i, MODE_INT, 0);
4521                     if (mode != BLKmode)
4522                       {
4523                         SET_TYPE_MODE (gnu_return_type, mode);
4524                         TYPE_ALIGN (gnu_return_type)
4525                           = GET_MODE_ALIGNMENT (mode);
4526                         TYPE_SIZE (gnu_return_type)
4527                           = bitsize_int (GET_MODE_BITSIZE (mode));
4528                         TYPE_SIZE_UNIT (gnu_return_type)
4529                           = size_int (GET_MODE_SIZE (mode));
4530                       }
4531                   }
4532
4533                 if (debug_info_p)
4534                   rest_of_record_type_compilation (gnu_return_type);
4535               }
4536           }
4537
4538         /* Deal with platform-specific calling conventions.  */
4539         if (Has_Stdcall_Convention (gnat_entity))
4540           prepend_one_attribute
4541             (&attr_list, ATTR_MACHINE_ATTRIBUTE,
4542              get_identifier ("stdcall"), NULL_TREE,
4543              gnat_entity);
4544         else if (Has_Thiscall_Convention (gnat_entity))
4545           prepend_one_attribute
4546             (&attr_list, ATTR_MACHINE_ATTRIBUTE,
4547              get_identifier ("thiscall"), NULL_TREE,
4548              gnat_entity);
4549
4550         /* If we should request stack realignment for a foreign convention
4551            subprogram, do so.  Note that this applies to task entry points
4552            in particular.  */
4553         if (FOREIGN_FORCE_REALIGN_STACK
4554             && Has_Foreign_Convention (gnat_entity))
4555           prepend_one_attribute
4556             (&attr_list, ATTR_MACHINE_ATTRIBUTE,
4557              get_identifier ("force_align_arg_pointer"), NULL_TREE,
4558              gnat_entity);
4559
4560         /* Deal with a pragma Linker_Section on a subprogram.  */
4561         if ((kind == E_Function || kind == E_Procedure)
4562             && Present (Linker_Section_Pragma (gnat_entity)))
4563           prepend_one_attribute_pragma (&attr_list,
4564                                         Linker_Section_Pragma (gnat_entity));
4565
4566         /* The lists have been built in reverse.  */
4567         gnu_param_list = nreverse (gnu_param_list);
4568         gnu_cico_list = nreverse (gnu_cico_list);
4569
4570         if (kind == E_Function)
4571           Set_Mechanism (gnat_entity, return_unconstrained_p
4572                                       || return_by_direct_ref_p
4573                                       || return_by_invisi_ref_p
4574                                       ? By_Reference : By_Copy);
4575         gnu_type
4576           = create_subprog_type (gnu_return_type, gnu_param_list,
4577                                  gnu_cico_list, return_unconstrained_p,
4578                                  return_by_direct_ref_p,
4579                                  return_by_invisi_ref_p);
4580
4581         /* A procedure (something that doesn't return anything) shouldn't be
4582            considered const since there would be no reason for calling such a
4583            subprogram.  Note that procedures with Out (or In Out) parameters
4584            have already been converted into a function with a return type.
4585            Similarly, if the function returns an unconstrained type, then the
4586            function will allocate the return value on the secondary stack and
4587            thus calls to it cannot be CSE'ed, lest the stack be reclaimed.  */
4588         if (TREE_CODE (gnu_return_type) == VOID_TYPE || return_unconstrained_p)
4589           const_flag = false;
4590
4591         if (const_flag || noreturn_flag)
4592           {
4593             const int quals
4594               = (const_flag ? TYPE_QUAL_CONST : 0)
4595                 | (noreturn_flag ? TYPE_QUAL_VOLATILE : 0);
4596             gnu_type = change_qualified_type (gnu_type, quals);
4597           }
4598
4599         /* If we have a builtin decl for that function, use it.  Check if the
4600            profiles are compatible and warn if they are not.  The checker is
4601            expected to post extra diagnostics in this case.  */
4602         if (gnu_builtin_decl)
4603           {
4604             intrin_binding_t inb;
4605
4606             inb.gnat_entity = gnat_entity;
4607             inb.ada_fntype = gnu_type;
4608             inb.btin_fntype = TREE_TYPE (gnu_builtin_decl);
4609
4610             if (!intrin_profiles_compatible_p (&inb))
4611               post_error
4612                 ("?profile of& doesn''t match the builtin it binds!",
4613                  gnat_entity);
4614
4615             gnu_decl = gnu_builtin_decl;
4616             gnu_type = TREE_TYPE (gnu_builtin_decl);
4617             break;
4618           }
4619
4620         /* If there was no specified Interface_Name and the external and
4621            internal names of the subprogram are the same, only use the
4622            internal name to allow disambiguation of nested subprograms.  */
4623         if (No (Interface_Name (gnat_entity))
4624             && gnu_ext_name == gnu_entity_name)
4625           gnu_ext_name = NULL_TREE;
4626
4627         /* If we are defining the subprogram and it has an Address clause
4628            we must get the address expression from the saved GCC tree for the
4629            subprogram if it has a Freeze_Node.  Otherwise, we elaborate
4630            the address expression here since the front-end has guaranteed
4631            in that case that the elaboration has no effects.  If there is
4632            an Address clause and we are not defining the object, just
4633            make it a constant.  */
4634         if (Present (Address_Clause (gnat_entity)))
4635           {
4636             tree gnu_address = NULL_TREE;
4637
4638             if (definition)
4639               gnu_address
4640                 = (present_gnu_tree (gnat_entity)
4641                    ? get_gnu_tree (gnat_entity)
4642                    : gnat_to_gnu (Expression (Address_Clause (gnat_entity))));
4643
4644             save_gnu_tree (gnat_entity, NULL_TREE, false);
4645
4646             /* Convert the type of the object to a reference type that can
4647                alias everything as per 13.3(19).  */
4648             gnu_type
4649               = build_reference_type_for_mode (gnu_type, ptr_mode, true);
4650             if (gnu_address)
4651               gnu_address = convert (gnu_type, gnu_address);
4652
4653             gnu_decl
4654               = create_var_decl (gnu_entity_name, gnu_ext_name, gnu_type,
4655                                  gnu_address, false, Is_Public (gnat_entity),
4656                                  extern_flag, false, NULL, gnat_entity);
4657             DECL_BY_REF_P (gnu_decl) = 1;
4658           }
4659
4660         else if (kind == E_Subprogram_Type)
4661           {
4662             process_attributes (&gnu_type, &attr_list, false, gnat_entity);
4663             gnu_decl
4664               = create_type_decl (gnu_entity_name, gnu_type, artificial_flag,
4665                                   debug_info_p, gnat_entity);
4666           }
4667         else
4668           {
4669             gnu_decl
4670               = create_subprog_decl (gnu_entity_name, gnu_ext_name, gnu_type,
4671                                      gnu_param_list, inline_status,
4672                                      public_flag, extern_flag, artificial_flag,
4673                                      attr_list, gnat_entity);
4674             /* This is unrelated to the stub built right above.  */
4675             DECL_STUBBED_P (gnu_decl)
4676               = Convention (gnat_entity) == Convention_Stubbed;
4677           }
4678       }
4679       break;
4680
4681     case E_Incomplete_Type:
4682     case E_Incomplete_Subtype:
4683     case E_Private_Type:
4684     case E_Private_Subtype:
4685     case E_Limited_Private_Type:
4686     case E_Limited_Private_Subtype:
4687     case E_Record_Type_With_Private:
4688     case E_Record_Subtype_With_Private:
4689       {
4690         /* Get the "full view" of this entity.  If this is an incomplete
4691            entity from a limited with, treat its non-limited view as the
4692            full view.  Otherwise, use either the full view or the underlying
4693            full view, whichever is present.  This is used in all the tests
4694            below.  */
4695         Entity_Id full_view
4696           = (IN (kind, Incomplete_Kind) && From_Limited_With (gnat_entity))
4697             ? Non_Limited_View (gnat_entity)
4698             : Present (Full_View (gnat_entity))
4699               ? Full_View (gnat_entity)
4700               : IN (kind, Private_Kind)
4701                 ? Underlying_Full_View (gnat_entity)
4702                 : Empty;
4703
4704         /* If this is an incomplete type with no full view, it must be a Taft
4705            Amendment type, in which case we return a dummy type.  Otherwise,
4706            just get the type from its Etype.  */
4707         if (No (full_view))
4708           {
4709             if (kind == E_Incomplete_Type)
4710               {
4711                 gnu_type = make_dummy_type (gnat_entity);
4712                 gnu_decl = TYPE_STUB_DECL (gnu_type);
4713               }
4714             else
4715               {
4716                 gnu_decl = gnat_to_gnu_entity (Etype (gnat_entity),
4717                                                NULL_TREE, 0);
4718                 maybe_present = true;
4719               }
4720             break;
4721           }
4722
4723         /* If we already made a type for the full view, reuse it.  */
4724         else if (present_gnu_tree (full_view))
4725           {
4726             gnu_decl = get_gnu_tree (full_view);
4727             break;
4728           }
4729
4730         /* Otherwise, if we are not defining the type now, get the type
4731            from the full view.  But always get the type from the full view
4732            for define on use types, since otherwise we won't see them!  */
4733         else if (!definition
4734                  || (Is_Itype (full_view) && No (Freeze_Node (gnat_entity)))
4735                  || (Is_Itype (gnat_entity) && No (Freeze_Node (full_view))))
4736           {
4737             gnu_decl = gnat_to_gnu_entity (full_view, NULL_TREE, 0);
4738             maybe_present = true;
4739             break;
4740           }
4741
4742         /* For incomplete types, make a dummy type entry which will be
4743            replaced later.  Save it as the full declaration's type so
4744            we can do any needed updates when we see it.  */
4745         gnu_type = make_dummy_type (gnat_entity);
4746         gnu_decl = TYPE_STUB_DECL (gnu_type);
4747         if (Has_Completion_In_Body (gnat_entity))
4748           DECL_TAFT_TYPE_P (gnu_decl) = 1;
4749         save_gnu_tree (full_view, gnu_decl, 0);
4750         break;
4751       }
4752
4753     case E_Class_Wide_Type:
4754       /* Class-wide types are always transformed into their root type.  */
4755       gnu_decl = gnat_to_gnu_entity (gnat_equiv_type, NULL_TREE, 0);
4756       maybe_present = true;
4757       break;
4758
4759     case E_Task_Type:
4760     case E_Task_Subtype:
4761     case E_Protected_Type:
4762     case E_Protected_Subtype:
4763       /* Concurrent types are always transformed into their record type.  */
4764       if (type_annotate_only && No (gnat_equiv_type))
4765         gnu_type = void_type_node;
4766       else
4767         gnu_decl = gnat_to_gnu_entity (gnat_equiv_type, NULL_TREE, 0);
4768       maybe_present = true;
4769       break;
4770
4771     case E_Label:
4772       gnu_decl = create_label_decl (gnu_entity_name, gnat_entity);
4773       break;
4774
4775     case E_Block:
4776     case E_Loop:
4777       /* Nothing at all to do here, so just return an ERROR_MARK and claim
4778          we've already saved it, so we don't try to.  */
4779       gnu_decl = error_mark_node;
4780       saved = true;
4781       break;
4782
4783     case E_Abstract_State:
4784       /* This is a SPARK annotation that only reaches here when compiling in
4785          ASIS mode.  */
4786       gcc_assert (type_annotate_only);
4787       gnu_decl = error_mark_node;
4788       saved = true;
4789       break;
4790
4791     default:
4792       gcc_unreachable ();
4793     }
4794
4795   /* If we had a case where we evaluated another type and it might have
4796      defined this one, handle it here.  */
4797   if (maybe_present && present_gnu_tree (gnat_entity))
4798     {
4799       gnu_decl = get_gnu_tree (gnat_entity);
4800       saved = true;
4801     }
4802
4803   /* If we are processing a type and there is either no decl for it or
4804      we just made one, do some common processing for the type, such as
4805      handling alignment and possible padding.  */
4806   if (is_type && (!gnu_decl || this_made_decl))
4807     {
4808       /* Process the attributes, if not already done.  Note that the type is
4809          already defined so we cannot pass true for IN_PLACE here.  */
4810       process_attributes (&gnu_type, &attr_list, false, gnat_entity);
4811
4812       /* Tell the middle-end that objects of tagged types are guaranteed to
4813          be properly aligned.  This is necessary because conversions to the
4814          class-wide type are translated into conversions to the root type,
4815          which can be less aligned than some of its derived types.  */
4816       if (Is_Tagged_Type (gnat_entity)
4817           || Is_Class_Wide_Equivalent_Type (gnat_entity))
4818         TYPE_ALIGN_OK (gnu_type) = 1;
4819
4820       /* Record whether the type is passed by reference.  */
4821       if (!VOID_TYPE_P (gnu_type) && Is_By_Reference_Type (gnat_entity))
4822         TYPE_BY_REFERENCE_P (gnu_type) = 1;
4823
4824       /* ??? Don't set the size for a String_Literal since it is either
4825          confirming or we don't handle it properly (if the low bound is
4826          non-constant).  */
4827       if (!gnu_size && kind != E_String_Literal_Subtype)
4828         {
4829           Uint gnat_size = Known_Esize (gnat_entity)
4830                            ? Esize (gnat_entity) : RM_Size (gnat_entity);
4831           gnu_size
4832             = validate_size (gnat_size, gnu_type, gnat_entity, TYPE_DECL,
4833                              false, Has_Size_Clause (gnat_entity));
4834         }
4835
4836       /* If a size was specified, see if we can make a new type of that size
4837          by rearranging the type, for example from a fat to a thin pointer.  */
4838       if (gnu_size)
4839         {
4840           gnu_type
4841             = make_type_from_size (gnu_type, gnu_size,
4842                                    Has_Biased_Representation (gnat_entity));
4843
4844           if (operand_equal_p (TYPE_SIZE (gnu_type), gnu_size, 0)
4845               && operand_equal_p (rm_size (gnu_type), gnu_size, 0))
4846             gnu_size = NULL_TREE;
4847         }
4848
4849       /* If the alignment has not already been processed and this is not
4850          an unconstrained array type, see if an alignment is specified.
4851          If not, we pick a default alignment for atomic objects.  */
4852       if (align != 0 || TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
4853         ;
4854       else if (Known_Alignment (gnat_entity))
4855         {
4856           align = validate_alignment (Alignment (gnat_entity), gnat_entity,
4857                                       TYPE_ALIGN (gnu_type));
4858
4859           /* Warn on suspiciously large alignments.  This should catch
4860              errors about the (alignment,byte)/(size,bit) discrepancy.  */
4861           if (align > BIGGEST_ALIGNMENT && Has_Alignment_Clause (gnat_entity))
4862             {
4863               tree size;
4864
4865               /* If a size was specified, take it into account.  Otherwise
4866                  use the RM size for records or unions as the type size has
4867                  already been adjusted to the alignment.  */
4868               if (gnu_size)
4869                 size = gnu_size;
4870               else if (RECORD_OR_UNION_TYPE_P (gnu_type)
4871                        && !TYPE_FAT_POINTER_P (gnu_type))
4872                 size = rm_size (gnu_type);
4873               else
4874                 size = TYPE_SIZE (gnu_type);
4875
4876               /* Consider an alignment as suspicious if the alignment/size
4877                  ratio is greater or equal to the byte/bit ratio.  */
4878               if (tree_fits_uhwi_p (size)
4879                   && align >= tree_to_uhwi (size) * BITS_PER_UNIT)
4880                 post_error_ne ("?suspiciously large alignment specified for&",
4881                                Expression (Alignment_Clause (gnat_entity)),
4882                                gnat_entity);
4883             }
4884         }
4885       else if (Is_Atomic_Or_VFA (gnat_entity) && !gnu_size
4886                && tree_fits_uhwi_p (TYPE_SIZE (gnu_type))
4887                && integer_pow2p (TYPE_SIZE (gnu_type)))
4888         align = MIN (BIGGEST_ALIGNMENT,
4889                      tree_to_uhwi (TYPE_SIZE (gnu_type)));
4890       else if (Is_Atomic_Or_VFA (gnat_entity) && gnu_size
4891                && tree_fits_uhwi_p (gnu_size)
4892                && integer_pow2p (gnu_size))
4893         align = MIN (BIGGEST_ALIGNMENT, tree_to_uhwi (gnu_size));
4894
4895       /* See if we need to pad the type.  If we did, and made a record,
4896          the name of the new type may be changed.  So get it back for
4897          us when we make the new TYPE_DECL below.  */
4898       if (gnu_size || align > 0)
4899         gnu_type = maybe_pad_type (gnu_type, gnu_size, align, gnat_entity,
4900                                    false, !gnu_decl, definition, false);
4901
4902       if (TYPE_IS_PADDING_P (gnu_type))
4903         gnu_entity_name = TYPE_IDENTIFIER (gnu_type);
4904
4905       /* Now set the RM size of the type.  We cannot do it before padding
4906          because we need to accept arbitrary RM sizes on integral types.  */
4907       set_rm_size (RM_Size (gnat_entity), gnu_type, gnat_entity);
4908
4909       /* If we are at global level, GCC will have applied variable_size to
4910          the type, but that won't have done anything.  So, if it's not
4911          a constant or self-referential, call elaborate_expression_1 to
4912          make a variable for the size rather than calculating it each time.
4913          Handle both the RM size and the actual size.  */
4914       if (global_bindings_p ()
4915           && TYPE_SIZE (gnu_type)
4916           && !TREE_CONSTANT (TYPE_SIZE (gnu_type))
4917           && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
4918         {
4919           tree size = TYPE_SIZE (gnu_type);
4920
4921           TYPE_SIZE (gnu_type)
4922             = elaborate_expression_1 (size, gnat_entity,
4923                                       get_identifier ("SIZE"),
4924                                       definition, false);
4925
4926           /* ??? For now, store the size as a multiple of the alignment in
4927              bytes so that we can see the alignment from the tree.  */
4928           TYPE_SIZE_UNIT (gnu_type)
4929             = elaborate_expression_2 (TYPE_SIZE_UNIT (gnu_type), gnat_entity,
4930                                       get_identifier ("SIZE_A_UNIT"),
4931                                       definition, false,
4932                                       TYPE_ALIGN (gnu_type));
4933
4934           /* ??? gnu_type may come from an existing type so the MULT_EXPR node
4935              may not be marked by the call to create_type_decl below.  */
4936           MARK_VISITED (TYPE_SIZE_UNIT (gnu_type));
4937
4938           if (TREE_CODE (gnu_type) == RECORD_TYPE)
4939             {
4940               tree variant_part = get_variant_part (gnu_type);
4941               tree ada_size = TYPE_ADA_SIZE (gnu_type);
4942
4943               if (variant_part)
4944                 {
4945                   tree union_type = TREE_TYPE (variant_part);
4946                   tree offset = DECL_FIELD_OFFSET (variant_part);
4947
4948                   /* If the position of the variant part is constant, subtract
4949                      it from the size of the type of the parent to get the new
4950                      size.  This manual CSE reduces the data size.  */
4951                   if (TREE_CODE (offset) == INTEGER_CST)
4952                     {
4953                       tree bitpos = DECL_FIELD_BIT_OFFSET (variant_part);
4954                       TYPE_SIZE (union_type)
4955                         = size_binop (MINUS_EXPR, TYPE_SIZE (gnu_type),
4956                                       bit_from_pos (offset, bitpos));
4957                       TYPE_SIZE_UNIT (union_type)
4958                         = size_binop (MINUS_EXPR, TYPE_SIZE_UNIT (gnu_type),
4959                                       byte_from_pos (offset, bitpos));
4960                     }
4961                   else
4962                     {
4963                       TYPE_SIZE (union_type)
4964                         = elaborate_expression_1 (TYPE_SIZE (union_type),
4965                                                   gnat_entity,
4966                                                   get_identifier ("VSIZE"),
4967                                                   definition, false);
4968
4969                       /* ??? For now, store the size as a multiple of the
4970                          alignment in bytes so that we can see the alignment
4971                          from the tree.  */
4972                       TYPE_SIZE_UNIT (union_type)
4973                         = elaborate_expression_2 (TYPE_SIZE_UNIT (union_type),
4974                                                   gnat_entity,
4975                                                   get_identifier
4976                                                   ("VSIZE_A_UNIT"),
4977                                                   definition, false,
4978                                                   TYPE_ALIGN (union_type));
4979
4980                       /* ??? For now, store the offset as a multiple of the
4981                          alignment in bytes so that we can see the alignment
4982                          from the tree.  */
4983                       DECL_FIELD_OFFSET (variant_part)
4984                         = elaborate_expression_2 (offset,
4985                                                   gnat_entity,
4986                                                   get_identifier ("VOFFSET"),
4987                                                   definition, false,
4988                                                   DECL_OFFSET_ALIGN
4989                                                   (variant_part));
4990                     }
4991
4992                   DECL_SIZE (variant_part) = TYPE_SIZE (union_type);
4993                   DECL_SIZE_UNIT (variant_part) = TYPE_SIZE_UNIT (union_type);
4994                 }
4995
4996               if (operand_equal_p (ada_size, size, 0))
4997                 ada_size = TYPE_SIZE (gnu_type);
4998               else
4999                 ada_size
5000                   = elaborate_expression_1 (ada_size, gnat_entity,
5001                                             get_identifier ("RM_SIZE"),
5002                                             definition, false);
5003               SET_TYPE_ADA_SIZE (gnu_type, ada_size);
5004             }
5005         }
5006
5007       /* If this is a record type or subtype, call elaborate_expression_2 on
5008          any field position.  Do this for both global and local types.
5009          Skip any fields that we haven't made trees for to avoid problems with
5010          class wide types.  */
5011       if (IN (kind, Record_Kind))
5012         for (gnat_temp = First_Entity (gnat_entity); Present (gnat_temp);
5013              gnat_temp = Next_Entity (gnat_temp))
5014           if (Ekind (gnat_temp) == E_Component && present_gnu_tree (gnat_temp))
5015             {
5016               tree gnu_field = get_gnu_tree (gnat_temp);
5017
5018               /* ??? For now, store the offset as a multiple of the alignment
5019                  in bytes so that we can see the alignment from the tree.  */
5020               if (!CONTAINS_PLACEHOLDER_P (DECL_FIELD_OFFSET (gnu_field)))
5021                 {
5022                   DECL_FIELD_OFFSET (gnu_field)
5023                     = elaborate_expression_2 (DECL_FIELD_OFFSET (gnu_field),
5024                                               gnat_temp,
5025                                               get_identifier ("OFFSET"),
5026                                               definition, false,
5027                                               DECL_OFFSET_ALIGN (gnu_field));
5028
5029                   /* ??? The context of gnu_field is not necessarily gnu_type
5030                      so the MULT_EXPR node built above may not be marked by
5031                      the call to create_type_decl below.  */
5032                   if (global_bindings_p ())
5033                     MARK_VISITED (DECL_FIELD_OFFSET (gnu_field));
5034                 }
5035             }
5036
5037       if (Is_Atomic_Or_VFA (gnat_entity))
5038         check_ok_for_atomic_type (gnu_type, gnat_entity, false);
5039
5040       /* If this is not an unconstrained array type, set some flags.  */
5041       if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
5042         {
5043           if (Present (Alignment_Clause (gnat_entity)))
5044             TYPE_USER_ALIGN (gnu_type) = 1;
5045
5046           if (Universal_Aliasing (gnat_entity))
5047             TYPE_UNIVERSAL_ALIASING_P (gnu_type) = 1;
5048
5049           /* If it is passed by reference, force BLKmode to ensure that
5050              objects of this type will always be put in memory.  */
5051           if (TYPE_MODE (gnu_type) != BLKmode
5052               && AGGREGATE_TYPE_P (gnu_type)
5053               && TYPE_BY_REFERENCE_P (gnu_type))
5054             SET_TYPE_MODE (gnu_type, BLKmode);
5055
5056           if (Treat_As_Volatile (gnat_entity))
5057             {
5058               const int quals
5059                 = TYPE_QUAL_VOLATILE
5060                   | (Is_Atomic_Or_VFA (gnat_entity) ? TYPE_QUAL_ATOMIC : 0);
5061               gnu_type = change_qualified_type (gnu_type, quals);
5062             }
5063         }
5064
5065       if (!gnu_decl)
5066         gnu_decl = create_type_decl (gnu_entity_name, gnu_type,
5067                                      !Comes_From_Source (gnat_entity),
5068                                      debug_info_p, gnat_entity);
5069       else
5070         {
5071           TREE_TYPE (gnu_decl) = gnu_type;
5072           TYPE_STUB_DECL (gnu_type) = gnu_decl;
5073         }
5074     }
5075
5076   if (is_type && !TYPE_IS_DUMMY_P (TREE_TYPE (gnu_decl)))
5077     {
5078       gnu_type = TREE_TYPE (gnu_decl);
5079
5080       /* If this is a derived type, relate its alias set to that of its parent
5081          to avoid troubles when a call to an inherited primitive is inlined in
5082          a context where a derived object is accessed.  The inlined code works
5083          on the parent view so the resulting code may access the same object
5084          using both the parent and the derived alias sets, which thus have to
5085          conflict.  As the same issue arises with component references, the
5086          parent alias set also has to conflict with composite types enclosing
5087          derived components.  For instance, if we have:
5088
5089             type D is new T;
5090             type R is record
5091                Component : D;
5092             end record;
5093
5094          we want T to conflict with both D and R, in addition to R being a
5095          superset of D by record/component construction.
5096
5097          One way to achieve this is to perform an alias set copy from the
5098          parent to the derived type.  This is not quite appropriate, though,
5099          as we don't want separate derived types to conflict with each other:
5100
5101             type I1 is new Integer;
5102             type I2 is new Integer;
5103
5104          We want I1 and I2 to both conflict with Integer but we do not want
5105          I1 to conflict with I2, and an alias set copy on derivation would
5106          have that effect.
5107
5108          The option chosen is to make the alias set of the derived type a
5109          superset of that of its parent type.  It trivially fulfills the
5110          simple requirement for the Integer derivation example above, and
5111          the component case as well by superset transitivity:
5112
5113                    superset      superset
5114                 R ----------> D ----------> T
5115
5116          However, for composite types, conversions between derived types are
5117          translated into VIEW_CONVERT_EXPRs so a sequence like:
5118
5119             type Comp1 is new Comp;
5120             type Comp2 is new Comp;
5121             procedure Proc (C : Comp1);
5122
5123             C : Comp2;
5124             Proc (Comp1 (C));
5125
5126          is translated into:
5127
5128             C : Comp2;
5129             Proc ((Comp1 &) &VIEW_CONVERT_EXPR <Comp1> (C));
5130
5131          and gimplified into:
5132
5133             C : Comp2;
5134             Comp1 *C.0;
5135             C.0 = (Comp1 *) &C;
5136             Proc (C.0);
5137
5138          i.e. generates code involving type punning.  Therefore, Comp1 needs
5139          to conflict with Comp2 and an alias set copy is required.
5140
5141          The language rules ensure the parent type is already frozen here.  */
5142       if (kind != E_Subprogram_Type
5143           && Is_Derived_Type (gnat_entity)
5144           && !type_annotate_only)
5145         {
5146           Entity_Id gnat_parent_type = Underlying_Type (Etype (gnat_entity));
5147           /* For constrained packed array subtypes, the implementation type is
5148              used instead of the nominal type.  */
5149           if (kind == E_Array_Subtype
5150               && Is_Constrained (gnat_entity)
5151               && Present (Packed_Array_Impl_Type (gnat_parent_type)))
5152             gnat_parent_type = Packed_Array_Impl_Type (gnat_parent_type);
5153           relate_alias_sets (gnu_type, gnat_to_gnu_type (gnat_parent_type),
5154                              Is_Composite_Type (gnat_entity)
5155                              ? ALIAS_SET_COPY : ALIAS_SET_SUPERSET);
5156         }
5157
5158       /* Back-annotate the Alignment of the type if not already in the
5159          tree.  Likewise for sizes.  */
5160       if (Unknown_Alignment (gnat_entity))
5161         {
5162           unsigned int double_align, align;
5163           bool is_capped_double, align_clause;
5164
5165           /* If the default alignment of "double" or larger scalar types is
5166              specifically capped and this is not an array with an alignment
5167              clause on the component type, return the cap.  */
5168           if ((double_align = double_float_alignment) > 0)
5169             is_capped_double
5170               = is_double_float_or_array (gnat_entity, &align_clause);
5171           else if ((double_align = double_scalar_alignment) > 0)
5172             is_capped_double
5173               = is_double_scalar_or_array (gnat_entity, &align_clause);
5174           else
5175             is_capped_double = align_clause = false;
5176
5177           if (is_capped_double && !align_clause)
5178             align = double_align;
5179           else
5180             align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
5181
5182           Set_Alignment (gnat_entity, UI_From_Int (align));
5183         }
5184
5185       if (Unknown_Esize (gnat_entity) && TYPE_SIZE (gnu_type))
5186         {
5187           tree gnu_size = TYPE_SIZE (gnu_type);
5188
5189           /* If the size is self-referential, annotate the maximum value.  */
5190           if (CONTAINS_PLACEHOLDER_P (gnu_size))
5191             gnu_size = max_size (gnu_size, true);
5192
5193           /* If we are just annotating types and the type is tagged, the tag
5194              and the parent components are not generated by the front-end so
5195              sizes must be adjusted if there is no representation clause.  */
5196           if (type_annotate_only
5197               && Is_Tagged_Type (gnat_entity)
5198               && !VOID_TYPE_P (gnu_type)
5199               && (!TYPE_FIELDS (gnu_type)
5200                   || integer_zerop (bit_position (TYPE_FIELDS (gnu_type)))))
5201             {
5202               tree pointer_size = bitsize_int (POINTER_SIZE), offset;
5203               Uint uint_size;
5204
5205               if (Is_Derived_Type (gnat_entity))
5206                 {
5207                   Entity_Id gnat_parent = Etype (Base_Type (gnat_entity));
5208                   offset = UI_To_gnu (Esize (gnat_parent), bitsizetype);
5209                   Set_Alignment (gnat_entity, Alignment (gnat_parent));
5210                 }
5211               else
5212                 offset = pointer_size;
5213
5214               if (TYPE_FIELDS (gnu_type))
5215                 offset
5216                   = round_up (offset, DECL_ALIGN (TYPE_FIELDS (gnu_type)));
5217
5218               gnu_size = size_binop (PLUS_EXPR, gnu_size, offset);
5219               gnu_size = round_up (gnu_size, POINTER_SIZE);
5220               uint_size = annotate_value (gnu_size);
5221               Set_Esize (gnat_entity, uint_size);
5222               Set_RM_Size (gnat_entity, uint_size);
5223             }
5224           else
5225             Set_Esize (gnat_entity, annotate_value (gnu_size));
5226         }
5227
5228       if (Unknown_RM_Size (gnat_entity) && rm_size (gnu_type))
5229         Set_RM_Size (gnat_entity, annotate_value (rm_size (gnu_type)));
5230     }
5231
5232   /* If we really have a ..._DECL node, set a couple of flags on it.  But we
5233      cannot do so if we are reusing the ..._DECL node made for an equivalent
5234      type or an alias or a renamed object as the predicates don't apply to it
5235      but to GNAT_ENTITY.  */
5236   if (DECL_P (gnu_decl)
5237       && !(is_type && gnat_equiv_type != gnat_entity)
5238       && !Present (Alias (gnat_entity))
5239       && !(Present (Renamed_Object (gnat_entity)) && saved))
5240     {
5241       if (!Comes_From_Source (gnat_entity))
5242         DECL_ARTIFICIAL (gnu_decl) = 1;
5243
5244       if (!debug_info_p)
5245         DECL_IGNORED_P (gnu_decl) = 1;
5246     }
5247
5248   /* If we haven't already, associate the ..._DECL node that we just made with
5249      the input GNAT entity node.  */
5250   if (!saved)
5251     save_gnu_tree (gnat_entity, gnu_decl, false);
5252
5253   /* Now we are sure gnat_entity has a corresponding ..._DECL node,
5254      eliminate as many deferred computations as possible.  */
5255   process_deferred_decl_context (false);
5256
5257   /* If this is an enumeration or floating-point type, we were not able to set
5258      the bounds since they refer to the type.  These are always static.  */
5259   if ((kind == E_Enumeration_Type && Present (First_Literal (gnat_entity)))
5260       || (kind == E_Floating_Point_Type))
5261     {
5262       tree gnu_scalar_type = gnu_type;
5263       tree gnu_low_bound, gnu_high_bound;
5264
5265       /* If this is a padded type, we need to use the underlying type.  */
5266       if (TYPE_IS_PADDING_P (gnu_scalar_type))
5267         gnu_scalar_type = TREE_TYPE (TYPE_FIELDS (gnu_scalar_type));
5268
5269       /* If this is a floating point type and we haven't set a floating
5270          point type yet, use this in the evaluation of the bounds.  */
5271       if (!longest_float_type_node && kind == E_Floating_Point_Type)
5272         longest_float_type_node = gnu_scalar_type;
5273
5274       gnu_low_bound = gnat_to_gnu (Type_Low_Bound (gnat_entity));
5275       gnu_high_bound = gnat_to_gnu (Type_High_Bound (gnat_entity));
5276
5277       if (kind == E_Enumeration_Type)
5278         {
5279           /* Enumeration types have specific RM bounds.  */
5280           SET_TYPE_RM_MIN_VALUE (gnu_scalar_type, gnu_low_bound);
5281           SET_TYPE_RM_MAX_VALUE (gnu_scalar_type, gnu_high_bound);
5282         }
5283       else
5284         {
5285           /* Floating-point types don't have specific RM bounds.  */
5286           TYPE_GCC_MIN_VALUE (gnu_scalar_type) = gnu_low_bound;
5287           TYPE_GCC_MAX_VALUE (gnu_scalar_type) = gnu_high_bound;
5288         }
5289     }
5290
5291   /* If we deferred processing of incomplete types, re-enable it.  If there
5292      were no other disables and we have deferred types to process, do so.  */
5293   if (this_deferred
5294       && --defer_incomplete_level == 0
5295       && defer_incomplete_list)
5296     {
5297       struct incomplete *p, *next;
5298
5299       /* We are back to level 0 for the deferring of incomplete types.
5300          But processing these incomplete types below may itself require
5301          deferring, so preserve what we have and restart from scratch.  */
5302       p = defer_incomplete_list;
5303       defer_incomplete_list = NULL;
5304
5305       for (; p; p = next)
5306         {
5307           next = p->next;
5308
5309           if (p->old_type)
5310             update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5311                                gnat_to_gnu_type (p->full_type));
5312           free (p);
5313         }
5314     }
5315
5316   /* If we are not defining this type, see if it's on one of the lists of
5317      incomplete types.  If so, handle the list entry now.  */
5318   if (is_type && !definition)
5319     {
5320       struct incomplete *p;
5321
5322       for (p = defer_incomplete_list; p; p = p->next)
5323         if (p->old_type && p->full_type == gnat_entity)
5324           {
5325             update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5326                                TREE_TYPE (gnu_decl));
5327             p->old_type = NULL_TREE;
5328           }
5329
5330       for (p = defer_limited_with; p; p = p->next)
5331         if (p->old_type && Non_Limited_View (p->full_type) == gnat_entity)
5332           {
5333             update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5334                                TREE_TYPE (gnu_decl));
5335             p->old_type = NULL_TREE;
5336           }
5337     }
5338
5339   if (this_global)
5340     force_global--;
5341
5342   /* If this is a packed array type whose original array type is itself
5343      an Itype without freeze node, make sure the latter is processed.  */
5344   if (Is_Packed_Array_Impl_Type (gnat_entity)
5345       && Is_Itype (Original_Array_Type (gnat_entity))
5346       && No (Freeze_Node (Original_Array_Type (gnat_entity)))
5347       && !present_gnu_tree (Original_Array_Type (gnat_entity)))
5348     gnat_to_gnu_entity (Original_Array_Type (gnat_entity), NULL_TREE, 0);
5349
5350   return gnu_decl;
5351 }
5352
5353 /* Similar, but if the returned value is a COMPONENT_REF, return the
5354    FIELD_DECL.  */
5355
5356 tree
5357 gnat_to_gnu_field_decl (Entity_Id gnat_entity)
5358 {
5359   tree gnu_field = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5360
5361   if (TREE_CODE (gnu_field) == COMPONENT_REF)
5362     gnu_field = TREE_OPERAND (gnu_field, 1);
5363
5364   return gnu_field;
5365 }
5366
5367 /* Similar, but GNAT_ENTITY is assumed to refer to a GNAT type.  Return
5368    the GCC type corresponding to that entity.  */
5369
5370 tree
5371 gnat_to_gnu_type (Entity_Id gnat_entity)
5372 {
5373   tree gnu_decl;
5374
5375   /* The back end never attempts to annotate generic types.  */
5376   if (Is_Generic_Type (gnat_entity) && type_annotate_only)
5377      return void_type_node;
5378
5379   gnu_decl = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5380   gcc_assert (TREE_CODE (gnu_decl) == TYPE_DECL);
5381
5382   return TREE_TYPE (gnu_decl);
5383 }
5384
5385 /* Similar, but GNAT_ENTITY is assumed to refer to a GNAT type.  Return
5386    the unpadded version of the GCC type corresponding to that entity.  */
5387
5388 tree
5389 get_unpadded_type (Entity_Id gnat_entity)
5390 {
5391   tree type = gnat_to_gnu_type (gnat_entity);
5392
5393   if (TYPE_IS_PADDING_P (type))
5394     type = TREE_TYPE (TYPE_FIELDS (type));
5395
5396   return type;
5397 }
5398
5399 /* Return the DECL associated with the public subprogram GNAT_ENTITY but whose
5400    type has been changed to that of the parameterless procedure, except if an
5401    alias is already present, in which case it is returned instead.  */
5402
5403 tree
5404 get_minimal_subprog_decl (Entity_Id gnat_entity)
5405 {
5406   tree gnu_entity_name, gnu_ext_name;
5407   struct attrib *attr_list = NULL;
5408
5409   /* See the E_Function/E_Procedure case of gnat_to_gnu_entity for the model
5410      of the handling applied here.  */
5411
5412   while (Present (Alias (gnat_entity)))
5413     {
5414       gnat_entity = Alias (gnat_entity);
5415       if (present_gnu_tree (gnat_entity))
5416         return get_gnu_tree (gnat_entity);
5417     }
5418
5419   gnu_entity_name = get_entity_name (gnat_entity);
5420   gnu_ext_name = create_concat_name (gnat_entity, NULL);
5421
5422   if (Has_Stdcall_Convention (gnat_entity))
5423     prepend_one_attribute (&attr_list, ATTR_MACHINE_ATTRIBUTE,
5424                            get_identifier ("stdcall"), NULL_TREE,
5425                            gnat_entity);
5426   else if (Has_Thiscall_Convention (gnat_entity))
5427     prepend_one_attribute (&attr_list, ATTR_MACHINE_ATTRIBUTE,
5428                            get_identifier ("thiscall"), NULL_TREE,
5429                            gnat_entity);
5430
5431   if (No (Interface_Name (gnat_entity)) && gnu_ext_name == gnu_entity_name)
5432     gnu_ext_name = NULL_TREE;
5433
5434   return
5435     create_subprog_decl (gnu_entity_name, gnu_ext_name, void_ftype, NULL_TREE,
5436                          is_disabled, true, true, true, attr_list, gnat_entity);
5437 }
5438
5439 /* Return whether the E_Subprogram_Type/E_Function/E_Procedure GNAT_ENTITY is
5440    a C++ imported method or equivalent.
5441
5442    We use the predicate on 32-bit x86/Windows to find out whether we need to
5443    use the "thiscall" calling convention for GNAT_ENTITY.  This convention is
5444    used for C++ methods (functions with METHOD_TYPE) by the back-end.  */
5445
5446 bool
5447 is_cplusplus_method (Entity_Id gnat_entity)
5448 {
5449   if (Convention (gnat_entity) != Convention_CPP)
5450     return false;
5451
5452   /* This is the main case: C++ method imported as a primitive operation.
5453      Note that a C++ class with no virtual functions can be imported as a
5454      limited record type so the operation is not necessarily dispatching.  */
5455   if (Is_Primitive (gnat_entity))
5456     return true;
5457
5458   /* A thunk needs to be handled like its associated primitive operation.  */
5459   if (Is_Subprogram (gnat_entity) && Is_Thunk (gnat_entity))
5460     return true;
5461
5462   /* A constructor is a method on the C++ side.  */
5463   if (Is_Constructor (gnat_entity))
5464     return true;
5465
5466   /* This is set on the E_Subprogram_Type built for a dispatching call.  */
5467   if (Is_Dispatch_Table_Entity (gnat_entity))
5468     return true;
5469
5470   return false;
5471 }
5472
5473 /* Finalize the processing of From_Limited_With incomplete types.  */
5474
5475 void
5476 finalize_from_limited_with (void)
5477 {
5478   struct incomplete *p, *next;
5479
5480   p = defer_limited_with;
5481   defer_limited_with = NULL;
5482
5483   for (; p; p = next)
5484     {
5485       next = p->next;
5486
5487       if (p->old_type)
5488         update_pointer_to (TYPE_MAIN_VARIANT (p->old_type),
5489                            gnat_to_gnu_type (p->full_type));
5490       free (p);
5491     }
5492 }
5493
5494 /* Return the equivalent type to be used for GNAT_ENTITY, if it's a
5495    kind of type (such E_Task_Type) that has a different type which Gigi
5496    uses for its representation.  If the type does not have a special type
5497    for its representation, return GNAT_ENTITY.  If a type is supposed to
5498    exist, but does not, abort unless annotating types, in which case
5499    return Empty.  If GNAT_ENTITY is Empty, return Empty.  */
5500
5501 Entity_Id
5502 Gigi_Equivalent_Type (Entity_Id gnat_entity)
5503 {
5504   Entity_Id gnat_equiv = gnat_entity;
5505
5506   if (No (gnat_entity))
5507     return gnat_entity;
5508
5509   switch (Ekind (gnat_entity))
5510     {
5511     case E_Class_Wide_Subtype:
5512       if (Present (Equivalent_Type (gnat_entity)))
5513         gnat_equiv = Equivalent_Type (gnat_entity);
5514       break;
5515
5516     case E_Access_Protected_Subprogram_Type:
5517     case E_Anonymous_Access_Protected_Subprogram_Type:
5518       gnat_equiv = Equivalent_Type (gnat_entity);
5519       break;
5520
5521     case E_Class_Wide_Type:
5522       gnat_equiv = Root_Type (gnat_entity);
5523       break;
5524
5525     case E_Task_Type:
5526     case E_Task_Subtype:
5527     case E_Protected_Type:
5528     case E_Protected_Subtype:
5529       gnat_equiv = Corresponding_Record_Type (gnat_entity);
5530       break;
5531
5532     default:
5533       break;
5534     }
5535
5536   gcc_assert (Present (gnat_equiv) || type_annotate_only);
5537
5538   return gnat_equiv;
5539 }
5540
5541 /* Return a GCC tree for a type corresponding to the component type of the
5542    array type or subtype GNAT_ARRAY.  DEFINITION is true if this component
5543    is for an array being defined.  DEBUG_INFO_P is true if we need to write
5544    debug information for other types that we may create in the process.  */
5545
5546 static tree
5547 gnat_to_gnu_component_type (Entity_Id gnat_array, bool definition,
5548                             bool debug_info_p)
5549 {
5550   const Entity_Id gnat_type = Component_Type (gnat_array);
5551   tree gnu_type = gnat_to_gnu_type (gnat_type);
5552   tree gnu_comp_size;
5553
5554   /* Try to get a smaller form of the component if needed.  */
5555   if ((Is_Packed (gnat_array)
5556        || Has_Component_Size_Clause (gnat_array))
5557       && !Is_Bit_Packed_Array (gnat_array)
5558       && !Has_Aliased_Components (gnat_array)
5559       && !Strict_Alignment (gnat_type)
5560       && RECORD_OR_UNION_TYPE_P (gnu_type)
5561       && !TYPE_FAT_POINTER_P (gnu_type)
5562       && tree_fits_uhwi_p (TYPE_SIZE (gnu_type)))
5563     gnu_type = make_packable_type (gnu_type, false);
5564
5565   if (Has_Atomic_Components (gnat_array))
5566     check_ok_for_atomic_type (gnu_type, gnat_array, true);
5567
5568   /* Get and validate any specified Component_Size.  */
5569   gnu_comp_size
5570     = validate_size (Component_Size (gnat_array), gnu_type, gnat_array,
5571                      Is_Bit_Packed_Array (gnat_array) ? TYPE_DECL : VAR_DECL,
5572                      true, Has_Component_Size_Clause (gnat_array));
5573
5574   /* If the array has aliased components and the component size can be zero,
5575      force at least unit size to ensure that the components have distinct
5576      addresses.  */
5577   if (!gnu_comp_size
5578       && Has_Aliased_Components (gnat_array)
5579       && (integer_zerop (TYPE_SIZE (gnu_type))
5580           || (TREE_CODE (gnu_type) == ARRAY_TYPE
5581               && !TREE_CONSTANT (TYPE_SIZE (gnu_type)))))
5582     gnu_comp_size
5583       = size_binop (MAX_EXPR, TYPE_SIZE (gnu_type), bitsize_unit_node);
5584
5585   /* If the component type is a RECORD_TYPE that has a self-referential size,
5586      then use the maximum size for the component size.  */
5587   if (!gnu_comp_size
5588       && TREE_CODE (gnu_type) == RECORD_TYPE
5589       && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_type)))
5590     gnu_comp_size = max_size (TYPE_SIZE (gnu_type), true);
5591
5592   /* Honor the component size.  This is not needed for bit-packed arrays.  */
5593   if (gnu_comp_size && !Is_Bit_Packed_Array (gnat_array))
5594     {
5595       tree orig_type = gnu_type;
5596       unsigned int max_align;
5597
5598       /* If an alignment is specified, use it as a cap on the component type
5599          so that it can be honored for the whole type.  But ignore it for the
5600          original type of packed array types.  */
5601       if (No (Packed_Array_Impl_Type (gnat_array))
5602           && Known_Alignment (gnat_array))
5603         max_align = validate_alignment (Alignment (gnat_array), gnat_array, 0);
5604       else
5605         max_align = 0;
5606
5607       gnu_type = make_type_from_size (gnu_type, gnu_comp_size, false);
5608       if (max_align > 0 && TYPE_ALIGN (gnu_type) > max_align)
5609         gnu_type = orig_type;
5610       else
5611         orig_type = gnu_type;
5612
5613       gnu_type = maybe_pad_type (gnu_type, gnu_comp_size, 0, gnat_array,
5614                                  true, false, definition, true);
5615
5616       /* If a padding record was made, declare it now since it will never be
5617          declared otherwise.  This is necessary to ensure that its subtrees
5618          are properly marked.  */
5619       if (gnu_type != orig_type && !DECL_P (TYPE_NAME (gnu_type)))
5620         create_type_decl (TYPE_NAME (gnu_type), gnu_type, true, debug_info_p,
5621                           gnat_array);
5622     }
5623
5624   if (Has_Volatile_Components (gnat_array))
5625     {
5626       const int quals
5627         = TYPE_QUAL_VOLATILE
5628           | (Has_Atomic_Components (gnat_array) ? TYPE_QUAL_ATOMIC : 0);
5629       gnu_type = change_qualified_type (gnu_type, quals);
5630     }
5631
5632   return gnu_type;
5633 }
5634
5635 /* Return a GCC tree for a parameter corresponding to GNAT_PARAM and
5636    using MECH as its passing mechanism, to be placed in the parameter
5637    list built for GNAT_SUBPROG.  Assume a foreign convention for the
5638    latter if FOREIGN is true.  Also set CICO to true if the parameter
5639    must use the copy-in copy-out implementation mechanism.
5640
5641    The returned tree is a PARM_DECL, except for those cases where no
5642    parameter needs to be actually passed to the subprogram; the type
5643    of this "shadow" parameter is then returned instead.  */
5644
5645 static tree
5646 gnat_to_gnu_param (Entity_Id gnat_param, Mechanism_Type mech,
5647                    Entity_Id gnat_subprog, bool foreign, bool *cico)
5648 {
5649   tree gnu_param_name = get_entity_name (gnat_param);
5650   tree gnu_param_type = gnat_to_gnu_type (Etype (gnat_param));
5651   bool in_param = (Ekind (gnat_param) == E_In_Parameter);
5652   /* The parameter can be indirectly modified if its address is taken.  */
5653   bool ro_param = in_param && !Address_Taken (gnat_param);
5654   bool by_return = false, by_component_ptr = false;
5655   bool by_ref = false;
5656   tree gnu_param;
5657
5658   /* Copy-return is used only for the first parameter of a valued procedure.
5659      It's a copy mechanism for which a parameter is never allocated.  */
5660   if (mech == By_Copy_Return)
5661     {
5662       gcc_assert (Ekind (gnat_param) == E_Out_Parameter);
5663       mech = By_Copy;
5664       by_return = true;
5665     }
5666
5667   /* If this is either a foreign function or if the underlying type won't
5668      be passed by reference and is as aligned as the original type, strip
5669      off possible padding type.  */
5670   if (TYPE_IS_PADDING_P (gnu_param_type))
5671     {
5672       tree unpadded_type = TREE_TYPE (TYPE_FIELDS (gnu_param_type));
5673
5674       if (foreign
5675           || (!must_pass_by_ref (unpadded_type)
5676               && mech != By_Reference
5677               && (mech == By_Copy || !default_pass_by_ref (unpadded_type))
5678               && TYPE_ALIGN (unpadded_type) >= TYPE_ALIGN (gnu_param_type)))
5679         gnu_param_type = unpadded_type;
5680     }
5681
5682   /* If this is a read-only parameter, make a variant of the type that is
5683      read-only.  ??? However, if this is an unconstrained array, that type
5684      can be very complex, so skip it for now.  Likewise for any other
5685      self-referential type.  */
5686   if (ro_param
5687       && TREE_CODE (gnu_param_type) != UNCONSTRAINED_ARRAY_TYPE
5688       && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_param_type)))
5689     gnu_param_type = change_qualified_type (gnu_param_type, TYPE_QUAL_CONST);
5690
5691   /* For foreign conventions, pass arrays as pointers to the element type.
5692      First check for unconstrained array and get the underlying array.  */
5693   if (foreign && TREE_CODE (gnu_param_type) == UNCONSTRAINED_ARRAY_TYPE)
5694     gnu_param_type
5695       = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_param_type))));
5696
5697   /* For GCC builtins, pass Address integer types as (void *)  */
5698   if (Convention (gnat_subprog) == Convention_Intrinsic
5699       && Present (Interface_Name (gnat_subprog))
5700       && Is_Descendent_Of_Address (Etype (gnat_param)))
5701     gnu_param_type = ptr_void_type_node;
5702
5703   /* Arrays are passed as pointers to element type for foreign conventions.  */
5704   if (foreign && mech != By_Copy && TREE_CODE (gnu_param_type) == ARRAY_TYPE)
5705     {
5706       /* Strip off any multi-dimensional entries, then strip
5707          off the last array to get the component type.  */
5708       while (TREE_CODE (TREE_TYPE (gnu_param_type)) == ARRAY_TYPE
5709              && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_param_type)))
5710         gnu_param_type = TREE_TYPE (gnu_param_type);
5711
5712       by_component_ptr = true;
5713       gnu_param_type = TREE_TYPE (gnu_param_type);
5714
5715       if (ro_param)
5716         gnu_param_type
5717           = change_qualified_type (gnu_param_type, TYPE_QUAL_CONST);
5718
5719       gnu_param_type = build_pointer_type (gnu_param_type);
5720     }
5721
5722   /* Fat pointers are passed as thin pointers for foreign conventions.  */
5723   else if (foreign && TYPE_IS_FAT_POINTER_P (gnu_param_type))
5724     gnu_param_type
5725       = make_type_from_size (gnu_param_type, size_int (POINTER_SIZE), 0);
5726
5727   /* If we must pass or were requested to pass by reference, do so.
5728      If we were requested to pass by copy, do so.
5729      Otherwise, for foreign conventions, pass In Out or Out parameters
5730      or aggregates by reference.  For COBOL and Fortran, pass all
5731      integer and FP types that way too.  For Convention Ada, use
5732      the standard Ada default.  */
5733   else if (must_pass_by_ref (gnu_param_type)
5734            || mech == By_Reference
5735            || (mech != By_Copy
5736                && ((foreign
5737                     && (!in_param || AGGREGATE_TYPE_P (gnu_param_type)))
5738                    || (foreign
5739                        && (Convention (gnat_subprog) == Convention_Fortran
5740                            || Convention (gnat_subprog) == Convention_COBOL)
5741                        && (INTEGRAL_TYPE_P (gnu_param_type)
5742                            || FLOAT_TYPE_P (gnu_param_type)))
5743                    || (!foreign
5744                        && default_pass_by_ref (gnu_param_type)))))
5745     {
5746       /* We take advantage of 6.2(12) by considering that references built for
5747          parameters whose type isn't by-ref and for which the mechanism hasn't
5748          been forced to by-ref are restrict-qualified in the C sense.  */
5749       bool restrict_p
5750         = !TYPE_IS_BY_REFERENCE_P (gnu_param_type) && mech != By_Reference;
5751       gnu_param_type = build_reference_type (gnu_param_type);
5752       if (restrict_p)
5753         gnu_param_type
5754           = change_qualified_type (gnu_param_type, TYPE_QUAL_RESTRICT);
5755       by_ref = true;
5756     }
5757
5758   /* Pass In Out or Out parameters using copy-in copy-out mechanism.  */
5759   else if (!in_param)
5760     *cico = true;
5761
5762   if (mech == By_Copy && (by_ref || by_component_ptr))
5763     post_error ("?cannot pass & by copy", gnat_param);
5764
5765   /* If this is an Out parameter that isn't passed by reference and isn't
5766      a pointer or aggregate, we don't make a PARM_DECL for it.  Instead,
5767      it will be a VAR_DECL created when we process the procedure, so just
5768      return its type.  For the special parameter of a valued procedure,
5769      never pass it in.
5770
5771      An exception is made to cover the RM-6.4.1 rule requiring "by copy"
5772      Out parameters with discriminants or implicit initial values to be
5773      handled like In Out parameters.  These type are normally built as
5774      aggregates, hence passed by reference, except for some packed arrays
5775      which end up encoded in special integer types.  Note that scalars can
5776      be given implicit initial values using the Default_Value aspect.
5777
5778      The exception we need to make is then for packed arrays of records
5779      with discriminants or implicit initial values.  We have no light/easy
5780      way to check for the latter case, so we merely check for packed arrays
5781      of records.  This may lead to useless copy-in operations, but in very
5782      rare cases only, as these would be exceptions in a set of already
5783      exceptional situations.  */
5784   if (Ekind (gnat_param) == E_Out_Parameter
5785       && !by_ref
5786       && (by_return
5787           || (!POINTER_TYPE_P (gnu_param_type)
5788               && !AGGREGATE_TYPE_P (gnu_param_type)
5789               && !Has_Default_Aspect (Etype (gnat_param))))
5790       && !(Is_Array_Type (Etype (gnat_param))
5791            && Is_Packed (Etype (gnat_param))
5792            && Is_Composite_Type (Component_Type (Etype (gnat_param)))))
5793     return gnu_param_type;
5794
5795   gnu_param = create_param_decl (gnu_param_name, gnu_param_type,
5796                                  ro_param || by_ref || by_component_ptr);
5797   DECL_BY_REF_P (gnu_param) = by_ref;
5798   DECL_BY_COMPONENT_PTR_P (gnu_param) = by_component_ptr;
5799   DECL_POINTS_TO_READONLY_P (gnu_param)
5800     = (ro_param && (by_ref || by_component_ptr));
5801   DECL_CAN_NEVER_BE_NULL_P (gnu_param) = Can_Never_Be_Null (gnat_param);
5802
5803   /* If no Mechanism was specified, indicate what we're using, then
5804      back-annotate it.  */
5805   if (mech == Default)
5806     mech = (by_ref || by_component_ptr) ? By_Reference : By_Copy;
5807
5808   Set_Mechanism (gnat_param, mech);
5809   return gnu_param;
5810 }
5811
5812 /* Return true if GNAT_ENTITY is an incomplete entity coming from a limited
5813    with of the main unit and whose full view has not been elaborated yet.  */
5814
5815 static bool
5816 is_from_limited_with_of_main (Entity_Id gnat_entity)
5817 {
5818   /* Class-wide types are always transformed into their root type.  */
5819   if (Ekind (gnat_entity) == E_Class_Wide_Type)
5820     gnat_entity = Root_Type (gnat_entity);
5821
5822   if (IN (Ekind (gnat_entity), Incomplete_Kind)
5823       && From_Limited_With (gnat_entity))
5824     {
5825       Entity_Id gnat_full_view = Non_Limited_View (gnat_entity);
5826
5827       if (present_gnu_tree (gnat_full_view))
5828         return false;
5829
5830       return In_Extended_Main_Code_Unit (gnat_full_view);
5831     }
5832
5833   return false;
5834 }
5835
5836 /* Like build_qualified_type, but TYPE_QUALS is added to the existing
5837    qualifiers on TYPE.  */
5838
5839 static tree
5840 change_qualified_type (tree type, int type_quals)
5841 {
5842   return build_qualified_type (type, TYPE_QUALS (type) | type_quals);
5843 }
5844
5845 /* Return true if DISCR1 and DISCR2 represent the same discriminant.  */
5846
5847 static bool
5848 same_discriminant_p (Entity_Id discr1, Entity_Id discr2)
5849 {
5850   while (Present (Corresponding_Discriminant (discr1)))
5851     discr1 = Corresponding_Discriminant (discr1);
5852
5853   while (Present (Corresponding_Discriminant (discr2)))
5854     discr2 = Corresponding_Discriminant (discr2);
5855
5856   return
5857     Original_Record_Component (discr1) == Original_Record_Component (discr2);
5858 }
5859
5860 /* Return true if the array type GNU_TYPE, which represents a dimension of
5861    GNAT_TYPE, has a non-aliased component in the back-end sense.  */
5862
5863 static bool
5864 array_type_has_nonaliased_component (tree gnu_type, Entity_Id gnat_type)
5865 {
5866   /* If the array type is not the innermost dimension of the GNAT type,
5867      then it has a non-aliased component.  */
5868   if (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
5869       && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
5870     return true;
5871
5872   /* If the array type has an aliased component in the front-end sense,
5873      then it also has an aliased component in the back-end sense.  */
5874   if (Has_Aliased_Components (gnat_type))
5875     return false;
5876
5877   /* If this is a derived type, then it has a non-aliased component if
5878      and only if its parent type also has one.  */
5879   if (Is_Derived_Type (gnat_type))
5880     {
5881       tree gnu_parent_type = gnat_to_gnu_type (Etype (gnat_type));
5882       int index;
5883       if (TREE_CODE (gnu_parent_type) == UNCONSTRAINED_ARRAY_TYPE)
5884         gnu_parent_type
5885           = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_parent_type))));
5886       for (index = Number_Dimensions (gnat_type) - 1; index > 0; index--)
5887         gnu_parent_type = TREE_TYPE (gnu_parent_type);
5888       return TYPE_NONALIASED_COMPONENT (gnu_parent_type);
5889     }
5890
5891   /* Otherwise, rely exclusively on properties of the element type.  */
5892   return type_for_nonaliased_component_p (TREE_TYPE (gnu_type));
5893 }
5894
5895 /* Return true if GNAT_ADDRESS is a value known at compile-time.  */
5896
5897 static bool
5898 compile_time_known_address_p (Node_Id gnat_address)
5899 {
5900   /* Catch System'To_Address.  */
5901   if (Nkind (gnat_address) == N_Unchecked_Type_Conversion)
5902     gnat_address = Expression (gnat_address);
5903
5904   return Compile_Time_Known_Value (gnat_address);
5905 }
5906
5907 /* Return true if GNAT_RANGE, a N_Range node, cannot be superflat, i.e. if the
5908    inequality HB >= LB-1 is true.  LB and HB are the low and high bounds.  */
5909
5910 static bool
5911 cannot_be_superflat_p (Node_Id gnat_range)
5912 {
5913   Node_Id gnat_lb = Low_Bound (gnat_range), gnat_hb = High_Bound (gnat_range);
5914   Node_Id scalar_range;
5915   tree gnu_lb, gnu_hb, gnu_lb_minus_one;
5916
5917   /* If the low bound is not constant, try to find an upper bound.  */
5918   while (Nkind (gnat_lb) != N_Integer_Literal
5919          && (Ekind (Etype (gnat_lb)) == E_Signed_Integer_Subtype
5920              || Ekind (Etype (gnat_lb)) == E_Modular_Integer_Subtype)
5921          && (scalar_range = Scalar_Range (Etype (gnat_lb)))
5922          && (Nkind (scalar_range) == N_Signed_Integer_Type_Definition
5923              || Nkind (scalar_range) == N_Range))
5924     gnat_lb = High_Bound (scalar_range);
5925
5926   /* If the high bound is not constant, try to find a lower bound.  */
5927   while (Nkind (gnat_hb) != N_Integer_Literal
5928          && (Ekind (Etype (gnat_hb)) == E_Signed_Integer_Subtype
5929              || Ekind (Etype (gnat_hb)) == E_Modular_Integer_Subtype)
5930          && (scalar_range = Scalar_Range (Etype (gnat_hb)))
5931          && (Nkind (scalar_range) == N_Signed_Integer_Type_Definition
5932              || Nkind (scalar_range) == N_Range))
5933     gnat_hb = Low_Bound (scalar_range);
5934
5935   /* If we have failed to find constant bounds, punt.  */
5936   if (Nkind (gnat_lb) != N_Integer_Literal
5937       || Nkind (gnat_hb) != N_Integer_Literal)
5938     return false;
5939
5940   /* We need at least a signed 64-bit type to catch most cases.  */
5941   gnu_lb = UI_To_gnu (Intval (gnat_lb), sbitsizetype);
5942   gnu_hb = UI_To_gnu (Intval (gnat_hb), sbitsizetype);
5943   if (TREE_OVERFLOW (gnu_lb) || TREE_OVERFLOW (gnu_hb))
5944     return false;
5945
5946   /* If the low bound is the smallest integer, nothing can be smaller.  */
5947   gnu_lb_minus_one = size_binop (MINUS_EXPR, gnu_lb, sbitsize_one_node);
5948   if (TREE_OVERFLOW (gnu_lb_minus_one))
5949     return true;
5950
5951   return !tree_int_cst_lt (gnu_hb, gnu_lb_minus_one);
5952 }
5953
5954 /* Return true if GNU_EXPR is (essentially) the address of a CONSTRUCTOR.  */
5955
5956 static bool
5957 constructor_address_p (tree gnu_expr)
5958 {
5959   while (TREE_CODE (gnu_expr) == NOP_EXPR
5960          || TREE_CODE (gnu_expr) == CONVERT_EXPR
5961          || TREE_CODE (gnu_expr) == NON_LVALUE_EXPR)
5962     gnu_expr = TREE_OPERAND (gnu_expr, 0);
5963
5964   return (TREE_CODE (gnu_expr) == ADDR_EXPR
5965           && TREE_CODE (TREE_OPERAND (gnu_expr, 0)) == CONSTRUCTOR);
5966 }
5967 \f
5968 /* Given GNAT_ENTITY, elaborate all expressions that are required to
5969    be elaborated at the point of its definition, but do nothing else.  */
5970
5971 void
5972 elaborate_entity (Entity_Id gnat_entity)
5973 {
5974   switch (Ekind (gnat_entity))
5975     {
5976     case E_Signed_Integer_Subtype:
5977     case E_Modular_Integer_Subtype:
5978     case E_Enumeration_Subtype:
5979     case E_Ordinary_Fixed_Point_Subtype:
5980     case E_Decimal_Fixed_Point_Subtype:
5981     case E_Floating_Point_Subtype:
5982       {
5983         Node_Id gnat_lb = Type_Low_Bound (gnat_entity);
5984         Node_Id gnat_hb = Type_High_Bound (gnat_entity);
5985
5986         /* ??? Tests to avoid Constraint_Error in static expressions
5987            are needed until after the front stops generating bogus
5988            conversions on bounds of real types.  */
5989         if (!Raises_Constraint_Error (gnat_lb))
5990           elaborate_expression (gnat_lb, gnat_entity, get_identifier ("L"),
5991                                 true, false, Needs_Debug_Info (gnat_entity));
5992         if (!Raises_Constraint_Error (gnat_hb))
5993           elaborate_expression (gnat_hb, gnat_entity, get_identifier ("U"),
5994                                 true, false, Needs_Debug_Info (gnat_entity));
5995       break;
5996       }
5997
5998     case E_Record_Subtype:
5999     case E_Private_Subtype:
6000     case E_Limited_Private_Subtype:
6001     case E_Record_Subtype_With_Private:
6002       if (Has_Discriminants (gnat_entity) && Is_Constrained (gnat_entity))
6003         {
6004           Node_Id gnat_discriminant_expr;
6005           Entity_Id gnat_field;
6006
6007           for (gnat_field
6008                = First_Discriminant (Implementation_Base_Type (gnat_entity)),
6009                gnat_discriminant_expr
6010                = First_Elmt (Discriminant_Constraint (gnat_entity));
6011                Present (gnat_field);
6012                gnat_field = Next_Discriminant (gnat_field),
6013                gnat_discriminant_expr = Next_Elmt (gnat_discriminant_expr))
6014             /* Ignore access discriminants.  */
6015             if (!Is_Access_Type (Etype (Node (gnat_discriminant_expr))))
6016               elaborate_expression (Node (gnat_discriminant_expr),
6017                                     gnat_entity, get_entity_name (gnat_field),
6018                                     true, false, false);
6019         }
6020       break;
6021
6022     }
6023 }
6024 \f
6025 /* Return true if the size in units represented by GNU_SIZE can be handled by
6026    an allocation.  If STATIC_P is true, consider only what can be done with a
6027    static allocation.  */
6028
6029 static bool
6030 allocatable_size_p (tree gnu_size, bool static_p)
6031 {
6032   /* We can allocate a fixed size if it is a valid for the middle-end.  */
6033   if (TREE_CODE (gnu_size) == INTEGER_CST)
6034     return valid_constant_size_p (gnu_size);
6035
6036   /* We can allocate a variable size if this isn't a static allocation.  */
6037   else
6038     return !static_p;
6039 }
6040 \f
6041 /* Prepend to ATTR_LIST an entry for an attribute with provided TYPE,
6042    NAME, ARGS and ERROR_POINT.  */
6043
6044 static void
6045 prepend_one_attribute (struct attrib **attr_list,
6046                        enum attr_type attr_type,
6047                        tree attr_name,
6048                        tree attr_args,
6049                        Node_Id attr_error_point)
6050 {
6051   struct attrib * attr = (struct attrib *) xmalloc (sizeof (struct attrib));
6052
6053   attr->type = attr_type;
6054   attr->name = attr_name;
6055   attr->args = attr_args;
6056   attr->error_point = attr_error_point;
6057
6058   attr->next = *attr_list;
6059   *attr_list = attr;
6060 }
6061
6062 /* Prepend to ATTR_LIST an entry for an attribute provided by GNAT_PRAGMA.  */
6063
6064 static void
6065 prepend_one_attribute_pragma (struct attrib **attr_list, Node_Id gnat_pragma)
6066 {
6067   const Node_Id gnat_arg = Pragma_Argument_Associations (gnat_pragma);
6068   tree gnu_arg0 = NULL_TREE, gnu_arg1 = NULL_TREE;
6069   enum attr_type etype;
6070
6071   /* Map the pragma at hand.  Skip if this isn't one we know how to handle.  */
6072   switch (Get_Pragma_Id (Chars (Pragma_Identifier (gnat_pragma))))
6073     {
6074     case Pragma_Machine_Attribute:
6075       etype = ATTR_MACHINE_ATTRIBUTE;
6076       break;
6077
6078     case Pragma_Linker_Alias:
6079       etype = ATTR_LINK_ALIAS;
6080       break;
6081
6082     case Pragma_Linker_Section:
6083       etype = ATTR_LINK_SECTION;
6084       break;
6085
6086     case Pragma_Linker_Constructor:
6087       etype = ATTR_LINK_CONSTRUCTOR;
6088       break;
6089
6090     case Pragma_Linker_Destructor:
6091       etype = ATTR_LINK_DESTRUCTOR;
6092       break;
6093
6094     case Pragma_Weak_External:
6095       etype = ATTR_WEAK_EXTERNAL;
6096       break;
6097
6098     case Pragma_Thread_Local_Storage:
6099       etype = ATTR_THREAD_LOCAL_STORAGE;
6100       break;
6101
6102     default:
6103       return;
6104     }
6105
6106   /* See what arguments we have and turn them into GCC trees for attribute
6107      handlers.  These expect identifier for strings.  We handle at most two
6108      arguments and static expressions only.  */
6109   if (Present (gnat_arg) && Present (First (gnat_arg)))
6110     {
6111       Node_Id gnat_arg0 = Next (First (gnat_arg));
6112       Node_Id gnat_arg1 = Empty;
6113
6114       if (Present (gnat_arg0)
6115           && Is_OK_Static_Expression (Expression (gnat_arg0)))
6116         {
6117           gnu_arg0 = gnat_to_gnu (Expression (gnat_arg0));
6118
6119           if (TREE_CODE (gnu_arg0) == STRING_CST)
6120             {
6121               gnu_arg0 = get_identifier (TREE_STRING_POINTER (gnu_arg0));
6122               if (IDENTIFIER_LENGTH (gnu_arg0) == 0)
6123                 return;
6124             }
6125
6126           gnat_arg1 = Next (gnat_arg0);
6127         }
6128
6129       if (Present (gnat_arg1)
6130           && Is_OK_Static_Expression (Expression (gnat_arg1)))
6131         {
6132           gnu_arg1 = gnat_to_gnu (Expression (gnat_arg1));
6133
6134           if (TREE_CODE (gnu_arg1) == STRING_CST)
6135            gnu_arg1 = get_identifier (TREE_STRING_POINTER (gnu_arg1));
6136         }
6137     }
6138
6139   /* Prepend to the list.  Make a list of the argument we might have, as GCC
6140      expects it.  */
6141   prepend_one_attribute (attr_list, etype, gnu_arg0,
6142                          gnu_arg1
6143                          ? build_tree_list (NULL_TREE, gnu_arg1) : NULL_TREE,
6144                          Present (Next (First (gnat_arg)))
6145                          ? Expression (Next (First (gnat_arg))) : gnat_pragma);
6146 }
6147
6148 /* Prepend to ATTR_LIST the list of attributes for GNAT_ENTITY, if any.  */
6149
6150 static void
6151 prepend_attributes (struct attrib **attr_list, Entity_Id gnat_entity)
6152 {
6153   Node_Id gnat_temp;
6154
6155   /* Attributes are stored as Representation Item pragmas.  */
6156   for (gnat_temp = First_Rep_Item (gnat_entity);
6157        Present (gnat_temp);
6158        gnat_temp = Next_Rep_Item (gnat_temp))
6159     if (Nkind (gnat_temp) == N_Pragma)
6160       prepend_one_attribute_pragma (attr_list, gnat_temp);
6161 }
6162 \f
6163 /* Given a GNAT tree GNAT_EXPR, for an expression which is a value within a
6164    type definition (either a bound or a discriminant value) for GNAT_ENTITY,
6165    return the GCC tree to use for that expression.  GNU_NAME is the suffix
6166    to use if a variable needs to be created and DEFINITION is true if this
6167    is a definition of GNAT_ENTITY.  If NEED_VALUE is true, we need a result;
6168    otherwise, we are just elaborating the expression for side-effects.  If
6169    NEED_DEBUG is true, we need a variable for debugging purposes even if it
6170    isn't needed for code generation.  */
6171
6172 static tree
6173 elaborate_expression (Node_Id gnat_expr, Entity_Id gnat_entity, tree gnu_name,
6174                       bool definition, bool need_value, bool need_debug)
6175 {
6176   tree gnu_expr;
6177
6178   /* If we already elaborated this expression (e.g. it was involved
6179      in the definition of a private type), use the old value.  */
6180   if (present_gnu_tree (gnat_expr))
6181     return get_gnu_tree (gnat_expr);
6182
6183   /* If we don't need a value and this is static or a discriminant,
6184      we don't need to do anything.  */
6185   if (!need_value
6186       && (Is_OK_Static_Expression (gnat_expr)
6187           || (Nkind (gnat_expr) == N_Identifier
6188               && Ekind (Entity (gnat_expr)) == E_Discriminant)))
6189     return NULL_TREE;
6190
6191   /* If it's a static expression, we don't need a variable for debugging.  */
6192   if (need_debug && Is_OK_Static_Expression (gnat_expr))
6193     need_debug = false;
6194
6195   /* Otherwise, convert this tree to its GCC equivalent and elaborate it.  */
6196   gnu_expr = elaborate_expression_1 (gnat_to_gnu (gnat_expr), gnat_entity,
6197                                      gnu_name, definition, need_debug);
6198
6199   /* Save the expression in case we try to elaborate this entity again.  Since
6200      it's not a DECL, don't check it.  Don't save if it's a discriminant.  */
6201   if (!CONTAINS_PLACEHOLDER_P (gnu_expr))
6202     save_gnu_tree (gnat_expr, gnu_expr, true);
6203
6204   return need_value ? gnu_expr : error_mark_node;
6205 }
6206
6207 /* Similar, but take a GNU expression and always return a result.  */
6208
6209 static tree
6210 elaborate_expression_1 (tree gnu_expr, Entity_Id gnat_entity, tree gnu_name,
6211                         bool definition, bool need_debug)
6212 {
6213   const bool expr_public_p = Is_Public (gnat_entity);
6214   const bool expr_global_p = expr_public_p || global_bindings_p ();
6215   bool expr_variable_p, use_variable;
6216
6217   /* In most cases, we won't see a naked FIELD_DECL because a discriminant
6218      reference will have been replaced with a COMPONENT_REF when the type
6219      is being elaborated.  However, there are some cases involving child
6220      types where we will.  So convert it to a COMPONENT_REF.  We hope it
6221      will be at the highest level of the expression in these cases.  */
6222   if (TREE_CODE (gnu_expr) == FIELD_DECL)
6223     gnu_expr = build3 (COMPONENT_REF, TREE_TYPE (gnu_expr),
6224                        build0 (PLACEHOLDER_EXPR, DECL_CONTEXT (gnu_expr)),
6225                        gnu_expr, NULL_TREE);
6226
6227   /* If GNU_EXPR contains a placeholder, just return it.  We rely on the fact
6228      that an expression cannot contain both a discriminant and a variable.  */
6229   if (CONTAINS_PLACEHOLDER_P (gnu_expr))
6230     return gnu_expr;
6231
6232   /* If GNU_EXPR is neither a constant nor based on a read-only variable, make
6233      a variable that is initialized to contain the expression when the package
6234      containing the definition is elaborated.  If this entity is defined at top
6235      level, replace the expression by the variable; otherwise use a SAVE_EXPR
6236      if this is necessary.  */
6237   if (CONSTANT_CLASS_P (gnu_expr))
6238     expr_variable_p = false;
6239   else
6240     {
6241       /* Skip any conversions and simple constant arithmetics to see if the
6242          expression is based on a read-only variable.
6243          ??? This really should remain read-only, but we have to think about
6244          the typing of the tree here.  */
6245       tree inner = remove_conversions (gnu_expr, true);
6246
6247       inner = skip_simple_constant_arithmetic (inner);
6248
6249       if (handled_component_p (inner))
6250         inner = get_inner_constant_reference (inner);
6251
6252       expr_variable_p
6253         = !(inner
6254             && TREE_CODE (inner) == VAR_DECL
6255             && (TREE_READONLY (inner) || DECL_READONLY_ONCE_ELAB (inner)));
6256     }
6257
6258   /* We only need to use the variable if we are in a global context since GCC
6259      can do the right thing in the local case.  However, when not optimizing,
6260      use it for bounds of loop iteration scheme to avoid code duplication.  */
6261   use_variable = expr_variable_p
6262                  && (expr_global_p
6263                      || (!optimize
6264                          && definition
6265                          && Is_Itype (gnat_entity)
6266                          && Nkind (Associated_Node_For_Itype (gnat_entity))
6267                             == N_Loop_Parameter_Specification));
6268
6269   /* Now create it, possibly only for debugging purposes.  */
6270   if (use_variable || need_debug)
6271     {
6272       /* The following variable creation can happen when processing the body of
6273          subprograms that are defined out of the extended main unit and
6274          inlined. In this case, we are not at the global scope, and thus the
6275          new variable must not be tagged "external", as we used to do here as
6276          long as definition == 0.  */
6277       const bool external_flag = !definition && expr_global_p;
6278       tree gnu_decl
6279         = create_var_decl_1
6280           (create_concat_name (gnat_entity, IDENTIFIER_POINTER (gnu_name)),
6281            NULL_TREE, TREE_TYPE (gnu_expr), gnu_expr, true, expr_public_p,
6282            external_flag, expr_global_p, !need_debug, NULL, gnat_entity);
6283
6284       DECL_ARTIFICIAL (gnu_decl) = 1;
6285
6286       /* Using this variable at debug time (if need_debug is true) requires a
6287          proper location.  The back-end will compute a location for this
6288          variable only if the variable is used by the generated code.
6289          Returning the variable ensures the caller will use it in generated
6290          code.  Note that there is no need for a location if the debug info
6291          contains an integer constant.
6292          FIXME: when the encoding-based debug scheme is dropped, move this
6293          condition to the top-level IF block: we will not need to create a
6294          variable anymore in such cases, then.  */
6295       if (use_variable || (need_debug && !TREE_CONSTANT (gnu_expr)))
6296         return gnu_decl;
6297     }
6298
6299   return expr_variable_p ? gnat_save_expr (gnu_expr) : gnu_expr;
6300 }
6301
6302 /* Similar, but take an alignment factor and make it explicit in the tree.  */
6303
6304 static tree
6305 elaborate_expression_2 (tree gnu_expr, Entity_Id gnat_entity, tree gnu_name,
6306                         bool definition, bool need_debug, unsigned int align)
6307 {
6308   tree unit_align = size_int (align / BITS_PER_UNIT);
6309   return
6310     size_binop (MULT_EXPR,
6311                 elaborate_expression_1 (size_binop (EXACT_DIV_EXPR,
6312                                                     gnu_expr,
6313                                                     unit_align),
6314                                         gnat_entity, gnu_name, definition,
6315                                         need_debug),
6316                 unit_align);
6317 }
6318 \f
6319 /* Given a GNU tree and a GNAT list of choices, generate an expression to test
6320    the value passed against the list of choices.  */
6321
6322 tree
6323 choices_to_gnu (tree operand, Node_Id choices)
6324 {
6325   Node_Id choice;
6326   Node_Id gnat_temp;
6327   tree result = boolean_false_node;
6328   tree this_test, low = 0, high = 0, single = 0;
6329
6330   for (choice = First (choices); Present (choice); choice = Next (choice))
6331     {
6332       switch (Nkind (choice))
6333         {
6334         case N_Range:
6335           low = gnat_to_gnu (Low_Bound (choice));
6336           high = gnat_to_gnu (High_Bound (choice));
6337
6338           this_test
6339             = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
6340                                build_binary_op (GE_EXPR, boolean_type_node,
6341                                                 operand, low),
6342                                build_binary_op (LE_EXPR, boolean_type_node,
6343                                                 operand, high));
6344
6345           break;
6346
6347         case N_Subtype_Indication:
6348           gnat_temp = Range_Expression (Constraint (choice));
6349           low = gnat_to_gnu (Low_Bound (gnat_temp));
6350           high = gnat_to_gnu (High_Bound (gnat_temp));
6351
6352           this_test
6353             = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
6354                                build_binary_op (GE_EXPR, boolean_type_node,
6355                                                 operand, low),
6356                                build_binary_op (LE_EXPR, boolean_type_node,
6357                                                 operand, high));
6358           break;
6359
6360         case N_Identifier:
6361         case N_Expanded_Name:
6362           /* This represents either a subtype range, an enumeration
6363              literal, or a constant  Ekind says which.  If an enumeration
6364              literal or constant, fall through to the next case.  */
6365           if (Ekind (Entity (choice)) != E_Enumeration_Literal
6366               && Ekind (Entity (choice)) != E_Constant)
6367             {
6368               tree type = gnat_to_gnu_type (Entity (choice));
6369
6370               low = TYPE_MIN_VALUE (type);
6371               high = TYPE_MAX_VALUE (type);
6372
6373               this_test
6374                 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
6375                                    build_binary_op (GE_EXPR, boolean_type_node,
6376                                                     operand, low),
6377                                    build_binary_op (LE_EXPR, boolean_type_node,
6378                                                     operand, high));
6379               break;
6380             }
6381
6382           /* ... fall through ... */
6383
6384         case N_Character_Literal:
6385         case N_Integer_Literal:
6386           single = gnat_to_gnu (choice);
6387           this_test = build_binary_op (EQ_EXPR, boolean_type_node, operand,
6388                                        single);
6389           break;
6390
6391         case N_Others_Choice:
6392           this_test = boolean_true_node;
6393           break;
6394
6395         default:
6396           gcc_unreachable ();
6397         }
6398
6399       result = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, result,
6400                                 this_test);
6401     }
6402
6403   return result;
6404 }
6405 \f
6406 /* Adjust PACKED setting as passed to gnat_to_gnu_field for a field of
6407    type FIELD_TYPE to be placed in RECORD_TYPE.  Return the result.  */
6408
6409 static int
6410 adjust_packed (tree field_type, tree record_type, int packed)
6411 {
6412   /* If the field contains an item of variable size, we cannot pack it
6413      because we cannot create temporaries of non-fixed size in case
6414      we need to take the address of the field.  See addressable_p and
6415      the notes on the addressability issues for further details.  */
6416   if (type_has_variable_size (field_type))
6417     return 0;
6418
6419   /* If the alignment of the record is specified and the field type
6420      is over-aligned, request Storage_Unit alignment for the field.  */
6421   if (packed == -2)
6422     {
6423       if (TYPE_ALIGN (field_type) > TYPE_ALIGN (record_type))
6424         return -1;
6425       else
6426         return 0;
6427     }
6428
6429   return packed;
6430 }
6431
6432 /* Return a GCC tree for a field corresponding to GNAT_FIELD to be
6433    placed in GNU_RECORD_TYPE.
6434
6435    PACKED is 1 if the enclosing record is packed, -1 if the enclosing
6436    record has Component_Alignment of Storage_Unit, -2 if the enclosing
6437    record has a specified alignment.
6438
6439    DEFINITION is true if this field is for a record being defined.
6440
6441    DEBUG_INFO_P is true if we need to write debug information for types
6442    that we may create in the process.  */
6443
6444 static tree
6445 gnat_to_gnu_field (Entity_Id gnat_field, tree gnu_record_type, int packed,
6446                    bool definition, bool debug_info_p)
6447 {
6448   const Entity_Id gnat_field_type = Etype (gnat_field);
6449   const bool is_aliased
6450     = Is_Aliased (gnat_field);
6451   const bool is_atomic
6452     = (Is_Atomic_Or_VFA (gnat_field) || Is_Atomic_Or_VFA (gnat_field_type));
6453   const bool is_independent
6454     = (Is_Independent (gnat_field) || Is_Independent (gnat_field_type));
6455   const bool is_volatile
6456     = (Treat_As_Volatile (gnat_field) || Treat_As_Volatile (gnat_field_type));
6457   const bool needs_strict_alignment
6458     = (is_aliased
6459        || is_independent
6460        || is_volatile
6461        || Strict_Alignment (gnat_field_type));
6462   tree gnu_field_type = gnat_to_gnu_type (gnat_field_type);
6463   tree gnu_field_id = get_entity_name (gnat_field);
6464   tree gnu_field, gnu_size, gnu_pos;
6465
6466   /* If this field requires strict alignment, we cannot pack it because
6467      it would very likely be under-aligned in the record.  */
6468   if (needs_strict_alignment)
6469     packed = 0;
6470   else
6471     packed = adjust_packed (gnu_field_type, gnu_record_type, packed);
6472
6473   /* If a size is specified, use it.  Otherwise, if the record type is packed,
6474      use the official RM size.  See "Handling of Type'Size Values" in Einfo
6475      for further details.  */
6476   if (Known_Esize (gnat_field))
6477     gnu_size = validate_size (Esize (gnat_field), gnu_field_type,
6478                               gnat_field, FIELD_DECL, false, true);
6479   else if (packed == 1)
6480     gnu_size = validate_size (RM_Size (gnat_field_type), gnu_field_type,
6481                               gnat_field, FIELD_DECL, false, true);
6482   else
6483     gnu_size = NULL_TREE;
6484
6485   /* If we have a specified size that is smaller than that of the field's type,
6486      or a position is specified, and the field's type is a record that doesn't
6487      require strict alignment, see if we can get either an integral mode form
6488      of the type or a smaller form.  If we can, show a size was specified for
6489      the field if there wasn't one already, so we know to make this a bitfield
6490      and avoid making things wider.
6491
6492      Changing to an integral mode form is useful when the record is packed as
6493      we can then place the field at a non-byte-aligned position and so achieve
6494      tighter packing.  This is in addition required if the field shares a byte
6495      with another field and the front-end lets the back-end handle the access
6496      to the field, because GCC cannot handle non-byte-aligned BLKmode fields.
6497
6498      Changing to a smaller form is required if the specified size is smaller
6499      than that of the field's type and the type contains sub-fields that are
6500      padded, in order to avoid generating accesses to these sub-fields that
6501      are wider than the field.
6502
6503      We avoid the transformation if it is not required or potentially useful,
6504      as it might entail an increase of the field's alignment and have ripple
6505      effects on the outer record type.  A typical case is a field known to be
6506      byte-aligned and not to share a byte with another field.  */
6507   if (!needs_strict_alignment
6508       && RECORD_OR_UNION_TYPE_P (gnu_field_type)
6509       && !TYPE_FAT_POINTER_P (gnu_field_type)
6510       && tree_fits_uhwi_p (TYPE_SIZE (gnu_field_type))
6511       && (packed == 1
6512           || (gnu_size
6513               && (tree_int_cst_lt (gnu_size, TYPE_SIZE (gnu_field_type))
6514                   || (Present (Component_Clause (gnat_field))
6515                       && !(UI_To_Int (Component_Bit_Offset (gnat_field))
6516                            % BITS_PER_UNIT == 0
6517                            && value_factor_p (gnu_size, BITS_PER_UNIT)))))))
6518     {
6519       tree gnu_packable_type = make_packable_type (gnu_field_type, true);
6520       if (gnu_packable_type != gnu_field_type)
6521         {
6522           gnu_field_type = gnu_packable_type;
6523           if (!gnu_size)
6524             gnu_size = rm_size (gnu_field_type);
6525         }
6526     }
6527
6528   if (Is_Atomic_Or_VFA (gnat_field))
6529     check_ok_for_atomic_type (gnu_field_type, gnat_field, false);
6530
6531   if (Present (Component_Clause (gnat_field)))
6532     {
6533       Node_Id gnat_clause = Component_Clause (gnat_field);
6534       Entity_Id gnat_parent
6535         = Parent_Subtype (Underlying_Type (Scope (gnat_field)));
6536
6537       gnu_pos = UI_To_gnu (Component_Bit_Offset (gnat_field), bitsizetype);
6538       gnu_size = validate_size (Esize (gnat_field), gnu_field_type,
6539                                 gnat_field, FIELD_DECL, false, true);
6540
6541       /* Ensure the position does not overlap with the parent subtype, if there
6542          is one.  This test is omitted if the parent of the tagged type has a
6543          full rep clause since, in this case, component clauses are allowed to
6544          overlay the space allocated for the parent type and the front-end has
6545          checked that there are no overlapping components.  */
6546       if (Present (gnat_parent) && !Is_Fully_Repped_Tagged_Type (gnat_parent))
6547         {
6548           tree gnu_parent = gnat_to_gnu_type (gnat_parent);
6549
6550           if (TREE_CODE (TYPE_SIZE (gnu_parent)) == INTEGER_CST
6551               && tree_int_cst_lt (gnu_pos, TYPE_SIZE (gnu_parent)))
6552             post_error_ne_tree
6553               ("offset of& must be beyond parent{, minimum allowed is ^}",
6554                Position (gnat_clause), gnat_field, TYPE_SIZE_UNIT (gnu_parent));
6555         }
6556
6557       /* If this field needs strict alignment, make sure that the record is
6558          sufficiently aligned and that the position and size are consistent
6559          with the type.  But don't do it if we are just annotating types and
6560          the field's type is tagged, since tagged types aren't fully laid out
6561          in this mode.  Also, note that atomic implies volatile so the inner
6562          test sequences ordering is significant here.  */
6563       if (needs_strict_alignment
6564           && !(type_annotate_only && Is_Tagged_Type (gnat_field_type)))
6565         {
6566           const unsigned int type_align = TYPE_ALIGN (gnu_field_type);
6567
6568           if (TYPE_ALIGN (gnu_record_type) < type_align)
6569             TYPE_ALIGN (gnu_record_type) = type_align;
6570
6571           /* If the position is not a multiple of the alignment of the type,
6572              then error out and reset the position.  */
6573           if (!integer_zerop (size_binop (TRUNC_MOD_EXPR, gnu_pos,
6574                                           bitsize_int (type_align))))
6575             {
6576               const char *s;
6577
6578               if (is_atomic)
6579                 s = "position of atomic field& must be multiple of ^ bits";
6580               else if (is_aliased)
6581                 s = "position of aliased field& must be multiple of ^ bits";
6582               else if (is_independent)
6583                 s = "position of independent field& must be multiple of ^ bits";
6584               else if (is_volatile)
6585                 s = "position of volatile field& must be multiple of ^ bits";
6586               else if (Strict_Alignment (gnat_field_type))
6587                 s = "position of & with aliased or tagged part must be"
6588                     " multiple of ^ bits";
6589               else
6590                 gcc_unreachable ();
6591
6592               post_error_ne_num (s, First_Bit (gnat_clause), gnat_field,
6593                                  type_align);
6594               gnu_pos = NULL_TREE;
6595             }
6596
6597           if (gnu_size)
6598             {
6599               tree gnu_type_size = TYPE_SIZE (gnu_field_type);
6600               const int cmp = tree_int_cst_compare (gnu_size, gnu_type_size);
6601
6602               /* If the size is lower than that of the type, or greater for
6603                  atomic and aliased, then error out and reset the size.  */
6604               if (cmp < 0 || (cmp > 0 && (is_atomic || is_aliased)))
6605                 {
6606                   const char *s;
6607
6608                   if (is_atomic)
6609                     s = "size of atomic field& must be ^ bits";
6610                   else if (is_aliased)
6611                     s = "size of aliased field& must be ^ bits";
6612                   else if (is_independent)
6613                     s = "size of independent field& must be at least ^ bits";
6614                   else if (is_volatile)
6615                     s = "size of volatile field& must be at least ^ bits";
6616                   else if (Strict_Alignment (gnat_field_type))
6617                     s = "size of & with aliased or tagged part must be"
6618                         " at least ^ bits";
6619                   else
6620                     gcc_unreachable ();
6621
6622                   post_error_ne_tree (s, Last_Bit (gnat_clause), gnat_field,
6623                                       gnu_type_size);
6624                   gnu_size = NULL_TREE;
6625                 }
6626
6627               /* Likewise if the size is not a multiple of a byte,  */
6628               else if (!integer_zerop (size_binop (TRUNC_MOD_EXPR, gnu_size,
6629                                                    bitsize_unit_node)))
6630                 {
6631                   const char *s;
6632
6633                   if (is_independent)
6634                     s = "size of independent field& must be multiple of"
6635                         " Storage_Unit";
6636                   else if (is_volatile)
6637                     s = "size of volatile field& must be multiple of"
6638                         " Storage_Unit";
6639                   else if (Strict_Alignment (gnat_field_type))
6640                     s = "size of & with aliased or tagged part must be"
6641                         " multiple of Storage_Unit";
6642                   else
6643                     gcc_unreachable ();
6644
6645                   post_error_ne (s, Last_Bit (gnat_clause), gnat_field);
6646                   gnu_size = NULL_TREE;
6647                 }
6648             }
6649         }
6650     }
6651
6652   /* If the record has rep clauses and this is the tag field, make a rep
6653      clause for it as well.  */
6654   else if (Has_Specified_Layout (Scope (gnat_field))
6655            && Chars (gnat_field) == Name_uTag)
6656     {
6657       gnu_pos = bitsize_zero_node;
6658       gnu_size = TYPE_SIZE (gnu_field_type);
6659     }
6660
6661   else
6662     {
6663       gnu_pos = NULL_TREE;
6664
6665       /* If we are packing the record and the field is BLKmode, round the
6666          size up to a byte boundary.  */
6667       if (packed && TYPE_MODE (gnu_field_type) == BLKmode && gnu_size)
6668         gnu_size = round_up (gnu_size, BITS_PER_UNIT);
6669     }
6670
6671   /* We need to make the size the maximum for the type if it is
6672      self-referential and an unconstrained type.  In that case, we can't
6673      pack the field since we can't make a copy to align it.  */
6674   if (TREE_CODE (gnu_field_type) == RECORD_TYPE
6675       && !gnu_size
6676       && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_field_type))
6677       && !Is_Constrained (Underlying_Type (gnat_field_type)))
6678     {
6679       gnu_size = max_size (TYPE_SIZE (gnu_field_type), true);
6680       packed = 0;
6681     }
6682
6683   /* If a size is specified, adjust the field's type to it.  */
6684   if (gnu_size)
6685     {
6686       tree orig_field_type;
6687
6688       /* If the field's type is justified modular, we would need to remove
6689          the wrapper to (better) meet the layout requirements.  However we
6690          can do so only if the field is not aliased to preserve the unique
6691          layout and if the prescribed size is not greater than that of the
6692          packed array to preserve the justification.  */
6693       if (!needs_strict_alignment
6694           && TREE_CODE (gnu_field_type) == RECORD_TYPE
6695           && TYPE_JUSTIFIED_MODULAR_P (gnu_field_type)
6696           && tree_int_cst_compare (gnu_size, TYPE_ADA_SIZE (gnu_field_type))
6697                <= 0)
6698         gnu_field_type = TREE_TYPE (TYPE_FIELDS (gnu_field_type));
6699
6700       /* Similarly if the field's type is a misaligned integral type, but
6701          there is no restriction on the size as there is no justification.  */
6702       if (!needs_strict_alignment
6703           && TYPE_IS_PADDING_P (gnu_field_type)
6704           && INTEGRAL_TYPE_P (TREE_TYPE (TYPE_FIELDS (gnu_field_type))))
6705         gnu_field_type = TREE_TYPE (TYPE_FIELDS (gnu_field_type));
6706
6707       gnu_field_type
6708         = make_type_from_size (gnu_field_type, gnu_size,
6709                                Has_Biased_Representation (gnat_field));
6710
6711       orig_field_type = gnu_field_type;
6712       gnu_field_type = maybe_pad_type (gnu_field_type, gnu_size, 0, gnat_field,
6713                                        false, false, definition, true);
6714
6715       /* If a padding record was made, declare it now since it will never be
6716          declared otherwise.  This is necessary to ensure that its subtrees
6717          are properly marked.  */
6718       if (gnu_field_type != orig_field_type
6719           && !DECL_P (TYPE_NAME (gnu_field_type)))
6720         create_type_decl (TYPE_NAME (gnu_field_type), gnu_field_type, true,
6721                           debug_info_p, gnat_field);
6722     }
6723
6724   /* Otherwise (or if there was an error), don't specify a position.  */
6725   else
6726     gnu_pos = NULL_TREE;
6727
6728   gcc_assert (TREE_CODE (gnu_field_type) != RECORD_TYPE
6729               || !TYPE_CONTAINS_TEMPLATE_P (gnu_field_type));
6730
6731   /* Now create the decl for the field.  */
6732   gnu_field
6733     = create_field_decl (gnu_field_id, gnu_field_type, gnu_record_type,
6734                          gnu_size, gnu_pos, packed, Is_Aliased (gnat_field));
6735   Sloc_to_locus (Sloc (gnat_field), &DECL_SOURCE_LOCATION (gnu_field));
6736   DECL_ALIASED_P (gnu_field) = Is_Aliased (gnat_field);
6737   TREE_THIS_VOLATILE (gnu_field) = TREE_SIDE_EFFECTS (gnu_field) = is_volatile;
6738
6739   if (Ekind (gnat_field) == E_Discriminant)
6740     DECL_DISCRIMINANT_NUMBER (gnu_field)
6741       = UI_To_gnu (Discriminant_Number (gnat_field), sizetype);
6742
6743   return gnu_field;
6744 }
6745 \f
6746 /* Return true if at least one member of COMPONENT_LIST needs strict
6747    alignment.  */
6748
6749 static bool
6750 components_need_strict_alignment (Node_Id component_list)
6751 {
6752   Node_Id component_decl;
6753
6754   for (component_decl = First_Non_Pragma (Component_Items (component_list));
6755        Present (component_decl);
6756        component_decl = Next_Non_Pragma (component_decl))
6757     {
6758       Entity_Id gnat_field = Defining_Entity (component_decl);
6759
6760       if (Is_Aliased (gnat_field))
6761         return true;
6762
6763       if (Strict_Alignment (Etype (gnat_field)))
6764         return true;
6765     }
6766
6767   return false;
6768 }
6769
6770 /* Return true if TYPE is a type with variable size or a padding type with a
6771    field of variable size or a record that has a field with such a type.  */
6772
6773 static bool
6774 type_has_variable_size (tree type)
6775 {
6776   tree field;
6777
6778   if (!TREE_CONSTANT (TYPE_SIZE (type)))
6779     return true;
6780
6781   if (TYPE_IS_PADDING_P (type)
6782       && !TREE_CONSTANT (DECL_SIZE (TYPE_FIELDS (type))))
6783     return true;
6784
6785   if (!RECORD_OR_UNION_TYPE_P (type))
6786     return false;
6787
6788   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
6789     if (type_has_variable_size (TREE_TYPE (field)))
6790       return true;
6791
6792   return false;
6793 }
6794 \f
6795 /* Return true if FIELD is an artificial field.  */
6796
6797 static bool
6798 field_is_artificial (tree field)
6799 {
6800   /* These fields are generated by the front-end proper.  */
6801   if (IDENTIFIER_POINTER (DECL_NAME (field)) [0] == '_')
6802     return true;
6803
6804   /* These fields are generated by gigi.  */
6805   if (DECL_INTERNAL_P (field))
6806     return true;
6807
6808   return false;
6809 }
6810
6811 /* Return true if FIELD is a non-artificial aliased field.  */
6812
6813 static bool
6814 field_is_aliased (tree field)
6815 {
6816   if (field_is_artificial (field))
6817     return false;
6818
6819   return DECL_ALIASED_P (field);
6820 }
6821
6822 /* Return true if FIELD is a non-artificial field with self-referential
6823    size.  */
6824
6825 static bool
6826 field_has_self_size (tree field)
6827 {
6828   if (field_is_artificial (field))
6829     return false;
6830
6831   if (DECL_SIZE (field) && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
6832     return false;
6833
6834   return CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (field)));
6835 }
6836
6837 /* Return true if FIELD is a non-artificial field with variable size.  */
6838
6839 static bool
6840 field_has_variable_size (tree field)
6841 {
6842   if (field_is_artificial (field))
6843     return false;
6844
6845   if (DECL_SIZE (field) && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST)
6846     return false;
6847
6848   return TREE_CODE (TYPE_SIZE (TREE_TYPE (field))) != INTEGER_CST;
6849 }
6850
6851 /* qsort comparer for the bit positions of two record components.  */
6852
6853 static int
6854 compare_field_bitpos (const PTR rt1, const PTR rt2)
6855 {
6856   const_tree const field1 = * (const_tree const *) rt1;
6857   const_tree const field2 = * (const_tree const *) rt2;
6858   const int ret
6859     = tree_int_cst_compare (bit_position (field1), bit_position (field2));
6860
6861   return ret ? ret : (int) (DECL_UID (field1) - DECL_UID (field2));
6862 }
6863
6864 /* Structure holding information for a given variant.  */
6865 typedef struct vinfo
6866 {
6867   /* The record type of the variant.  */
6868   tree type;
6869
6870   /* The name of the variant.  */
6871   tree name;
6872
6873   /* The qualifier of the variant.  */
6874   tree qual;
6875
6876   /* Whether the variant has a rep clause.  */
6877   bool has_rep;
6878
6879   /* Whether the variant is packed.  */
6880   bool packed;
6881
6882 } vinfo_t;
6883
6884 /* Translate and chain the GNAT_COMPONENT_LIST to the GNU_FIELD_LIST, set the
6885    result as the field list of GNU_RECORD_TYPE and finish it up.  Return true
6886    if GNU_RECORD_TYPE has a rep clause which affects the layout (see below).
6887    When called from gnat_to_gnu_entity during the processing of a record type
6888    definition, the GCC node for the parent, if any, will be the single field
6889    of GNU_RECORD_TYPE and the GCC nodes for the discriminants will be on the
6890    GNU_FIELD_LIST.  The other calls to this function are recursive calls for
6891    the component list of a variant and, in this case, GNU_FIELD_LIST is empty.
6892
6893    PACKED is 1 if this is for a packed record, -1 if this is for a record
6894    with Component_Alignment of Storage_Unit, -2 if this is for a record
6895    with a specified alignment.
6896
6897    DEFINITION is true if we are defining this record type.
6898
6899    CANCEL_ALIGNMENT is true if the alignment should be zeroed before laying
6900    out the record.  This means the alignment only serves to force fields to
6901    be bitfields, but not to require the record to be that aligned.  This is
6902    used for variants.
6903
6904    ALL_REP is true if a rep clause is present for all the fields.
6905
6906    UNCHECKED_UNION is true if we are building this type for a record with a
6907    Pragma Unchecked_Union.
6908
6909    ARTIFICIAL is true if this is a type that was generated by the compiler.
6910
6911    DEBUG_INFO is true if we need to write debug information about the type.
6912
6913    MAYBE_UNUSED is true if this type may be unused in the end; this doesn't
6914    mean that its contents may be unused as well, only the container itself.
6915
6916    REORDER is true if we are permitted to reorder components of this type.
6917
6918    FIRST_FREE_POS, if nonzero, is the first (lowest) free field position in
6919    the outer record type down to this variant level.  It is nonzero only if
6920    all the fields down to this level have a rep clause and ALL_REP is false.
6921
6922    P_GNU_REP_LIST, if nonzero, is a pointer to a list to which each field
6923    with a rep clause is to be added; in this case, that is all that should
6924    be done with such fields and the return value will be false.  */
6925
6926 static bool
6927 components_to_record (tree gnu_record_type, Node_Id gnat_component_list,
6928                       tree gnu_field_list, int packed, bool definition,
6929                       bool cancel_alignment, bool all_rep,
6930                       bool unchecked_union, bool artificial,
6931                       bool debug_info, bool maybe_unused, bool reorder,
6932                       tree first_free_pos, tree *p_gnu_rep_list)
6933 {
6934   bool all_rep_and_size = all_rep && TYPE_SIZE (gnu_record_type);
6935   bool variants_have_rep = all_rep;
6936   bool layout_with_rep = false;
6937   bool has_self_field = false;
6938   bool has_aliased_after_self_field = false;
6939   Node_Id component_decl, variant_part;
6940   tree gnu_field, gnu_next, gnu_last;
6941   tree gnu_variant_part = NULL_TREE;
6942   tree gnu_rep_list = NULL_TREE;
6943   tree gnu_var_list = NULL_TREE;
6944   tree gnu_self_list = NULL_TREE;
6945   tree gnu_zero_list = NULL_TREE;
6946
6947   /* For each component referenced in a component declaration create a GCC
6948      field and add it to the list, skipping pragmas in the GNAT list.  */
6949   gnu_last = tree_last (gnu_field_list);
6950   if (Present (Component_Items (gnat_component_list)))
6951     for (component_decl
6952            = First_Non_Pragma (Component_Items (gnat_component_list));
6953          Present (component_decl);
6954          component_decl = Next_Non_Pragma (component_decl))
6955       {
6956         Entity_Id gnat_field = Defining_Entity (component_decl);
6957         Name_Id gnat_name = Chars (gnat_field);
6958
6959         /* If present, the _Parent field must have been created as the single
6960            field of the record type.  Put it before any other fields.  */
6961         if (gnat_name == Name_uParent)
6962           {
6963             gnu_field = TYPE_FIELDS (gnu_record_type);
6964             gnu_field_list = chainon (gnu_field_list, gnu_field);
6965           }
6966         else
6967           {
6968             gnu_field = gnat_to_gnu_field (gnat_field, gnu_record_type, packed,
6969                                            definition, debug_info);
6970
6971             /* If this is the _Tag field, put it before any other fields.  */
6972             if (gnat_name == Name_uTag)
6973               gnu_field_list = chainon (gnu_field_list, gnu_field);
6974
6975             /* If this is the _Controller field, put it before the other
6976                fields except for the _Tag or _Parent field.  */
6977             else if (gnat_name == Name_uController && gnu_last)
6978               {
6979                 DECL_CHAIN (gnu_field) = DECL_CHAIN (gnu_last);
6980                 DECL_CHAIN (gnu_last) = gnu_field;
6981               }
6982
6983             /* If this is a regular field, put it after the other fields.  */
6984             else
6985               {
6986                 DECL_CHAIN (gnu_field) = gnu_field_list;
6987                 gnu_field_list = gnu_field;
6988                 if (!gnu_last)
6989                   gnu_last = gnu_field;
6990
6991                 /* And record information for the final layout.  */
6992                 if (field_has_self_size (gnu_field))
6993                   has_self_field = true;
6994                 else if (has_self_field && field_is_aliased (gnu_field))
6995                   has_aliased_after_self_field = true;
6996               }
6997           }
6998
6999         save_gnu_tree (gnat_field, gnu_field, false);
7000       }
7001
7002   /* At the end of the component list there may be a variant part.  */
7003   variant_part = Variant_Part (gnat_component_list);
7004
7005   /* We create a QUAL_UNION_TYPE for the variant part since the variants are
7006      mutually exclusive and should go in the same memory.  To do this we need
7007      to treat each variant as a record whose elements are created from the
7008      component list for the variant.  So here we create the records from the
7009      lists for the variants and put them all into the QUAL_UNION_TYPE.
7010      If this is an Unchecked_Union, we make a UNION_TYPE instead or
7011      use GNU_RECORD_TYPE if there are no fields so far.  */
7012   if (Present (variant_part))
7013     {
7014       Node_Id gnat_discr = Name (variant_part), variant;
7015       tree gnu_discr = gnat_to_gnu (gnat_discr);
7016       tree gnu_name = TYPE_IDENTIFIER (gnu_record_type);
7017       tree gnu_var_name
7018         = concat_name (get_identifier (Get_Name_String (Chars (gnat_discr))),
7019                        "XVN");
7020       tree gnu_union_type, gnu_union_name;
7021       tree this_first_free_pos, gnu_variant_list = NULL_TREE;
7022       bool union_field_needs_strict_alignment = false;
7023       auto_vec <vinfo_t, 16> variant_types;
7024       vinfo_t *gnu_variant;
7025       unsigned int variants_align = 0;
7026       unsigned int i;
7027
7028       gnu_union_name
7029         = concat_name (gnu_name, IDENTIFIER_POINTER (gnu_var_name));
7030
7031       /* Reuse the enclosing union if this is an Unchecked_Union whose fields
7032          are all in the variant part, to match the layout of C unions.  There
7033          is an associated check below.  */
7034       if (TREE_CODE (gnu_record_type) == UNION_TYPE)
7035         gnu_union_type = gnu_record_type;
7036       else
7037         {
7038           gnu_union_type
7039             = make_node (unchecked_union ? UNION_TYPE : QUAL_UNION_TYPE);
7040
7041           TYPE_NAME (gnu_union_type) = gnu_union_name;
7042           TYPE_ALIGN (gnu_union_type) = 0;
7043           TYPE_PACKED (gnu_union_type) = TYPE_PACKED (gnu_record_type);
7044         }
7045
7046       /* If all the fields down to this level have a rep clause, find out
7047          whether all the fields at this level also have one.  If so, then
7048          compute the new first free position to be passed downward.  */
7049       this_first_free_pos = first_free_pos;
7050       if (this_first_free_pos)
7051         {
7052           for (gnu_field = gnu_field_list;
7053                gnu_field;
7054                gnu_field = DECL_CHAIN (gnu_field))
7055             if (DECL_FIELD_OFFSET (gnu_field))
7056               {
7057                 tree pos = bit_position (gnu_field);
7058                 if (!tree_int_cst_lt (pos, this_first_free_pos))
7059                   this_first_free_pos
7060                     = size_binop (PLUS_EXPR, pos, DECL_SIZE (gnu_field));
7061               }
7062             else
7063               {
7064                 this_first_free_pos = NULL_TREE;
7065                 break;
7066               }
7067         }
7068
7069       /* We build the variants in two passes.  The bulk of the work is done in
7070          the first pass, that is to say translating the GNAT nodes, building
7071          the container types and computing the associated properties.  However
7072          we cannot finish up the container types during this pass because we
7073          don't know where the variant part will be placed until the end.  */
7074       for (variant = First_Non_Pragma (Variants (variant_part));
7075            Present (variant);
7076            variant = Next_Non_Pragma (variant))
7077         {
7078           tree gnu_variant_type = make_node (RECORD_TYPE);
7079           tree gnu_inner_name, gnu_qual;
7080           bool has_rep;
7081           int field_packed;
7082           vinfo_t vinfo;
7083
7084           Get_Variant_Encoding (variant);
7085           gnu_inner_name = get_identifier_with_length (Name_Buffer, Name_Len);
7086           TYPE_NAME (gnu_variant_type)
7087             = concat_name (gnu_union_name,
7088                            IDENTIFIER_POINTER (gnu_inner_name));
7089
7090           /* Set the alignment of the inner type in case we need to make
7091              inner objects into bitfields, but then clear it out so the
7092              record actually gets only the alignment required.  */
7093           TYPE_ALIGN (gnu_variant_type) = TYPE_ALIGN (gnu_record_type);
7094           TYPE_PACKED (gnu_variant_type) = TYPE_PACKED (gnu_record_type);
7095
7096           /* Similarly, if the outer record has a size specified and all
7097              the fields have a rep clause, we can propagate the size.  */
7098           if (all_rep_and_size)
7099             {
7100               TYPE_SIZE (gnu_variant_type) = TYPE_SIZE (gnu_record_type);
7101               TYPE_SIZE_UNIT (gnu_variant_type)
7102                 = TYPE_SIZE_UNIT (gnu_record_type);
7103             }
7104
7105           /* Add the fields into the record type for the variant.  Note that
7106              we aren't sure to really use it at this point, see below.  */
7107           has_rep
7108             = components_to_record (gnu_variant_type, Component_List (variant),
7109                                     NULL_TREE, packed, definition,
7110                                     !all_rep_and_size, all_rep,
7111                                     unchecked_union,
7112                                     true, debug_info, true, reorder,
7113                                     this_first_free_pos,
7114                                     all_rep || this_first_free_pos
7115                                     ? NULL : &gnu_rep_list);
7116
7117           /* Translate the qualifier and annotate the GNAT node.  */
7118           gnu_qual = choices_to_gnu (gnu_discr, Discrete_Choices (variant));
7119           Set_Present_Expr (variant, annotate_value (gnu_qual));
7120
7121           /* Deal with packedness like in gnat_to_gnu_field.  */
7122           if (components_need_strict_alignment (Component_List (variant)))
7123             {
7124               field_packed = 0;
7125               union_field_needs_strict_alignment = true;
7126             }
7127           else
7128             field_packed
7129               = adjust_packed (gnu_variant_type, gnu_record_type, packed);
7130
7131           /* Push this variant onto the stack for the second pass.  */
7132           vinfo.type = gnu_variant_type;
7133           vinfo.name = gnu_inner_name;
7134           vinfo.qual = gnu_qual;
7135           vinfo.has_rep = has_rep;
7136           vinfo.packed = field_packed;
7137           variant_types.safe_push (vinfo);
7138
7139           /* Compute the global properties that will determine the placement of
7140              the variant part.  */
7141           variants_have_rep |= has_rep;
7142           if (!field_packed && TYPE_ALIGN (gnu_variant_type) > variants_align)
7143             variants_align = TYPE_ALIGN (gnu_variant_type);
7144         }
7145
7146       /* Round up the first free position to the alignment of the variant part
7147          for the variants without rep clause.  This will guarantee a consistent
7148          layout independently of the placement of the variant part.  */
7149       if (variants_have_rep && variants_align > 0 && this_first_free_pos)
7150         this_first_free_pos = round_up (this_first_free_pos, variants_align);
7151
7152       /* In the second pass, the container types are adjusted if necessary and
7153          finished up, then the corresponding fields of the variant part are
7154          built with their qualifier, unless this is an unchecked union.  */
7155       FOR_EACH_VEC_ELT (variant_types, i, gnu_variant)
7156         {
7157           tree gnu_variant_type = gnu_variant->type;
7158           tree gnu_field_list = TYPE_FIELDS (gnu_variant_type);
7159
7160           /* If this is an Unchecked_Union whose fields are all in the variant
7161              part and we have a single field with no representation clause or
7162              placed at offset zero, use the field directly to match the layout
7163              of C unions.  */
7164           if (TREE_CODE (gnu_record_type) == UNION_TYPE
7165               && gnu_field_list
7166               && !DECL_CHAIN (gnu_field_list)
7167               && (!DECL_FIELD_OFFSET (gnu_field_list)
7168                   || integer_zerop (bit_position (gnu_field_list))))
7169             {
7170               gnu_field = gnu_field_list;
7171               DECL_CONTEXT (gnu_field) = gnu_record_type;
7172             }
7173           else
7174             {
7175               /* Finalize the variant type now.  We used to throw away empty
7176                  record types but we no longer do that because we need them to
7177                  generate complete debug info for the variant; otherwise, the
7178                  union type definition will be lacking the fields associated
7179                  with these empty variants.  */
7180               if (gnu_field_list && variants_have_rep && !gnu_variant->has_rep)
7181                 {
7182                   /* The variant part will be at offset 0 so we need to ensure
7183                      that the fields are laid out starting from the first free
7184                      position at this level.  */
7185                   tree gnu_rep_type = make_node (RECORD_TYPE);
7186                   tree gnu_rep_part;
7187                   finish_record_type (gnu_rep_type, NULL_TREE, 0, debug_info);
7188                   gnu_rep_part
7189                     = create_rep_part (gnu_rep_type, gnu_variant_type,
7190                                        this_first_free_pos);
7191                   DECL_CHAIN (gnu_rep_part) = gnu_field_list;
7192                   gnu_field_list = gnu_rep_part;
7193                   finish_record_type (gnu_variant_type, gnu_field_list, 0,
7194                                       false);
7195                 }
7196
7197               if (debug_info)
7198                 rest_of_record_type_compilation (gnu_variant_type);
7199               create_type_decl (TYPE_NAME (gnu_variant_type), gnu_variant_type,
7200                                 true, debug_info, gnat_component_list);
7201
7202               gnu_field
7203                 = create_field_decl (gnu_variant->name, gnu_variant_type,
7204                                      gnu_union_type,
7205                                      all_rep_and_size
7206                                      ? TYPE_SIZE (gnu_variant_type) : 0,
7207                                      variants_have_rep ? bitsize_zero_node : 0,
7208                                      gnu_variant->packed, 0);
7209
7210               DECL_INTERNAL_P (gnu_field) = 1;
7211
7212               if (!unchecked_union)
7213                 DECL_QUALIFIER (gnu_field) = gnu_variant->qual;
7214             }
7215
7216           DECL_CHAIN (gnu_field) = gnu_variant_list;
7217           gnu_variant_list = gnu_field;
7218         }
7219
7220       /* Only make the QUAL_UNION_TYPE if there are non-empty variants.  */
7221       if (gnu_variant_list)
7222         {
7223           int union_field_packed;
7224
7225           if (all_rep_and_size)
7226             {
7227               TYPE_SIZE (gnu_union_type) = TYPE_SIZE (gnu_record_type);
7228               TYPE_SIZE_UNIT (gnu_union_type)
7229                 = TYPE_SIZE_UNIT (gnu_record_type);
7230             }
7231
7232           finish_record_type (gnu_union_type, nreverse (gnu_variant_list),
7233                               all_rep_and_size ? 1 : 0, debug_info);
7234
7235           /* If GNU_UNION_TYPE is our record type, it means we must have an
7236              Unchecked_Union with no fields.  Verify that and, if so, just
7237              return.  */
7238           if (gnu_union_type == gnu_record_type)
7239             {
7240               gcc_assert (unchecked_union
7241                           && !gnu_field_list
7242                           && !gnu_rep_list);
7243               return variants_have_rep;
7244             }
7245
7246           create_type_decl (TYPE_NAME (gnu_union_type), gnu_union_type, true,
7247                             debug_info, gnat_component_list);
7248
7249           /* Deal with packedness like in gnat_to_gnu_field.  */
7250           if (union_field_needs_strict_alignment)
7251             union_field_packed = 0;
7252           else
7253             union_field_packed
7254               = adjust_packed (gnu_union_type, gnu_record_type, packed);
7255
7256           gnu_variant_part
7257             = create_field_decl (gnu_var_name, gnu_union_type, gnu_record_type,
7258                                  all_rep_and_size
7259                                  ? TYPE_SIZE (gnu_union_type) : 0,
7260                                  variants_have_rep ? bitsize_zero_node : 0,
7261                                  union_field_packed, 0);
7262
7263           DECL_INTERNAL_P (gnu_variant_part) = 1;
7264         }
7265     }
7266
7267   /* Scan GNU_FIELD_LIST and see if any fields have rep clauses and, if we are
7268      permitted to reorder components, self-referential sizes or variable sizes.
7269      If they do, pull them out and put them onto the appropriate list.  We have
7270      to do this in a separate pass since we want to handle the discriminants
7271      but can't play with them until we've used them in debugging data above.
7272
7273      Similarly, pull out the fields with zero size and no rep clause, as they
7274      would otherwise modify the layout and thus very likely run afoul of the
7275      Ada semantics, which are different from those of C here.
7276
7277      ??? If we reorder them, debugging information will be wrong but there is
7278      nothing that can be done about this at the moment.  */
7279   gnu_last = NULL_TREE;
7280
7281 #define MOVE_FROM_FIELD_LIST_TO(LIST)   \
7282   do {                                  \
7283     if (gnu_last)                       \
7284       DECL_CHAIN (gnu_last) = gnu_next; \
7285     else                                \
7286       gnu_field_list = gnu_next;        \
7287                                         \
7288     DECL_CHAIN (gnu_field) = (LIST);    \
7289     (LIST) = gnu_field;                 \
7290   } while (0)
7291
7292   for (gnu_field = gnu_field_list; gnu_field; gnu_field = gnu_next)
7293     {
7294       gnu_next = DECL_CHAIN (gnu_field);
7295
7296       if (DECL_FIELD_OFFSET (gnu_field))
7297         {
7298           MOVE_FROM_FIELD_LIST_TO (gnu_rep_list);
7299           continue;
7300         }
7301
7302       if ((reorder || has_aliased_after_self_field)
7303           && field_has_self_size (gnu_field))
7304         {
7305           MOVE_FROM_FIELD_LIST_TO (gnu_self_list);
7306           continue;
7307         }
7308
7309       if (reorder && field_has_variable_size (gnu_field))
7310         {
7311           MOVE_FROM_FIELD_LIST_TO (gnu_var_list);
7312           continue;
7313         }
7314
7315       if (DECL_SIZE (gnu_field) && integer_zerop (DECL_SIZE (gnu_field)))
7316         {
7317           DECL_FIELD_OFFSET (gnu_field) = size_zero_node;
7318           SET_DECL_OFFSET_ALIGN (gnu_field, BIGGEST_ALIGNMENT);
7319           DECL_FIELD_BIT_OFFSET (gnu_field) = bitsize_zero_node;
7320           if (field_is_aliased (gnu_field))
7321             TYPE_ALIGN (gnu_record_type)
7322               = MAX (TYPE_ALIGN (gnu_record_type),
7323                      TYPE_ALIGN (TREE_TYPE (gnu_field)));
7324           MOVE_FROM_FIELD_LIST_TO (gnu_zero_list);
7325           continue;
7326         }
7327
7328       gnu_last = gnu_field;
7329     }
7330
7331 #undef MOVE_FROM_FIELD_LIST_TO
7332
7333   gnu_field_list = nreverse (gnu_field_list);
7334
7335   /* If permitted, we reorder the fields as follows:
7336
7337        1) all fixed length fields,
7338        2) all fields whose length doesn't depend on discriminants,
7339        3) all fields whose length depends on discriminants,
7340        4) the variant part,
7341
7342      within the record and within each variant recursively.  */
7343   if (reorder)
7344     gnu_field_list
7345       = chainon (gnu_field_list, chainon (gnu_var_list, gnu_self_list));
7346
7347   /* Otherwise, if there is an aliased field placed after a field whose length
7348      depends on discriminants, we put all the fields of the latter sort, last.
7349      We need to do this in case an object of this record type is mutable.  */
7350   else if (has_aliased_after_self_field)
7351     gnu_field_list = chainon (gnu_field_list, gnu_self_list);
7352
7353   /* If P_REP_LIST is nonzero, this means that we are asked to move the fields
7354      in our REP list to the previous level because this level needs them in
7355      order to do a correct layout, i.e. avoid having overlapping fields.  */
7356   if (p_gnu_rep_list && gnu_rep_list)
7357     *p_gnu_rep_list = chainon (*p_gnu_rep_list, gnu_rep_list);
7358
7359   /* Otherwise, sort the fields by bit position and put them into their own
7360      record, before the others, if we also have fields without rep clause.  */
7361   else if (gnu_rep_list)
7362     {
7363       tree gnu_rep_type, gnu_rep_part;
7364       int i, len = list_length (gnu_rep_list);
7365       tree *gnu_arr = XALLOCAVEC (tree, len);
7366
7367       /* If all the fields have a rep clause, we can do a flat layout.  */
7368       layout_with_rep = !gnu_field_list
7369                         && (!gnu_variant_part || variants_have_rep);
7370       gnu_rep_type
7371         = layout_with_rep ? gnu_record_type : make_node (RECORD_TYPE);
7372
7373       for (gnu_field = gnu_rep_list, i = 0;
7374            gnu_field;
7375            gnu_field = DECL_CHAIN (gnu_field), i++)
7376         gnu_arr[i] = gnu_field;
7377
7378       qsort (gnu_arr, len, sizeof (tree), compare_field_bitpos);
7379
7380       /* Put the fields in the list in order of increasing position, which
7381          means we start from the end.  */
7382       gnu_rep_list = NULL_TREE;
7383       for (i = len - 1; i >= 0; i--)
7384         {
7385           DECL_CHAIN (gnu_arr[i]) = gnu_rep_list;
7386           gnu_rep_list = gnu_arr[i];
7387           DECL_CONTEXT (gnu_arr[i]) = gnu_rep_type;
7388         }
7389
7390       if (layout_with_rep)
7391         gnu_field_list = gnu_rep_list;
7392       else
7393         {
7394           finish_record_type (gnu_rep_type, gnu_rep_list, 1, debug_info);
7395
7396           /* If FIRST_FREE_POS is nonzero, we need to ensure that the fields
7397              without rep clause are laid out starting from this position.
7398              Therefore, we force it as a minimal size on the REP part.  */
7399           gnu_rep_part
7400             = create_rep_part (gnu_rep_type, gnu_record_type, first_free_pos);
7401
7402           /* Chain the REP part at the beginning of the field list.  */
7403           DECL_CHAIN (gnu_rep_part) = gnu_field_list;
7404           gnu_field_list = gnu_rep_part;
7405         }
7406     }
7407
7408   /* Chain the variant part at the end of the field list.  */
7409   if (gnu_variant_part)
7410     gnu_field_list = chainon (gnu_field_list, gnu_variant_part);
7411
7412   if (cancel_alignment)
7413     TYPE_ALIGN (gnu_record_type) = 0;
7414
7415   TYPE_ARTIFICIAL (gnu_record_type) = artificial;
7416
7417   finish_record_type (gnu_record_type, gnu_field_list, layout_with_rep ? 1 : 0,
7418                       debug_info && !maybe_unused);
7419
7420   /* Chain the fields with zero size at the beginning of the field list.  */
7421   if (gnu_zero_list)
7422     TYPE_FIELDS (gnu_record_type)
7423       = chainon (gnu_zero_list, TYPE_FIELDS (gnu_record_type));
7424
7425   return (gnu_rep_list && !p_gnu_rep_list) || variants_have_rep;
7426 }
7427 \f
7428 /* Given GNU_SIZE, a GCC tree representing a size, return a Uint to be
7429    placed into an Esize, Component_Bit_Offset, or Component_Size value
7430    in the GNAT tree.  */
7431
7432 static Uint
7433 annotate_value (tree gnu_size)
7434 {
7435   TCode tcode;
7436   Node_Ref_Or_Val ops[3], ret, pre_op1 = No_Uint;
7437   struct tree_int_map in;
7438   int i;
7439
7440   /* See if we've already saved the value for this node.  */
7441   if (EXPR_P (gnu_size))
7442     {
7443       struct tree_int_map *e;
7444
7445       in.base.from = gnu_size;
7446       e = annotate_value_cache->find (&in);
7447
7448       if (e)
7449         return (Node_Ref_Or_Val) e->to;
7450     }
7451   else
7452     in.base.from = NULL_TREE;
7453
7454   /* If we do not return inside this switch, TCODE will be set to the
7455      code to use for a Create_Node operand and LEN (set above) will be
7456      the number of recursive calls for us to make.  */
7457
7458   switch (TREE_CODE (gnu_size))
7459     {
7460     case INTEGER_CST:
7461       return TREE_OVERFLOW (gnu_size) ? No_Uint : UI_From_gnu (gnu_size);
7462
7463     case COMPONENT_REF:
7464       /* The only case we handle here is a simple discriminant reference.  */
7465       if (DECL_DISCRIMINANT_NUMBER (TREE_OPERAND (gnu_size, 1)))
7466         {
7467           tree n = DECL_DISCRIMINANT_NUMBER (TREE_OPERAND (gnu_size, 1));
7468
7469           /* Climb up the chain of successive extensions, if any.  */
7470           while (TREE_CODE (TREE_OPERAND (gnu_size, 0)) == COMPONENT_REF
7471                  && DECL_NAME (TREE_OPERAND (TREE_OPERAND (gnu_size, 0), 1))
7472                     == parent_name_id)
7473             gnu_size = TREE_OPERAND (gnu_size, 0);
7474
7475           if (TREE_CODE (TREE_OPERAND (gnu_size, 0)) == PLACEHOLDER_EXPR)
7476             return
7477               Create_Node (Discrim_Val, annotate_value (n), No_Uint, No_Uint);
7478         }
7479
7480       return No_Uint;
7481
7482     CASE_CONVERT:   case NON_LVALUE_EXPR:
7483       return annotate_value (TREE_OPERAND (gnu_size, 0));
7484
7485       /* Now just list the operations we handle.  */
7486     case COND_EXPR:             tcode = Cond_Expr; break;
7487     case PLUS_EXPR:             tcode = Plus_Expr; break;
7488     case MINUS_EXPR:            tcode = Minus_Expr; break;
7489     case MULT_EXPR:             tcode = Mult_Expr; break;
7490     case TRUNC_DIV_EXPR:        tcode = Trunc_Div_Expr; break;
7491     case CEIL_DIV_EXPR:         tcode = Ceil_Div_Expr; break;
7492     case FLOOR_DIV_EXPR:        tcode = Floor_Div_Expr; break;
7493     case TRUNC_MOD_EXPR:        tcode = Trunc_Mod_Expr; break;
7494     case CEIL_MOD_EXPR:         tcode = Ceil_Mod_Expr; break;
7495     case FLOOR_MOD_EXPR:        tcode = Floor_Mod_Expr; break;
7496     case EXACT_DIV_EXPR:        tcode = Exact_Div_Expr; break;
7497     case NEGATE_EXPR:           tcode = Negate_Expr; break;
7498     case MIN_EXPR:              tcode = Min_Expr; break;
7499     case MAX_EXPR:              tcode = Max_Expr; break;
7500     case ABS_EXPR:              tcode = Abs_Expr; break;
7501     case TRUTH_ANDIF_EXPR:      tcode = Truth_Andif_Expr; break;
7502     case TRUTH_ORIF_EXPR:       tcode = Truth_Orif_Expr; break;
7503     case TRUTH_AND_EXPR:        tcode = Truth_And_Expr; break;
7504     case TRUTH_OR_EXPR:         tcode = Truth_Or_Expr; break;
7505     case TRUTH_XOR_EXPR:        tcode = Truth_Xor_Expr; break;
7506     case TRUTH_NOT_EXPR:        tcode = Truth_Not_Expr; break;
7507     case LT_EXPR:               tcode = Lt_Expr; break;
7508     case LE_EXPR:               tcode = Le_Expr; break;
7509     case GT_EXPR:               tcode = Gt_Expr; break;
7510     case GE_EXPR:               tcode = Ge_Expr; break;
7511     case EQ_EXPR:               tcode = Eq_Expr; break;
7512     case NE_EXPR:               tcode = Ne_Expr; break;
7513
7514     case BIT_AND_EXPR:
7515       tcode = Bit_And_Expr;
7516       /* For negative values in sizetype, build NEGATE_EXPR of the opposite.
7517          Such values appear in expressions with aligning patterns.  Note that,
7518          since sizetype is unsigned, we have to jump through some hoops.   */
7519       if (TREE_CODE (TREE_OPERAND (gnu_size, 1)) == INTEGER_CST)
7520         {
7521           tree op1 = TREE_OPERAND (gnu_size, 1);
7522           wide_int signed_op1 = wi::sext (op1, TYPE_PRECISION (sizetype));
7523           if (wi::neg_p (signed_op1))
7524             {
7525               op1 = wide_int_to_tree (sizetype, wi::neg (signed_op1));
7526               pre_op1 = annotate_value (build1 (NEGATE_EXPR, sizetype, op1));
7527             }
7528         }
7529       break;
7530
7531     case CALL_EXPR:
7532       /* In regular mode, inline back only if symbolic annotation is requested
7533          in order to avoid memory explosion on big discriminated record types.
7534          But not in ASIS mode, as symbolic annotation is required for DDA.  */
7535       if (List_Representation_Info == 3 || type_annotate_only)
7536         {
7537           tree t = maybe_inline_call_in_expr (gnu_size);
7538           if (t)
7539             return annotate_value (t);
7540         }
7541       else
7542         return Uint_Minus_1;
7543
7544       /* Fall through... */
7545
7546     default:
7547       return No_Uint;
7548     }
7549
7550   /* Now get each of the operands that's relevant for this code.  If any
7551      cannot be expressed as a repinfo node, say we can't.  */
7552   for (i = 0; i < 3; i++)
7553     ops[i] = No_Uint;
7554
7555   for (i = 0; i < TREE_CODE_LENGTH (TREE_CODE (gnu_size)); i++)
7556     {
7557       if (i == 1 && pre_op1 != No_Uint)
7558         ops[i] = pre_op1;
7559       else
7560         ops[i] = annotate_value (TREE_OPERAND (gnu_size, i));
7561       if (ops[i] == No_Uint)
7562         return No_Uint;
7563     }
7564
7565   ret = Create_Node (tcode, ops[0], ops[1], ops[2]);
7566
7567   /* Save the result in the cache.  */
7568   if (in.base.from)
7569     {
7570       struct tree_int_map **h;
7571       /* We can't assume the hash table data hasn't moved since the initial
7572          look up, so we have to search again.  Allocating and inserting an
7573          entry at that point would be an alternative, but then we'd better
7574          discard the entry if we decided not to cache it.  */
7575       h = annotate_value_cache->find_slot (&in, INSERT);
7576       gcc_assert (!*h);
7577       *h = ggc_alloc<tree_int_map> ();
7578       (*h)->base.from = gnu_size;
7579       (*h)->to = ret;
7580     }
7581
7582   return ret;
7583 }
7584
7585 /* Given GNAT_ENTITY, an object (constant, variable, parameter, exception)
7586    and GNU_TYPE, its corresponding GCC type, set Esize and Alignment to the
7587    size and alignment used by Gigi.  Prefer SIZE over TYPE_SIZE if non-null.
7588    BY_REF is true if the object is used by reference.  */
7589
7590 void
7591 annotate_object (Entity_Id gnat_entity, tree gnu_type, tree size, bool by_ref)
7592 {
7593   if (by_ref)
7594     {
7595       if (TYPE_IS_FAT_POINTER_P (gnu_type))
7596         gnu_type = TYPE_UNCONSTRAINED_ARRAY (gnu_type);
7597       else
7598         gnu_type = TREE_TYPE (gnu_type);
7599     }
7600
7601   if (Unknown_Esize (gnat_entity))
7602     {
7603       if (TREE_CODE (gnu_type) == RECORD_TYPE
7604           && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
7605         size = TYPE_SIZE (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type))));
7606       else if (!size)
7607         size = TYPE_SIZE (gnu_type);
7608
7609       if (size)
7610         Set_Esize (gnat_entity, annotate_value (size));
7611     }
7612
7613   if (Unknown_Alignment (gnat_entity))
7614     Set_Alignment (gnat_entity,
7615                    UI_From_Int (TYPE_ALIGN (gnu_type) / BITS_PER_UNIT));
7616 }
7617
7618 /* Return first element of field list whose TREE_PURPOSE is the same as ELEM.
7619    Return NULL_TREE if there is no such element in the list.  */
7620
7621 static tree
7622 purpose_member_field (const_tree elem, tree list)
7623 {
7624   while (list)
7625     {
7626       tree field = TREE_PURPOSE (list);
7627       if (SAME_FIELD_P (field, elem))
7628         return list;
7629       list = TREE_CHAIN (list);
7630     }
7631   return NULL_TREE;
7632 }
7633
7634 /* Given GNAT_ENTITY, a record type, and GNU_TYPE, its corresponding GCC type,
7635    set Component_Bit_Offset and Esize of the components to the position and
7636    size used by Gigi.  */
7637
7638 static void
7639 annotate_rep (Entity_Id gnat_entity, tree gnu_type)
7640 {
7641   Entity_Id gnat_field;
7642   tree gnu_list;
7643
7644   /* We operate by first making a list of all fields and their position (we
7645      can get the size easily) and then update all the sizes in the tree.  */
7646   gnu_list
7647     = build_position_list (gnu_type, false, size_zero_node, bitsize_zero_node,
7648                            BIGGEST_ALIGNMENT, NULL_TREE);
7649
7650   for (gnat_field = First_Entity (gnat_entity);
7651        Present (gnat_field);
7652        gnat_field = Next_Entity (gnat_field))
7653     if (Ekind (gnat_field) == E_Component
7654         || (Ekind (gnat_field) == E_Discriminant
7655             && !Is_Unchecked_Union (Scope (gnat_field))))
7656       {
7657         tree t = purpose_member_field (gnat_to_gnu_field_decl (gnat_field),
7658                                        gnu_list);
7659         if (t)
7660           {
7661             tree parent_offset;
7662
7663             /* If we are just annotating types and the type is tagged, the tag
7664                and the parent components are not generated by the front-end so
7665                we need to add the appropriate offset to each component without
7666                representation clause.  */
7667             if (type_annotate_only
7668                 && Is_Tagged_Type (gnat_entity)
7669                 && No (Component_Clause (gnat_field)))
7670               {
7671                 /* For a component appearing in the current extension, the
7672                    offset is the size of the parent.  */
7673                 if (Is_Derived_Type (gnat_entity)
7674                     && Original_Record_Component (gnat_field) == gnat_field)
7675                   parent_offset
7676                     = UI_To_gnu (Esize (Etype (Base_Type (gnat_entity))),
7677                                  bitsizetype);
7678                 else
7679                   parent_offset = bitsize_int (POINTER_SIZE);
7680
7681                 if (TYPE_FIELDS (gnu_type))
7682                   parent_offset
7683                     = round_up (parent_offset,
7684                                 DECL_ALIGN (TYPE_FIELDS (gnu_type)));
7685               }
7686             else
7687               parent_offset = bitsize_zero_node;
7688
7689             Set_Component_Bit_Offset
7690               (gnat_field,
7691                annotate_value
7692                  (size_binop (PLUS_EXPR,
7693                               bit_from_pos (TREE_VEC_ELT (TREE_VALUE (t), 0),
7694                                             TREE_VEC_ELT (TREE_VALUE (t), 2)),
7695                               parent_offset)));
7696
7697             Set_Esize (gnat_field,
7698                        annotate_value (DECL_SIZE (TREE_PURPOSE (t))));
7699           }
7700         else if (Is_Tagged_Type (gnat_entity) && Is_Derived_Type (gnat_entity))
7701           {
7702             /* If there is no entry, this is an inherited component whose
7703                position is the same as in the parent type.  */
7704             Set_Component_Bit_Offset
7705               (gnat_field,
7706                Component_Bit_Offset (Original_Record_Component (gnat_field)));
7707
7708             Set_Esize (gnat_field,
7709                        Esize (Original_Record_Component (gnat_field)));
7710           }
7711       }
7712 }
7713 \f
7714 /* Scan all fields in GNU_TYPE and return a TREE_LIST where TREE_PURPOSE is
7715    the FIELD_DECL and TREE_VALUE a TREE_VEC containing the byte position, the
7716    value to be placed into DECL_OFFSET_ALIGN and the bit position.  The list
7717    of fields is flattened, except for variant parts if DO_NOT_FLATTEN_VARIANT
7718    is set to true.  GNU_POS is to be added to the position, GNU_BITPOS to the
7719    bit position, OFFSET_ALIGN is the present offset alignment.  GNU_LIST is a
7720    pre-existing list to be chained to the newly created entries.  */
7721
7722 static tree
7723 build_position_list (tree gnu_type, bool do_not_flatten_variant, tree gnu_pos,
7724                      tree gnu_bitpos, unsigned int offset_align, tree gnu_list)
7725 {
7726   tree gnu_field;
7727
7728   for (gnu_field = TYPE_FIELDS (gnu_type);
7729        gnu_field;
7730        gnu_field = DECL_CHAIN (gnu_field))
7731     {
7732       tree gnu_our_bitpos = size_binop (PLUS_EXPR, gnu_bitpos,
7733                                         DECL_FIELD_BIT_OFFSET (gnu_field));
7734       tree gnu_our_offset = size_binop (PLUS_EXPR, gnu_pos,
7735                                         DECL_FIELD_OFFSET (gnu_field));
7736       unsigned int our_offset_align
7737         = MIN (offset_align, DECL_OFFSET_ALIGN (gnu_field));
7738       tree v = make_tree_vec (3);
7739
7740       TREE_VEC_ELT (v, 0) = gnu_our_offset;
7741       TREE_VEC_ELT (v, 1) = size_int (our_offset_align);
7742       TREE_VEC_ELT (v, 2) = gnu_our_bitpos;
7743       gnu_list = tree_cons (gnu_field, v, gnu_list);
7744
7745       /* Recurse on internal fields, flattening the nested fields except for
7746          those in the variant part, if requested.  */
7747       if (DECL_INTERNAL_P (gnu_field))
7748         {
7749           tree gnu_field_type = TREE_TYPE (gnu_field);
7750           if (do_not_flatten_variant
7751               && TREE_CODE (gnu_field_type) == QUAL_UNION_TYPE)
7752             gnu_list
7753               = build_position_list (gnu_field_type, do_not_flatten_variant,
7754                                      size_zero_node, bitsize_zero_node,
7755                                      BIGGEST_ALIGNMENT, gnu_list);
7756           else
7757             gnu_list
7758               = build_position_list (gnu_field_type, do_not_flatten_variant,
7759                                      gnu_our_offset, gnu_our_bitpos,
7760                                      our_offset_align, gnu_list);
7761         }
7762     }
7763
7764   return gnu_list;
7765 }
7766
7767 /* Return a list describing the substitutions needed to reflect the
7768    discriminant substitutions from GNAT_TYPE to GNAT_SUBTYPE.  They can
7769    be in any order.  The values in an element of the list are in the form
7770    of operands to SUBSTITUTE_IN_EXPR.  DEFINITION is true if this is for
7771    a definition of GNAT_SUBTYPE.  */
7772
7773 static vec<subst_pair>
7774 build_subst_list (Entity_Id gnat_subtype, Entity_Id gnat_type, bool definition)
7775 {
7776   vec<subst_pair> gnu_list = vNULL;
7777   Entity_Id gnat_discrim;
7778   Node_Id gnat_constr;
7779
7780   for (gnat_discrim = First_Stored_Discriminant (gnat_type),
7781        gnat_constr = First_Elmt (Stored_Constraint (gnat_subtype));
7782        Present (gnat_discrim);
7783        gnat_discrim = Next_Stored_Discriminant (gnat_discrim),
7784        gnat_constr = Next_Elmt (gnat_constr))
7785     /* Ignore access discriminants.  */
7786     if (!Is_Access_Type (Etype (Node (gnat_constr))))
7787       {
7788         tree gnu_field = gnat_to_gnu_field_decl (gnat_discrim);
7789         tree replacement = convert (TREE_TYPE (gnu_field),
7790                                     elaborate_expression
7791                                     (Node (gnat_constr), gnat_subtype,
7792                                      get_entity_name (gnat_discrim),
7793                                      definition, true, false));
7794         subst_pair s = {gnu_field, replacement};
7795         gnu_list.safe_push (s);
7796       }
7797
7798   return gnu_list;
7799 }
7800
7801 /* Scan all fields in QUAL_UNION_TYPE and return a list describing the
7802    variants of QUAL_UNION_TYPE that are still relevant after applying
7803    the substitutions described in SUBST_LIST.  GNU_LIST is a pre-existing
7804    list to be prepended to the newly created entries.  */
7805
7806 static vec<variant_desc>
7807 build_variant_list (tree qual_union_type, vec<subst_pair> subst_list,
7808                     vec<variant_desc> gnu_list)
7809 {
7810   tree gnu_field;
7811
7812   for (gnu_field = TYPE_FIELDS (qual_union_type);
7813        gnu_field;
7814        gnu_field = DECL_CHAIN (gnu_field))
7815     {
7816       tree qual = DECL_QUALIFIER (gnu_field);
7817       unsigned int i;
7818       subst_pair *s;
7819
7820       FOR_EACH_VEC_ELT (subst_list, i, s)
7821         qual = SUBSTITUTE_IN_EXPR (qual, s->discriminant, s->replacement);
7822
7823       /* If the new qualifier is not unconditionally false, its variant may
7824          still be accessed.  */
7825       if (!integer_zerop (qual))
7826         {
7827           tree variant_type = TREE_TYPE (gnu_field), variant_subpart;
7828           variant_desc v = {variant_type, gnu_field, qual, NULL_TREE};
7829
7830           gnu_list.safe_push (v);
7831
7832           /* Recurse on the variant subpart of the variant, if any.  */
7833           variant_subpart = get_variant_part (variant_type);
7834           if (variant_subpart)
7835             gnu_list = build_variant_list (TREE_TYPE (variant_subpart),
7836                                            subst_list, gnu_list);
7837
7838           /* If the new qualifier is unconditionally true, the subsequent
7839              variants cannot be accessed.  */
7840           if (integer_onep (qual))
7841             break;
7842         }
7843     }
7844
7845   return gnu_list;
7846 }
7847 \f
7848 /* UINT_SIZE is a Uint giving the specified size for an object of GNU_TYPE
7849    corresponding to GNAT_OBJECT.  If the size is valid, return an INTEGER_CST
7850    corresponding to its value.  Otherwise, return NULL_TREE.  KIND is set to
7851    VAR_DECL if we are specifying the size of an object, TYPE_DECL for the
7852    size of a type, and FIELD_DECL for the size of a field.  COMPONENT_P is
7853    true if we are being called to process the Component_Size of GNAT_OBJECT;
7854    this is used only for error messages.  ZERO_OK is true if a size of zero
7855    is permitted; if ZERO_OK is false, it means that a size of zero should be
7856    treated as an unspecified size.  */
7857
7858 static tree
7859 validate_size (Uint uint_size, tree gnu_type, Entity_Id gnat_object,
7860                enum tree_code kind, bool component_p, bool zero_ok)
7861 {
7862   Node_Id gnat_error_node;
7863   tree type_size, size;
7864
7865   /* Return 0 if no size was specified.  */
7866   if (uint_size == No_Uint)
7867     return NULL_TREE;
7868
7869   /* Ignore a negative size since that corresponds to our back-annotation.  */
7870   if (UI_Lt (uint_size, Uint_0))
7871     return NULL_TREE;
7872
7873   /* Find the node to use for error messages.  */
7874   if ((Ekind (gnat_object) == E_Component
7875        || Ekind (gnat_object) == E_Discriminant)
7876       && Present (Component_Clause (gnat_object)))
7877     gnat_error_node = Last_Bit (Component_Clause (gnat_object));
7878   else if (Present (Size_Clause (gnat_object)))
7879     gnat_error_node = Expression (Size_Clause (gnat_object));
7880   else
7881     gnat_error_node = gnat_object;
7882
7883   /* Get the size as an INTEGER_CST.  Issue an error if a size was specified
7884      but cannot be represented in bitsizetype.  */
7885   size = UI_To_gnu (uint_size, bitsizetype);
7886   if (TREE_OVERFLOW (size))
7887     {
7888       if (component_p)
7889         post_error_ne ("component size for& is too large", gnat_error_node,
7890                        gnat_object);
7891       else
7892         post_error_ne ("size for& is too large", gnat_error_node,
7893                        gnat_object);
7894       return NULL_TREE;
7895     }
7896
7897   /* Ignore a zero size if it is not permitted.  */
7898   if (!zero_ok && integer_zerop (size))
7899     return NULL_TREE;
7900
7901   /* The size of objects is always a multiple of a byte.  */
7902   if (kind == VAR_DECL
7903       && !integer_zerop (size_binop (TRUNC_MOD_EXPR, size, bitsize_unit_node)))
7904     {
7905       if (component_p)
7906         post_error_ne ("component size for& is not a multiple of Storage_Unit",
7907                        gnat_error_node, gnat_object);
7908       else
7909         post_error_ne ("size for& is not a multiple of Storage_Unit",
7910                        gnat_error_node, gnat_object);
7911       return NULL_TREE;
7912     }
7913
7914   /* If this is an integral type or a packed array type, the front-end has
7915      already verified the size, so we need not do it here (which would mean
7916      checking against the bounds).  However, if this is an aliased object,
7917      it may not be smaller than the type of the object.  */
7918   if ((INTEGRAL_TYPE_P (gnu_type) || TYPE_IS_PACKED_ARRAY_TYPE_P (gnu_type))
7919       && !(kind == VAR_DECL && Is_Aliased (gnat_object)))
7920     return size;
7921
7922   /* If the object is a record that contains a template, add the size of the
7923      template to the specified size.  */
7924   if (TREE_CODE (gnu_type) == RECORD_TYPE
7925       && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
7926     size = size_binop (PLUS_EXPR, DECL_SIZE (TYPE_FIELDS (gnu_type)), size);
7927
7928   if (kind == VAR_DECL
7929       /* If a type needs strict alignment, a component of this type in
7930          a packed record cannot be packed and thus uses the type size.  */
7931       || (kind == TYPE_DECL && Strict_Alignment (gnat_object)))
7932     type_size = TYPE_SIZE (gnu_type);
7933   else
7934     type_size = rm_size (gnu_type);
7935
7936   /* Modify the size of a discriminated type to be the maximum size.  */
7937   if (type_size && CONTAINS_PLACEHOLDER_P (type_size))
7938     type_size = max_size (type_size, true);
7939
7940   /* If this is an access type or a fat pointer, the minimum size is that given
7941      by the smallest integral mode that's valid for pointers.  */
7942   if (TREE_CODE (gnu_type) == POINTER_TYPE || TYPE_IS_FAT_POINTER_P (gnu_type))
7943     {
7944       machine_mode p_mode = GET_CLASS_NARROWEST_MODE (MODE_INT);
7945       while (!targetm.valid_pointer_mode (p_mode))
7946         p_mode = GET_MODE_WIDER_MODE (p_mode);
7947       type_size = bitsize_int (GET_MODE_BITSIZE (p_mode));
7948     }
7949
7950   /* Issue an error either if the default size of the object isn't a constant
7951      or if the new size is smaller than it.  */
7952   if (TREE_CODE (type_size) != INTEGER_CST
7953       || TREE_OVERFLOW (type_size)
7954       || tree_int_cst_lt (size, type_size))
7955     {
7956       if (component_p)
7957         post_error_ne_tree
7958           ("component size for& too small{, minimum allowed is ^}",
7959            gnat_error_node, gnat_object, type_size);
7960       else
7961         post_error_ne_tree
7962           ("size for& too small{, minimum allowed is ^}",
7963            gnat_error_node, gnat_object, type_size);
7964       return NULL_TREE;
7965     }
7966
7967   return size;
7968 }
7969 \f
7970 /* Similarly, but both validate and process a value of RM size.  This routine
7971    is only called for types.  */
7972
7973 static void
7974 set_rm_size (Uint uint_size, tree gnu_type, Entity_Id gnat_entity)
7975 {
7976   Node_Id gnat_attr_node;
7977   tree old_size, size;
7978
7979   /* Do nothing if no size was specified.  */
7980   if (uint_size == No_Uint)
7981     return;
7982
7983   /* Ignore a negative size since that corresponds to our back-annotation.  */
7984   if (UI_Lt (uint_size, Uint_0))
7985     return;
7986
7987   /* Only issue an error if a Value_Size clause was explicitly given.
7988      Otherwise, we'd be duplicating an error on the Size clause.  */
7989   gnat_attr_node
7990     = Get_Attribute_Definition_Clause (gnat_entity, Attr_Value_Size);
7991
7992   /* Get the size as an INTEGER_CST.  Issue an error if a size was specified
7993      but cannot be represented in bitsizetype.  */
7994   size = UI_To_gnu (uint_size, bitsizetype);
7995   if (TREE_OVERFLOW (size))
7996     {
7997       if (Present (gnat_attr_node))
7998         post_error_ne ("Value_Size for& is too large", gnat_attr_node,
7999                        gnat_entity);
8000       return;
8001     }
8002
8003   /* Ignore a zero size unless a Value_Size clause exists, or a size clause
8004      exists, or this is an integer type, in which case the front-end will
8005      have always set it.  */
8006   if (No (gnat_attr_node)
8007       && integer_zerop (size)
8008       && !Has_Size_Clause (gnat_entity)
8009       && !Is_Discrete_Or_Fixed_Point_Type (gnat_entity))
8010     return;
8011
8012   old_size = rm_size (gnu_type);
8013
8014   /* If the old size is self-referential, get the maximum size.  */
8015   if (CONTAINS_PLACEHOLDER_P (old_size))
8016     old_size = max_size (old_size, true);
8017
8018   /* Issue an error either if the old size of the object isn't a constant or
8019      if the new size is smaller than it.  The front-end has already verified
8020      this for scalar and packed array types.  */
8021   if (TREE_CODE (old_size) != INTEGER_CST
8022       || TREE_OVERFLOW (old_size)
8023       || (AGGREGATE_TYPE_P (gnu_type)
8024           && !(TREE_CODE (gnu_type) == ARRAY_TYPE
8025                && TYPE_PACKED_ARRAY_TYPE_P (gnu_type))
8026           && !(TYPE_IS_PADDING_P (gnu_type)
8027                && TREE_CODE (TREE_TYPE (TYPE_FIELDS (gnu_type))) == ARRAY_TYPE
8028                && TYPE_PACKED_ARRAY_TYPE_P
8029                   (TREE_TYPE (TYPE_FIELDS (gnu_type))))
8030           && tree_int_cst_lt (size, old_size)))
8031     {
8032       if (Present (gnat_attr_node))
8033         post_error_ne_tree
8034           ("Value_Size for& too small{, minimum allowed is ^}",
8035            gnat_attr_node, gnat_entity, old_size);
8036       return;
8037     }
8038
8039   /* Otherwise, set the RM size proper for integral types...  */
8040   if ((TREE_CODE (gnu_type) == INTEGER_TYPE
8041        && Is_Discrete_Or_Fixed_Point_Type (gnat_entity))
8042       || (TREE_CODE (gnu_type) == ENUMERAL_TYPE
8043           || TREE_CODE (gnu_type) == BOOLEAN_TYPE))
8044     SET_TYPE_RM_SIZE (gnu_type, size);
8045
8046   /* ...or the Ada size for record and union types.  */
8047   else if (RECORD_OR_UNION_TYPE_P (gnu_type)
8048            && !TYPE_FAT_POINTER_P (gnu_type))
8049     SET_TYPE_ADA_SIZE (gnu_type, size);
8050 }
8051 \f
8052 /* ALIGNMENT is a Uint giving the alignment specified for GNAT_ENTITY,
8053    a type or object whose present alignment is ALIGN.  If this alignment is
8054    valid, return it.  Otherwise, give an error and return ALIGN.  */
8055
8056 static unsigned int
8057 validate_alignment (Uint alignment, Entity_Id gnat_entity, unsigned int align)
8058 {
8059   unsigned int max_allowed_alignment = get_target_maximum_allowed_alignment ();
8060   unsigned int new_align;
8061   Node_Id gnat_error_node;
8062
8063   /* Don't worry about checking alignment if alignment was not specified
8064      by the source program and we already posted an error for this entity.  */
8065   if (Error_Posted (gnat_entity) && !Has_Alignment_Clause (gnat_entity))
8066     return align;
8067
8068   /* Post the error on the alignment clause if any.  Note, for the implicit
8069      base type of an array type, the alignment clause is on the first
8070      subtype.  */
8071   if (Present (Alignment_Clause (gnat_entity)))
8072     gnat_error_node = Expression (Alignment_Clause (gnat_entity));
8073
8074   else if (Is_Itype (gnat_entity)
8075            && Is_Array_Type (gnat_entity)
8076            && Etype (gnat_entity) == gnat_entity
8077            && Present (Alignment_Clause (First_Subtype (gnat_entity))))
8078     gnat_error_node =
8079       Expression (Alignment_Clause (First_Subtype (gnat_entity)));
8080
8081   else
8082     gnat_error_node = gnat_entity;
8083
8084   /* Within GCC, an alignment is an integer, so we must make sure a value is
8085      specified that fits in that range.  Also, there is an upper bound to
8086      alignments we can support/allow.  */
8087   if (!UI_Is_In_Int_Range (alignment)
8088       || ((new_align = UI_To_Int (alignment)) > max_allowed_alignment))
8089     post_error_ne_num ("largest supported alignment for& is ^",
8090                        gnat_error_node, gnat_entity, max_allowed_alignment);
8091   else if (!(Present (Alignment_Clause (gnat_entity))
8092              && From_At_Mod (Alignment_Clause (gnat_entity)))
8093            && new_align * BITS_PER_UNIT < align)
8094     {
8095       unsigned int double_align;
8096       bool is_capped_double, align_clause;
8097
8098       /* If the default alignment of "double" or larger scalar types is
8099          specifically capped and the new alignment is above the cap, do
8100          not post an error and change the alignment only if there is an
8101          alignment clause; this makes it possible to have the associated
8102          GCC type overaligned by default for performance reasons.  */
8103       if ((double_align = double_float_alignment) > 0)
8104         {
8105           Entity_Id gnat_type
8106             = Is_Type (gnat_entity) ? gnat_entity : Etype (gnat_entity);
8107           is_capped_double
8108             = is_double_float_or_array (gnat_type, &align_clause);
8109         }
8110       else if ((double_align = double_scalar_alignment) > 0)
8111         {
8112           Entity_Id gnat_type
8113             = Is_Type (gnat_entity) ? gnat_entity : Etype (gnat_entity);
8114           is_capped_double
8115             = is_double_scalar_or_array (gnat_type, &align_clause);
8116         }
8117       else
8118         is_capped_double = align_clause = false;
8119
8120       if (is_capped_double && new_align >= double_align)
8121         {
8122           if (align_clause)
8123             align = new_align * BITS_PER_UNIT;
8124         }
8125       else
8126         {
8127           if (is_capped_double)
8128             align = double_align * BITS_PER_UNIT;
8129
8130           post_error_ne_num ("alignment for& must be at least ^",
8131                              gnat_error_node, gnat_entity,
8132                              align / BITS_PER_UNIT);
8133         }
8134     }
8135   else
8136     {
8137       new_align = (new_align > 0 ? new_align * BITS_PER_UNIT : 1);
8138       if (new_align > align)
8139         align = new_align;
8140     }
8141
8142   return align;
8143 }
8144 \f
8145 /* Verify that TYPE is something we can implement atomically.  If not, issue
8146    an error for GNAT_ENTITY.  COMPONENT_P is true if we are being called to
8147    process a component type.  */
8148
8149 static void
8150 check_ok_for_atomic_type (tree type, Entity_Id gnat_entity, bool component_p)
8151 {
8152   Node_Id gnat_error_point = gnat_entity;
8153   Node_Id gnat_node;
8154   machine_mode mode;
8155   enum mode_class mclass;
8156   unsigned int align;
8157   tree size;
8158
8159   /* If this is an anonymous base type, nothing to check, the error will be
8160      reported on the source type if need be.  */
8161   if (!Comes_From_Source (gnat_entity))
8162     return;
8163
8164   mode = TYPE_MODE (type);
8165   mclass = GET_MODE_CLASS (mode);
8166   align = TYPE_ALIGN (type);
8167   size = TYPE_SIZE (type);
8168
8169   /* Consider all aligned floating-point types atomic and any aligned types
8170      that are represented by integers no wider than a machine word.  */
8171   if ((mclass == MODE_FLOAT
8172        || ((mclass == MODE_INT || mclass == MODE_PARTIAL_INT)
8173            && GET_MODE_BITSIZE (mode) <= BITS_PER_WORD))
8174       && align >= GET_MODE_ALIGNMENT (mode))
8175     return;
8176
8177   /* For the moment, also allow anything that has an alignment equal to its
8178      size and which is smaller than a word.  */
8179   if (size
8180       && TREE_CODE (size) == INTEGER_CST
8181       && compare_tree_int (size, align) == 0
8182       && align <= BITS_PER_WORD)
8183     return;
8184
8185   for (gnat_node = First_Rep_Item (gnat_entity);
8186        Present (gnat_node);
8187        gnat_node = Next_Rep_Item (gnat_node))
8188     if (Nkind (gnat_node) == N_Pragma)
8189       {
8190         unsigned char pragma_id
8191           = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node)));
8192
8193         if ((pragma_id == Pragma_Atomic && !component_p)
8194             || (pragma_id == Pragma_Atomic_Components && component_p))
8195           {
8196             gnat_error_point = First (Pragma_Argument_Associations (gnat_node));
8197             break;
8198           }
8199       }
8200
8201   if (component_p)
8202     post_error_ne ("atomic access to component of & cannot be guaranteed",
8203                    gnat_error_point, gnat_entity);
8204   else if (Is_Volatile_Full_Access (gnat_entity))
8205     post_error_ne ("volatile full access to & cannot be guaranteed",
8206                    gnat_error_point, gnat_entity);
8207   else
8208     post_error_ne ("atomic access to & cannot be guaranteed",
8209                    gnat_error_point, gnat_entity);
8210 }
8211 \f
8212
8213 /* Helper for the intrin compatibility checks family.  Evaluate whether
8214    two types are definitely incompatible.  */
8215
8216 static bool
8217 intrin_types_incompatible_p (tree t1, tree t2)
8218 {
8219   enum tree_code code;
8220
8221   if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
8222     return false;
8223
8224   if (TYPE_MODE (t1) != TYPE_MODE (t2))
8225     return true;
8226
8227   if (TREE_CODE (t1) != TREE_CODE (t2))
8228     return true;
8229
8230   code = TREE_CODE (t1);
8231
8232   switch (code)
8233     {
8234     case INTEGER_TYPE:
8235     case REAL_TYPE:
8236       return TYPE_PRECISION (t1) != TYPE_PRECISION (t2);
8237
8238     case POINTER_TYPE:
8239     case REFERENCE_TYPE:
8240       /* Assume designated types are ok.  We'd need to account for char * and
8241          void * variants to do better, which could rapidly get messy and isn't
8242          clearly worth the effort.  */
8243       return false;
8244
8245     default:
8246       break;
8247     }
8248
8249   return false;
8250 }
8251
8252 /* Helper for intrin_profiles_compatible_p, to perform compatibility checks
8253    on the Ada/builtin argument lists for the INB binding.  */
8254
8255 static bool
8256 intrin_arglists_compatible_p (intrin_binding_t * inb)
8257 {
8258   function_args_iterator ada_iter, btin_iter;
8259
8260   function_args_iter_init (&ada_iter, inb->ada_fntype);
8261   function_args_iter_init (&btin_iter, inb->btin_fntype);
8262
8263   /* Sequence position of the last argument we checked.  */
8264   int argpos = 0;
8265
8266   while (1)
8267     {
8268       tree ada_type = function_args_iter_cond (&ada_iter);
8269       tree btin_type = function_args_iter_cond (&btin_iter);
8270
8271       /* If we've exhausted both lists simultaneously, we're done.  */
8272       if (ada_type == NULL_TREE && btin_type == NULL_TREE)
8273         break;
8274
8275       /* If one list is shorter than the other, they fail to match.  */
8276       if (ada_type == NULL_TREE || btin_type == NULL_TREE)
8277         return false;
8278
8279       /* If we're done with the Ada args and not with the internal builtin
8280          args, or the other way around, complain.  */
8281       if (ada_type == void_type_node
8282           && btin_type != void_type_node)
8283         {
8284           post_error ("?Ada arguments list too short!", inb->gnat_entity);
8285           return false;
8286         }
8287
8288       if (btin_type == void_type_node
8289           && ada_type != void_type_node)
8290         {
8291           post_error_ne_num ("?Ada arguments list too long ('> ^)!",
8292                              inb->gnat_entity, inb->gnat_entity, argpos);
8293           return false;
8294         }
8295
8296       /* Otherwise, check that types match for the current argument.  */
8297       argpos ++;
8298       if (intrin_types_incompatible_p (ada_type, btin_type))
8299         {
8300           post_error_ne_num ("?intrinsic binding type mismatch on argument ^!",
8301                              inb->gnat_entity, inb->gnat_entity, argpos);
8302           return false;
8303         }
8304
8305
8306       function_args_iter_next (&ada_iter);
8307       function_args_iter_next (&btin_iter);
8308     }
8309
8310   return true;
8311 }
8312
8313 /* Helper for intrin_profiles_compatible_p, to perform compatibility checks
8314    on the Ada/builtin return values for the INB binding.  */
8315
8316 static bool
8317 intrin_return_compatible_p (intrin_binding_t * inb)
8318 {
8319   tree ada_return_type = TREE_TYPE (inb->ada_fntype);
8320   tree btin_return_type = TREE_TYPE (inb->btin_fntype);
8321
8322   /* Accept function imported as procedure, common and convenient.  */
8323   if (VOID_TYPE_P (ada_return_type)
8324       && !VOID_TYPE_P (btin_return_type))
8325     return true;
8326
8327   /* If return type is Address (integer type), map it to void *.  */
8328   if (Is_Descendent_Of_Address (Etype (inb->gnat_entity)))
8329     ada_return_type = ptr_void_type_node;
8330
8331   /* Check return types compatibility otherwise.  Note that this
8332      handles void/void as well.  */
8333   if (intrin_types_incompatible_p (btin_return_type, ada_return_type))
8334     {
8335       post_error ("?intrinsic binding type mismatch on return value!",
8336                   inb->gnat_entity);
8337       return false;
8338     }
8339
8340   return true;
8341 }
8342
8343 /* Check and return whether the Ada and gcc builtin profiles bound by INB are
8344    compatible.  Issue relevant warnings when they are not.
8345
8346    This is intended as a light check to diagnose the most obvious cases, not
8347    as a full fledged type compatibility predicate.  It is the programmer's
8348    responsibility to ensure correctness of the Ada declarations in Imports,
8349    especially when binding straight to a compiler internal.  */
8350
8351 static bool
8352 intrin_profiles_compatible_p (intrin_binding_t * inb)
8353 {
8354   /* Check compatibility on return values and argument lists, each responsible
8355      for posting warnings as appropriate.  Ensure use of the proper sloc for
8356      this purpose.  */
8357
8358   bool arglists_compatible_p, return_compatible_p;
8359   location_t saved_location = input_location;
8360
8361   Sloc_to_locus (Sloc (inb->gnat_entity), &input_location);
8362
8363   return_compatible_p = intrin_return_compatible_p (inb);
8364   arglists_compatible_p = intrin_arglists_compatible_p (inb);
8365
8366   input_location = saved_location;
8367
8368   return return_compatible_p && arglists_compatible_p;
8369 }
8370 \f
8371 /* Return a FIELD_DECL node modeled on OLD_FIELD.  FIELD_TYPE is its type
8372    and RECORD_TYPE is the type of the parent.  If SIZE is nonzero, it is the
8373    specified size for this field.  POS_LIST is a position list describing
8374    the layout of OLD_FIELD and SUBST_LIST a substitution list to be applied
8375    to this layout.  */
8376
8377 static tree
8378 create_field_decl_from (tree old_field, tree field_type, tree record_type,
8379                         tree size, tree pos_list,
8380                         vec<subst_pair> subst_list)
8381 {
8382   tree t = TREE_VALUE (purpose_member (old_field, pos_list));
8383   tree pos = TREE_VEC_ELT (t, 0), bitpos = TREE_VEC_ELT (t, 2);
8384   unsigned int offset_align = tree_to_uhwi (TREE_VEC_ELT (t, 1));
8385   tree new_pos, new_field;
8386   unsigned int i;
8387   subst_pair *s;
8388
8389   if (CONTAINS_PLACEHOLDER_P (pos))
8390     FOR_EACH_VEC_ELT (subst_list, i, s)
8391       pos = SUBSTITUTE_IN_EXPR (pos, s->discriminant, s->replacement);
8392
8393   /* If the position is now a constant, we can set it as the position of the
8394      field when we make it.  Otherwise, we need to deal with it specially.  */
8395   if (TREE_CONSTANT (pos))
8396     new_pos = bit_from_pos (pos, bitpos);
8397   else
8398     new_pos = NULL_TREE;
8399
8400   new_field
8401     = create_field_decl (DECL_NAME (old_field), field_type, record_type,
8402                          size, new_pos, DECL_PACKED (old_field),
8403                          !DECL_NONADDRESSABLE_P (old_field));
8404
8405   if (!new_pos)
8406     {
8407       normalize_offset (&pos, &bitpos, offset_align);
8408       /* Finalize the position.  */
8409       DECL_FIELD_OFFSET (new_field) = variable_size (pos);
8410       DECL_FIELD_BIT_OFFSET (new_field) = bitpos;
8411       SET_DECL_OFFSET_ALIGN (new_field, offset_align);
8412       DECL_SIZE (new_field) = size;
8413       DECL_SIZE_UNIT (new_field)
8414         = convert (sizetype,
8415                    size_binop (CEIL_DIV_EXPR, size, bitsize_unit_node));
8416       layout_decl (new_field, DECL_OFFSET_ALIGN (new_field));
8417     }
8418
8419   DECL_INTERNAL_P (new_field) = DECL_INTERNAL_P (old_field);
8420   SET_DECL_ORIGINAL_FIELD_TO_FIELD (new_field, old_field);
8421   DECL_DISCRIMINANT_NUMBER (new_field) = DECL_DISCRIMINANT_NUMBER (old_field);
8422   TREE_THIS_VOLATILE (new_field) = TREE_THIS_VOLATILE (old_field);
8423
8424   return new_field;
8425 }
8426
8427 /* Create the REP part of RECORD_TYPE with REP_TYPE.  If MIN_SIZE is nonzero,
8428    it is the minimal size the REP_PART must have.  */
8429
8430 static tree
8431 create_rep_part (tree rep_type, tree record_type, tree min_size)
8432 {
8433   tree field;
8434
8435   if (min_size && !tree_int_cst_lt (TYPE_SIZE (rep_type), min_size))
8436     min_size = NULL_TREE;
8437
8438   field = create_field_decl (get_identifier ("REP"), rep_type, record_type,
8439                              min_size, NULL_TREE, 0, 1);
8440   DECL_INTERNAL_P (field) = 1;
8441
8442   return field;
8443 }
8444
8445 /* Return the REP part of RECORD_TYPE, if any.  Otherwise return NULL.  */
8446
8447 static tree
8448 get_rep_part (tree record_type)
8449 {
8450   tree field = TYPE_FIELDS (record_type);
8451
8452   /* The REP part is the first field, internal, another record, and its name
8453      starts with an 'R'.  */
8454   if (field
8455       && DECL_INTERNAL_P (field)
8456       && TREE_CODE (TREE_TYPE (field)) == RECORD_TYPE
8457       && IDENTIFIER_POINTER (DECL_NAME (field)) [0] == 'R')
8458     return field;
8459
8460   return NULL_TREE;
8461 }
8462
8463 /* Return the variant part of RECORD_TYPE, if any.  Otherwise return NULL.  */
8464
8465 tree
8466 get_variant_part (tree record_type)
8467 {
8468   tree field;
8469
8470   /* The variant part is the only internal field that is a qualified union.  */
8471   for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
8472     if (DECL_INTERNAL_P (field)
8473         && TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE)
8474       return field;
8475
8476   return NULL_TREE;
8477 }
8478
8479 /* Return a new variant part modeled on OLD_VARIANT_PART.  VARIANT_LIST is
8480    the list of variants to be used and RECORD_TYPE is the type of the parent.
8481    POS_LIST is a position list describing the layout of fields present in
8482    OLD_VARIANT_PART and SUBST_LIST a substitution list to be applied to this
8483    layout.  */
8484
8485 static tree
8486 create_variant_part_from (tree old_variant_part,
8487                           vec<variant_desc> variant_list,
8488                           tree record_type, tree pos_list,
8489                           vec<subst_pair> subst_list)
8490 {
8491   tree offset = DECL_FIELD_OFFSET (old_variant_part);
8492   tree old_union_type = TREE_TYPE (old_variant_part);
8493   tree new_union_type, new_variant_part;
8494   tree union_field_list = NULL_TREE;
8495   variant_desc *v;
8496   unsigned int i;
8497
8498   /* First create the type of the variant part from that of the old one.  */
8499   new_union_type = make_node (QUAL_UNION_TYPE);
8500   TYPE_NAME (new_union_type)
8501     = concat_name (TYPE_NAME (record_type),
8502                    IDENTIFIER_POINTER (DECL_NAME (old_variant_part)));
8503
8504   /* If the position of the variant part is constant, subtract it from the
8505      size of the type of the parent to get the new size.  This manual CSE
8506      reduces the code size when not optimizing.  */
8507   if (TREE_CODE (offset) == INTEGER_CST)
8508     {
8509       tree bitpos = DECL_FIELD_BIT_OFFSET (old_variant_part);
8510       tree first_bit = bit_from_pos (offset, bitpos);
8511       TYPE_SIZE (new_union_type)
8512         = size_binop (MINUS_EXPR, TYPE_SIZE (record_type), first_bit);
8513       TYPE_SIZE_UNIT (new_union_type)
8514         = size_binop (MINUS_EXPR, TYPE_SIZE_UNIT (record_type),
8515                       byte_from_pos (offset, bitpos));
8516       SET_TYPE_ADA_SIZE (new_union_type,
8517                          size_binop (MINUS_EXPR, TYPE_ADA_SIZE (record_type),
8518                                      first_bit));
8519       TYPE_ALIGN (new_union_type) = TYPE_ALIGN (old_union_type);
8520       relate_alias_sets (new_union_type, old_union_type, ALIAS_SET_COPY);
8521     }
8522   else
8523     copy_and_substitute_in_size (new_union_type, old_union_type, subst_list);
8524
8525   /* Now finish up the new variants and populate the union type.  */
8526   FOR_EACH_VEC_ELT_REVERSE (variant_list, i, v)
8527     {
8528       tree old_field = v->field, new_field;
8529       tree old_variant, old_variant_subpart, new_variant, field_list;
8530
8531       /* Skip variants that don't belong to this nesting level.  */
8532       if (DECL_CONTEXT (old_field) != old_union_type)
8533         continue;
8534
8535       /* Retrieve the list of fields already added to the new variant.  */
8536       new_variant = v->new_type;
8537       field_list = TYPE_FIELDS (new_variant);
8538
8539       /* If the old variant had a variant subpart, we need to create a new
8540          variant subpart and add it to the field list.  */
8541       old_variant = v->type;
8542       old_variant_subpart = get_variant_part (old_variant);
8543       if (old_variant_subpart)
8544         {
8545           tree new_variant_subpart
8546             = create_variant_part_from (old_variant_subpart, variant_list,
8547                                         new_variant, pos_list, subst_list);
8548           DECL_CHAIN (new_variant_subpart) = field_list;
8549           field_list = new_variant_subpart;
8550         }
8551
8552       /* Finish up the new variant and create the field.  No need for debug
8553          info thanks to the XVS type.  */
8554       finish_record_type (new_variant, nreverse (field_list), 2, false);
8555       compute_record_mode (new_variant);
8556       create_type_decl (TYPE_NAME (new_variant), new_variant, true, false,
8557                         Empty);
8558
8559       new_field
8560         = create_field_decl_from (old_field, new_variant, new_union_type,
8561                                   TYPE_SIZE (new_variant),
8562                                   pos_list, subst_list);
8563       DECL_QUALIFIER (new_field) = v->qual;
8564       DECL_INTERNAL_P (new_field) = 1;
8565       DECL_CHAIN (new_field) = union_field_list;
8566       union_field_list = new_field;
8567     }
8568
8569   /* Finish up the union type and create the variant part.  No need for debug
8570      info thanks to the XVS type.  Note that we don't reverse the field list
8571      because VARIANT_LIST has been traversed in reverse order.  */
8572   finish_record_type (new_union_type, union_field_list, 2, false);
8573   compute_record_mode (new_union_type);
8574   create_type_decl (TYPE_NAME (new_union_type), new_union_type, true, false,
8575                     Empty);
8576
8577   new_variant_part
8578     = create_field_decl_from (old_variant_part, new_union_type, record_type,
8579                               TYPE_SIZE (new_union_type),
8580                               pos_list, subst_list);
8581   DECL_INTERNAL_P (new_variant_part) = 1;
8582
8583   /* With multiple discriminants it is possible for an inner variant to be
8584      statically selected while outer ones are not; in this case, the list
8585      of fields of the inner variant is not flattened and we end up with a
8586      qualified union with a single member.  Drop the useless container.  */
8587   if (!DECL_CHAIN (union_field_list))
8588     {
8589       DECL_CONTEXT (union_field_list) = record_type;
8590       DECL_FIELD_OFFSET (union_field_list)
8591         = DECL_FIELD_OFFSET (new_variant_part);
8592       DECL_FIELD_BIT_OFFSET (union_field_list)
8593         = DECL_FIELD_BIT_OFFSET (new_variant_part);
8594       SET_DECL_OFFSET_ALIGN (union_field_list,
8595                              DECL_OFFSET_ALIGN (new_variant_part));
8596       new_variant_part = union_field_list;
8597     }
8598
8599   return new_variant_part;
8600 }
8601
8602 /* Copy the size (and alignment and alias set) from OLD_TYPE to NEW_TYPE,
8603    which are both RECORD_TYPE, after applying the substitutions described
8604    in SUBST_LIST.  */
8605
8606 static void
8607 copy_and_substitute_in_size (tree new_type, tree old_type,
8608                              vec<subst_pair> subst_list)
8609 {
8610   unsigned int i;
8611   subst_pair *s;
8612
8613   TYPE_SIZE (new_type) = TYPE_SIZE (old_type);
8614   TYPE_SIZE_UNIT (new_type) = TYPE_SIZE_UNIT (old_type);
8615   SET_TYPE_ADA_SIZE (new_type, TYPE_ADA_SIZE (old_type));
8616   TYPE_ALIGN (new_type) = TYPE_ALIGN (old_type);
8617   relate_alias_sets (new_type, old_type, ALIAS_SET_COPY);
8618
8619   if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE (new_type)))
8620     FOR_EACH_VEC_ELT (subst_list, i, s)
8621       TYPE_SIZE (new_type)
8622         = SUBSTITUTE_IN_EXPR (TYPE_SIZE (new_type),
8623                               s->discriminant, s->replacement);
8624
8625   if (CONTAINS_PLACEHOLDER_P (TYPE_SIZE_UNIT (new_type)))
8626     FOR_EACH_VEC_ELT (subst_list, i, s)
8627       TYPE_SIZE_UNIT (new_type)
8628         = SUBSTITUTE_IN_EXPR (TYPE_SIZE_UNIT (new_type),
8629                               s->discriminant, s->replacement);
8630
8631   if (CONTAINS_PLACEHOLDER_P (TYPE_ADA_SIZE (new_type)))
8632     FOR_EACH_VEC_ELT (subst_list, i, s)
8633       SET_TYPE_ADA_SIZE
8634         (new_type, SUBSTITUTE_IN_EXPR (TYPE_ADA_SIZE (new_type),
8635                                        s->discriminant, s->replacement));
8636
8637   /* Finalize the size.  */
8638   TYPE_SIZE (new_type) = variable_size (TYPE_SIZE (new_type));
8639   TYPE_SIZE_UNIT (new_type) = variable_size (TYPE_SIZE_UNIT (new_type));
8640 }
8641
8642 /* Add a parallel type to GNU_TYPE, the translation of GNAT_ENTITY, which is
8643    the implementation type of a packed array type (Is_Packed_Array_Impl_Type).
8644    The parallel type is the original array type if it has been translated.  */
8645
8646 static void
8647 add_parallel_type_for_packed_array (tree gnu_type, Entity_Id gnat_entity)
8648 {
8649   Entity_Id gnat_original_array_type
8650     = Underlying_Type (Original_Array_Type (gnat_entity));
8651   tree gnu_original_array_type;
8652
8653   if (!present_gnu_tree (gnat_original_array_type))
8654     return;
8655
8656   gnu_original_array_type = gnat_to_gnu_type (gnat_original_array_type);
8657
8658   if (TYPE_IS_DUMMY_P (gnu_original_array_type))
8659     return;
8660
8661   add_parallel_type (gnu_type, gnu_original_array_type);
8662 }
8663 \f
8664 /* Given a type T, a FIELD_DECL F, and a replacement value R, return a
8665    type with all size expressions that contain F in a PLACEHOLDER_EXPR
8666    updated by replacing F with R.
8667
8668    The function doesn't update the layout of the type, i.e. it assumes
8669    that the substitution is purely formal.  That's why the replacement
8670    value R must itself contain a PLACEHOLDER_EXPR.  */
8671
8672 tree
8673 substitute_in_type (tree t, tree f, tree r)
8674 {
8675   tree nt;
8676
8677   gcc_assert (CONTAINS_PLACEHOLDER_P (r));
8678
8679   switch (TREE_CODE (t))
8680     {
8681     case INTEGER_TYPE:
8682     case ENUMERAL_TYPE:
8683     case BOOLEAN_TYPE:
8684     case REAL_TYPE:
8685
8686       /* First the domain types of arrays.  */
8687       if (CONTAINS_PLACEHOLDER_P (TYPE_GCC_MIN_VALUE (t))
8688           || CONTAINS_PLACEHOLDER_P (TYPE_GCC_MAX_VALUE (t)))
8689         {
8690           tree low = SUBSTITUTE_IN_EXPR (TYPE_GCC_MIN_VALUE (t), f, r);
8691           tree high = SUBSTITUTE_IN_EXPR (TYPE_GCC_MAX_VALUE (t), f, r);
8692
8693           if (low == TYPE_GCC_MIN_VALUE (t) && high == TYPE_GCC_MAX_VALUE (t))
8694             return t;
8695
8696           nt = copy_type (t);
8697           TYPE_GCC_MIN_VALUE (nt) = low;
8698           TYPE_GCC_MAX_VALUE (nt) = high;
8699
8700           if (TREE_CODE (t) == INTEGER_TYPE && TYPE_INDEX_TYPE (t))
8701             SET_TYPE_INDEX_TYPE
8702               (nt, substitute_in_type (TYPE_INDEX_TYPE (t), f, r));
8703
8704           return nt;
8705         }
8706
8707       /* Then the subtypes.  */
8708       if (CONTAINS_PLACEHOLDER_P (TYPE_RM_MIN_VALUE (t))
8709           || CONTAINS_PLACEHOLDER_P (TYPE_RM_MAX_VALUE (t)))
8710         {
8711           tree low = SUBSTITUTE_IN_EXPR (TYPE_RM_MIN_VALUE (t), f, r);
8712           tree high = SUBSTITUTE_IN_EXPR (TYPE_RM_MAX_VALUE (t), f, r);
8713
8714           if (low == TYPE_RM_MIN_VALUE (t) && high == TYPE_RM_MAX_VALUE (t))
8715             return t;
8716
8717           nt = copy_type (t);
8718           SET_TYPE_RM_MIN_VALUE (nt, low);
8719           SET_TYPE_RM_MAX_VALUE (nt, high);
8720
8721           return nt;
8722         }
8723
8724       return t;
8725
8726     case COMPLEX_TYPE:
8727       nt = substitute_in_type (TREE_TYPE (t), f, r);
8728       if (nt == TREE_TYPE (t))
8729         return t;
8730
8731       return build_complex_type (nt);
8732
8733     case FUNCTION_TYPE:
8734       /* These should never show up here.  */
8735       gcc_unreachable ();
8736
8737     case ARRAY_TYPE:
8738       {
8739         tree component = substitute_in_type (TREE_TYPE (t), f, r);
8740         tree domain = substitute_in_type (TYPE_DOMAIN (t), f, r);
8741
8742         if (component == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
8743           return t;
8744
8745         nt = build_nonshared_array_type (component, domain);
8746         TYPE_ALIGN (nt) = TYPE_ALIGN (t);
8747         TYPE_USER_ALIGN (nt) = TYPE_USER_ALIGN (t);
8748         SET_TYPE_MODE (nt, TYPE_MODE (t));
8749         TYPE_SIZE (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE (t), f, r);
8750         TYPE_SIZE_UNIT (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE_UNIT (t), f, r);
8751         TYPE_NONALIASED_COMPONENT (nt) = TYPE_NONALIASED_COMPONENT (t);
8752         TYPE_MULTI_ARRAY_P (nt) = TYPE_MULTI_ARRAY_P (t);
8753         TYPE_CONVENTION_FORTRAN_P (nt) = TYPE_CONVENTION_FORTRAN_P (t);
8754         return nt;
8755       }
8756
8757     case RECORD_TYPE:
8758     case UNION_TYPE:
8759     case QUAL_UNION_TYPE:
8760       {
8761         bool changed_field = false;
8762         tree field;
8763
8764         /* Start out with no fields, make new fields, and chain them
8765            in.  If we haven't actually changed the type of any field,
8766            discard everything we've done and return the old type.  */
8767         nt = copy_type (t);
8768         TYPE_FIELDS (nt) = NULL_TREE;
8769
8770         for (field = TYPE_FIELDS (t); field; field = DECL_CHAIN (field))
8771           {
8772             tree new_field = copy_node (field), new_n;
8773
8774             new_n = substitute_in_type (TREE_TYPE (field), f, r);
8775             if (new_n != TREE_TYPE (field))
8776               {
8777                 TREE_TYPE (new_field) = new_n;
8778                 changed_field = true;
8779               }
8780
8781             new_n = SUBSTITUTE_IN_EXPR (DECL_FIELD_OFFSET (field), f, r);
8782             if (new_n != DECL_FIELD_OFFSET (field))
8783               {
8784                 DECL_FIELD_OFFSET (new_field) = new_n;
8785                 changed_field = true;
8786               }
8787
8788             /* Do the substitution inside the qualifier, if any.  */
8789             if (TREE_CODE (t) == QUAL_UNION_TYPE)
8790               {
8791                 new_n = SUBSTITUTE_IN_EXPR (DECL_QUALIFIER (field), f, r);
8792                 if (new_n != DECL_QUALIFIER (field))
8793                   {
8794                     DECL_QUALIFIER (new_field) = new_n;
8795                     changed_field = true;
8796                   }
8797               }
8798
8799             DECL_CONTEXT (new_field) = nt;
8800             SET_DECL_ORIGINAL_FIELD_TO_FIELD (new_field, field);
8801
8802             DECL_CHAIN (new_field) = TYPE_FIELDS (nt);
8803             TYPE_FIELDS (nt) = new_field;
8804           }
8805
8806         if (!changed_field)
8807           return t;
8808
8809         TYPE_FIELDS (nt) = nreverse (TYPE_FIELDS (nt));
8810         TYPE_SIZE (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE (t), f, r);
8811         TYPE_SIZE_UNIT (nt) = SUBSTITUTE_IN_EXPR (TYPE_SIZE_UNIT (t), f, r);
8812         SET_TYPE_ADA_SIZE (nt, SUBSTITUTE_IN_EXPR (TYPE_ADA_SIZE (t), f, r));
8813         return nt;
8814       }
8815
8816     default:
8817       return t;
8818     }
8819 }
8820 \f
8821 /* Return the RM size of GNU_TYPE.  This is the actual number of bits
8822    needed to represent the object.  */
8823
8824 tree
8825 rm_size (tree gnu_type)
8826 {
8827   /* For integral types, we store the RM size explicitly.  */
8828   if (INTEGRAL_TYPE_P (gnu_type) && TYPE_RM_SIZE (gnu_type))
8829     return TYPE_RM_SIZE (gnu_type);
8830
8831   /* Return the RM size of the actual data plus the size of the template.  */
8832   if (TREE_CODE (gnu_type) == RECORD_TYPE
8833       && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
8834     return
8835       size_binop (PLUS_EXPR,
8836                   rm_size (TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)))),
8837                   DECL_SIZE (TYPE_FIELDS (gnu_type)));
8838
8839   /* For record or union types, we store the size explicitly.  */
8840   if (RECORD_OR_UNION_TYPE_P (gnu_type)
8841       && !TYPE_FAT_POINTER_P (gnu_type)
8842       && TYPE_ADA_SIZE (gnu_type))
8843     return TYPE_ADA_SIZE (gnu_type);
8844
8845   /* For other types, this is just the size.  */
8846   return TYPE_SIZE (gnu_type);
8847 }
8848 \f
8849 /* Return the name to be used for GNAT_ENTITY.  If a type, create a
8850    fully-qualified name, possibly with type information encoding.
8851    Otherwise, return the name.  */
8852
8853 tree
8854 get_entity_name (Entity_Id gnat_entity)
8855 {
8856   Get_Encoded_Name (gnat_entity);
8857   return get_identifier_with_length (Name_Buffer, Name_Len);
8858 }
8859
8860 /* Return an identifier representing the external name to be used for
8861    GNAT_ENTITY.  If SUFFIX is specified, the name is followed by "___"
8862    and the specified suffix.  */
8863
8864 tree
8865 create_concat_name (Entity_Id gnat_entity, const char *suffix)
8866 {
8867   const Entity_Kind kind = Ekind (gnat_entity);
8868   const bool has_suffix = (suffix != NULL);
8869   String_Template temp = {1, has_suffix ? strlen (suffix) : 0};
8870   String_Pointer sp = {suffix, &temp};
8871
8872   Get_External_Name (gnat_entity, has_suffix, sp);
8873
8874   /* A variable using the Stdcall convention lives in a DLL.  We adjust
8875      its name to use the jump table, the _imp__NAME contains the address
8876      for the NAME variable.  */
8877   if ((kind == E_Variable || kind == E_Constant)
8878       && Has_Stdcall_Convention (gnat_entity))
8879     {
8880       const int len = strlen (STDCALL_PREFIX) + Name_Len;
8881       char *new_name = (char *) alloca (len + 1);
8882       strcpy (new_name, STDCALL_PREFIX);
8883       strcat (new_name, Name_Buffer);
8884       return get_identifier_with_length (new_name, len);
8885     }
8886
8887   return get_identifier_with_length (Name_Buffer, Name_Len);
8888 }
8889
8890 /* Given GNU_NAME, an IDENTIFIER_NODE containing a name and SUFFIX, a
8891    string, return a new IDENTIFIER_NODE that is the concatenation of
8892    the name followed by "___" and the specified suffix.  */
8893
8894 tree
8895 concat_name (tree gnu_name, const char *suffix)
8896 {
8897   const int len = IDENTIFIER_LENGTH (gnu_name) + 3 + strlen (suffix);
8898   char *new_name = (char *) alloca (len + 1);
8899   strcpy (new_name, IDENTIFIER_POINTER (gnu_name));
8900   strcat (new_name, "___");
8901   strcat (new_name, suffix);
8902   return get_identifier_with_length (new_name, len);
8903 }
8904
8905 /* Initialize data structures of the decl.c module.  */
8906
8907 void
8908 init_gnat_decl (void)
8909 {
8910   /* Initialize the cache of annotated values.  */
8911   annotate_value_cache = hash_table<value_annotation_hasher>::create_ggc (512);
8912 }
8913
8914 /* Destroy data structures of the decl.c module.  */
8915
8916 void
8917 destroy_gnat_decl (void)
8918 {
8919   /* Destroy the cache of annotated values.  */
8920   annotate_value_cache->empty ();
8921   annotate_value_cache = NULL;
8922 }
8923
8924 #include "gt-ada-decl.h"