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