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