OSDN Git Service

* gcc-interface/gigi.h (maybe_variable): Delete.
[pf3gnuchains/gcc-fork.git] / gcc / ada / gcc-interface / utils.c
1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                                U T I L S                                 *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *          Copyright (C) 1992-2010, Free Software Foundation, Inc.         *
10  *                                                                          *
11  * GNAT is free software;  you can  redistribute it  and/or modify it under *
12  * terms of the  GNU General Public License as published  by the Free Soft- *
13  * ware  Foundation;  either version 3,  or (at your option) any later ver- *
14  * sion.  GNAT is distributed in the hope that it will be useful, but WITH- *
15  * OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY *
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License *
17  * for  more details.  You should have received a copy of the GNU General   *
18  * Public License along with GCC; see the file COPYING3.  If not see        *
19  * <http://www.gnu.org/licenses/>.                                          *
20  *                                                                          *
21  * GNAT was originally developed  by the GNAT team at  New York University. *
22  * Extensive contributions were provided by Ada Core Technologies Inc.      *
23  *                                                                          *
24  ****************************************************************************/
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "tree.h"
31 #include "flags.h"
32 #include "toplev.h"
33 #include "rtl.h"
34 #include "output.h"
35 #include "ggc.h"
36 #include "debug.h"
37 #include "convert.h"
38 #include "target.h"
39 #include "function.h"
40 #include "langhooks.h"
41 #include "pointer-set.h"
42 #include "cgraph.h"
43 #include "tree-dump.h"
44 #include "tree-inline.h"
45 #include "tree-iterator.h"
46 #include "gimple.h"
47
48 #include "ada.h"
49 #include "types.h"
50 #include "atree.h"
51 #include "elists.h"
52 #include "namet.h"
53 #include "nlists.h"
54 #include "stringt.h"
55 #include "uintp.h"
56 #include "fe.h"
57 #include "sinfo.h"
58 #include "einfo.h"
59 #include "ada-tree.h"
60 #include "gigi.h"
61
62 #ifndef MAX_BITS_PER_WORD
63 #define MAX_BITS_PER_WORD  BITS_PER_WORD
64 #endif
65
66 /* If nonzero, pretend we are allocating at global level.  */
67 int force_global;
68
69 /* The default alignment of "double" floating-point types, i.e. floating
70    point types whose size is equal to 64 bits, or 0 if this alignment is
71    not specifically capped.  */
72 int double_float_alignment;
73
74 /* The default alignment of "double" or larger scalar types, i.e. scalar
75    types whose size is greater or equal to 64 bits, or 0 if this alignment
76    is not specifically capped.  */
77 int double_scalar_alignment;
78
79 /* Tree nodes for the various types and decls we create.  */
80 tree gnat_std_decls[(int) ADT_LAST];
81
82 /* Functions to call for each of the possible raise reasons.  */
83 tree gnat_raise_decls[(int) LAST_REASON_CODE + 1];
84
85 /* Forward declarations for handlers of attributes.  */
86 static tree handle_const_attribute (tree *, tree, tree, int, bool *);
87 static tree handle_nothrow_attribute (tree *, tree, tree, int, bool *);
88 static tree handle_pure_attribute (tree *, tree, tree, int, bool *);
89 static tree handle_novops_attribute (tree *, tree, tree, int, bool *);
90 static tree handle_nonnull_attribute (tree *, tree, tree, int, bool *);
91 static tree handle_sentinel_attribute (tree *, tree, tree, int, bool *);
92 static tree handle_noreturn_attribute (tree *, tree, tree, int, bool *);
93 static tree handle_malloc_attribute (tree *, tree, tree, int, bool *);
94 static tree handle_type_generic_attribute (tree *, tree, tree, int, bool *);
95 static tree handle_vector_size_attribute (tree *, tree, tree, int, bool *);
96 static tree handle_vector_type_attribute (tree *, tree, tree, int, bool *);
97
98 /* Fake handler for attributes we don't properly support, typically because
99    they'd require dragging a lot of the common-c front-end circuitry.  */
100 static tree fake_attribute_handler      (tree *, tree, tree, int, bool *);
101
102 /* Table of machine-independent internal attributes for Ada.  We support
103    this minimal set of attributes to accommodate the needs of builtins.  */
104 const struct attribute_spec gnat_internal_attribute_table[] =
105 {
106   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
107   { "const",        0, 0,  true,  false, false, handle_const_attribute   },
108   { "nothrow",      0, 0,  true,  false, false, handle_nothrow_attribute },
109   { "pure",         0, 0,  true,  false, false, handle_pure_attribute },
110   { "no vops",      0, 0,  true,  false, false, handle_novops_attribute },
111   { "nonnull",      0, -1, false, true,  true,  handle_nonnull_attribute },
112   { "sentinel",     0, 1,  false, true,  true,  handle_sentinel_attribute },
113   { "noreturn",     0, 0,  true,  false, false, handle_noreturn_attribute },
114   { "malloc",       0, 0,  true,  false, false, handle_malloc_attribute },
115   { "type generic", 0, 0,  false, true, true, handle_type_generic_attribute },
116
117   { "vector_size",  1, 1,  false, true, false,  handle_vector_size_attribute },
118   { "vector_type",  0, 0,  false, true, false,  handle_vector_type_attribute },
119   { "may_alias",    0, 0, false, true, false, NULL },
120
121   /* ??? format and format_arg are heavy and not supported, which actually
122      prevents support for stdio builtins, which we however declare as part
123      of the common builtins.def contents.  */
124   { "format",     3, 3,  false, true,  true,  fake_attribute_handler },
125   { "format_arg", 1, 1,  false, true,  true,  fake_attribute_handler },
126
127   { NULL,         0, 0, false, false, false, NULL }
128 };
129
130 /* Associates a GNAT tree node to a GCC tree node. It is used in
131    `save_gnu_tree', `get_gnu_tree' and `present_gnu_tree'. See documentation
132    of `save_gnu_tree' for more info.  */
133 static GTY((length ("max_gnat_nodes"))) tree *associate_gnat_to_gnu;
134
135 #define GET_GNU_TREE(GNAT_ENTITY)       \
136   associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id]
137
138 #define SET_GNU_TREE(GNAT_ENTITY,VAL)   \
139   associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id] = (VAL)
140
141 #define PRESENT_GNU_TREE(GNAT_ENTITY)   \
142   (associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id] != NULL_TREE)
143
144 /* Associates a GNAT entity to a GCC tree node used as a dummy, if any.  */
145 static GTY((length ("max_gnat_nodes"))) tree *dummy_node_table;
146
147 #define GET_DUMMY_NODE(GNAT_ENTITY)     \
148   dummy_node_table[(GNAT_ENTITY) - First_Node_Id]
149
150 #define SET_DUMMY_NODE(GNAT_ENTITY,VAL) \
151   dummy_node_table[(GNAT_ENTITY) - First_Node_Id] = (VAL)
152
153 #define PRESENT_DUMMY_NODE(GNAT_ENTITY) \
154   (dummy_node_table[(GNAT_ENTITY) - First_Node_Id] != NULL_TREE)
155
156 /* This variable keeps a table for types for each precision so that we only
157    allocate each of them once. Signed and unsigned types are kept separate.
158
159    Note that these types are only used when fold-const requests something
160    special.  Perhaps we should NOT share these types; we'll see how it
161    goes later.  */
162 static GTY(()) tree signed_and_unsigned_types[2 * MAX_BITS_PER_WORD + 1][2];
163
164 /* Likewise for float types, but record these by mode.  */
165 static GTY(()) tree float_types[NUM_MACHINE_MODES];
166
167 /* For each binding contour we allocate a binding_level structure to indicate
168    the binding depth.  */
169
170 struct GTY((chain_next ("%h.chain"))) gnat_binding_level {
171   /* The binding level containing this one (the enclosing binding level). */
172   struct gnat_binding_level *chain;
173   /* The BLOCK node for this level.  */
174   tree block;
175   /* If nonzero, the setjmp buffer that needs to be updated for any
176      variable-sized definition within this context.  */
177   tree jmpbuf_decl;
178 };
179
180 /* The binding level currently in effect.  */
181 static GTY(()) struct gnat_binding_level *current_binding_level;
182
183 /* A chain of gnat_binding_level structures awaiting reuse.  */
184 static GTY((deletable)) struct gnat_binding_level *free_binding_level;
185
186 /* An array of global declarations.  */
187 static GTY(()) VEC(tree,gc) *global_decls;
188
189 /* An array of builtin function declarations.  */
190 static GTY(()) VEC(tree,gc) *builtin_decls;
191
192 /* An array of global renaming pointers.  */
193 static GTY(()) VEC(tree,gc) *global_renaming_pointers;
194
195 /* A chain of unused BLOCK nodes. */
196 static GTY((deletable)) tree free_block_chain;
197
198 static tree merge_sizes (tree, tree, tree, bool, bool);
199 static tree compute_related_constant (tree, tree);
200 static tree split_plus (tree, tree *);
201 static tree float_type_for_precision (int, enum machine_mode);
202 static tree convert_to_fat_pointer (tree, tree);
203 static tree convert_to_thin_pointer (tree, tree);
204 static tree make_descriptor_field (const char *,tree, tree, tree);
205 static bool potential_alignment_gap (tree, tree, tree);
206 \f
207 /* Initialize the association of GNAT nodes to GCC trees.  */
208
209 void
210 init_gnat_to_gnu (void)
211 {
212   associate_gnat_to_gnu
213     = (tree *) ggc_alloc_cleared (max_gnat_nodes * sizeof (tree));
214 }
215
216 /* GNAT_ENTITY is a GNAT tree node for an entity.   GNU_DECL is the GCC tree
217    which is to be associated with GNAT_ENTITY. Such GCC tree node is always
218    a ..._DECL node.  If NO_CHECK is true, the latter check is suppressed.
219
220    If GNU_DECL is zero, a previous association is to be reset.  */
221
222 void
223 save_gnu_tree (Entity_Id gnat_entity, tree gnu_decl, bool no_check)
224 {
225   /* Check that GNAT_ENTITY is not already defined and that it is being set
226      to something which is a decl.  Raise gigi 401 if not.  Usually, this
227      means GNAT_ENTITY is defined twice, but occasionally is due to some
228      Gigi problem.  */
229   gcc_assert (!(gnu_decl
230                 && (PRESENT_GNU_TREE (gnat_entity)
231                     || (!no_check && !DECL_P (gnu_decl)))));
232
233   SET_GNU_TREE (gnat_entity, gnu_decl);
234 }
235
236 /* GNAT_ENTITY is a GNAT tree node for a defining identifier.
237    Return the ..._DECL node that was associated with it.  If there is no tree
238    node associated with GNAT_ENTITY, abort.
239
240    In some cases, such as delayed elaboration or expressions that need to
241    be elaborated only once, GNAT_ENTITY is really not an entity.  */
242
243 tree
244 get_gnu_tree (Entity_Id gnat_entity)
245 {
246   gcc_assert (PRESENT_GNU_TREE (gnat_entity));
247   return GET_GNU_TREE (gnat_entity);
248 }
249
250 /* Return nonzero if a GCC tree has been associated with GNAT_ENTITY.  */
251
252 bool
253 present_gnu_tree (Entity_Id gnat_entity)
254 {
255   return PRESENT_GNU_TREE (gnat_entity);
256 }
257 \f
258 /* Initialize the association of GNAT nodes to GCC trees as dummies.  */
259
260 void
261 init_dummy_type (void)
262 {
263   dummy_node_table
264     = (tree *) ggc_alloc_cleared (max_gnat_nodes * sizeof (tree));
265 }
266
267 /* Make a dummy type corresponding to GNAT_TYPE.  */
268
269 tree
270 make_dummy_type (Entity_Id gnat_type)
271 {
272   Entity_Id gnat_underlying = Gigi_Equivalent_Type (gnat_type);
273   tree gnu_type;
274
275   /* If there is an equivalent type, get its underlying type.  */
276   if (Present (gnat_underlying))
277     gnat_underlying = Underlying_Type (gnat_underlying);
278
279   /* If there was no equivalent type (can only happen when just annotating
280      types) or underlying type, go back to the original type.  */
281   if (No (gnat_underlying))
282     gnat_underlying = gnat_type;
283
284   /* If it there already a dummy type, use that one.  Else make one.  */
285   if (PRESENT_DUMMY_NODE (gnat_underlying))
286     return GET_DUMMY_NODE (gnat_underlying);
287
288   /* If this is a record, make a RECORD_TYPE or UNION_TYPE; else make
289      an ENUMERAL_TYPE.  */
290   gnu_type = make_node (Is_Record_Type (gnat_underlying)
291                         ? tree_code_for_record_type (gnat_underlying)
292                         : ENUMERAL_TYPE);
293   TYPE_NAME (gnu_type) = get_entity_name (gnat_type);
294   TYPE_DUMMY_P (gnu_type) = 1;
295   TYPE_STUB_DECL (gnu_type)
296     = create_type_stub_decl (TYPE_NAME (gnu_type), gnu_type);
297   if (AGGREGATE_TYPE_P (gnu_type))
298     TYPE_BY_REFERENCE_P (gnu_type) = Is_By_Reference_Type (gnat_type);
299
300   SET_DUMMY_NODE (gnat_underlying, gnu_type);
301
302   return gnu_type;
303 }
304 \f
305 /* Return nonzero if we are currently in the global binding level.  */
306
307 int
308 global_bindings_p (void)
309 {
310   return ((force_global || !current_function_decl) ? -1 : 0);
311 }
312
313 /* Enter a new binding level. */
314
315 void
316 gnat_pushlevel (void)
317 {
318   struct gnat_binding_level *newlevel = NULL;
319
320   /* Reuse a struct for this binding level, if there is one.  */
321   if (free_binding_level)
322     {
323       newlevel = free_binding_level;
324       free_binding_level = free_binding_level->chain;
325     }
326   else
327     newlevel
328       = (struct gnat_binding_level *)
329         ggc_alloc (sizeof (struct gnat_binding_level));
330
331   /* Use a free BLOCK, if any; otherwise, allocate one.  */
332   if (free_block_chain)
333     {
334       newlevel->block = free_block_chain;
335       free_block_chain = BLOCK_CHAIN (free_block_chain);
336       BLOCK_CHAIN (newlevel->block) = NULL_TREE;
337     }
338   else
339     newlevel->block = make_node (BLOCK);
340
341   /* Point the BLOCK we just made to its parent.  */
342   if (current_binding_level)
343     BLOCK_SUPERCONTEXT (newlevel->block) = current_binding_level->block;
344
345   BLOCK_VARS (newlevel->block) = BLOCK_SUBBLOCKS (newlevel->block) = NULL_TREE;
346   TREE_USED (newlevel->block) = 1;
347
348   /* Add this level to the front of the chain (stack) of levels that are
349      active.  */
350   newlevel->chain = current_binding_level;
351   newlevel->jmpbuf_decl = NULL_TREE;
352   current_binding_level = newlevel;
353 }
354
355 /* Set SUPERCONTEXT of the BLOCK for the current binding level to FNDECL
356    and point FNDECL to this BLOCK.  */
357
358 void
359 set_current_block_context (tree fndecl)
360 {
361   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
362   DECL_INITIAL (fndecl) = current_binding_level->block;
363 }
364
365 /* Set the jmpbuf_decl for the current binding level to DECL.  */
366
367 void
368 set_block_jmpbuf_decl (tree decl)
369 {
370   current_binding_level->jmpbuf_decl = decl;
371 }
372
373 /* Get the jmpbuf_decl, if any, for the current binding level.  */
374
375 tree
376 get_block_jmpbuf_decl (void)
377 {
378   return current_binding_level->jmpbuf_decl;
379 }
380
381 /* Exit a binding level. Set any BLOCK into the current code group.  */
382
383 void
384 gnat_poplevel (void)
385 {
386   struct gnat_binding_level *level = current_binding_level;
387   tree block = level->block;
388
389   BLOCK_VARS (block) = nreverse (BLOCK_VARS (block));
390   BLOCK_SUBBLOCKS (block) = nreverse (BLOCK_SUBBLOCKS (block));
391
392   /* If this is a function-level BLOCK don't do anything.  Otherwise, if there
393      are no variables free the block and merge its subblocks into those of its
394      parent block. Otherwise, add it to the list of its parent.  */
395   if (TREE_CODE (BLOCK_SUPERCONTEXT (block)) == FUNCTION_DECL)
396     ;
397   else if (BLOCK_VARS (block) == NULL_TREE)
398     {
399       BLOCK_SUBBLOCKS (level->chain->block)
400         = chainon (BLOCK_SUBBLOCKS (block),
401                    BLOCK_SUBBLOCKS (level->chain->block));
402       BLOCK_CHAIN (block) = free_block_chain;
403       free_block_chain = block;
404     }
405   else
406     {
407       BLOCK_CHAIN (block) = BLOCK_SUBBLOCKS (level->chain->block);
408       BLOCK_SUBBLOCKS (level->chain->block) = block;
409       TREE_USED (block) = 1;
410       set_block_for_group (block);
411     }
412
413   /* Free this binding structure.  */
414   current_binding_level = level->chain;
415   level->chain = free_binding_level;
416   free_binding_level = level;
417 }
418
419 \f
420 /* Records a ..._DECL node DECL as belonging to the current lexical scope
421    and uses GNAT_NODE for location information and propagating flags.  */
422
423 void
424 gnat_pushdecl (tree decl, Node_Id gnat_node)
425 {
426   /* If this decl is public external or at toplevel, there is no context.
427      But PARM_DECLs always go in the level of its function.  */
428   if (TREE_CODE (decl) != PARM_DECL
429       && ((DECL_EXTERNAL (decl) && TREE_PUBLIC (decl))
430           || global_bindings_p ()))
431     DECL_CONTEXT (decl) = 0;
432   else
433     {
434       DECL_CONTEXT (decl) = current_function_decl;
435
436       /* Functions imported in another function are not really nested.
437          For really nested functions mark them initially as needing
438          a static chain for uses of that flag before unnesting;
439          lower_nested_functions will then recompute it.  */
440       if (TREE_CODE (decl) == FUNCTION_DECL && !TREE_PUBLIC (decl))
441         DECL_STATIC_CHAIN (decl) = 1;
442     }
443
444   TREE_NO_WARNING (decl) = (gnat_node == Empty || Warnings_Off (gnat_node));
445
446   /* Set the location of DECL and emit a declaration for it.  */
447   if (Present (gnat_node))
448     Sloc_to_locus (Sloc (gnat_node), &DECL_SOURCE_LOCATION (decl));
449   add_decl_expr (decl, gnat_node);
450
451   /* Put the declaration on the list.  The list of declarations is in reverse
452      order.  The list will be reversed later.  Put global variables in the
453      globals list and builtin functions in a dedicated list to speed up
454      further lookups.  Don't put TYPE_DECLs for UNCONSTRAINED_ARRAY_TYPE into
455      the list, as they will cause trouble with the debugger and aren't needed
456      anyway.  */
457   if (TREE_CODE (decl) != TYPE_DECL
458       || TREE_CODE (TREE_TYPE (decl)) != UNCONSTRAINED_ARRAY_TYPE)
459     {
460       if (global_bindings_p ())
461         {
462           VEC_safe_push (tree, gc, global_decls, decl);
463
464           if (TREE_CODE (decl) == FUNCTION_DECL && DECL_BUILT_IN (decl))
465             VEC_safe_push (tree, gc, builtin_decls, decl);
466         }
467       else
468         {
469           TREE_CHAIN (decl) = BLOCK_VARS (current_binding_level->block);
470           BLOCK_VARS (current_binding_level->block) = decl;
471         }
472     }
473
474   /* For the declaration of a type, set its name if it either is not already
475      set or if the previous type name was not derived from a source name.
476      We'd rather have the type named with a real name and all the pointer
477      types to the same object have the same POINTER_TYPE node.  Code in the
478      equivalent function of c-decl.c makes a copy of the type node here, but
479      that may cause us trouble with incomplete types.  We make an exception
480      for fat pointer types because the compiler automatically builds them
481      for unconstrained array types and the debugger uses them to represent
482      both these and pointers to these.  */
483   if (TREE_CODE (decl) == TYPE_DECL && DECL_NAME (decl))
484     {
485       tree t = TREE_TYPE (decl);
486
487       if (!(TYPE_NAME (t) && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL))
488         ;
489       else if (TYPE_IS_FAT_POINTER_P (t))
490         {
491           tree tt = build_variant_type_copy (t);
492           TYPE_NAME (tt) = decl;
493           TREE_USED (tt) = TREE_USED (t);
494           TREE_TYPE (decl) = tt;
495           if (DECL_ORIGINAL_TYPE (TYPE_NAME (t)))
496             DECL_ORIGINAL_TYPE (decl) = DECL_ORIGINAL_TYPE (TYPE_NAME (t));
497           else
498             DECL_ORIGINAL_TYPE (decl) = t;
499           t = NULL_TREE;
500           DECL_ARTIFICIAL (decl) = 0;
501         }
502       else if (DECL_ARTIFICIAL (TYPE_NAME (t)) && !DECL_ARTIFICIAL (decl))
503         ;
504       else
505         t = NULL_TREE;
506
507       /* Propagate the name to all the variants.  This is needed for
508          the type qualifiers machinery to work properly.  */
509       if (t)
510         for (t = TYPE_MAIN_VARIANT (t); t; t = TYPE_NEXT_VARIANT (t))
511           TYPE_NAME (t) = decl;
512     }
513 }
514 \f
515 /* Do little here.  Set up the standard declarations later after the
516    front end has been run.  */
517
518 void
519 gnat_init_decl_processing (void)
520 {
521   /* Make the binding_level structure for global names.  */
522   current_function_decl = 0;
523   current_binding_level = 0;
524   free_binding_level = 0;
525   gnat_pushlevel ();
526
527   build_common_tree_nodes (true, true);
528
529   /* In Ada, we use a signed type for SIZETYPE.  Use the signed type
530      corresponding to the width of Pmode.  In most cases when ptr_mode
531      and Pmode differ, C will use the width of ptr_mode for SIZETYPE.
532      But we get far better code using the width of Pmode.  */
533   size_type_node = gnat_type_for_mode (Pmode, 0);
534   set_sizetype (size_type_node);
535
536   /* In Ada, we use an unsigned 8-bit type for the default boolean type.  */
537   boolean_type_node = make_unsigned_type (8);
538   TREE_SET_CODE (boolean_type_node, BOOLEAN_TYPE);
539   SET_TYPE_RM_MAX_VALUE (boolean_type_node,
540                          build_int_cst (boolean_type_node, 1));
541   SET_TYPE_RM_SIZE (boolean_type_node, bitsize_int (1));
542
543   build_common_tree_nodes_2 (0);
544   boolean_true_node = TYPE_MAX_VALUE (boolean_type_node);
545
546   ptr_void_type_node = build_pointer_type (void_type_node);
547 }
548 \f
549 /* Record TYPE as a builtin type for Ada.  NAME is the name of the type.  */
550
551 void
552 record_builtin_type (const char *name, tree type)
553 {
554   tree type_decl = build_decl (input_location,
555                                TYPE_DECL, get_identifier (name), type);
556
557   gnat_pushdecl (type_decl, Empty);
558
559   if (debug_hooks->type_decl)
560     debug_hooks->type_decl (type_decl, false);
561 }
562 \f
563 /* Given a record type RECORD_TYPE and a list of FIELD_DECL nodes FIELD_LIST,
564    finish constructing the record or union type.  If REP_LEVEL is zero, this
565    record has no representation clause and so will be entirely laid out here.
566    If REP_LEVEL is one, this record has a representation clause and has been
567    laid out already; only set the sizes and alignment.  If REP_LEVEL is two,
568    this record is derived from a parent record and thus inherits its layout;
569    only make a pass on the fields to finalize them.  DEBUG_INFO_P is true if
570    we need to write debug information about this type.  */
571
572 void
573 finish_record_type (tree record_type, tree field_list, int rep_level,
574                     bool debug_info_p)
575 {
576   enum tree_code code = TREE_CODE (record_type);
577   tree name = TYPE_NAME (record_type);
578   tree ada_size = bitsize_zero_node;
579   tree size = bitsize_zero_node;
580   bool had_size = TYPE_SIZE (record_type) != 0;
581   bool had_size_unit = TYPE_SIZE_UNIT (record_type) != 0;
582   bool had_align = TYPE_ALIGN (record_type) != 0;
583   tree field;
584
585   TYPE_FIELDS (record_type) = field_list;
586
587   /* Always attach the TYPE_STUB_DECL for a record type.  It is required to
588      generate debug info and have a parallel type.  */
589   if (name && TREE_CODE (name) == TYPE_DECL)
590     name = DECL_NAME (name);
591   TYPE_STUB_DECL (record_type) = create_type_stub_decl (name, record_type);
592
593   /* Globally initialize the record first.  If this is a rep'ed record,
594      that just means some initializations; otherwise, layout the record.  */
595   if (rep_level > 0)
596     {
597       TYPE_ALIGN (record_type) = MAX (BITS_PER_UNIT, TYPE_ALIGN (record_type));
598
599       if (!had_size_unit)
600         TYPE_SIZE_UNIT (record_type) = size_zero_node;
601
602       if (!had_size)
603         TYPE_SIZE (record_type) = bitsize_zero_node;
604
605       /* For all-repped records with a size specified, lay the QUAL_UNION_TYPE
606          out just like a UNION_TYPE, since the size will be fixed.  */
607       else if (code == QUAL_UNION_TYPE)
608         code = UNION_TYPE;
609     }
610   else
611     {
612       /* Ensure there isn't a size already set.  There can be in an error
613          case where there is a rep clause but all fields have errors and
614          no longer have a position.  */
615       TYPE_SIZE (record_type) = 0;
616       layout_type (record_type);
617     }
618
619   /* At this point, the position and size of each field is known.  It was
620      either set before entry by a rep clause, or by laying out the type above.
621
622      We now run a pass over the fields (in reverse order for QUAL_UNION_TYPEs)
623      to compute the Ada size; the GCC size and alignment (for rep'ed records
624      that are not padding types); and the mode (for rep'ed records).  We also
625      clear the DECL_BIT_FIELD indication for the cases we know have not been
626      handled yet, and adjust DECL_NONADDRESSABLE_P accordingly.  */
627
628   if (code == QUAL_UNION_TYPE)
629     field_list = nreverse (field_list);
630
631   for (field = field_list; field; field = TREE_CHAIN (field))
632     {
633       tree type = TREE_TYPE (field);
634       tree pos = bit_position (field);
635       tree this_size = DECL_SIZE (field);
636       tree this_ada_size;
637
638       if ((TREE_CODE (type) == RECORD_TYPE
639            || TREE_CODE (type) == UNION_TYPE
640            || TREE_CODE (type) == QUAL_UNION_TYPE)
641           && !TYPE_FAT_POINTER_P (type)
642           && !TYPE_CONTAINS_TEMPLATE_P (type)
643           && TYPE_ADA_SIZE (type))
644         this_ada_size = TYPE_ADA_SIZE (type);
645       else
646         this_ada_size = this_size;
647
648       /* Clear DECL_BIT_FIELD for the cases layout_decl does not handle.  */
649       if (DECL_BIT_FIELD (field)
650           && operand_equal_p (this_size, TYPE_SIZE (type), 0))
651         {
652           unsigned int align = TYPE_ALIGN (type);
653
654           /* In the general case, type alignment is required.  */
655           if (value_factor_p (pos, align))
656             {
657               /* The enclosing record type must be sufficiently aligned.
658                  Otherwise, if no alignment was specified for it and it
659                  has been laid out already, bump its alignment to the
660                  desired one if this is compatible with its size.  */
661               if (TYPE_ALIGN (record_type) >= align)
662                 {
663                   DECL_ALIGN (field) = MAX (DECL_ALIGN (field), align);
664                   DECL_BIT_FIELD (field) = 0;
665                 }
666               else if (!had_align
667                        && rep_level == 0
668                        && value_factor_p (TYPE_SIZE (record_type), align))
669                 {
670                   TYPE_ALIGN (record_type) = align;
671                   DECL_ALIGN (field) = MAX (DECL_ALIGN (field), align);
672                   DECL_BIT_FIELD (field) = 0;
673                 }
674             }
675
676           /* In the non-strict alignment case, only byte alignment is.  */
677           if (!STRICT_ALIGNMENT
678               && DECL_BIT_FIELD (field)
679               && value_factor_p (pos, BITS_PER_UNIT))
680             DECL_BIT_FIELD (field) = 0;
681         }
682
683       /* If we still have DECL_BIT_FIELD set at this point, we know that the
684          field is technically not addressable.  Except that it can actually
685          be addressed if it is BLKmode and happens to be properly aligned.  */
686       if (DECL_BIT_FIELD (field)
687           && !(DECL_MODE (field) == BLKmode
688                && value_factor_p (pos, BITS_PER_UNIT)))
689         DECL_NONADDRESSABLE_P (field) = 1;
690
691       /* A type must be as aligned as its most aligned field that is not
692          a bit-field.  But this is already enforced by layout_type.  */
693       if (rep_level > 0 && !DECL_BIT_FIELD (field))
694         TYPE_ALIGN (record_type)
695           = MAX (TYPE_ALIGN (record_type), DECL_ALIGN (field));
696
697       switch (code)
698         {
699         case UNION_TYPE:
700           ada_size = size_binop (MAX_EXPR, ada_size, this_ada_size);
701           size = size_binop (MAX_EXPR, size, this_size);
702           break;
703
704         case QUAL_UNION_TYPE:
705           ada_size
706             = fold_build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
707                            this_ada_size, ada_size);
708           size = fold_build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
709                               this_size, size);
710           break;
711
712         case RECORD_TYPE:
713           /* Since we know here that all fields are sorted in order of
714              increasing bit position, the size of the record is one
715              higher than the ending bit of the last field processed
716              unless we have a rep clause, since in that case we might
717              have a field outside a QUAL_UNION_TYPE that has a higher ending
718              position.  So use a MAX in that case.  Also, if this field is a
719              QUAL_UNION_TYPE, we need to take into account the previous size in
720              the case of empty variants.  */
721           ada_size
722             = merge_sizes (ada_size, pos, this_ada_size,
723                            TREE_CODE (type) == QUAL_UNION_TYPE, rep_level > 0);
724           size
725             = merge_sizes (size, pos, this_size,
726                            TREE_CODE (type) == QUAL_UNION_TYPE, rep_level > 0);
727           break;
728
729         default:
730           gcc_unreachable ();
731         }
732     }
733
734   if (code == QUAL_UNION_TYPE)
735     nreverse (field_list);
736
737   if (rep_level < 2)
738     {
739       /* If this is a padding record, we never want to make the size smaller
740          than what was specified in it, if any.  */
741       if (TYPE_IS_PADDING_P (record_type) && TYPE_SIZE (record_type))
742         size = TYPE_SIZE (record_type);
743
744       /* Now set any of the values we've just computed that apply.  */
745       if (!TYPE_FAT_POINTER_P (record_type)
746           && !TYPE_CONTAINS_TEMPLATE_P (record_type))
747         SET_TYPE_ADA_SIZE (record_type, ada_size);
748
749       if (rep_level > 0)
750         {
751           tree size_unit = had_size_unit
752                            ? TYPE_SIZE_UNIT (record_type)
753                            : convert (sizetype,
754                                       size_binop (CEIL_DIV_EXPR, size,
755                                                   bitsize_unit_node));
756           unsigned int align = TYPE_ALIGN (record_type);
757
758           TYPE_SIZE (record_type) = variable_size (round_up (size, align));
759           TYPE_SIZE_UNIT (record_type)
760             = variable_size (round_up (size_unit, align / BITS_PER_UNIT));
761
762           compute_record_mode (record_type);
763         }
764     }
765
766   if (debug_info_p)
767     rest_of_record_type_compilation (record_type);
768 }
769
770 /* Wrap up compilation of RECORD_TYPE, i.e. output all the debug information
771    associated with it.  It need not be invoked directly in most cases since
772    finish_record_type takes care of doing so, but this can be necessary if
773    a parallel type is to be attached to the record type.  */
774
775 void
776 rest_of_record_type_compilation (tree record_type)
777 {
778   tree field_list = TYPE_FIELDS (record_type);
779   tree field;
780   enum tree_code code = TREE_CODE (record_type);
781   bool var_size = false;
782
783   for (field = field_list; field; field = TREE_CHAIN (field))
784     {
785       /* We need to make an XVE/XVU record if any field has variable size,
786          whether or not the record does.  For example, if we have a union,
787          it may be that all fields, rounded up to the alignment, have the
788          same size, in which case we'll use that size.  But the debug
789          output routines (except Dwarf2) won't be able to output the fields,
790          so we need to make the special record.  */
791       if (TREE_CODE (DECL_SIZE (field)) != INTEGER_CST
792           /* If a field has a non-constant qualifier, the record will have
793              variable size too.  */
794           || (code == QUAL_UNION_TYPE
795               && TREE_CODE (DECL_QUALIFIER (field)) != INTEGER_CST))
796         {
797           var_size = true;
798           break;
799         }
800     }
801
802   /* If this record is of variable size, rename it so that the
803      debugger knows it is and make a new, parallel, record
804      that tells the debugger how the record is laid out.  See
805      exp_dbug.ads.  But don't do this for records that are padding
806      since they confuse GDB.  */
807   if (var_size && !TYPE_IS_PADDING_P (record_type))
808     {
809       tree new_record_type
810         = make_node (TREE_CODE (record_type) == QUAL_UNION_TYPE
811                      ? UNION_TYPE : TREE_CODE (record_type));
812       tree orig_name = TYPE_NAME (record_type), new_name;
813       tree last_pos = bitsize_zero_node;
814       tree old_field, prev_old_field = NULL_TREE;
815
816       if (TREE_CODE (orig_name) == TYPE_DECL)
817         orig_name = DECL_NAME (orig_name);
818
819       new_name
820         = concat_name (orig_name, TREE_CODE (record_type) == QUAL_UNION_TYPE
821                                   ? "XVU" : "XVE");
822       TYPE_NAME (new_record_type) = new_name;
823       TYPE_ALIGN (new_record_type) = BIGGEST_ALIGNMENT;
824       TYPE_STUB_DECL (new_record_type)
825         = create_type_stub_decl (new_name, new_record_type);
826       DECL_IGNORED_P (TYPE_STUB_DECL (new_record_type))
827         = DECL_IGNORED_P (TYPE_STUB_DECL (record_type));
828       TYPE_SIZE (new_record_type) = size_int (TYPE_ALIGN (record_type));
829       TYPE_SIZE_UNIT (new_record_type)
830         = size_int (TYPE_ALIGN (record_type) / BITS_PER_UNIT);
831
832       add_parallel_type (TYPE_STUB_DECL (record_type), new_record_type);
833
834       /* Now scan all the fields, replacing each field with a new
835          field corresponding to the new encoding.  */
836       for (old_field = TYPE_FIELDS (record_type); old_field;
837            old_field = TREE_CHAIN (old_field))
838         {
839           tree field_type = TREE_TYPE (old_field);
840           tree field_name = DECL_NAME (old_field);
841           tree new_field;
842           tree curpos = bit_position (old_field);
843           bool var = false;
844           unsigned int align = 0;
845           tree pos;
846
847           /* See how the position was modified from the last position.
848
849           There are two basic cases we support: a value was added
850           to the last position or the last position was rounded to
851           a boundary and they something was added.  Check for the
852           first case first.  If not, see if there is any evidence
853           of rounding.  If so, round the last position and try
854           again.
855
856           If this is a union, the position can be taken as zero. */
857
858           /* Some computations depend on the shape of the position expression,
859              so strip conversions to make sure it's exposed.  */
860           curpos = remove_conversions (curpos, true);
861
862           if (TREE_CODE (new_record_type) == UNION_TYPE)
863             pos = bitsize_zero_node, align = 0;
864           else
865             pos = compute_related_constant (curpos, last_pos);
866
867           if (!pos && TREE_CODE (curpos) == MULT_EXPR
868               && host_integerp (TREE_OPERAND (curpos, 1), 1))
869             {
870               tree offset = TREE_OPERAND (curpos, 0);
871               align = tree_low_cst (TREE_OPERAND (curpos, 1), 1);
872
873               /* An offset which is a bitwise AND with a negative power of 2
874                  means an alignment corresponding to this power of 2.  */
875               offset = remove_conversions (offset, true);
876               if (TREE_CODE (offset) == BIT_AND_EXPR
877                   && host_integerp (TREE_OPERAND (offset, 1), 0)
878                   && tree_int_cst_sgn (TREE_OPERAND (offset, 1)) < 0)
879                 {
880                   unsigned int pow
881                     = - tree_low_cst (TREE_OPERAND (offset, 1), 0);
882                   if (exact_log2 (pow) > 0)
883                     align *= pow;
884                 }
885
886               pos = compute_related_constant (curpos,
887                                               round_up (last_pos, align));
888             }
889           else if (!pos && TREE_CODE (curpos) == PLUS_EXPR
890                    && TREE_CODE (TREE_OPERAND (curpos, 1)) == INTEGER_CST
891                    && TREE_CODE (TREE_OPERAND (curpos, 0)) == MULT_EXPR
892                    && host_integerp (TREE_OPERAND
893                                      (TREE_OPERAND (curpos, 0), 1),
894                                      1))
895             {
896               align
897                 = tree_low_cst
898                 (TREE_OPERAND (TREE_OPERAND (curpos, 0), 1), 1);
899               pos = compute_related_constant (curpos,
900                                               round_up (last_pos, align));
901             }
902           else if (potential_alignment_gap (prev_old_field, old_field,
903                                             pos))
904             {
905               align = TYPE_ALIGN (field_type);
906               pos = compute_related_constant (curpos,
907                                               round_up (last_pos, align));
908             }
909
910           /* If we can't compute a position, set it to zero.
911
912           ??? We really should abort here, but it's too much work
913           to get this correct for all cases.  */
914
915           if (!pos)
916             pos = bitsize_zero_node;
917
918           /* See if this type is variable-sized and make a pointer type
919              and indicate the indirection if so.  Beware that the debug
920              back-end may adjust the position computed above according
921              to the alignment of the field type, i.e. the pointer type
922              in this case, if we don't preventively counter that.  */
923           if (TREE_CODE (DECL_SIZE (old_field)) != INTEGER_CST)
924             {
925               field_type = build_pointer_type (field_type);
926               if (align != 0 && TYPE_ALIGN (field_type) > align)
927                 {
928                   field_type = copy_node (field_type);
929                   TYPE_ALIGN (field_type) = align;
930                 }
931               var = true;
932             }
933
934           /* Make a new field name, if necessary.  */
935           if (var || align != 0)
936             {
937               char suffix[16];
938
939               if (align != 0)
940                 sprintf (suffix, "XV%c%u", var ? 'L' : 'A',
941                          align / BITS_PER_UNIT);
942               else
943                 strcpy (suffix, "XVL");
944
945               field_name = concat_name (field_name, suffix);
946             }
947
948           new_field = create_field_decl (field_name, field_type,
949                                          new_record_type, 0,
950                                          DECL_SIZE (old_field), pos, 0);
951           TREE_CHAIN (new_field) = TYPE_FIELDS (new_record_type);
952           TYPE_FIELDS (new_record_type) = new_field;
953
954           /* If old_field is a QUAL_UNION_TYPE, take its size as being
955              zero.  The only time it's not the last field of the record
956              is when there are other components at fixed positions after
957              it (meaning there was a rep clause for every field) and we
958              want to be able to encode them.  */
959           last_pos = size_binop (PLUS_EXPR, bit_position (old_field),
960                                  (TREE_CODE (TREE_TYPE (old_field))
961                                   == QUAL_UNION_TYPE)
962                                  ? bitsize_zero_node
963                                  : DECL_SIZE (old_field));
964           prev_old_field = old_field;
965         }
966
967       TYPE_FIELDS (new_record_type)
968         = nreverse (TYPE_FIELDS (new_record_type));
969
970       rest_of_type_decl_compilation (TYPE_STUB_DECL (new_record_type));
971     }
972
973   rest_of_type_decl_compilation (TYPE_STUB_DECL (record_type));
974 }
975
976 /* Append PARALLEL_TYPE on the chain of parallel types for decl.  */
977
978 void
979 add_parallel_type (tree decl, tree parallel_type)
980 {
981   tree d = decl;
982
983   while (DECL_PARALLEL_TYPE (d))
984     d = TYPE_STUB_DECL (DECL_PARALLEL_TYPE (d));
985
986   SET_DECL_PARALLEL_TYPE (d, parallel_type);
987 }
988
989 /* Return the parallel type associated to a type, if any.  */
990
991 tree
992 get_parallel_type (tree type)
993 {
994   if (TYPE_STUB_DECL (type))
995     return DECL_PARALLEL_TYPE (TYPE_STUB_DECL (type));
996   else
997     return NULL_TREE;
998 }
999
1000 /* Utility function of above to merge LAST_SIZE, the previous size of a record
1001    with FIRST_BIT and SIZE that describe a field.  SPECIAL is true if this
1002    represents a QUAL_UNION_TYPE in which case we must look for COND_EXPRs and
1003    replace a value of zero with the old size.  If HAS_REP is true, we take the
1004    MAX of the end position of this field with LAST_SIZE.  In all other cases,
1005    we use FIRST_BIT plus SIZE.  Return an expression for the size.  */
1006
1007 static tree
1008 merge_sizes (tree last_size, tree first_bit, tree size, bool special,
1009              bool has_rep)
1010 {
1011   tree type = TREE_TYPE (last_size);
1012   tree new_size;
1013
1014   if (!special || TREE_CODE (size) != COND_EXPR)
1015     {
1016       new_size = size_binop (PLUS_EXPR, first_bit, size);
1017       if (has_rep)
1018         new_size = size_binop (MAX_EXPR, last_size, new_size);
1019     }
1020
1021   else
1022     new_size = fold_build3 (COND_EXPR, type, TREE_OPERAND (size, 0),
1023                             integer_zerop (TREE_OPERAND (size, 1))
1024                             ? last_size : merge_sizes (last_size, first_bit,
1025                                                        TREE_OPERAND (size, 1),
1026                                                        1, has_rep),
1027                             integer_zerop (TREE_OPERAND (size, 2))
1028                             ? last_size : merge_sizes (last_size, first_bit,
1029                                                        TREE_OPERAND (size, 2),
1030                                                        1, has_rep));
1031
1032   /* We don't need any NON_VALUE_EXPRs and they can confuse us (especially
1033      when fed through substitute_in_expr) into thinking that a constant
1034      size is not constant.  */
1035   while (TREE_CODE (new_size) == NON_LVALUE_EXPR)
1036     new_size = TREE_OPERAND (new_size, 0);
1037
1038   return new_size;
1039 }
1040
1041 /* Utility function of above to see if OP0 and OP1, both of SIZETYPE, are
1042    related by the addition of a constant.  Return that constant if so.  */
1043
1044 static tree
1045 compute_related_constant (tree op0, tree op1)
1046 {
1047   tree op0_var, op1_var;
1048   tree op0_con = split_plus (op0, &op0_var);
1049   tree op1_con = split_plus (op1, &op1_var);
1050   tree result = size_binop (MINUS_EXPR, op0_con, op1_con);
1051
1052   if (operand_equal_p (op0_var, op1_var, 0))
1053     return result;
1054   else if (operand_equal_p (op0, size_binop (PLUS_EXPR, op1_var, result), 0))
1055     return result;
1056   else
1057     return 0;
1058 }
1059
1060 /* Utility function of above to split a tree OP which may be a sum, into a
1061    constant part, which is returned, and a variable part, which is stored
1062    in *PVAR.  *PVAR may be bitsize_zero_node.  All operations must be of
1063    bitsizetype.  */
1064
1065 static tree
1066 split_plus (tree in, tree *pvar)
1067 {
1068   /* Strip NOPS in order to ease the tree traversal and maximize the
1069      potential for constant or plus/minus discovery. We need to be careful
1070      to always return and set *pvar to bitsizetype trees, but it's worth
1071      the effort.  */
1072   STRIP_NOPS (in);
1073
1074   *pvar = convert (bitsizetype, in);
1075
1076   if (TREE_CODE (in) == INTEGER_CST)
1077     {
1078       *pvar = bitsize_zero_node;
1079       return convert (bitsizetype, in);
1080     }
1081   else if (TREE_CODE (in) == PLUS_EXPR || TREE_CODE (in) == MINUS_EXPR)
1082     {
1083       tree lhs_var, rhs_var;
1084       tree lhs_con = split_plus (TREE_OPERAND (in, 0), &lhs_var);
1085       tree rhs_con = split_plus (TREE_OPERAND (in, 1), &rhs_var);
1086
1087       if (lhs_var == TREE_OPERAND (in, 0)
1088           && rhs_var == TREE_OPERAND (in, 1))
1089         return bitsize_zero_node;
1090
1091       *pvar = size_binop (TREE_CODE (in), lhs_var, rhs_var);
1092       return size_binop (TREE_CODE (in), lhs_con, rhs_con);
1093     }
1094   else
1095     return bitsize_zero_node;
1096 }
1097 \f
1098 /* Return a FUNCTION_TYPE node.  RETURN_TYPE is the type returned by the
1099    subprogram.  If it is VOID_TYPE, then we are dealing with a procedure,
1100    otherwise we are dealing with a function.  PARAM_DECL_LIST is a list of
1101    PARM_DECL nodes that are the subprogram parameters.  CICO_LIST is the
1102    copy-in/copy-out list to be stored into the TYPE_CICO_LIST field.
1103    RETURN_UNCONSTRAINED_P is true if the function returns an unconstrained
1104    object.  RETURN_BY_DIRECT_REF_P is true if the function returns by direct
1105    reference.  RETURN_BY_INVISI_REF_P is true if the function returns by
1106    invisible reference.  */
1107
1108 tree
1109 create_subprog_type (tree return_type, tree param_decl_list, tree cico_list,
1110                      bool return_unconstrained_p, bool return_by_direct_ref_p,
1111                      bool return_by_invisi_ref_p)
1112 {
1113   /* A chain of TREE_LIST nodes whose TREE_VALUEs are the data type nodes of
1114      the subprogram formal parameters.  This list is generated by traversing
1115      the input list of PARM_DECL nodes.  */
1116   tree param_type_list = NULL_TREE;
1117   tree t, type;
1118
1119   for (t = param_decl_list; t; t = TREE_CHAIN (t))
1120     param_type_list = tree_cons (NULL_TREE, TREE_TYPE (t), param_type_list);
1121
1122   /* The list of the function parameter types has to be terminated by the void
1123      type to signal to the back-end that we are not dealing with a variable
1124      parameter subprogram, but that it has a fixed number of parameters.  */
1125   param_type_list = tree_cons (NULL_TREE, void_type_node, param_type_list);
1126
1127   /* The list of argument types has been created in reverse so reverse it.  */
1128   param_type_list = nreverse (param_type_list);
1129
1130   type = build_function_type (return_type, param_type_list);
1131
1132   /* TYPE may have been shared since GCC hashes types.  If it has a different
1133      CICO_LIST, make a copy.  Likewise for the various flags.  */
1134   if (TYPE_CI_CO_LIST (type) != cico_list
1135       || TYPE_RETURN_UNCONSTRAINED_P (type) != return_unconstrained_p
1136       || TYPE_RETURN_BY_DIRECT_REF_P (type) != return_by_direct_ref_p
1137       || TREE_ADDRESSABLE (type) != return_by_invisi_ref_p)
1138     {
1139       type = copy_type (type);
1140       TYPE_CI_CO_LIST (type) = cico_list;
1141       TYPE_RETURN_UNCONSTRAINED_P (type) = return_unconstrained_p;
1142       TYPE_RETURN_BY_DIRECT_REF_P (type) = return_by_direct_ref_p;
1143       TREE_ADDRESSABLE (type) = return_by_invisi_ref_p;
1144     }
1145
1146   return type;
1147 }
1148 \f
1149 /* Return a copy of TYPE but safe to modify in any way.  */
1150
1151 tree
1152 copy_type (tree type)
1153 {
1154   tree new_type = copy_node (type);
1155
1156   /* Unshare the language-specific data.  */
1157   if (TYPE_LANG_SPECIFIC (type))
1158     {
1159       TYPE_LANG_SPECIFIC (new_type) = NULL;
1160       SET_TYPE_LANG_SPECIFIC (new_type, GET_TYPE_LANG_SPECIFIC (type));
1161     }
1162
1163   /* And the contents of the language-specific slot if needed.  */
1164   if ((INTEGRAL_TYPE_P (type) || TREE_CODE (type) == REAL_TYPE)
1165       && TYPE_RM_VALUES (type))
1166     {
1167       TYPE_RM_VALUES (new_type) = NULL_TREE;
1168       SET_TYPE_RM_SIZE (new_type, TYPE_RM_SIZE (type));
1169       SET_TYPE_RM_MIN_VALUE (new_type, TYPE_RM_MIN_VALUE (type));
1170       SET_TYPE_RM_MAX_VALUE (new_type, TYPE_RM_MAX_VALUE (type));
1171     }
1172
1173   /* copy_node clears this field instead of copying it, because it is
1174      aliased with TREE_CHAIN.  */
1175   TYPE_STUB_DECL (new_type) = TYPE_STUB_DECL (type);
1176
1177   TYPE_POINTER_TO (new_type) = 0;
1178   TYPE_REFERENCE_TO (new_type) = 0;
1179   TYPE_MAIN_VARIANT (new_type) = new_type;
1180   TYPE_NEXT_VARIANT (new_type) = 0;
1181
1182   return new_type;
1183 }
1184 \f
1185 /* Return a subtype of sizetype with range MIN to MAX and whose
1186    TYPE_INDEX_TYPE is INDEX.  GNAT_NODE is used for the position
1187    of the associated TYPE_DECL.  */
1188
1189 tree
1190 create_index_type (tree min, tree max, tree index, Node_Id gnat_node)
1191 {
1192   /* First build a type for the desired range.  */
1193   tree type = build_index_2_type (min, max);
1194
1195   /* If this type has the TYPE_INDEX_TYPE we want, return it.  */
1196   if (TYPE_INDEX_TYPE (type) == index)
1197     return type;
1198
1199   /* Otherwise, if TYPE_INDEX_TYPE is set, make a copy.  Note that we have
1200      no way of sharing these types, but that's only a small hole.  */
1201   if (TYPE_INDEX_TYPE (type))
1202     type = copy_type (type);
1203
1204   SET_TYPE_INDEX_TYPE (type, index);
1205   create_type_decl (NULL_TREE, type, NULL, true, false, gnat_node);
1206
1207   return type;
1208 }
1209
1210 /* Return a subtype of TYPE with range MIN to MAX.  If TYPE is NULL,
1211    sizetype is used.  */
1212
1213 tree
1214 create_range_type (tree type, tree min, tree max)
1215 {
1216   tree range_type;
1217
1218   if (type == NULL_TREE)
1219     type = sizetype;
1220
1221   /* First build a type with the base range.  */
1222   range_type
1223     = build_range_type (type, TYPE_MIN_VALUE (type), TYPE_MAX_VALUE (type));
1224
1225   min = convert (type, min);
1226   max = convert (type, max);
1227
1228   /* If this type has the TYPE_RM_{MIN,MAX}_VALUE we want, return it.  */
1229   if (TYPE_RM_MIN_VALUE (range_type)
1230       && TYPE_RM_MAX_VALUE (range_type)
1231       && operand_equal_p (TYPE_RM_MIN_VALUE (range_type), min, 0)
1232       && operand_equal_p (TYPE_RM_MAX_VALUE (range_type), max, 0))
1233     return range_type;
1234
1235   /* Otherwise, if TYPE_RM_{MIN,MAX}_VALUE is set, make a copy.  */
1236   if (TYPE_RM_MIN_VALUE (range_type) || TYPE_RM_MAX_VALUE (range_type))
1237     range_type = copy_type (range_type);
1238
1239   /* Then set the actual range.  */
1240   SET_TYPE_RM_MIN_VALUE (range_type, min);
1241   SET_TYPE_RM_MAX_VALUE (range_type, max);
1242
1243   return range_type;
1244 }
1245 \f
1246 /* Return a TYPE_DECL node suitable for the TYPE_STUB_DECL field of a type.
1247    TYPE_NAME gives the name of the type and TYPE is a ..._TYPE node giving
1248    its data type.  */
1249
1250 tree
1251 create_type_stub_decl (tree type_name, tree type)
1252 {
1253   /* Using a named TYPE_DECL ensures that a type name marker is emitted in
1254      STABS while setting DECL_ARTIFICIAL ensures that no DW_TAG_typedef is
1255      emitted in DWARF.  */
1256   tree type_decl = build_decl (input_location,
1257                                TYPE_DECL, type_name, type);
1258   DECL_ARTIFICIAL (type_decl) = 1;
1259   return type_decl;
1260 }
1261
1262 /* Return a TYPE_DECL node.  TYPE_NAME gives the name of the type and TYPE
1263    is a ..._TYPE node giving its data type.  ARTIFICIAL_P is true if this
1264    is a declaration that was generated by the compiler.  DEBUG_INFO_P is
1265    true if we need to write debug information about this type.  GNAT_NODE
1266    is used for the position of the decl.  */
1267
1268 tree
1269 create_type_decl (tree type_name, tree type, struct attrib *attr_list,
1270                   bool artificial_p, bool debug_info_p, Node_Id gnat_node)
1271 {
1272   enum tree_code code = TREE_CODE (type);
1273   bool named = TYPE_NAME (type) && TREE_CODE (TYPE_NAME (type)) == TYPE_DECL;
1274   tree type_decl;
1275
1276   /* Only the builtin TYPE_STUB_DECL should be used for dummy types.  */
1277   gcc_assert (!TYPE_IS_DUMMY_P (type));
1278
1279   /* If the type hasn't been named yet, we're naming it; preserve an existing
1280      TYPE_STUB_DECL that has been attached to it for some purpose.  */
1281   if (!named && TYPE_STUB_DECL (type))
1282     {
1283       type_decl = TYPE_STUB_DECL (type);
1284       DECL_NAME (type_decl) = type_name;
1285     }
1286   else
1287     type_decl = build_decl (input_location,
1288                             TYPE_DECL, type_name, type);
1289
1290   DECL_ARTIFICIAL (type_decl) = artificial_p;
1291   gnat_pushdecl (type_decl, gnat_node);
1292   process_attributes (type_decl, attr_list);
1293
1294   /* If we're naming the type, equate the TYPE_STUB_DECL to the name.
1295      This causes the name to be also viewed as a "tag" by the debug
1296      back-end, with the advantage that no DW_TAG_typedef is emitted
1297      for artificial "tagged" types in DWARF.  */
1298   if (!named)
1299     TYPE_STUB_DECL (type) = type_decl;
1300
1301   /* Pass the type declaration to the debug back-end unless this is an
1302      UNCONSTRAINED_ARRAY_TYPE that the back-end does not support, or a
1303      type for which debugging information was not requested, or else an
1304      ENUMERAL_TYPE or RECORD_TYPE (except for fat pointers) which are
1305      handled separately.  And do not pass dummy types either.  */
1306   if (code == UNCONSTRAINED_ARRAY_TYPE || !debug_info_p)
1307     DECL_IGNORED_P (type_decl) = 1;
1308   else if (code != ENUMERAL_TYPE
1309            && (code != RECORD_TYPE || TYPE_FAT_POINTER_P (type))
1310            && !((code == POINTER_TYPE || code == REFERENCE_TYPE)
1311                 && TYPE_IS_DUMMY_P (TREE_TYPE (type)))
1312            && !(code == RECORD_TYPE
1313                 && TYPE_IS_DUMMY_P
1314                    (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (type))))))
1315     rest_of_type_decl_compilation (type_decl);
1316
1317   return type_decl;
1318 }
1319 \f
1320 /* Return a VAR_DECL or CONST_DECL node.
1321
1322    VAR_NAME gives the name of the variable.  ASM_NAME is its assembler name
1323    (if provided).  TYPE is its data type (a GCC ..._TYPE node).  VAR_INIT is
1324    the GCC tree for an optional initial expression; NULL_TREE if none.
1325
1326    CONST_FLAG is true if this variable is constant, in which case we might
1327    return a CONST_DECL node unless CONST_DECL_ALLOWED_P is false.
1328
1329    PUBLIC_FLAG is true if this is for a reference to a public entity or for a
1330    definition to be made visible outside of the current compilation unit, for
1331    instance variable definitions in a package specification.
1332
1333    EXTERN_FLAG is true when processing an external variable declaration (as
1334    opposed to a definition: no storage is to be allocated for the variable).
1335
1336    STATIC_FLAG is only relevant when not at top level.  In that case
1337    it indicates whether to always allocate storage to the variable.
1338
1339    GNAT_NODE is used for the position of the decl.  */
1340
1341 tree
1342 create_var_decl_1 (tree var_name, tree asm_name, tree type, tree var_init,
1343                    bool const_flag, bool public_flag, bool extern_flag,
1344                    bool static_flag, bool const_decl_allowed_p,
1345                    struct attrib *attr_list, Node_Id gnat_node)
1346 {
1347   bool init_const
1348     = (var_init != 0
1349        && gnat_types_compatible_p (type, TREE_TYPE (var_init))
1350        && (global_bindings_p () || static_flag
1351            ? initializer_constant_valid_p (var_init, TREE_TYPE (var_init)) != 0
1352            : TREE_CONSTANT (var_init)));
1353
1354   /* Whether we will make TREE_CONSTANT the DECL we produce here, in which
1355      case the initializer may be used in-lieu of the DECL node (as done in
1356      Identifier_to_gnu).  This is useful to prevent the need of elaboration
1357      code when an identifier for which such a decl is made is in turn used as
1358      an initializer.  We used to rely on CONST vs VAR_DECL for this purpose,
1359      but extra constraints apply to this choice (see below) and are not
1360      relevant to the distinction we wish to make. */
1361   bool constant_p = const_flag && init_const;
1362
1363   /* The actual DECL node.  CONST_DECL was initially intended for enumerals
1364      and may be used for scalars in general but not for aggregates.  */
1365   tree var_decl
1366     = build_decl (input_location,
1367                   (constant_p && const_decl_allowed_p
1368                    && !AGGREGATE_TYPE_P (type)) ? CONST_DECL : VAR_DECL,
1369                   var_name, type);
1370
1371   /* If this is external, throw away any initializations (they will be done
1372      elsewhere) unless this is a constant for which we would like to remain
1373      able to get the initializer.  If we are defining a global here, leave a
1374      constant initialization and save any variable elaborations for the
1375      elaboration routine.  If we are just annotating types, throw away the
1376      initialization if it isn't a constant.  */
1377   if ((extern_flag && !constant_p)
1378       || (type_annotate_only && var_init && !TREE_CONSTANT (var_init)))
1379     var_init = NULL_TREE;
1380
1381   /* At the global level, an initializer requiring code to be generated
1382      produces elaboration statements.  Check that such statements are allowed,
1383      that is, not violating a No_Elaboration_Code restriction.  */
1384   if (global_bindings_p () && var_init != 0 && !init_const)
1385     Check_Elaboration_Code_Allowed (gnat_node);
1386
1387   DECL_INITIAL  (var_decl) = var_init;
1388   TREE_READONLY (var_decl) = const_flag;
1389   DECL_EXTERNAL (var_decl) = extern_flag;
1390   TREE_PUBLIC   (var_decl) = public_flag || extern_flag;
1391   TREE_CONSTANT (var_decl) = constant_p;
1392   TREE_THIS_VOLATILE (var_decl) = TREE_SIDE_EFFECTS (var_decl)
1393     = TYPE_VOLATILE (type);
1394
1395   /* Ada doesn't feature Fortran-like COMMON variables so we shouldn't
1396      try to fiddle with DECL_COMMON.  However, on platforms that don't
1397      support global BSS sections, uninitialized global variables would
1398      go in DATA instead, thus increasing the size of the executable.  */
1399   if (!flag_no_common
1400       && TREE_CODE (var_decl) == VAR_DECL
1401       && TREE_PUBLIC (var_decl)
1402       && !have_global_bss_p ())
1403     DECL_COMMON (var_decl) = 1;
1404
1405   /* If it's public and not external, always allocate storage for it.
1406      At the global binding level we need to allocate static storage for the
1407      variable if and only if it's not external. If we are not at the top level
1408      we allocate automatic storage unless requested not to.  */
1409   TREE_STATIC (var_decl)
1410     = !extern_flag && (public_flag || static_flag || global_bindings_p ());
1411
1412   /* For an external constant whose initializer is not absolute, do not emit
1413      debug info.  In DWARF this would mean a global relocation in a read-only
1414      section which runs afoul of the PE-COFF runtime relocation mechanism.  */
1415   if (extern_flag
1416       && constant_p
1417       && initializer_constant_valid_p (var_init, TREE_TYPE (var_init))
1418            != null_pointer_node)
1419     DECL_IGNORED_P (var_decl) = 1;
1420
1421   if (TREE_CODE (var_decl) == VAR_DECL)
1422     {
1423       if (asm_name)
1424         SET_DECL_ASSEMBLER_NAME (var_decl, asm_name);
1425       process_attributes (var_decl, attr_list);
1426     }
1427
1428   /* Add this decl to the current binding level.  */
1429   gnat_pushdecl (var_decl, gnat_node);
1430
1431   if (TREE_SIDE_EFFECTS (var_decl))
1432     TREE_ADDRESSABLE (var_decl) = 1;
1433
1434   if (TREE_CODE (var_decl) != CONST_DECL)
1435     {
1436       if (global_bindings_p ())
1437         rest_of_decl_compilation (var_decl, true, 0);
1438     }
1439   else
1440     expand_decl (var_decl);
1441
1442   return var_decl;
1443 }
1444 \f
1445 /* Return true if TYPE, an aggregate type, contains (or is) an array.  */
1446
1447 static bool
1448 aggregate_type_contains_array_p (tree type)
1449 {
1450   switch (TREE_CODE (type))
1451     {
1452     case RECORD_TYPE:
1453     case UNION_TYPE:
1454     case QUAL_UNION_TYPE:
1455       {
1456         tree field;
1457         for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1458           if (AGGREGATE_TYPE_P (TREE_TYPE (field))
1459               && aggregate_type_contains_array_p (TREE_TYPE (field)))
1460             return true;
1461         return false;
1462       }
1463
1464     case ARRAY_TYPE:
1465       return true;
1466
1467     default:
1468       gcc_unreachable ();
1469     }
1470 }
1471
1472 /* Return a FIELD_DECL node.  FIELD_NAME is the field's name, FIELD_TYPE is
1473    its type and RECORD_TYPE is the type of the enclosing record.  PACKED is
1474    1 if the enclosing record is packed, -1 if it has Component_Alignment of
1475    Storage_Unit.  If SIZE is nonzero, it is the specified size of the field.
1476    If POS is nonzero, it is the bit position.  If ADDRESSABLE is nonzero, it
1477    means we are allowed to take the address of the field; if it is negative,
1478    we should not make a bitfield, which is used by make_aligning_type.  */
1479
1480 tree
1481 create_field_decl (tree field_name, tree field_type, tree record_type,
1482                    int packed, tree size, tree pos, int addressable)
1483 {
1484   tree field_decl = build_decl (input_location,
1485                                 FIELD_DECL, field_name, field_type);
1486
1487   DECL_CONTEXT (field_decl) = record_type;
1488   TREE_READONLY (field_decl) = TYPE_READONLY (field_type);
1489
1490   /* If FIELD_TYPE is BLKmode, we must ensure this is aligned to at least a
1491      byte boundary since GCC cannot handle less-aligned BLKmode bitfields.
1492      Likewise for an aggregate without specified position that contains an
1493      array, because in this case slices of variable length of this array
1494      must be handled by GCC and variable-sized objects need to be aligned
1495      to at least a byte boundary.  */
1496   if (packed && (TYPE_MODE (field_type) == BLKmode
1497                  || (!pos
1498                      && AGGREGATE_TYPE_P (field_type)
1499                      && aggregate_type_contains_array_p (field_type))))
1500     DECL_ALIGN (field_decl) = BITS_PER_UNIT;
1501
1502   /* If a size is specified, use it.  Otherwise, if the record type is packed
1503      compute a size to use, which may differ from the object's natural size.
1504      We always set a size in this case to trigger the checks for bitfield
1505      creation below, which is typically required when no position has been
1506      specified.  */
1507   if (size)
1508     size = convert (bitsizetype, size);
1509   else if (packed == 1)
1510     {
1511       size = rm_size (field_type);
1512       if (TYPE_MODE (field_type) == BLKmode)
1513         size = round_up (size, BITS_PER_UNIT);
1514     }
1515
1516   /* If we may, according to ADDRESSABLE, make a bitfield if a size is
1517      specified for two reasons: first if the size differs from the natural
1518      size.  Second, if the alignment is insufficient.  There are a number of
1519      ways the latter can be true.
1520
1521      We never make a bitfield if the type of the field has a nonconstant size,
1522      because no such entity requiring bitfield operations should reach here.
1523
1524      We do *preventively* make a bitfield when there might be the need for it
1525      but we don't have all the necessary information to decide, as is the case
1526      of a field with no specified position in a packed record.
1527
1528      We also don't look at STRICT_ALIGNMENT here, and rely on later processing
1529      in layout_decl or finish_record_type to clear the bit_field indication if
1530      it is in fact not needed.  */
1531   if (addressable >= 0
1532       && size
1533       && TREE_CODE (size) == INTEGER_CST
1534       && TREE_CODE (TYPE_SIZE (field_type)) == INTEGER_CST
1535       && (!tree_int_cst_equal (size, TYPE_SIZE (field_type))
1536           || (pos && !value_factor_p (pos, TYPE_ALIGN (field_type)))
1537           || packed
1538           || (TYPE_ALIGN (record_type) != 0
1539               && TYPE_ALIGN (record_type) < TYPE_ALIGN (field_type))))
1540     {
1541       DECL_BIT_FIELD (field_decl) = 1;
1542       DECL_SIZE (field_decl) = size;
1543       if (!packed && !pos)
1544         {
1545           if (TYPE_ALIGN (record_type) != 0
1546               && TYPE_ALIGN (record_type) < TYPE_ALIGN (field_type))
1547             DECL_ALIGN (field_decl) = TYPE_ALIGN (record_type);
1548           else
1549             DECL_ALIGN (field_decl) = TYPE_ALIGN (field_type);
1550         }
1551     }
1552
1553   DECL_PACKED (field_decl) = pos ? DECL_BIT_FIELD (field_decl) : packed;
1554
1555   /* Bump the alignment if need be, either for bitfield/packing purposes or
1556      to satisfy the type requirements if no such consideration applies.  When
1557      we get the alignment from the type, indicate if this is from an explicit
1558      user request, which prevents stor-layout from lowering it later on.  */
1559   {
1560     unsigned int bit_align
1561       = (DECL_BIT_FIELD (field_decl) ? 1
1562          : packed && TYPE_MODE (field_type) != BLKmode ? BITS_PER_UNIT : 0);
1563
1564     if (bit_align > DECL_ALIGN (field_decl))
1565       DECL_ALIGN (field_decl) = bit_align;
1566     else if (!bit_align && TYPE_ALIGN (field_type) > DECL_ALIGN (field_decl))
1567       {
1568         DECL_ALIGN (field_decl) = TYPE_ALIGN (field_type);
1569         DECL_USER_ALIGN (field_decl) = TYPE_USER_ALIGN (field_type);
1570       }
1571   }
1572
1573   if (pos)
1574     {
1575       /* We need to pass in the alignment the DECL is known to have.
1576          This is the lowest-order bit set in POS, but no more than
1577          the alignment of the record, if one is specified.  Note
1578          that an alignment of 0 is taken as infinite.  */
1579       unsigned int known_align;
1580
1581       if (host_integerp (pos, 1))
1582         known_align = tree_low_cst (pos, 1) & - tree_low_cst (pos, 1);
1583       else
1584         known_align = BITS_PER_UNIT;
1585
1586       if (TYPE_ALIGN (record_type)
1587           && (known_align == 0 || known_align > TYPE_ALIGN (record_type)))
1588         known_align = TYPE_ALIGN (record_type);
1589
1590       layout_decl (field_decl, known_align);
1591       SET_DECL_OFFSET_ALIGN (field_decl,
1592                              host_integerp (pos, 1) ? BIGGEST_ALIGNMENT
1593                              : BITS_PER_UNIT);
1594       pos_from_bit (&DECL_FIELD_OFFSET (field_decl),
1595                     &DECL_FIELD_BIT_OFFSET (field_decl),
1596                     DECL_OFFSET_ALIGN (field_decl), pos);
1597     }
1598
1599   /* In addition to what our caller says, claim the field is addressable if we
1600      know that its type is not suitable.
1601
1602      The field may also be "technically" nonaddressable, meaning that even if
1603      we attempt to take the field's address we will actually get the address
1604      of a copy.  This is the case for true bitfields, but the DECL_BIT_FIELD
1605      value we have at this point is not accurate enough, so we don't account
1606      for this here and let finish_record_type decide.  */
1607   if (!addressable && !type_for_nonaliased_component_p (field_type))
1608     addressable = 1;
1609
1610   DECL_NONADDRESSABLE_P (field_decl) = !addressable;
1611
1612   return field_decl;
1613 }
1614 \f
1615 /* Return a PARM_DECL node.  PARAM_NAME is the name of the parameter and
1616    PARAM_TYPE is its type.  READONLY is true if the parameter is readonly
1617    (either an In parameter or an address of a pass-by-ref parameter).  */
1618
1619 tree
1620 create_param_decl (tree param_name, tree param_type, bool readonly)
1621 {
1622   tree param_decl = build_decl (input_location,
1623                                 PARM_DECL, param_name, param_type);
1624
1625   /* Honor TARGET_PROMOTE_PROTOTYPES like the C compiler, as not doing so
1626      can lead to various ABI violations.  */
1627   if (targetm.calls.promote_prototypes (NULL_TREE)
1628       && INTEGRAL_TYPE_P (param_type)
1629       && TYPE_PRECISION (param_type) < TYPE_PRECISION (integer_type_node))
1630     {
1631       /* We have to be careful about biased types here.  Make a subtype
1632          of integer_type_node with the proper biasing.  */
1633       if (TREE_CODE (param_type) == INTEGER_TYPE
1634           && TYPE_BIASED_REPRESENTATION_P (param_type))
1635         {
1636           tree subtype
1637             = make_unsigned_type (TYPE_PRECISION (integer_type_node));
1638           TREE_TYPE (subtype) = integer_type_node;
1639           TYPE_BIASED_REPRESENTATION_P (subtype) = 1;
1640           SET_TYPE_RM_MIN_VALUE (subtype, TYPE_MIN_VALUE (param_type));
1641           SET_TYPE_RM_MAX_VALUE (subtype, TYPE_MAX_VALUE (param_type));
1642           param_type = subtype;
1643         }
1644       else
1645         param_type = integer_type_node;
1646     }
1647
1648   DECL_ARG_TYPE (param_decl) = param_type;
1649   TREE_READONLY (param_decl) = readonly;
1650   return param_decl;
1651 }
1652 \f
1653 /* Given a DECL and ATTR_LIST, process the listed attributes.  */
1654
1655 void
1656 process_attributes (tree decl, struct attrib *attr_list)
1657 {
1658   for (; attr_list; attr_list = attr_list->next)
1659     switch (attr_list->type)
1660       {
1661       case ATTR_MACHINE_ATTRIBUTE:
1662         decl_attributes (&decl, tree_cons (attr_list->name, attr_list->args,
1663                                            NULL_TREE),
1664                          ATTR_FLAG_TYPE_IN_PLACE);
1665         break;
1666
1667       case ATTR_LINK_ALIAS:
1668         if (! DECL_EXTERNAL (decl))
1669           {
1670             TREE_STATIC (decl) = 1;
1671             assemble_alias (decl, attr_list->name);
1672           }
1673         break;
1674
1675       case ATTR_WEAK_EXTERNAL:
1676         if (SUPPORTS_WEAK)
1677           declare_weak (decl);
1678         else
1679           post_error ("?weak declarations not supported on this target",
1680                       attr_list->error_point);
1681         break;
1682
1683       case ATTR_LINK_SECTION:
1684         if (targetm.have_named_sections)
1685           {
1686             DECL_SECTION_NAME (decl)
1687               = build_string (IDENTIFIER_LENGTH (attr_list->name),
1688                               IDENTIFIER_POINTER (attr_list->name));
1689             DECL_COMMON (decl) = 0;
1690           }
1691         else
1692           post_error ("?section attributes are not supported for this target",
1693                       attr_list->error_point);
1694         break;
1695
1696       case ATTR_LINK_CONSTRUCTOR:
1697         DECL_STATIC_CONSTRUCTOR (decl) = 1;
1698         TREE_USED (decl) = 1;
1699         break;
1700
1701       case ATTR_LINK_DESTRUCTOR:
1702         DECL_STATIC_DESTRUCTOR (decl) = 1;
1703         TREE_USED (decl) = 1;
1704         break;
1705
1706       case ATTR_THREAD_LOCAL_STORAGE:
1707         DECL_TLS_MODEL (decl) = decl_default_tls_model (decl);
1708         DECL_COMMON (decl) = 0;
1709         break;
1710       }
1711 }
1712 \f
1713 /* Record DECL as a global renaming pointer.  */
1714
1715 void
1716 record_global_renaming_pointer (tree decl)
1717 {
1718   gcc_assert (DECL_RENAMED_OBJECT (decl));
1719   VEC_safe_push (tree, gc, global_renaming_pointers, decl);
1720 }
1721
1722 /* Invalidate the global renaming pointers.   */
1723
1724 void
1725 invalidate_global_renaming_pointers (void)
1726 {
1727   unsigned int i;
1728   tree iter;
1729
1730   for (i = 0; VEC_iterate(tree, global_renaming_pointers, i, iter); i++)
1731     SET_DECL_RENAMED_OBJECT (iter, NULL_TREE);
1732
1733   VEC_free (tree, gc, global_renaming_pointers);
1734 }
1735
1736 /* Return true if VALUE is a known to be a multiple of FACTOR, which must be
1737    a power of 2. */
1738
1739 bool
1740 value_factor_p (tree value, HOST_WIDE_INT factor)
1741 {
1742   if (host_integerp (value, 1))
1743     return tree_low_cst (value, 1) % factor == 0;
1744
1745   if (TREE_CODE (value) == MULT_EXPR)
1746     return (value_factor_p (TREE_OPERAND (value, 0), factor)
1747             || value_factor_p (TREE_OPERAND (value, 1), factor));
1748
1749   return false;
1750 }
1751
1752 /* Given 2 consecutive field decls PREV_FIELD and CURR_FIELD, return true
1753    unless we can prove these 2 fields are laid out in such a way that no gap
1754    exist between the end of PREV_FIELD and the beginning of CURR_FIELD.  OFFSET
1755    is the distance in bits between the end of PREV_FIELD and the starting
1756    position of CURR_FIELD. It is ignored if null. */
1757
1758 static bool
1759 potential_alignment_gap (tree prev_field, tree curr_field, tree offset)
1760 {
1761   /* If this is the first field of the record, there cannot be any gap */
1762   if (!prev_field)
1763     return false;
1764
1765   /* If the previous field is a union type, then return False: The only
1766      time when such a field is not the last field of the record is when
1767      there are other components at fixed positions after it (meaning there
1768      was a rep clause for every field), in which case we don't want the
1769      alignment constraint to override them. */
1770   if (TREE_CODE (TREE_TYPE (prev_field)) == QUAL_UNION_TYPE)
1771     return false;
1772
1773   /* If the distance between the end of prev_field and the beginning of
1774      curr_field is constant, then there is a gap if the value of this
1775      constant is not null. */
1776   if (offset && host_integerp (offset, 1))
1777     return !integer_zerop (offset);
1778
1779   /* If the size and position of the previous field are constant,
1780      then check the sum of this size and position. There will be a gap
1781      iff it is not multiple of the current field alignment. */
1782   if (host_integerp (DECL_SIZE (prev_field), 1)
1783       && host_integerp (bit_position (prev_field), 1))
1784     return ((tree_low_cst (bit_position (prev_field), 1)
1785              + tree_low_cst (DECL_SIZE (prev_field), 1))
1786             % DECL_ALIGN (curr_field) != 0);
1787
1788   /* If both the position and size of the previous field are multiples
1789      of the current field alignment, there cannot be any gap. */
1790   if (value_factor_p (bit_position (prev_field), DECL_ALIGN (curr_field))
1791       && value_factor_p (DECL_SIZE (prev_field), DECL_ALIGN (curr_field)))
1792     return false;
1793
1794   /* Fallback, return that there may be a potential gap */
1795   return true;
1796 }
1797
1798 /* Returns a LABEL_DECL node for LABEL_NAME.  */
1799
1800 tree
1801 create_label_decl (tree label_name)
1802 {
1803   tree label_decl = build_decl (input_location,
1804                                 LABEL_DECL, label_name, void_type_node);
1805
1806   DECL_CONTEXT (label_decl)     = current_function_decl;
1807   DECL_MODE (label_decl)        = VOIDmode;
1808   DECL_SOURCE_LOCATION (label_decl) = input_location;
1809
1810   return label_decl;
1811 }
1812 \f
1813 /* Returns a FUNCTION_DECL node.  SUBPROG_NAME is the name of the subprogram,
1814    ASM_NAME is its assembler name, SUBPROG_TYPE is its type (a FUNCTION_TYPE
1815    node), PARAM_DECL_LIST is the list of the subprogram arguments (a list of
1816    PARM_DECL nodes chained through the TREE_CHAIN field).
1817
1818    INLINE_FLAG, PUBLIC_FLAG, EXTERN_FLAG, and ATTR_LIST are used to set the
1819    appropriate fields in the FUNCTION_DECL.  GNAT_NODE gives the location.  */
1820
1821 tree
1822 create_subprog_decl (tree subprog_name, tree asm_name,
1823                      tree subprog_type, tree param_decl_list, bool inline_flag,
1824                      bool public_flag, bool extern_flag,
1825                      struct attrib *attr_list, Node_Id gnat_node)
1826 {
1827   tree subprog_decl = build_decl (input_location, FUNCTION_DECL, subprog_name,
1828                                   subprog_type);
1829   tree result_decl = build_decl (input_location, RESULT_DECL, NULL_TREE,
1830                                  TREE_TYPE (subprog_type));
1831
1832   /* If this is a non-inline function nested inside an inlined external
1833      function, we cannot honor both requests without cloning the nested
1834      function in the current unit since it is private to the other unit.
1835      We could inline the nested function as well but it's probably better
1836      to err on the side of too little inlining.  */
1837   if (!inline_flag
1838       && current_function_decl
1839       && DECL_DECLARED_INLINE_P (current_function_decl)
1840       && DECL_EXTERNAL (current_function_decl))
1841     DECL_DECLARED_INLINE_P (current_function_decl) = 0;
1842
1843   DECL_EXTERNAL (subprog_decl)  = extern_flag;
1844   TREE_PUBLIC (subprog_decl)    = public_flag;
1845   TREE_STATIC (subprog_decl)    = 1;
1846   TREE_READONLY (subprog_decl)  = TYPE_READONLY (subprog_type);
1847   TREE_THIS_VOLATILE (subprog_decl) = TYPE_VOLATILE (subprog_type);
1848   TREE_SIDE_EFFECTS (subprog_decl) = TYPE_VOLATILE (subprog_type);
1849   DECL_DECLARED_INLINE_P (subprog_decl) = inline_flag;
1850   DECL_ARGUMENTS (subprog_decl) = param_decl_list;
1851
1852   DECL_ARTIFICIAL (result_decl) = 1;
1853   DECL_IGNORED_P (result_decl) = 1;
1854   DECL_BY_REFERENCE (result_decl) = TREE_ADDRESSABLE (subprog_type);
1855   DECL_RESULT (subprog_decl) = result_decl;
1856
1857   if (asm_name)
1858     {
1859       SET_DECL_ASSEMBLER_NAME (subprog_decl, asm_name);
1860
1861       /* The expand_main_function circuitry expects "main_identifier_node" to
1862          designate the DECL_NAME of the 'main' entry point, in turn expected
1863          to be declared as the "main" function literally by default.  Ada
1864          program entry points are typically declared with a different name
1865          within the binder generated file, exported as 'main' to satisfy the
1866          system expectations.  Force main_identifier_node in this case.  */
1867       if (asm_name == main_identifier_node)
1868         DECL_NAME (subprog_decl) = main_identifier_node;
1869     }
1870
1871   process_attributes (subprog_decl, attr_list);
1872
1873   /* Add this decl to the current binding level.  */
1874   gnat_pushdecl (subprog_decl, gnat_node);
1875
1876   /* Output the assembler code and/or RTL for the declaration.  */
1877   rest_of_decl_compilation (subprog_decl, global_bindings_p (), 0);
1878
1879   return subprog_decl;
1880 }
1881 \f
1882 /* Set up the framework for generating code for SUBPROG_DECL, a subprogram
1883    body.  This routine needs to be invoked before processing the declarations
1884    appearing in the subprogram.  */
1885
1886 void
1887 begin_subprog_body (tree subprog_decl)
1888 {
1889   tree param_decl;
1890
1891   current_function_decl = subprog_decl;
1892   announce_function (subprog_decl);
1893
1894   /* Enter a new binding level and show that all the parameters belong to
1895      this function.  */
1896   gnat_pushlevel ();
1897   for (param_decl = DECL_ARGUMENTS (subprog_decl); param_decl;
1898        param_decl = TREE_CHAIN (param_decl))
1899     DECL_CONTEXT (param_decl) = subprog_decl;
1900
1901   make_decl_rtl (subprog_decl);
1902
1903   /* We handle pending sizes via the elaboration of types, so we don't need to
1904      save them.  This causes them to be marked as part of the outer function
1905      and then discarded.  */
1906   get_pending_sizes ();
1907 }
1908
1909 /* Finish the definition of the current subprogram BODY and finalize it.  */
1910
1911 void
1912 end_subprog_body (tree body)
1913 {
1914   tree fndecl = current_function_decl;
1915
1916   /* Mark the BLOCK for this level as being for this function and pop the
1917      level.  Since the vars in it are the parameters, clear them.  */
1918   BLOCK_VARS (current_binding_level->block) = 0;
1919   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
1920   DECL_INITIAL (fndecl) = current_binding_level->block;
1921   gnat_poplevel ();
1922
1923   /* We handle pending sizes via the elaboration of types, so we don't
1924      need to save them.  */
1925   get_pending_sizes ();
1926
1927   /* Mark the RESULT_DECL as being in this subprogram. */
1928   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
1929
1930   DECL_SAVED_TREE (fndecl) = body;
1931
1932   current_function_decl = DECL_CONTEXT (fndecl);
1933   set_cfun (NULL);
1934
1935   /* We cannot track the location of errors past this point.  */
1936   error_gnat_node = Empty;
1937
1938   /* If we're only annotating types, don't actually compile this function.  */
1939   if (type_annotate_only)
1940     return;
1941
1942   /* Dump functions before gimplification.  */
1943   dump_function (TDI_original, fndecl);
1944
1945   /* ??? This special handling of nested functions is probably obsolete.  */
1946   if (!DECL_CONTEXT (fndecl))
1947     cgraph_finalize_function (fndecl, false);
1948   else
1949     /* Register this function with cgraph just far enough to get it
1950        added to our parent's nested function list.  */
1951     (void) cgraph_node (fndecl);
1952 }
1953
1954 tree
1955 gnat_builtin_function (tree decl)
1956 {
1957   gnat_pushdecl (decl, Empty);
1958   return decl;
1959 }
1960
1961 /* Return an integer type with the number of bits of precision given by
1962    PRECISION.  UNSIGNEDP is nonzero if the type is unsigned; otherwise
1963    it is a signed type.  */
1964
1965 tree
1966 gnat_type_for_size (unsigned precision, int unsignedp)
1967 {
1968   tree t;
1969   char type_name[20];
1970
1971   if (precision <= 2 * MAX_BITS_PER_WORD
1972       && signed_and_unsigned_types[precision][unsignedp])
1973     return signed_and_unsigned_types[precision][unsignedp];
1974
1975  if (unsignedp)
1976     t = make_unsigned_type (precision);
1977   else
1978     t = make_signed_type (precision);
1979
1980   if (precision <= 2 * MAX_BITS_PER_WORD)
1981     signed_and_unsigned_types[precision][unsignedp] = t;
1982
1983   if (!TYPE_NAME (t))
1984     {
1985       sprintf (type_name, "%sSIGNED_%d", unsignedp ? "UN" : "", precision);
1986       TYPE_NAME (t) = get_identifier (type_name);
1987     }
1988
1989   return t;
1990 }
1991
1992 /* Likewise for floating-point types.  */
1993
1994 static tree
1995 float_type_for_precision (int precision, enum machine_mode mode)
1996 {
1997   tree t;
1998   char type_name[20];
1999
2000   if (float_types[(int) mode])
2001     return float_types[(int) mode];
2002
2003   float_types[(int) mode] = t = make_node (REAL_TYPE);
2004   TYPE_PRECISION (t) = precision;
2005   layout_type (t);
2006
2007   gcc_assert (TYPE_MODE (t) == mode);
2008   if (!TYPE_NAME (t))
2009     {
2010       sprintf (type_name, "FLOAT_%d", precision);
2011       TYPE_NAME (t) = get_identifier (type_name);
2012     }
2013
2014   return t;
2015 }
2016
2017 /* Return a data type that has machine mode MODE.  UNSIGNEDP selects
2018    an unsigned type; otherwise a signed type is returned.  */
2019
2020 tree
2021 gnat_type_for_mode (enum machine_mode mode, int unsignedp)
2022 {
2023   if (mode == BLKmode)
2024     return NULL_TREE;
2025
2026   if (mode == VOIDmode)
2027     return void_type_node;
2028
2029   if (COMPLEX_MODE_P (mode))
2030     return NULL_TREE;
2031
2032   if (SCALAR_FLOAT_MODE_P (mode))
2033     return float_type_for_precision (GET_MODE_PRECISION (mode), mode);
2034
2035   if (SCALAR_INT_MODE_P (mode))
2036     return gnat_type_for_size (GET_MODE_BITSIZE (mode), unsignedp);
2037
2038   if (VECTOR_MODE_P (mode))
2039     {
2040       enum machine_mode inner_mode = GET_MODE_INNER (mode);
2041       tree inner_type = gnat_type_for_mode (inner_mode, unsignedp);
2042       if (inner_type)
2043         return build_vector_type_for_mode (inner_type, mode);
2044     }
2045
2046   return NULL_TREE;
2047 }
2048
2049 /* Return the unsigned version of a TYPE_NODE, a scalar type.  */
2050
2051 tree
2052 gnat_unsigned_type (tree type_node)
2053 {
2054   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 1);
2055
2056   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
2057     {
2058       type = copy_node (type);
2059       TREE_TYPE (type) = type_node;
2060     }
2061   else if (TREE_TYPE (type_node)
2062            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
2063            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
2064     {
2065       type = copy_node (type);
2066       TREE_TYPE (type) = TREE_TYPE (type_node);
2067     }
2068
2069   return type;
2070 }
2071
2072 /* Return the signed version of a TYPE_NODE, a scalar type.  */
2073
2074 tree
2075 gnat_signed_type (tree type_node)
2076 {
2077   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 0);
2078
2079   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
2080     {
2081       type = copy_node (type);
2082       TREE_TYPE (type) = type_node;
2083     }
2084   else if (TREE_TYPE (type_node)
2085            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
2086            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
2087     {
2088       type = copy_node (type);
2089       TREE_TYPE (type) = TREE_TYPE (type_node);
2090     }
2091
2092   return type;
2093 }
2094
2095 /* Return 1 if the types T1 and T2 are compatible, i.e. if they can be
2096    transparently converted to each other.  */
2097
2098 int
2099 gnat_types_compatible_p (tree t1, tree t2)
2100 {
2101   enum tree_code code;
2102
2103   /* This is the default criterion.  */
2104   if (TYPE_MAIN_VARIANT (t1) == TYPE_MAIN_VARIANT (t2))
2105     return 1;
2106
2107   /* We only check structural equivalence here.  */
2108   if ((code = TREE_CODE (t1)) != TREE_CODE (t2))
2109     return 0;
2110
2111   /* Vector types are also compatible if they have the same number of subparts
2112      and the same form of (scalar) element type.  */
2113   if (code == VECTOR_TYPE
2114       && TYPE_VECTOR_SUBPARTS (t1) == TYPE_VECTOR_SUBPARTS (t2)
2115       && TREE_CODE (TREE_TYPE (t1)) == TREE_CODE (TREE_TYPE (t2))
2116       && TYPE_PRECISION (TREE_TYPE (t1)) == TYPE_PRECISION (TREE_TYPE (t2)))
2117     return 1;
2118
2119   /* Array types are also compatible if they are constrained and have
2120      the same component type and the same domain.  */
2121   if (code == ARRAY_TYPE
2122       && TREE_TYPE (t1) == TREE_TYPE (t2)
2123       && (TYPE_DOMAIN (t1) == TYPE_DOMAIN (t2)
2124           || (TYPE_DOMAIN (t1)
2125               && TYPE_DOMAIN (t2)
2126               && tree_int_cst_equal (TYPE_MIN_VALUE (TYPE_DOMAIN (t1)),
2127                                      TYPE_MIN_VALUE (TYPE_DOMAIN (t2)))
2128               && tree_int_cst_equal (TYPE_MAX_VALUE (TYPE_DOMAIN (t1)),
2129                                      TYPE_MAX_VALUE (TYPE_DOMAIN (t2))))))
2130     return 1;
2131
2132   /* Padding record types are also compatible if they pad the same
2133      type and have the same constant size.  */
2134   if (code == RECORD_TYPE
2135       && TYPE_PADDING_P (t1) && TYPE_PADDING_P (t2)
2136       && TREE_TYPE (TYPE_FIELDS (t1)) == TREE_TYPE (TYPE_FIELDS (t2))
2137       && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
2138     return 1;
2139
2140   return 0;
2141 }
2142 \f
2143 /* EXP is an expression for the size of an object.  If this size contains
2144    discriminant references, replace them with the maximum (if MAX_P) or
2145    minimum (if !MAX_P) possible value of the discriminant.  */
2146
2147 tree
2148 max_size (tree exp, bool max_p)
2149 {
2150   enum tree_code code = TREE_CODE (exp);
2151   tree type = TREE_TYPE (exp);
2152
2153   switch (TREE_CODE_CLASS (code))
2154     {
2155     case tcc_declaration:
2156     case tcc_constant:
2157       return exp;
2158
2159     case tcc_vl_exp:
2160       if (code == CALL_EXPR)
2161         {
2162           tree t, *argarray;
2163           int n, i;
2164
2165           t = maybe_inline_call_in_expr (exp);
2166           if (t)
2167             return max_size (t, max_p);
2168
2169           n = call_expr_nargs (exp);
2170           gcc_assert (n > 0);
2171           argarray = (tree *) alloca (n * sizeof (tree));
2172           for (i = 0; i < n; i++)
2173             argarray[i] = max_size (CALL_EXPR_ARG (exp, i), max_p);
2174           return build_call_array (type, CALL_EXPR_FN (exp), n, argarray);
2175         }
2176       break;
2177
2178     case tcc_reference:
2179       /* If this contains a PLACEHOLDER_EXPR, it is the thing we want to
2180          modify.  Otherwise, we treat it like a variable.  */
2181       if (!CONTAINS_PLACEHOLDER_P (exp))
2182         return exp;
2183
2184       type = TREE_TYPE (TREE_OPERAND (exp, 1));
2185       return
2186         max_size (max_p ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type), true);
2187
2188     case tcc_comparison:
2189       return max_p ? size_one_node : size_zero_node;
2190
2191     case tcc_unary:
2192     case tcc_binary:
2193     case tcc_expression:
2194       switch (TREE_CODE_LENGTH (code))
2195         {
2196         case 1:
2197           if (code == NON_LVALUE_EXPR)
2198             return max_size (TREE_OPERAND (exp, 0), max_p);
2199           else
2200             return
2201               fold_build1 (code, type,
2202                            max_size (TREE_OPERAND (exp, 0),
2203                                      code == NEGATE_EXPR ? !max_p : max_p));
2204
2205         case 2:
2206           if (code == COMPOUND_EXPR)
2207             return max_size (TREE_OPERAND (exp, 1), max_p);
2208
2209           /* Calculate "(A ? B : C) - D" as "A ? B - D : C - D" which
2210              may provide a tighter bound on max_size.  */
2211           if (code == MINUS_EXPR
2212               && TREE_CODE (TREE_OPERAND (exp, 0)) == COND_EXPR)
2213             {
2214               tree lhs = fold_build2 (MINUS_EXPR, type,
2215                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 1),
2216                                       TREE_OPERAND (exp, 1));
2217               tree rhs = fold_build2 (MINUS_EXPR, type,
2218                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 2),
2219                                       TREE_OPERAND (exp, 1));
2220               return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2221                                   max_size (lhs, max_p),
2222                                   max_size (rhs, max_p));
2223             }
2224
2225           {
2226             tree lhs = max_size (TREE_OPERAND (exp, 0), max_p);
2227             tree rhs = max_size (TREE_OPERAND (exp, 1),
2228                                  code == MINUS_EXPR ? !max_p : max_p);
2229
2230             /* Special-case wanting the maximum value of a MIN_EXPR.
2231                In that case, if one side overflows, return the other.
2232                sizetype is signed, but we know sizes are non-negative.
2233                Likewise, handle a MINUS_EXPR or PLUS_EXPR with the LHS
2234                overflowing or the maximum possible value and the RHS
2235                a variable.  */
2236             if (max_p
2237                 && code == MIN_EXPR
2238                 && TREE_CODE (rhs) == INTEGER_CST
2239                 && TREE_OVERFLOW (rhs))
2240               return lhs;
2241             else if (max_p
2242                      && code == MIN_EXPR
2243                      && TREE_CODE (lhs) == INTEGER_CST
2244                      && TREE_OVERFLOW (lhs))
2245               return rhs;
2246             else if ((code == MINUS_EXPR || code == PLUS_EXPR)
2247                      && ((TREE_CODE (lhs) == INTEGER_CST
2248                           && TREE_OVERFLOW (lhs))
2249                          || operand_equal_p (lhs, TYPE_MAX_VALUE (type), 0))
2250                      && !TREE_CONSTANT (rhs))
2251               return lhs;
2252             else
2253               return fold_build2 (code, type, lhs, rhs);
2254           }
2255
2256         case 3:
2257           if (code == SAVE_EXPR)
2258             return exp;
2259           else if (code == COND_EXPR)
2260             return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2261                                 max_size (TREE_OPERAND (exp, 1), max_p),
2262                                 max_size (TREE_OPERAND (exp, 2), max_p));
2263         }
2264
2265       /* Other tree classes cannot happen.  */
2266     default:
2267       break;
2268     }
2269
2270   gcc_unreachable ();
2271 }
2272 \f
2273 /* Build a template of type TEMPLATE_TYPE from the array bounds of ARRAY_TYPE.
2274    EXPR is an expression that we can use to locate any PLACEHOLDER_EXPRs.
2275    Return a constructor for the template.  */
2276
2277 tree
2278 build_template (tree template_type, tree array_type, tree expr)
2279 {
2280   tree template_elts = NULL_TREE;
2281   tree bound_list = NULL_TREE;
2282   tree field;
2283
2284   while (TREE_CODE (array_type) == RECORD_TYPE
2285          && (TYPE_PADDING_P (array_type)
2286              || TYPE_JUSTIFIED_MODULAR_P (array_type)))
2287     array_type = TREE_TYPE (TYPE_FIELDS (array_type));
2288
2289   if (TREE_CODE (array_type) == ARRAY_TYPE
2290       || (TREE_CODE (array_type) == INTEGER_TYPE
2291           && TYPE_HAS_ACTUAL_BOUNDS_P (array_type)))
2292     bound_list = TYPE_ACTUAL_BOUNDS (array_type);
2293
2294   /* First make the list for a CONSTRUCTOR for the template.  Go down the
2295      field list of the template instead of the type chain because this
2296      array might be an Ada array of arrays and we can't tell where the
2297      nested arrays stop being the underlying object.  */
2298
2299   for (field = TYPE_FIELDS (template_type); field;
2300        (bound_list
2301         ? (bound_list = TREE_CHAIN (bound_list))
2302         : (array_type = TREE_TYPE (array_type))),
2303        field = TREE_CHAIN (TREE_CHAIN (field)))
2304     {
2305       tree bounds, min, max;
2306
2307       /* If we have a bound list, get the bounds from there.  Likewise
2308          for an ARRAY_TYPE.  Otherwise, if expr is a PARM_DECL with
2309          DECL_BY_COMPONENT_PTR_P, use the bounds of the field in the template.
2310          This will give us a maximum range.  */
2311       if (bound_list)
2312         bounds = TREE_VALUE (bound_list);
2313       else if (TREE_CODE (array_type) == ARRAY_TYPE)
2314         bounds = TYPE_INDEX_TYPE (TYPE_DOMAIN (array_type));
2315       else if (expr && TREE_CODE (expr) == PARM_DECL
2316                && DECL_BY_COMPONENT_PTR_P (expr))
2317         bounds = TREE_TYPE (field);
2318       else
2319         gcc_unreachable ();
2320
2321       min = convert (TREE_TYPE (field), TYPE_MIN_VALUE (bounds));
2322       max = convert (TREE_TYPE (TREE_CHAIN (field)), TYPE_MAX_VALUE (bounds));
2323
2324       /* If either MIN or MAX involve a PLACEHOLDER_EXPR, we must
2325          substitute it from OBJECT.  */
2326       min = SUBSTITUTE_PLACEHOLDER_IN_EXPR (min, expr);
2327       max = SUBSTITUTE_PLACEHOLDER_IN_EXPR (max, expr);
2328
2329       template_elts = tree_cons (TREE_CHAIN (field), max,
2330                                  tree_cons (field, min, template_elts));
2331     }
2332
2333   return gnat_build_constructor (template_type, nreverse (template_elts));
2334 }
2335 \f
2336 /* Build a 32bit VMS descriptor from a Mechanism_Type, which must specify
2337    a descriptor type, and the GCC type of an object.  Each FIELD_DECL
2338    in the type contains in its DECL_INITIAL the expression to use when
2339    a constructor is made for the type.  GNAT_ENTITY is an entity used
2340    to print out an error message if the mechanism cannot be applied to
2341    an object of that type and also for the name.  */
2342
2343 tree
2344 build_vms_descriptor32 (tree type, Mechanism_Type mech, Entity_Id gnat_entity)
2345 {
2346   tree record_type = make_node (RECORD_TYPE);
2347   tree pointer32_type;
2348   tree field_list = 0;
2349   int klass;
2350   int dtype = 0;
2351   tree inner_type;
2352   int ndim;
2353   int i;
2354   tree *idx_arr;
2355   tree tem;
2356
2357   /* If TYPE is an unconstrained array, use the underlying array type.  */
2358   if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
2359     type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type))));
2360
2361   /* If this is an array, compute the number of dimensions in the array,
2362      get the index types, and point to the inner type.  */
2363   if (TREE_CODE (type) != ARRAY_TYPE)
2364     ndim = 0;
2365   else
2366     for (ndim = 1, inner_type = type;
2367          TREE_CODE (TREE_TYPE (inner_type)) == ARRAY_TYPE
2368          && TYPE_MULTI_ARRAY_P (TREE_TYPE (inner_type));
2369          ndim++, inner_type = TREE_TYPE (inner_type))
2370       ;
2371
2372   idx_arr = (tree *) alloca (ndim * sizeof (tree));
2373
2374   if (mech != By_Descriptor_NCA && mech != By_Short_Descriptor_NCA
2375       && TREE_CODE (type) == ARRAY_TYPE && TYPE_CONVENTION_FORTRAN_P (type))
2376     for (i = ndim - 1, inner_type = type;
2377          i >= 0;
2378          i--, inner_type = TREE_TYPE (inner_type))
2379       idx_arr[i] = TYPE_DOMAIN (inner_type);
2380   else
2381     for (i = 0, inner_type = type;
2382          i < ndim;
2383          i++, inner_type = TREE_TYPE (inner_type))
2384       idx_arr[i] = TYPE_DOMAIN (inner_type);
2385
2386   /* Now get the DTYPE value.  */
2387   switch (TREE_CODE (type))
2388     {
2389     case INTEGER_TYPE:
2390     case ENUMERAL_TYPE:
2391     case BOOLEAN_TYPE:
2392       if (TYPE_VAX_FLOATING_POINT_P (type))
2393         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2394           {
2395           case 6:
2396             dtype = 10;
2397             break;
2398           case 9:
2399             dtype = 11;
2400             break;
2401           case 15:
2402             dtype = 27;
2403             break;
2404           }
2405       else
2406         switch (GET_MODE_BITSIZE (TYPE_MODE (type)))
2407           {
2408           case 8:
2409             dtype = TYPE_UNSIGNED (type) ? 2 : 6;
2410             break;
2411           case 16:
2412             dtype = TYPE_UNSIGNED (type) ? 3 : 7;
2413             break;
2414           case 32:
2415             dtype = TYPE_UNSIGNED (type) ? 4 : 8;
2416             break;
2417           case 64:
2418             dtype = TYPE_UNSIGNED (type) ? 5 : 9;
2419             break;
2420           case 128:
2421             dtype = TYPE_UNSIGNED (type) ? 25 : 26;
2422             break;
2423           }
2424       break;
2425
2426     case REAL_TYPE:
2427       dtype = GET_MODE_BITSIZE (TYPE_MODE (type)) == 32 ? 52 : 53;
2428       break;
2429
2430     case COMPLEX_TYPE:
2431       if (TREE_CODE (TREE_TYPE (type)) == INTEGER_TYPE
2432           && TYPE_VAX_FLOATING_POINT_P (type))
2433         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2434           {
2435           case 6:
2436             dtype = 12;
2437             break;
2438           case 9:
2439             dtype = 13;
2440             break;
2441           case 15:
2442             dtype = 29;
2443           }
2444       else
2445         dtype = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) == 32 ? 54: 55;
2446       break;
2447
2448     case ARRAY_TYPE:
2449       dtype = 14;
2450       break;
2451
2452     default:
2453       break;
2454     }
2455
2456   /* Get the CLASS value.  */
2457   switch (mech)
2458     {
2459     case By_Descriptor_A:
2460     case By_Short_Descriptor_A:
2461       klass = 4;
2462       break;
2463     case By_Descriptor_NCA:
2464     case By_Short_Descriptor_NCA:
2465       klass = 10;
2466       break;
2467     case By_Descriptor_SB:
2468     case By_Short_Descriptor_SB:
2469       klass = 15;
2470       break;
2471     case By_Descriptor:
2472     case By_Short_Descriptor:
2473     case By_Descriptor_S:
2474     case By_Short_Descriptor_S:
2475     default:
2476       klass = 1;
2477       break;
2478     }
2479
2480   /* Make the type for a descriptor for VMS.  The first four fields
2481      are the same for all types.  */
2482
2483   field_list
2484     = chainon (field_list,
2485                make_descriptor_field
2486                ("LENGTH", gnat_type_for_size (16, 1), record_type,
2487                 size_in_bytes ((mech == By_Descriptor_A ||
2488                                 mech == By_Short_Descriptor_A)
2489                                ? inner_type : type)));
2490
2491   field_list = chainon (field_list,
2492                         make_descriptor_field ("DTYPE",
2493                                                gnat_type_for_size (8, 1),
2494                                                record_type, size_int (dtype)));
2495   field_list = chainon (field_list,
2496                         make_descriptor_field ("CLASS",
2497                                                gnat_type_for_size (8, 1),
2498                                                record_type, size_int (klass)));
2499
2500   /* Of course this will crash at run-time if the address space is not
2501      within the low 32 bits, but there is nothing else we can do.  */
2502   pointer32_type = build_pointer_type_for_mode (type, SImode, false);
2503
2504   field_list
2505     = chainon (field_list,
2506                make_descriptor_field
2507                ("POINTER", pointer32_type, record_type,
2508                 build_unary_op (ADDR_EXPR,
2509                                 pointer32_type,
2510                                 build0 (PLACEHOLDER_EXPR, type))));
2511
2512   switch (mech)
2513     {
2514     case By_Descriptor:
2515     case By_Short_Descriptor:
2516     case By_Descriptor_S:
2517     case By_Short_Descriptor_S:
2518       break;
2519
2520     case By_Descriptor_SB:
2521     case By_Short_Descriptor_SB:
2522       field_list
2523         = chainon (field_list,
2524                    make_descriptor_field
2525                    ("SB_L1", gnat_type_for_size (32, 1), record_type,
2526                     TREE_CODE (type) == ARRAY_TYPE
2527                     ? TYPE_MIN_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2528       field_list
2529         = chainon (field_list,
2530                    make_descriptor_field
2531                    ("SB_U1", gnat_type_for_size (32, 1), record_type,
2532                     TREE_CODE (type) == ARRAY_TYPE
2533                     ? TYPE_MAX_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2534       break;
2535
2536     case By_Descriptor_A:
2537     case By_Short_Descriptor_A:
2538     case By_Descriptor_NCA:
2539     case By_Short_Descriptor_NCA:
2540       field_list = chainon (field_list,
2541                             make_descriptor_field ("SCALE",
2542                                                    gnat_type_for_size (8, 1),
2543                                                    record_type,
2544                                                    size_zero_node));
2545
2546       field_list = chainon (field_list,
2547                             make_descriptor_field ("DIGITS",
2548                                                    gnat_type_for_size (8, 1),
2549                                                    record_type,
2550                                                    size_zero_node));
2551
2552       field_list
2553         = chainon (field_list,
2554                    make_descriptor_field
2555                    ("AFLAGS", gnat_type_for_size (8, 1), record_type,
2556                     size_int ((mech == By_Descriptor_NCA ||
2557                               mech == By_Short_Descriptor_NCA)
2558                               ? 0
2559                               /* Set FL_COLUMN, FL_COEFF, and FL_BOUNDS.  */
2560                               : (TREE_CODE (type) == ARRAY_TYPE
2561                                  && TYPE_CONVENTION_FORTRAN_P (type)
2562                                  ? 224 : 192))));
2563
2564       field_list = chainon (field_list,
2565                             make_descriptor_field ("DIMCT",
2566                                                    gnat_type_for_size (8, 1),
2567                                                    record_type,
2568                                                    size_int (ndim)));
2569
2570       field_list = chainon (field_list,
2571                             make_descriptor_field ("ARSIZE",
2572                                                    gnat_type_for_size (32, 1),
2573                                                    record_type,
2574                                                    size_in_bytes (type)));
2575
2576       /* Now build a pointer to the 0,0,0... element.  */
2577       tem = build0 (PLACEHOLDER_EXPR, type);
2578       for (i = 0, inner_type = type; i < ndim;
2579            i++, inner_type = TREE_TYPE (inner_type))
2580         tem = build4 (ARRAY_REF, TREE_TYPE (inner_type), tem,
2581                       convert (TYPE_DOMAIN (inner_type), size_zero_node),
2582                       NULL_TREE, NULL_TREE);
2583
2584       field_list
2585         = chainon (field_list,
2586                    make_descriptor_field
2587                    ("A0",
2588                     build_pointer_type_for_mode (inner_type, SImode, false),
2589                     record_type,
2590                     build1 (ADDR_EXPR,
2591                             build_pointer_type_for_mode (inner_type, SImode,
2592                                                          false),
2593                             tem)));
2594
2595       /* Next come the addressing coefficients.  */
2596       tem = size_one_node;
2597       for (i = 0; i < ndim; i++)
2598         {
2599           char fname[3];
2600           tree idx_length
2601             = size_binop (MULT_EXPR, tem,
2602                           size_binop (PLUS_EXPR,
2603                                       size_binop (MINUS_EXPR,
2604                                                   TYPE_MAX_VALUE (idx_arr[i]),
2605                                                   TYPE_MIN_VALUE (idx_arr[i])),
2606                                       size_int (1)));
2607
2608           fname[0] = ((mech == By_Descriptor_NCA ||
2609                        mech == By_Short_Descriptor_NCA) ? 'S' : 'M');
2610           fname[1] = '0' + i, fname[2] = 0;
2611           field_list
2612             = chainon (field_list,
2613                        make_descriptor_field (fname,
2614                                               gnat_type_for_size (32, 1),
2615                                               record_type, idx_length));
2616
2617           if (mech == By_Descriptor_NCA || mech == By_Short_Descriptor_NCA)
2618             tem = idx_length;
2619         }
2620
2621       /* Finally here are the bounds.  */
2622       for (i = 0; i < ndim; i++)
2623         {
2624           char fname[3];
2625
2626           fname[0] = 'L', fname[1] = '0' + i, fname[2] = 0;
2627           field_list
2628             = chainon (field_list,
2629                        make_descriptor_field
2630                        (fname, gnat_type_for_size (32, 1), record_type,
2631                         TYPE_MIN_VALUE (idx_arr[i])));
2632
2633           fname[0] = 'U';
2634           field_list
2635             = chainon (field_list,
2636                        make_descriptor_field
2637                        (fname, gnat_type_for_size (32, 1), record_type,
2638                         TYPE_MAX_VALUE (idx_arr[i])));
2639         }
2640       break;
2641
2642     default:
2643       post_error ("unsupported descriptor type for &", gnat_entity);
2644     }
2645
2646   TYPE_NAME (record_type) = create_concat_name (gnat_entity, "DESC");
2647   finish_record_type (record_type, field_list, 0, false);
2648   return record_type;
2649 }
2650
2651 /* Build a 64bit VMS descriptor from a Mechanism_Type, which must specify
2652    a descriptor type, and the GCC type of an object.  Each FIELD_DECL
2653    in the type contains in its DECL_INITIAL the expression to use when
2654    a constructor is made for the type.  GNAT_ENTITY is an entity used
2655    to print out an error message if the mechanism cannot be applied to
2656    an object of that type and also for the name.  */
2657
2658 tree
2659 build_vms_descriptor (tree type, Mechanism_Type mech, Entity_Id gnat_entity)
2660 {
2661   tree record64_type = make_node (RECORD_TYPE);
2662   tree pointer64_type;
2663   tree field_list64 = 0;
2664   int klass;
2665   int dtype = 0;
2666   tree inner_type;
2667   int ndim;
2668   int i;
2669   tree *idx_arr;
2670   tree tem;
2671
2672   /* If TYPE is an unconstrained array, use the underlying array type.  */
2673   if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
2674     type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type))));
2675
2676   /* If this is an array, compute the number of dimensions in the array,
2677      get the index types, and point to the inner type.  */
2678   if (TREE_CODE (type) != ARRAY_TYPE)
2679     ndim = 0;
2680   else
2681     for (ndim = 1, inner_type = type;
2682          TREE_CODE (TREE_TYPE (inner_type)) == ARRAY_TYPE
2683          && TYPE_MULTI_ARRAY_P (TREE_TYPE (inner_type));
2684          ndim++, inner_type = TREE_TYPE (inner_type))
2685       ;
2686
2687   idx_arr = (tree *) alloca (ndim * sizeof (tree));
2688
2689   if (mech != By_Descriptor_NCA
2690       && TREE_CODE (type) == ARRAY_TYPE && TYPE_CONVENTION_FORTRAN_P (type))
2691     for (i = ndim - 1, inner_type = type;
2692          i >= 0;
2693          i--, inner_type = TREE_TYPE (inner_type))
2694       idx_arr[i] = TYPE_DOMAIN (inner_type);
2695   else
2696     for (i = 0, inner_type = type;
2697          i < ndim;
2698          i++, inner_type = TREE_TYPE (inner_type))
2699       idx_arr[i] = TYPE_DOMAIN (inner_type);
2700
2701   /* Now get the DTYPE value.  */
2702   switch (TREE_CODE (type))
2703     {
2704     case INTEGER_TYPE:
2705     case ENUMERAL_TYPE:
2706     case BOOLEAN_TYPE:
2707       if (TYPE_VAX_FLOATING_POINT_P (type))
2708         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2709           {
2710           case 6:
2711             dtype = 10;
2712             break;
2713           case 9:
2714             dtype = 11;
2715             break;
2716           case 15:
2717             dtype = 27;
2718             break;
2719           }
2720       else
2721         switch (GET_MODE_BITSIZE (TYPE_MODE (type)))
2722           {
2723           case 8:
2724             dtype = TYPE_UNSIGNED (type) ? 2 : 6;
2725             break;
2726           case 16:
2727             dtype = TYPE_UNSIGNED (type) ? 3 : 7;
2728             break;
2729           case 32:
2730             dtype = TYPE_UNSIGNED (type) ? 4 : 8;
2731             break;
2732           case 64:
2733             dtype = TYPE_UNSIGNED (type) ? 5 : 9;
2734             break;
2735           case 128:
2736             dtype = TYPE_UNSIGNED (type) ? 25 : 26;
2737             break;
2738           }
2739       break;
2740
2741     case REAL_TYPE:
2742       dtype = GET_MODE_BITSIZE (TYPE_MODE (type)) == 32 ? 52 : 53;
2743       break;
2744
2745     case COMPLEX_TYPE:
2746       if (TREE_CODE (TREE_TYPE (type)) == INTEGER_TYPE
2747           && TYPE_VAX_FLOATING_POINT_P (type))
2748         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2749           {
2750           case 6:
2751             dtype = 12;
2752             break;
2753           case 9:
2754             dtype = 13;
2755             break;
2756           case 15:
2757             dtype = 29;
2758           }
2759       else
2760         dtype = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) == 32 ? 54: 55;
2761       break;
2762
2763     case ARRAY_TYPE:
2764       dtype = 14;
2765       break;
2766
2767     default:
2768       break;
2769     }
2770
2771   /* Get the CLASS value.  */
2772   switch (mech)
2773     {
2774     case By_Descriptor_A:
2775       klass = 4;
2776       break;
2777     case By_Descriptor_NCA:
2778       klass = 10;
2779       break;
2780     case By_Descriptor_SB:
2781       klass = 15;
2782       break;
2783     case By_Descriptor:
2784     case By_Descriptor_S:
2785     default:
2786       klass = 1;
2787       break;
2788     }
2789
2790   /* Make the type for a 64bit descriptor for VMS.  The first six fields
2791      are the same for all types.  */
2792
2793   field_list64 = chainon (field_list64,
2794                         make_descriptor_field ("MBO",
2795                                                gnat_type_for_size (16, 1),
2796                                                record64_type, size_int (1)));
2797
2798   field_list64 = chainon (field_list64,
2799                         make_descriptor_field ("DTYPE",
2800                                                gnat_type_for_size (8, 1),
2801                                                record64_type, size_int (dtype)));
2802   field_list64 = chainon (field_list64,
2803                         make_descriptor_field ("CLASS",
2804                                                gnat_type_for_size (8, 1),
2805                                                record64_type, size_int (klass)));
2806
2807   field_list64 = chainon (field_list64,
2808                         make_descriptor_field ("MBMO",
2809                                                gnat_type_for_size (32, 1),
2810                                                record64_type, ssize_int (-1)));
2811
2812   field_list64
2813     = chainon (field_list64,
2814                make_descriptor_field
2815                ("LENGTH", gnat_type_for_size (64, 1), record64_type,
2816                 size_in_bytes (mech == By_Descriptor_A ? inner_type : type)));
2817
2818   pointer64_type = build_pointer_type_for_mode (type, DImode, false);
2819
2820   field_list64
2821     = chainon (field_list64,
2822                make_descriptor_field
2823                ("POINTER", pointer64_type, record64_type,
2824                 build_unary_op (ADDR_EXPR,
2825                                 pointer64_type,
2826                                 build0 (PLACEHOLDER_EXPR, type))));
2827
2828   switch (mech)
2829     {
2830     case By_Descriptor:
2831     case By_Descriptor_S:
2832       break;
2833
2834     case By_Descriptor_SB:
2835       field_list64
2836         = chainon (field_list64,
2837                    make_descriptor_field
2838                    ("SB_L1", gnat_type_for_size (64, 1), record64_type,
2839                     TREE_CODE (type) == ARRAY_TYPE
2840                     ? TYPE_MIN_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2841       field_list64
2842         = chainon (field_list64,
2843                    make_descriptor_field
2844                    ("SB_U1", gnat_type_for_size (64, 1), record64_type,
2845                     TREE_CODE (type) == ARRAY_TYPE
2846                     ? TYPE_MAX_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2847       break;
2848
2849     case By_Descriptor_A:
2850     case By_Descriptor_NCA:
2851       field_list64 = chainon (field_list64,
2852                             make_descriptor_field ("SCALE",
2853                                                    gnat_type_for_size (8, 1),
2854                                                    record64_type,
2855                                                    size_zero_node));
2856
2857       field_list64 = chainon (field_list64,
2858                             make_descriptor_field ("DIGITS",
2859                                                    gnat_type_for_size (8, 1),
2860                                                    record64_type,
2861                                                    size_zero_node));
2862
2863       field_list64
2864         = chainon (field_list64,
2865                    make_descriptor_field
2866                    ("AFLAGS", gnat_type_for_size (8, 1), record64_type,
2867                     size_int (mech == By_Descriptor_NCA
2868                               ? 0
2869                               /* Set FL_COLUMN, FL_COEFF, and FL_BOUNDS.  */
2870                               : (TREE_CODE (type) == ARRAY_TYPE
2871                                  && TYPE_CONVENTION_FORTRAN_P (type)
2872                                  ? 224 : 192))));
2873
2874       field_list64 = chainon (field_list64,
2875                             make_descriptor_field ("DIMCT",
2876                                                    gnat_type_for_size (8, 1),
2877                                                    record64_type,
2878                                                    size_int (ndim)));
2879
2880       field_list64 = chainon (field_list64,
2881                             make_descriptor_field ("MBZ",
2882                                                    gnat_type_for_size (32, 1),
2883                                                    record64_type,
2884                                                    size_int (0)));
2885       field_list64 = chainon (field_list64,
2886                             make_descriptor_field ("ARSIZE",
2887                                                    gnat_type_for_size (64, 1),
2888                                                    record64_type,
2889                                                    size_in_bytes (type)));
2890
2891       /* Now build a pointer to the 0,0,0... element.  */
2892       tem = build0 (PLACEHOLDER_EXPR, type);
2893       for (i = 0, inner_type = type; i < ndim;
2894            i++, inner_type = TREE_TYPE (inner_type))
2895         tem = build4 (ARRAY_REF, TREE_TYPE (inner_type), tem,
2896                       convert (TYPE_DOMAIN (inner_type), size_zero_node),
2897                       NULL_TREE, NULL_TREE);
2898
2899       field_list64
2900         = chainon (field_list64,
2901                    make_descriptor_field
2902                    ("A0",
2903                     build_pointer_type_for_mode (inner_type, DImode, false),
2904                     record64_type,
2905                     build1 (ADDR_EXPR,
2906                             build_pointer_type_for_mode (inner_type, DImode,
2907                                                          false),
2908                             tem)));
2909
2910       /* Next come the addressing coefficients.  */
2911       tem = size_one_node;
2912       for (i = 0; i < ndim; i++)
2913         {
2914           char fname[3];
2915           tree idx_length
2916             = size_binop (MULT_EXPR, tem,
2917                           size_binop (PLUS_EXPR,
2918                                       size_binop (MINUS_EXPR,
2919                                                   TYPE_MAX_VALUE (idx_arr[i]),
2920                                                   TYPE_MIN_VALUE (idx_arr[i])),
2921                                       size_int (1)));
2922
2923           fname[0] = (mech == By_Descriptor_NCA ? 'S' : 'M');
2924           fname[1] = '0' + i, fname[2] = 0;
2925           field_list64
2926             = chainon (field_list64,
2927                        make_descriptor_field (fname,
2928                                               gnat_type_for_size (64, 1),
2929                                               record64_type, idx_length));
2930
2931           if (mech == By_Descriptor_NCA)
2932             tem = idx_length;
2933         }
2934
2935       /* Finally here are the bounds.  */
2936       for (i = 0; i < ndim; i++)
2937         {
2938           char fname[3];
2939
2940           fname[0] = 'L', fname[1] = '0' + i, fname[2] = 0;
2941           field_list64
2942             = chainon (field_list64,
2943                        make_descriptor_field
2944                        (fname, gnat_type_for_size (64, 1), record64_type,
2945                         TYPE_MIN_VALUE (idx_arr[i])));
2946
2947           fname[0] = 'U';
2948           field_list64
2949             = chainon (field_list64,
2950                        make_descriptor_field
2951                        (fname, gnat_type_for_size (64, 1), record64_type,
2952                         TYPE_MAX_VALUE (idx_arr[i])));
2953         }
2954       break;
2955
2956     default:
2957       post_error ("unsupported descriptor type for &", gnat_entity);
2958     }
2959
2960   TYPE_NAME (record64_type) = create_concat_name (gnat_entity, "DESC64");
2961   finish_record_type (record64_type, field_list64, 0, false);
2962   return record64_type;
2963 }
2964
2965 /* Utility routine for above code to make a field.  */
2966
2967 static tree
2968 make_descriptor_field (const char *name, tree type,
2969                        tree rec_type, tree initial)
2970 {
2971   tree field
2972     = create_field_decl (get_identifier (name), type, rec_type, 0, 0, 0, 0);
2973
2974   DECL_INITIAL (field) = initial;
2975   return field;
2976 }
2977
2978 /* Convert GNU_EXPR, a pointer to a 64bit VMS descriptor, to GNU_TYPE, a
2979    regular pointer or fat pointer type.  GNAT_SUBPROG is the subprogram to
2980    which the VMS descriptor is passed.  */
2981
2982 static tree
2983 convert_vms_descriptor64 (tree gnu_type, tree gnu_expr, Entity_Id gnat_subprog)
2984 {
2985   tree desc_type = TREE_TYPE (TREE_TYPE (gnu_expr));
2986   tree desc = build1 (INDIRECT_REF, desc_type, gnu_expr);
2987   /* The CLASS field is the 3rd field in the descriptor.  */
2988   tree klass = TREE_CHAIN (TREE_CHAIN (TYPE_FIELDS (desc_type)));
2989   /* The POINTER field is the 6th field in the descriptor.  */
2990   tree pointer64 = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (klass)));
2991
2992   /* Retrieve the value of the POINTER field.  */
2993   tree gnu_expr64
2994     = build3 (COMPONENT_REF, TREE_TYPE (pointer64), desc, pointer64, NULL_TREE);
2995
2996   if (POINTER_TYPE_P (gnu_type))
2997     return convert (gnu_type, gnu_expr64);
2998
2999   else if (TYPE_IS_FAT_POINTER_P (gnu_type))
3000     {
3001       tree p_array_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
3002       tree p_bounds_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_type)));
3003       tree template_type = TREE_TYPE (p_bounds_type);
3004       tree min_field = TYPE_FIELDS (template_type);
3005       tree max_field = TREE_CHAIN (TYPE_FIELDS (template_type));
3006       tree template_tree, template_addr, aflags, dimct, t, u;
3007       /* See the head comment of build_vms_descriptor.  */
3008       int iklass = TREE_INT_CST_LOW (DECL_INITIAL (klass));
3009       tree lfield, ufield;
3010
3011       /* Convert POINTER to the type of the P_ARRAY field.  */
3012       gnu_expr64 = convert (p_array_type, gnu_expr64);
3013
3014       switch (iklass)
3015         {
3016         case 1:  /* Class S  */
3017         case 15: /* Class SB */
3018           /* Build {1, LENGTH} template; LENGTH64 is the 5th field.  */
3019           t = TREE_CHAIN (TREE_CHAIN (klass));
3020           t = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3021           t = tree_cons (min_field,
3022                          convert (TREE_TYPE (min_field), integer_one_node),
3023                          tree_cons (max_field,
3024                                     convert (TREE_TYPE (max_field), t),
3025                                     NULL_TREE));
3026           template_tree = gnat_build_constructor (template_type, t);
3027           template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, template_tree);
3028
3029           /* For class S, we are done.  */
3030           if (iklass == 1)
3031             break;
3032
3033           /* Test that we really have a SB descriptor, like DEC Ada.  */
3034           t = build3 (COMPONENT_REF, TREE_TYPE (klass), desc, klass, NULL);
3035           u = convert (TREE_TYPE (klass), DECL_INITIAL (klass));
3036           u = build_binary_op (EQ_EXPR, integer_type_node, t, u);
3037           /* If so, there is already a template in the descriptor and
3038              it is located right after the POINTER field.  The fields are
3039              64bits so they must be repacked. */
3040           t = TREE_CHAIN (pointer64);
3041           lfield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3042           lfield = convert (TREE_TYPE (TYPE_FIELDS (template_type)), lfield);
3043
3044           t = TREE_CHAIN (t);
3045           ufield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3046           ufield = convert
3047            (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (template_type))), ufield);
3048
3049           /* Build the template in the form of a constructor. */
3050           t = tree_cons (TYPE_FIELDS (template_type), lfield,
3051                          tree_cons (TREE_CHAIN (TYPE_FIELDS (template_type)),
3052                                     ufield, NULL_TREE));
3053           template_tree = gnat_build_constructor (template_type, t);
3054
3055           /* Otherwise use the {1, LENGTH} template we build above.  */
3056           template_addr = build3 (COND_EXPR, p_bounds_type, u,
3057                                   build_unary_op (ADDR_EXPR, p_bounds_type,
3058                                                  template_tree),
3059                                   template_addr);
3060           break;
3061
3062         case 4:  /* Class A */
3063           /* The AFLAGS field is the 3rd field after the pointer in the
3064              descriptor.  */
3065           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (pointer64)));
3066           aflags = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3067           /* The DIMCT field is the next field in the descriptor after
3068              aflags.  */
3069           t = TREE_CHAIN (t);
3070           dimct = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3071           /* Raise CONSTRAINT_ERROR if either more than 1 dimension
3072              or FL_COEFF or FL_BOUNDS not set.  */
3073           u = build_int_cst (TREE_TYPE (aflags), 192);
3074           u = build_binary_op (TRUTH_OR_EXPR, integer_type_node,
3075                                build_binary_op (NE_EXPR, integer_type_node,
3076                                                 dimct,
3077                                                 convert (TREE_TYPE (dimct),
3078                                                          size_one_node)),
3079                                build_binary_op (NE_EXPR, integer_type_node,
3080                                                 build2 (BIT_AND_EXPR,
3081                                                         TREE_TYPE (aflags),
3082                                                         aflags, u),
3083                                                 u));
3084           /* There is already a template in the descriptor and it is located
3085              in block 3.  The fields are 64bits so they must be repacked. */
3086           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (TREE_CHAIN
3087               (t)))));
3088           lfield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3089           lfield = convert (TREE_TYPE (TYPE_FIELDS (template_type)), lfield);
3090
3091           t = TREE_CHAIN (t);
3092           ufield = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3093           ufield = convert
3094            (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (template_type))), ufield);
3095
3096           /* Build the template in the form of a constructor. */
3097           t = tree_cons (TYPE_FIELDS (template_type), lfield,
3098                          tree_cons (TREE_CHAIN (TYPE_FIELDS (template_type)),
3099                                     ufield, NULL_TREE));
3100           template_tree = gnat_build_constructor (template_type, t);
3101           template_tree = build3 (COND_EXPR, template_type, u,
3102                             build_call_raise (CE_Length_Check_Failed, Empty,
3103                                               N_Raise_Constraint_Error),
3104                             template_tree);
3105           template_addr
3106             = build_unary_op (ADDR_EXPR, p_bounds_type, template_tree);
3107           break;
3108
3109         case 10: /* Class NCA */
3110         default:
3111           post_error ("unsupported descriptor type for &", gnat_subprog);
3112           template_addr = integer_zero_node;
3113           break;
3114         }
3115
3116       /* Build the fat pointer in the form of a constructor.  */
3117       t = tree_cons (TYPE_FIELDS (gnu_type), gnu_expr64,
3118                      tree_cons (TREE_CHAIN (TYPE_FIELDS (gnu_type)),
3119                                 template_addr, NULL_TREE));
3120       return gnat_build_constructor (gnu_type, t);
3121     }
3122
3123   else
3124     gcc_unreachable ();
3125 }
3126
3127 /* Convert GNU_EXPR, a pointer to a 32bit VMS descriptor, to GNU_TYPE, a
3128    regular pointer or fat pointer type.  GNAT_SUBPROG is the subprogram to
3129    which the VMS descriptor is passed.  */
3130
3131 static tree
3132 convert_vms_descriptor32 (tree gnu_type, tree gnu_expr, Entity_Id gnat_subprog)
3133 {
3134   tree desc_type = TREE_TYPE (TREE_TYPE (gnu_expr));
3135   tree desc = build1 (INDIRECT_REF, desc_type, gnu_expr);
3136   /* The CLASS field is the 3rd field in the descriptor.  */
3137   tree klass = TREE_CHAIN (TREE_CHAIN (TYPE_FIELDS (desc_type)));
3138   /* The POINTER field is the 4th field in the descriptor.  */
3139   tree pointer = TREE_CHAIN (klass);
3140
3141   /* Retrieve the value of the POINTER field.  */
3142   tree gnu_expr32
3143     = build3 (COMPONENT_REF, TREE_TYPE (pointer), desc, pointer, NULL_TREE);
3144
3145   if (POINTER_TYPE_P (gnu_type))
3146     return convert (gnu_type, gnu_expr32);
3147
3148   else if (TYPE_IS_FAT_POINTER_P (gnu_type))
3149     {
3150       tree p_array_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
3151       tree p_bounds_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_type)));
3152       tree template_type = TREE_TYPE (p_bounds_type);
3153       tree min_field = TYPE_FIELDS (template_type);
3154       tree max_field = TREE_CHAIN (TYPE_FIELDS (template_type));
3155       tree template_tree, template_addr, aflags, dimct, t, u;
3156       /* See the head comment of build_vms_descriptor.  */
3157       int iklass = TREE_INT_CST_LOW (DECL_INITIAL (klass));
3158
3159       /* Convert POINTER to the type of the P_ARRAY field.  */
3160       gnu_expr32 = convert (p_array_type, gnu_expr32);
3161
3162       switch (iklass)
3163         {
3164         case 1:  /* Class S  */
3165         case 15: /* Class SB */
3166           /* Build {1, LENGTH} template; LENGTH is the 1st field.  */
3167           t = TYPE_FIELDS (desc_type);
3168           t = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3169           t = tree_cons (min_field,
3170                          convert (TREE_TYPE (min_field), integer_one_node),
3171                          tree_cons (max_field,
3172                                     convert (TREE_TYPE (max_field), t),
3173                                     NULL_TREE));
3174           template_tree = gnat_build_constructor (template_type, t);
3175           template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, template_tree);
3176
3177           /* For class S, we are done.  */
3178           if (iklass == 1)
3179             break;
3180
3181           /* Test that we really have a SB descriptor, like DEC Ada.  */
3182           t = build3 (COMPONENT_REF, TREE_TYPE (klass), desc, klass, NULL);
3183           u = convert (TREE_TYPE (klass), DECL_INITIAL (klass));
3184           u = build_binary_op (EQ_EXPR, integer_type_node, t, u);
3185           /* If so, there is already a template in the descriptor and
3186              it is located right after the POINTER field.  */
3187           t = TREE_CHAIN (pointer);
3188           template_tree
3189             = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3190           /* Otherwise use the {1, LENGTH} template we build above.  */
3191           template_addr = build3 (COND_EXPR, p_bounds_type, u,
3192                                   build_unary_op (ADDR_EXPR, p_bounds_type,
3193                                                  template_tree),
3194                                   template_addr);
3195           break;
3196
3197         case 4:  /* Class A */
3198           /* The AFLAGS field is the 7th field in the descriptor.  */
3199           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (pointer)));
3200           aflags = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3201           /* The DIMCT field is the 8th field in the descriptor.  */
3202           t = TREE_CHAIN (t);
3203           dimct = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3204           /* Raise CONSTRAINT_ERROR if either more than 1 dimension
3205              or FL_COEFF or FL_BOUNDS not set.  */
3206           u = build_int_cst (TREE_TYPE (aflags), 192);
3207           u = build_binary_op (TRUTH_OR_EXPR, integer_type_node,
3208                                build_binary_op (NE_EXPR, integer_type_node,
3209                                                 dimct,
3210                                                 convert (TREE_TYPE (dimct),
3211                                                          size_one_node)),
3212                                build_binary_op (NE_EXPR, integer_type_node,
3213                                                 build2 (BIT_AND_EXPR,
3214                                                         TREE_TYPE (aflags),
3215                                                         aflags, u),
3216                                                 u));
3217           /* There is already a template in the descriptor and it is
3218              located at the start of block 3 (12th field).  */
3219           t = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (t))));
3220           template_tree
3221             = build3 (COMPONENT_REF, TREE_TYPE (t), desc, t, NULL_TREE);
3222           template_tree = build3 (COND_EXPR, TREE_TYPE (t), u,
3223                             build_call_raise (CE_Length_Check_Failed, Empty,
3224                                               N_Raise_Constraint_Error),
3225                             template_tree);
3226           template_addr
3227             = build_unary_op (ADDR_EXPR, p_bounds_type, template_tree);
3228           break;
3229
3230         case 10: /* Class NCA */
3231         default:
3232           post_error ("unsupported descriptor type for &", gnat_subprog);
3233           template_addr = integer_zero_node;
3234           break;
3235         }
3236
3237       /* Build the fat pointer in the form of a constructor.  */
3238       t = tree_cons (TYPE_FIELDS (gnu_type), gnu_expr32,
3239                      tree_cons (TREE_CHAIN (TYPE_FIELDS (gnu_type)),
3240                                 template_addr, NULL_TREE));
3241
3242       return gnat_build_constructor (gnu_type, t);
3243     }
3244
3245   else
3246     gcc_unreachable ();
3247 }
3248
3249 /* Convert GNU_EXPR, a pointer to a VMS descriptor, to GNU_TYPE, a regular
3250    pointer or fat pointer type.  GNU_EXPR_ALT_TYPE is the alternate (32-bit)
3251    pointer type of GNU_EXPR.  GNAT_SUBPROG is the subprogram to which the
3252    VMS descriptor is passed.  */
3253
3254 static tree
3255 convert_vms_descriptor (tree gnu_type, tree gnu_expr, tree gnu_expr_alt_type,
3256                         Entity_Id gnat_subprog)
3257 {
3258   tree desc_type = TREE_TYPE (TREE_TYPE (gnu_expr));
3259   tree desc = build1 (INDIRECT_REF, desc_type, gnu_expr);
3260   tree mbo = TYPE_FIELDS (desc_type);
3261   const char *mbostr = IDENTIFIER_POINTER (DECL_NAME (mbo));
3262   tree mbmo = TREE_CHAIN (TREE_CHAIN (TREE_CHAIN (mbo)));
3263   tree is64bit, gnu_expr32, gnu_expr64;
3264
3265   /* If the field name is not MBO, it must be 32-bit and no alternate.
3266      Otherwise primary must be 64-bit and alternate 32-bit.  */
3267   if (strcmp (mbostr, "MBO") != 0)
3268     return convert_vms_descriptor32 (gnu_type, gnu_expr, gnat_subprog);
3269
3270   /* Build the test for 64-bit descriptor.  */
3271   mbo = build3 (COMPONENT_REF, TREE_TYPE (mbo), desc, mbo, NULL_TREE);
3272   mbmo = build3 (COMPONENT_REF, TREE_TYPE (mbmo), desc, mbmo, NULL_TREE);
3273   is64bit
3274     = build_binary_op (TRUTH_ANDIF_EXPR, integer_type_node,
3275                        build_binary_op (EQ_EXPR, integer_type_node,
3276                                         convert (integer_type_node, mbo),
3277                                         integer_one_node),
3278                        build_binary_op (EQ_EXPR, integer_type_node,
3279                                         convert (integer_type_node, mbmo),
3280                                         integer_minus_one_node));
3281
3282   /* Build the 2 possible end results.  */
3283   gnu_expr64 = convert_vms_descriptor64 (gnu_type, gnu_expr, gnat_subprog);
3284   gnu_expr = fold_convert (gnu_expr_alt_type, gnu_expr);
3285   gnu_expr32 = convert_vms_descriptor32 (gnu_type, gnu_expr, gnat_subprog);
3286
3287   return build3 (COND_EXPR, gnu_type, is64bit, gnu_expr64, gnu_expr32);
3288 }
3289
3290 /* Build a stub for the subprogram specified by the GCC tree GNU_SUBPROG
3291    and the GNAT node GNAT_SUBPROG.  */
3292
3293 void
3294 build_function_stub (tree gnu_subprog, Entity_Id gnat_subprog)
3295 {
3296   tree gnu_subprog_type, gnu_subprog_addr, gnu_subprog_call;
3297   tree gnu_stub_param, gnu_param_list, gnu_arg_types, gnu_param;
3298   tree gnu_stub_decl = DECL_FUNCTION_STUB (gnu_subprog);
3299   tree gnu_body;
3300
3301   gnu_subprog_type = TREE_TYPE (gnu_subprog);
3302   gnu_param_list = NULL_TREE;
3303
3304   begin_subprog_body (gnu_stub_decl);
3305   gnat_pushlevel ();
3306
3307   start_stmt_group ();
3308
3309   /* Loop over the parameters of the stub and translate any of them
3310      passed by descriptor into a by reference one.  */
3311   for (gnu_stub_param = DECL_ARGUMENTS (gnu_stub_decl),
3312        gnu_arg_types = TYPE_ARG_TYPES (gnu_subprog_type);
3313        gnu_stub_param;
3314        gnu_stub_param = TREE_CHAIN (gnu_stub_param),
3315        gnu_arg_types = TREE_CHAIN (gnu_arg_types))
3316     {
3317       if (DECL_BY_DESCRIPTOR_P (gnu_stub_param))
3318         gnu_param
3319           = convert_vms_descriptor (TREE_VALUE (gnu_arg_types),
3320                                     gnu_stub_param,
3321                                     DECL_PARM_ALT_TYPE (gnu_stub_param),
3322                                     gnat_subprog);
3323       else
3324         gnu_param = gnu_stub_param;
3325
3326       gnu_param_list = tree_cons (NULL_TREE, gnu_param, gnu_param_list);
3327     }
3328
3329   gnu_body = end_stmt_group ();
3330
3331   /* Invoke the internal subprogram.  */
3332   gnu_subprog_addr = build1 (ADDR_EXPR, build_pointer_type (gnu_subprog_type),
3333                              gnu_subprog);
3334   gnu_subprog_call = build_call_list (TREE_TYPE (gnu_subprog_type),
3335                                       gnu_subprog_addr,
3336                                       nreverse (gnu_param_list));
3337
3338   /* Propagate the return value, if any.  */
3339   if (VOID_TYPE_P (TREE_TYPE (gnu_subprog_type)))
3340     append_to_statement_list (gnu_subprog_call, &gnu_body);
3341   else
3342     append_to_statement_list (build_return_expr (DECL_RESULT (gnu_stub_decl),
3343                                                  gnu_subprog_call),
3344                               &gnu_body);
3345
3346   gnat_poplevel ();
3347
3348   allocate_struct_function (gnu_stub_decl, false);
3349   end_subprog_body (gnu_body);
3350 }
3351 \f
3352 /* Build a type to be used to represent an aliased object whose nominal
3353    type is an unconstrained array.  This consists of a RECORD_TYPE containing
3354    a field of TEMPLATE_TYPE and a field of OBJECT_TYPE, which is an
3355    ARRAY_TYPE.  If ARRAY_TYPE is that of the unconstrained array, this
3356    is used to represent an arbitrary unconstrained object.  Use NAME
3357    as the name of the record.  */
3358
3359 tree
3360 build_unc_object_type (tree template_type, tree object_type, tree name)
3361 {
3362   tree type = make_node (RECORD_TYPE);
3363   tree template_field = create_field_decl (get_identifier ("BOUNDS"),
3364                                            template_type, type, 0, 0, 0, 1);
3365   tree array_field = create_field_decl (get_identifier ("ARRAY"), object_type,
3366                                         type, 0, 0, 0, 1);
3367
3368   TYPE_NAME (type) = name;
3369   TYPE_CONTAINS_TEMPLATE_P (type) = 1;
3370   finish_record_type (type,
3371                       chainon (chainon (NULL_TREE, template_field),
3372                                array_field),
3373                       0, true);
3374
3375   return type;
3376 }
3377
3378 /* Same, taking a thin or fat pointer type instead of a template type. */
3379
3380 tree
3381 build_unc_object_type_from_ptr (tree thin_fat_ptr_type, tree object_type,
3382                                 tree name)
3383 {
3384   tree template_type;
3385
3386   gcc_assert (TYPE_IS_FAT_OR_THIN_POINTER_P (thin_fat_ptr_type));
3387
3388   template_type
3389     = (TYPE_IS_FAT_POINTER_P (thin_fat_ptr_type)
3390        ? TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (thin_fat_ptr_type))))
3391        : TREE_TYPE (TYPE_FIELDS (TREE_TYPE (thin_fat_ptr_type))));
3392   return build_unc_object_type (template_type, object_type, name);
3393 }
3394
3395 /* Shift the component offsets within an unconstrained object TYPE to make it
3396    suitable for use as a designated type for thin pointers.  */
3397
3398 void
3399 shift_unc_components_for_thin_pointers (tree type)
3400 {
3401   /* Thin pointer values designate the ARRAY data of an unconstrained object,
3402      allocated past the BOUNDS template.  The designated type is adjusted to
3403      have ARRAY at position zero and the template at a negative offset, so
3404      that COMPONENT_REFs on (*thin_ptr) designate the proper location.  */
3405
3406   tree bounds_field = TYPE_FIELDS (type);
3407   tree array_field  = TREE_CHAIN (TYPE_FIELDS (type));
3408
3409   DECL_FIELD_OFFSET (bounds_field)
3410     = size_binop (MINUS_EXPR, size_zero_node, byte_position (array_field));
3411
3412   DECL_FIELD_OFFSET (array_field) = size_zero_node;
3413   DECL_FIELD_BIT_OFFSET (array_field) = bitsize_zero_node;
3414 }
3415 \f
3416 /* Update anything previously pointing to OLD_TYPE to point to NEW_TYPE.
3417    In the normal case this is just two adjustments, but we have more to
3418    do if NEW_TYPE is an UNCONSTRAINED_ARRAY_TYPE.  */
3419
3420 void
3421 update_pointer_to (tree old_type, tree new_type)
3422 {
3423   tree ptr = TYPE_POINTER_TO (old_type);
3424   tree ref = TYPE_REFERENCE_TO (old_type);
3425   tree ptr1, ref1;
3426   tree type;
3427
3428   /* If this is the main variant, process all the other variants first.  */
3429   if (TYPE_MAIN_VARIANT (old_type) == old_type)
3430     for (type = TYPE_NEXT_VARIANT (old_type); type;
3431          type = TYPE_NEXT_VARIANT (type))
3432       update_pointer_to (type, new_type);
3433
3434   /* If no pointers and no references, we are done.  */
3435   if (!ptr && !ref)
3436     return;
3437
3438   /* Merge the old type qualifiers in the new type.
3439
3440      Each old variant has qualifiers for specific reasons, and the new
3441      designated type as well.  Each set of qualifiers represents useful
3442      information grabbed at some point, and merging the two simply unifies
3443      these inputs into the final type description.
3444
3445      Consider for instance a volatile type frozen after an access to constant
3446      type designating it; after the designated type's freeze, we get here with
3447      a volatile NEW_TYPE and a dummy OLD_TYPE with a readonly variant, created
3448      when the access type was processed.  We will make a volatile and readonly
3449      designated type, because that's what it really is.
3450
3451      We might also get here for a non-dummy OLD_TYPE variant with different
3452      qualifiers than those of NEW_TYPE, for instance in some cases of pointers
3453      to private record type elaboration (see the comments around the call to
3454      this routine in gnat_to_gnu_entity <E_Access_Type>).  We have to merge
3455      the qualifiers in those cases too, to avoid accidentally discarding the
3456      initial set, and will often end up with OLD_TYPE == NEW_TYPE then.  */
3457   new_type
3458     = build_qualified_type (new_type,
3459                             TYPE_QUALS (old_type) | TYPE_QUALS (new_type));
3460
3461   /* If old type and new type are identical, there is nothing to do.  */
3462   if (old_type == new_type)
3463     return;
3464
3465   /* Otherwise, first handle the simple case.  */
3466   if (TREE_CODE (new_type) != UNCONSTRAINED_ARRAY_TYPE)
3467     {
3468       TYPE_POINTER_TO (new_type) = ptr;
3469       TYPE_REFERENCE_TO (new_type) = ref;
3470
3471       for (; ptr; ptr = TYPE_NEXT_PTR_TO (ptr))
3472         for (ptr1 = TYPE_MAIN_VARIANT (ptr); ptr1;
3473              ptr1 = TYPE_NEXT_VARIANT (ptr1))
3474           TREE_TYPE (ptr1) = new_type;
3475
3476       for (; ref; ref = TYPE_NEXT_REF_TO (ref))
3477         for (ref1 = TYPE_MAIN_VARIANT (ref); ref1;
3478              ref1 = TYPE_NEXT_VARIANT (ref1))
3479           TREE_TYPE (ref1) = new_type;
3480     }
3481
3482   /* Now deal with the unconstrained array case.  In this case the "pointer"
3483      is actually a RECORD_TYPE where both fields are pointers to dummy nodes.
3484      Turn them into pointers to the correct types using update_pointer_to.  */
3485   else if (!TYPE_IS_FAT_POINTER_P (ptr))
3486     gcc_unreachable ();
3487
3488   else
3489     {
3490       tree new_obj_rec = TYPE_OBJECT_RECORD_TYPE (new_type);
3491       tree array_field = TYPE_FIELDS (ptr);
3492       tree bounds_field = TREE_CHAIN (TYPE_FIELDS (ptr));
3493       tree new_ptr = TYPE_POINTER_TO (new_type);
3494       tree new_ref;
3495       tree var;
3496
3497       /* Make pointers to the dummy template point to the real template.  */
3498       update_pointer_to
3499         (TREE_TYPE (TREE_TYPE (bounds_field)),
3500          TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (new_ptr)))));
3501
3502       /* The references to the template bounds present in the array type
3503          are made through a PLACEHOLDER_EXPR of type NEW_PTR.  Since we
3504          are updating PTR to make it a full replacement for NEW_PTR as
3505          pointer to NEW_TYPE, we must rework the PLACEHOLDER_EXPR so as
3506          to make it of type PTR.  */
3507       new_ref = build3 (COMPONENT_REF, TREE_TYPE (bounds_field),
3508                         build0 (PLACEHOLDER_EXPR, ptr),
3509                         bounds_field, NULL_TREE);
3510
3511       /* Create the new array for the new PLACEHOLDER_EXPR and make pointers
3512          to the dummy array point to it.  */
3513       update_pointer_to
3514         (TREE_TYPE (TREE_TYPE (array_field)),
3515          substitute_in_type (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (new_ptr))),
3516                              TREE_CHAIN (TYPE_FIELDS (new_ptr)), new_ref));
3517
3518       /* Make PTR the pointer to NEW_TYPE.  */
3519       TYPE_POINTER_TO (new_type) = TYPE_REFERENCE_TO (new_type)
3520         = TREE_TYPE (new_type) = ptr;
3521
3522       /* And show the original pointer NEW_PTR to the debugger.  This is the
3523          counterpart of the equivalent processing in gnat_pushdecl when the
3524          unconstrained array type is frozen after access types to it.  Note
3525          that update_pointer_to can be invoked multiple times on the same
3526          couple of types because of the type variants.  */
3527       if (TYPE_NAME (ptr)
3528           && TREE_CODE (TYPE_NAME (ptr)) == TYPE_DECL
3529           && !DECL_ORIGINAL_TYPE (TYPE_NAME (ptr)))
3530         {
3531           DECL_ORIGINAL_TYPE (TYPE_NAME (ptr)) = new_ptr;
3532           DECL_ARTIFICIAL (TYPE_NAME (ptr)) = 0;
3533         }
3534       for (var = TYPE_MAIN_VARIANT (ptr); var; var = TYPE_NEXT_VARIANT (var))
3535         SET_TYPE_UNCONSTRAINED_ARRAY (var, new_type);
3536
3537       /* Now handle updating the allocation record, what the thin pointer
3538          points to.  Update all pointers from the old record into the new
3539          one, update the type of the array field, and recompute the size.  */
3540       update_pointer_to (TYPE_OBJECT_RECORD_TYPE (old_type), new_obj_rec);
3541
3542       TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
3543         = TREE_TYPE (TREE_TYPE (array_field));
3544
3545       /* The size recomputation needs to account for alignment constraints, so
3546          we let layout_type work it out.  This will reset the field offsets to
3547          what they would be in a regular record, so we shift them back to what
3548          we want them to be for a thin pointer designated type afterwards.  */
3549       DECL_SIZE (TYPE_FIELDS (new_obj_rec)) = 0;
3550       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))) = 0;
3551       TYPE_SIZE (new_obj_rec) = 0;
3552       layout_type (new_obj_rec);
3553
3554       shift_unc_components_for_thin_pointers (new_obj_rec);
3555
3556       /* We are done, at last.  */
3557       rest_of_record_type_compilation (ptr);
3558     }
3559 }
3560 \f
3561 /* Convert EXPR, a pointer to a constrained array, into a pointer to an
3562    unconstrained one.  This involves making or finding a template.  */
3563
3564 static tree
3565 convert_to_fat_pointer (tree type, tree expr)
3566 {
3567   tree template_type = TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type))));
3568   tree p_array_type = TREE_TYPE (TYPE_FIELDS (type));
3569   tree etype = TREE_TYPE (expr);
3570   tree template_tree;
3571
3572   /* If EXPR is null, make a fat pointer that contains null pointers to the
3573      template and array.  */
3574   if (integer_zerop (expr))
3575     return
3576       gnat_build_constructor
3577         (type,
3578          tree_cons (TYPE_FIELDS (type),
3579                     convert (p_array_type, expr),
3580                     tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3581                                convert (build_pointer_type (template_type),
3582                                         expr),
3583                                NULL_TREE)));
3584
3585   /* If EXPR is a thin pointer, make template and data from the record..  */
3586   else if (TYPE_IS_THIN_POINTER_P (etype))
3587     {
3588       tree fields = TYPE_FIELDS (TREE_TYPE (etype));
3589
3590       expr = gnat_protect_expr (expr);
3591       if (TREE_CODE (expr) == ADDR_EXPR)
3592         expr = TREE_OPERAND (expr, 0);
3593       else
3594         expr = build1 (INDIRECT_REF, TREE_TYPE (etype), expr);
3595
3596       template_tree = build_component_ref (expr, NULL_TREE, fields, false);
3597       expr = build_unary_op (ADDR_EXPR, NULL_TREE,
3598                              build_component_ref (expr, NULL_TREE,
3599                                                   TREE_CHAIN (fields), false));
3600     }
3601
3602   /* Otherwise, build the constructor for the template.  */
3603   else
3604     template_tree = build_template (template_type, TREE_TYPE (etype), expr);
3605
3606   /* The final result is a constructor for the fat pointer.
3607
3608      If EXPR is an argument of a foreign convention subprogram, the type it
3609      points to is directly the component type.  In this case, the expression
3610      type may not match the corresponding FIELD_DECL type at this point, so we
3611      call "convert" here to fix that up if necessary.  This type consistency is
3612      required, for instance because it ensures that possible later folding of
3613      COMPONENT_REFs against this constructor always yields something of the
3614      same type as the initial reference.
3615
3616      Note that the call to "build_template" above is still fine because it
3617      will only refer to the provided TEMPLATE_TYPE in this case.  */
3618   return
3619     gnat_build_constructor
3620       (type,
3621        tree_cons (TYPE_FIELDS (type),
3622                   convert (p_array_type, expr),
3623                   tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3624                              build_unary_op (ADDR_EXPR, NULL_TREE,
3625                                              template_tree),
3626                              NULL_TREE)));
3627 }
3628 \f
3629 /* Convert to a thin pointer type, TYPE.  The only thing we know how to convert
3630    is something that is a fat pointer, so convert to it first if it EXPR
3631    is not already a fat pointer.  */
3632
3633 static tree
3634 convert_to_thin_pointer (tree type, tree expr)
3635 {
3636   if (!TYPE_IS_FAT_POINTER_P (TREE_TYPE (expr)))
3637     expr
3638       = convert_to_fat_pointer
3639         (TREE_TYPE (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type))), expr);
3640
3641   /* We get the pointer to the data and use a NOP_EXPR to make it the
3642      proper GCC type.  */
3643   expr = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (TREE_TYPE (expr)),
3644                               false);
3645   expr = build1 (NOP_EXPR, type, expr);
3646
3647   return expr;
3648 }
3649 \f
3650 /* Create an expression whose value is that of EXPR,
3651    converted to type TYPE.  The TREE_TYPE of the value
3652    is always TYPE.  This function implements all reasonable
3653    conversions; callers should filter out those that are
3654    not permitted by the language being compiled.  */
3655
3656 tree
3657 convert (tree type, tree expr)
3658 {
3659   enum tree_code code = TREE_CODE (type);
3660   tree etype = TREE_TYPE (expr);
3661   enum tree_code ecode = TREE_CODE (etype);
3662
3663   /* If EXPR is already the right type, we are done.  */
3664   if (type == etype)
3665     return expr;
3666
3667   /* If both input and output have padding and are of variable size, do this
3668      as an unchecked conversion.  Likewise if one is a mere variant of the
3669      other, so we avoid a pointless unpad/repad sequence.  */
3670   else if (code == RECORD_TYPE && ecode == RECORD_TYPE
3671            && TYPE_PADDING_P (type) && TYPE_PADDING_P (etype)
3672            && (!TREE_CONSTANT (TYPE_SIZE (type))
3673                || !TREE_CONSTANT (TYPE_SIZE (etype))
3674                || gnat_types_compatible_p (type, etype)
3675                || TYPE_NAME (TREE_TYPE (TYPE_FIELDS (type)))
3676                   == TYPE_NAME (TREE_TYPE (TYPE_FIELDS (etype)))))
3677     ;
3678
3679   /* If the output type has padding, convert to the inner type and make a
3680      constructor to build the record, unless a variable size is involved.  */
3681   else if (code == RECORD_TYPE && TYPE_PADDING_P (type))
3682     {
3683       /* If we previously converted from another type and our type is
3684          of variable size, remove the conversion to avoid the need for
3685          variable-sized temporaries.  Likewise for a conversion between
3686          original and packable version.  */
3687       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
3688           && (!TREE_CONSTANT (TYPE_SIZE (type))
3689               || (ecode == RECORD_TYPE
3690                   && TYPE_NAME (etype)
3691                      == TYPE_NAME (TREE_TYPE (TREE_OPERAND (expr, 0))))))
3692         expr = TREE_OPERAND (expr, 0);
3693
3694       /* If we are just removing the padding from expr, convert the original
3695          object if we have variable size in order to avoid the need for some
3696          variable-sized temporaries.  Likewise if the padding is a variant
3697          of the other, so we avoid a pointless unpad/repad sequence.  */
3698       if (TREE_CODE (expr) == COMPONENT_REF
3699           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (expr, 0)))
3700           && (!TREE_CONSTANT (TYPE_SIZE (type))
3701               || gnat_types_compatible_p (type,
3702                                           TREE_TYPE (TREE_OPERAND (expr, 0)))
3703               || (ecode == RECORD_TYPE
3704                   && TYPE_NAME (etype)
3705                      == TYPE_NAME (TREE_TYPE (TYPE_FIELDS (type))))))
3706         return convert (type, TREE_OPERAND (expr, 0));
3707
3708       /* If the inner type is of self-referential size and the expression type
3709          is a record, do this as an unchecked conversion.  But first pad the
3710          expression if possible to have the same size on both sides.  */
3711       if (TREE_CODE (etype) == RECORD_TYPE
3712           && CONTAINS_PLACEHOLDER_P (DECL_SIZE (TYPE_FIELDS (type))))
3713         {
3714           if (TREE_CONSTANT (TYPE_SIZE (etype)))
3715             expr = convert (maybe_pad_type (etype, TYPE_SIZE (type), 0, Empty,
3716                             false, false, false, true), expr);
3717           return unchecked_convert (type, expr, false);
3718         }
3719
3720       /* If we are converting between array types with variable size, do the
3721          final conversion as an unchecked conversion, again to avoid the need
3722          for some variable-sized temporaries.  If valid, this conversion is
3723          very likely purely technical and without real effects.  */
3724       if (TREE_CODE (etype) == ARRAY_TYPE
3725           && TREE_CODE (TREE_TYPE (TYPE_FIELDS (type))) == ARRAY_TYPE
3726           && !TREE_CONSTANT (TYPE_SIZE (etype))
3727           && !TREE_CONSTANT (TYPE_SIZE (type)))
3728         return unchecked_convert (type,
3729                                   convert (TREE_TYPE (TYPE_FIELDS (type)),
3730                                            expr),
3731                                   false);
3732
3733       return
3734         gnat_build_constructor (type,
3735                                 tree_cons (TYPE_FIELDS (type),
3736                                            convert (TREE_TYPE
3737                                                     (TYPE_FIELDS (type)),
3738                                                     expr),
3739                                            NULL_TREE));
3740     }
3741
3742   /* If the input type has padding, remove it and convert to the output type.
3743      The conditions ordering is arranged to ensure that the output type is not
3744      a padding type here, as it is not clear whether the conversion would
3745      always be correct if this was to happen.  */
3746   else if (ecode == RECORD_TYPE && TYPE_PADDING_P (etype))
3747     {
3748       tree unpadded;
3749
3750       /* If we have just converted to this padded type, just get the
3751          inner expression.  */
3752       if (TREE_CODE (expr) == CONSTRUCTOR
3753           && !VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (expr))
3754           && VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->index
3755              == TYPE_FIELDS (etype))
3756         unpadded
3757           = VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->value;
3758
3759       /* Otherwise, build an explicit component reference.  */
3760       else
3761         unpadded
3762           = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (etype), false);
3763
3764       return convert (type, unpadded);
3765     }
3766
3767   /* If the input is a biased type, adjust first.  */
3768   if (ecode == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (etype))
3769     return convert (type, fold_build2 (PLUS_EXPR, TREE_TYPE (etype),
3770                                        fold_convert (TREE_TYPE (etype),
3771                                                      expr),
3772                                        TYPE_MIN_VALUE (etype)));
3773
3774   /* If the input is a justified modular type, we need to extract the actual
3775      object before converting it to any other type with the exceptions of an
3776      unconstrained array or of a mere type variant.  It is useful to avoid the
3777      extraction and conversion in the type variant case because it could end
3778      up replacing a VAR_DECL expr by a constructor and we might be about the
3779      take the address of the result.  */
3780   if (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)
3781       && code != UNCONSTRAINED_ARRAY_TYPE
3782       && TYPE_MAIN_VARIANT (type) != TYPE_MAIN_VARIANT (etype))
3783     return convert (type, build_component_ref (expr, NULL_TREE,
3784                                                TYPE_FIELDS (etype), false));
3785
3786   /* If converting to a type that contains a template, convert to the data
3787      type and then build the template. */
3788   if (code == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (type))
3789     {
3790       tree obj_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type)));
3791
3792       /* If the source already has a template, get a reference to the
3793          associated array only, as we are going to rebuild a template
3794          for the target type anyway.  */
3795       expr = maybe_unconstrained_array (expr);
3796
3797       return
3798         gnat_build_constructor
3799           (type,
3800            tree_cons (TYPE_FIELDS (type),
3801                       build_template (TREE_TYPE (TYPE_FIELDS (type)),
3802                                       obj_type, NULL_TREE),
3803                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3804                                  convert (obj_type, expr), NULL_TREE)));
3805     }
3806
3807   /* There are some special cases of expressions that we process
3808      specially.  */
3809   switch (TREE_CODE (expr))
3810     {
3811     case ERROR_MARK:
3812       return expr;
3813
3814     case NULL_EXPR:
3815       /* Just set its type here.  For TRANSFORM_EXPR, we will do the actual
3816          conversion in gnat_expand_expr.  NULL_EXPR does not represent
3817          and actual value, so no conversion is needed.  */
3818       expr = copy_node (expr);
3819       TREE_TYPE (expr) = type;
3820       return expr;
3821
3822     case STRING_CST:
3823       /* If we are converting a STRING_CST to another constrained array type,
3824          just make a new one in the proper type.  */
3825       if (code == ecode && AGGREGATE_TYPE_P (etype)
3826           && !(TREE_CODE (TYPE_SIZE (etype)) == INTEGER_CST
3827                && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
3828         {
3829           expr = copy_node (expr);
3830           TREE_TYPE (expr) = type;
3831           return expr;
3832         }
3833       break;
3834
3835     case VECTOR_CST:
3836       /* If we are converting a VECTOR_CST to a mere variant type, just make
3837          a new one in the proper type.  */
3838       if (code == ecode && gnat_types_compatible_p (type, etype))
3839         {
3840           expr = copy_node (expr);
3841           TREE_TYPE (expr) = type;
3842           return expr;
3843         }
3844
3845     case CONSTRUCTOR:
3846       /* If we are converting a CONSTRUCTOR to a mere variant type, just make
3847          a new one in the proper type.  */
3848       if (code == ecode && gnat_types_compatible_p (type, etype))
3849         {
3850           expr = copy_node (expr);
3851           TREE_TYPE (expr) = type;
3852           return expr;
3853         }
3854
3855       /* Likewise for a conversion between original and packable version, but
3856          we have to work harder in order to preserve type consistency.  */
3857       if (code == ecode
3858           && code == RECORD_TYPE
3859           && TYPE_NAME (type) == TYPE_NAME (etype))
3860         {
3861           VEC(constructor_elt,gc) *e = CONSTRUCTOR_ELTS (expr);
3862           unsigned HOST_WIDE_INT len = VEC_length (constructor_elt, e);
3863           VEC(constructor_elt,gc) *v = VEC_alloc (constructor_elt, gc, len);
3864           tree efield = TYPE_FIELDS (etype), field = TYPE_FIELDS (type);
3865           unsigned HOST_WIDE_INT idx;
3866           tree index, value;
3867
3868           /* Whether we need to clear TREE_CONSTANT et al. on the output
3869              constructor when we convert in place.  */
3870           bool clear_constant = false;
3871
3872           FOR_EACH_CONSTRUCTOR_ELT(e, idx, index, value)
3873             {
3874               constructor_elt *elt = VEC_quick_push (constructor_elt, v, NULL);
3875               /* We expect only simple constructors.  Otherwise, punt.  */
3876               if (!(index == efield || index == DECL_ORIGINAL_FIELD (efield)))
3877                 break;
3878               elt->index = field;
3879               elt->value = convert (TREE_TYPE (field), value);
3880
3881               /* If packing has made this field a bitfield and the input
3882                  value couldn't be emitted statically any more, we need to
3883                  clear TREE_CONSTANT on our output.  */
3884               if (!clear_constant
3885                   && TREE_CONSTANT (expr)
3886                   && !CONSTRUCTOR_BITFIELD_P (efield)
3887                   && CONSTRUCTOR_BITFIELD_P (field)
3888                   && !initializer_constant_valid_for_bitfield_p (value))
3889                 clear_constant = true;
3890
3891               efield = TREE_CHAIN (efield);
3892               field = TREE_CHAIN (field);
3893             }
3894
3895           /* If we have been able to match and convert all the input fields
3896              to their output type, convert in place now.  We'll fallback to a
3897              view conversion downstream otherwise.  */
3898           if (idx == len)
3899             {
3900               expr = copy_node (expr);
3901               TREE_TYPE (expr) = type;
3902               CONSTRUCTOR_ELTS (expr) = v;
3903               if (clear_constant)
3904                 TREE_CONSTANT (expr) = TREE_STATIC (expr) = 0;
3905               return expr;
3906             }
3907         }
3908
3909       /* Likewise for a conversion between array type and vector type with a
3910          compatible representative array.  */
3911       else if (code == VECTOR_TYPE
3912                && ecode == ARRAY_TYPE
3913                && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type),
3914                                            etype))
3915         {
3916           VEC(constructor_elt,gc) *e = CONSTRUCTOR_ELTS (expr);
3917           unsigned HOST_WIDE_INT len = VEC_length (constructor_elt, e);
3918           VEC(constructor_elt,gc) *v;
3919           unsigned HOST_WIDE_INT ix;
3920           tree value;
3921
3922           /* Build a VECTOR_CST from a *constant* array constructor.  */
3923           if (TREE_CONSTANT (expr))
3924             {
3925               bool constant_p = true;
3926
3927               /* Iterate through elements and check if all constructor
3928                  elements are *_CSTs.  */
3929               FOR_EACH_CONSTRUCTOR_VALUE (e, ix, value)
3930                 if (!CONSTANT_CLASS_P (value))
3931                   {
3932                     constant_p = false;
3933                     break;
3934                   }
3935
3936               if (constant_p)
3937                 return build_vector_from_ctor (type,
3938                                                CONSTRUCTOR_ELTS (expr));
3939             }
3940
3941           /* Otherwise, build a regular vector constructor.  */
3942           v = VEC_alloc (constructor_elt, gc, len);
3943           FOR_EACH_CONSTRUCTOR_VALUE (e, ix, value)
3944             {
3945               constructor_elt *elt = VEC_quick_push (constructor_elt, v, NULL);
3946               elt->index = NULL_TREE;
3947               elt->value = value;
3948             }
3949           expr = copy_node (expr);
3950           TREE_TYPE (expr) = type;
3951           CONSTRUCTOR_ELTS (expr) = v;
3952           return expr;
3953         }
3954       break;
3955
3956     case UNCONSTRAINED_ARRAY_REF:
3957       /* Convert this to the type of the inner array by getting the address of
3958          the array from the template.  */
3959       expr = build_unary_op (INDIRECT_REF, NULL_TREE,
3960                              build_component_ref (TREE_OPERAND (expr, 0),
3961                                                   get_identifier ("P_ARRAY"),
3962                                                   NULL_TREE, false));
3963       etype = TREE_TYPE (expr);
3964       ecode = TREE_CODE (etype);
3965       break;
3966
3967     case VIEW_CONVERT_EXPR:
3968       {
3969         /* GCC 4.x is very sensitive to type consistency overall, and view
3970            conversions thus are very frequent.  Even though just "convert"ing
3971            the inner operand to the output type is fine in most cases, it
3972            might expose unexpected input/output type mismatches in special
3973            circumstances so we avoid such recursive calls when we can.  */
3974         tree op0 = TREE_OPERAND (expr, 0);
3975
3976         /* If we are converting back to the original type, we can just
3977            lift the input conversion.  This is a common occurrence with
3978            switches back-and-forth amongst type variants.  */
3979         if (type == TREE_TYPE (op0))
3980           return op0;
3981
3982         /* Otherwise, if we're converting between two aggregate or vector
3983            types, we might be allowed to substitute the VIEW_CONVERT_EXPR
3984            target type in place or to just convert the inner expression.  */
3985         if ((AGGREGATE_TYPE_P (type) && AGGREGATE_TYPE_P (etype))
3986             || (VECTOR_TYPE_P (type) && VECTOR_TYPE_P (etype)))
3987           {
3988             /* If we are converting between mere variants, we can just
3989                substitute the VIEW_CONVERT_EXPR in place.  */
3990             if (gnat_types_compatible_p (type, etype))
3991               return build1 (VIEW_CONVERT_EXPR, type, op0);
3992
3993             /* Otherwise, we may just bypass the input view conversion unless
3994                one of the types is a fat pointer,  which is handled by
3995                specialized code below which relies on exact type matching.  */
3996             else if (!TYPE_IS_FAT_POINTER_P (type)
3997                      && !TYPE_IS_FAT_POINTER_P (etype))
3998               return convert (type, op0);
3999           }
4000       }
4001       break;
4002
4003     case INDIRECT_REF:
4004       /* If both types are record types, just convert the pointer and
4005          make a new INDIRECT_REF.
4006
4007          ??? Disable this for now since it causes problems with the
4008          code in build_binary_op for MODIFY_EXPR which wants to
4009          strip off conversions.  But that code really is a mess and
4010          we need to do this a much better way some time.  */
4011       if (0
4012           && (TREE_CODE (type) == RECORD_TYPE
4013               || TREE_CODE (type) == UNION_TYPE)
4014           && (TREE_CODE (etype) == RECORD_TYPE
4015               || TREE_CODE (etype) == UNION_TYPE)
4016           && !TYPE_IS_FAT_POINTER_P (type) && !TYPE_IS_FAT_POINTER_P (etype))
4017         return build_unary_op (INDIRECT_REF, NULL_TREE,
4018                                convert (build_pointer_type (type),
4019                                         TREE_OPERAND (expr, 0)));
4020       break;
4021
4022     default:
4023       break;
4024     }
4025
4026   /* Check for converting to a pointer to an unconstrained array.  */
4027   if (TYPE_IS_FAT_POINTER_P (type) && !TYPE_IS_FAT_POINTER_P (etype))
4028     return convert_to_fat_pointer (type, expr);
4029
4030   /* If we are converting between two aggregate or vector types that are mere
4031      variants, just make a VIEW_CONVERT_EXPR.  Likewise when we are converting
4032      to a vector type from its representative array type.  */
4033   else if ((code == ecode
4034             && (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
4035             && gnat_types_compatible_p (type, etype))
4036            || (code == VECTOR_TYPE
4037                && ecode == ARRAY_TYPE
4038                && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type),
4039                                            etype)))
4040     return build1 (VIEW_CONVERT_EXPR, type, expr);
4041
4042   /* In all other cases of related types, make a NOP_EXPR.  */
4043   else if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype)
4044            || (code == INTEGER_CST && ecode == INTEGER_CST
4045                && (type == TREE_TYPE (etype) || etype == TREE_TYPE (type))))
4046     return fold_convert (type, expr);
4047
4048   switch (code)
4049     {
4050     case VOID_TYPE:
4051       return fold_build1 (CONVERT_EXPR, type, expr);
4052
4053     case INTEGER_TYPE:
4054       if (TYPE_HAS_ACTUAL_BOUNDS_P (type)
4055           && (ecode == ARRAY_TYPE || ecode == UNCONSTRAINED_ARRAY_TYPE
4056               || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))))
4057         return unchecked_convert (type, expr, false);
4058       else if (TYPE_BIASED_REPRESENTATION_P (type))
4059         return fold_convert (type,
4060                              fold_build2 (MINUS_EXPR, TREE_TYPE (type),
4061                                           convert (TREE_TYPE (type), expr),
4062                                           TYPE_MIN_VALUE (type)));
4063
4064       /* ... fall through ... */
4065
4066     case ENUMERAL_TYPE:
4067     case BOOLEAN_TYPE:
4068       /* If we are converting an additive expression to an integer type
4069          with lower precision, be wary of the optimization that can be
4070          applied by convert_to_integer.  There are 2 problematic cases:
4071            - if the first operand was originally of a biased type,
4072              because we could be recursively called to convert it
4073              to an intermediate type and thus rematerialize the
4074              additive operator endlessly,
4075            - if the expression contains a placeholder, because an
4076              intermediate conversion that changes the sign could
4077              be inserted and thus introduce an artificial overflow
4078              at compile time when the placeholder is substituted.  */
4079       if (code == INTEGER_TYPE
4080           && ecode == INTEGER_TYPE
4081           && TYPE_PRECISION (type) < TYPE_PRECISION (etype)
4082           && (TREE_CODE (expr) == PLUS_EXPR || TREE_CODE (expr) == MINUS_EXPR))
4083         {
4084           tree op0 = get_unwidened (TREE_OPERAND (expr, 0), type);
4085
4086           if ((TREE_CODE (TREE_TYPE (op0)) == INTEGER_TYPE
4087                && TYPE_BIASED_REPRESENTATION_P (TREE_TYPE (op0)))
4088               || CONTAINS_PLACEHOLDER_P (expr))
4089             return build1 (NOP_EXPR, type, expr);
4090         }
4091
4092       return fold (convert_to_integer (type, expr));
4093
4094     case POINTER_TYPE:
4095     case REFERENCE_TYPE:
4096       /* If converting between two pointers to records denoting
4097          both a template and type, adjust if needed to account
4098          for any differing offsets, since one might be negative.  */
4099       if (TYPE_IS_THIN_POINTER_P (etype) && TYPE_IS_THIN_POINTER_P (type))
4100         {
4101           tree bit_diff
4102             = size_diffop (bit_position (TYPE_FIELDS (TREE_TYPE (etype))),
4103                            bit_position (TYPE_FIELDS (TREE_TYPE (type))));
4104           tree byte_diff = size_binop (CEIL_DIV_EXPR, bit_diff,
4105                                        sbitsize_int (BITS_PER_UNIT));
4106
4107           expr = build1 (NOP_EXPR, type, expr);
4108           TREE_CONSTANT (expr) = TREE_CONSTANT (TREE_OPERAND (expr, 0));
4109           if (integer_zerop (byte_diff))
4110             return expr;
4111
4112           return build_binary_op (POINTER_PLUS_EXPR, type, expr,
4113                                   fold (convert (sizetype, byte_diff)));
4114         }
4115
4116       /* If converting to a thin pointer, handle specially.  */
4117       if (TYPE_IS_THIN_POINTER_P (type)
4118           && TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type)))
4119         return convert_to_thin_pointer (type, expr);
4120
4121       /* If converting fat pointer to normal pointer, get the pointer to the
4122          array and then convert it.  */
4123       else if (TYPE_IS_FAT_POINTER_P (etype))
4124         expr = build_component_ref (expr, get_identifier ("P_ARRAY"),
4125                                     NULL_TREE, false);
4126
4127       return fold (convert_to_pointer (type, expr));
4128
4129     case REAL_TYPE:
4130       return fold (convert_to_real (type, expr));
4131
4132     case RECORD_TYPE:
4133       if (TYPE_JUSTIFIED_MODULAR_P (type) && !AGGREGATE_TYPE_P (etype))
4134         return
4135           gnat_build_constructor
4136             (type, tree_cons (TYPE_FIELDS (type),
4137                               convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
4138                               NULL_TREE));
4139
4140       /* ... fall through ... */
4141
4142     case ARRAY_TYPE:
4143       /* In these cases, assume the front-end has validated the conversion.
4144          If the conversion is valid, it will be a bit-wise conversion, so
4145          it can be viewed as an unchecked conversion.  */
4146       return unchecked_convert (type, expr, false);
4147
4148     case UNION_TYPE:
4149       /* This is a either a conversion between a tagged type and some
4150          subtype, which we have to mark as a UNION_TYPE because of
4151          overlapping fields or a conversion of an Unchecked_Union.  */
4152       return unchecked_convert (type, expr, false);
4153
4154     case UNCONSTRAINED_ARRAY_TYPE:
4155       /* If the input is a VECTOR_TYPE, convert to the representative
4156          array type first.  */
4157       if (ecode == VECTOR_TYPE)
4158         {
4159           expr = convert (TYPE_REPRESENTATIVE_ARRAY (etype), expr);
4160           etype = TREE_TYPE (expr);
4161           ecode = TREE_CODE (etype);
4162         }
4163
4164       /* If EXPR is a constrained array, take its address, convert it to a
4165          fat pointer, and then dereference it.  Likewise if EXPR is a
4166          record containing both a template and a constrained array.
4167          Note that a record representing a justified modular type
4168          always represents a packed constrained array.  */
4169       if (ecode == ARRAY_TYPE
4170           || (ecode == INTEGER_TYPE && TYPE_HAS_ACTUAL_BOUNDS_P (etype))
4171           || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))
4172           || (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)))
4173         return
4174           build_unary_op
4175             (INDIRECT_REF, NULL_TREE,
4176              convert_to_fat_pointer (TREE_TYPE (type),
4177                                      build_unary_op (ADDR_EXPR,
4178                                                      NULL_TREE, expr)));
4179
4180       /* Do something very similar for converting one unconstrained
4181          array to another.  */
4182       else if (ecode == UNCONSTRAINED_ARRAY_TYPE)
4183         return
4184           build_unary_op (INDIRECT_REF, NULL_TREE,
4185                           convert (TREE_TYPE (type),
4186                                    build_unary_op (ADDR_EXPR,
4187                                                    NULL_TREE, expr)));
4188       else
4189         gcc_unreachable ();
4190
4191     case COMPLEX_TYPE:
4192       return fold (convert_to_complex (type, expr));
4193
4194     default:
4195       gcc_unreachable ();
4196     }
4197 }
4198 \f
4199 /* Remove all conversions that are done in EXP.  This includes converting
4200    from a padded type or to a justified modular type.  If TRUE_ADDRESS
4201    is true, always return the address of the containing object even if
4202    the address is not bit-aligned.  */
4203
4204 tree
4205 remove_conversions (tree exp, bool true_address)
4206 {
4207   switch (TREE_CODE (exp))
4208     {
4209     case CONSTRUCTOR:
4210       if (true_address
4211           && TREE_CODE (TREE_TYPE (exp)) == RECORD_TYPE
4212           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (exp)))
4213         return
4214           remove_conversions (VEC_index (constructor_elt,
4215                                          CONSTRUCTOR_ELTS (exp), 0)->value,
4216                               true);
4217       break;
4218
4219     case COMPONENT_REF:
4220       if (TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
4221         return remove_conversions (TREE_OPERAND (exp, 0), true_address);
4222       break;
4223
4224     case VIEW_CONVERT_EXPR:  case NON_LVALUE_EXPR:
4225     CASE_CONVERT:
4226       return remove_conversions (TREE_OPERAND (exp, 0), true_address);
4227
4228     default:
4229       break;
4230     }
4231
4232   return exp;
4233 }
4234 \f
4235 /* If EXP's type is an UNCONSTRAINED_ARRAY_TYPE, return an expression that
4236    refers to the underlying array.  If its type has TYPE_CONTAINS_TEMPLATE_P,
4237    likewise return an expression pointing to the underlying array.  */
4238
4239 tree
4240 maybe_unconstrained_array (tree exp)
4241 {
4242   enum tree_code code = TREE_CODE (exp);
4243   tree new_exp;
4244
4245   switch (TREE_CODE (TREE_TYPE (exp)))
4246     {
4247     case UNCONSTRAINED_ARRAY_TYPE:
4248       if (code == UNCONSTRAINED_ARRAY_REF)
4249         {
4250           new_exp
4251             = build_unary_op (INDIRECT_REF, NULL_TREE,
4252                               build_component_ref (TREE_OPERAND (exp, 0),
4253                                                    get_identifier ("P_ARRAY"),
4254                                                    NULL_TREE, false));
4255           TREE_READONLY (new_exp) = TREE_READONLY (exp);
4256           return new_exp;
4257         }
4258
4259       else if (code == NULL_EXPR)
4260         return build1 (NULL_EXPR,
4261                        TREE_TYPE (TREE_TYPE (TYPE_FIELDS
4262                                              (TREE_TYPE (TREE_TYPE (exp))))),
4263                        TREE_OPERAND (exp, 0));
4264
4265     case RECORD_TYPE:
4266       /* If this is a padded type, convert to the unpadded type and see if
4267          it contains a template.  */
4268       if (TYPE_PADDING_P (TREE_TYPE (exp)))
4269         {
4270           new_exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
4271           if (TREE_CODE (TREE_TYPE (new_exp)) == RECORD_TYPE
4272               && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (new_exp)))
4273             return
4274               build_component_ref (new_exp, NULL_TREE,
4275                                    TREE_CHAIN
4276                                    (TYPE_FIELDS (TREE_TYPE (new_exp))),
4277                                    0);
4278         }
4279       else if (TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (exp)))
4280         return
4281           build_component_ref (exp, NULL_TREE,
4282                                TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (exp))), 0);
4283       break;
4284
4285     default:
4286       break;
4287     }
4288
4289   return exp;
4290 }
4291
4292 /* If EXP's type is a VECTOR_TYPE, return EXP converted to the associated
4293    TYPE_REPRESENTATIVE_ARRAY.  */
4294
4295 tree
4296 maybe_vector_array (tree exp)
4297 {
4298   tree etype = TREE_TYPE (exp);
4299
4300   if (VECTOR_TYPE_P (etype))
4301     exp = convert (TYPE_REPRESENTATIVE_ARRAY (etype), exp);
4302
4303   return exp;
4304 }
4305 \f
4306 /* Return true if EXPR is an expression that can be folded as an operand
4307    of a VIEW_CONVERT_EXPR.  See ada-tree.h for a complete rationale.  */
4308
4309 static bool
4310 can_fold_for_view_convert_p (tree expr)
4311 {
4312   tree t1, t2;
4313
4314   /* The folder will fold NOP_EXPRs between integral types with the same
4315      precision (in the middle-end's sense).  We cannot allow it if the
4316      types don't have the same precision in the Ada sense as well.  */
4317   if (TREE_CODE (expr) != NOP_EXPR)
4318     return true;
4319
4320   t1 = TREE_TYPE (expr);
4321   t2 = TREE_TYPE (TREE_OPERAND (expr, 0));
4322
4323   /* Defer to the folder for non-integral conversions.  */
4324   if (!(INTEGRAL_TYPE_P (t1) && INTEGRAL_TYPE_P (t2)))
4325     return true;
4326
4327   /* Only fold conversions that preserve both precisions.  */
4328   if (TYPE_PRECISION (t1) == TYPE_PRECISION (t2)
4329       && operand_equal_p (rm_size (t1), rm_size (t2), 0))
4330     return true;
4331
4332   return false;
4333 }
4334
4335 /* Return an expression that does an unchecked conversion of EXPR to TYPE.
4336    If NOTRUNC_P is true, truncation operations should be suppressed.
4337
4338    Special care is required with (source or target) integral types whose
4339    precision is not equal to their size, to make sure we fetch or assign
4340    the value bits whose location might depend on the endianness, e.g.
4341
4342      Rmsize : constant := 8;
4343      subtype Int is Integer range 0 .. 2 ** Rmsize - 1;
4344
4345      type Bit_Array is array (1 .. Rmsize) of Boolean;
4346      pragma Pack (Bit_Array);
4347
4348      function To_Bit_Array is new Unchecked_Conversion (Int, Bit_Array);
4349
4350      Value : Int := 2#1000_0001#;
4351      Vbits : Bit_Array := To_Bit_Array (Value);
4352
4353    we expect the 8 bits at Vbits'Address to always contain Value, while
4354    their original location depends on the endianness, at Value'Address
4355    on a little-endian architecture but not on a big-endian one.  */
4356
4357 tree
4358 unchecked_convert (tree type, tree expr, bool notrunc_p)
4359 {
4360   tree etype = TREE_TYPE (expr);
4361
4362   /* If the expression is already the right type, we are done.  */
4363   if (etype == type)
4364     return expr;
4365
4366   /* If both types types are integral just do a normal conversion.
4367      Likewise for a conversion to an unconstrained array.  */
4368   if ((((INTEGRAL_TYPE_P (type)
4369          && !(TREE_CODE (type) == INTEGER_TYPE
4370               && TYPE_VAX_FLOATING_POINT_P (type)))
4371         || (POINTER_TYPE_P (type) && ! TYPE_IS_THIN_POINTER_P (type))
4372         || (TREE_CODE (type) == RECORD_TYPE
4373             && TYPE_JUSTIFIED_MODULAR_P (type)))
4374        && ((INTEGRAL_TYPE_P (etype)
4375             && !(TREE_CODE (etype) == INTEGER_TYPE
4376                  && TYPE_VAX_FLOATING_POINT_P (etype)))
4377            || (POINTER_TYPE_P (etype) && !TYPE_IS_THIN_POINTER_P (etype))
4378            || (TREE_CODE (etype) == RECORD_TYPE
4379                && TYPE_JUSTIFIED_MODULAR_P (etype))))
4380       || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
4381     {
4382       if (TREE_CODE (etype) == INTEGER_TYPE
4383           && TYPE_BIASED_REPRESENTATION_P (etype))
4384         {
4385           tree ntype = copy_type (etype);
4386           TYPE_BIASED_REPRESENTATION_P (ntype) = 0;
4387           TYPE_MAIN_VARIANT (ntype) = ntype;
4388           expr = build1 (NOP_EXPR, ntype, expr);
4389         }
4390
4391       if (TREE_CODE (type) == INTEGER_TYPE
4392           && TYPE_BIASED_REPRESENTATION_P (type))
4393         {
4394           tree rtype = copy_type (type);
4395           TYPE_BIASED_REPRESENTATION_P (rtype) = 0;
4396           TYPE_MAIN_VARIANT (rtype) = rtype;
4397           expr = convert (rtype, expr);
4398           expr = build1 (NOP_EXPR, type, expr);
4399         }
4400       else
4401         expr = convert (type, expr);
4402     }
4403
4404   /* If we are converting to an integral type whose precision is not equal
4405      to its size, first unchecked convert to a record that contains an
4406      object of the output type.  Then extract the field. */
4407   else if (INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
4408            && 0 != compare_tree_int (TYPE_RM_SIZE (type),
4409                                      GET_MODE_BITSIZE (TYPE_MODE (type))))
4410     {
4411       tree rec_type = make_node (RECORD_TYPE);
4412       tree field = create_field_decl (get_identifier ("OBJ"), type,
4413                                       rec_type, 1, 0, 0, 0);
4414
4415       TYPE_FIELDS (rec_type) = field;
4416       layout_type (rec_type);
4417
4418       expr = unchecked_convert (rec_type, expr, notrunc_p);
4419       expr = build_component_ref (expr, NULL_TREE, field, 0);
4420     }
4421
4422   /* Similarly if we are converting from an integral type whose precision
4423      is not equal to its size.  */
4424   else if (INTEGRAL_TYPE_P (etype) && TYPE_RM_SIZE (etype)
4425       && 0 != compare_tree_int (TYPE_RM_SIZE (etype),
4426                                 GET_MODE_BITSIZE (TYPE_MODE (etype))))
4427     {
4428       tree rec_type = make_node (RECORD_TYPE);
4429       tree field
4430         = create_field_decl (get_identifier ("OBJ"), etype, rec_type,
4431                              1, 0, 0, 0);
4432
4433       TYPE_FIELDS (rec_type) = field;
4434       layout_type (rec_type);
4435
4436       expr = gnat_build_constructor (rec_type, build_tree_list (field, expr));
4437       expr = unchecked_convert (type, expr, notrunc_p);
4438     }
4439
4440   /* We have a special case when we are converting between two unconstrained
4441      array types.  In that case, take the address, convert the fat pointer
4442      types, and dereference.  */
4443   else if (TREE_CODE (etype) == UNCONSTRAINED_ARRAY_TYPE
4444            && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
4445     expr = build_unary_op (INDIRECT_REF, NULL_TREE,
4446                            build1 (VIEW_CONVERT_EXPR, TREE_TYPE (type),
4447                                    build_unary_op (ADDR_EXPR, NULL_TREE,
4448                                                    expr)));
4449
4450   /* Another special case is when we are converting to a vector type from its
4451      representative array type; this a regular conversion.  */
4452   else if (TREE_CODE (type) == VECTOR_TYPE
4453            && TREE_CODE (etype) == ARRAY_TYPE
4454            && gnat_types_compatible_p (TYPE_REPRESENTATIVE_ARRAY (type),
4455                                        etype))
4456     expr = convert (type, expr);
4457
4458   else
4459     {
4460       expr = maybe_unconstrained_array (expr);
4461       etype = TREE_TYPE (expr);
4462       if (can_fold_for_view_convert_p (expr))
4463         expr = fold_build1 (VIEW_CONVERT_EXPR, type, expr);
4464       else
4465         expr = build1 (VIEW_CONVERT_EXPR, type, expr);
4466     }
4467
4468   /* If the result is an integral type whose precision is not equal to its
4469      size, sign- or zero-extend the result.  We need not do this if the input
4470      is an integral type of the same precision and signedness or if the output
4471      is a biased type or if both the input and output are unsigned.  */
4472   if (!notrunc_p
4473       && INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
4474       && !(TREE_CODE (type) == INTEGER_TYPE
4475            && TYPE_BIASED_REPRESENTATION_P (type))
4476       && 0 != compare_tree_int (TYPE_RM_SIZE (type),
4477                                 GET_MODE_BITSIZE (TYPE_MODE (type)))
4478       && !(INTEGRAL_TYPE_P (etype)
4479            && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (etype)
4480            && operand_equal_p (TYPE_RM_SIZE (type),
4481                                (TYPE_RM_SIZE (etype) != 0
4482                                 ? TYPE_RM_SIZE (etype) : TYPE_SIZE (etype)),
4483                                0))
4484       && !(TYPE_UNSIGNED (type) && TYPE_UNSIGNED (etype)))
4485     {
4486       tree base_type = gnat_type_for_mode (TYPE_MODE (type),
4487                                            TYPE_UNSIGNED (type));
4488       tree shift_expr
4489         = convert (base_type,
4490                    size_binop (MINUS_EXPR,
4491                                bitsize_int
4492                                (GET_MODE_BITSIZE (TYPE_MODE (type))),
4493                                TYPE_RM_SIZE (type)));
4494       expr
4495         = convert (type,
4496                    build_binary_op (RSHIFT_EXPR, base_type,
4497                                     build_binary_op (LSHIFT_EXPR, base_type,
4498                                                      convert (base_type, expr),
4499                                                      shift_expr),
4500                                     shift_expr));
4501     }
4502
4503   /* An unchecked conversion should never raise Constraint_Error.  The code
4504      below assumes that GCC's conversion routines overflow the same way that
4505      the underlying hardware does.  This is probably true.  In the rare case
4506      when it is false, we can rely on the fact that such conversions are
4507      erroneous anyway.  */
4508   if (TREE_CODE (expr) == INTEGER_CST)
4509     TREE_OVERFLOW (expr) = 0;
4510
4511   /* If the sizes of the types differ and this is an VIEW_CONVERT_EXPR,
4512      show no longer constant.  */
4513   if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
4514       && !operand_equal_p (TYPE_SIZE_UNIT (type), TYPE_SIZE_UNIT (etype),
4515                            OEP_ONLY_CONST))
4516     TREE_CONSTANT (expr) = 0;
4517
4518   return expr;
4519 }
4520 \f
4521 /* Return the appropriate GCC tree code for the specified GNAT_TYPE,
4522    the latter being a record type as predicated by Is_Record_Type.  */
4523
4524 enum tree_code
4525 tree_code_for_record_type (Entity_Id gnat_type)
4526 {
4527   Node_Id component_list
4528     = Component_List (Type_Definition
4529                       (Declaration_Node
4530                        (Implementation_Base_Type (gnat_type))));
4531   Node_Id component;
4532
4533  /* Make this a UNION_TYPE unless it's either not an Unchecked_Union or
4534     we have a non-discriminant field outside a variant.  In either case,
4535     it's a RECORD_TYPE.  */
4536
4537   if (!Is_Unchecked_Union (gnat_type))
4538     return RECORD_TYPE;
4539
4540   for (component = First_Non_Pragma (Component_Items (component_list));
4541        Present (component);
4542        component = Next_Non_Pragma (component))
4543     if (Ekind (Defining_Entity (component)) == E_Component)
4544       return RECORD_TYPE;
4545
4546   return UNION_TYPE;
4547 }
4548
4549 /* Return true if GNAT_TYPE is a "double" floating-point type, i.e. whose
4550    size is equal to 64 bits, or an array of such a type.  Set ALIGN_CLAUSE
4551    according to the presence of an alignment clause on the type or, if it
4552    is an array, on the component type.  */
4553
4554 bool
4555 is_double_float_or_array (Entity_Id gnat_type, bool *align_clause)
4556 {
4557   gnat_type = Underlying_Type (gnat_type);
4558
4559   *align_clause = Present (Alignment_Clause (gnat_type));
4560
4561   if (Is_Array_Type (gnat_type))
4562     {
4563       gnat_type = Underlying_Type (Component_Type (gnat_type));
4564       if (Present (Alignment_Clause (gnat_type)))
4565         *align_clause = true;
4566     }
4567
4568   if (!Is_Floating_Point_Type (gnat_type))
4569     return false;
4570
4571   if (UI_To_Int (Esize (gnat_type)) != 64)
4572     return false;
4573
4574   return true;
4575 }
4576
4577 /* Return true if GNAT_TYPE is a "double" or larger scalar type, i.e. whose
4578    size is greater or equal to 64 bits, or an array of such a type.  Set
4579    ALIGN_CLAUSE according to the presence of an alignment clause on the
4580    type or, if it is an array, on the component type.  */
4581
4582 bool
4583 is_double_scalar_or_array (Entity_Id gnat_type, bool *align_clause)
4584 {
4585   gnat_type = Underlying_Type (gnat_type);
4586
4587   *align_clause = Present (Alignment_Clause (gnat_type));
4588
4589   if (Is_Array_Type (gnat_type))
4590     {
4591       gnat_type = Underlying_Type (Component_Type (gnat_type));
4592       if (Present (Alignment_Clause (gnat_type)))
4593         *align_clause = true;
4594     }
4595
4596   if (!Is_Scalar_Type (gnat_type))
4597     return false;
4598
4599   if (UI_To_Int (Esize (gnat_type)) < 64)
4600     return false;
4601
4602   return true;
4603 }
4604
4605 /* Return true if GNU_TYPE is suitable as the type of a non-aliased
4606    component of an aggregate type.  */
4607
4608 bool
4609 type_for_nonaliased_component_p (tree gnu_type)
4610 {
4611   /* If the type is passed by reference, we may have pointers to the
4612      component so it cannot be made non-aliased. */
4613   if (must_pass_by_ref (gnu_type) || default_pass_by_ref (gnu_type))
4614     return false;
4615
4616   /* We used to say that any component of aggregate type is aliased
4617      because the front-end may take 'Reference of it.  The front-end
4618      has been enhanced in the meantime so as to use a renaming instead
4619      in most cases, but the back-end can probably take the address of
4620      such a component too so we go for the conservative stance.
4621
4622      For instance, we might need the address of any array type, even
4623      if normally passed by copy, to construct a fat pointer if the
4624      component is used as an actual for an unconstrained formal.
4625
4626      Likewise for record types: even if a specific record subtype is
4627      passed by copy, the parent type might be passed by ref (e.g. if
4628      it's of variable size) and we might take the address of a child
4629      component to pass to a parent formal.  We have no way to check
4630      for such conditions here.  */
4631   if (AGGREGATE_TYPE_P (gnu_type))
4632     return false;
4633
4634   return true;
4635 }
4636
4637 /* Perform final processing on global variables.  */
4638
4639 void
4640 gnat_write_global_declarations (void)
4641 {
4642   /* Proceed to optimize and emit assembly.
4643      FIXME: shouldn't be the front end's responsibility to call this.  */
4644   cgraph_finalize_compilation_unit ();
4645
4646   /* Emit debug info for all global declarations.  */
4647   emit_debug_global_declarations (VEC_address (tree, global_decls),
4648                                   VEC_length (tree, global_decls));
4649 }
4650
4651 /* ************************************************************************
4652  * *                           GCC builtins support                       *
4653  * ************************************************************************ */
4654
4655 /* The general scheme is fairly simple:
4656
4657    For each builtin function/type to be declared, gnat_install_builtins calls
4658    internal facilities which eventually get to gnat_push_decl, which in turn
4659    tracks the so declared builtin function decls in the 'builtin_decls' global
4660    datastructure. When an Intrinsic subprogram declaration is processed, we
4661    search this global datastructure to retrieve the associated BUILT_IN DECL
4662    node.  */
4663
4664 /* Search the chain of currently available builtin declarations for a node
4665    corresponding to function NAME (an IDENTIFIER_NODE).  Return the first node
4666    found, if any, or NULL_TREE otherwise.  */
4667 tree
4668 builtin_decl_for (tree name)
4669 {
4670   unsigned i;
4671   tree decl;
4672
4673   for (i = 0; VEC_iterate(tree, builtin_decls, i, decl); i++)
4674     if (DECL_NAME (decl) == name)
4675       return decl;
4676
4677   return NULL_TREE;
4678 }
4679
4680 /* The code below eventually exposes gnat_install_builtins, which declares
4681    the builtin types and functions we might need, either internally or as
4682    user accessible facilities.
4683
4684    ??? This is a first implementation shot, still in rough shape.  It is
4685    heavily inspired from the "C" family implementation, with chunks copied
4686    verbatim from there.
4687
4688    Two obvious TODO candidates are
4689    o Use a more efficient name/decl mapping scheme
4690    o Devise a middle-end infrastructure to avoid having to copy
4691      pieces between front-ends.  */
4692
4693 /* ----------------------------------------------------------------------- *
4694  *                         BUILTIN ELEMENTARY TYPES                        *
4695  * ----------------------------------------------------------------------- */
4696
4697 /* Standard data types to be used in builtin argument declarations.  */
4698
4699 enum c_tree_index
4700 {
4701     CTI_SIGNED_SIZE_TYPE, /* For format checking only.  */
4702     CTI_STRING_TYPE,
4703     CTI_CONST_STRING_TYPE,
4704
4705     CTI_MAX
4706 };
4707
4708 static tree c_global_trees[CTI_MAX];
4709
4710 #define signed_size_type_node   c_global_trees[CTI_SIGNED_SIZE_TYPE]
4711 #define string_type_node        c_global_trees[CTI_STRING_TYPE]
4712 #define const_string_type_node  c_global_trees[CTI_CONST_STRING_TYPE]
4713
4714 /* ??? In addition some attribute handlers, we currently don't support a
4715    (small) number of builtin-types, which in turns inhibits support for a
4716    number of builtin functions.  */
4717 #define wint_type_node    void_type_node
4718 #define intmax_type_node  void_type_node
4719 #define uintmax_type_node void_type_node
4720
4721 /* Build the void_list_node (void_type_node having been created).  */
4722
4723 static tree
4724 build_void_list_node (void)
4725 {
4726   tree t = build_tree_list (NULL_TREE, void_type_node);
4727   return t;
4728 }
4729
4730 /* Used to help initialize the builtin-types.def table.  When a type of
4731    the correct size doesn't exist, use error_mark_node instead of NULL.
4732    The later results in segfaults even when a decl using the type doesn't
4733    get invoked.  */
4734
4735 static tree
4736 builtin_type_for_size (int size, bool unsignedp)
4737 {
4738   tree type = gnat_type_for_size (size, unsignedp);
4739   return type ? type : error_mark_node;
4740 }
4741
4742 /* Build/push the elementary type decls that builtin functions/types
4743    will need.  */
4744
4745 static void
4746 install_builtin_elementary_types (void)
4747 {
4748   signed_size_type_node = size_type_node;
4749   pid_type_node = integer_type_node;
4750   void_list_node = build_void_list_node ();
4751
4752   string_type_node = build_pointer_type (char_type_node);
4753   const_string_type_node
4754     = build_pointer_type (build_qualified_type
4755                           (char_type_node, TYPE_QUAL_CONST));
4756 }
4757
4758 /* ----------------------------------------------------------------------- *
4759  *                          BUILTIN FUNCTION TYPES                         *
4760  * ----------------------------------------------------------------------- */
4761
4762 /* Now, builtin function types per se.  */
4763
4764 enum c_builtin_type
4765 {
4766 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
4767 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
4768 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
4769 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
4770 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4771 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4772 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
4773 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6) NAME,
4774 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7) NAME,
4775 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
4776 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
4777 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
4778 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
4779 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
4780 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG6) \
4781   NAME,
4782 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
4783 #include "builtin-types.def"
4784 #undef DEF_PRIMITIVE_TYPE
4785 #undef DEF_FUNCTION_TYPE_0
4786 #undef DEF_FUNCTION_TYPE_1
4787 #undef DEF_FUNCTION_TYPE_2
4788 #undef DEF_FUNCTION_TYPE_3
4789 #undef DEF_FUNCTION_TYPE_4
4790 #undef DEF_FUNCTION_TYPE_5
4791 #undef DEF_FUNCTION_TYPE_6
4792 #undef DEF_FUNCTION_TYPE_7
4793 #undef DEF_FUNCTION_TYPE_VAR_0
4794 #undef DEF_FUNCTION_TYPE_VAR_1
4795 #undef DEF_FUNCTION_TYPE_VAR_2
4796 #undef DEF_FUNCTION_TYPE_VAR_3
4797 #undef DEF_FUNCTION_TYPE_VAR_4
4798 #undef DEF_FUNCTION_TYPE_VAR_5
4799 #undef DEF_POINTER_TYPE
4800   BT_LAST
4801 };
4802
4803 typedef enum c_builtin_type builtin_type;
4804
4805 /* A temporary array used in communication with def_fn_type.  */
4806 static GTY(()) tree builtin_types[(int) BT_LAST + 1];
4807
4808 /* A helper function for install_builtin_types.  Build function type
4809    for DEF with return type RET and N arguments.  If VAR is true, then the
4810    function should be variadic after those N arguments.
4811
4812    Takes special care not to ICE if any of the types involved are
4813    error_mark_node, which indicates that said type is not in fact available
4814    (see builtin_type_for_size).  In which case the function type as a whole
4815    should be error_mark_node.  */
4816
4817 static void
4818 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
4819 {
4820   tree args = NULL, t;
4821   va_list list;
4822   int i;
4823
4824   va_start (list, n);
4825   for (i = 0; i < n; ++i)
4826     {
4827       builtin_type a = (builtin_type) va_arg (list, int);
4828       t = builtin_types[a];
4829       if (t == error_mark_node)
4830         goto egress;
4831       args = tree_cons (NULL_TREE, t, args);
4832     }
4833   va_end (list);
4834
4835   args = nreverse (args);
4836   if (!var)
4837     args = chainon (args, void_list_node);
4838
4839   t = builtin_types[ret];
4840   if (t == error_mark_node)
4841     goto egress;
4842   t = build_function_type (t, args);
4843
4844  egress:
4845   builtin_types[def] = t;
4846 }
4847
4848 /* Build the builtin function types and install them in the builtin_types
4849    array for later use in builtin function decls.  */
4850
4851 static void
4852 install_builtin_function_types (void)
4853 {
4854   tree va_list_ref_type_node;
4855   tree va_list_arg_type_node;
4856
4857   if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4858     {
4859       va_list_arg_type_node = va_list_ref_type_node =
4860         build_pointer_type (TREE_TYPE (va_list_type_node));
4861     }
4862   else
4863     {
4864       va_list_arg_type_node = va_list_type_node;
4865       va_list_ref_type_node = build_reference_type (va_list_type_node);
4866     }
4867
4868 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
4869   builtin_types[ENUM] = VALUE;
4870 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
4871   def_fn_type (ENUM, RETURN, 0, 0);
4872 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
4873   def_fn_type (ENUM, RETURN, 0, 1, ARG1);
4874 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
4875   def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
4876 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4877   def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
4878 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4879   def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
4880 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4881   def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4882 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4883                             ARG6)                                       \
4884   def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
4885 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
4886                             ARG6, ARG7)                                 \
4887   def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
4888 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
4889   def_fn_type (ENUM, RETURN, 1, 0);
4890 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
4891   def_fn_type (ENUM, RETURN, 1, 1, ARG1);
4892 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
4893   def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
4894 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
4895   def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
4896 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
4897   def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
4898 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
4899   def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
4900 #define DEF_POINTER_TYPE(ENUM, TYPE) \
4901   builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
4902
4903 #include "builtin-types.def"
4904
4905 #undef DEF_PRIMITIVE_TYPE
4906 #undef DEF_FUNCTION_TYPE_1
4907 #undef DEF_FUNCTION_TYPE_2
4908 #undef DEF_FUNCTION_TYPE_3
4909 #undef DEF_FUNCTION_TYPE_4
4910 #undef DEF_FUNCTION_TYPE_5
4911 #undef DEF_FUNCTION_TYPE_6
4912 #undef DEF_FUNCTION_TYPE_VAR_0
4913 #undef DEF_FUNCTION_TYPE_VAR_1
4914 #undef DEF_FUNCTION_TYPE_VAR_2
4915 #undef DEF_FUNCTION_TYPE_VAR_3
4916 #undef DEF_FUNCTION_TYPE_VAR_4
4917 #undef DEF_FUNCTION_TYPE_VAR_5
4918 #undef DEF_POINTER_TYPE
4919   builtin_types[(int) BT_LAST] = NULL_TREE;
4920 }
4921
4922 /* ----------------------------------------------------------------------- *
4923  *                            BUILTIN ATTRIBUTES                           *
4924  * ----------------------------------------------------------------------- */
4925
4926 enum built_in_attribute
4927 {
4928 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
4929 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
4930 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
4931 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
4932 #include "builtin-attrs.def"
4933 #undef DEF_ATTR_NULL_TREE
4934 #undef DEF_ATTR_INT
4935 #undef DEF_ATTR_IDENT
4936 #undef DEF_ATTR_TREE_LIST
4937   ATTR_LAST
4938 };
4939
4940 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
4941
4942 static void
4943 install_builtin_attributes (void)
4944 {
4945   /* Fill in the built_in_attributes array.  */
4946 #define DEF_ATTR_NULL_TREE(ENUM)                                \
4947   built_in_attributes[(int) ENUM] = NULL_TREE;
4948 #define DEF_ATTR_INT(ENUM, VALUE)                               \
4949   built_in_attributes[(int) ENUM] = build_int_cst (NULL_TREE, VALUE);
4950 #define DEF_ATTR_IDENT(ENUM, STRING)                            \
4951   built_in_attributes[(int) ENUM] = get_identifier (STRING);
4952 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
4953   built_in_attributes[(int) ENUM]                       \
4954     = tree_cons (built_in_attributes[(int) PURPOSE],    \
4955                  built_in_attributes[(int) VALUE],      \
4956                  built_in_attributes[(int) CHAIN]);
4957 #include "builtin-attrs.def"
4958 #undef DEF_ATTR_NULL_TREE
4959 #undef DEF_ATTR_INT
4960 #undef DEF_ATTR_IDENT
4961 #undef DEF_ATTR_TREE_LIST
4962 }
4963
4964 /* Handle a "const" attribute; arguments as in
4965    struct attribute_spec.handler.  */
4966
4967 static tree
4968 handle_const_attribute (tree *node, tree ARG_UNUSED (name),
4969                         tree ARG_UNUSED (args), int ARG_UNUSED (flags),
4970                         bool *no_add_attrs)
4971 {
4972   if (TREE_CODE (*node) == FUNCTION_DECL)
4973     TREE_READONLY (*node) = 1;
4974   else
4975     *no_add_attrs = true;
4976
4977   return NULL_TREE;
4978 }
4979
4980 /* Handle a "nothrow" attribute; arguments as in
4981    struct attribute_spec.handler.  */
4982
4983 static tree
4984 handle_nothrow_attribute (tree *node, tree ARG_UNUSED (name),
4985                           tree ARG_UNUSED (args), int ARG_UNUSED (flags),
4986                           bool *no_add_attrs)
4987 {
4988   if (TREE_CODE (*node) == FUNCTION_DECL)
4989     TREE_NOTHROW (*node) = 1;
4990   else
4991     *no_add_attrs = true;
4992
4993   return NULL_TREE;
4994 }
4995
4996 /* Handle a "pure" attribute; arguments as in
4997    struct attribute_spec.handler.  */
4998
4999 static tree
5000 handle_pure_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5001                        int ARG_UNUSED (flags), bool *no_add_attrs)
5002 {
5003   if (TREE_CODE (*node) == FUNCTION_DECL)
5004     DECL_PURE_P (*node) = 1;
5005   /* ??? TODO: Support types.  */
5006   else
5007     {
5008       warning (OPT_Wattributes, "%qs attribute ignored",
5009                IDENTIFIER_POINTER (name));
5010       *no_add_attrs = true;
5011     }
5012
5013   return NULL_TREE;
5014 }
5015
5016 /* Handle a "no vops" attribute; arguments as in
5017    struct attribute_spec.handler.  */
5018
5019 static tree
5020 handle_novops_attribute (tree *node, tree ARG_UNUSED (name),
5021                          tree ARG_UNUSED (args), int ARG_UNUSED (flags),
5022                          bool *ARG_UNUSED (no_add_attrs))
5023 {
5024   gcc_assert (TREE_CODE (*node) == FUNCTION_DECL);
5025   DECL_IS_NOVOPS (*node) = 1;
5026   return NULL_TREE;
5027 }
5028
5029 /* Helper for nonnull attribute handling; fetch the operand number
5030    from the attribute argument list.  */
5031
5032 static bool
5033 get_nonnull_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5034 {
5035   /* Verify the arg number is a constant.  */
5036   if (TREE_CODE (arg_num_expr) != INTEGER_CST
5037       || TREE_INT_CST_HIGH (arg_num_expr) != 0)
5038     return false;
5039
5040   *valp = TREE_INT_CST_LOW (arg_num_expr);
5041   return true;
5042 }
5043
5044 /* Handle the "nonnull" attribute.  */
5045 static tree
5046 handle_nonnull_attribute (tree *node, tree ARG_UNUSED (name),
5047                           tree args, int ARG_UNUSED (flags),
5048                           bool *no_add_attrs)
5049 {
5050   tree type = *node;
5051   unsigned HOST_WIDE_INT attr_arg_num;
5052
5053   /* If no arguments are specified, all pointer arguments should be
5054      non-null.  Verify a full prototype is given so that the arguments
5055      will have the correct types when we actually check them later.  */
5056   if (!args)
5057     {
5058       if (!TYPE_ARG_TYPES (type))
5059         {
5060           error ("nonnull attribute without arguments on a non-prototype");
5061           *no_add_attrs = true;
5062         }
5063       return NULL_TREE;
5064     }
5065
5066   /* Argument list specified.  Verify that each argument number references
5067      a pointer argument.  */
5068   for (attr_arg_num = 1; args; args = TREE_CHAIN (args))
5069     {
5070       tree argument;
5071       unsigned HOST_WIDE_INT arg_num = 0, ck_num;
5072
5073       if (!get_nonnull_operand (TREE_VALUE (args), &arg_num))
5074         {
5075           error ("nonnull argument has invalid operand number (argument %lu)",
5076                  (unsigned long) attr_arg_num);
5077           *no_add_attrs = true;
5078           return NULL_TREE;
5079         }
5080
5081       argument = TYPE_ARG_TYPES (type);
5082       if (argument)
5083         {
5084           for (ck_num = 1; ; ck_num++)
5085             {
5086               if (!argument || ck_num == arg_num)
5087                 break;
5088               argument = TREE_CHAIN (argument);
5089             }
5090
5091           if (!argument
5092               || TREE_CODE (TREE_VALUE (argument)) == VOID_TYPE)
5093             {
5094               error ("nonnull argument with out-of-range operand number (argument %lu, operand %lu)",
5095                      (unsigned long) attr_arg_num, (unsigned long) arg_num);
5096               *no_add_attrs = true;
5097               return NULL_TREE;
5098             }
5099
5100           if (TREE_CODE (TREE_VALUE (argument)) != POINTER_TYPE)
5101             {
5102               error ("nonnull argument references non-pointer operand (argument %lu, operand %lu)",
5103                    (unsigned long) attr_arg_num, (unsigned long) arg_num);
5104               *no_add_attrs = true;
5105               return NULL_TREE;
5106             }
5107         }
5108     }
5109
5110   return NULL_TREE;
5111 }
5112
5113 /* Handle a "sentinel" attribute.  */
5114
5115 static tree
5116 handle_sentinel_attribute (tree *node, tree name, tree args,
5117                            int ARG_UNUSED (flags), bool *no_add_attrs)
5118 {
5119   tree params = TYPE_ARG_TYPES (*node);
5120
5121   if (!params)
5122     {
5123       warning (OPT_Wattributes,
5124                "%qs attribute requires prototypes with named arguments",
5125                IDENTIFIER_POINTER (name));
5126       *no_add_attrs = true;
5127     }
5128   else
5129     {
5130       while (TREE_CHAIN (params))
5131         params = TREE_CHAIN (params);
5132
5133       if (VOID_TYPE_P (TREE_VALUE (params)))
5134         {
5135           warning (OPT_Wattributes,
5136                    "%qs attribute only applies to variadic functions",
5137                    IDENTIFIER_POINTER (name));
5138           *no_add_attrs = true;
5139         }
5140     }
5141
5142   if (args)
5143     {
5144       tree position = TREE_VALUE (args);
5145
5146       if (TREE_CODE (position) != INTEGER_CST)
5147         {
5148           warning (0, "requested position is not an integer constant");
5149           *no_add_attrs = true;
5150         }
5151       else
5152         {
5153           if (tree_int_cst_lt (position, integer_zero_node))
5154             {
5155               warning (0, "requested position is less than zero");
5156               *no_add_attrs = true;
5157             }
5158         }
5159     }
5160
5161   return NULL_TREE;
5162 }
5163
5164 /* Handle a "noreturn" attribute; arguments as in
5165    struct attribute_spec.handler.  */
5166
5167 static tree
5168 handle_noreturn_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5169                            int ARG_UNUSED (flags), bool *no_add_attrs)
5170 {
5171   tree type = TREE_TYPE (*node);
5172
5173   /* See FIXME comment in c_common_attribute_table.  */
5174   if (TREE_CODE (*node) == FUNCTION_DECL)
5175     TREE_THIS_VOLATILE (*node) = 1;
5176   else if (TREE_CODE (type) == POINTER_TYPE
5177            && TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE)
5178     TREE_TYPE (*node)
5179       = build_pointer_type
5180         (build_type_variant (TREE_TYPE (type),
5181                              TYPE_READONLY (TREE_TYPE (type)), 1));
5182   else
5183     {
5184       warning (OPT_Wattributes, "%qs attribute ignored",
5185                IDENTIFIER_POINTER (name));
5186       *no_add_attrs = true;
5187     }
5188
5189   return NULL_TREE;
5190 }
5191
5192 /* Handle a "malloc" attribute; arguments as in
5193    struct attribute_spec.handler.  */
5194
5195 static tree
5196 handle_malloc_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5197                          int ARG_UNUSED (flags), bool *no_add_attrs)
5198 {
5199   if (TREE_CODE (*node) == FUNCTION_DECL
5200       && POINTER_TYPE_P (TREE_TYPE (TREE_TYPE (*node))))
5201     DECL_IS_MALLOC (*node) = 1;
5202   else
5203     {
5204       warning (OPT_Wattributes, "%qs attribute ignored",
5205                IDENTIFIER_POINTER (name));
5206       *no_add_attrs = true;
5207     }
5208
5209   return NULL_TREE;
5210 }
5211
5212 /* Fake handler for attributes we don't properly support.  */
5213
5214 tree
5215 fake_attribute_handler (tree * ARG_UNUSED (node),
5216                         tree ARG_UNUSED (name),
5217                         tree ARG_UNUSED (args),
5218                         int  ARG_UNUSED (flags),
5219                         bool * ARG_UNUSED (no_add_attrs))
5220 {
5221   return NULL_TREE;
5222 }
5223
5224 /* Handle a "type_generic" attribute.  */
5225
5226 static tree
5227 handle_type_generic_attribute (tree *node, tree ARG_UNUSED (name),
5228                                tree ARG_UNUSED (args), int ARG_UNUSED (flags),
5229                                bool * ARG_UNUSED (no_add_attrs))
5230 {
5231   tree params;
5232
5233   /* Ensure we have a function type.  */
5234   gcc_assert (TREE_CODE (*node) == FUNCTION_TYPE);
5235
5236   params = TYPE_ARG_TYPES (*node);
5237   while (params && ! VOID_TYPE_P (TREE_VALUE (params)))
5238     params = TREE_CHAIN (params);
5239
5240   /* Ensure we have a variadic function.  */
5241   gcc_assert (!params);
5242
5243   return NULL_TREE;
5244 }
5245
5246 /* Handle a "vector_size" attribute; arguments as in
5247    struct attribute_spec.handler.  */
5248
5249 static tree
5250 handle_vector_size_attribute (tree *node, tree name, tree args,
5251                               int ARG_UNUSED (flags),
5252                               bool *no_add_attrs)
5253 {
5254   unsigned HOST_WIDE_INT vecsize, nunits;
5255   enum machine_mode orig_mode;
5256   tree type = *node, new_type, size;
5257
5258   *no_add_attrs = true;
5259
5260   size = TREE_VALUE (args);
5261
5262   if (!host_integerp (size, 1))
5263     {
5264       warning (OPT_Wattributes, "%qs attribute ignored",
5265                IDENTIFIER_POINTER (name));
5266       return NULL_TREE;
5267     }
5268
5269   /* Get the vector size (in bytes).  */
5270   vecsize = tree_low_cst (size, 1);
5271
5272   /* We need to provide for vector pointers, vector arrays, and
5273      functions returning vectors.  For example:
5274
5275        __attribute__((vector_size(16))) short *foo;
5276
5277      In this case, the mode is SI, but the type being modified is
5278      HI, so we need to look further.  */
5279
5280   while (POINTER_TYPE_P (type)
5281          || TREE_CODE (type) == FUNCTION_TYPE
5282          || TREE_CODE (type) == METHOD_TYPE
5283          || TREE_CODE (type) == ARRAY_TYPE
5284          || TREE_CODE (type) == OFFSET_TYPE)
5285     type = TREE_TYPE (type);
5286
5287   /* Get the mode of the type being modified.  */
5288   orig_mode = TYPE_MODE (type);
5289
5290   if ((!INTEGRAL_TYPE_P (type)
5291        && !SCALAR_FLOAT_TYPE_P (type)
5292        && !FIXED_POINT_TYPE_P (type))
5293       || (!SCALAR_FLOAT_MODE_P (orig_mode)
5294           && GET_MODE_CLASS (orig_mode) != MODE_INT
5295           && !ALL_SCALAR_FIXED_POINT_MODE_P (orig_mode))
5296       || !host_integerp (TYPE_SIZE_UNIT (type), 1)
5297       || TREE_CODE (type) == BOOLEAN_TYPE)
5298     {
5299       error ("invalid vector type for attribute %qs",
5300              IDENTIFIER_POINTER (name));
5301       return NULL_TREE;
5302     }
5303
5304   if (vecsize % tree_low_cst (TYPE_SIZE_UNIT (type), 1))
5305     {
5306       error ("vector size not an integral multiple of component size");
5307       return NULL;
5308     }
5309
5310   if (vecsize == 0)
5311     {
5312       error ("zero vector size");
5313       return NULL;
5314     }
5315
5316   /* Calculate how many units fit in the vector.  */
5317   nunits = vecsize / tree_low_cst (TYPE_SIZE_UNIT (type), 1);
5318   if (nunits & (nunits - 1))
5319     {
5320       error ("number of components of the vector not a power of two");
5321       return NULL_TREE;
5322     }
5323
5324   new_type = build_vector_type (type, nunits);
5325
5326   /* Build back pointers if needed.  */
5327   *node = lang_hooks.types.reconstruct_complex_type (*node, new_type);
5328
5329   return NULL_TREE;
5330 }
5331
5332 /* Handle a "vector_type" attribute; arguments as in
5333    struct attribute_spec.handler.  */
5334
5335 static tree
5336 handle_vector_type_attribute (tree *node, tree name, tree ARG_UNUSED (args),
5337                               int ARG_UNUSED (flags),
5338                               bool *no_add_attrs)
5339 {
5340   /* Vector representative type and size.  */
5341   tree rep_type = *node;
5342   tree rep_size = TYPE_SIZE_UNIT (rep_type);
5343   tree rep_name;
5344
5345   /* Vector size in bytes and number of units.  */
5346   unsigned HOST_WIDE_INT vec_bytes, vec_units;
5347
5348   /* Vector element type and mode.  */
5349   tree elem_type;
5350   enum machine_mode elem_mode;
5351
5352   *no_add_attrs = true;
5353
5354   /* Get the representative array type, possibly nested within a
5355      padding record e.g. for alignment purposes.  */
5356
5357   if (TYPE_IS_PADDING_P (rep_type))
5358     rep_type = TREE_TYPE (TYPE_FIELDS (rep_type));
5359
5360   if (TREE_CODE (rep_type) != ARRAY_TYPE)
5361     {
5362       error ("attribute %qs applies to array types only",
5363              IDENTIFIER_POINTER (name));
5364       return NULL_TREE;
5365     }
5366
5367   /* Silently punt on variable sizes.  We can't make vector types for them,
5368      need to ignore them on front-end generated subtypes of unconstrained
5369      bases, and this attribute is for binding implementors, not end-users, so
5370      we should never get there from legitimate explicit uses.  */
5371
5372   if (!host_integerp (rep_size, 1))
5373     return NULL_TREE;
5374
5375   /* Get the element type/mode and check this is something we know
5376      how to make vectors of.  */
5377
5378   elem_type = TREE_TYPE (rep_type);
5379   elem_mode = TYPE_MODE (elem_type);
5380
5381   if ((!INTEGRAL_TYPE_P (elem_type)
5382        && !SCALAR_FLOAT_TYPE_P (elem_type)
5383        && !FIXED_POINT_TYPE_P (elem_type))
5384       || (!SCALAR_FLOAT_MODE_P (elem_mode)
5385           && GET_MODE_CLASS (elem_mode) != MODE_INT
5386           && !ALL_SCALAR_FIXED_POINT_MODE_P (elem_mode))
5387       || !host_integerp (TYPE_SIZE_UNIT (elem_type), 1))
5388     {
5389       error ("invalid element type for attribute %qs",
5390              IDENTIFIER_POINTER (name));
5391       return NULL_TREE;
5392     }
5393
5394   /* Sanity check the vector size and element type consistency.  */
5395
5396   vec_bytes = tree_low_cst (rep_size, 1);
5397
5398   if (vec_bytes % tree_low_cst (TYPE_SIZE_UNIT (elem_type), 1))
5399     {
5400       error ("vector size not an integral multiple of component size");
5401       return NULL;
5402     }
5403
5404   if (vec_bytes == 0)
5405     {
5406       error ("zero vector size");
5407       return NULL;
5408     }
5409
5410   vec_units = vec_bytes / tree_low_cst (TYPE_SIZE_UNIT (elem_type), 1);
5411   if (vec_units & (vec_units - 1))
5412     {
5413       error ("number of components of the vector not a power of two");
5414       return NULL_TREE;
5415     }
5416
5417   /* Build the vector type and replace.  */
5418
5419   *node = build_vector_type (elem_type, vec_units);
5420   rep_name = TYPE_NAME (rep_type);
5421   if (TREE_CODE (rep_name) == TYPE_DECL)
5422     rep_name = DECL_NAME (rep_name);
5423   TYPE_NAME (*node) = rep_name;
5424   TYPE_REPRESENTATIVE_ARRAY (*node) = rep_type;
5425
5426   return NULL_TREE;
5427 }
5428
5429 /* ----------------------------------------------------------------------- *
5430  *                              BUILTIN FUNCTIONS                          *
5431  * ----------------------------------------------------------------------- */
5432
5433 /* Worker for DEF_BUILTIN.  Possibly define a builtin function with one or two
5434    names.  Does not declare a non-__builtin_ function if flag_no_builtin, or
5435    if nonansi_p and flag_no_nonansi_builtin.  */
5436
5437 static void
5438 def_builtin_1 (enum built_in_function fncode,
5439                const char *name,
5440                enum built_in_class fnclass,
5441                tree fntype, tree libtype,
5442                bool both_p, bool fallback_p,
5443                bool nonansi_p ATTRIBUTE_UNUSED,
5444                tree fnattrs, bool implicit_p)
5445 {
5446   tree decl;
5447   const char *libname;
5448
5449   /* Preserve an already installed decl.  It most likely was setup in advance
5450      (e.g. as part of the internal builtins) for specific reasons.  */
5451   if (built_in_decls[(int) fncode] != NULL_TREE)
5452     return;
5453
5454   gcc_assert ((!both_p && !fallback_p)
5455               || !strncmp (name, "__builtin_",
5456                            strlen ("__builtin_")));
5457
5458   libname = name + strlen ("__builtin_");
5459   decl = add_builtin_function (name, fntype, fncode, fnclass,
5460                                (fallback_p ? libname : NULL),
5461                                fnattrs);
5462   if (both_p)
5463     /* ??? This is normally further controlled by command-line options
5464        like -fno-builtin, but we don't have them for Ada.  */
5465     add_builtin_function (libname, libtype, fncode, fnclass,
5466                           NULL, fnattrs);
5467
5468   built_in_decls[(int) fncode] = decl;
5469   if (implicit_p)
5470     implicit_built_in_decls[(int) fncode] = decl;
5471 }
5472
5473 static int flag_isoc94 = 0;
5474 static int flag_isoc99 = 0;
5475
5476 /* Install what the common builtins.def offers.  */
5477
5478 static void
5479 install_builtin_functions (void)
5480 {
5481 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
5482                     NONANSI_P, ATTRS, IMPLICIT, COND)                   \
5483   if (NAME && COND)                                                     \
5484     def_builtin_1 (ENUM, NAME, CLASS,                                   \
5485                    builtin_types[(int) TYPE],                           \
5486                    builtin_types[(int) LIBTYPE],                        \
5487                    BOTH_P, FALLBACK_P, NONANSI_P,                       \
5488                    built_in_attributes[(int) ATTRS], IMPLICIT);
5489 #include "builtins.def"
5490 #undef DEF_BUILTIN
5491 }
5492
5493 /* ----------------------------------------------------------------------- *
5494  *                              BUILTIN FUNCTIONS                          *
5495  * ----------------------------------------------------------------------- */
5496
5497 /* Install the builtin functions we might need.  */
5498
5499 void
5500 gnat_install_builtins (void)
5501 {
5502   install_builtin_elementary_types ();
5503   install_builtin_function_types ();
5504   install_builtin_attributes ();
5505
5506   /* Install builtins used by generic middle-end pieces first.  Some of these
5507      know about internal specificities and control attributes accordingly, for
5508      instance __builtin_alloca vs no-throw and -fstack-check.  We will ignore
5509      the generic definition from builtins.def.  */
5510   build_common_builtin_nodes ();
5511
5512   /* Now, install the target specific builtins, such as the AltiVec family on
5513      ppc, and the common set as exposed by builtins.def.  */
5514   targetm.init_builtins ();
5515   install_builtin_functions ();
5516 }
5517
5518 #include "gt-ada-utils.h"
5519 #include "gtype-ada.h"