OSDN Git Service

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