OSDN Git Service

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