OSDN Git Service

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