OSDN Git Service

* decl.c (gnat_to_gnu_entity): Use TREE_OVERFLOW instead of
[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-2007, 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 2,  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  distributed with GNAT;  see file COPYING.  If not, write *
19  * to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor, *
20  * Boston, MA 02110-1301, USA.                                              *
21  *                                                                          *
22  * GNAT was originally developed  by the GNAT team at  New York University. *
23  * Extensive contributions were provided by Ada Core Technologies Inc.      *
24  *                                                                          *
25  ****************************************************************************/
26
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "tree.h"
32 #include "flags.h"
33 #include "defaults.h"
34 #include "toplev.h"
35 #include "output.h"
36 #include "ggc.h"
37 #include "debug.h"
38 #include "convert.h"
39 #include "target.h"
40 #include "function.h"
41 #include "cgraph.h"
42 #include "tree-inline.h"
43 #include "tree-gimple.h"
44 #include "tree-dump.h"
45 #include "pointer-set.h"
46
47 #include "ada.h"
48 #include "types.h"
49 #include "atree.h"
50 #include "elists.h"
51 #include "namet.h"
52 #include "nlists.h"
53 #include "stringt.h"
54 #include "uintp.h"
55 #include "fe.h"
56 #include "sinfo.h"
57 #include "einfo.h"
58 #include "ada-tree.h"
59 #include "gigi.h"
60
61 #ifndef MAX_FIXED_MODE_SIZE
62 #define MAX_FIXED_MODE_SIZE GET_MODE_BITSIZE (DImode)
63 #endif
64
65 #ifndef MAX_BITS_PER_WORD
66 #define MAX_BITS_PER_WORD  BITS_PER_WORD
67 #endif
68
69 /* If nonzero, pretend we are allocating at global level.  */
70 int force_global;
71
72 /* Tree nodes for the various types and decls we create.  */
73 tree gnat_std_decls[(int) ADT_LAST];
74
75 /* Functions to call for each of the possible raise reasons.  */
76 tree gnat_raise_decls[(int) LAST_REASON_CODE + 1];
77
78 /* Forward declarations for handlers of attributes.  */
79 static tree handle_const_attribute (tree *, tree, tree, int, bool *);
80 static tree handle_nothrow_attribute (tree *, tree, tree, int, bool *);
81
82 /* Table of machine-independent internal attributes for Ada.  We support
83    this minimal set of attributes to accommodate the Alpha back-end which
84    unconditionally puts them on its builtins.  */
85 const struct attribute_spec gnat_internal_attribute_table[] =
86 {
87   /* { name, min_len, max_len, decl_req, type_req, fn_type_req, handler } */
88   { "const",   0, 0, true,  false, false, handle_const_attribute   },
89   { "nothrow", 0, 0, true,  false, false, handle_nothrow_attribute },
90   { NULL,      0, 0, false, false, false, NULL }
91 };
92
93 /* Associates a GNAT tree node to a GCC tree node. It is used in
94    `save_gnu_tree', `get_gnu_tree' and `present_gnu_tree'. See documentation
95    of `save_gnu_tree' for more info.  */
96 static GTY((length ("max_gnat_nodes"))) tree *associate_gnat_to_gnu;
97
98 #define GET_GNU_TREE(GNAT_ENTITY)       \
99   associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id]
100
101 #define SET_GNU_TREE(GNAT_ENTITY,VAL)   \
102   associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id] = (VAL)
103
104 #define PRESENT_GNU_TREE(GNAT_ENTITY)   \
105   (associate_gnat_to_gnu[(GNAT_ENTITY) - First_Node_Id] != NULL_TREE)
106
107 /* Associates a GNAT entity to a GCC tree node used as a dummy, if any.  */
108 static GTY((length ("max_gnat_nodes"))) tree *dummy_node_table;
109
110 #define GET_DUMMY_NODE(GNAT_ENTITY)     \
111   dummy_node_table[(GNAT_ENTITY) - First_Node_Id]
112
113 #define SET_DUMMY_NODE(GNAT_ENTITY,VAL) \
114   dummy_node_table[(GNAT_ENTITY) - First_Node_Id] = (VAL)
115
116 #define PRESENT_DUMMY_NODE(GNAT_ENTITY) \
117   (dummy_node_table[(GNAT_ENTITY) - First_Node_Id] != NULL_TREE)
118
119 /* This variable keeps a table for types for each precision so that we only
120    allocate each of them once. Signed and unsigned types are kept separate.
121
122    Note that these types are only used when fold-const requests something
123    special.  Perhaps we should NOT share these types; we'll see how it
124    goes later.  */
125 static GTY(()) tree signed_and_unsigned_types[2 * MAX_BITS_PER_WORD + 1][2];
126
127 /* Likewise for float types, but record these by mode.  */
128 static GTY(()) tree float_types[NUM_MACHINE_MODES];
129
130 /* For each binding contour we allocate a binding_level structure to indicate
131    the binding depth.  */
132
133 struct gnat_binding_level GTY((chain_next ("%h.chain")))
134 {
135   /* The binding level containing this one (the enclosing binding level). */
136   struct gnat_binding_level *chain;
137   /* The BLOCK node for this level.  */
138   tree block;
139   /* If nonzero, the setjmp buffer that needs to be updated for any
140      variable-sized definition within this context.  */
141   tree jmpbuf_decl;
142 };
143
144 /* The binding level currently in effect.  */
145 static GTY(()) struct gnat_binding_level *current_binding_level;
146
147 /* A chain of gnat_binding_level structures awaiting reuse.  */
148 static GTY((deletable)) struct gnat_binding_level *free_binding_level;
149
150 /* An array of global declarations.  */
151 static GTY(()) VEC (tree,gc) *global_decls;
152
153 /* An array of global renaming pointers.  */
154 static GTY(()) VEC (tree,gc) *global_renaming_pointers;
155
156 /* Arrays of functions called automatically at the beginning and
157    end of execution, on targets without .ctors/.dtors sections.  */
158 static GTY(()) VEC (tree,gc) *static_ctors;
159 static GTY(()) VEC (tree,gc) *static_dtors;
160
161 /* A chain of unused BLOCK nodes. */
162 static GTY((deletable)) tree free_block_chain;
163
164 struct language_function GTY(())
165 {
166   int unused;
167 };
168
169 static void gnat_install_builtins (void);
170 static tree merge_sizes (tree, tree, tree, bool, bool);
171 static tree compute_related_constant (tree, tree);
172 static tree split_plus (tree, tree *);
173 static bool value_zerop (tree);
174 static void gnat_gimplify_function (tree);
175 static tree float_type_for_precision (int, enum machine_mode);
176 static tree convert_to_fat_pointer (tree, tree);
177 static tree convert_to_thin_pointer (tree, tree);
178 static tree make_descriptor_field (const char *,tree, tree, tree);
179 static bool potential_alignment_gap (tree, tree, tree);
180 \f
181 /* Initialize the association of GNAT nodes to GCC trees.  */
182
183 void
184 init_gnat_to_gnu (void)
185 {
186   associate_gnat_to_gnu
187     = (tree *) ggc_alloc_cleared (max_gnat_nodes * sizeof (tree));
188 }
189
190 /* GNAT_ENTITY is a GNAT tree node for an entity.   GNU_DECL is the GCC tree
191    which is to be associated with GNAT_ENTITY. Such GCC tree node is always
192    a ..._DECL node.  If NO_CHECK is nonzero, the latter check is suppressed.
193
194    If GNU_DECL is zero, a previous association is to be reset.  */
195
196 void
197 save_gnu_tree (Entity_Id gnat_entity, tree gnu_decl, bool no_check)
198 {
199   /* Check that GNAT_ENTITY is not already defined and that it is being set
200      to something which is a decl.  Raise gigi 401 if not.  Usually, this
201      means GNAT_ENTITY is defined twice, but occasionally is due to some
202      Gigi problem.  */
203   gcc_assert (!(gnu_decl
204                 && (PRESENT_GNU_TREE (gnat_entity)
205                     || (!no_check && !DECL_P (gnu_decl)))));
206
207   SET_GNU_TREE (gnat_entity, gnu_decl);
208 }
209
210 /* GNAT_ENTITY is a GNAT tree node for a defining identifier.
211    Return the ..._DECL node that was associated with it.  If there is no tree
212    node associated with GNAT_ENTITY, abort.
213
214    In some cases, such as delayed elaboration or expressions that need to
215    be elaborated only once, GNAT_ENTITY is really not an entity.  */
216
217 tree
218 get_gnu_tree (Entity_Id gnat_entity)
219 {
220   gcc_assert (PRESENT_GNU_TREE (gnat_entity));
221   return GET_GNU_TREE (gnat_entity);
222 }
223
224 /* Return nonzero if a GCC tree has been associated with GNAT_ENTITY.  */
225
226 bool
227 present_gnu_tree (Entity_Id gnat_entity)
228 {
229   return PRESENT_GNU_TREE (gnat_entity);
230 }
231 \f
232 /* Initialize the association of GNAT nodes to GCC trees as dummies.  */
233
234 void
235 init_dummy_type (void)
236 {
237   dummy_node_table
238     = (tree *) ggc_alloc_cleared (max_gnat_nodes * sizeof (tree));
239 }
240
241 /* Make a dummy type corresponding to GNAT_TYPE.  */
242
243 tree
244 make_dummy_type (Entity_Id gnat_type)
245 {
246   Entity_Id gnat_underlying;
247   tree gnu_type;
248   enum tree_code code;
249
250   /* Find a full type for GNAT_TYPE, taking into account any class wide
251      types.  */
252   if (Is_Class_Wide_Type (gnat_type) && Present (Equivalent_Type (gnat_type)))
253     gnat_type = Equivalent_Type (gnat_type);
254   else if (Ekind (gnat_type) == E_Class_Wide_Type)
255     gnat_type = Root_Type (gnat_type);
256
257   /* Find a full view for GNAT_TYPE, looking through any incomplete or
258      private types.  */
259   if (IN (Ekind (gnat_type), Incomplete_Kind)
260       && From_With_Type (gnat_type))
261     gnat_underlying = Non_Limited_View (gnat_type);
262   else if (IN (Ekind (gnat_type), Incomplete_Or_Private_Kind)
263            && Present (Full_View (gnat_type)))
264     gnat_underlying = Full_View (gnat_type);
265   else
266     gnat_underlying = gnat_type;
267
268   /* If it there already a dummy type, use that one.  Else make one.  */
269   if (PRESENT_DUMMY_NODE (gnat_underlying))
270     return GET_DUMMY_NODE (gnat_underlying);
271
272   /* If this is a record, make this a RECORD_TYPE or UNION_TYPE; else make
273      it an ENUMERAL_TYPE.  */
274   if (Is_Record_Type (gnat_underlying))
275     code = tree_code_for_record_type (gnat_underlying);
276   else
277     code = ENUMERAL_TYPE;
278
279   gnu_type = make_node (code);
280   TYPE_NAME (gnu_type) = get_entity_name (gnat_type);
281   TYPE_DUMMY_P (gnu_type) = 1;
282   if (AGGREGATE_TYPE_P (gnu_type))
283     TYPE_STUB_DECL (gnu_type) = build_decl (TYPE_DECL, NULL_TREE, gnu_type);
284
285   SET_DUMMY_NODE (gnat_underlying, gnu_type);
286
287   return gnu_type;
288 }
289 \f
290 /* Return nonzero if we are currently in the global binding level.  */
291
292 int
293 global_bindings_p (void)
294 {
295   return ((force_global || !current_function_decl) ? -1 : 0);
296 }
297
298 /* Enter a new binding level. */
299
300 void
301 gnat_pushlevel ()
302 {
303   struct gnat_binding_level *newlevel = NULL;
304
305   /* Reuse a struct for this binding level, if there is one.  */
306   if (free_binding_level)
307     {
308       newlevel = free_binding_level;
309       free_binding_level = free_binding_level->chain;
310     }
311   else
312     newlevel
313       = (struct gnat_binding_level *)
314         ggc_alloc (sizeof (struct gnat_binding_level));
315
316   /* Use a free BLOCK, if any; otherwise, allocate one.  */
317   if (free_block_chain)
318     {
319       newlevel->block = free_block_chain;
320       free_block_chain = TREE_CHAIN (free_block_chain);
321       TREE_CHAIN (newlevel->block) = NULL_TREE;
322     }
323   else
324     newlevel->block = make_node (BLOCK);
325
326   /* Point the BLOCK we just made to its parent.  */
327   if (current_binding_level)
328     BLOCK_SUPERCONTEXT (newlevel->block) = current_binding_level->block;
329
330   BLOCK_VARS (newlevel->block) = BLOCK_SUBBLOCKS (newlevel->block) = NULL_TREE;
331   TREE_USED (newlevel->block) = 1;
332
333   /* Add this level to the front of the chain (stack) of levels that are
334      active.  */
335   newlevel->chain = current_binding_level;
336   newlevel->jmpbuf_decl = NULL_TREE;
337   current_binding_level = newlevel;
338 }
339
340 /* Set SUPERCONTEXT of the BLOCK for the current binding level to FNDECL
341    and point FNDECL to this BLOCK.  */
342
343 void
344 set_current_block_context (tree fndecl)
345 {
346   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
347   DECL_INITIAL (fndecl) = current_binding_level->block;
348 }
349
350 /* Set the jmpbuf_decl for the current binding level to DECL.  */
351
352 void
353 set_block_jmpbuf_decl (tree decl)
354 {
355   current_binding_level->jmpbuf_decl = decl;
356 }
357
358 /* Get the jmpbuf_decl, if any, for the current binding level.  */
359
360 tree
361 get_block_jmpbuf_decl ()
362 {
363   return current_binding_level->jmpbuf_decl;
364 }
365
366 /* Exit a binding level. Set any BLOCK into the current code group.  */
367
368 void
369 gnat_poplevel ()
370 {
371   struct gnat_binding_level *level = current_binding_level;
372   tree block = level->block;
373
374   BLOCK_VARS (block) = nreverse (BLOCK_VARS (block));
375   BLOCK_SUBBLOCKS (block) = nreverse (BLOCK_SUBBLOCKS (block));
376
377   /* If this is a function-level BLOCK don't do anything.  Otherwise, if there
378      are no variables free the block and merge its subblocks into those of its
379      parent block. Otherwise, add it to the list of its parent.  */
380   if (TREE_CODE (BLOCK_SUPERCONTEXT (block)) == FUNCTION_DECL)
381     ;
382   else if (BLOCK_VARS (block) == NULL_TREE)
383     {
384       BLOCK_SUBBLOCKS (level->chain->block)
385         = chainon (BLOCK_SUBBLOCKS (block),
386                    BLOCK_SUBBLOCKS (level->chain->block));
387       TREE_CHAIN (block) = free_block_chain;
388       free_block_chain = block;
389     }
390   else
391     {
392       TREE_CHAIN (block) = BLOCK_SUBBLOCKS (level->chain->block);
393       BLOCK_SUBBLOCKS (level->chain->block) = block;
394       TREE_USED (block) = 1;
395       set_block_for_group (block);
396     }
397
398   /* Free this binding structure.  */
399   current_binding_level = level->chain;
400   level->chain = free_binding_level;
401   free_binding_level = level;
402 }
403
404 /* Insert BLOCK at the end of the list of subblocks of the
405    current binding level.  This is used when a BIND_EXPR is expanded,
406    to handle the BLOCK node inside the BIND_EXPR.  */
407
408 void
409 insert_block (tree block)
410 {
411   TREE_USED (block) = 1;
412   TREE_CHAIN (block) = BLOCK_SUBBLOCKS (current_binding_level->block);
413   BLOCK_SUBBLOCKS (current_binding_level->block) = block;
414 }
415 \f
416 /* Records a ..._DECL node DECL as belonging to the current lexical scope
417    and uses GNAT_NODE for location information and propagating flags.  */
418
419 void
420 gnat_pushdecl (tree decl, Node_Id gnat_node)
421 {
422   /* If at top level, there is no context. But PARM_DECLs always go in the
423      level of its function.  */
424   if (global_bindings_p () && TREE_CODE (decl) != PARM_DECL)
425     DECL_CONTEXT (decl) = 0;
426   else
427     {
428       DECL_CONTEXT (decl) = current_function_decl;
429
430       /* Functions imported in another function are not really nested.  */
431       if (TREE_CODE (decl) == FUNCTION_DECL && TREE_PUBLIC (decl))
432         DECL_NO_STATIC_CHAIN (decl) = 1;
433     }
434
435   TREE_NO_WARNING (decl) = (gnat_node == Empty || Warnings_Off (gnat_node));
436
437   /* Set the location of DECL and emit a declaration for it.  */
438   if (Present (gnat_node))
439     Sloc_to_locus (Sloc (gnat_node), &DECL_SOURCE_LOCATION (decl));
440   add_decl_expr (decl, gnat_node);
441
442   /* Put the declaration on the list.  The list of declarations is in reverse
443      order. The list will be reversed later.  Put global variables in the
444      globals list. Don't put TYPE_DECLs for UNCONSTRAINED_ARRAY_TYPE into the
445      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         VEC_safe_push (tree, gc, global_decls, decl);
452       else
453         {
454           TREE_CHAIN (decl) = BLOCK_VARS (current_binding_level->block);
455           BLOCK_VARS (current_binding_level->block) = decl;
456         }
457     }
458
459   /* For the declaration of a type, set its name if it either is not already
460      set, was set to an IDENTIFIER_NODE, indicating an internal name,
461      or if the previous type name was not derived from a source name.
462      We'd rather have the type named with a real name and all the pointer
463      types to the same object have the same POINTER_TYPE node.  Code in this
464      function in c-decl.c makes a copy of the type node here, but that may
465      cause us trouble with incomplete types, so let's not try it (at least
466      for now).  */
467
468   if (TREE_CODE (decl) == TYPE_DECL
469       && DECL_NAME (decl)
470       && (!TYPE_NAME (TREE_TYPE (decl))
471           || TREE_CODE (TYPE_NAME (TREE_TYPE (decl))) == IDENTIFIER_NODE
472           || (TREE_CODE (TYPE_NAME (TREE_TYPE (decl))) == TYPE_DECL
473               && DECL_ARTIFICIAL (TYPE_NAME (TREE_TYPE (decl)))
474               && !DECL_ARTIFICIAL (decl))))
475     TYPE_NAME (TREE_TYPE (decl)) = decl;
476
477   /*  if (TREE_CODE (decl) != CONST_DECL)
478       rest_of_decl_compilation (decl, global_bindings_p (), 0); */
479 }
480 \f
481 /* Do little here.  Set up the standard declarations later after the
482    front end has been run.  */
483
484 void
485 gnat_init_decl_processing (void)
486 {
487   input_line = 0;
488
489   /* Make the binding_level structure for global names.  */
490   current_function_decl = 0;
491   current_binding_level = 0;
492   free_binding_level = 0;
493   gnat_pushlevel ();
494
495   build_common_tree_nodes (true, true);
496
497   /* In Ada, we use a signed type for SIZETYPE.  Use the signed type
498      corresponding to the size of Pmode.  In most cases when ptr_mode and
499      Pmode differ, C will use the width of ptr_mode as sizetype.  But we get
500      far better code using the width of Pmode.  Make this here since we need
501      this before we can expand the GNAT types.  */
502   size_type_node = gnat_type_for_size (GET_MODE_BITSIZE (Pmode), 0);
503   set_sizetype (size_type_node);
504   build_common_tree_nodes_2 (0);
505
506   /* Give names and make TYPE_DECLs for common types.  */
507   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier (SIZE_TYPE), sizetype),
508                  Empty);
509   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier ("integer"),
510                              integer_type_node),
511                  Empty);
512   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier ("unsigned char"),
513                              char_type_node),
514                  Empty);
515   gnat_pushdecl (build_decl (TYPE_DECL, get_identifier ("long integer"),
516                              long_integer_type_node),
517                  Empty);
518
519   ptr_void_type_node = build_pointer_type (void_type_node);
520
521   gnat_install_builtins ();
522 }
523
524 /* Install the builtin functions the middle-end needs.  */
525
526 static void
527 gnat_install_builtins ()
528 {
529   /* Builtins used by generic optimizers.  */
530   build_common_builtin_nodes ();
531
532   /* Target specific builtins, such as the AltiVec family on ppc.  */
533   targetm.init_builtins ();
534 }
535
536 /* Create the predefined scalar types such as `integer_type_node' needed
537    in the gcc back-end and initialize the global binding level.  */
538
539 void
540 init_gigi_decls (tree long_long_float_type, tree exception_type)
541 {
542   tree endlink, decl;
543   unsigned int i;
544
545   /* Set the types that GCC and Gigi use from the front end.  We would like
546      to do this for char_type_node, but it needs to correspond to the C
547      char type.  */
548   if (TREE_CODE (TREE_TYPE (long_long_float_type)) == INTEGER_TYPE)
549     {
550       /* In this case, the builtin floating point types are VAX float,
551          so make up a type for use.  */
552       longest_float_type_node = make_node (REAL_TYPE);
553       TYPE_PRECISION (longest_float_type_node) = LONG_DOUBLE_TYPE_SIZE;
554       layout_type (longest_float_type_node);
555       create_type_decl (get_identifier ("longest float type"),
556                         longest_float_type_node, NULL, false, true, Empty);
557     }
558   else
559     longest_float_type_node = TREE_TYPE (long_long_float_type);
560
561   except_type_node = TREE_TYPE (exception_type);
562
563   unsigned_type_node = gnat_type_for_size (INT_TYPE_SIZE, 1);
564   create_type_decl (get_identifier ("unsigned int"), unsigned_type_node,
565                     NULL, false, true, Empty);
566
567   void_type_decl_node = create_type_decl (get_identifier ("void"),
568                                           void_type_node, NULL, false, true,
569                                           Empty);
570
571   void_ftype = build_function_type (void_type_node, NULL_TREE);
572   ptr_void_ftype = build_pointer_type (void_ftype);
573
574   /* Now declare runtime functions. */
575   endlink = tree_cons (NULL_TREE, void_type_node, NULL_TREE);
576
577   /* malloc is a function declaration tree for a function to allocate
578      memory.  */
579   malloc_decl = create_subprog_decl (get_identifier ("__gnat_malloc"),
580                                      NULL_TREE,
581                                      build_function_type (ptr_void_type_node,
582                                                           tree_cons (NULL_TREE,
583                                                                      sizetype,
584                                                                      endlink)),
585                                      NULL_TREE, false, true, true, NULL,
586                                      Empty);
587   DECL_IS_MALLOC (malloc_decl) = 1;
588
589   /* free is a function declaration tree for a function to free memory.  */
590   free_decl
591     = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
592                            build_function_type (void_type_node,
593                                                 tree_cons (NULL_TREE,
594                                                            ptr_void_type_node,
595                                                            endlink)),
596                            NULL_TREE, false, true, true, NULL, Empty);
597
598   /* Make the types and functions used for exception processing.    */
599   jmpbuf_type
600     = build_array_type (gnat_type_for_mode (Pmode, 0),
601                         build_index_type (build_int_cst (NULL_TREE, 5)));
602   create_type_decl (get_identifier ("JMPBUF_T"), jmpbuf_type, NULL,
603                     false, true, Empty);
604   jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
605
606   /* Functions to get and set the jumpbuf pointer for the current thread.  */
607   get_jmpbuf_decl
608     = create_subprog_decl
609     (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
610      NULL_TREE, build_function_type (jmpbuf_ptr_type, NULL_TREE),
611      NULL_TREE, false, true, true, NULL, Empty);
612   /* Avoid creating superfluous edges to __builtin_setjmp receivers.  */
613   DECL_IS_PURE (get_jmpbuf_decl) = 1;
614
615   set_jmpbuf_decl
616     = create_subprog_decl
617     (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
618      NULL_TREE,
619      build_function_type (void_type_node,
620                           tree_cons (NULL_TREE, jmpbuf_ptr_type, endlink)),
621      NULL_TREE, false, true, true, NULL, Empty);
622
623   /* Function to get the current exception.  */
624   get_excptr_decl
625     = create_subprog_decl
626     (get_identifier ("system__soft_links__get_gnat_exception"),
627      NULL_TREE,
628      build_function_type (build_pointer_type (except_type_node), NULL_TREE),
629      NULL_TREE, false, true, true, NULL, Empty);
630   /* Avoid creating superfluous edges to __builtin_setjmp receivers.  */
631   DECL_IS_PURE (get_excptr_decl) = 1;
632
633   /* Functions that raise exceptions. */
634   raise_nodefer_decl
635     = create_subprog_decl
636       (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE,
637        build_function_type (void_type_node,
638                             tree_cons (NULL_TREE,
639                                        build_pointer_type (except_type_node),
640                                        endlink)),
641        NULL_TREE, false, true, true, NULL, Empty);
642
643   /* Dummy objects to materialize "others" and "all others" in the exception
644      tables.  These are exported by a-exexpr.adb, so see this unit for the
645      types to use.  */
646
647   others_decl
648     = create_var_decl (get_identifier ("OTHERS"),
649                        get_identifier ("__gnat_others_value"),
650                        integer_type_node, 0, 1, 0, 1, 1, 0, Empty);
651
652   all_others_decl
653     = create_var_decl (get_identifier ("ALL_OTHERS"),
654                        get_identifier ("__gnat_all_others_value"),
655                        integer_type_node, 0, 1, 0, 1, 1, 0, Empty);
656
657   /* Hooks to call when entering/leaving an exception handler.  */
658   begin_handler_decl
659     = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
660                            build_function_type (void_type_node,
661                                                 tree_cons (NULL_TREE,
662                                                            ptr_void_type_node,
663                                                            endlink)),
664                            NULL_TREE, false, true, true, NULL, Empty);
665
666   end_handler_decl
667     = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
668                            build_function_type (void_type_node,
669                                                 tree_cons (NULL_TREE,
670                                                            ptr_void_type_node,
671                                                            endlink)),
672                            NULL_TREE, false, true, true, NULL, Empty);
673
674   /* If in no exception handlers mode, all raise statements are redirected to
675      __gnat_last_chance_handler. No need to redefine raise_nodefer_decl, since
676      this procedure will never be called in this mode.  */
677   if (No_Exception_Handlers_Set ())
678     {
679       decl
680         = create_subprog_decl
681           (get_identifier ("__gnat_last_chance_handler"), NULL_TREE,
682            build_function_type (void_type_node,
683                                 tree_cons (NULL_TREE,
684                                            build_pointer_type (char_type_node),
685                                            tree_cons (NULL_TREE,
686                                                       integer_type_node,
687                                                       endlink))),
688            NULL_TREE, false, true, true, NULL, Empty);
689
690       for (i = 0; i < ARRAY_SIZE (gnat_raise_decls); i++)
691         gnat_raise_decls[i] = decl;
692     }
693   else
694     /* Otherwise, make one decl for each exception reason.  */
695     for (i = 0; i < ARRAY_SIZE (gnat_raise_decls); i++)
696       {
697         char name[17];
698
699         sprintf (name, "__gnat_rcheck_%.2d", i);
700         gnat_raise_decls[i]
701           = create_subprog_decl
702             (get_identifier (name), NULL_TREE,
703              build_function_type (void_type_node,
704                                   tree_cons (NULL_TREE,
705                                              build_pointer_type
706                                              (char_type_node),
707                                              tree_cons (NULL_TREE,
708                                                         integer_type_node,
709                                                         endlink))),
710              NULL_TREE, false, true, true, NULL, Empty);
711       }
712
713   /* Indicate that these never return.  */
714   TREE_THIS_VOLATILE (raise_nodefer_decl) = 1;
715   TREE_SIDE_EFFECTS (raise_nodefer_decl) = 1;
716   TREE_TYPE (raise_nodefer_decl)
717     = build_qualified_type (TREE_TYPE (raise_nodefer_decl),
718                             TYPE_QUAL_VOLATILE);
719
720   for (i = 0; i < ARRAY_SIZE (gnat_raise_decls); i++)
721     {
722       TREE_THIS_VOLATILE (gnat_raise_decls[i]) = 1;
723       TREE_SIDE_EFFECTS (gnat_raise_decls[i]) = 1;
724       TREE_TYPE (gnat_raise_decls[i])
725         = build_qualified_type (TREE_TYPE (gnat_raise_decls[i]),
726                                 TYPE_QUAL_VOLATILE);
727     }
728
729   /* setjmp returns an integer and has one operand, which is a pointer to
730      a jmpbuf.  */
731   setjmp_decl
732     = create_subprog_decl
733       (get_identifier ("__builtin_setjmp"), NULL_TREE,
734        build_function_type (integer_type_node,
735                             tree_cons (NULL_TREE,  jmpbuf_ptr_type, endlink)),
736        NULL_TREE, false, true, true, NULL, Empty);
737
738   DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
739   DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
740
741   /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
742      address.  */
743   update_setjmp_buf_decl
744     = create_subprog_decl
745       (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
746        build_function_type (void_type_node,
747                             tree_cons (NULL_TREE,  jmpbuf_ptr_type, endlink)),
748        NULL_TREE, false, true, true, NULL, Empty);
749
750   DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
751   DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
752
753   main_identifier_node = get_identifier ("main");
754 }
755 \f
756 /* Given a record type (RECORD_TYPE) and a chain of FIELD_DECL nodes
757    (FIELDLIST), finish constructing the record or union type.  If HAS_REP is
758    true, this record has a rep clause; don't call layout_type but merely set
759    the size and alignment ourselves.  If DEFER_DEBUG is true, do not call
760    the debugging routines on this type; it will be done later. */
761
762 void
763 finish_record_type (tree record_type, tree fieldlist, bool has_rep,
764                     bool defer_debug)
765 {
766   enum tree_code code = TREE_CODE (record_type);
767   tree ada_size = bitsize_zero_node;
768   tree size = bitsize_zero_node;
769   bool var_size = false;
770   bool had_size = TYPE_SIZE (record_type) != 0;
771   bool had_size_unit = TYPE_SIZE_UNIT (record_type) != 0;
772   tree field;
773
774   TYPE_FIELDS (record_type) = fieldlist;
775   TYPE_STUB_DECL (record_type)
776     = build_decl (TYPE_DECL, NULL_TREE, record_type);
777
778   /* We don't need both the typedef name and the record name output in
779      the debugging information, since they are the same.  */
780   DECL_ARTIFICIAL (TYPE_STUB_DECL (record_type)) = 1;
781
782   /* Globally initialize the record first.  If this is a rep'ed record,
783      that just means some initializations; otherwise, layout the record.  */
784
785   if (has_rep)
786     {
787       TYPE_ALIGN (record_type) = MAX (BITS_PER_UNIT, TYPE_ALIGN (record_type));
788       TYPE_MODE (record_type) = BLKmode;
789
790       if (!had_size_unit)
791         TYPE_SIZE_UNIT (record_type) = size_zero_node;
792       if (!had_size)
793         TYPE_SIZE (record_type) = bitsize_zero_node;
794
795       /* For all-repped records with a size specified, lay the QUAL_UNION_TYPE
796          out just like a UNION_TYPE, since the size will be fixed.  */
797       else if (code == QUAL_UNION_TYPE)
798         code = UNION_TYPE;
799     }
800   else
801     {
802       /* Ensure there isn't a size already set.  There can be in an error
803          case where there is a rep clause but all fields have errors and
804          no longer have a position.  */
805       TYPE_SIZE (record_type) = 0;
806       layout_type (record_type);
807     }
808
809   /* At this point, the position and size of each field is known.  It was
810      either set before entry by a rep clause, or by laying out the type above.
811
812      We now run a pass over the fields (in reverse order for QUAL_UNION_TYPEs)
813      to compute the Ada size; the GCC size and alignment (for rep'ed records
814      that are not padding types); and the mode (for rep'ed records).  We also
815      clear the DECL_BIT_FIELD indication for the cases we know have not been
816      handled yet, and adjust DECL_NONADDRESSABLE_P accordingly.  */
817
818   if (code == QUAL_UNION_TYPE)
819     fieldlist = nreverse (fieldlist);
820
821   for (field = fieldlist; field; field = TREE_CHAIN (field))
822     {
823       tree pos = bit_position (field);
824
825       tree type = TREE_TYPE (field);
826       tree this_size = DECL_SIZE (field);
827       tree this_ada_size = DECL_SIZE (field);
828
829       /* We need to make an XVE/XVU record if any field has variable size,
830          whether or not the record does.  For example, if we have a union,
831          it may be that all fields, rounded up to the alignment, have the
832          same size, in which case we'll use that size.  But the debug
833          output routines (except Dwarf2) won't be able to output the fields,
834          so we need to make the special record.  */
835       if (TREE_CODE (this_size) != INTEGER_CST)
836         var_size = true;
837
838       if ((TREE_CODE (type) == RECORD_TYPE || TREE_CODE (type) == UNION_TYPE
839           || TREE_CODE (type) == QUAL_UNION_TYPE)
840           && !TYPE_IS_FAT_POINTER_P (type)
841           && !TYPE_CONTAINS_TEMPLATE_P (type)
842           && TYPE_ADA_SIZE (type))
843         this_ada_size = TYPE_ADA_SIZE (type);
844
845       /* Clear DECL_BIT_FIELD for the cases layout_decl does not handle.  */
846       if (DECL_BIT_FIELD (field) && !STRICT_ALIGNMENT
847           && value_factor_p (pos, BITS_PER_UNIT)
848           && operand_equal_p (this_size, TYPE_SIZE (type), 0))
849         DECL_BIT_FIELD (field) = 0;
850
851       /* If we still have DECL_BIT_FIELD set at this point, we know the field
852          is technically not addressable.  Except that it can actually be
853          addressed if the field is BLKmode and happens to be properly
854          aligned.  */
855       DECL_NONADDRESSABLE_P (field)
856         |= DECL_BIT_FIELD (field) && DECL_MODE (field) != BLKmode;
857
858       if (has_rep && !DECL_BIT_FIELD (field))
859         TYPE_ALIGN (record_type)
860           = MAX (TYPE_ALIGN (record_type), DECL_ALIGN (field));
861
862       switch (code)
863         {
864         case UNION_TYPE:
865           ada_size = size_binop (MAX_EXPR, ada_size, this_ada_size);
866           size = size_binop (MAX_EXPR, size, this_size);
867           break;
868
869         case QUAL_UNION_TYPE:
870           ada_size
871             = fold (build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
872                             this_ada_size, ada_size));
873           size = fold (build3 (COND_EXPR, bitsizetype, DECL_QUALIFIER (field),
874                                this_size, size));
875           break;
876
877         case RECORD_TYPE:
878           /* Since we know here that all fields are sorted in order of
879              increasing bit position, the size of the record is one
880              higher than the ending bit of the last field processed
881              unless we have a rep clause, since in that case we might
882              have a field outside a QUAL_UNION_TYPE that has a higher ending
883              position.  So use a MAX in that case.  Also, if this field is a
884              QUAL_UNION_TYPE, we need to take into account the previous size in
885              the case of empty variants.  */
886           ada_size
887             = merge_sizes (ada_size, pos, this_ada_size,
888                            TREE_CODE (type) == QUAL_UNION_TYPE, has_rep);
889           size = merge_sizes (size, pos, this_size,
890                               TREE_CODE (type) == QUAL_UNION_TYPE, has_rep);
891           break;
892
893         default:
894           gcc_unreachable ();
895         }
896     }
897
898   if (code == QUAL_UNION_TYPE)
899     nreverse (fieldlist);
900
901   /* If this is a padding record, we never want to make the size smaller than
902      what was specified in it, if any.  */
903   if (TREE_CODE (record_type) == RECORD_TYPE
904       && TYPE_IS_PADDING_P (record_type) && TYPE_SIZE (record_type))
905     size = TYPE_SIZE (record_type);
906
907   /* Now set any of the values we've just computed that apply.  */
908   if (!TYPE_IS_FAT_POINTER_P (record_type)
909       && !TYPE_CONTAINS_TEMPLATE_P (record_type))
910     SET_TYPE_ADA_SIZE (record_type, ada_size);
911
912   if (has_rep)
913     {
914       tree size_unit
915         = (had_size_unit ? TYPE_SIZE_UNIT (record_type)
916            : convert (sizetype, size_binop (CEIL_DIV_EXPR, size,
917                                             bitsize_unit_node)));
918
919       TYPE_SIZE (record_type)
920         = variable_size (round_up (size, TYPE_ALIGN (record_type)));
921       TYPE_SIZE_UNIT (record_type)
922         = variable_size (round_up (size_unit,
923                                    TYPE_ALIGN (record_type) / BITS_PER_UNIT));
924
925       compute_record_mode (record_type);
926     }
927
928   if (!defer_debug)
929     write_record_type_debug_info (record_type);
930 }
931
932 /* Output the debug information associated to a record type.  */
933
934 void
935 write_record_type_debug_info (tree record_type)
936 {
937   tree fieldlist = TYPE_FIELDS (record_type);
938   tree field;
939   bool var_size = false;
940
941   for (field = fieldlist; field; field = TREE_CHAIN (field))
942     {
943       /* We need to make an XVE/XVU record if any field has variable size,
944          whether or not the record does.  For example, if we have a union,
945          it may be that all fields, rounded up to the alignment, have the
946          same size, in which case we'll use that size.  But the debug
947          output routines (except Dwarf2) won't be able to output the fields,
948          so we need to make the special record.  */
949       if (TREE_CODE (DECL_SIZE (field)) != INTEGER_CST)
950         {
951           var_size = true;
952           break;
953         }
954     }
955
956   /* If this record is of variable size, rename it so that the
957      debugger knows it is and make a new, parallel, record
958      that tells the debugger how the record is laid out.  See
959      exp_dbug.ads.  But don't do this for records that are padding
960      since they confuse GDB.  */
961   if (var_size
962       && !(TREE_CODE (record_type) == RECORD_TYPE
963            && TYPE_IS_PADDING_P (record_type)))
964     {
965       tree new_record_type
966         = make_node (TREE_CODE (record_type) == QUAL_UNION_TYPE
967                      ? UNION_TYPE : TREE_CODE (record_type));
968       tree orig_name = TYPE_NAME (record_type);
969       tree orig_id
970         = (TREE_CODE (orig_name) == TYPE_DECL ? DECL_NAME (orig_name)
971            : orig_name);
972       tree new_id
973         = concat_id_with_name (orig_id,
974                                TREE_CODE (record_type) == QUAL_UNION_TYPE
975                                ? "XVU" : "XVE");
976       tree last_pos = bitsize_zero_node;
977       tree old_field;
978       tree prev_old_field = 0;
979
980       TYPE_NAME (new_record_type) = new_id;
981       TYPE_ALIGN (new_record_type) = BIGGEST_ALIGNMENT;
982       TYPE_STUB_DECL (new_record_type)
983         = build_decl (TYPE_DECL, NULL_TREE, new_record_type);
984       DECL_ARTIFICIAL (TYPE_STUB_DECL (new_record_type)) = 1;
985       DECL_IGNORED_P (TYPE_STUB_DECL (new_record_type))
986         = DECL_IGNORED_P (TYPE_STUB_DECL (record_type));
987       TYPE_SIZE (new_record_type) = size_int (TYPE_ALIGN (record_type));
988       TYPE_SIZE_UNIT (new_record_type)
989         = size_int (TYPE_ALIGN (record_type) / BITS_PER_UNIT);
990
991       /* Now scan all the fields, replacing each field with a new
992          field corresponding to the new encoding.  */
993       for (old_field = TYPE_FIELDS (record_type); old_field;
994            old_field = TREE_CHAIN (old_field))
995         {
996           tree field_type = TREE_TYPE (old_field);
997           tree field_name = DECL_NAME (old_field);
998           tree new_field;
999           tree curpos = bit_position (old_field);
1000           bool var = false;
1001           unsigned int align = 0;
1002           tree pos;
1003
1004           /* See how the position was modified from the last position.
1005
1006           There are two basic cases we support: a value was added
1007           to the last position or the last position was rounded to
1008           a boundary and they something was added.  Check for the
1009           first case first.  If not, see if there is any evidence
1010           of rounding.  If so, round the last position and try
1011           again.
1012
1013           If this is a union, the position can be taken as zero. */
1014
1015           if (TREE_CODE (new_record_type) == UNION_TYPE)
1016             pos = bitsize_zero_node, align = 0;
1017           else
1018             pos = compute_related_constant (curpos, last_pos);
1019
1020           if (!pos && TREE_CODE (curpos) == MULT_EXPR
1021               && TREE_CODE (TREE_OPERAND (curpos, 1)) == INTEGER_CST)
1022             {
1023               align = TREE_INT_CST_LOW (TREE_OPERAND (curpos, 1));
1024               pos = compute_related_constant (curpos,
1025                                               round_up (last_pos, align));
1026             }
1027           else if (!pos && TREE_CODE (curpos) == PLUS_EXPR
1028                    && TREE_CODE (TREE_OPERAND (curpos, 1)) == INTEGER_CST
1029                    && TREE_CODE (TREE_OPERAND (curpos, 0)) == MULT_EXPR
1030                    && host_integerp (TREE_OPERAND
1031                                      (TREE_OPERAND (curpos, 0), 1),
1032                                      1))
1033             {
1034               align
1035                 = tree_low_cst
1036                 (TREE_OPERAND (TREE_OPERAND (curpos, 0), 1), 1);
1037               pos = compute_related_constant (curpos,
1038                                               round_up (last_pos, align));
1039             }
1040           else if (potential_alignment_gap (prev_old_field, old_field,
1041                                             pos))
1042             {
1043               align = TYPE_ALIGN (field_type);
1044               pos = compute_related_constant (curpos,
1045                                               round_up (last_pos, align));
1046             }
1047
1048           /* If we can't compute a position, set it to zero.
1049
1050           ??? We really should abort here, but it's too much work
1051           to get this correct for all cases.  */
1052
1053           if (!pos)
1054             pos = bitsize_zero_node;
1055
1056           /* See if this type is variable-size and make a new type
1057              and indicate the indirection if so.  */
1058           if (TREE_CODE (DECL_SIZE (old_field)) != INTEGER_CST)
1059             {
1060               field_type = build_pointer_type (field_type);
1061               var = true;
1062             }
1063
1064           /* The heuristics above might get the alignment wrong.
1065              Adjust the obvious case where align is smaller than the
1066              alignments necessary for objects of field_type. */
1067           if (align < TYPE_ALIGN(field_type))
1068             align = TYPE_ALIGN(field_type);
1069
1070           /* Make a new field name, if necessary.  */
1071           if (var || align != 0)
1072             {
1073               char suffix[6];
1074
1075               if (align != 0)
1076                 sprintf (suffix, "XV%c%u", var ? 'L' : 'A',
1077                          align / BITS_PER_UNIT);
1078               else
1079                 strcpy (suffix, "XVL");
1080
1081               field_name = concat_id_with_name (field_name, suffix);
1082             }
1083
1084           new_field = create_field_decl (field_name, field_type,
1085                                          new_record_type, 0,
1086                                          DECL_SIZE (old_field), pos, 0);
1087           TREE_CHAIN (new_field) = TYPE_FIELDS (new_record_type);
1088           TYPE_FIELDS (new_record_type) = new_field;
1089
1090           /* If old_field is a QUAL_UNION_TYPE, take its size as being
1091              zero.  The only time it's not the last field of the record
1092              is when there are other components at fixed positions after
1093              it (meaning there was a rep clause for every field) and we
1094              want to be able to encode them.  */
1095           last_pos = size_binop (PLUS_EXPR, bit_position (old_field),
1096                                  (TREE_CODE (TREE_TYPE (old_field))
1097                                   == QUAL_UNION_TYPE)
1098                                  ? bitsize_zero_node
1099                                  : DECL_SIZE (old_field));
1100           prev_old_field = old_field;
1101         }
1102
1103       TYPE_FIELDS (new_record_type)
1104         = nreverse (TYPE_FIELDS (new_record_type));
1105
1106       rest_of_type_compilation (new_record_type, global_bindings_p ());
1107     }
1108
1109   rest_of_type_compilation (record_type, global_bindings_p ());
1110 }
1111
1112 /* Utility function of above to merge LAST_SIZE, the previous size of a record
1113    with FIRST_BIT and SIZE that describe a field.  SPECIAL is nonzero
1114    if this represents a QUAL_UNION_TYPE in which case we must look for
1115    COND_EXPRs and replace a value of zero with the old size.  If HAS_REP
1116    is nonzero, we must take the MAX of the end position of this field
1117    with LAST_SIZE.  In all other cases, we use FIRST_BIT plus SIZE.
1118
1119    We return an expression for the size.  */
1120
1121 static tree
1122 merge_sizes (tree last_size, tree first_bit, tree size, bool special,
1123              bool has_rep)
1124 {
1125   tree type = TREE_TYPE (last_size);
1126   tree new;
1127
1128   if (!special || TREE_CODE (size) != COND_EXPR)
1129     {
1130       new = size_binop (PLUS_EXPR, first_bit, size);
1131       if (has_rep)
1132         new = size_binop (MAX_EXPR, last_size, new);
1133     }
1134
1135   else
1136     new = fold (build3 (COND_EXPR, type, TREE_OPERAND (size, 0),
1137                         integer_zerop (TREE_OPERAND (size, 1))
1138                         ? last_size : merge_sizes (last_size, first_bit,
1139                                                    TREE_OPERAND (size, 1),
1140                                                    1, has_rep),
1141                         integer_zerop (TREE_OPERAND (size, 2))
1142                         ? last_size : merge_sizes (last_size, first_bit,
1143                                                    TREE_OPERAND (size, 2),
1144                                                    1, has_rep)));
1145
1146   /* We don't need any NON_VALUE_EXPRs and they can confuse us (especially
1147      when fed through substitute_in_expr) into thinking that a constant
1148      size is not constant.  */
1149   while (TREE_CODE (new) == NON_LVALUE_EXPR)
1150     new = TREE_OPERAND (new, 0);
1151
1152   return new;
1153 }
1154
1155 /* Utility function of above to see if OP0 and OP1, both of SIZETYPE, are
1156    related by the addition of a constant.  Return that constant if so.  */
1157
1158 static tree
1159 compute_related_constant (tree op0, tree op1)
1160 {
1161   tree op0_var, op1_var;
1162   tree op0_con = split_plus (op0, &op0_var);
1163   tree op1_con = split_plus (op1, &op1_var);
1164   tree result = size_binop (MINUS_EXPR, op0_con, op1_con);
1165
1166   if (operand_equal_p (op0_var, op1_var, 0))
1167     return result;
1168   else if (operand_equal_p (op0, size_binop (PLUS_EXPR, op1_var, result), 0))
1169     return result;
1170   else
1171     return 0;
1172 }
1173
1174 /* Utility function of above to split a tree OP which may be a sum, into a
1175    constant part, which is returned, and a variable part, which is stored
1176    in *PVAR.  *PVAR may be bitsize_zero_node.  All operations must be of
1177    bitsizetype.  */
1178
1179 static tree
1180 split_plus (tree in, tree *pvar)
1181 {
1182   /* Strip NOPS in order to ease the tree traversal and maximize the
1183      potential for constant or plus/minus discovery. We need to be careful
1184      to always return and set *pvar to bitsizetype trees, but it's worth
1185      the effort.  */
1186   STRIP_NOPS (in);
1187
1188   *pvar = convert (bitsizetype, in);
1189
1190   if (TREE_CODE (in) == INTEGER_CST)
1191     {
1192       *pvar = bitsize_zero_node;
1193       return convert (bitsizetype, in);
1194     }
1195   else if (TREE_CODE (in) == PLUS_EXPR || TREE_CODE (in) == MINUS_EXPR)
1196     {
1197       tree lhs_var, rhs_var;
1198       tree lhs_con = split_plus (TREE_OPERAND (in, 0), &lhs_var);
1199       tree rhs_con = split_plus (TREE_OPERAND (in, 1), &rhs_var);
1200
1201       if (lhs_var == TREE_OPERAND (in, 0)
1202           && rhs_var == TREE_OPERAND (in, 1))
1203         return bitsize_zero_node;
1204
1205       *pvar = size_binop (TREE_CODE (in), lhs_var, rhs_var);
1206       return size_binop (TREE_CODE (in), lhs_con, rhs_con);
1207     }
1208   else
1209     return bitsize_zero_node;
1210 }
1211 \f
1212 /* Return a FUNCTION_TYPE node. RETURN_TYPE is the type returned by the
1213    subprogram. If it is void_type_node, then we are dealing with a procedure,
1214    otherwise we are dealing with a function. PARAM_DECL_LIST is a list of
1215    PARM_DECL nodes that are the subprogram arguments.  CICO_LIST is the
1216    copy-in/copy-out list to be stored into TYPE_CICO_LIST.
1217    RETURNS_UNCONSTRAINED is nonzero if the function returns an unconstrained
1218    object.  RETURNS_BY_REF is nonzero if the function returns by reference.
1219    RETURNS_WITH_DSP is nonzero if the function is to return with a
1220    depressed stack pointer.  RETURNS_BY_TARGET_PTR is true if the function
1221    is to be passed (as its first parameter) the address of the place to copy
1222    its result.  */
1223
1224 tree
1225 create_subprog_type (tree return_type, tree param_decl_list, tree cico_list,
1226                      bool returns_unconstrained, bool returns_by_ref,
1227                      bool returns_with_dsp, bool returns_by_target_ptr)
1228 {
1229   /* A chain of TREE_LIST nodes whose TREE_VALUEs are the data type nodes of
1230      the subprogram formal parameters. This list is generated by traversing the
1231      input list of PARM_DECL nodes.  */
1232   tree param_type_list = NULL;
1233   tree param_decl;
1234   tree type;
1235
1236   for (param_decl = param_decl_list; param_decl;
1237        param_decl = TREE_CHAIN (param_decl))
1238     param_type_list = tree_cons (NULL_TREE, TREE_TYPE (param_decl),
1239                                  param_type_list);
1240
1241   /* The list of the function parameter types has to be terminated by the void
1242      type to signal to the back-end that we are not dealing with a variable
1243      parameter subprogram, but that the subprogram has a fixed number of
1244      parameters.  */
1245   param_type_list = tree_cons (NULL_TREE, void_type_node, param_type_list);
1246
1247   /* The list of argument types has been created in reverse
1248      so nreverse it.   */
1249   param_type_list = nreverse (param_type_list);
1250
1251   type = build_function_type (return_type, param_type_list);
1252
1253   /* TYPE may have been shared since GCC hashes types.  If it has a CICO_LIST
1254      or the new type should, make a copy of TYPE.  Likewise for
1255      RETURNS_UNCONSTRAINED and RETURNS_BY_REF.  */
1256   if (TYPE_CI_CO_LIST (type) || cico_list
1257       || TYPE_RETURNS_UNCONSTRAINED_P (type) != returns_unconstrained
1258       || TYPE_RETURNS_BY_REF_P (type) != returns_by_ref
1259       || TYPE_RETURNS_BY_TARGET_PTR_P (type) != returns_by_target_ptr)
1260     type = copy_type (type);
1261
1262   TYPE_CI_CO_LIST (type) = cico_list;
1263   TYPE_RETURNS_UNCONSTRAINED_P (type) = returns_unconstrained;
1264   TYPE_RETURNS_STACK_DEPRESSED (type) = returns_with_dsp;
1265   TYPE_RETURNS_BY_REF_P (type) = returns_by_ref;
1266   TYPE_RETURNS_BY_TARGET_PTR_P (type) = returns_by_target_ptr;
1267   return type;
1268 }
1269 \f
1270 /* Return a copy of TYPE but safe to modify in any way.  */
1271
1272 tree
1273 copy_type (tree type)
1274 {
1275   tree new = copy_node (type);
1276
1277   /* copy_node clears this field instead of copying it, because it is
1278      aliased with TREE_CHAIN.  */
1279   TYPE_STUB_DECL (new) = TYPE_STUB_DECL (type);
1280
1281   TYPE_POINTER_TO (new) = 0;
1282   TYPE_REFERENCE_TO (new) = 0;
1283   TYPE_MAIN_VARIANT (new) = new;
1284   TYPE_NEXT_VARIANT (new) = 0;
1285
1286   return new;
1287 }
1288 \f
1289 /* Return an INTEGER_TYPE of SIZETYPE with range MIN to MAX and whose
1290    TYPE_INDEX_TYPE is INDEX.  */
1291
1292 tree
1293 create_index_type (tree min, tree max, tree index)
1294 {
1295   /* First build a type for the desired range.  */
1296   tree type = build_index_2_type (min, max);
1297
1298   /* If this type has the TYPE_INDEX_TYPE we want, return it.  Otherwise, if it
1299      doesn't have TYPE_INDEX_TYPE set, set it to INDEX.  If TYPE_INDEX_TYPE
1300      is set, but not to INDEX, make a copy of this type with the requested
1301      index type.  Note that we have no way of sharing these types, but that's
1302      only a small hole.  */
1303   if (TYPE_INDEX_TYPE (type) == index)
1304     return type;
1305   else if (TYPE_INDEX_TYPE (type))
1306     type = copy_type (type);
1307
1308   SET_TYPE_INDEX_TYPE (type, index);
1309   create_type_decl (NULL_TREE, type, NULL, true, false, Empty);
1310   return type;
1311 }
1312 \f
1313 /* Return a TYPE_DECL node. TYPE_NAME gives the name of the type (a character
1314    string) and TYPE is a ..._TYPE node giving its data type.
1315    ARTIFICIAL_P is true if this is a declaration that was generated
1316    by the compiler.  DEBUG_INFO_P is true if we need to write debugging
1317    information about this type.  GNAT_NODE is used for the position of
1318    the decl.  */
1319
1320 tree
1321 create_type_decl (tree type_name, tree type, struct attrib *attr_list,
1322                   bool artificial_p, bool debug_info_p, Node_Id gnat_node)
1323 {
1324   tree type_decl = build_decl (TYPE_DECL, type_name, type);
1325   enum tree_code code = TREE_CODE (type);
1326
1327   DECL_ARTIFICIAL (type_decl) = artificial_p;
1328
1329   if (!TYPE_IS_DUMMY_P (type))
1330     gnat_pushdecl (type_decl, gnat_node);
1331
1332   process_attributes (type_decl, attr_list);
1333
1334   /* Pass type declaration information to the debugger unless this is an
1335      UNCONSTRAINED_ARRAY_TYPE, which the debugger does not support,
1336      and ENUMERAL_TYPE or RECORD_TYPE which is handled separately, or
1337      type for which debugging information was not requested.  */
1338   if (code == UNCONSTRAINED_ARRAY_TYPE || ! debug_info_p)
1339     DECL_IGNORED_P (type_decl) = 1;
1340   if (code == UNCONSTRAINED_ARRAY_TYPE || TYPE_IS_DUMMY_P (type)
1341       || !debug_info_p)
1342     DECL_IGNORED_P (type_decl) = 1;
1343   else if (code != ENUMERAL_TYPE && code != RECORD_TYPE
1344            && !((code == POINTER_TYPE || code == REFERENCE_TYPE)
1345                 && TYPE_IS_DUMMY_P (TREE_TYPE (type))))
1346     rest_of_decl_compilation (type_decl, global_bindings_p (), 0);
1347
1348   return type_decl;
1349 }
1350
1351 /* Helper for create_var_decl and create_true_var_decl. Returns a GCC VAR_DECL
1352    or CONST_DECL node.
1353
1354    VAR_NAME gives the name of the variable.  ASM_NAME is its assembler name
1355    (if provided).  TYPE is its data type (a GCC ..._TYPE node).  VAR_INIT is
1356    the GCC tree for an optional initial expression; NULL_TREE if none.
1357
1358    CONST_FLAG is true if this variable is constant, in which case we might
1359    return a CONST_DECL node unless CONST_DECL_ALLOWED_FLAG is false.
1360
1361    PUBLIC_FLAG is true if this definition is to be made visible outside of
1362    the current compilation unit. This flag should be set when processing the
1363    variable definitions in a package specification.  EXTERN_FLAG is nonzero
1364    when processing an external variable declaration (as opposed to a
1365    definition: no storage is to be allocated for the variable here).
1366
1367    STATIC_FLAG is only relevant when not at top level.  In that case
1368    it indicates whether to always allocate storage to the variable.
1369
1370    GNAT_NODE is used for the position of the decl.  */
1371
1372 static tree
1373 create_var_decl_1 (tree var_name, tree asm_name, tree type, tree var_init,
1374                    bool const_flag, bool const_decl_allowed_flag,
1375                    bool public_flag, bool extern_flag, bool static_flag,
1376                    struct attrib *attr_list, Node_Id gnat_node)
1377 {
1378   bool init_const
1379     = (!var_init
1380        ? false
1381        : (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (TREE_TYPE (var_init))
1382           && (global_bindings_p () || static_flag
1383               ? 0 != initializer_constant_valid_p (var_init,
1384                                                    TREE_TYPE (var_init))
1385               : TREE_CONSTANT (var_init))));
1386   tree var_decl
1387     = build_decl ((const_flag && const_decl_allowed_flag && init_const
1388                    /* Only make a CONST_DECL for sufficiently-small objects.
1389                       We consider complex double "sufficiently-small"  */
1390                    && TYPE_SIZE (type) != 0
1391                    && host_integerp (TYPE_SIZE_UNIT (type), 1)
1392                    && 0 >= compare_tree_int (TYPE_SIZE_UNIT (type),
1393                                              GET_MODE_SIZE (DCmode)))
1394                   ? CONST_DECL : VAR_DECL, var_name, type);
1395
1396   /* If this is external, throw away any initializations unless this is a
1397      CONST_DECL (meaning we have a constant); they will be done elsewhere.
1398      If we are defining a global here, leave a constant initialization and
1399      save any variable elaborations for the elaboration routine.  If we are
1400      just annotating types, throw away the initialization if it isn't a
1401      constant.  */
1402   if ((extern_flag && TREE_CODE (var_decl) != CONST_DECL)
1403       || (type_annotate_only && var_init && !TREE_CONSTANT (var_init)))
1404     var_init = NULL_TREE;
1405
1406   /* At the global level, an initializer requiring code to be generated
1407      produces elaboration statements.  Check that such statements are allowed,
1408      that is, not violating a No_Elaboration_Code restriction.  */
1409   if (global_bindings_p () && var_init != 0 && ! init_const)
1410     Check_Elaboration_Code_Allowed (gnat_node);
1411
1412   /* Ada doesn't feature Fortran-like COMMON variables so we shouldn't
1413      try to fiddle with DECL_COMMON.  However, on platforms that don't
1414      support global BSS sections, uninitialized global variables would
1415      go in DATA instead, thus increasing the size of the executable.  */
1416   if (!flag_no_common
1417       && TREE_CODE (var_decl) == VAR_DECL
1418       && !have_global_bss_p ())
1419     DECL_COMMON (var_decl) = 1;
1420   DECL_INITIAL  (var_decl) = var_init;
1421   TREE_READONLY (var_decl) = const_flag;
1422   DECL_EXTERNAL (var_decl) = extern_flag;
1423   TREE_PUBLIC   (var_decl) = public_flag || extern_flag;
1424   TREE_CONSTANT (var_decl) = TREE_CODE (var_decl) == CONST_DECL;
1425   TREE_THIS_VOLATILE (var_decl) = TREE_SIDE_EFFECTS (var_decl)
1426     = TYPE_VOLATILE (type);
1427
1428   /* If it's public and not external, always allocate storage for it.
1429      At the global binding level we need to allocate static storage for the
1430      variable if and only if it's not external. If we are not at the top level
1431      we allocate automatic storage unless requested not to.  */
1432   TREE_STATIC (var_decl)
1433     = public_flag || (global_bindings_p () ? !extern_flag : static_flag);
1434
1435   if (asm_name && VAR_OR_FUNCTION_DECL_P (var_decl))
1436     SET_DECL_ASSEMBLER_NAME (var_decl, asm_name);
1437
1438   process_attributes (var_decl, attr_list);
1439
1440   /* Add this decl to the current binding level.  */
1441   gnat_pushdecl (var_decl, gnat_node);
1442
1443   if (TREE_SIDE_EFFECTS (var_decl))
1444     TREE_ADDRESSABLE (var_decl) = 1;
1445
1446   if (TREE_CODE (var_decl) != CONST_DECL)
1447     rest_of_decl_compilation (var_decl, global_bindings_p (), 0);
1448   else
1449     /* expand CONST_DECLs to set their MODE, ALIGN, SIZE and SIZE_UNIT,
1450        which we need for later back-annotations.  */
1451     expand_decl (var_decl);
1452
1453   return var_decl;
1454 }
1455
1456 /* Wrapper around create_var_decl_1 for cases where we don't care whether
1457    a VAR or a CONST decl node is created.  */
1458
1459 tree
1460 create_var_decl (tree var_name, tree asm_name, tree type, tree var_init,
1461                  bool const_flag, bool public_flag, bool extern_flag,
1462                  bool static_flag, struct attrib *attr_list,
1463                  Node_Id gnat_node)
1464 {
1465   return create_var_decl_1 (var_name, asm_name, type, var_init,
1466                             const_flag, true,
1467                             public_flag, extern_flag, static_flag,
1468                             attr_list, gnat_node);
1469 }
1470
1471 /* Wrapper around create_var_decl_1 for cases where a VAR_DECL node is
1472    required.  The primary intent is for DECL_CONST_CORRESPONDING_VARs, which
1473    must be VAR_DECLs and on which we want TREE_READONLY set to have them
1474    possibly assigned to a readonly data section.  */
1475
1476 tree
1477 create_true_var_decl (tree var_name, tree asm_name, tree type, tree var_init,
1478                       bool const_flag, bool public_flag, bool extern_flag,
1479                       bool static_flag, struct attrib *attr_list,
1480                       Node_Id gnat_node)
1481 {
1482   return create_var_decl_1 (var_name, asm_name, type, var_init,
1483                             const_flag, false,
1484                             public_flag, extern_flag, static_flag,
1485                             attr_list, gnat_node);
1486 }
1487 \f
1488 /* Returns a FIELD_DECL node. FIELD_NAME the field name, FIELD_TYPE is its
1489    type, and RECORD_TYPE is the type of the parent.  PACKED is nonzero if
1490    this field is in a record type with a "pragma pack".  If SIZE is nonzero
1491    it is the specified size for this field.  If POS is nonzero, it is the bit
1492    position.  If ADDRESSABLE is nonzero, it means we are allowed to take
1493    the address of this field for aliasing purposes. If it is negative, we
1494    should not make a bitfield, which is used by make_aligning_type.   */
1495
1496 tree
1497 create_field_decl (tree field_name, tree field_type, tree record_type,
1498                    int packed, tree size, tree pos, int addressable)
1499 {
1500   tree field_decl = build_decl (FIELD_DECL, field_name, field_type);
1501
1502   DECL_CONTEXT (field_decl) = record_type;
1503   TREE_READONLY (field_decl) = TYPE_READONLY (field_type);
1504
1505   /* If FIELD_TYPE is BLKmode, we must ensure this is aligned to at least a
1506      byte boundary since GCC cannot handle less-aligned BLKmode bitfields.  */
1507   if (packed && TYPE_MODE (field_type) == BLKmode)
1508     DECL_ALIGN (field_decl) = BITS_PER_UNIT;
1509
1510   /* If a size is specified, use it.  Otherwise, if the record type is packed
1511      compute a size to use, which may differ from the object's natural size.
1512      We always set a size in this case to trigger the checks for bitfield
1513      creation below, which is typically required when no position has been
1514      specified.  */
1515   if (size)
1516     size = convert (bitsizetype, size);
1517   else if (packed == 1)
1518     {
1519       size = rm_size (field_type);
1520
1521       /* For a constant size larger than MAX_FIXED_MODE_SIZE, round up to
1522          byte.  */
1523       if (TREE_CODE (size) == INTEGER_CST
1524           && compare_tree_int (size, MAX_FIXED_MODE_SIZE) > 0)
1525         size = round_up (size, BITS_PER_UNIT);
1526     }
1527
1528   /* If we may, according to ADDRESSABLE, make a bitfield if a size is
1529      specified for two reasons: first if the size differs from the natural
1530      size.  Second, if the alignment is insufficient.  There are a number of
1531      ways the latter can be true.
1532
1533      We never make a bitfield if the type of the field has a nonconstant size,
1534      because no such entity requiring bitfield operations should reach here.
1535
1536      We do *preventively* make a bitfield when there might be the need for it
1537      but we don't have all the necessary information to decide, as is the case
1538      of a field with no specified position in a packed record.
1539
1540      We also don't look at STRICT_ALIGNMENT here, and rely on later processing
1541      in layout_decl or finish_record_type to clear the bit_field indication if
1542      it is in fact not needed.  */
1543   if (addressable >= 0
1544       && size
1545       && TREE_CODE (size) == INTEGER_CST
1546       && TREE_CODE (TYPE_SIZE (field_type)) == INTEGER_CST
1547       && (!operand_equal_p (TYPE_SIZE (field_type), size, 0)
1548           || (pos && !value_factor_p (pos, TYPE_ALIGN (field_type)))
1549           || packed
1550           || (TYPE_ALIGN (record_type) != 0
1551               && TYPE_ALIGN (record_type) < TYPE_ALIGN (field_type))))
1552     {
1553       DECL_BIT_FIELD (field_decl) = 1;
1554       DECL_SIZE (field_decl) = size;
1555       if (!packed && !pos)
1556         DECL_ALIGN (field_decl)
1557           = (TYPE_ALIGN (record_type) != 0
1558              ? MIN (TYPE_ALIGN (record_type), TYPE_ALIGN (field_type))
1559              : TYPE_ALIGN (field_type));
1560     }
1561
1562   DECL_PACKED (field_decl) = pos ? DECL_BIT_FIELD (field_decl) : packed;
1563   DECL_ALIGN (field_decl)
1564     = MAX (DECL_ALIGN (field_decl),
1565            DECL_BIT_FIELD (field_decl) ? 1
1566            : packed && TYPE_MODE (field_type) != BLKmode ? BITS_PER_UNIT
1567            : TYPE_ALIGN (field_type));
1568
1569   if (pos)
1570     {
1571       /* We need to pass in the alignment the DECL is known to have.
1572          This is the lowest-order bit set in POS, but no more than
1573          the alignment of the record, if one is specified.  Note
1574          that an alignment of 0 is taken as infinite.  */
1575       unsigned int known_align;
1576
1577       if (host_integerp (pos, 1))
1578         known_align = tree_low_cst (pos, 1) & - tree_low_cst (pos, 1);
1579       else
1580         known_align = BITS_PER_UNIT;
1581
1582       if (TYPE_ALIGN (record_type)
1583           && (known_align == 0 || known_align > TYPE_ALIGN (record_type)))
1584         known_align = TYPE_ALIGN (record_type);
1585
1586       layout_decl (field_decl, known_align);
1587       SET_DECL_OFFSET_ALIGN (field_decl,
1588                              host_integerp (pos, 1) ? BIGGEST_ALIGNMENT
1589                              : BITS_PER_UNIT);
1590       pos_from_bit (&DECL_FIELD_OFFSET (field_decl),
1591                     &DECL_FIELD_BIT_OFFSET (field_decl),
1592                     DECL_OFFSET_ALIGN (field_decl), pos);
1593
1594       DECL_HAS_REP_P (field_decl) = 1;
1595     }
1596
1597   /* If the field type is passed by reference, we will have pointers to the
1598      field, so it is addressable. */
1599   if (must_pass_by_ref (field_type) || default_pass_by_ref (field_type))
1600     addressable = 1;
1601
1602   /* Mark the decl as nonaddressable if it is indicated so semantically,
1603      meaning we won't ever attempt to take the address of the field.
1604
1605      It may also be "technically" nonaddressable, meaning that even if we
1606      attempt to take the field's address we will actually get the address of a
1607      copy. This is the case for true bitfields, but the DECL_BIT_FIELD value
1608      we have at this point is not accurate enough, so we don't account for
1609      this here and let finish_record_type decide.  */
1610   DECL_NONADDRESSABLE_P (field_decl) = !addressable;
1611
1612   return field_decl;
1613 }
1614
1615 /* Subroutine of previous function: return nonzero if EXP, ignoring any side
1616    effects, has the value of zero.  */
1617
1618 static bool
1619 value_zerop (tree exp)
1620 {
1621   if (TREE_CODE (exp) == COMPOUND_EXPR)
1622     return value_zerop (TREE_OPERAND (exp, 1));
1623
1624   return integer_zerop (exp);
1625 }
1626 \f
1627 /* Returns a PARM_DECL node. PARAM_NAME is the name of the parameter,
1628    PARAM_TYPE is its type.  READONLY is true if the parameter is
1629    readonly (either an IN parameter or an address of a pass-by-ref
1630    parameter). */
1631
1632 tree
1633 create_param_decl (tree param_name, tree param_type, bool readonly)
1634 {
1635   tree param_decl = build_decl (PARM_DECL, param_name, param_type);
1636
1637   /* Honor targetm.calls.promote_prototypes(), as not doing so can
1638      lead to various ABI violations.  */
1639   if (targetm.calls.promote_prototypes (param_type)
1640       && (TREE_CODE (param_type) == INTEGER_TYPE
1641           || TREE_CODE (param_type) == ENUMERAL_TYPE)
1642       && TYPE_PRECISION (param_type) < TYPE_PRECISION (integer_type_node))
1643     {
1644       /* We have to be careful about biased types here.  Make a subtype
1645          of integer_type_node with the proper biasing.  */
1646       if (TREE_CODE (param_type) == INTEGER_TYPE
1647           && TYPE_BIASED_REPRESENTATION_P (param_type))
1648         {
1649           param_type
1650             = copy_type (build_range_type (integer_type_node,
1651                                            TYPE_MIN_VALUE (param_type),
1652                                            TYPE_MAX_VALUE (param_type)));
1653
1654           TYPE_BIASED_REPRESENTATION_P (param_type) = 1;
1655         }
1656       else
1657         param_type = integer_type_node;
1658     }
1659
1660   DECL_ARG_TYPE (param_decl) = param_type;
1661   TREE_READONLY (param_decl) = readonly;
1662   return param_decl;
1663 }
1664 \f
1665 /* Given a DECL and ATTR_LIST, process the listed attributes.  */
1666
1667 void
1668 process_attributes (tree decl, struct attrib *attr_list)
1669 {
1670   for (; attr_list; attr_list = attr_list->next)
1671     switch (attr_list->type)
1672       {
1673       case ATTR_MACHINE_ATTRIBUTE:
1674         decl_attributes (&decl, tree_cons (attr_list->name, attr_list->args,
1675                                            NULL_TREE),
1676                          ATTR_FLAG_TYPE_IN_PLACE);
1677         break;
1678
1679       case ATTR_LINK_ALIAS:
1680         if (! DECL_EXTERNAL (decl))
1681           {
1682             TREE_STATIC (decl) = 1;
1683             assemble_alias (decl, attr_list->name);
1684           }
1685         break;
1686
1687       case ATTR_WEAK_EXTERNAL:
1688         if (SUPPORTS_WEAK)
1689           declare_weak (decl);
1690         else
1691           post_error ("?weak declarations not supported on this target",
1692                       attr_list->error_point);
1693         break;
1694
1695       case ATTR_LINK_SECTION:
1696         if (targetm.have_named_sections)
1697           {
1698             DECL_SECTION_NAME (decl)
1699               = build_string (IDENTIFIER_LENGTH (attr_list->name),
1700                               IDENTIFIER_POINTER (attr_list->name));
1701             DECL_COMMON (decl) = 0;
1702           }
1703         else
1704           post_error ("?section attributes are not supported for this target",
1705                       attr_list->error_point);
1706         break;
1707
1708       case ATTR_LINK_CONSTRUCTOR:
1709         DECL_STATIC_CONSTRUCTOR (decl) = 1;
1710         TREE_USED (decl) = 1;
1711         break;
1712
1713       case ATTR_LINK_DESTRUCTOR:
1714         DECL_STATIC_DESTRUCTOR (decl) = 1;
1715         TREE_USED (decl) = 1;
1716         break;
1717       }
1718 }
1719 \f
1720 /* Record a global renaming pointer.  */
1721
1722 void
1723 record_global_renaming_pointer (tree decl)
1724 {
1725   gcc_assert (DECL_RENAMED_OBJECT (decl));
1726   VEC_safe_push (tree, gc, global_renaming_pointers, decl);
1727 }
1728
1729 /* Invalidate the global renaming pointers.   */
1730
1731 void
1732 invalidate_global_renaming_pointers (void)
1733 {
1734   unsigned int i;
1735   tree iter;
1736
1737   for (i = 0; VEC_iterate(tree, global_renaming_pointers, i, iter); i++)
1738     SET_DECL_RENAMED_OBJECT (iter, NULL_TREE);
1739
1740   VEC_free (tree, gc, global_renaming_pointers);
1741 }
1742
1743 /* Return true if VALUE is a known to be a multiple of FACTOR, which must be
1744    a power of 2. */
1745
1746 bool
1747 value_factor_p (tree value, HOST_WIDE_INT factor)
1748 {
1749   if (host_integerp (value, 1))
1750     return tree_low_cst (value, 1) % factor == 0;
1751
1752   if (TREE_CODE (value) == MULT_EXPR)
1753     return (value_factor_p (TREE_OPERAND (value, 0), factor)
1754             || value_factor_p (TREE_OPERAND (value, 1), factor));
1755
1756   return 0;
1757 }
1758
1759 /* Given 2 consecutive field decls PREV_FIELD and CURR_FIELD, return true
1760    unless we can prove these 2 fields are laid out in such a way that no gap
1761    exist between the end of PREV_FIELD and the beginning of CURR_FIELD.  OFFSET
1762    is the distance in bits between the end of PREV_FIELD and the starting
1763    position of CURR_FIELD. It is ignored if null. */
1764
1765 static bool
1766 potential_alignment_gap (tree prev_field, tree curr_field, tree offset)
1767 {
1768   /* If this is the first field of the record, there cannot be any gap */
1769   if (!prev_field)
1770     return false;
1771
1772   /* If the previous field is a union type, then return False: The only
1773      time when such a field is not the last field of the record is when
1774      there are other components at fixed positions after it (meaning there
1775      was a rep clause for every field), in which case we don't want the
1776      alignment constraint to override them. */
1777   if (TREE_CODE (TREE_TYPE (prev_field)) == QUAL_UNION_TYPE)
1778     return false;
1779
1780   /* If the distance between the end of prev_field and the beginning of
1781      curr_field is constant, then there is a gap if the value of this
1782      constant is not null. */
1783   if (offset && host_integerp (offset, 1))
1784     return !integer_zerop (offset);
1785
1786   /* If the size and position of the previous field are constant,
1787      then check the sum of this size and position. There will be a gap
1788      iff it is not multiple of the current field alignment. */
1789   if (host_integerp (DECL_SIZE (prev_field), 1)
1790       && host_integerp (bit_position (prev_field), 1))
1791     return ((tree_low_cst (bit_position (prev_field), 1)
1792              + tree_low_cst (DECL_SIZE (prev_field), 1))
1793             % DECL_ALIGN (curr_field) != 0);
1794
1795   /* If both the position and size of the previous field are multiples
1796      of the current field alignment, there cannot be any gap. */
1797   if (value_factor_p (bit_position (prev_field), DECL_ALIGN (curr_field))
1798       && value_factor_p (DECL_SIZE (prev_field), DECL_ALIGN (curr_field)))
1799     return false;
1800
1801   /* Fallback, return that there may be a potential gap */
1802   return true;
1803 }
1804
1805 /* Returns a LABEL_DECL node for LABEL_NAME.  */
1806
1807 tree
1808 create_label_decl (tree label_name)
1809 {
1810   tree label_decl = build_decl (LABEL_DECL, label_name, void_type_node);
1811
1812   DECL_CONTEXT (label_decl)     = current_function_decl;
1813   DECL_MODE (label_decl)        = VOIDmode;
1814   DECL_SOURCE_LOCATION (label_decl) = input_location;
1815
1816   return label_decl;
1817 }
1818 \f
1819 /* Returns a FUNCTION_DECL node.  SUBPROG_NAME is the name of the subprogram,
1820    ASM_NAME is its assembler name, SUBPROG_TYPE is its type (a FUNCTION_TYPE
1821    node), PARAM_DECL_LIST is the list of the subprogram arguments (a list of
1822    PARM_DECL nodes chained through the TREE_CHAIN field).
1823
1824    INLINE_FLAG, PUBLIC_FLAG, EXTERN_FLAG, and ATTR_LIST are used to set the
1825    appropriate fields in the FUNCTION_DECL.  GNAT_NODE gives the location.  */
1826
1827 tree
1828 create_subprog_decl (tree subprog_name, tree asm_name,
1829                      tree subprog_type, tree param_decl_list, bool inline_flag,
1830                      bool public_flag, bool extern_flag,
1831                      struct attrib *attr_list, Node_Id gnat_node)
1832 {
1833   tree return_type  = TREE_TYPE (subprog_type);
1834   tree subprog_decl = build_decl (FUNCTION_DECL, subprog_name, subprog_type);
1835
1836   /* If this is a function nested inside an inlined external function, it
1837      means we aren't going to compile the outer function unless it is
1838      actually inlined, so do the same for us.  */
1839   if (current_function_decl && DECL_INLINE (current_function_decl)
1840       && DECL_EXTERNAL (current_function_decl))
1841     extern_flag = true;
1842
1843   DECL_EXTERNAL (subprog_decl)  = extern_flag;
1844   TREE_PUBLIC (subprog_decl)    = public_flag;
1845   TREE_STATIC (subprog_decl)    = 1;
1846   TREE_READONLY (subprog_decl)  = TYPE_READONLY (subprog_type);
1847   TREE_THIS_VOLATILE (subprog_decl) = TYPE_VOLATILE (subprog_type);
1848   TREE_SIDE_EFFECTS (subprog_decl) = TYPE_VOLATILE (subprog_type);
1849   DECL_ARGUMENTS (subprog_decl) = param_decl_list;
1850   DECL_RESULT (subprog_decl)    = build_decl (RESULT_DECL, 0, return_type);
1851   DECL_ARTIFICIAL (DECL_RESULT (subprog_decl)) = 1;
1852   DECL_IGNORED_P (DECL_RESULT (subprog_decl)) = 1;
1853
1854    /* TREE_ADDRESSABLE is set on the result type to request the use of the
1855       target by-reference return mechanism.  This is not supported all the
1856       way down to RTL expansion with GCC 4, which ICEs on temporary creation
1857       attempts with such a type and expects DECL_BY_REFERENCE to be set on
1858       the RESULT_DECL instead - see gnat_genericize for more details.  */
1859    if (TREE_ADDRESSABLE (TREE_TYPE (DECL_RESULT (subprog_decl))))
1860      {
1861        tree result_decl = DECL_RESULT (subprog_decl);
1862
1863        TREE_ADDRESSABLE (TREE_TYPE (result_decl)) = 0;
1864        DECL_BY_REFERENCE (result_decl) = 1;
1865      }
1866
1867   if (inline_flag)
1868     DECL_DECLARED_INLINE_P (subprog_decl) = 1;
1869
1870   if (asm_name)
1871     SET_DECL_ASSEMBLER_NAME (subprog_decl, asm_name);
1872
1873   process_attributes (subprog_decl, attr_list);
1874
1875   /* Add this decl to the current binding level.  */
1876   gnat_pushdecl (subprog_decl, gnat_node);
1877
1878   /* Output the assembler code and/or RTL for the declaration.  */
1879   rest_of_decl_compilation (subprog_decl, global_bindings_p (), 0);
1880
1881   return subprog_decl;
1882 }
1883 \f
1884 /* Set up the framework for generating code for SUBPROG_DECL, a subprogram
1885    body. This routine needs to be invoked before processing the declarations
1886    appearing in the subprogram.  */
1887
1888 void
1889 begin_subprog_body (tree subprog_decl)
1890 {
1891   tree param_decl;
1892
1893   current_function_decl = subprog_decl;
1894   announce_function (subprog_decl);
1895
1896   /* Enter a new binding level and show that all the parameters belong to
1897      this function.  */
1898   gnat_pushlevel ();
1899   for (param_decl = DECL_ARGUMENTS (subprog_decl); param_decl;
1900        param_decl = TREE_CHAIN (param_decl))
1901     DECL_CONTEXT (param_decl) = subprog_decl;
1902
1903   make_decl_rtl (subprog_decl);
1904
1905   /* We handle pending sizes via the elaboration of types, so we don't need to
1906      save them.  This causes them to be marked as part of the outer function
1907      and then discarded.  */
1908   get_pending_sizes ();
1909 }
1910
1911
1912 /* Helper for the genericization callback.  Return a dereference of VAL
1913    if it is of a reference type.  */
1914
1915 static tree
1916 convert_from_reference (tree val)
1917 {
1918   tree value_type, ref;
1919
1920   if (TREE_CODE (TREE_TYPE (val)) != REFERENCE_TYPE)
1921     return val;
1922
1923   value_type =  TREE_TYPE (TREE_TYPE (val));
1924   ref = build1 (INDIRECT_REF, value_type, val);
1925
1926   /* See if what we reference is CONST or VOLATILE, which requires
1927      looking into array types to get to the component type.  */
1928
1929   while (TREE_CODE (value_type) == ARRAY_TYPE)
1930     value_type = TREE_TYPE (value_type);
1931
1932   TREE_READONLY (ref)
1933     = (TYPE_QUALS (value_type) & TYPE_QUAL_CONST);
1934   TREE_THIS_VOLATILE (ref)
1935     = (TYPE_QUALS (value_type) & TYPE_QUAL_VOLATILE);
1936
1937   TREE_SIDE_EFFECTS (ref)
1938     = (TREE_THIS_VOLATILE (ref) || TREE_SIDE_EFFECTS (val));
1939
1940   return ref;
1941 }
1942
1943 /* Helper for the genericization callback.  Returns true if T denotes
1944    a RESULT_DECL with DECL_BY_REFERENCE set.  */
1945
1946 static inline bool
1947 is_byref_result (tree t)
1948 {
1949   return (TREE_CODE (t) == RESULT_DECL && DECL_BY_REFERENCE (t));
1950 }
1951
1952
1953 /* Tree walking callback for gnat_genericize. Currently ...
1954
1955    o Adjust references to the function's DECL_RESULT if it is marked
1956      DECL_BY_REFERENCE and so has had its type turned into a reference
1957      type at the end of the function compilation.  */
1958
1959 static tree
1960 gnat_genericize_r (tree *stmt_p, int *walk_subtrees, void *data)
1961 {
1962   /* This implementation is modeled after what the C++ front-end is
1963      doing, basis of the downstream passes behavior.  */
1964
1965   tree stmt = *stmt_p;
1966   struct pointer_set_t *p_set = (struct pointer_set_t*) data;
1967
1968   /* If we have a direct mention of the result decl, dereference.  */
1969   if (is_byref_result (stmt))
1970     {
1971       *stmt_p = convert_from_reference (stmt);
1972       *walk_subtrees = 0;
1973       return NULL;
1974     }
1975
1976   /* Otherwise, no need to walk the the same tree twice.  */
1977   if (pointer_set_contains (p_set, stmt))
1978     {
1979       *walk_subtrees = 0;
1980       return NULL_TREE;
1981     }
1982
1983   /* If we are taking the address of what now is a reference, just get the
1984      reference value.  */
1985   if (TREE_CODE (stmt) == ADDR_EXPR
1986       && is_byref_result (TREE_OPERAND (stmt, 0)))
1987     {
1988       *stmt_p = convert (TREE_TYPE (stmt), TREE_OPERAND (stmt, 0));
1989       *walk_subtrees = 0;
1990     }
1991
1992   /* Don't dereference an by-reference RESULT_DECL inside a RETURN_EXPR.  */
1993   else if (TREE_CODE (stmt) == RETURN_EXPR
1994            && TREE_OPERAND (stmt, 0)
1995            && is_byref_result (TREE_OPERAND (stmt, 0)))
1996     *walk_subtrees = 0;
1997
1998   /* Don't look inside trees that cannot embed references of interest.  */
1999   else if (IS_TYPE_OR_DECL_P (stmt))
2000     *walk_subtrees = 0;
2001
2002   pointer_set_insert (p_set, *stmt_p);
2003
2004   return NULL;
2005 }
2006
2007 /* Perform lowering of Ada trees to GENERIC. In particular:
2008
2009    o Turn a DECL_BY_REFERENCE RESULT_DECL into a real by-reference decl
2010      and adjust all the references to this decl accordingly.  */
2011
2012 static void
2013 gnat_genericize (tree fndecl)
2014 {
2015   /* Prior to GCC 4, an explicit By_Reference result mechanism for a function
2016      was handled by simply setting TREE_ADDRESSABLE on the result type.
2017      Everything required to actually pass by invisible ref using the target
2018      mechanism (e.g. extra parameter) was handled at RTL expansion time.
2019
2020      This doesn't work with GCC 4 any more for several reasons.  First, the
2021      gimplification process might need the creation of temporaries of this
2022      type, and the gimplifier ICEs on such attempts.  Second, the middle-end
2023      now relies on a different attribute for such cases (DECL_BY_REFERENCE on
2024      RESULT/PARM_DECLs), and expects the user invisible by-reference-ness to
2025      be explicitely accounted for by the front-end in the function body.
2026
2027      We achieve the complete transformation in two steps:
2028
2029      1/ create_subprog_decl performs early attribute tweaks: it clears
2030         TREE_ADDRESSABLE from the result type and sets DECL_BY_REFERENCE on
2031         the result decl.  The former ensures that the bit isn't set in the GCC
2032         tree saved for the function, so prevents ICEs on temporary creation.
2033         The latter we use here to trigger the rest of the processing.
2034
2035      2/ This function performs the type transformation on the result decl
2036         and adjusts all the references to this decl from the function body
2037         accordingly.
2038
2039      Clearing TREE_ADDRESSABLE from the type differs from the C++ front-end
2040      strategy, which escapes the gimplifier temporary creation issues by
2041      creating it's own temporaries using TARGET_EXPR nodes.  Our way relies
2042      on simple specific support code in aggregate_value_p to look at the
2043      target function result decl explicitely.  */
2044
2045   struct pointer_set_t *p_set;
2046   tree decl_result = DECL_RESULT (fndecl);
2047
2048   if (!DECL_BY_REFERENCE (decl_result))
2049     return;
2050
2051   /* Make the DECL_RESULT explicitely by-reference and adjust all the
2052      occurrences in the function body using the common tree-walking facility.
2053      We want to see every occurrence of the result decl to adjust the
2054      referencing tree, so need to use our own pointer set to control which
2055      trees should be visited again or not.  */
2056
2057   p_set = pointer_set_create ();
2058
2059   TREE_TYPE (decl_result) = build_reference_type (TREE_TYPE (decl_result));
2060   TREE_ADDRESSABLE (decl_result) = 0;
2061   relayout_decl (decl_result);
2062
2063   walk_tree (&DECL_SAVED_TREE (fndecl), gnat_genericize_r, p_set, NULL);
2064
2065   pointer_set_destroy (p_set);
2066 }
2067
2068 /* Finish the definition of the current subprogram and compile it all the way
2069    to assembler language output.  BODY is the tree corresponding to
2070    the subprogram.  */
2071
2072 void
2073 end_subprog_body (tree body)
2074 {
2075   tree fndecl = current_function_decl;
2076
2077   /* Mark the BLOCK for this level as being for this function and pop the
2078      level.  Since the vars in it are the parameters, clear them.  */
2079   BLOCK_VARS (current_binding_level->block) = 0;
2080   BLOCK_SUPERCONTEXT (current_binding_level->block) = fndecl;
2081   DECL_INITIAL (fndecl) = current_binding_level->block;
2082   gnat_poplevel ();
2083
2084   /* Deal with inline.  If declared inline or we should default to inline,
2085      set the flag in the decl.  */
2086   DECL_INLINE (fndecl)
2087     = DECL_DECLARED_INLINE_P (fndecl) || flag_inline_trees == 2;
2088
2089   /* We handle pending sizes via the elaboration of types, so we don't
2090      need to save them.  */
2091   get_pending_sizes ();
2092
2093   /* Mark the RESULT_DECL as being in this subprogram. */
2094   DECL_CONTEXT (DECL_RESULT (fndecl)) = fndecl;
2095
2096   DECL_SAVED_TREE (fndecl) = body;
2097
2098   current_function_decl = DECL_CONTEXT (fndecl);
2099   cfun = NULL;
2100
2101   /* If we're only annotating types, don't actually compile this function.  */
2102   if (type_annotate_only)
2103     return;
2104
2105   /* If we don't have .ctors/.dtors sections, and this is a static
2106      constructor or destructor, it must be recorded now.  */
2107   if (DECL_STATIC_CONSTRUCTOR (fndecl) && !targetm.have_ctors_dtors)
2108     VEC_safe_push (tree, gc, static_ctors, fndecl);
2109
2110   if (DECL_STATIC_DESTRUCTOR (fndecl) && !targetm.have_ctors_dtors)
2111     VEC_safe_push (tree, gc, static_dtors, fndecl);
2112
2113   /* Perform the required pre-gimplfication transformations on the tree.  */
2114   gnat_genericize (fndecl);
2115
2116   /* We do different things for nested and non-nested functions.
2117      ??? This should be in cgraph.  */
2118   if (!DECL_CONTEXT (fndecl))
2119     {
2120       gnat_gimplify_function (fndecl);
2121       cgraph_finalize_function (fndecl, false);
2122     }
2123   else
2124     /* Register this function with cgraph just far enough to get it
2125        added to our parent's nested function list.  */
2126     (void) cgraph_node (fndecl);
2127 }
2128
2129 /* Convert FNDECL's code to GIMPLE and handle any nested functions.  */
2130
2131 static void
2132 gnat_gimplify_function (tree fndecl)
2133 {
2134   struct cgraph_node *cgn;
2135
2136   dump_function (TDI_original, fndecl);
2137   gimplify_function_tree (fndecl);
2138   dump_function (TDI_generic, fndecl);
2139
2140   /* Convert all nested functions to GIMPLE now.  We do things in this order
2141      so that items like VLA sizes are expanded properly in the context of the
2142      correct function.  */
2143   cgn = cgraph_node (fndecl);
2144   for (cgn = cgn->nested; cgn; cgn = cgn->next_nested)
2145     gnat_gimplify_function (cgn->decl);
2146 }
2147 \f
2148
2149 tree
2150 gnat_builtin_function (tree decl)
2151 {
2152   gnat_pushdecl (decl, Empty);
2153   return decl;
2154 }
2155
2156 /* Handle a "const" attribute; arguments as in
2157    struct attribute_spec.handler.  */
2158
2159 static tree
2160 handle_const_attribute (tree *node, tree ARG_UNUSED (name),
2161                         tree ARG_UNUSED (args), int ARG_UNUSED (flags),
2162                         bool *no_add_attrs)
2163 {
2164   if (TREE_CODE (*node) == FUNCTION_DECL)
2165     TREE_READONLY (*node) = 1;
2166   else
2167     *no_add_attrs = true;
2168
2169   return NULL_TREE;
2170 }
2171
2172 /* Handle a "nothrow" attribute; arguments as in
2173    struct attribute_spec.handler.  */
2174
2175 static tree
2176 handle_nothrow_attribute (tree *node, tree ARG_UNUSED (name),
2177                           tree ARG_UNUSED (args), int ARG_UNUSED (flags),
2178                           bool *no_add_attrs)
2179 {
2180   if (TREE_CODE (*node) == FUNCTION_DECL)
2181     TREE_NOTHROW (*node) = 1;
2182   else
2183     *no_add_attrs = true;
2184
2185   return NULL_TREE;
2186 }
2187
2188 /* Return an integer type with the number of bits of precision given by
2189    PRECISION.  UNSIGNEDP is nonzero if the type is unsigned; otherwise
2190    it is a signed type.  */
2191
2192 tree
2193 gnat_type_for_size (unsigned precision, int unsignedp)
2194 {
2195   tree t;
2196   char type_name[20];
2197
2198   if (precision <= 2 * MAX_BITS_PER_WORD
2199       && signed_and_unsigned_types[precision][unsignedp])
2200     return signed_and_unsigned_types[precision][unsignedp];
2201
2202  if (unsignedp)
2203     t = make_unsigned_type (precision);
2204   else
2205     t = make_signed_type (precision);
2206
2207   if (precision <= 2 * MAX_BITS_PER_WORD)
2208     signed_and_unsigned_types[precision][unsignedp] = t;
2209
2210   if (!TYPE_NAME (t))
2211     {
2212       sprintf (type_name, "%sSIGNED_%d", unsignedp ? "UN" : "", precision);
2213       TYPE_NAME (t) = get_identifier (type_name);
2214     }
2215
2216   return t;
2217 }
2218
2219 /* Likewise for floating-point types.  */
2220
2221 static tree
2222 float_type_for_precision (int precision, enum machine_mode mode)
2223 {
2224   tree t;
2225   char type_name[20];
2226
2227   if (float_types[(int) mode])
2228     return float_types[(int) mode];
2229
2230   float_types[(int) mode] = t = make_node (REAL_TYPE);
2231   TYPE_PRECISION (t) = precision;
2232   layout_type (t);
2233
2234   gcc_assert (TYPE_MODE (t) == mode);
2235   if (!TYPE_NAME (t))
2236     {
2237       sprintf (type_name, "FLOAT_%d", precision);
2238       TYPE_NAME (t) = get_identifier (type_name);
2239     }
2240
2241   return t;
2242 }
2243
2244 /* Return a data type that has machine mode MODE.  UNSIGNEDP selects
2245    an unsigned type; otherwise a signed type is returned.  */
2246
2247 tree
2248 gnat_type_for_mode (enum machine_mode mode, int unsignedp)
2249 {
2250   if (mode == BLKmode)
2251     return NULL_TREE;
2252   else if (mode == VOIDmode)
2253     return void_type_node;
2254   else if (COMPLEX_MODE_P (mode))
2255     return NULL_TREE;
2256   else if (SCALAR_FLOAT_MODE_P (mode))
2257     return float_type_for_precision (GET_MODE_PRECISION (mode), mode);
2258   else if (SCALAR_INT_MODE_P (mode))
2259     return gnat_type_for_size (GET_MODE_BITSIZE (mode), unsignedp);
2260   else
2261     return NULL_TREE;
2262 }
2263
2264 /* Return the unsigned version of a TYPE_NODE, a scalar type.  */
2265
2266 tree
2267 gnat_unsigned_type (tree type_node)
2268 {
2269   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 1);
2270
2271   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
2272     {
2273       type = copy_node (type);
2274       TREE_TYPE (type) = type_node;
2275     }
2276   else if (TREE_TYPE (type_node)
2277            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
2278            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
2279     {
2280       type = copy_node (type);
2281       TREE_TYPE (type) = TREE_TYPE (type_node);
2282     }
2283
2284   return type;
2285 }
2286
2287 /* Return the signed version of a TYPE_NODE, a scalar type.  */
2288
2289 tree
2290 gnat_signed_type (tree type_node)
2291 {
2292   tree type = gnat_type_for_size (TYPE_PRECISION (type_node), 0);
2293
2294   if (TREE_CODE (type_node) == INTEGER_TYPE && TYPE_MODULAR_P (type_node))
2295     {
2296       type = copy_node (type);
2297       TREE_TYPE (type) = type_node;
2298     }
2299   else if (TREE_TYPE (type_node)
2300            && TREE_CODE (TREE_TYPE (type_node)) == INTEGER_TYPE
2301            && TYPE_MODULAR_P (TREE_TYPE (type_node)))
2302     {
2303       type = copy_node (type);
2304       TREE_TYPE (type) = TREE_TYPE (type_node);
2305     }
2306
2307   return type;
2308 }
2309
2310 /* Return a type the same as TYPE except unsigned or signed according to
2311    UNSIGNEDP.  */
2312
2313 tree
2314 gnat_signed_or_unsigned_type (int unsignedp, tree type)
2315 {
2316   if (!INTEGRAL_TYPE_P (type) || TYPE_UNSIGNED (type) == unsignedp)
2317     return type;
2318   else
2319     return gnat_type_for_size (TYPE_PRECISION (type), unsignedp);
2320 }
2321 \f
2322 /* EXP is an expression for the size of an object.  If this size contains
2323    discriminant references, replace them with the maximum (if MAX_P) or
2324    minimum (if !MAX_P) possible value of the discriminant.  */
2325
2326 tree
2327 max_size (tree exp, bool max_p)
2328 {
2329   enum tree_code code = TREE_CODE (exp);
2330   tree type = TREE_TYPE (exp);
2331
2332   switch (TREE_CODE_CLASS (code))
2333     {
2334     case tcc_declaration:
2335     case tcc_constant:
2336       return exp;
2337
2338     case tcc_exceptional:
2339       if (code == TREE_LIST)
2340         return tree_cons (TREE_PURPOSE (exp),
2341                           max_size (TREE_VALUE (exp), max_p),
2342                           TREE_CHAIN (exp)
2343                           ? max_size (TREE_CHAIN (exp), max_p) : NULL_TREE);
2344       break;
2345
2346     case tcc_reference:
2347       /* If this contains a PLACEHOLDER_EXPR, it is the thing we want to
2348          modify.  Otherwise, we treat it like a variable.  */
2349       if (!CONTAINS_PLACEHOLDER_P (exp))
2350         return exp;
2351
2352       type = TREE_TYPE (TREE_OPERAND (exp, 1));
2353       return
2354         max_size (max_p ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type), true);
2355
2356     case tcc_comparison:
2357       return max_p ? size_one_node : size_zero_node;
2358
2359     case tcc_unary:
2360     case tcc_binary:
2361     case tcc_expression:
2362       switch (TREE_CODE_LENGTH (code))
2363         {
2364         case 1:
2365           if (code == NON_LVALUE_EXPR)
2366             return max_size (TREE_OPERAND (exp, 0), max_p);
2367           else
2368             return
2369               fold (build1 (code, type,
2370                             max_size (TREE_OPERAND (exp, 0),
2371                                       code == NEGATE_EXPR ? !max_p : max_p)));
2372
2373         case 2:
2374           if (code == COMPOUND_EXPR)
2375             return max_size (TREE_OPERAND (exp, 1), max_p);
2376
2377           /* Calculate "(A ? B : C) - D" as "A ? B - D : C - D" which
2378              may provide a tighter bound on max_size.  */
2379           if (code == MINUS_EXPR
2380               && TREE_CODE (TREE_OPERAND (exp, 0)) == COND_EXPR)
2381             {
2382               tree lhs = fold_build2 (MINUS_EXPR, type,
2383                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 1),
2384                                       TREE_OPERAND (exp, 1));
2385               tree rhs = fold_build2 (MINUS_EXPR, type,
2386                                       TREE_OPERAND (TREE_OPERAND (exp, 0), 2),
2387                                       TREE_OPERAND (exp, 1));
2388               return fold_build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2389                                   max_size (lhs, max_p),
2390                                   max_size (rhs, max_p));
2391             }
2392
2393           {
2394             tree lhs = max_size (TREE_OPERAND (exp, 0), max_p);
2395             tree rhs = max_size (TREE_OPERAND (exp, 1),
2396                                  code == MINUS_EXPR ? !max_p : max_p);
2397
2398             /* Special-case wanting the maximum value of a MIN_EXPR.
2399                In that case, if one side overflows, return the other.
2400                sizetype is signed, but we know sizes are non-negative.
2401                Likewise, handle a MINUS_EXPR or PLUS_EXPR with the LHS
2402                overflowing or the maximum possible value and the RHS
2403                a variable.  */
2404             if (max_p
2405                 && code == MIN_EXPR
2406                 && TREE_CODE (rhs) == INTEGER_CST
2407                 && TREE_OVERFLOW (rhs))
2408               return lhs;
2409             else if (max_p
2410                      && code == MIN_EXPR
2411                      && TREE_CODE (lhs) == INTEGER_CST
2412                      && TREE_OVERFLOW (lhs))
2413               return rhs;
2414             else if ((code == MINUS_EXPR || code == PLUS_EXPR)
2415                      && ((TREE_CODE (lhs) == INTEGER_CST
2416                           && TREE_OVERFLOW (lhs))
2417                          || operand_equal_p (lhs, TYPE_MAX_VALUE (type), 0))
2418                      && !TREE_CONSTANT (rhs))
2419               return lhs;
2420             else
2421               return fold (build2 (code, type, lhs, rhs));
2422           }
2423
2424         case 3:
2425           if (code == SAVE_EXPR)
2426             return exp;
2427           else if (code == COND_EXPR)
2428             return fold (build2 (max_p ? MAX_EXPR : MIN_EXPR, type,
2429                                  max_size (TREE_OPERAND (exp, 1), max_p),
2430                                  max_size (TREE_OPERAND (exp, 2), max_p)));
2431           else if (code == CALL_EXPR && TREE_OPERAND (exp, 1))
2432             return build3 (CALL_EXPR, type, TREE_OPERAND (exp, 0),
2433                            max_size (TREE_OPERAND (exp, 1), max_p), NULL);
2434         }
2435
2436       /* Other tree classes cannot happen.  */
2437     default:
2438       break;
2439     }
2440
2441   gcc_unreachable ();
2442 }
2443 \f
2444 /* Build a template of type TEMPLATE_TYPE from the array bounds of ARRAY_TYPE.
2445    EXPR is an expression that we can use to locate any PLACEHOLDER_EXPRs.
2446    Return a constructor for the template.  */
2447
2448 tree
2449 build_template (tree template_type, tree array_type, tree expr)
2450 {
2451   tree template_elts = NULL_TREE;
2452   tree bound_list = NULL_TREE;
2453   tree field;
2454
2455   if (TREE_CODE (array_type) == RECORD_TYPE
2456       && (TYPE_IS_PADDING_P (array_type)
2457           || TYPE_JUSTIFIED_MODULAR_P (array_type)))
2458     array_type = TREE_TYPE (TYPE_FIELDS (array_type));
2459
2460   if (TREE_CODE (array_type) == ARRAY_TYPE
2461       || (TREE_CODE (array_type) == INTEGER_TYPE
2462           && TYPE_HAS_ACTUAL_BOUNDS_P (array_type)))
2463     bound_list = TYPE_ACTUAL_BOUNDS (array_type);
2464
2465   /* First make the list for a CONSTRUCTOR for the template.   Go down the
2466      field list of the template instead of the type chain because this
2467      array might be an Ada array of arrays and we can't tell where the
2468      nested arrays stop being the underlying object.  */
2469
2470   for (field = TYPE_FIELDS (template_type); field;
2471        (bound_list
2472         ? (bound_list = TREE_CHAIN (bound_list))
2473         : (array_type = TREE_TYPE (array_type))),
2474        field = TREE_CHAIN (TREE_CHAIN (field)))
2475     {
2476       tree bounds, min, max;
2477
2478       /* If we have a bound list, get the bounds from there.  Likewise
2479          for an ARRAY_TYPE.  Otherwise, if expr is a PARM_DECL with
2480          DECL_BY_COMPONENT_PTR_P, use the bounds of the field in the template.
2481          This will give us a maximum range.  */
2482       if (bound_list)
2483         bounds = TREE_VALUE (bound_list);
2484       else if (TREE_CODE (array_type) == ARRAY_TYPE)
2485         bounds = TYPE_INDEX_TYPE (TYPE_DOMAIN (array_type));
2486       else if (expr && TREE_CODE (expr) == PARM_DECL
2487                && DECL_BY_COMPONENT_PTR_P (expr))
2488         bounds = TREE_TYPE (field);
2489       else
2490         gcc_unreachable ();
2491
2492       min = convert (TREE_TYPE (TREE_CHAIN (field)), TYPE_MIN_VALUE (bounds));
2493       max = convert (TREE_TYPE (field), TYPE_MAX_VALUE (bounds));
2494
2495       /* If either MIN or MAX involve a PLACEHOLDER_EXPR, we must
2496          substitute it from OBJECT.  */
2497       min = SUBSTITUTE_PLACEHOLDER_IN_EXPR (min, expr);
2498       max = SUBSTITUTE_PLACEHOLDER_IN_EXPR (max, expr);
2499
2500       template_elts = tree_cons (TREE_CHAIN (field), max,
2501                                  tree_cons (field, min, template_elts));
2502     }
2503
2504   return gnat_build_constructor (template_type, nreverse (template_elts));
2505 }
2506 \f
2507 /* Build a VMS descriptor from a Mechanism_Type, which must specify
2508    a descriptor type, and the GCC type of an object.  Each FIELD_DECL
2509    in the type contains in its DECL_INITIAL the expression to use when
2510    a constructor is made for the type.  GNAT_ENTITY is an entity used
2511    to print out an error message if the mechanism cannot be applied to
2512    an object of that type and also for the name.  */
2513
2514 tree
2515 build_vms_descriptor (tree type, Mechanism_Type mech, Entity_Id gnat_entity)
2516 {
2517   tree record_type = make_node (RECORD_TYPE);
2518   tree field_list = 0;
2519   int class;
2520   int dtype = 0;
2521   tree inner_type;
2522   int ndim;
2523   int i;
2524   tree *idx_arr;
2525   tree tem;
2526
2527   /* If TYPE is an unconstrained array, use the underlying array type.  */
2528   if (TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
2529     type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (type))));
2530
2531   /* If this is an array, compute the number of dimensions in the array,
2532      get the index types, and point to the inner type.  */
2533   if (TREE_CODE (type) != ARRAY_TYPE)
2534     ndim = 0;
2535   else
2536     for (ndim = 1, inner_type = type;
2537          TREE_CODE (TREE_TYPE (inner_type)) == ARRAY_TYPE
2538          && TYPE_MULTI_ARRAY_P (TREE_TYPE (inner_type));
2539          ndim++, inner_type = TREE_TYPE (inner_type))
2540       ;
2541
2542   idx_arr = (tree *) alloca (ndim * sizeof (tree));
2543
2544   if (mech != By_Descriptor_NCA
2545       && TREE_CODE (type) == ARRAY_TYPE && TYPE_CONVENTION_FORTRAN_P (type))
2546     for (i = ndim - 1, inner_type = type;
2547          i >= 0;
2548          i--, inner_type = TREE_TYPE (inner_type))
2549       idx_arr[i] = TYPE_DOMAIN (inner_type);
2550   else
2551     for (i = 0, inner_type = type;
2552          i < ndim;
2553          i++, inner_type = TREE_TYPE (inner_type))
2554       idx_arr[i] = TYPE_DOMAIN (inner_type);
2555
2556   /* Now get the DTYPE value.  */
2557   switch (TREE_CODE (type))
2558     {
2559     case INTEGER_TYPE:
2560     case ENUMERAL_TYPE:
2561       if (TYPE_VAX_FLOATING_POINT_P (type))
2562         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2563           {
2564           case 6:
2565             dtype = 10;
2566             break;
2567           case 9:
2568             dtype = 11;
2569             break;
2570           case 15:
2571             dtype = 27;
2572             break;
2573           }
2574       else
2575         switch (GET_MODE_BITSIZE (TYPE_MODE (type)))
2576           {
2577           case 8:
2578             dtype = TYPE_UNSIGNED (type) ? 2 : 6;
2579             break;
2580           case 16:
2581             dtype = TYPE_UNSIGNED (type) ? 3 : 7;
2582             break;
2583           case 32:
2584             dtype = TYPE_UNSIGNED (type) ? 4 : 8;
2585             break;
2586           case 64:
2587             dtype = TYPE_UNSIGNED (type) ? 5 : 9;
2588             break;
2589           case 128:
2590             dtype = TYPE_UNSIGNED (type) ? 25 : 26;
2591             break;
2592           }
2593       break;
2594
2595     case REAL_TYPE:
2596       dtype = GET_MODE_BITSIZE (TYPE_MODE (type)) == 32 ? 52 : 53;
2597       break;
2598
2599     case COMPLEX_TYPE:
2600       if (TREE_CODE (TREE_TYPE (type)) == INTEGER_TYPE
2601           && TYPE_VAX_FLOATING_POINT_P (type))
2602         switch (tree_low_cst (TYPE_DIGITS_VALUE (type), 1))
2603           {
2604           case 6:
2605             dtype = 12;
2606             break;
2607           case 9:
2608             dtype = 13;
2609             break;
2610           case 15:
2611             dtype = 29;
2612           }
2613       else
2614         dtype = GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE (type))) == 32 ? 54: 55;
2615       break;
2616
2617     case ARRAY_TYPE:
2618       dtype = 14;
2619       break;
2620
2621     default:
2622       break;
2623     }
2624
2625   /* Get the CLASS value.  */
2626   switch (mech)
2627     {
2628     case By_Descriptor_A:
2629       class = 4;
2630       break;
2631     case By_Descriptor_NCA:
2632       class = 10;
2633       break;
2634     case By_Descriptor_SB:
2635       class = 15;
2636       break;
2637     default:
2638       class = 1;
2639     }
2640
2641   /* Make the type for a descriptor for VMS.  The first four fields
2642      are the same for all types.  */
2643
2644   field_list
2645     = chainon (field_list,
2646                make_descriptor_field
2647                ("LENGTH", gnat_type_for_size (16, 1), record_type,
2648                 size_in_bytes (mech == By_Descriptor_A ? inner_type : type)));
2649
2650   field_list = chainon (field_list,
2651                         make_descriptor_field ("DTYPE",
2652                                                gnat_type_for_size (8, 1),
2653                                                record_type, size_int (dtype)));
2654   field_list = chainon (field_list,
2655                         make_descriptor_field ("CLASS",
2656                                                gnat_type_for_size (8, 1),
2657                                                record_type, size_int (class)));
2658
2659   field_list
2660     = chainon (field_list,
2661                make_descriptor_field
2662                ("POINTER",
2663                 build_pointer_type_for_mode (type, SImode, false), record_type,
2664                 build1 (ADDR_EXPR,
2665                         build_pointer_type_for_mode (type, SImode, false),
2666                         build0 (PLACEHOLDER_EXPR, type))));
2667
2668   switch (mech)
2669     {
2670     case By_Descriptor:
2671     case By_Descriptor_S:
2672       break;
2673
2674     case By_Descriptor_SB:
2675       field_list
2676         = chainon (field_list,
2677                    make_descriptor_field
2678                    ("SB_L1", gnat_type_for_size (32, 1), record_type,
2679                     TREE_CODE (type) == ARRAY_TYPE
2680                     ? TYPE_MIN_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2681       field_list
2682         = chainon (field_list,
2683                    make_descriptor_field
2684                    ("SB_L2", gnat_type_for_size (32, 1), record_type,
2685                     TREE_CODE (type) == ARRAY_TYPE
2686                     ? TYPE_MAX_VALUE (TYPE_DOMAIN (type)) : size_zero_node));
2687       break;
2688
2689     case By_Descriptor_A:
2690     case By_Descriptor_NCA:
2691       field_list = chainon (field_list,
2692                             make_descriptor_field ("SCALE",
2693                                                    gnat_type_for_size (8, 1),
2694                                                    record_type,
2695                                                    size_zero_node));
2696
2697       field_list = chainon (field_list,
2698                             make_descriptor_field ("DIGITS",
2699                                                    gnat_type_for_size (8, 1),
2700                                                    record_type,
2701                                                    size_zero_node));
2702
2703       field_list
2704         = chainon (field_list,
2705                    make_descriptor_field
2706                    ("AFLAGS", gnat_type_for_size (8, 1), record_type,
2707                     size_int (mech == By_Descriptor_NCA
2708                               ? 0
2709                               /* Set FL_COLUMN, FL_COEFF, and FL_BOUNDS.  */
2710                               : (TREE_CODE (type) == ARRAY_TYPE
2711                                  && TYPE_CONVENTION_FORTRAN_P (type)
2712                                  ? 224 : 192))));
2713
2714       field_list = chainon (field_list,
2715                             make_descriptor_field ("DIMCT",
2716                                                    gnat_type_for_size (8, 1),
2717                                                    record_type,
2718                                                    size_int (ndim)));
2719
2720       field_list = chainon (field_list,
2721                             make_descriptor_field ("ARSIZE",
2722                                                    gnat_type_for_size (32, 1),
2723                                                    record_type,
2724                                                    size_in_bytes (type)));
2725
2726       /* Now build a pointer to the 0,0,0... element.  */
2727       tem = build0 (PLACEHOLDER_EXPR, type);
2728       for (i = 0, inner_type = type; i < ndim;
2729            i++, inner_type = TREE_TYPE (inner_type))
2730         tem = build4 (ARRAY_REF, TREE_TYPE (inner_type), tem,
2731                       convert (TYPE_DOMAIN (inner_type), size_zero_node),
2732                       NULL_TREE, NULL_TREE);
2733
2734       field_list
2735         = chainon (field_list,
2736                    make_descriptor_field
2737                    ("A0",
2738                     build_pointer_type_for_mode (inner_type, SImode, false),
2739                     record_type,
2740                     build1 (ADDR_EXPR,
2741                             build_pointer_type_for_mode (inner_type, SImode,
2742                                                          false),
2743                             tem)));
2744
2745       /* Next come the addressing coefficients.  */
2746       tem = size_int (1);
2747       for (i = 0; i < ndim; i++)
2748         {
2749           char fname[3];
2750           tree idx_length
2751             = size_binop (MULT_EXPR, tem,
2752                           size_binop (PLUS_EXPR,
2753                                       size_binop (MINUS_EXPR,
2754                                                   TYPE_MAX_VALUE (idx_arr[i]),
2755                                                   TYPE_MIN_VALUE (idx_arr[i])),
2756                                       size_int (1)));
2757
2758           fname[0] = (mech == By_Descriptor_NCA ? 'S' : 'M');
2759           fname[1] = '0' + i, fname[2] = 0;
2760           field_list
2761             = chainon (field_list,
2762                        make_descriptor_field (fname,
2763                                               gnat_type_for_size (32, 1),
2764                                               record_type, idx_length));
2765
2766           if (mech == By_Descriptor_NCA)
2767             tem = idx_length;
2768         }
2769
2770       /* Finally here are the bounds.  */
2771       for (i = 0; i < ndim; i++)
2772         {
2773           char fname[3];
2774
2775           fname[0] = 'L', fname[1] = '0' + i, fname[2] = 0;
2776           field_list
2777             = chainon (field_list,
2778                        make_descriptor_field
2779                        (fname, gnat_type_for_size (32, 1), record_type,
2780                         TYPE_MIN_VALUE (idx_arr[i])));
2781
2782           fname[0] = 'U';
2783           field_list
2784             = chainon (field_list,
2785                        make_descriptor_field
2786                        (fname, gnat_type_for_size (32, 1), record_type,
2787                         TYPE_MAX_VALUE (idx_arr[i])));
2788         }
2789       break;
2790
2791     default:
2792       post_error ("unsupported descriptor type for &", gnat_entity);
2793     }
2794
2795   finish_record_type (record_type, field_list, false, true);
2796   create_type_decl (create_concat_name (gnat_entity, "DESC"), record_type,
2797                     NULL, true, false, gnat_entity);
2798
2799   return record_type;
2800 }
2801
2802 /* Utility routine for above code to make a field.  */
2803
2804 static tree
2805 make_descriptor_field (const char *name, tree type,
2806                        tree rec_type, tree initial)
2807 {
2808   tree field
2809     = create_field_decl (get_identifier (name), type, rec_type, 0, 0, 0, 0);
2810
2811   DECL_INITIAL (field) = initial;
2812   return field;
2813 }
2814 \f
2815 /* Build a type to be used to represent an aliased object whose nominal
2816    type is an unconstrained array.  This consists of a RECORD_TYPE containing
2817    a field of TEMPLATE_TYPE and a field of OBJECT_TYPE, which is an
2818    ARRAY_TYPE.  If ARRAY_TYPE is that of the unconstrained array, this
2819    is used to represent an arbitrary unconstrained object.  Use NAME
2820    as the name of the record.  */
2821
2822 tree
2823 build_unc_object_type (tree template_type, tree object_type, tree name)
2824 {
2825   tree type = make_node (RECORD_TYPE);
2826   tree template_field = create_field_decl (get_identifier ("BOUNDS"),
2827                                            template_type, type, 0, 0, 0, 1);
2828   tree array_field = create_field_decl (get_identifier ("ARRAY"), object_type,
2829                                         type, 0, 0, 0, 1);
2830
2831   TYPE_NAME (type) = name;
2832   TYPE_CONTAINS_TEMPLATE_P (type) = 1;
2833   finish_record_type (type,
2834                       chainon (chainon (NULL_TREE, template_field),
2835                                array_field),
2836                       false, false);
2837
2838   return type;
2839 }
2840
2841 /* Same, taking a thin or fat pointer type instead of a template type. */
2842
2843 tree
2844 build_unc_object_type_from_ptr (tree thin_fat_ptr_type, tree object_type,
2845                                 tree name)
2846 {
2847   tree template_type;
2848
2849   gcc_assert (TYPE_FAT_OR_THIN_POINTER_P (thin_fat_ptr_type));
2850
2851   template_type
2852     = (TYPE_FAT_POINTER_P (thin_fat_ptr_type)
2853        ? TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (thin_fat_ptr_type))))
2854        : TREE_TYPE (TYPE_FIELDS (TREE_TYPE (thin_fat_ptr_type))));
2855   return build_unc_object_type (template_type, object_type, name);
2856 }
2857 \f
2858 /* Update anything previously pointing to OLD_TYPE to point to NEW_TYPE.  In
2859    the normal case this is just two adjustments, but we have more to do
2860    if NEW is an UNCONSTRAINED_ARRAY_TYPE.  */
2861
2862 void
2863 update_pointer_to (tree old_type, tree new_type)
2864 {
2865   tree ptr = TYPE_POINTER_TO (old_type);
2866   tree ref = TYPE_REFERENCE_TO (old_type);
2867   tree ptr1, ref1;
2868   tree type;
2869
2870   /* If this is the main variant, process all the other variants first.  */
2871   if (TYPE_MAIN_VARIANT (old_type) == old_type)
2872     for (type = TYPE_NEXT_VARIANT (old_type); type;
2873          type = TYPE_NEXT_VARIANT (type))
2874       update_pointer_to (type, new_type);
2875
2876   /* If no pointer or reference, we are done.  */
2877   if (!ptr && !ref)
2878     return;
2879
2880   /* Merge the old type qualifiers in the new type.
2881
2882      Each old variant has qualifiers for specific reasons, and the new
2883      designated type as well. Each set of qualifiers represents useful
2884      information grabbed at some point, and merging the two simply unifies
2885      these inputs into the final type description.
2886
2887      Consider for instance a volatile type frozen after an access to constant
2888      type designating it. After the designated type freeze, we get here with a
2889      volatile new_type and a dummy old_type with a readonly variant, created
2890      when the access type was processed. We shall make a volatile and readonly
2891      designated type, because that's what it really is.
2892
2893      We might also get here for a non-dummy old_type variant with different
2894      qualifiers than the new_type ones, for instance in some cases of pointers
2895      to private record type elaboration (see the comments around the call to
2896      this routine from gnat_to_gnu_entity/E_Access_Type). We have to merge the
2897      qualifiers in thoses cases too, to avoid accidentally discarding the
2898      initial set, and will often end up with old_type == new_type then.  */
2899   new_type = build_qualified_type (new_type,
2900                                    TYPE_QUALS (old_type)
2901                                    | TYPE_QUALS (new_type));
2902
2903   /* If the new type and the old one are identical, there is nothing to
2904      update.  */
2905   if (old_type == new_type)
2906     return;
2907
2908   /* Otherwise, first handle the simple case.  */
2909   if (TREE_CODE (new_type) != UNCONSTRAINED_ARRAY_TYPE)
2910     {
2911       TYPE_POINTER_TO (new_type) = ptr;
2912       TYPE_REFERENCE_TO (new_type) = ref;
2913
2914       for (; ptr; ptr = TYPE_NEXT_PTR_TO (ptr))
2915         for (ptr1 = TYPE_MAIN_VARIANT (ptr); ptr1;
2916              ptr1 = TYPE_NEXT_VARIANT (ptr1))
2917           TREE_TYPE (ptr1) = new_type;
2918
2919       for (; ref; ref = TYPE_NEXT_REF_TO (ref))
2920         for (ref1 = TYPE_MAIN_VARIANT (ref); ref1;
2921              ref1 = TYPE_NEXT_VARIANT (ref1))
2922           TREE_TYPE (ref1) = new_type;
2923     }
2924
2925   /* Now deal with the unconstrained array case. In this case the "pointer"
2926      is actually a RECORD_TYPE where the types of both fields are
2927      pointers to void.  In that case, copy the field list from the
2928      old type to the new one and update the fields' context. */
2929   else if (TREE_CODE (ptr) != RECORD_TYPE || !TYPE_IS_FAT_POINTER_P (ptr))
2930     gcc_unreachable ();
2931
2932   else
2933     {
2934       tree new_obj_rec = TYPE_OBJECT_RECORD_TYPE (new_type);
2935       tree ptr_temp_type;
2936       tree new_ref;
2937       tree var;
2938
2939       SET_DECL_ORIGINAL_FIELD (TYPE_FIELDS (ptr),
2940                                TYPE_FIELDS (TYPE_POINTER_TO (new_type)));
2941       SET_DECL_ORIGINAL_FIELD (TREE_CHAIN (TYPE_FIELDS (ptr)),
2942                                TREE_CHAIN (TYPE_FIELDS
2943                                            (TYPE_POINTER_TO (new_type))));
2944
2945       TYPE_FIELDS (ptr) = TYPE_FIELDS (TYPE_POINTER_TO (new_type));
2946       DECL_CONTEXT (TYPE_FIELDS (ptr)) = ptr;
2947       DECL_CONTEXT (TREE_CHAIN (TYPE_FIELDS (ptr))) = ptr;
2948
2949       /* Rework the PLACEHOLDER_EXPR inside the reference to the
2950          template bounds.
2951
2952          ??? This is now the only use of gnat_substitute_in_type, which
2953          is now a very "heavy" routine to do this, so it should be replaced
2954          at some point.  */
2955       ptr_temp_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (ptr)));
2956       new_ref = build3 (COMPONENT_REF, ptr_temp_type,
2957                         build0 (PLACEHOLDER_EXPR, ptr),
2958                         TREE_CHAIN (TYPE_FIELDS (ptr)), NULL_TREE);
2959
2960       update_pointer_to
2961         (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))),
2962          gnat_substitute_in_type (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))),
2963                                   TREE_CHAIN (TYPE_FIELDS (ptr)), new_ref));
2964
2965       for (var = TYPE_MAIN_VARIANT (ptr); var; var = TYPE_NEXT_VARIANT (var))
2966         {
2967           SET_TYPE_UNCONSTRAINED_ARRAY (var, new_type);
2968
2969           /* This may seem a bit gross, in particular wrt DECL_CONTEXT, but
2970              actually is in keeping with what build_qualified_type does.  */
2971           TYPE_FIELDS (var) = TYPE_FIELDS (ptr);
2972         }
2973
2974       TYPE_POINTER_TO (new_type) = TYPE_REFERENCE_TO (new_type)
2975         = TREE_TYPE (new_type) = ptr;
2976
2977       /* Now handle updating the allocation record, what the thin pointer
2978          points to.  Update all pointers from the old record into the new
2979          one, update the types of the fields, and recompute the size.  */
2980
2981       update_pointer_to (TYPE_OBJECT_RECORD_TYPE (old_type), new_obj_rec);
2982
2983       TREE_TYPE (TYPE_FIELDS (new_obj_rec)) = TREE_TYPE (ptr_temp_type);
2984       TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2985         = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr)));
2986       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2987         = TYPE_SIZE (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))));
2988       DECL_SIZE_UNIT (TREE_CHAIN (TYPE_FIELDS (new_obj_rec)))
2989         = TYPE_SIZE_UNIT (TREE_TYPE (TREE_TYPE (TYPE_FIELDS (ptr))));
2990
2991       TYPE_SIZE (new_obj_rec)
2992         = size_binop (PLUS_EXPR,
2993                       DECL_SIZE (TYPE_FIELDS (new_obj_rec)),
2994                       DECL_SIZE (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))));
2995       TYPE_SIZE_UNIT (new_obj_rec)
2996         = size_binop (PLUS_EXPR,
2997                       DECL_SIZE_UNIT (TYPE_FIELDS (new_obj_rec)),
2998                       DECL_SIZE_UNIT (TREE_CHAIN (TYPE_FIELDS (new_obj_rec))));
2999       rest_of_type_compilation (ptr, global_bindings_p ());
3000     }
3001 }
3002 \f
3003 /* Convert a pointer to a constrained array into a pointer to a fat
3004    pointer.  This involves making or finding a template.  */
3005
3006 static tree
3007 convert_to_fat_pointer (tree type, tree expr)
3008 {
3009   tree template_type = TREE_TYPE (TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type))));
3010   tree template, template_addr;
3011   tree etype = TREE_TYPE (expr);
3012
3013   /* If EXPR is a constant of zero, we make a fat pointer that has a null
3014      pointer to the template and array.  */
3015   if (integer_zerop (expr))
3016     return
3017       gnat_build_constructor
3018         (type,
3019          tree_cons (TYPE_FIELDS (type),
3020                     convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
3021                     tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3022                                convert (build_pointer_type (template_type),
3023                                         expr),
3024                                NULL_TREE)));
3025
3026   /* If EXPR is a thin pointer, make the template and data from the record.  */
3027
3028   else if (TYPE_THIN_POINTER_P (etype))
3029     {
3030       tree fields = TYPE_FIELDS (TREE_TYPE (etype));
3031
3032       expr = save_expr (expr);
3033       if (TREE_CODE (expr) == ADDR_EXPR)
3034         expr = TREE_OPERAND (expr, 0);
3035       else
3036         expr = build1 (INDIRECT_REF, TREE_TYPE (etype), expr);
3037
3038       template = build_component_ref (expr, NULL_TREE, fields, false);
3039       expr = build_unary_op (ADDR_EXPR, NULL_TREE,
3040                              build_component_ref (expr, NULL_TREE,
3041                                                   TREE_CHAIN (fields), false));
3042     }
3043   else
3044     /* Otherwise, build the constructor for the template.  */
3045     template = build_template (template_type, TREE_TYPE (etype), expr);
3046
3047   template_addr = build_unary_op (ADDR_EXPR, NULL_TREE, template);
3048
3049   /* The result is a CONSTRUCTOR for the fat pointer.
3050
3051      If expr is an argument of a foreign convention subprogram, the type it
3052      points to is directly the component type. In this case, the expression
3053      type may not match the corresponding FIELD_DECL type at this point, so we
3054      call "convert" here to fix that up if necessary. This type consistency is
3055      required, for instance because it ensures that possible later folding of
3056      component_refs against this constructor always yields something of the
3057      same type as the initial reference.
3058
3059      Note that the call to "build_template" above is still fine, because it
3060      will only refer to the provided template_type in this case.  */
3061    return
3062      gnat_build_constructor
3063      (type, tree_cons (TYPE_FIELDS (type),
3064                       convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
3065                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3066                                  template_addr, NULL_TREE)));
3067 }
3068 \f
3069 /* Convert to a thin pointer type, TYPE.  The only thing we know how to convert
3070    is something that is a fat pointer, so convert to it first if it EXPR
3071    is not already a fat pointer.  */
3072
3073 static tree
3074 convert_to_thin_pointer (tree type, tree expr)
3075 {
3076   if (!TYPE_FAT_POINTER_P (TREE_TYPE (expr)))
3077     expr
3078       = convert_to_fat_pointer
3079         (TREE_TYPE (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type))), expr);
3080
3081   /* We get the pointer to the data and use a NOP_EXPR to make it the
3082      proper GCC type.  */
3083   expr = build_component_ref (expr, NULL_TREE, TYPE_FIELDS (TREE_TYPE (expr)),
3084                               false);
3085   expr = build1 (NOP_EXPR, type, expr);
3086
3087   return expr;
3088 }
3089 \f
3090 /* Create an expression whose value is that of EXPR,
3091    converted to type TYPE.  The TREE_TYPE of the value
3092    is always TYPE.  This function implements all reasonable
3093    conversions; callers should filter out those that are
3094    not permitted by the language being compiled.  */
3095
3096 tree
3097 convert (tree type, tree expr)
3098 {
3099   enum tree_code code = TREE_CODE (type);
3100   tree etype = TREE_TYPE (expr);
3101   enum tree_code ecode = TREE_CODE (etype);
3102
3103   /* If EXPR is already the right type, we are done.  */
3104   if (type == etype)
3105     return expr;
3106
3107   /* If the input type has padding, remove it by doing a component reference
3108      to the field.  If the output type has padding, make a constructor
3109      to build the record.  If both input and output have padding and are
3110      of variable size, do this as an unchecked conversion.  */
3111   else if (ecode == RECORD_TYPE && code == RECORD_TYPE
3112       && TYPE_IS_PADDING_P (type) && TYPE_IS_PADDING_P (etype)
3113       && (!TREE_CONSTANT (TYPE_SIZE (type))
3114           || !TREE_CONSTANT (TYPE_SIZE (etype))))
3115     ;
3116   else if (ecode == RECORD_TYPE && TYPE_IS_PADDING_P (etype))
3117     {
3118       /* If we have just converted to this padded type, just get
3119          the inner expression.  */
3120       if (TREE_CODE (expr) == CONSTRUCTOR
3121           && !VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (expr))
3122           && VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->index
3123              == TYPE_FIELDS (etype))
3124         return VEC_index (constructor_elt, CONSTRUCTOR_ELTS (expr), 0)->value;
3125       else
3126         return convert (type,
3127                         build_component_ref (expr, NULL_TREE,
3128                                              TYPE_FIELDS (etype), false));
3129     }
3130   else if (code == RECORD_TYPE && TYPE_IS_PADDING_P (type))
3131     {
3132       /* If we previously converted from another type and our type is
3133          of variable size, remove the conversion to avoid the need for
3134          variable-size temporaries.  */
3135       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
3136           && !TREE_CONSTANT (TYPE_SIZE (type)))
3137         expr = TREE_OPERAND (expr, 0);
3138
3139       /* If we are just removing the padding from expr, convert the original
3140          object if we have variable size.  That will avoid the need
3141          for some variable-size temporaries.  */
3142       if (TREE_CODE (expr) == COMPONENT_REF
3143           && TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == RECORD_TYPE
3144           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (expr, 0)))
3145           && !TREE_CONSTANT (TYPE_SIZE (type)))
3146         return convert (type, TREE_OPERAND (expr, 0));
3147
3148       /* If the result type is a padded type with a self-referentially-sized
3149          field and the expression type is a record, do this as an
3150          unchecked conversion.  */
3151       else if (TREE_CODE (etype) == RECORD_TYPE
3152                && CONTAINS_PLACEHOLDER_P (DECL_SIZE (TYPE_FIELDS (type))))
3153         return unchecked_convert (type, expr, false);
3154
3155       else
3156         return
3157           gnat_build_constructor (type,
3158                              tree_cons (TYPE_FIELDS (type),
3159                                         convert (TREE_TYPE
3160                                                  (TYPE_FIELDS (type)),
3161                                                  expr),
3162                                         NULL_TREE));
3163     }
3164
3165   /* If the input is a biased type, adjust first.  */
3166   if (ecode == INTEGER_TYPE && TYPE_BIASED_REPRESENTATION_P (etype))
3167     return convert (type, fold (build2 (PLUS_EXPR, TREE_TYPE (etype),
3168                                         fold_convert (TREE_TYPE (etype),
3169                                                       expr),
3170                                         TYPE_MIN_VALUE (etype))));
3171
3172   /* If the input is a justified modular type, we need to extract the actual
3173      object before converting it to any other type with the exceptions of an
3174      unconstrained array or of a mere type variant.  It is useful to avoid the
3175      extraction and conversion in the type variant case because it could end
3176      up replacing a VAR_DECL expr by a constructor and we might be about the
3177      take the address of the result.  */
3178   if (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)
3179       && code != UNCONSTRAINED_ARRAY_TYPE
3180       && TYPE_MAIN_VARIANT (type) != TYPE_MAIN_VARIANT (etype))
3181     return convert (type, build_component_ref (expr, NULL_TREE,
3182                                                TYPE_FIELDS (etype), false));
3183
3184   /* If converting to a type that contains a template, convert to the data
3185      type and then build the template. */
3186   if (code == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (type))
3187     {
3188       tree obj_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (type)));
3189
3190       /* If the source already has a template, get a reference to the
3191          associated array only, as we are going to rebuild a template
3192          for the target type anyway.  */
3193       expr = maybe_unconstrained_array (expr);
3194
3195       return
3196         gnat_build_constructor
3197           (type,
3198            tree_cons (TYPE_FIELDS (type),
3199                       build_template (TREE_TYPE (TYPE_FIELDS (type)),
3200                                       obj_type, NULL_TREE),
3201                       tree_cons (TREE_CHAIN (TYPE_FIELDS (type)),
3202                                  convert (obj_type, expr), NULL_TREE)));
3203     }
3204
3205   /* There are some special cases of expressions that we process
3206      specially.  */
3207   switch (TREE_CODE (expr))
3208     {
3209     case ERROR_MARK:
3210       return expr;
3211
3212     case NULL_EXPR:
3213       /* Just set its type here.  For TRANSFORM_EXPR, we will do the actual
3214          conversion in gnat_expand_expr.  NULL_EXPR does not represent
3215          and actual value, so no conversion is needed.  */
3216       expr = copy_node (expr);
3217       TREE_TYPE (expr) = type;
3218       return expr;
3219
3220     case STRING_CST:
3221       /* If we are converting a STRING_CST to another constrained array type,
3222          just make a new one in the proper type.  */
3223       if (code == ecode && AGGREGATE_TYPE_P (etype)
3224           && !(TREE_CODE (TYPE_SIZE (etype)) == INTEGER_CST
3225                && TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST))
3226         {
3227           expr = copy_node (expr);
3228           TREE_TYPE (expr) = type;
3229           return expr;
3230         }
3231       break;
3232
3233     case UNCONSTRAINED_ARRAY_REF:
3234       /* Convert this to the type of the inner array by getting the address of
3235          the array from the template.  */
3236       expr = build_unary_op (INDIRECT_REF, NULL_TREE,
3237                              build_component_ref (TREE_OPERAND (expr, 0),
3238                                                   get_identifier ("P_ARRAY"),
3239                                                   NULL_TREE, false));
3240       etype = TREE_TYPE (expr);
3241       ecode = TREE_CODE (etype);
3242       break;
3243
3244     case VIEW_CONVERT_EXPR:
3245       {
3246         /* GCC 4.x is very sensitive to type consistency overall, and view
3247            conversions thus are very frequent.  Even though just "convert"ing
3248            the inner operand to the output type is fine in most cases, it
3249            might expose unexpected input/output type mismatches in special
3250            circumstances so we avoid such recursive calls when we can.  */
3251
3252         tree op0 = TREE_OPERAND (expr, 0);
3253
3254         /* If we are converting back to the original type, we can just
3255            lift the input conversion.  This is a common occurrence with
3256            switches back-and-forth amongst type variants.  */
3257         if (type == TREE_TYPE (op0))
3258           return op0;
3259
3260         /* Otherwise, if we're converting between two aggregate types, we
3261            might be allowed to substitute the VIEW_CONVERT target type in
3262            place or to just convert the inner expression.  */
3263         if (AGGREGATE_TYPE_P (type) && AGGREGATE_TYPE_P (etype))
3264           {
3265             /* If we are converting between type variants, we can just
3266                substitute the VIEW_CONVERT in place.  */
3267             if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype))
3268               return build1 (VIEW_CONVERT_EXPR, type, op0);
3269
3270             /* Otherwise, we may just bypass the input view conversion unless
3271                one of the types is a fat pointer,  which is handled by
3272                specialized code below which relies on exact type matching.  */
3273             else if (!TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
3274               return convert (type, op0);
3275           }
3276       }
3277       break;
3278
3279     case INDIRECT_REF:
3280       /* If both types are record types, just convert the pointer and
3281          make a new INDIRECT_REF.
3282
3283          ??? Disable this for now since it causes problems with the
3284          code in build_binary_op for MODIFY_EXPR which wants to
3285          strip off conversions.  But that code really is a mess and
3286          we need to do this a much better way some time.  */
3287       if (0
3288           && (TREE_CODE (type) == RECORD_TYPE
3289               || TREE_CODE (type) == UNION_TYPE)
3290           && (TREE_CODE (etype) == RECORD_TYPE
3291               || TREE_CODE (etype) == UNION_TYPE)
3292           && !TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
3293         return build_unary_op (INDIRECT_REF, NULL_TREE,
3294                                convert (build_pointer_type (type),
3295                                         TREE_OPERAND (expr, 0)));
3296       break;
3297
3298     default:
3299       break;
3300     }
3301
3302   /* Check for converting to a pointer to an unconstrained array.  */
3303   if (TYPE_FAT_POINTER_P (type) && !TYPE_FAT_POINTER_P (etype))
3304     return convert_to_fat_pointer (type, expr);
3305
3306   /* If we're converting between two aggregate types that have the same main
3307      variant, just make a VIEW_CONVER_EXPR.  */
3308   else if (AGGREGATE_TYPE_P (type)
3309            && TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype))
3310     return build1 (VIEW_CONVERT_EXPR, type, expr);
3311
3312   /* In all other cases of related types, make a NOP_EXPR.  */
3313   else if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (etype)
3314            || (code == INTEGER_CST && ecode == INTEGER_CST
3315                && (type == TREE_TYPE (etype) || etype == TREE_TYPE (type))))
3316     return fold_convert (type, expr);
3317
3318   switch (code)
3319     {
3320     case VOID_TYPE:
3321       return build1 (CONVERT_EXPR, type, expr);
3322
3323     case BOOLEAN_TYPE:
3324       return fold_convert (type, gnat_truthvalue_conversion (expr));
3325
3326     case INTEGER_TYPE:
3327       if (TYPE_HAS_ACTUAL_BOUNDS_P (type)
3328           && (ecode == ARRAY_TYPE || ecode == UNCONSTRAINED_ARRAY_TYPE
3329               || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))))
3330         return unchecked_convert (type, expr, false);
3331       else if (TYPE_BIASED_REPRESENTATION_P (type))
3332         return fold_convert (type,
3333                              fold_build2 (MINUS_EXPR, TREE_TYPE (type),
3334                                           convert (TREE_TYPE (type), expr),
3335                                           TYPE_MIN_VALUE (type)));
3336
3337       /* ... fall through ... */
3338
3339     case ENUMERAL_TYPE:
3340       return fold (convert_to_integer (type, expr));
3341
3342     case POINTER_TYPE:
3343     case REFERENCE_TYPE:
3344       /* If converting between two pointers to records denoting
3345          both a template and type, adjust if needed to account
3346          for any differing offsets, since one might be negative.  */
3347       if (TYPE_THIN_POINTER_P (etype) && TYPE_THIN_POINTER_P (type))
3348         {
3349           tree bit_diff
3350             = size_diffop (bit_position (TYPE_FIELDS (TREE_TYPE (etype))),
3351                            bit_position (TYPE_FIELDS (TREE_TYPE (type))));
3352           tree byte_diff = size_binop (CEIL_DIV_EXPR, bit_diff,
3353                                        sbitsize_int (BITS_PER_UNIT));
3354
3355           expr = build1 (NOP_EXPR, type, expr);
3356           TREE_CONSTANT (expr) = TREE_CONSTANT (TREE_OPERAND (expr, 0));
3357           if (integer_zerop (byte_diff))
3358             return expr;
3359
3360           return build_binary_op (PLUS_EXPR, type, expr,
3361                                   fold (convert_to_pointer (type, byte_diff)));
3362         }
3363
3364       /* If converting to a thin pointer, handle specially.  */
3365       if (TYPE_THIN_POINTER_P (type)
3366           && TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (type)))
3367         return convert_to_thin_pointer (type, expr);
3368
3369       /* If converting fat pointer to normal pointer, get the pointer to the
3370          array and then convert it.  */
3371       else if (TYPE_FAT_POINTER_P (etype))
3372         expr = build_component_ref (expr, get_identifier ("P_ARRAY"),
3373                                     NULL_TREE, false);
3374
3375       return fold (convert_to_pointer (type, expr));
3376
3377     case REAL_TYPE:
3378       return fold (convert_to_real (type, expr));
3379
3380     case RECORD_TYPE:
3381       if (TYPE_JUSTIFIED_MODULAR_P (type) && !AGGREGATE_TYPE_P (etype))
3382         return
3383           gnat_build_constructor
3384             (type, tree_cons (TYPE_FIELDS (type),
3385                               convert (TREE_TYPE (TYPE_FIELDS (type)), expr),
3386                               NULL_TREE));
3387
3388       /* ... fall through ... */
3389
3390     case ARRAY_TYPE:
3391       /* In these cases, assume the front-end has validated the conversion.
3392          If the conversion is valid, it will be a bit-wise conversion, so
3393          it can be viewed as an unchecked conversion.  */
3394       return unchecked_convert (type, expr, false);
3395
3396     case UNION_TYPE:
3397       /* This is a either a conversion between a tagged type and some
3398          subtype, which we have to mark as a UNION_TYPE because of
3399          overlapping fields or a conversion of an Unchecked_Union.  */
3400       return unchecked_convert (type, expr, false);
3401
3402     case UNCONSTRAINED_ARRAY_TYPE:
3403       /* If EXPR is a constrained array, take its address, convert it to a
3404          fat pointer, and then dereference it.  Likewise if EXPR is a
3405          record containing both a template and a constrained array.
3406          Note that a record representing a justified modular type
3407          always represents a packed constrained array.  */
3408       if (ecode == ARRAY_TYPE
3409           || (ecode == INTEGER_TYPE && TYPE_HAS_ACTUAL_BOUNDS_P (etype))
3410           || (ecode == RECORD_TYPE && TYPE_CONTAINS_TEMPLATE_P (etype))
3411           || (ecode == RECORD_TYPE && TYPE_JUSTIFIED_MODULAR_P (etype)))
3412         return
3413           build_unary_op
3414             (INDIRECT_REF, NULL_TREE,
3415              convert_to_fat_pointer (TREE_TYPE (type),
3416                                      build_unary_op (ADDR_EXPR,
3417                                                      NULL_TREE, expr)));
3418
3419       /* Do something very similar for converting one unconstrained
3420          array to another.  */
3421       else if (ecode == UNCONSTRAINED_ARRAY_TYPE)
3422         return
3423           build_unary_op (INDIRECT_REF, NULL_TREE,
3424                           convert (TREE_TYPE (type),
3425                                    build_unary_op (ADDR_EXPR,
3426                                                    NULL_TREE, expr)));
3427       else
3428         gcc_unreachable ();
3429
3430     case COMPLEX_TYPE:
3431       return fold (convert_to_complex (type, expr));
3432
3433     default:
3434       gcc_unreachable ();
3435     }
3436 }
3437 \f
3438 /* Remove all conversions that are done in EXP.  This includes converting
3439    from a padded type or to a justified modular type.  If TRUE_ADDRESS
3440    is true, always return the address of the containing object even if
3441    the address is not bit-aligned.  */
3442
3443 tree
3444 remove_conversions (tree exp, bool true_address)
3445 {
3446   switch (TREE_CODE (exp))
3447     {
3448     case CONSTRUCTOR:
3449       if (true_address
3450           && TREE_CODE (TREE_TYPE (exp)) == RECORD_TYPE
3451           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (exp)))
3452         return
3453           remove_conversions (VEC_index (constructor_elt,
3454                                          CONSTRUCTOR_ELTS (exp), 0)->value,
3455                               true);
3456       break;
3457
3458     case COMPONENT_REF:
3459       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (exp, 0))) == RECORD_TYPE
3460           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (exp, 0))))
3461         return remove_conversions (TREE_OPERAND (exp, 0), true_address);
3462       break;
3463
3464     case VIEW_CONVERT_EXPR:  case NON_LVALUE_EXPR:
3465     case NOP_EXPR:  case CONVERT_EXPR:
3466       return remove_conversions (TREE_OPERAND (exp, 0), true_address);
3467
3468     default:
3469       break;
3470     }
3471
3472   return exp;
3473 }
3474 \f
3475 /* If EXP's type is an UNCONSTRAINED_ARRAY_TYPE, return an expression that
3476    refers to the underlying array.  If its type has TYPE_CONTAINS_TEMPLATE_P,
3477    likewise return an expression pointing to the underlying array.  */
3478
3479 tree
3480 maybe_unconstrained_array (tree exp)
3481 {
3482   enum tree_code code = TREE_CODE (exp);
3483   tree new;
3484
3485   switch (TREE_CODE (TREE_TYPE (exp)))
3486     {
3487     case UNCONSTRAINED_ARRAY_TYPE:
3488       if (code == UNCONSTRAINED_ARRAY_REF)
3489         {
3490           new
3491             = build_unary_op (INDIRECT_REF, NULL_TREE,
3492                               build_component_ref (TREE_OPERAND (exp, 0),
3493                                                    get_identifier ("P_ARRAY"),
3494                                                    NULL_TREE, false));
3495           TREE_READONLY (new) = TREE_STATIC (new) = TREE_READONLY (exp);
3496           return new;
3497         }
3498
3499       else if (code == NULL_EXPR)
3500         return build1 (NULL_EXPR,
3501                        TREE_TYPE (TREE_TYPE (TYPE_FIELDS
3502                                              (TREE_TYPE (TREE_TYPE (exp))))),
3503                        TREE_OPERAND (exp, 0));
3504
3505     case RECORD_TYPE:
3506       /* If this is a padded type, convert to the unpadded type and see if
3507          it contains a template.  */
3508       if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
3509         {
3510           new = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
3511           if (TREE_CODE (TREE_TYPE (new)) == RECORD_TYPE
3512               && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (new)))
3513             return
3514               build_component_ref (new, NULL_TREE,
3515                                    TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (new))),
3516                                    0);
3517         }
3518       else if (TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (exp)))
3519         return
3520           build_component_ref (exp, NULL_TREE,
3521                                TREE_CHAIN (TYPE_FIELDS (TREE_TYPE (exp))), 0);
3522       break;
3523
3524     default:
3525       break;
3526     }
3527
3528   return exp;
3529 }
3530 \f
3531 /* Return an expression that does an unchecked conversion of EXPR to TYPE.
3532    If NOTRUNC_P is true, truncation operations should be suppressed.  */
3533
3534 tree
3535 unchecked_convert (tree type, tree expr, bool notrunc_p)
3536 {
3537   tree etype = TREE_TYPE (expr);
3538
3539   /* If the expression is already the right type, we are done.  */
3540   if (etype == type)
3541     return expr;
3542
3543   /* If both types types are integral just do a normal conversion.
3544      Likewise for a conversion to an unconstrained array.  */
3545   if ((((INTEGRAL_TYPE_P (type)
3546          && !(TREE_CODE (type) == INTEGER_TYPE
3547               && TYPE_VAX_FLOATING_POINT_P (type)))
3548         || (POINTER_TYPE_P (type) && ! TYPE_THIN_POINTER_P (type))
3549         || (TREE_CODE (type) == RECORD_TYPE
3550             && TYPE_JUSTIFIED_MODULAR_P (type)))
3551        && ((INTEGRAL_TYPE_P (etype)
3552             && !(TREE_CODE (etype) == INTEGER_TYPE
3553                  && TYPE_VAX_FLOATING_POINT_P (etype)))
3554            || (POINTER_TYPE_P (etype) && !TYPE_THIN_POINTER_P (etype))
3555            || (TREE_CODE (etype) == RECORD_TYPE
3556                && TYPE_JUSTIFIED_MODULAR_P (etype))))
3557       || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
3558     {
3559       tree rtype = type;
3560
3561       if (TREE_CODE (etype) == INTEGER_TYPE
3562           && TYPE_BIASED_REPRESENTATION_P (etype))
3563         {
3564           tree ntype = copy_type (etype);
3565
3566           TYPE_BIASED_REPRESENTATION_P (ntype) = 0;
3567           TYPE_MAIN_VARIANT (ntype) = ntype;
3568           expr = build1 (NOP_EXPR, ntype, expr);
3569         }
3570
3571       if (TREE_CODE (type) == INTEGER_TYPE
3572           && TYPE_BIASED_REPRESENTATION_P (type))
3573         {
3574           rtype = copy_type (type);
3575           TYPE_BIASED_REPRESENTATION_P (rtype) = 0;
3576           TYPE_MAIN_VARIANT (rtype) = rtype;
3577         }
3578
3579       expr = convert (rtype, expr);
3580       if (type != rtype)
3581         expr = build1 (NOP_EXPR, type, expr);
3582     }
3583
3584   /* If we are converting TO an integral type whose precision is not the
3585      same as its size, first unchecked convert to a record that contains
3586      an object of the output type.  Then extract the field. */
3587   else if (INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
3588            && 0 != compare_tree_int (TYPE_RM_SIZE (type),
3589                                      GET_MODE_BITSIZE (TYPE_MODE (type))))
3590     {
3591       tree rec_type = make_node (RECORD_TYPE);
3592       tree field = create_field_decl (get_identifier ("OBJ"), type,
3593                                       rec_type, 1, 0, 0, 0);
3594
3595       TYPE_FIELDS (rec_type) = field;
3596       layout_type (rec_type);
3597
3598       expr = unchecked_convert (rec_type, expr, notrunc_p);
3599       expr = build_component_ref (expr, NULL_TREE, field, 0);
3600     }
3601
3602   /* Similarly for integral input type whose precision is not equal to its
3603      size.  */
3604   else if (INTEGRAL_TYPE_P (etype) && TYPE_RM_SIZE (etype)
3605       && 0 != compare_tree_int (TYPE_RM_SIZE (etype),
3606                                 GET_MODE_BITSIZE (TYPE_MODE (etype))))
3607     {
3608       tree rec_type = make_node (RECORD_TYPE);
3609       tree field
3610         = create_field_decl (get_identifier ("OBJ"), etype, rec_type,
3611                              1, 0, 0, 0);
3612
3613       TYPE_FIELDS (rec_type) = field;
3614       layout_type (rec_type);
3615
3616       expr = gnat_build_constructor (rec_type, build_tree_list (field, expr));
3617       expr = unchecked_convert (type, expr, notrunc_p);
3618     }
3619
3620   /* We have a special case when we are converting between two
3621      unconstrained array types.  In that case, take the address,
3622      convert the fat pointer types, and dereference.  */
3623   else if (TREE_CODE (etype) == UNCONSTRAINED_ARRAY_TYPE
3624            && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
3625     expr = build_unary_op (INDIRECT_REF, NULL_TREE,
3626                            build1 (VIEW_CONVERT_EXPR, TREE_TYPE (type),
3627                                    build_unary_op (ADDR_EXPR, NULL_TREE,
3628                                                    expr)));
3629   else
3630     {
3631       expr = maybe_unconstrained_array (expr);
3632
3633       /* There's no point in doing two unchecked conversions in a row.  */
3634       if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
3635         expr = TREE_OPERAND (expr, 0);
3636
3637       etype = TREE_TYPE (expr);
3638       expr = build1 (VIEW_CONVERT_EXPR, type, expr);
3639     }
3640
3641   /* If the result is an integral type whose size is not equal to
3642      the size of the underlying machine type, sign- or zero-extend
3643      the result.  We need not do this in the case where the input is
3644      an integral type of the same precision and signedness or if the output
3645      is a biased type or if both the input and output are unsigned.  */
3646   if (!notrunc_p
3647       && INTEGRAL_TYPE_P (type) && TYPE_RM_SIZE (type)
3648       && !(TREE_CODE (type) == INTEGER_TYPE
3649            && TYPE_BIASED_REPRESENTATION_P (type))
3650       && 0 != compare_tree_int (TYPE_RM_SIZE (type),
3651                                 GET_MODE_BITSIZE (TYPE_MODE (type)))
3652       && !(INTEGRAL_TYPE_P (etype)
3653            && TYPE_UNSIGNED (type) == TYPE_UNSIGNED (etype)
3654            && operand_equal_p (TYPE_RM_SIZE (type),
3655                                (TYPE_RM_SIZE (etype) != 0
3656                                 ? TYPE_RM_SIZE (etype) : TYPE_SIZE (etype)),
3657                                0))
3658       && !(TYPE_UNSIGNED (type) && TYPE_UNSIGNED (etype)))
3659     {
3660       tree base_type = gnat_type_for_mode (TYPE_MODE (type),
3661                                            TYPE_UNSIGNED (type));
3662       tree shift_expr
3663         = convert (base_type,
3664                    size_binop (MINUS_EXPR,
3665                                bitsize_int
3666                                (GET_MODE_BITSIZE (TYPE_MODE (type))),
3667                                TYPE_RM_SIZE (type)));
3668       expr
3669         = convert (type,
3670                    build_binary_op (RSHIFT_EXPR, base_type,
3671                                     build_binary_op (LSHIFT_EXPR, base_type,
3672                                                      convert (base_type, expr),
3673                                                      shift_expr),
3674                                     shift_expr));
3675     }
3676
3677   /* An unchecked conversion should never raise Constraint_Error.  The code
3678      below assumes that GCC's conversion routines overflow the same way that
3679      the underlying hardware does.  This is probably true.  In the rare case
3680      when it is false, we can rely on the fact that such conversions are
3681      erroneous anyway.  */
3682   if (TREE_CODE (expr) == INTEGER_CST)
3683     TREE_OVERFLOW (expr) = 0;
3684
3685   /* If the sizes of the types differ and this is an VIEW_CONVERT_EXPR,
3686      show no longer constant.  */
3687   if (TREE_CODE (expr) == VIEW_CONVERT_EXPR
3688       && !operand_equal_p (TYPE_SIZE_UNIT (type), TYPE_SIZE_UNIT (etype),
3689                            OEP_ONLY_CONST))
3690     TREE_CONSTANT (expr) = 0;
3691
3692   return expr;
3693 }
3694 \f
3695 /* Search the chain of currently reachable declarations for a builtin
3696    FUNCTION_DECL node corresponding to function NAME (an IDENTIFIER_NODE).
3697    Return the first node found, if any, or NULL_TREE otherwise.  */
3698 tree
3699 builtin_decl_for (tree name __attribute__ ((unused)))
3700 {
3701   /* ??? not clear yet how to implement this function in tree-ssa, so
3702      return NULL_TREE for now */
3703   return NULL_TREE;
3704 }
3705
3706 /* Return the appropriate GCC tree code for the specified GNAT type,
3707    the latter being a record type as predicated by Is_Record_Type.  */
3708
3709 enum tree_code
3710 tree_code_for_record_type (Entity_Id gnat_type)
3711 {
3712   Node_Id component_list
3713     = Component_List (Type_Definition
3714                       (Declaration_Node
3715                        (Implementation_Base_Type (gnat_type))));
3716   Node_Id component;
3717
3718  /* Make this a UNION_TYPE unless it's either not an Unchecked_Union or
3719     we have a non-discriminant field outside a variant.  In either case,
3720     it's a RECORD_TYPE.  */
3721
3722   if (!Is_Unchecked_Union (gnat_type))
3723     return RECORD_TYPE;
3724
3725   for (component = First_Non_Pragma (Component_Items (component_list));
3726        Present (component);
3727        component = Next_Non_Pragma (component))
3728     if (Ekind (Defining_Entity (component)) == E_Component)
3729       return RECORD_TYPE;
3730
3731   return UNION_TYPE;
3732 }
3733
3734 /* Build a global constructor or destructor function.  METHOD_TYPE gives
3735    the type of the function and VEC points to the vector of constructor
3736    or destructor functions to be invoked.  FIXME: Migrate into cgraph.  */
3737
3738 static void
3739 build_global_cdtor (int method_type, tree *vec, int len)
3740 {
3741   tree body = NULL_TREE;
3742   int i;
3743
3744   for (i = 0; i < len; i++)
3745     {
3746       tree fntype = TREE_TYPE (vec[i]);
3747       tree fnaddr = build1 (ADDR_EXPR, build_pointer_type (fntype), vec[i]);
3748       tree fncall = build3 (CALL_EXPR, TREE_TYPE (fntype), fnaddr, NULL_TREE,
3749                             NULL_TREE);
3750       append_to_statement_list (fncall, &body);
3751     }
3752
3753   if (body)
3754     cgraph_build_static_cdtor (method_type, body, DEFAULT_INIT_PRIORITY);
3755 }
3756
3757 /* Perform final processing on global variables.  */
3758
3759 void
3760 gnat_write_global_declarations (void)
3761 {
3762   /* Generate functions to call static constructors and destructors
3763      for targets that do not support .ctors/.dtors sections.  These
3764      functions have magic names which are detected by collect2.  */
3765   build_global_cdtor ('I', VEC_address (tree, static_ctors),
3766                            VEC_length (tree, static_ctors));
3767   build_global_cdtor ('D', VEC_address (tree, static_dtors),
3768                            VEC_length (tree, static_dtors));
3769
3770   /* Proceed to optimize and emit assembly.
3771      FIXME: shouldn't be the front end's responsibility to call this.  */
3772   cgraph_optimize ();
3773
3774   /* Emit debug info for all global declarations.  */
3775   emit_debug_global_declarations (VEC_address (tree, global_decls),
3776                                   VEC_length (tree, global_decls));
3777 }
3778
3779 #include "gt-ada-utils.h"
3780 #include "gtype-ada.h"