OSDN Git Service

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