OSDN Git Service

* gcc-interface/gigi.h (create_label_decl): Adjust.
[pf3gnuchains/gcc-fork.git] / gcc / ada / gcc-interface / trans.c
1 /****************************************************************************
2  *                                                                          *
3  *                         GNAT COMPILER COMPONENTS                         *
4  *                                                                          *
5  *                                T R A N S                                 *
6  *                                                                          *
7  *                          C Implementation File                           *
8  *                                                                          *
9  *          Copyright (C) 1992-2012, Free Software Foundation, Inc.         *
10  *                                                                          *
11  * GNAT is free software;  you can  redistribute it  and/or modify it under *
12  * terms of the  GNU General Public License as published  by the Free Soft- *
13  * ware  Foundation;  either version 3,  or (at your option) any later ver- *
14  * sion.  GNAT is distributed in the hope that it will be useful, but WITH- *
15  * OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY *
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License *
17  * for  more details.  You should have  received  a copy of the GNU General *
18  * Public License  distributed  with GNAT;  see file  COPYING3.  If not see *
19  * <http://www.gnu.org/licenses/>.                                          *
20  *                                                                          *
21  * GNAT was originally developed  by the GNAT team at  New York University. *
22  * Extensive contributions were provided by Ada Core Technologies Inc.      *
23  *                                                                          *
24  ****************************************************************************/
25
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "tm.h"
30 #include "tree.h"
31 #include "flags.h"
32 #include "ggc.h"
33 #include "output.h"
34 #include "libfuncs.h"   /* For set_stack_check_libfunc.  */
35 #include "tree-iterator.h"
36 #include "gimple.h"
37 #include "bitmap.h"
38 #include "cgraph.h"
39
40 #include "ada.h"
41 #include "adadecode.h"
42 #include "types.h"
43 #include "atree.h"
44 #include "elists.h"
45 #include "namet.h"
46 #include "nlists.h"
47 #include "snames.h"
48 #include "stringt.h"
49 #include "uintp.h"
50 #include "urealp.h"
51 #include "fe.h"
52 #include "sinfo.h"
53 #include "einfo.h"
54 #include "gadaint.h"
55 #include "ada-tree.h"
56 #include "gigi.h"
57
58 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
59    for fear of running out of stack space.  If we need more, we use xmalloc
60    instead.  */
61 #define ALLOCA_THRESHOLD 1000
62
63 /* Let code below know whether we are targetting VMS without need of
64    intrusive preprocessor directives.  */
65 #ifndef TARGET_ABI_OPEN_VMS
66 #define TARGET_ABI_OPEN_VMS 0
67 #endif
68
69 /* In configurations where blocks have no end_locus attached, just
70    sink assignments into a dummy global.  */
71 #ifndef BLOCK_SOURCE_END_LOCATION
72 static location_t block_end_locus_sink;
73 #define BLOCK_SOURCE_END_LOCATION(BLOCK) block_end_locus_sink
74 #endif
75
76 /* For efficient float-to-int rounding, it is necessary to know whether
77    floating-point arithmetic may use wider intermediate results.  When
78    FP_ARITH_MAY_WIDEN is not defined, be conservative and only assume
79    that arithmetic does not widen if double precision is emulated.  */
80 #ifndef FP_ARITH_MAY_WIDEN
81 #if defined(HAVE_extendsfdf2)
82 #define FP_ARITH_MAY_WIDEN HAVE_extendsfdf2
83 #else
84 #define FP_ARITH_MAY_WIDEN 0
85 #endif
86 #endif
87
88 /* Pointers to front-end tables accessed through macros.  */
89 struct Node *Nodes_Ptr;
90 Node_Id *Next_Node_Ptr;
91 Node_Id *Prev_Node_Ptr;
92 struct Elist_Header *Elists_Ptr;
93 struct Elmt_Item *Elmts_Ptr;
94 struct String_Entry *Strings_Ptr;
95 Char_Code *String_Chars_Ptr;
96 struct List_Header *List_Headers_Ptr;
97
98 /* Highest number in the front-end node table.  */
99 int max_gnat_nodes;
100
101 /* Current node being treated, in case abort called.  */
102 Node_Id error_gnat_node;
103
104 /* True when gigi is being called on an analyzed but unexpanded
105    tree, and the only purpose of the call is to properly annotate
106    types with representation information.  */
107 bool type_annotate_only;
108
109 /* Current filename without path.  */
110 const char *ref_filename;
111
112 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
113    of unconstrained array IN parameters to avoid emitting a great deal of
114    redundant instructions to recompute them each time.  */
115 struct GTY (()) parm_attr_d {
116   int id; /* GTY doesn't like Entity_Id.  */
117   int dim;
118   tree first;
119   tree last;
120   tree length;
121 };
122
123 typedef struct parm_attr_d *parm_attr;
124
125 DEF_VEC_P(parm_attr);
126 DEF_VEC_ALLOC_P(parm_attr,gc);
127
128 struct GTY(()) language_function {
129   VEC(parm_attr,gc) *parm_attr_cache;
130   bitmap named_ret_val;
131   VEC(tree,gc) *other_ret_val;
132   int gnat_ret;
133 };
134
135 #define f_parm_attr_cache \
136   DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
137
138 #define f_named_ret_val \
139   DECL_STRUCT_FUNCTION (current_function_decl)->language->named_ret_val
140
141 #define f_other_ret_val \
142   DECL_STRUCT_FUNCTION (current_function_decl)->language->other_ret_val
143
144 #define f_gnat_ret \
145   DECL_STRUCT_FUNCTION (current_function_decl)->language->gnat_ret
146
147 /* A structure used to gather together information about a statement group.
148    We use this to gather related statements, for example the "then" part
149    of a IF.  In the case where it represents a lexical scope, we may also
150    have a BLOCK node corresponding to it and/or cleanups.  */
151
152 struct GTY((chain_next ("%h.previous"))) stmt_group {
153   struct stmt_group *previous;  /* Previous code group.  */
154   tree stmt_list;               /* List of statements for this code group.  */
155   tree block;                   /* BLOCK for this code group, if any.  */
156   tree cleanups;                /* Cleanups for this code group, if any.  */
157 };
158
159 static GTY(()) struct stmt_group *current_stmt_group;
160
161 /* List of unused struct stmt_group nodes.  */
162 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
163
164 /* A structure used to record information on elaboration procedures
165    we've made and need to process.
166
167    ??? gnat_node should be Node_Id, but gengtype gets confused.  */
168
169 struct GTY((chain_next ("%h.next"))) elab_info {
170   struct elab_info *next;       /* Pointer to next in chain.  */
171   tree elab_proc;               /* Elaboration procedure.  */
172   int gnat_node;                /* The N_Compilation_Unit.  */
173 };
174
175 static GTY(()) struct elab_info *elab_info_list;
176
177 /* Stack of exception pointer variables.  Each entry is the VAR_DECL
178    that stores the address of the raised exception.  Nonzero means we
179    are in an exception handler.  Not used in the zero-cost case.  */
180 static GTY(()) VEC(tree,gc) *gnu_except_ptr_stack;
181
182 /* In ZCX case, current exception pointer.  Used to re-raise it.  */
183 static GTY(()) tree gnu_incoming_exc_ptr;
184
185 /* Stack for storing the current elaboration procedure decl.  */
186 static GTY(()) VEC(tree,gc) *gnu_elab_proc_stack;
187
188 /* Stack of labels to be used as a goto target instead of a return in
189    some functions.  See processing for N_Subprogram_Body.  */
190 static GTY(()) VEC(tree,gc) *gnu_return_label_stack;
191
192 /* Stack of variable for the return value of a function with copy-in/copy-out
193    parameters.  See processing for N_Subprogram_Body.  */
194 static GTY(()) VEC(tree,gc) *gnu_return_var_stack;
195
196 /* Structure used to record information for a range check.  */
197 struct GTY(()) range_check_info_d {
198   tree low_bound;
199   tree high_bound;
200   tree type;
201   tree invariant_cond;
202 };
203
204 typedef struct range_check_info_d *range_check_info;
205
206 DEF_VEC_P(range_check_info);
207 DEF_VEC_ALLOC_P(range_check_info,gc);
208
209 /* Structure used to record information for a loop.  */
210 struct GTY(()) loop_info_d {
211   tree label;
212   tree loop_var;
213   VEC(range_check_info,gc) *checks;
214 };
215
216 typedef struct loop_info_d *loop_info;
217
218 DEF_VEC_P(loop_info);
219 DEF_VEC_ALLOC_P(loop_info,gc);
220
221 /* Stack of loop_info structures associated with LOOP_STMT nodes.  */
222 static GTY(()) VEC(loop_info,gc) *gnu_loop_stack;
223
224 /* The stacks for N_{Push,Pop}_*_Label.  */
225 static GTY(()) VEC(tree,gc) *gnu_constraint_error_label_stack;
226 static GTY(()) VEC(tree,gc) *gnu_storage_error_label_stack;
227 static GTY(()) VEC(tree,gc) *gnu_program_error_label_stack;
228
229 /* Map GNAT tree codes to GCC tree codes for simple expressions.  */
230 static enum tree_code gnu_codes[Number_Node_Kinds];
231
232 static void init_code_table (void);
233 static void Compilation_Unit_to_gnu (Node_Id);
234 static void record_code_position (Node_Id);
235 static void insert_code_for (Node_Id);
236 static void add_cleanup (tree, Node_Id);
237 static void add_stmt_list (List_Id);
238 static void push_exception_label_stack (VEC(tree,gc) **, Entity_Id);
239 static tree build_stmt_group (List_Id, bool);
240 static enum gimplify_status gnat_gimplify_stmt (tree *);
241 static void elaborate_all_entities (Node_Id);
242 static void process_freeze_entity (Node_Id);
243 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
244 static tree emit_range_check (tree, Node_Id, Node_Id);
245 static tree emit_index_check (tree, tree, tree, tree, Node_Id);
246 static tree emit_check (tree, tree, int, Node_Id);
247 static tree build_unary_op_trapv (enum tree_code, tree, tree, Node_Id);
248 static tree build_binary_op_trapv (enum tree_code, tree, tree, tree, Node_Id);
249 static tree convert_with_check (Entity_Id, tree, bool, bool, bool, Node_Id);
250 static bool addressable_p (tree, tree);
251 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
252 static tree extract_values (tree, tree);
253 static tree pos_to_constructor (Node_Id, tree, Entity_Id);
254 static tree maybe_implicit_deref (tree);
255 static void set_expr_location_from_node (tree, Node_Id);
256 static bool set_end_locus_from_node (tree, Node_Id);
257 static void set_gnu_expr_location_from_node (tree, Node_Id);
258 static int lvalue_required_p (Node_Id, tree, bool, bool, bool);
259 static tree build_raise_check (int, enum exception_info_kind);
260 static tree create_init_temporary (const char *, tree, tree *, Node_Id);
261
262 /* Hooks for debug info back-ends, only supported and used in a restricted set
263    of configurations.  */
264 static const char *extract_encoding (const char *) ATTRIBUTE_UNUSED;
265 static const char *decode_name (const char *) ATTRIBUTE_UNUSED;
266 \f
267 /* This is the main program of the back-end.  It sets up all the table
268    structures and then generates code.  */
269
270 void
271 gigi (Node_Id gnat_root, int max_gnat_node, int number_name ATTRIBUTE_UNUSED,
272       struct Node *nodes_ptr, Node_Id *next_node_ptr, Node_Id *prev_node_ptr,
273       struct Elist_Header *elists_ptr, struct Elmt_Item *elmts_ptr,
274       struct String_Entry *strings_ptr, Char_Code *string_chars_ptr,
275       struct List_Header *list_headers_ptr, Nat number_file,
276       struct File_Info_Type *file_info_ptr,
277       Entity_Id standard_boolean, Entity_Id standard_integer,
278       Entity_Id standard_character, Entity_Id standard_long_long_float,
279       Entity_Id standard_exception_type, Int gigi_operating_mode)
280 {
281   Entity_Id gnat_literal;
282   tree long_long_float_type, exception_type, t, ftype;
283   tree int64_type = gnat_type_for_size (64, 0);
284   struct elab_info *info;
285   int i;
286
287   max_gnat_nodes = max_gnat_node;
288
289   Nodes_Ptr = nodes_ptr;
290   Next_Node_Ptr = next_node_ptr;
291   Prev_Node_Ptr = prev_node_ptr;
292   Elists_Ptr = elists_ptr;
293   Elmts_Ptr = elmts_ptr;
294   Strings_Ptr = strings_ptr;
295   String_Chars_Ptr = string_chars_ptr;
296   List_Headers_Ptr = list_headers_ptr;
297
298   type_annotate_only = (gigi_operating_mode == 1);
299
300   for (i = 0; i < number_file; i++)
301     {
302       /* Use the identifier table to make a permanent copy of the filename as
303          the name table gets reallocated after Gigi returns but before all the
304          debugging information is output.  The __gnat_to_canonical_file_spec
305          call translates filenames from pragmas Source_Reference that contain
306          host style syntax not understood by gdb.  */
307       const char *filename
308         = IDENTIFIER_POINTER
309            (get_identifier
310             (__gnat_to_canonical_file_spec
311              (Get_Name_String (file_info_ptr[i].File_Name))));
312
313       /* We rely on the order isomorphism between files and line maps.  */
314       gcc_assert ((int) LINEMAPS_ORDINARY_USED (line_table) == i);
315
316       /* We create the line map for a source file at once, with a fixed number
317          of columns chosen to avoid jumping over the next power of 2.  */
318       linemap_add (line_table, LC_ENTER, 0, filename, 1);
319       linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
320       linemap_position_for_column (line_table, 252 - 1);
321       linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
322     }
323
324   gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
325
326   /* Declare the name of the compilation unit as the first global
327      name in order to make the middle-end fully deterministic.  */
328   t = create_concat_name (Defining_Entity (Unit (gnat_root)), NULL);
329   first_global_object_name = ggc_strdup (IDENTIFIER_POINTER (t));
330
331   /* Initialize ourselves.  */
332   init_code_table ();
333   init_gnat_to_gnu ();
334   init_dummy_type ();
335
336   /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
337      errors.  */
338   if (type_annotate_only)
339     {
340       TYPE_SIZE (void_type_node) = bitsize_zero_node;
341       TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
342     }
343
344   /* Enable GNAT stack checking method if needed */
345   if (!Stack_Check_Probes_On_Target)
346     set_stack_check_libfunc ("_gnat_stack_check");
347
348   /* Retrieve alignment settings.  */
349   double_float_alignment = get_target_double_float_alignment ();
350   double_scalar_alignment = get_target_double_scalar_alignment ();
351
352   /* Record the builtin types.  Define `integer' and `character' first so that
353      dbx will output them first.  */
354   record_builtin_type ("integer", integer_type_node, false);
355   record_builtin_type ("character", unsigned_char_type_node, false);
356   record_builtin_type ("boolean", boolean_type_node, false);
357   record_builtin_type ("void", void_type_node, false);
358
359   /* Save the type we made for integer as the type for Standard.Integer.  */
360   save_gnu_tree (Base_Type (standard_integer),
361                  TYPE_NAME (integer_type_node),
362                  false);
363
364   /* Likewise for character as the type for Standard.Character.  */
365   save_gnu_tree (Base_Type (standard_character),
366                  TYPE_NAME (unsigned_char_type_node),
367                  false);
368
369   /* Likewise for boolean as the type for Standard.Boolean.  */
370   save_gnu_tree (Base_Type (standard_boolean),
371                  TYPE_NAME (boolean_type_node),
372                  false);
373   gnat_literal = First_Literal (Base_Type (standard_boolean));
374   t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
375   gcc_assert (t == boolean_false_node);
376   t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
377                        boolean_type_node, t, true, false, false, false,
378                        NULL, gnat_literal);
379   DECL_IGNORED_P (t) = 1;
380   save_gnu_tree (gnat_literal, t, false);
381   gnat_literal = Next_Literal (gnat_literal);
382   t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
383   gcc_assert (t == boolean_true_node);
384   t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
385                        boolean_type_node, t, true, false, false, false,
386                        NULL, gnat_literal);
387   DECL_IGNORED_P (t) = 1;
388   save_gnu_tree (gnat_literal, t, false);
389
390   void_ftype = build_function_type_list (void_type_node, NULL_TREE);
391   ptr_void_ftype = build_pointer_type (void_ftype);
392
393   /* Now declare run-time functions.  */
394   ftype = build_function_type_list (ptr_void_type_node, sizetype, NULL_TREE);
395
396   /* malloc is a function declaration tree for a function to allocate
397      memory.  */
398   malloc_decl
399     = create_subprog_decl (get_identifier ("__gnat_malloc"), NULL_TREE,
400                            ftype, NULL_TREE, false, true, true, true, NULL,
401                            Empty);
402   DECL_IS_MALLOC (malloc_decl) = 1;
403
404   /* malloc32 is a function declaration tree for a function to allocate
405      32-bit memory on a 64-bit system.  Needed only on 64-bit VMS.  */
406   malloc32_decl
407     = create_subprog_decl (get_identifier ("__gnat_malloc32"), NULL_TREE,
408                            ftype, NULL_TREE, false, true, true, true, NULL,
409                            Empty);
410   DECL_IS_MALLOC (malloc32_decl) = 1;
411
412   /* free is a function declaration tree for a function to free memory.  */
413   free_decl
414     = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
415                            build_function_type_list (void_type_node,
416                                                      ptr_void_type_node,
417                                                      NULL_TREE),
418                            NULL_TREE, false, true, true, true, NULL, Empty);
419
420   /* This is used for 64-bit multiplication with overflow checking.  */
421   mulv64_decl
422     = create_subprog_decl (get_identifier ("__gnat_mulv64"), NULL_TREE,
423                            build_function_type_list (int64_type, int64_type,
424                                                      int64_type, NULL_TREE),
425                            NULL_TREE, false, true, true, true, NULL, Empty);
426
427   /* Name of the _Parent field in tagged record types.  */
428   parent_name_id = get_identifier (Get_Name_String (Name_uParent));
429
430   /* Name of the Exception_Data type defined in System.Standard_Library.  */
431   exception_data_name_id
432     = get_identifier ("system__standard_library__exception_data");
433
434   /* Make the types and functions used for exception processing.  */
435   jmpbuf_type
436     = build_array_type (gnat_type_for_mode (Pmode, 0),
437                         build_index_type (size_int (5)));
438   record_builtin_type ("JMPBUF_T", jmpbuf_type, true);
439   jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
440
441   /* Functions to get and set the jumpbuf pointer for the current thread.  */
442   get_jmpbuf_decl
443     = create_subprog_decl
444       (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
445        NULL_TREE, build_function_type_list (jmpbuf_ptr_type, NULL_TREE),
446        NULL_TREE, false, true, true, true, NULL, Empty);
447   DECL_IGNORED_P (get_jmpbuf_decl) = 1;
448
449   set_jmpbuf_decl
450     = create_subprog_decl
451       (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
452        NULL_TREE, build_function_type_list (void_type_node, jmpbuf_ptr_type,
453                                             NULL_TREE),
454        NULL_TREE, false, true, true, true, NULL, Empty);
455   DECL_IGNORED_P (set_jmpbuf_decl) = 1;
456
457   /* setjmp returns an integer and has one operand, which is a pointer to
458      a jmpbuf.  */
459   setjmp_decl
460     = create_subprog_decl
461       (get_identifier ("__builtin_setjmp"), NULL_TREE,
462        build_function_type_list (integer_type_node, jmpbuf_ptr_type,
463                                  NULL_TREE),
464        NULL_TREE, false, true, true, true, NULL, Empty);
465   DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
466   DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
467
468   /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
469      address.  */
470   update_setjmp_buf_decl
471     = create_subprog_decl
472       (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
473        build_function_type_list (void_type_node, jmpbuf_ptr_type, NULL_TREE),
474        NULL_TREE, false, true, true, true, NULL, Empty);
475   DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
476   DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
477
478   /* Hooks to call when entering/leaving an exception handler.  */
479   ftype
480     = build_function_type_list (void_type_node, ptr_void_type_node, NULL_TREE);
481
482   begin_handler_decl
483     = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
484                            ftype, NULL_TREE, false, true, true, true, NULL,
485                            Empty);
486   DECL_IGNORED_P (begin_handler_decl) = 1;
487
488   end_handler_decl
489     = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
490                            ftype, NULL_TREE, false, true, true, true, NULL,
491                            Empty);
492   DECL_IGNORED_P (end_handler_decl) = 1;
493
494   reraise_zcx_decl
495     = create_subprog_decl (get_identifier ("__gnat_reraise_zcx"), NULL_TREE,
496                            ftype, NULL_TREE, false, true, true, true, NULL,
497                            Empty);
498   DECL_IGNORED_P (reraise_zcx_decl) = 1;
499
500   /* If in no exception handlers mode, all raise statements are redirected to
501      __gnat_last_chance_handler.  No need to redefine raise_nodefer_decl since
502      this procedure will never be called in this mode.  */
503   if (No_Exception_Handlers_Set ())
504     {
505       tree decl
506         = create_subprog_decl
507           (get_identifier ("__gnat_last_chance_handler"), NULL_TREE,
508            build_function_type_list (void_type_node,
509                                      build_pointer_type
510                                      (unsigned_char_type_node),
511                                      integer_type_node, NULL_TREE),
512            NULL_TREE, false, true, true, true, NULL, Empty);
513       TREE_THIS_VOLATILE (decl) = 1;
514       TREE_SIDE_EFFECTS (decl) = 1;
515       TREE_TYPE (decl)
516         = build_qualified_type (TREE_TYPE (decl), TYPE_QUAL_VOLATILE);
517       for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
518         gnat_raise_decls[i] = decl;
519     }
520   else
521     {
522       /* Otherwise, make one decl for each exception reason.  */
523       for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
524         gnat_raise_decls[i] = build_raise_check (i, exception_simple);
525       for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls_ext); i++)
526         gnat_raise_decls_ext[i]
527           = build_raise_check (i,
528                                i == CE_Index_Check_Failed
529                                || i == CE_Range_Check_Failed
530                                || i == CE_Invalid_Data
531                                ? exception_range : exception_column);
532     }
533
534   /* Set the types that GCC and Gigi use from the front end.  */
535   exception_type
536     = gnat_to_gnu_entity (Base_Type (standard_exception_type),  NULL_TREE, 0);
537   except_type_node = TREE_TYPE (exception_type);
538
539   /* Make other functions used for exception processing.  */
540   get_excptr_decl
541     = create_subprog_decl
542       (get_identifier ("system__soft_links__get_gnat_exception"), NULL_TREE,
543        build_function_type_list (build_pointer_type (except_type_node),
544                                  NULL_TREE),
545      NULL_TREE, false, true, true, true, NULL, Empty);
546
547   raise_nodefer_decl
548     = create_subprog_decl
549       (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE,
550        build_function_type_list (void_type_node,
551                                  build_pointer_type (except_type_node),
552                                  NULL_TREE),
553        NULL_TREE, false, true, true, true, NULL, Empty);
554
555   /* Indicate that it never returns.  */
556   TREE_THIS_VOLATILE (raise_nodefer_decl) = 1;
557   TREE_SIDE_EFFECTS (raise_nodefer_decl) = 1;
558   TREE_TYPE (raise_nodefer_decl)
559     = build_qualified_type (TREE_TYPE (raise_nodefer_decl),
560                             TYPE_QUAL_VOLATILE);
561
562   /* Build the special descriptor type and its null node if needed.  */
563   if (TARGET_VTABLE_USES_DESCRIPTORS)
564     {
565       tree null_node = fold_convert (ptr_void_ftype, null_pointer_node);
566       tree field_list = NULL_TREE;
567       int j;
568       VEC(constructor_elt,gc) *null_vec = NULL;
569       constructor_elt *elt;
570
571       fdesc_type_node = make_node (RECORD_TYPE);
572       VEC_safe_grow (constructor_elt, gc, null_vec,
573                      TARGET_VTABLE_USES_DESCRIPTORS);
574       elt = (VEC_address (constructor_elt,null_vec)
575              + TARGET_VTABLE_USES_DESCRIPTORS - 1);
576
577       for (j = 0; j < TARGET_VTABLE_USES_DESCRIPTORS; j++)
578         {
579           tree field
580             = create_field_decl (NULL_TREE, ptr_void_ftype, fdesc_type_node,
581                                  NULL_TREE, NULL_TREE, 0, 1);
582           DECL_CHAIN (field) = field_list;
583           field_list = field;
584           elt->index = field;
585           elt->value = null_node;
586           elt--;
587         }
588
589       finish_record_type (fdesc_type_node, nreverse (field_list), 0, false);
590       record_builtin_type ("descriptor", fdesc_type_node, true);
591       null_fdesc_node = gnat_build_constructor (fdesc_type_node, null_vec);
592     }
593
594   long_long_float_type
595     = gnat_to_gnu_entity (Base_Type (standard_long_long_float), NULL_TREE, 0);
596
597   if (TREE_CODE (TREE_TYPE (long_long_float_type)) == INTEGER_TYPE)
598     {
599       /* In this case, the builtin floating point types are VAX float,
600          so make up a type for use.  */
601       longest_float_type_node = make_node (REAL_TYPE);
602       TYPE_PRECISION (longest_float_type_node) = LONG_DOUBLE_TYPE_SIZE;
603       layout_type (longest_float_type_node);
604       record_builtin_type ("longest float type", longest_float_type_node,
605                            false);
606     }
607   else
608     longest_float_type_node = TREE_TYPE (long_long_float_type);
609
610   /* Dummy objects to materialize "others" and "all others" in the exception
611      tables.  These are exported by a-exexpr-gcc.adb, so see this unit for
612      the types to use.  */
613   others_decl
614     = create_var_decl (get_identifier ("OTHERS"),
615                        get_identifier ("__gnat_others_value"),
616                        integer_type_node, NULL_TREE, true, false, true, false,
617                        NULL, Empty);
618
619   all_others_decl
620     = create_var_decl (get_identifier ("ALL_OTHERS"),
621                        get_identifier ("__gnat_all_others_value"),
622                        integer_type_node, NULL_TREE, true, false, true, false,
623                        NULL, Empty);
624
625   main_identifier_node = get_identifier ("main");
626
627   /* Install the builtins we might need, either internally or as
628      user available facilities for Intrinsic imports.  */
629   gnat_install_builtins ();
630
631   VEC_safe_push (tree, gc, gnu_except_ptr_stack, NULL_TREE);
632   VEC_safe_push (tree, gc, gnu_constraint_error_label_stack, NULL_TREE);
633   VEC_safe_push (tree, gc, gnu_storage_error_label_stack, NULL_TREE);
634   VEC_safe_push (tree, gc, gnu_program_error_label_stack, NULL_TREE);
635
636   /* Process any Pragma Ident for the main unit.  */
637 #ifdef ASM_OUTPUT_IDENT
638   if (Present (Ident_String (Main_Unit)))
639     ASM_OUTPUT_IDENT
640       (asm_out_file,
641        TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
642 #endif
643
644   /* If we are using the GCC exception mechanism, let GCC know.  */
645   if (Exception_Mechanism == Back_End_Exceptions)
646     gnat_init_gcc_eh ();
647
648   /* Now translate the compilation unit proper.  */
649   Compilation_Unit_to_gnu (gnat_root);
650
651   /* Finally see if we have any elaboration procedures to deal with.  */
652   for (info = elab_info_list; info; info = info->next)
653     {
654       tree gnu_body = DECL_SAVED_TREE (info->elab_proc), gnu_stmts;
655
656       /* We should have a BIND_EXPR but it may not have any statements in it.
657          If it doesn't have any, we have nothing to do except for setting the
658          flag on the GNAT node.  Otherwise, process the function as others.  */
659       gnu_stmts = gnu_body;
660       if (TREE_CODE (gnu_stmts) == BIND_EXPR)
661         gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
662       if (!gnu_stmts || !STATEMENT_LIST_HEAD (gnu_stmts))
663         Set_Has_No_Elaboration_Code (info->gnat_node, 1);
664       else
665         {
666           begin_subprog_body (info->elab_proc);
667           end_subprog_body (gnu_body);
668           rest_of_subprog_body_compilation (info->elab_proc);
669         }
670     }
671
672   /* We cannot track the location of errors past this point.  */
673   error_gnat_node = Empty;
674 }
675 \f
676 /* Return a subprogram decl corresponding to __gnat_rcheck_xx for the given
677    CHECK if KIND is EXCEPTION_SIMPLE, or else to __gnat_rcheck_xx_ext.  */
678
679 static tree
680 build_raise_check (int check, enum exception_info_kind kind)
681 {
682   char name[21];
683   tree result, ftype;
684
685   if (kind == exception_simple)
686     {
687       sprintf (name, "__gnat_rcheck_%.2d", check);
688       ftype
689         = build_function_type_list (void_type_node,
690                                     build_pointer_type
691                                     (unsigned_char_type_node),
692                                     integer_type_node, NULL_TREE);
693     }
694   else
695     {
696       tree t = (kind == exception_column ? NULL_TREE : integer_type_node);
697       sprintf (name, "__gnat_rcheck_%.2d_ext", check);
698       ftype
699         = build_function_type_list (void_type_node,
700                                     build_pointer_type
701                                     (unsigned_char_type_node),
702                                     integer_type_node, integer_type_node,
703                                     t, t, NULL_TREE);
704     }
705
706   result
707     = create_subprog_decl (get_identifier (name), NULL_TREE, ftype, NULL_TREE,
708                            false, true, true, true, NULL, Empty);
709
710   /* Indicate that it never returns.  */
711   TREE_THIS_VOLATILE (result) = 1;
712   TREE_SIDE_EFFECTS (result) = 1;
713   TREE_TYPE (result)
714     = build_qualified_type (TREE_TYPE (result), TYPE_QUAL_VOLATILE);
715
716   return result;
717 }
718 \f
719 /* Return a positive value if an lvalue is required for GNAT_NODE, which is
720    an N_Attribute_Reference.  */
721
722 static int
723 lvalue_required_for_attribute_p (Node_Id gnat_node)
724 {
725   switch (Get_Attribute_Id (Attribute_Name (gnat_node)))
726     {
727     case Attr_Pos:
728     case Attr_Val:
729     case Attr_Pred:
730     case Attr_Succ:
731     case Attr_First:
732     case Attr_Last:
733     case Attr_Range_Length:
734     case Attr_Length:
735     case Attr_Object_Size:
736     case Attr_Value_Size:
737     case Attr_Component_Size:
738     case Attr_Max_Size_In_Storage_Elements:
739     case Attr_Min:
740     case Attr_Max:
741     case Attr_Null_Parameter:
742     case Attr_Passed_By_Reference:
743     case Attr_Mechanism_Code:
744       return 0;
745
746     case Attr_Address:
747     case Attr_Access:
748     case Attr_Unchecked_Access:
749     case Attr_Unrestricted_Access:
750     case Attr_Code_Address:
751     case Attr_Pool_Address:
752     case Attr_Size:
753     case Attr_Alignment:
754     case Attr_Bit_Position:
755     case Attr_Position:
756     case Attr_First_Bit:
757     case Attr_Last_Bit:
758     case Attr_Bit:
759     case Attr_Asm_Input:
760     case Attr_Asm_Output:
761     default:
762       return 1;
763     }
764 }
765
766 /* Return a positive value if an lvalue is required for GNAT_NODE.  GNU_TYPE
767    is the type that will be used for GNAT_NODE in the translated GNU tree.
768    CONSTANT indicates whether the underlying object represented by GNAT_NODE
769    is constant in the Ada sense.  If it is, ADDRESS_OF_CONSTANT indicates
770    whether its value is the address of a constant and ALIASED whether it is
771    aliased.  If it isn't, ADDRESS_OF_CONSTANT and ALIASED are ignored.
772
773    The function climbs up the GNAT tree starting from the node and returns 1
774    upon encountering a node that effectively requires an lvalue downstream.
775    It returns int instead of bool to facilitate usage in non-purely binary
776    logic contexts.  */
777
778 static int
779 lvalue_required_p (Node_Id gnat_node, tree gnu_type, bool constant,
780                    bool address_of_constant, bool aliased)
781 {
782   Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
783
784   switch (Nkind (gnat_parent))
785     {
786     case N_Reference:
787       return 1;
788
789     case N_Attribute_Reference:
790       return lvalue_required_for_attribute_p (gnat_parent);
791
792     case N_Parameter_Association:
793     case N_Function_Call:
794     case N_Procedure_Call_Statement:
795       /* If the parameter is by reference, an lvalue is required.  */
796       return (!constant
797               || must_pass_by_ref (gnu_type)
798               || default_pass_by_ref (gnu_type));
799
800     case N_Indexed_Component:
801       /* Only the array expression can require an lvalue.  */
802       if (Prefix (gnat_parent) != gnat_node)
803         return 0;
804
805       /* ??? Consider that referencing an indexed component with a
806          non-constant index forces the whole aggregate to memory.
807          Note that N_Integer_Literal is conservative, any static
808          expression in the RM sense could probably be accepted.  */
809       for (gnat_temp = First (Expressions (gnat_parent));
810            Present (gnat_temp);
811            gnat_temp = Next (gnat_temp))
812         if (Nkind (gnat_temp) != N_Integer_Literal)
813           return 1;
814
815       /* ... fall through ... */
816
817     case N_Slice:
818       /* Only the array expression can require an lvalue.  */
819       if (Prefix (gnat_parent) != gnat_node)
820         return 0;
821
822       aliased |= Has_Aliased_Components (Etype (gnat_node));
823       return lvalue_required_p (gnat_parent, gnu_type, constant,
824                                 address_of_constant, aliased);
825
826     case N_Selected_Component:
827       aliased |= Is_Aliased (Entity (Selector_Name (gnat_parent)));
828       return lvalue_required_p (gnat_parent, gnu_type, constant,
829                                 address_of_constant, aliased);
830
831     case N_Object_Renaming_Declaration:
832       /* We need to make a real renaming only if the constant object is
833          aliased or if we may use a renaming pointer; otherwise we can
834          optimize and return the rvalue.  We make an exception if the object
835          is an identifier since in this case the rvalue can be propagated
836          attached to the CONST_DECL.  */
837       return (!constant
838               || aliased
839               /* This should match the constant case of the renaming code.  */
840               || Is_Composite_Type
841                  (Underlying_Type (Etype (Name (gnat_parent))))
842               || Nkind (Name (gnat_parent)) == N_Identifier);
843
844     case N_Object_Declaration:
845       /* We cannot use a constructor if this is an atomic object because
846          the actual assignment might end up being done component-wise.  */
847       return (!constant
848               ||(Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
849                  && Is_Atomic (Defining_Entity (gnat_parent)))
850               /* We don't use a constructor if this is a class-wide object
851                  because the effective type of the object is the equivalent
852                  type of the class-wide subtype and it smashes most of the
853                  data into an array of bytes to which we cannot convert.  */
854               || Ekind ((Etype (Defining_Entity (gnat_parent))))
855                  == E_Class_Wide_Subtype);
856
857     case N_Assignment_Statement:
858       /* We cannot use a constructor if the LHS is an atomic object because
859          the actual assignment might end up being done component-wise.  */
860       return (!constant
861               || Name (gnat_parent) == gnat_node
862               || (Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
863                   && Is_Atomic (Entity (Name (gnat_parent)))));
864
865     case N_Unchecked_Type_Conversion:
866         if (!constant)
867           return 1;
868
869       /* ... fall through ... */
870
871     case N_Type_Conversion:
872     case N_Qualified_Expression:
873       /* We must look through all conversions because we may need to bypass
874          an intermediate conversion that is meant to be purely formal.  */
875      return lvalue_required_p (gnat_parent,
876                                get_unpadded_type (Etype (gnat_parent)),
877                                constant, address_of_constant, aliased);
878
879     case N_Allocator:
880       /* We should only reach here through the N_Qualified_Expression case.
881          Force an lvalue for composite types since a block-copy to the newly
882          allocated area of memory is made.  */
883       return Is_Composite_Type (Underlying_Type (Etype (gnat_node)));
884
885    case N_Explicit_Dereference:
886       /* We look through dereferences for address of constant because we need
887          to handle the special cases listed above.  */
888       if (constant && address_of_constant)
889         return lvalue_required_p (gnat_parent,
890                                   get_unpadded_type (Etype (gnat_parent)),
891                                   true, false, true);
892
893       /* ... fall through ... */
894
895     default:
896       return 0;
897     }
898
899   gcc_unreachable ();
900 }
901
902 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Identifier,
903    to a GCC tree, which is returned.  GNU_RESULT_TYPE_P is a pointer
904    to where we should place the result type.  */
905
906 static tree
907 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
908 {
909   Node_Id gnat_temp, gnat_temp_type;
910   tree gnu_result, gnu_result_type;
911
912   /* Whether we should require an lvalue for GNAT_NODE.  Needed in
913      specific circumstances only, so evaluated lazily.  < 0 means
914      unknown, > 0 means known true, 0 means known false.  */
915   int require_lvalue = -1;
916
917   /* If GNAT_NODE is a constant, whether we should use the initialization
918      value instead of the constant entity, typically for scalars with an
919      address clause when the parent doesn't require an lvalue.  */
920   bool use_constant_initializer = false;
921
922   /* If the Etype of this node does not equal the Etype of the Entity,
923      something is wrong with the entity map, probably in generic
924      instantiation. However, this does not apply to types. Since we sometime
925      have strange Ekind's, just do this test for objects. Also, if the Etype of
926      the Entity is private, the Etype of the N_Identifier is allowed to be the
927      full type and also we consider a packed array type to be the same as the
928      original type. Similarly, a class-wide type is equivalent to a subtype of
929      itself. Finally, if the types are Itypes, one may be a copy of the other,
930      which is also legal.  */
931   gnat_temp = (Nkind (gnat_node) == N_Defining_Identifier
932                ? gnat_node : Entity (gnat_node));
933   gnat_temp_type = Etype (gnat_temp);
934
935   gcc_assert (Etype (gnat_node) == gnat_temp_type
936               || (Is_Packed (gnat_temp_type)
937                   && Etype (gnat_node) == Packed_Array_Type (gnat_temp_type))
938               || (Is_Class_Wide_Type (Etype (gnat_node)))
939               || (IN (Ekind (gnat_temp_type), Private_Kind)
940                   && Present (Full_View (gnat_temp_type))
941                   && ((Etype (gnat_node) == Full_View (gnat_temp_type))
942                       || (Is_Packed (Full_View (gnat_temp_type))
943                           && (Etype (gnat_node)
944                               == Packed_Array_Type (Full_View
945                                                     (gnat_temp_type))))))
946               || (Is_Itype (Etype (gnat_node)) && Is_Itype (gnat_temp_type))
947               || !(Ekind (gnat_temp) == E_Variable
948                    || Ekind (gnat_temp) == E_Component
949                    || Ekind (gnat_temp) == E_Constant
950                    || Ekind (gnat_temp) == E_Loop_Parameter
951                    || IN (Ekind (gnat_temp), Formal_Kind)));
952
953   /* If this is a reference to a deferred constant whose partial view is an
954      unconstrained private type, the proper type is on the full view of the
955      constant, not on the full view of the type, which may be unconstrained.
956
957      This may be a reference to a type, for example in the prefix of the
958      attribute Position, generated for dispatching code (see Make_DT in
959      exp_disp,adb). In that case we need the type itself, not is parent,
960      in particular if it is a derived type  */
961   if (Ekind (gnat_temp) == E_Constant
962       && Is_Private_Type (gnat_temp_type)
963       && (Has_Unknown_Discriminants (gnat_temp_type)
964           || (Present (Full_View (gnat_temp_type))
965               && Has_Discriminants (Full_View (gnat_temp_type))))
966       && Present (Full_View (gnat_temp)))
967     {
968       gnat_temp = Full_View (gnat_temp);
969       gnat_temp_type = Etype (gnat_temp);
970     }
971   else
972     {
973       /* We want to use the Actual_Subtype if it has already been elaborated,
974          otherwise the Etype.  Avoid using Actual_Subtype for packed arrays to
975          simplify things.  */
976       if ((Ekind (gnat_temp) == E_Constant
977            || Ekind (gnat_temp) == E_Variable || Is_Formal (gnat_temp))
978           && !(Is_Array_Type (Etype (gnat_temp))
979                && Present (Packed_Array_Type (Etype (gnat_temp))))
980           && Present (Actual_Subtype (gnat_temp))
981           && present_gnu_tree (Actual_Subtype (gnat_temp)))
982         gnat_temp_type = Actual_Subtype (gnat_temp);
983       else
984         gnat_temp_type = Etype (gnat_node);
985     }
986
987   /* Expand the type of this identifier first, in case it is an enumeral
988      literal, which only get made when the type is expanded.  There is no
989      order-of-elaboration issue here.  */
990   gnu_result_type = get_unpadded_type (gnat_temp_type);
991
992   /* If this is a non-imported scalar constant with an address clause,
993      retrieve the value instead of a pointer to be dereferenced unless
994      an lvalue is required.  This is generally more efficient and actually
995      required if this is a static expression because it might be used
996      in a context where a dereference is inappropriate, such as a case
997      statement alternative or a record discriminant.  There is no possible
998      volatile-ness short-circuit here since Volatile constants must be
999      imported per C.6.  */
1000   if (Ekind (gnat_temp) == E_Constant
1001       && Is_Scalar_Type (gnat_temp_type)
1002       && !Is_Imported (gnat_temp)
1003       && Present (Address_Clause (gnat_temp)))
1004     {
1005       require_lvalue = lvalue_required_p (gnat_node, gnu_result_type, true,
1006                                           false, Is_Aliased (gnat_temp));
1007       use_constant_initializer = !require_lvalue;
1008     }
1009
1010   if (use_constant_initializer)
1011     {
1012       /* If this is a deferred constant, the initializer is attached to
1013          the full view.  */
1014       if (Present (Full_View (gnat_temp)))
1015         gnat_temp = Full_View (gnat_temp);
1016
1017       gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_temp)));
1018     }
1019   else
1020     gnu_result = gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0);
1021
1022   /* Some objects (such as parameters passed by reference, globals of
1023      variable size, and renamed objects) actually represent the address
1024      of the object.  In that case, we must do the dereference.  Likewise,
1025      deal with parameters to foreign convention subprograms.  */
1026   if (DECL_P (gnu_result)
1027       && (DECL_BY_REF_P (gnu_result)
1028           || (TREE_CODE (gnu_result) == PARM_DECL
1029               && DECL_BY_COMPONENT_PTR_P (gnu_result))))
1030     {
1031       const bool read_only = DECL_POINTS_TO_READONLY_P (gnu_result);
1032
1033       /* First do the first dereference if needed.  */
1034       if (TREE_CODE (gnu_result) == PARM_DECL
1035           && DECL_BY_DOUBLE_REF_P (gnu_result))
1036         {
1037           gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1038           if (TREE_CODE (gnu_result) == INDIRECT_REF)
1039             TREE_THIS_NOTRAP (gnu_result) = 1;
1040
1041           /* The first reference, in case of a double reference, always points
1042              to read-only, see gnat_to_gnu_param for the rationale.  */
1043           TREE_READONLY (gnu_result) = 1;
1044         }
1045
1046       /* If it's a PARM_DECL to foreign convention subprogram, convert it.  */
1047       if (TREE_CODE (gnu_result) == PARM_DECL
1048           && DECL_BY_COMPONENT_PTR_P (gnu_result))
1049         gnu_result
1050           = convert (build_pointer_type (gnu_result_type), gnu_result);
1051
1052       /* If it's a CONST_DECL, return the underlying constant like below.  */
1053       else if (TREE_CODE (gnu_result) == CONST_DECL)
1054         gnu_result = DECL_INITIAL (gnu_result);
1055
1056       /* If it's a renaming pointer and we are at the right binding level,
1057          we can reference the renamed object directly, since the renamed
1058          expression has been protected against multiple evaluations.  */
1059       if (TREE_CODE (gnu_result) == VAR_DECL
1060           && !DECL_LOOP_PARM_P (gnu_result)
1061           && DECL_RENAMED_OBJECT (gnu_result)
1062           && (!DECL_RENAMING_GLOBAL_P (gnu_result) || global_bindings_p ()))
1063         gnu_result = DECL_RENAMED_OBJECT (gnu_result);
1064
1065       /* Otherwise, do the final dereference.  */
1066       else
1067         {
1068           gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1069
1070           if ((TREE_CODE (gnu_result) == INDIRECT_REF
1071                || TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
1072               && No (Address_Clause (gnat_temp)))
1073             TREE_THIS_NOTRAP (gnu_result) = 1;
1074
1075           if (read_only)
1076             TREE_READONLY (gnu_result) = 1;
1077         }
1078     }
1079
1080   /* The GNAT tree has the type of a function as the type of its result.  Also
1081      use the type of the result if the Etype is a subtype which is nominally
1082      unconstrained.  But remove any padding from the resulting type.  */
1083   if (TREE_CODE (TREE_TYPE (gnu_result)) == FUNCTION_TYPE
1084       || Is_Constr_Subt_For_UN_Aliased (gnat_temp_type))
1085     {
1086       gnu_result_type = TREE_TYPE (gnu_result);
1087       if (TYPE_IS_PADDING_P (gnu_result_type))
1088         gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
1089     }
1090
1091   /* If we have a constant declaration and its initializer, try to return the
1092      latter to avoid the need to call fold in lots of places and the need for
1093      elaboration code if this identifier is used as an initializer itself.
1094      Don't do it for aggregate types that contain a placeholder since their
1095      initializers cannot be manipulated easily.  */
1096   if (TREE_CONSTANT (gnu_result)
1097       && DECL_P (gnu_result)
1098       && DECL_INITIAL (gnu_result)
1099       && !(AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))
1100            && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_result))
1101            && type_contains_placeholder_p (TREE_TYPE (gnu_result))))
1102     {
1103       bool constant_only = (TREE_CODE (gnu_result) == CONST_DECL
1104                             && !DECL_CONST_CORRESPONDING_VAR (gnu_result));
1105       bool address_of_constant = (TREE_CODE (gnu_result) == CONST_DECL
1106                                   && DECL_CONST_ADDRESS_P (gnu_result));
1107
1108       /* If there is a (corresponding) variable or this is the address of a
1109          constant, we only want to return the initializer if an lvalue isn't
1110          required.  Evaluate this now if we have not already done so.  */
1111       if ((!constant_only || address_of_constant) && require_lvalue < 0)
1112         require_lvalue
1113           = lvalue_required_p (gnat_node, gnu_result_type, true,
1114                                address_of_constant, Is_Aliased (gnat_temp));
1115
1116       /* ??? We need to unshare the initializer if the object is external
1117          as such objects are not marked for unsharing if we are not at the
1118          global level.  This should be fixed in add_decl_expr.  */
1119       if ((constant_only && !address_of_constant) || !require_lvalue)
1120         gnu_result = unshare_expr (DECL_INITIAL (gnu_result));
1121     }
1122
1123   *gnu_result_type_p = gnu_result_type;
1124
1125   return gnu_result;
1126 }
1127 \f
1128 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Pragma.  Return
1129    any statements we generate.  */
1130
1131 static tree
1132 Pragma_to_gnu (Node_Id gnat_node)
1133 {
1134   Node_Id gnat_temp;
1135   tree gnu_result = alloc_stmt_list ();
1136
1137   /* Check for (and ignore) unrecognized pragma and do nothing if we are just
1138      annotating types.  */
1139   if (type_annotate_only
1140       || !Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
1141     return gnu_result;
1142
1143   switch (Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node))))
1144     {
1145     case Pragma_Inspection_Point:
1146       /* Do nothing at top level: all such variables are already viewable.  */
1147       if (global_bindings_p ())
1148         break;
1149
1150       for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1151            Present (gnat_temp);
1152            gnat_temp = Next (gnat_temp))
1153         {
1154           Node_Id gnat_expr = Expression (gnat_temp);
1155           tree gnu_expr = gnat_to_gnu (gnat_expr);
1156           int use_address;
1157           enum machine_mode mode;
1158           tree asm_constraint = NULL_TREE;
1159 #ifdef ASM_COMMENT_START
1160           char *comment;
1161 #endif
1162
1163           if (TREE_CODE (gnu_expr) == UNCONSTRAINED_ARRAY_REF)
1164             gnu_expr = TREE_OPERAND (gnu_expr, 0);
1165
1166           /* Use the value only if it fits into a normal register,
1167              otherwise use the address.  */
1168           mode = TYPE_MODE (TREE_TYPE (gnu_expr));
1169           use_address = ((GET_MODE_CLASS (mode) != MODE_INT
1170                           && GET_MODE_CLASS (mode) != MODE_PARTIAL_INT)
1171                          || GET_MODE_SIZE (mode) > UNITS_PER_WORD);
1172
1173           if (use_address)
1174             gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
1175
1176 #ifdef ASM_COMMENT_START
1177           comment = concat (ASM_COMMENT_START,
1178                             " inspection point: ",
1179                             Get_Name_String (Chars (gnat_expr)),
1180                             use_address ? " address" : "",
1181                             " is in %0",
1182                             NULL);
1183           asm_constraint = build_string (strlen (comment), comment);
1184           free (comment);
1185 #endif
1186           gnu_expr = build5 (ASM_EXPR, void_type_node,
1187                              asm_constraint,
1188                              NULL_TREE,
1189                              tree_cons
1190                              (build_tree_list (NULL_TREE,
1191                                                build_string (1, "g")),
1192                               gnu_expr, NULL_TREE),
1193                              NULL_TREE, NULL_TREE);
1194           ASM_VOLATILE_P (gnu_expr) = 1;
1195           set_expr_location_from_node (gnu_expr, gnat_node);
1196           append_to_statement_list (gnu_expr, &gnu_result);
1197         }
1198       break;
1199
1200     case Pragma_Optimize:
1201       switch (Chars (Expression
1202                      (First (Pragma_Argument_Associations (gnat_node)))))
1203         {
1204         case Name_Time:  case Name_Space:
1205           if (!optimize)
1206             post_error ("insufficient -O value?", gnat_node);
1207           break;
1208
1209         case Name_Off:
1210           if (optimize)
1211             post_error ("must specify -O0?", gnat_node);
1212           break;
1213
1214         default:
1215           gcc_unreachable ();
1216         }
1217       break;
1218
1219     case Pragma_Reviewable:
1220       if (write_symbols == NO_DEBUG)
1221         post_error ("must specify -g?", gnat_node);
1222       break;
1223     }
1224
1225   return gnu_result;
1226 }
1227 \f
1228 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Attribute node,
1229    to a GCC tree, which is returned.  GNU_RESULT_TYPE_P is a pointer to
1230    where we should place the result type.  ATTRIBUTE is the attribute ID.  */
1231
1232 static tree
1233 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
1234 {
1235   tree gnu_prefix = gnat_to_gnu (Prefix (gnat_node));
1236   tree gnu_type = TREE_TYPE (gnu_prefix);
1237   tree gnu_expr, gnu_result_type, gnu_result = error_mark_node;
1238   bool prefix_unused = false;
1239
1240   /* If the input is a NULL_EXPR, make a new one.  */
1241   if (TREE_CODE (gnu_prefix) == NULL_EXPR)
1242     {
1243       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1244       *gnu_result_type_p = gnu_result_type;
1245       return build1 (NULL_EXPR, gnu_result_type, TREE_OPERAND (gnu_prefix, 0));
1246     }
1247
1248   switch (attribute)
1249     {
1250     case Attr_Pos:
1251     case Attr_Val:
1252       /* These are just conversions since representation clauses for
1253          enumeration types are handled in the front-end.  */
1254       {
1255         bool checkp = Do_Range_Check (First (Expressions (gnat_node)));
1256         gnu_result = gnat_to_gnu (First (Expressions (gnat_node)));
1257         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1258         gnu_result = convert_with_check (Etype (gnat_node), gnu_result,
1259                                          checkp, checkp, true, gnat_node);
1260       }
1261       break;
1262
1263     case Attr_Pred:
1264     case Attr_Succ:
1265       /* These just add or subtract the constant 1 since representation
1266          clauses for enumeration types are handled in the front-end.  */
1267       gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
1268       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1269
1270       if (Do_Range_Check (First (Expressions (gnat_node))))
1271         {
1272           gnu_expr = gnat_protect_expr (gnu_expr);
1273           gnu_expr
1274             = emit_check
1275               (build_binary_op (EQ_EXPR, boolean_type_node,
1276                                 gnu_expr,
1277                                 attribute == Attr_Pred
1278                                 ? TYPE_MIN_VALUE (gnu_result_type)
1279                                 : TYPE_MAX_VALUE (gnu_result_type)),
1280                gnu_expr, CE_Range_Check_Failed, gnat_node);
1281         }
1282
1283       gnu_result
1284         = build_binary_op (attribute == Attr_Pred ? MINUS_EXPR : PLUS_EXPR,
1285                            gnu_result_type, gnu_expr,
1286                            convert (gnu_result_type, integer_one_node));
1287       break;
1288
1289     case Attr_Address:
1290     case Attr_Unrestricted_Access:
1291       /* Conversions don't change addresses but can cause us to miss the
1292          COMPONENT_REF case below, so strip them off.  */
1293       gnu_prefix = remove_conversions (gnu_prefix,
1294                                        !Must_Be_Byte_Aligned (gnat_node));
1295
1296       /* If we are taking 'Address of an unconstrained object, this is the
1297          pointer to the underlying array.  */
1298       if (attribute == Attr_Address)
1299         gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1300
1301       /* If we are building a static dispatch table, we have to honor
1302          TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
1303          with the C++ ABI.  We do it in the non-static case as well,
1304          see gnat_to_gnu_entity, case E_Access_Subprogram_Type.  */
1305       else if (TARGET_VTABLE_USES_DESCRIPTORS
1306                && Is_Dispatch_Table_Entity (Etype (gnat_node)))
1307         {
1308           tree gnu_field, t;
1309           /* Descriptors can only be built here for top-level functions.  */
1310           bool build_descriptor = (global_bindings_p () != 0);
1311           int i;
1312           VEC(constructor_elt,gc) *gnu_vec = NULL;
1313           constructor_elt *elt;
1314
1315           gnu_result_type = get_unpadded_type (Etype (gnat_node));
1316
1317           /* If we're not going to build the descriptor, we have to retrieve
1318              the one which will be built by the linker (or by the compiler
1319              later if a static chain is requested).  */
1320           if (!build_descriptor)
1321             {
1322               gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
1323               gnu_result = fold_convert (build_pointer_type (gnu_result_type),
1324                                          gnu_result);
1325               gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
1326             }
1327
1328           VEC_safe_grow (constructor_elt, gc, gnu_vec,
1329                          TARGET_VTABLE_USES_DESCRIPTORS);
1330           elt = (VEC_address (constructor_elt, gnu_vec)
1331                  + TARGET_VTABLE_USES_DESCRIPTORS - 1);
1332           for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
1333                i < TARGET_VTABLE_USES_DESCRIPTORS;
1334                gnu_field = DECL_CHAIN (gnu_field), i++)
1335             {
1336               if (build_descriptor)
1337                 {
1338                   t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
1339                               build_int_cst (NULL_TREE, i));
1340                   TREE_CONSTANT (t) = 1;
1341                 }
1342               else
1343                 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
1344                             gnu_field, NULL_TREE);
1345
1346               elt->index = gnu_field;
1347               elt->value = t;
1348               elt--;
1349             }
1350
1351           gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
1352           break;
1353         }
1354
1355       /* ... fall through ... */
1356
1357     case Attr_Access:
1358     case Attr_Unchecked_Access:
1359     case Attr_Code_Address:
1360       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1361       gnu_result
1362         = build_unary_op (((attribute == Attr_Address
1363                             || attribute == Attr_Unrestricted_Access)
1364                            && !Must_Be_Byte_Aligned (gnat_node))
1365                           ? ATTR_ADDR_EXPR : ADDR_EXPR,
1366                           gnu_result_type, gnu_prefix);
1367
1368       /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
1369          don't try to build a trampoline.  */
1370       if (attribute == Attr_Code_Address)
1371         {
1372           gnu_expr = remove_conversions (gnu_result, false);
1373
1374           if (TREE_CODE (gnu_expr) == ADDR_EXPR)
1375             TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
1376         }
1377
1378       /* For other address attributes applied to a nested function,
1379          find an inner ADDR_EXPR and annotate it so that we can issue
1380          a useful warning with -Wtrampolines.  */
1381       else if (TREE_CODE (TREE_TYPE (gnu_prefix)) == FUNCTION_TYPE)
1382         {
1383           gnu_expr = remove_conversions (gnu_result, false);
1384
1385           if (TREE_CODE (gnu_expr) == ADDR_EXPR
1386               && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
1387             {
1388               set_expr_location_from_node (gnu_expr, gnat_node);
1389
1390               /* Check that we're not violating the No_Implicit_Dynamic_Code
1391                  restriction.  Be conservative if we don't know anything
1392                  about the trampoline strategy for the target.  */
1393               Check_Implicit_Dynamic_Code_Allowed (gnat_node);
1394             }
1395         }
1396       break;
1397
1398     case Attr_Pool_Address:
1399       {
1400         tree gnu_obj_type;
1401         tree gnu_ptr = gnu_prefix;
1402
1403         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1404
1405         /* If this is an unconstrained array, we know the object has been
1406            allocated with the template in front of the object.  So compute
1407            the template address.  */
1408         if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
1409           gnu_ptr
1410             = convert (build_pointer_type
1411                        (TYPE_OBJECT_RECORD_TYPE
1412                         (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
1413                        gnu_ptr);
1414
1415         gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
1416         if (TREE_CODE (gnu_obj_type) == RECORD_TYPE
1417             && TYPE_CONTAINS_TEMPLATE_P (gnu_obj_type))
1418           {
1419             tree gnu_char_ptr_type
1420               = build_pointer_type (unsigned_char_type_node);
1421             tree gnu_pos = byte_position (TYPE_FIELDS (gnu_obj_type));
1422             gnu_ptr = convert (gnu_char_ptr_type, gnu_ptr);
1423             gnu_ptr = build_binary_op (POINTER_PLUS_EXPR, gnu_char_ptr_type,
1424                                        gnu_ptr, gnu_pos);
1425           }
1426
1427         gnu_result = convert (gnu_result_type, gnu_ptr);
1428       }
1429       break;
1430
1431     case Attr_Size:
1432     case Attr_Object_Size:
1433     case Attr_Value_Size:
1434     case Attr_Max_Size_In_Storage_Elements:
1435       gnu_expr = gnu_prefix;
1436
1437       /* Remove NOPs and conversions between original and packable version
1438          from GNU_EXPR, and conversions from GNU_PREFIX.  We use GNU_EXPR
1439          to see if a COMPONENT_REF was involved.  */
1440       while (TREE_CODE (gnu_expr) == NOP_EXPR
1441              || (TREE_CODE (gnu_expr) == VIEW_CONVERT_EXPR
1442                  && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
1443                  && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
1444                     == RECORD_TYPE
1445                  && TYPE_NAME (TREE_TYPE (gnu_expr))
1446                     == TYPE_NAME (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))))
1447         gnu_expr = TREE_OPERAND (gnu_expr, 0);
1448
1449       gnu_prefix = remove_conversions (gnu_prefix, true);
1450       prefix_unused = true;
1451       gnu_type = TREE_TYPE (gnu_prefix);
1452
1453       /* Replace an unconstrained array type with the type of the underlying
1454          array.  We can't do this with a call to maybe_unconstrained_array
1455          since we may have a TYPE_DECL.  For 'Max_Size_In_Storage_Elements,
1456          use the record type that will be used to allocate the object and its
1457          template.  */
1458       if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1459         {
1460           gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1461           if (attribute != Attr_Max_Size_In_Storage_Elements)
1462             gnu_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
1463         }
1464
1465       /* If we're looking for the size of a field, return the field size.
1466          Otherwise, if the prefix is an object, or if we're looking for
1467          'Object_Size or 'Max_Size_In_Storage_Elements, the result is the
1468          GCC size of the type.  Otherwise, it is the RM size of the type.  */
1469       if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1470         gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
1471       else if (TREE_CODE (gnu_prefix) != TYPE_DECL
1472                || attribute == Attr_Object_Size
1473                || attribute == Attr_Max_Size_In_Storage_Elements)
1474         {
1475           /* If the prefix is an object of a padded type, the GCC size isn't
1476              relevant to the programmer.  Normally what we want is the RM size,
1477              which was set from the specified size, but if it was not set, we
1478              want the size of the field.  Using the MAX of those two produces
1479              the right result in all cases.  Don't use the size of the field
1480              if it's self-referential, since that's never what's wanted.  */
1481           if (TREE_CODE (gnu_prefix) != TYPE_DECL
1482               && TYPE_IS_PADDING_P (gnu_type)
1483               && TREE_CODE (gnu_expr) == COMPONENT_REF)
1484             {
1485               gnu_result = rm_size (gnu_type);
1486               if (!CONTAINS_PLACEHOLDER_P
1487                    (DECL_SIZE (TREE_OPERAND (gnu_expr, 1))))
1488                 gnu_result
1489                   = size_binop (MAX_EXPR, gnu_result,
1490                                 DECL_SIZE (TREE_OPERAND (gnu_expr, 1)));
1491             }
1492           else if (Nkind (Prefix (gnat_node)) == N_Explicit_Dereference)
1493             {
1494               Node_Id gnat_deref = Prefix (gnat_node);
1495               Node_Id gnat_actual_subtype
1496                 = Actual_Designated_Subtype (gnat_deref);
1497               tree gnu_ptr_type
1498                 = TREE_TYPE (gnat_to_gnu (Prefix (gnat_deref)));
1499
1500               if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
1501                   && Present (gnat_actual_subtype))
1502                 {
1503                   tree gnu_actual_obj_type
1504                     = gnat_to_gnu_type (gnat_actual_subtype);
1505                   gnu_type
1506                     = build_unc_object_type_from_ptr (gnu_ptr_type,
1507                                                       gnu_actual_obj_type,
1508                                                       get_identifier ("SIZE"),
1509                                                       false);
1510                 }
1511
1512               gnu_result = TYPE_SIZE (gnu_type);
1513             }
1514           else
1515             gnu_result = TYPE_SIZE (gnu_type);
1516         }
1517       else
1518         gnu_result = rm_size (gnu_type);
1519
1520       /* Deal with a self-referential size by returning the maximum size for
1521          a type and by qualifying the size with the object otherwise.  */
1522       if (CONTAINS_PLACEHOLDER_P (gnu_result))
1523         {
1524           if (TREE_CODE (gnu_prefix) == TYPE_DECL)
1525             gnu_result = max_size (gnu_result, true);
1526           else
1527             gnu_result = substitute_placeholder_in_expr (gnu_result, gnu_expr);
1528         }
1529
1530       /* If the type contains a template, subtract its size.  */
1531       if (TREE_CODE (gnu_type) == RECORD_TYPE
1532           && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
1533         gnu_result = size_binop (MINUS_EXPR, gnu_result,
1534                                  DECL_SIZE (TYPE_FIELDS (gnu_type)));
1535
1536       /* For 'Max_Size_In_Storage_Elements, adjust the unit.  */
1537       if (attribute == Attr_Max_Size_In_Storage_Elements)
1538         gnu_result = size_binop (CEIL_DIV_EXPR, gnu_result, bitsize_unit_node);
1539
1540       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1541       break;
1542
1543     case Attr_Alignment:
1544       {
1545         unsigned int align;
1546
1547         if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1548             && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1549           gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1550
1551         gnu_type = TREE_TYPE (gnu_prefix);
1552         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1553         prefix_unused = true;
1554
1555         if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1556           align = DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1)) / BITS_PER_UNIT;
1557         else
1558           {
1559             Node_Id gnat_prefix = Prefix (gnat_node);
1560             Entity_Id gnat_type = Etype (gnat_prefix);
1561             unsigned int double_align;
1562             bool is_capped_double, align_clause;
1563
1564             /* If the default alignment of "double" or larger scalar types is
1565                specifically capped and there is an alignment clause neither
1566                on the type nor on the prefix itself, return the cap.  */
1567             if ((double_align = double_float_alignment) > 0)
1568               is_capped_double
1569                 = is_double_float_or_array (gnat_type, &align_clause);
1570             else if ((double_align = double_scalar_alignment) > 0)
1571               is_capped_double
1572                 = is_double_scalar_or_array (gnat_type, &align_clause);
1573             else
1574               is_capped_double = align_clause = false;
1575
1576             if (is_capped_double
1577                 && Nkind (gnat_prefix) == N_Identifier
1578                 && Present (Alignment_Clause (Entity (gnat_prefix))))
1579               align_clause = true;
1580
1581             if (is_capped_double && !align_clause)
1582               align = double_align;
1583             else
1584               align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
1585           }
1586
1587         gnu_result = size_int (align);
1588       }
1589       break;
1590
1591     case Attr_First:
1592     case Attr_Last:
1593     case Attr_Range_Length:
1594       prefix_unused = true;
1595
1596       if (INTEGRAL_TYPE_P (gnu_type) || TREE_CODE (gnu_type) == REAL_TYPE)
1597         {
1598           gnu_result_type = get_unpadded_type (Etype (gnat_node));
1599
1600           if (attribute == Attr_First)
1601             gnu_result = TYPE_MIN_VALUE (gnu_type);
1602           else if (attribute == Attr_Last)
1603             gnu_result = TYPE_MAX_VALUE (gnu_type);
1604           else
1605             gnu_result
1606               = build_binary_op
1607                 (MAX_EXPR, get_base_type (gnu_result_type),
1608                  build_binary_op
1609                  (PLUS_EXPR, get_base_type (gnu_result_type),
1610                   build_binary_op (MINUS_EXPR,
1611                                    get_base_type (gnu_result_type),
1612                                    convert (gnu_result_type,
1613                                             TYPE_MAX_VALUE (gnu_type)),
1614                                    convert (gnu_result_type,
1615                                             TYPE_MIN_VALUE (gnu_type))),
1616                   convert (gnu_result_type, integer_one_node)),
1617                  convert (gnu_result_type, integer_zero_node));
1618
1619           break;
1620         }
1621
1622       /* ... fall through ... */
1623
1624     case Attr_Length:
1625       {
1626         int Dimension = (Present (Expressions (gnat_node))
1627                          ? UI_To_Int (Intval (First (Expressions (gnat_node))))
1628                          : 1), i;
1629         struct parm_attr_d *pa = NULL;
1630         Entity_Id gnat_param = Empty;
1631
1632         /* Make sure any implicit dereference gets done.  */
1633         gnu_prefix = maybe_implicit_deref (gnu_prefix);
1634         gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1635
1636         /* We treat unconstrained array In parameters specially.  */
1637         if (!Is_Constrained (Etype (Prefix (gnat_node))))
1638           {
1639             Node_Id gnat_prefix = Prefix (gnat_node);
1640
1641             /* This is the direct case.  */
1642             if (Nkind (gnat_prefix) == N_Identifier
1643                 && Ekind (Entity (gnat_prefix)) == E_In_Parameter)
1644               gnat_param = Entity (gnat_prefix);
1645
1646             /* This is the indirect case.  Note that we need to be sure that
1647                the access value cannot be null as we'll hoist the load.  */
1648             if (Nkind (gnat_prefix) == N_Explicit_Dereference
1649                 && Nkind (Prefix (gnat_prefix)) == N_Identifier
1650                 && Ekind (Entity (Prefix (gnat_prefix))) == E_In_Parameter
1651                 && Can_Never_Be_Null (Entity (Prefix (gnat_prefix))))
1652               gnat_param = Entity (Prefix (gnat_prefix));
1653           }
1654
1655         gnu_type = TREE_TYPE (gnu_prefix);
1656         prefix_unused = true;
1657         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1658
1659         if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
1660           {
1661             int ndim;
1662             tree gnu_type_temp;
1663
1664             for (ndim = 1, gnu_type_temp = gnu_type;
1665                  TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
1666                  && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
1667                  ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
1668               ;
1669
1670             Dimension = ndim + 1 - Dimension;
1671           }
1672
1673         for (i = 1; i < Dimension; i++)
1674           gnu_type = TREE_TYPE (gnu_type);
1675
1676         gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
1677
1678         /* When not optimizing, look up the slot associated with the parameter
1679            and the dimension in the cache and create a new one on failure.  */
1680         if (!optimize && Present (gnat_param))
1681           {
1682             FOR_EACH_VEC_ELT (parm_attr, f_parm_attr_cache, i, pa)
1683               if (pa->id == gnat_param && pa->dim == Dimension)
1684                 break;
1685
1686             if (!pa)
1687               {
1688                 pa = ggc_alloc_cleared_parm_attr_d ();
1689                 pa->id = gnat_param;
1690                 pa->dim = Dimension;
1691                 VEC_safe_push (parm_attr, gc, f_parm_attr_cache, pa);
1692               }
1693           }
1694
1695         /* Return the cached expression or build a new one.  */
1696         if (attribute == Attr_First)
1697           {
1698             if (pa && pa->first)
1699               {
1700                 gnu_result = pa->first;
1701                 break;
1702               }
1703
1704             gnu_result
1705               = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
1706           }
1707
1708         else if (attribute == Attr_Last)
1709           {
1710             if (pa && pa->last)
1711               {
1712                 gnu_result = pa->last;
1713                 break;
1714               }
1715
1716             gnu_result
1717               = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
1718           }
1719
1720         else /* attribute == Attr_Range_Length || attribute == Attr_Length  */
1721           {
1722             if (pa && pa->length)
1723               {
1724                 gnu_result = pa->length;
1725                 break;
1726               }
1727             else
1728               {
1729                 /* We used to compute the length as max (hb - lb + 1, 0),
1730                    which could overflow for some cases of empty arrays, e.g.
1731                    when lb == index_type'first.  We now compute the length as
1732                    (hb >= lb) ? hb - lb + 1 : 0, which would only overflow in
1733                    much rarer cases, for extremely large arrays we expect
1734                    never to encounter in practice.  In addition, the former
1735                    computation required the use of potentially constraining
1736                    signed arithmetic while the latter doesn't.  Note that
1737                    the comparison must be done in the original index type,
1738                    to avoid any overflow during the conversion.  */
1739                 tree comp_type = get_base_type (gnu_result_type);
1740                 tree index_type = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
1741                 tree lb = TYPE_MIN_VALUE (index_type);
1742                 tree hb = TYPE_MAX_VALUE (index_type);
1743                 gnu_result
1744                   = build_binary_op (PLUS_EXPR, comp_type,
1745                                      build_binary_op (MINUS_EXPR,
1746                                                       comp_type,
1747                                                       convert (comp_type, hb),
1748                                                       convert (comp_type, lb)),
1749                                      convert (comp_type, integer_one_node));
1750                 gnu_result
1751                   = build_cond_expr (comp_type,
1752                                      build_binary_op (GE_EXPR,
1753                                                       boolean_type_node,
1754                                                       hb, lb),
1755                                      gnu_result,
1756                                      convert (comp_type, integer_zero_node));
1757               }
1758           }
1759
1760         /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
1761            handling.  Note that these attributes could not have been used on
1762            an unconstrained array type.  */
1763         gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
1764
1765         /* Cache the expression we have just computed.  Since we want to do it
1766            at run time, we force the use of a SAVE_EXPR and let the gimplifier
1767            create the temporary in the outermost binding level.  We will make
1768            sure in Subprogram_Body_to_gnu that it is evaluated on all possible
1769            paths by forcing its evaluation on entry of the function.  */
1770         if (pa)
1771           {
1772             gnu_result
1773               = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
1774             if (attribute == Attr_First)
1775               pa->first = gnu_result;
1776             else if (attribute == Attr_Last)
1777               pa->last = gnu_result;
1778             else
1779               pa->length = gnu_result;
1780           }
1781
1782         /* Set the source location onto the predicate of the condition in the
1783            'Length case but do not do it if the expression is cached to avoid
1784            messing up the debug info.  */
1785         else if ((attribute == Attr_Range_Length || attribute == Attr_Length)
1786                  && TREE_CODE (gnu_result) == COND_EXPR
1787                  && EXPR_P (TREE_OPERAND (gnu_result, 0)))
1788           set_expr_location_from_node (TREE_OPERAND (gnu_result, 0),
1789                                        gnat_node);
1790
1791         break;
1792       }
1793
1794     case Attr_Bit_Position:
1795     case Attr_Position:
1796     case Attr_First_Bit:
1797     case Attr_Last_Bit:
1798     case Attr_Bit:
1799       {
1800         HOST_WIDE_INT bitsize;
1801         HOST_WIDE_INT bitpos;
1802         tree gnu_offset;
1803         tree gnu_field_bitpos;
1804         tree gnu_field_offset;
1805         tree gnu_inner;
1806         enum machine_mode mode;
1807         int unsignedp, volatilep;
1808
1809         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1810         gnu_prefix = remove_conversions (gnu_prefix, true);
1811         prefix_unused = true;
1812
1813         /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
1814            the result is 0.  Don't allow 'Bit on a bare component, though.  */
1815         if (attribute == Attr_Bit
1816             && TREE_CODE (gnu_prefix) != COMPONENT_REF
1817             && TREE_CODE (gnu_prefix) != FIELD_DECL)
1818           {
1819             gnu_result = integer_zero_node;
1820             break;
1821           }
1822
1823         else
1824           gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
1825                       || (attribute == Attr_Bit_Position
1826                           && TREE_CODE (gnu_prefix) == FIELD_DECL));
1827
1828         get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
1829                              &mode, &unsignedp, &volatilep, false);
1830
1831         if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1832           {
1833             gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
1834             gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
1835
1836             for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
1837                  TREE_CODE (gnu_inner) == COMPONENT_REF
1838                  && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
1839                  gnu_inner = TREE_OPERAND (gnu_inner, 0))
1840               {
1841                 gnu_field_bitpos
1842                   = size_binop (PLUS_EXPR, gnu_field_bitpos,
1843                                 bit_position (TREE_OPERAND (gnu_inner, 1)));
1844                 gnu_field_offset
1845                   = size_binop (PLUS_EXPR, gnu_field_offset,
1846                                 byte_position (TREE_OPERAND (gnu_inner, 1)));
1847               }
1848           }
1849         else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
1850           {
1851             gnu_field_bitpos = bit_position (gnu_prefix);
1852             gnu_field_offset = byte_position (gnu_prefix);
1853           }
1854         else
1855           {
1856             gnu_field_bitpos = bitsize_zero_node;
1857             gnu_field_offset = size_zero_node;
1858           }
1859
1860         switch (attribute)
1861           {
1862           case Attr_Position:
1863             gnu_result = gnu_field_offset;
1864             break;
1865
1866           case Attr_First_Bit:
1867           case Attr_Bit:
1868             gnu_result = size_int (bitpos % BITS_PER_UNIT);
1869             break;
1870
1871           case Attr_Last_Bit:
1872             gnu_result = bitsize_int (bitpos % BITS_PER_UNIT);
1873             gnu_result = size_binop (PLUS_EXPR, gnu_result,
1874                                      TYPE_SIZE (TREE_TYPE (gnu_prefix)));
1875             gnu_result = size_binop (MINUS_EXPR, gnu_result,
1876                                      bitsize_one_node);
1877             break;
1878
1879           case Attr_Bit_Position:
1880             gnu_result = gnu_field_bitpos;
1881             break;
1882                 }
1883
1884         /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
1885            handling.  */
1886         gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
1887         break;
1888       }
1889
1890     case Attr_Min:
1891     case Attr_Max:
1892       {
1893         tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
1894         tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
1895
1896         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1897         gnu_result = build_binary_op (attribute == Attr_Min
1898                                       ? MIN_EXPR : MAX_EXPR,
1899                                       gnu_result_type, gnu_lhs, gnu_rhs);
1900       }
1901       break;
1902
1903     case Attr_Passed_By_Reference:
1904       gnu_result = size_int (default_pass_by_ref (gnu_type)
1905                              || must_pass_by_ref (gnu_type));
1906       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1907       break;
1908
1909     case Attr_Component_Size:
1910       if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1911           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1912         gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1913
1914       gnu_prefix = maybe_implicit_deref (gnu_prefix);
1915       gnu_type = TREE_TYPE (gnu_prefix);
1916
1917       if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1918         gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
1919
1920       while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
1921              && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
1922         gnu_type = TREE_TYPE (gnu_type);
1923
1924       gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
1925
1926       /* Note this size cannot be self-referential.  */
1927       gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
1928       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1929       prefix_unused = true;
1930       break;
1931
1932     case Attr_Descriptor_Size:
1933       gnu_type = TREE_TYPE (gnu_prefix);
1934       gcc_assert (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE);
1935
1936       /* What we want is the offset of the ARRAY field in the record that the
1937         thin pointer designates, but the components have been shifted so this
1938         is actually the opposite of the offset of the BOUNDS field.  */
1939       gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1940       gnu_result = size_binop (MINUS_EXPR, bitsize_zero_node,
1941                                bit_position (TYPE_FIELDS (gnu_type)));
1942       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1943       prefix_unused = true;
1944       break;
1945
1946     case Attr_Null_Parameter:
1947       /* This is just a zero cast to the pointer type for our prefix and
1948          dereferenced.  */
1949       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1950       gnu_result
1951         = build_unary_op (INDIRECT_REF, NULL_TREE,
1952                           convert (build_pointer_type (gnu_result_type),
1953                                    integer_zero_node));
1954       TREE_PRIVATE (gnu_result) = 1;
1955       break;
1956
1957     case Attr_Mechanism_Code:
1958       {
1959         int code;
1960         Entity_Id gnat_obj = Entity (Prefix (gnat_node));
1961
1962         prefix_unused = true;
1963         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1964         if (Present (Expressions (gnat_node)))
1965           {
1966             int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
1967
1968             for (gnat_obj = First_Formal (gnat_obj); i > 1;
1969                  i--, gnat_obj = Next_Formal (gnat_obj))
1970               ;
1971           }
1972
1973         code = Mechanism (gnat_obj);
1974         if (code == Default)
1975           code = ((present_gnu_tree (gnat_obj)
1976                    && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
1977                        || ((TREE_CODE (get_gnu_tree (gnat_obj))
1978                             == PARM_DECL)
1979                            && (DECL_BY_COMPONENT_PTR_P
1980                                (get_gnu_tree (gnat_obj))))))
1981                   ? By_Reference : By_Copy);
1982         gnu_result = convert (gnu_result_type, size_int (- code));
1983       }
1984       break;
1985
1986     default:
1987       /* Say we have an unimplemented attribute.  Then set the value to be
1988          returned to be a zero and hope that's something we can convert to
1989          the type of this attribute.  */
1990       post_error ("unimplemented attribute", gnat_node);
1991       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1992       gnu_result = integer_zero_node;
1993       break;
1994     }
1995
1996   /* If this is an attribute where the prefix was unused, force a use of it if
1997      it has a side-effect.  But don't do it if the prefix is just an entity
1998      name.  However, if an access check is needed, we must do it.  See second
1999      example in AARM 11.6(5.e).  */
2000   if (prefix_unused && TREE_SIDE_EFFECTS (gnu_prefix)
2001       && !Is_Entity_Name (Prefix (gnat_node)))
2002     gnu_result = build_compound_expr  (TREE_TYPE (gnu_result), gnu_prefix,
2003                                        gnu_result);
2004
2005   *gnu_result_type_p = gnu_result_type;
2006   return gnu_result;
2007 }
2008 \f
2009 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Case_Statement,
2010    to a GCC tree, which is returned.  */
2011
2012 static tree
2013 Case_Statement_to_gnu (Node_Id gnat_node)
2014 {
2015   tree gnu_result, gnu_expr, gnu_label;
2016   Node_Id gnat_when;
2017   location_t end_locus;
2018   bool may_fallthru = false;
2019
2020   gnu_expr = gnat_to_gnu (Expression (gnat_node));
2021   gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2022
2023   /*  The range of values in a case statement is determined by the rules in
2024       RM 5.4(7-9). In almost all cases, this range is represented by the Etype
2025       of the expression. One exception arises in the case of a simple name that
2026       is parenthesized. This still has the Etype of the name, but since it is
2027       not a name, para 7 does not apply, and we need to go to the base type.
2028       This is the only case where parenthesization affects the dynamic
2029       semantics (i.e. the range of possible values at run time that is covered
2030       by the others alternative).
2031
2032       Another exception is if the subtype of the expression is non-static.  In
2033       that case, we also have to use the base type.  */
2034   if (Paren_Count (Expression (gnat_node)) != 0
2035       || !Is_OK_Static_Subtype (Underlying_Type
2036                                 (Etype (Expression (gnat_node)))))
2037     gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2038
2039   /* We build a SWITCH_EXPR that contains the code with interspersed
2040      CASE_LABEL_EXPRs for each label.  */
2041   if (!Sloc_to_locus (Sloc (gnat_node) + UI_To_Int (End_Span (gnat_node)),
2042       &end_locus))
2043     end_locus = input_location;
2044   gnu_label = create_artificial_label (end_locus);
2045   start_stmt_group ();
2046
2047   for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
2048        Present (gnat_when);
2049        gnat_when = Next_Non_Pragma (gnat_when))
2050     {
2051       bool choices_added_p = false;
2052       Node_Id gnat_choice;
2053
2054       /* First compile all the different case choices for the current WHEN
2055          alternative.  */
2056       for (gnat_choice = First (Discrete_Choices (gnat_when));
2057            Present (gnat_choice); gnat_choice = Next (gnat_choice))
2058         {
2059           tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2060
2061           switch (Nkind (gnat_choice))
2062             {
2063             case N_Range:
2064               gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
2065               gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
2066               break;
2067
2068             case N_Subtype_Indication:
2069               gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
2070                                                 (Constraint (gnat_choice))));
2071               gnu_high = gnat_to_gnu (High_Bound (Range_Expression
2072                                                   (Constraint (gnat_choice))));
2073               break;
2074
2075             case N_Identifier:
2076             case N_Expanded_Name:
2077               /* This represents either a subtype range or a static value of
2078                  some kind; Ekind says which.  */
2079               if (IN (Ekind (Entity (gnat_choice)), Type_Kind))
2080                 {
2081                   tree gnu_type = get_unpadded_type (Entity (gnat_choice));
2082
2083                   gnu_low = fold (TYPE_MIN_VALUE (gnu_type));
2084                   gnu_high = fold (TYPE_MAX_VALUE (gnu_type));
2085                   break;
2086                 }
2087
2088               /* ... fall through ... */
2089
2090             case N_Character_Literal:
2091             case N_Integer_Literal:
2092               gnu_low = gnat_to_gnu (gnat_choice);
2093               break;
2094
2095             case N_Others_Choice:
2096               break;
2097
2098             default:
2099               gcc_unreachable ();
2100             }
2101
2102           /* If the case value is a subtype that raises Constraint_Error at
2103              run time because of a wrong bound, then gnu_low or gnu_high is
2104              not translated into an INTEGER_CST.  In such a case, we need
2105              to ensure that the when statement is not added in the tree,
2106              otherwise it will crash the gimplifier.  */
2107           if ((!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST)
2108               && (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST))
2109             {
2110               add_stmt_with_node (build_case_label
2111                                   (gnu_low, gnu_high,
2112                                    create_artificial_label (input_location)),
2113                                   gnat_choice);
2114               choices_added_p = true;
2115             }
2116         }
2117
2118       /* Push a binding level here in case variables are declared as we want
2119          them to be local to this set of statements instead of to the block
2120          containing the Case statement.  */
2121       if (choices_added_p)
2122         {
2123           tree group = build_stmt_group (Statements (gnat_when), true);
2124           bool group_may_fallthru = block_may_fallthru (group);
2125           add_stmt (group);
2126           if (group_may_fallthru)
2127             {
2128               tree stmt = build1 (GOTO_EXPR, void_type_node, gnu_label);
2129               SET_EXPR_LOCATION (stmt, end_locus);
2130               add_stmt (stmt);
2131               may_fallthru = true;
2132             }
2133         }
2134     }
2135
2136   /* Now emit a definition of the label the cases branch to, if any.  */
2137   if (may_fallthru)
2138     add_stmt (build1 (LABEL_EXPR, void_type_node, gnu_label));
2139   gnu_result = build3 (SWITCH_EXPR, TREE_TYPE (gnu_expr), gnu_expr,
2140                        end_stmt_group (), NULL_TREE);
2141
2142   return gnu_result;
2143 }
2144 \f
2145 /* Find out whether VAR is an iteration variable of an enclosing loop in the
2146    current function.  If so, push a range_check_info structure onto the stack
2147    of this enclosing loop and return it.  Otherwise, return NULL.  */
2148
2149 static struct range_check_info_d *
2150 push_range_check_info (tree var)
2151 {
2152   struct loop_info_d *iter = NULL;
2153   unsigned int i;
2154
2155   if (VEC_empty (loop_info, gnu_loop_stack))
2156     return NULL;
2157
2158   var = remove_conversions (var, false);
2159
2160   if (TREE_CODE (var) != VAR_DECL)
2161     return NULL;
2162
2163   if (decl_function_context (var) != current_function_decl)
2164     return NULL;
2165
2166   for (i = VEC_length (loop_info, gnu_loop_stack) - 1;
2167        VEC_iterate (loop_info, gnu_loop_stack, i, iter);
2168        i--)
2169     if (var == iter->loop_var)
2170       break;
2171
2172   if (iter)
2173     {
2174       struct range_check_info_d *rci = ggc_alloc_range_check_info_d ();
2175       VEC_safe_push (range_check_info, gc, iter->checks, rci);
2176       return rci;
2177     }
2178
2179   return NULL;
2180 }
2181
2182 /* Return true if VAL (of type TYPE) can equal the minimum value if MAX is
2183    false, or the maximum value if MAX is true, of TYPE.  */
2184
2185 static bool
2186 can_equal_min_or_max_val_p (tree val, tree type, bool max)
2187 {
2188   tree min_or_max_val = (max ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type));
2189
2190   if (TREE_CODE (min_or_max_val) != INTEGER_CST)
2191     return true;
2192
2193   if (TREE_CODE (val) == NOP_EXPR)
2194     val = (max
2195            ? TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val, 0)))
2196            : TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val, 0))));
2197
2198   if (TREE_CODE (val) != INTEGER_CST)
2199     return true;
2200
2201   return tree_int_cst_equal (val, min_or_max_val) == 1;
2202 }
2203
2204 /* Return true if VAL (of type TYPE) can equal the minimum value of TYPE.
2205    If REVERSE is true, minimum value is taken as maximum value.  */
2206
2207 static inline bool
2208 can_equal_min_val_p (tree val, tree type, bool reverse)
2209 {
2210   return can_equal_min_or_max_val_p (val, type, reverse);
2211 }
2212
2213 /* Return true if VAL (of type TYPE) can equal the maximum value of TYPE.
2214    If REVERSE is true, maximum value is taken as minimum value.  */
2215
2216 static inline bool
2217 can_equal_max_val_p (tree val, tree type, bool reverse)
2218 {
2219   return can_equal_min_or_max_val_p (val, type, !reverse);
2220 }
2221
2222 /* Return true if VAL1 can be lower than VAL2.  */
2223
2224 static bool
2225 can_be_lower_p (tree val1, tree val2)
2226 {
2227   if (TREE_CODE (val1) == NOP_EXPR)
2228     val1 = TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val1, 0)));
2229
2230   if (TREE_CODE (val1) != INTEGER_CST)
2231     return true;
2232
2233   if (TREE_CODE (val2) == NOP_EXPR)
2234     val2 = TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val2, 0)));
2235
2236   if (TREE_CODE (val2) != INTEGER_CST)
2237     return true;
2238
2239   return tree_int_cst_lt (val1, val2);
2240 }
2241
2242 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Loop_Statement,
2243    to a GCC tree, which is returned.  */
2244
2245 static tree
2246 Loop_Statement_to_gnu (Node_Id gnat_node)
2247 {
2248   const Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
2249   struct loop_info_d *gnu_loop_info = ggc_alloc_cleared_loop_info_d ();
2250   tree gnu_loop_stmt = build4 (LOOP_STMT, void_type_node, NULL_TREE,
2251                                NULL_TREE, NULL_TREE, NULL_TREE);
2252   tree gnu_loop_label = create_artificial_label (input_location);
2253   tree gnu_cond_expr = NULL_TREE, gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2254   tree gnu_result;
2255
2256   /* Push the loop_info structure associated with the LOOP_STMT.  */
2257   VEC_safe_push (loop_info, gc, gnu_loop_stack, gnu_loop_info);
2258
2259   /* Set location information for statement and end label.  */
2260   set_expr_location_from_node (gnu_loop_stmt, gnat_node);
2261   Sloc_to_locus (Sloc (End_Label (gnat_node)),
2262                  &DECL_SOURCE_LOCATION (gnu_loop_label));
2263   LOOP_STMT_LABEL (gnu_loop_stmt) = gnu_loop_label;
2264
2265   /* Save the label so that a corresponding N_Exit_Statement can find it.  */
2266   gnu_loop_info->label = gnu_loop_label;
2267
2268   /* Set the condition under which the loop must keep going.
2269      For the case "LOOP .... END LOOP;" the condition is always true.  */
2270   if (No (gnat_iter_scheme))
2271     ;
2272
2273   /* For the case "WHILE condition LOOP ..... END LOOP;" it's immediate.  */
2274   else if (Present (Condition (gnat_iter_scheme)))
2275     LOOP_STMT_COND (gnu_loop_stmt)
2276       = gnat_to_gnu (Condition (gnat_iter_scheme));
2277
2278   /* Otherwise we have an iteration scheme and the condition is given by the
2279      bounds of the subtype of the iteration variable.  */
2280   else
2281     {
2282       Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
2283       Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
2284       Entity_Id gnat_type = Etype (gnat_loop_var);
2285       tree gnu_type = get_unpadded_type (gnat_type);
2286       tree gnu_base_type = get_base_type (gnu_type);
2287       tree gnu_one_node = convert (gnu_base_type, integer_one_node);
2288       tree gnu_loop_var, gnu_loop_iv, gnu_first, gnu_last, gnu_stmt;
2289       enum tree_code update_code, test_code, shift_code;
2290       bool reverse = Reverse_Present (gnat_loop_spec), use_iv = false;
2291
2292       gnu_low = TYPE_MIN_VALUE (gnu_type);
2293       gnu_high = TYPE_MAX_VALUE (gnu_type);
2294
2295       /* We must disable modulo reduction for the iteration variable, if any,
2296          in order for the loop comparison to be effective.  */
2297       if (reverse)
2298         {
2299           gnu_first = gnu_high;
2300           gnu_last = gnu_low;
2301           update_code = MINUS_NOMOD_EXPR;
2302           test_code = GE_EXPR;
2303           shift_code = PLUS_NOMOD_EXPR;
2304         }
2305       else
2306         {
2307           gnu_first = gnu_low;
2308           gnu_last = gnu_high;
2309           update_code = PLUS_NOMOD_EXPR;
2310           test_code = LE_EXPR;
2311           shift_code = MINUS_NOMOD_EXPR;
2312         }
2313
2314       /* We use two different strategies to translate the loop, depending on
2315          whether optimization is enabled.
2316
2317          If it is, we generate the canonical loop form expected by the loop
2318          optimizer and the loop vectorizer, which is the do-while form:
2319
2320              ENTRY_COND
2321            loop:
2322              TOP_UPDATE
2323              BODY
2324              BOTTOM_COND
2325              GOTO loop
2326
2327          This avoids an implicit dependency on loop header copying and makes
2328          it possible to turn BOTTOM_COND into an inequality test.
2329
2330          If optimization is disabled, loop header copying doesn't come into
2331          play and we try to generate the loop form with the fewer conditional
2332          branches.  First, the default form, which is:
2333
2334            loop:
2335              TOP_COND
2336              BODY
2337              BOTTOM_UPDATE
2338              GOTO loop
2339
2340          It should catch most loops with constant ending point.  Then, if we
2341          cannot, we try to generate the shifted form:
2342
2343            loop:
2344              TOP_COND
2345              TOP_UPDATE
2346              BODY
2347              GOTO loop
2348
2349          which should catch loops with constant starting point.  Otherwise, if
2350          we cannot, we generate the fallback form:
2351
2352              ENTRY_COND
2353            loop:
2354              BODY
2355              BOTTOM_COND
2356              BOTTOM_UPDATE
2357              GOTO loop
2358
2359          which works in all cases.  */
2360
2361       if (optimize)
2362         {
2363           /* We can use the do-while form directly if GNU_FIRST-1 doesn't
2364              overflow.  */
2365           if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse))
2366             ;
2367
2368           /* Otherwise, use the do-while form with the help of a special
2369              induction variable in the unsigned version of the base type
2370              or the unsigned version of the size type, whichever is the
2371              largest, in order to have wrap-around arithmetics for it.  */
2372           else
2373             {
2374               if (TYPE_PRECISION (gnu_base_type)
2375                   > TYPE_PRECISION (size_type_node))
2376                 gnu_base_type = gnat_unsigned_type (gnu_base_type);
2377               else
2378                 gnu_base_type = size_type_node;
2379
2380               gnu_first = convert (gnu_base_type, gnu_first);
2381               gnu_last = convert (gnu_base_type, gnu_last);
2382               gnu_one_node = convert (gnu_base_type, integer_one_node);
2383               use_iv = true;
2384             }
2385
2386           gnu_first
2387             = build_binary_op (shift_code, gnu_base_type, gnu_first,
2388                                gnu_one_node);
2389           LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
2390           LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
2391         }
2392       else
2393         {
2394           /* We can use the default form if GNU_LAST+1 doesn't overflow.  */
2395           if (!can_equal_max_val_p (gnu_last, gnu_base_type, reverse))
2396             ;
2397
2398           /* Otherwise, we can use the shifted form if neither GNU_FIRST-1 nor
2399              GNU_LAST-1 does.  */
2400           else if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse)
2401                    && !can_equal_min_val_p (gnu_last, gnu_base_type, reverse))
2402             {
2403               gnu_first
2404                 = build_binary_op (shift_code, gnu_base_type, gnu_first,
2405                                    gnu_one_node);
2406               gnu_last
2407                 = build_binary_op (shift_code, gnu_base_type, gnu_last,
2408                                    gnu_one_node);
2409               LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
2410             }
2411
2412           /* Otherwise, use the fallback form.  */
2413           else
2414             LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
2415         }
2416
2417       /* If we use the BOTTOM_COND, we can turn the test into an inequality
2418          test but we may have to add ENTRY_COND to protect the empty loop.  */
2419       if (LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt))
2420         {
2421           test_code = NE_EXPR;
2422           if (can_be_lower_p (gnu_high, gnu_low))
2423             {
2424               gnu_cond_expr
2425                 = build3 (COND_EXPR, void_type_node,
2426                           build_binary_op (LE_EXPR, boolean_type_node,
2427                                            gnu_low, gnu_high),
2428                           NULL_TREE, alloc_stmt_list ());
2429               set_expr_location_from_node (gnu_cond_expr, gnat_loop_spec);
2430             }
2431         }
2432
2433       /* Open a new nesting level that will surround the loop to declare the
2434          iteration variable.  */
2435       start_stmt_group ();
2436       gnat_pushlevel ();
2437
2438       /* If we use the special induction variable, create it and set it to
2439          its initial value.  Morever, the regular iteration variable cannot
2440          itself be initialized, lest the initial value wrapped around.  */
2441       if (use_iv)
2442         {
2443           gnu_loop_iv
2444             = create_init_temporary ("I", gnu_first, &gnu_stmt, gnat_loop_var);
2445           add_stmt (gnu_stmt);
2446           gnu_first = NULL_TREE;
2447         }
2448       else
2449         gnu_loop_iv = NULL_TREE;
2450
2451       /* Declare the iteration variable and set it to its initial value.  */
2452       gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, 1);
2453       if (DECL_BY_REF_P (gnu_loop_var))
2454         gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
2455       else if (use_iv)
2456         {
2457           gcc_assert (DECL_LOOP_PARM_P (gnu_loop_var));
2458           SET_DECL_INDUCTION_VAR (gnu_loop_var, gnu_loop_iv);
2459         }
2460       gnu_loop_info->loop_var = gnu_loop_var;
2461
2462       /* Do all the arithmetics in the base type.  */
2463       gnu_loop_var = convert (gnu_base_type, gnu_loop_var);
2464
2465       /* Set either the top or bottom exit condition.  */
2466       if (use_iv)
2467         LOOP_STMT_COND (gnu_loop_stmt)
2468           = build_binary_op (test_code, boolean_type_node, gnu_loop_iv,
2469                              gnu_last);
2470       else
2471         LOOP_STMT_COND (gnu_loop_stmt)
2472           = build_binary_op (test_code, boolean_type_node, gnu_loop_var,
2473                              gnu_last);
2474
2475       /* Set either the top or bottom update statement and give it the source
2476          location of the iteration for better coverage info.  */
2477       if (use_iv)
2478         {
2479           gnu_stmt
2480             = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_iv,
2481                                build_binary_op (update_code, gnu_base_type,
2482                                                 gnu_loop_iv, gnu_one_node));
2483           set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2484           append_to_statement_list (gnu_stmt,
2485                                     &LOOP_STMT_UPDATE (gnu_loop_stmt));
2486           gnu_stmt
2487             = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
2488                                gnu_loop_iv);
2489           set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2490           append_to_statement_list (gnu_stmt,
2491                                     &LOOP_STMT_UPDATE (gnu_loop_stmt));
2492         }
2493       else
2494         {
2495           gnu_stmt
2496             = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
2497                                build_binary_op (update_code, gnu_base_type,
2498                                                 gnu_loop_var, gnu_one_node));
2499           set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2500           LOOP_STMT_UPDATE (gnu_loop_stmt) = gnu_stmt;
2501         }
2502     }
2503
2504   /* If the loop was named, have the name point to this loop.  In this case,
2505      the association is not a DECL node, but the end label of the loop.  */
2506   if (Present (Identifier (gnat_node)))
2507     save_gnu_tree (Entity (Identifier (gnat_node)), gnu_loop_label, true);
2508
2509   /* Make the loop body into its own block, so any allocated storage will be
2510      released every iteration.  This is needed for stack allocation.  */
2511   LOOP_STMT_BODY (gnu_loop_stmt)
2512     = build_stmt_group (Statements (gnat_node), true);
2513   TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
2514
2515   /* If we have an iteration scheme, then we are in a statement group.  Add
2516      the LOOP_STMT to it, finish it and make it the "loop".  */
2517   if (Present (gnat_iter_scheme) && No (Condition (gnat_iter_scheme)))
2518     {
2519       struct range_check_info_d *rci;
2520       unsigned n_checks = VEC_length (range_check_info, gnu_loop_info->checks);
2521       unsigned int i;
2522
2523       /* First, if we have computed a small number of invariant conditions for
2524          range checks applied to the iteration variable, then initialize these
2525          conditions in front of the loop.  Otherwise, leave them set to True.
2526
2527          ??? The heuristics need to be improved, by taking into account the
2528              following datapoints:
2529                - loop unswitching is disabled for big loops.  The cap is the
2530                  parameter PARAM_MAX_UNSWITCH_INSNS (50).
2531                - loop unswitching can only be applied a small number of times
2532                  to a given loop.  The cap is PARAM_MAX_UNSWITCH_LEVEL (3).
2533                - the front-end quickly generates useless or redundant checks
2534                  that can be entirely optimized away in the end.  */
2535       if (1 <= n_checks && n_checks <= 4)
2536         for (i = 0;
2537              VEC_iterate (range_check_info, gnu_loop_info->checks, i, rci);
2538              i++)
2539           {
2540             tree low_ok
2541               = build_binary_op (GE_EXPR, boolean_type_node,
2542                                  convert (rci->type, gnu_low),
2543                                  rci->low_bound);
2544             tree high_ok
2545               = build_binary_op (LE_EXPR, boolean_type_node,
2546                                  convert (rci->type, gnu_high),
2547                                  rci->high_bound);
2548             tree range_ok
2549               = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
2550                                  low_ok, high_ok);
2551
2552             TREE_OPERAND (rci->invariant_cond, 0)
2553               = build_unary_op (TRUTH_NOT_EXPR, boolean_type_node, range_ok);
2554
2555             add_stmt_with_node_force (rci->invariant_cond, gnat_node);
2556           }
2557
2558       add_stmt (gnu_loop_stmt);
2559       gnat_poplevel ();
2560       gnu_loop_stmt = end_stmt_group ();
2561     }
2562
2563   /* If we have an outer COND_EXPR, that's our result and this loop is its
2564      "true" statement.  Otherwise, the result is the LOOP_STMT.  */
2565   if (gnu_cond_expr)
2566     {
2567       COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
2568       gnu_result = gnu_cond_expr;
2569       recalculate_side_effects (gnu_cond_expr);
2570     }
2571   else
2572     gnu_result = gnu_loop_stmt;
2573
2574   VEC_pop (loop_info, gnu_loop_stack);
2575
2576   return gnu_result;
2577 }
2578 \f
2579 /* Emit statements to establish __gnat_handle_vms_condition as a VMS condition
2580    handler for the current function.  */
2581
2582 /* This is implemented by issuing a call to the appropriate VMS specific
2583    builtin.  To avoid having VMS specific sections in the global gigi decls
2584    array, we maintain the decls of interest here.  We can't declare them
2585    inside the function because we must mark them never to be GC'd, which we
2586    can only do at the global level.  */
2587
2588 static GTY(()) tree vms_builtin_establish_handler_decl = NULL_TREE;
2589 static GTY(()) tree gnat_vms_condition_handler_decl = NULL_TREE;
2590
2591 static void
2592 establish_gnat_vms_condition_handler (void)
2593 {
2594   tree establish_stmt;
2595
2596   /* Elaborate the required decls on the first call.  Check on the decl for
2597      the gnat condition handler to decide, as this is one we create so we are
2598      sure that it will be non null on subsequent calls.  The builtin decl is
2599      looked up so remains null on targets where it is not implemented yet.  */
2600   if (gnat_vms_condition_handler_decl == NULL_TREE)
2601     {
2602       vms_builtin_establish_handler_decl
2603         = builtin_decl_for
2604           (get_identifier ("__builtin_establish_vms_condition_handler"));
2605
2606       gnat_vms_condition_handler_decl
2607         = create_subprog_decl (get_identifier ("__gnat_handle_vms_condition"),
2608                                NULL_TREE,
2609                                build_function_type_list (boolean_type_node,
2610                                                          ptr_void_type_node,
2611                                                          ptr_void_type_node,
2612                                                          NULL_TREE),
2613                                NULL_TREE, false, true, true, true, NULL,
2614                                Empty);
2615
2616       /* ??? DECL_CONTEXT shouldn't have been set because of DECL_EXTERNAL.  */
2617       DECL_CONTEXT (gnat_vms_condition_handler_decl) = NULL_TREE;
2618     }
2619
2620   /* Do nothing if the establish builtin is not available, which might happen
2621      on targets where the facility is not implemented.  */
2622   if (vms_builtin_establish_handler_decl == NULL_TREE)
2623     return;
2624
2625   establish_stmt
2626     = build_call_n_expr (vms_builtin_establish_handler_decl, 1,
2627                          build_unary_op
2628                          (ADDR_EXPR, NULL_TREE,
2629                           gnat_vms_condition_handler_decl));
2630
2631   add_stmt (establish_stmt);
2632 }
2633
2634 /* This page implements a form of Named Return Value optimization modelled
2635    on the C++ optimization of the same name.  The main difference is that
2636    we disregard any semantical considerations when applying it here, the
2637    counterpart being that we don't try to apply it to semantically loaded
2638    return types, i.e. types with the TREE_ADDRESSABLE flag set.
2639
2640    We consider a function body of the following GENERIC form:
2641
2642      return_type R1;
2643        [...]
2644      RETURN_EXPR [<retval> = ...]
2645        [...]
2646      RETURN_EXPR [<retval> = R1]
2647        [...]
2648      return_type Ri;
2649        [...]
2650      RETURN_EXPR [<retval> = ...]
2651        [...]
2652      RETURN_EXPR [<retval> = Ri]
2653        [...]
2654
2655    and we try to fulfill a simple criterion that would make it possible to
2656    replace one or several Ri variables with the RESULT_DECL of the function.
2657
2658    The first observation is that RETURN_EXPRs that don't directly reference
2659    any of the Ri variables on the RHS of their assignment are transparent wrt
2660    the optimization.  This is because the Ri variables aren't addressable so
2661    any transformation applied to them doesn't affect the RHS; moreover, the
2662    assignment writes the full <retval> object so existing values are entirely
2663    discarded.
2664
2665    This property can be extended to some forms of RETURN_EXPRs that reference
2666    the Ri variables, for example CONSTRUCTORs, but isn't true in the general
2667    case, in particular when function calls are involved.
2668
2669    Therefore the algorithm is as follows:
2670
2671      1. Collect the list of candidates for a Named Return Value (Ri variables
2672         on the RHS of assignments of RETURN_EXPRs) as well as the list of the
2673         other expressions on the RHS of such assignments.
2674
2675      2. Prune the members of the first list (candidates) that are referenced
2676         by a member of the second list (expressions).
2677
2678      3. Extract a set of candidates with non-overlapping live ranges from the
2679         first list.  These are the Named Return Values.
2680
2681      4. Adjust the relevant RETURN_EXPRs and replace the occurrences of the
2682         Named Return Values in the function with the RESULT_DECL.
2683
2684    If the function returns an unconstrained type, things are a bit different
2685    because the anonymous return object is allocated on the secondary stack
2686    and RESULT_DECL is only a pointer to it.  Each return object can be of a
2687    different size and is allocated separately so we need not care about the
2688    aforementioned overlapping issues.  Therefore, we don't collect the other
2689    expressions and skip step #2 in the algorithm.  */
2690
2691 struct nrv_data
2692 {
2693   bitmap nrv;
2694   tree result;
2695   Node_Id gnat_ret;
2696   struct pointer_set_t *visited;
2697 };
2698
2699 /* Return true if T is a Named Return Value.  */
2700
2701 static inline bool
2702 is_nrv_p (bitmap nrv, tree t)
2703 {
2704   return TREE_CODE (t) == VAR_DECL && bitmap_bit_p (nrv, DECL_UID (t));
2705 }
2706
2707 /* Helper function for walk_tree, used by finalize_nrv below.  */
2708
2709 static tree
2710 prune_nrv_r (tree *tp, int *walk_subtrees, void *data)
2711 {
2712   struct nrv_data *dp = (struct nrv_data *)data;
2713   tree t = *tp;
2714
2715   /* No need to walk into types or decls.  */
2716   if (IS_TYPE_OR_DECL_P (t))
2717     *walk_subtrees = 0;
2718
2719   if (is_nrv_p (dp->nrv, t))
2720     bitmap_clear_bit (dp->nrv, DECL_UID (t));
2721
2722   return NULL_TREE;
2723 }
2724
2725 /* Prune Named Return Values in BLOCK and return true if there is still a
2726    Named Return Value in BLOCK or one of its sub-blocks.  */
2727
2728 static bool
2729 prune_nrv_in_block (bitmap nrv, tree block)
2730 {
2731   bool has_nrv = false;
2732   tree t;
2733
2734   /* First recurse on the sub-blocks.  */
2735   for (t = BLOCK_SUBBLOCKS (block); t; t = BLOCK_CHAIN (t))
2736     has_nrv |= prune_nrv_in_block (nrv, t);
2737
2738   /* Then make sure to keep at most one NRV per block.  */
2739   for (t = BLOCK_VARS (block); t; t = DECL_CHAIN (t))
2740     if (is_nrv_p (nrv, t))
2741       {
2742         if (has_nrv)
2743           bitmap_clear_bit (nrv, DECL_UID (t));
2744         else
2745           has_nrv = true;
2746       }
2747
2748   return has_nrv;
2749 }
2750
2751 /* Helper function for walk_tree, used by finalize_nrv below.  */
2752
2753 static tree
2754 finalize_nrv_r (tree *tp, int *walk_subtrees, void *data)
2755 {
2756   struct nrv_data *dp = (struct nrv_data *)data;
2757   tree t = *tp;
2758
2759   /* No need to walk into types.  */
2760   if (TYPE_P (t))
2761     *walk_subtrees = 0;
2762
2763   /* Change RETURN_EXPRs of NRVs to just refer to the RESULT_DECL; this is a
2764      nop, but differs from using NULL_TREE in that it indicates that we care
2765      about the value of the RESULT_DECL.  */
2766   else if (TREE_CODE (t) == RETURN_EXPR
2767            && TREE_CODE (TREE_OPERAND (t, 0)) == MODIFY_EXPR)
2768     {
2769       tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1), init_expr;
2770
2771       /* If this is the temporary created for a return value with variable
2772          size in call_to_gnu, we replace the RHS with the init expression.  */
2773       if (TREE_CODE (ret_val) == COMPOUND_EXPR
2774           && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
2775           && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
2776              == TREE_OPERAND (ret_val, 1))
2777         {
2778           init_expr = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
2779           ret_val = TREE_OPERAND (ret_val, 1);
2780         }
2781       else
2782         init_expr = NULL_TREE;
2783
2784       /* Strip useless conversions around the return value.  */
2785       if (gnat_useless_type_conversion (ret_val))
2786         ret_val = TREE_OPERAND (ret_val, 0);
2787
2788       if (is_nrv_p (dp->nrv, ret_val))
2789         {
2790           if (init_expr)
2791             TREE_OPERAND (TREE_OPERAND (t, 0), 1) = init_expr;
2792           else
2793             TREE_OPERAND (t, 0) = dp->result;
2794         }
2795     }
2796
2797   /* Replace the DECL_EXPR of NRVs with an initialization of the RESULT_DECL,
2798      if needed.  */
2799   else if (TREE_CODE (t) == DECL_EXPR
2800            && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
2801     {
2802       tree var = DECL_EXPR_DECL (t), init;
2803
2804       if (DECL_INITIAL (var))
2805         {
2806           init = build_binary_op (INIT_EXPR, NULL_TREE, dp->result,
2807                                   DECL_INITIAL (var));
2808           SET_EXPR_LOCATION (init, EXPR_LOCATION (t));
2809           DECL_INITIAL (var) = NULL_TREE;
2810         }
2811       else
2812         init = build_empty_stmt (EXPR_LOCATION (t));
2813       *tp = init;
2814
2815       /* Identify the NRV to the RESULT_DECL for debugging purposes.  */
2816       SET_DECL_VALUE_EXPR (var, dp->result);
2817       DECL_HAS_VALUE_EXPR_P (var) = 1;
2818       /* ??? Kludge to avoid an assertion failure during inlining.  */
2819       DECL_SIZE (var) = bitsize_unit_node;
2820       DECL_SIZE_UNIT (var) = size_one_node;
2821     }
2822
2823   /* And replace all uses of NRVs with the RESULT_DECL.  */
2824   else if (is_nrv_p (dp->nrv, t))
2825     *tp = convert (TREE_TYPE (t), dp->result);
2826
2827   /* Avoid walking into the same tree more than once.  Unfortunately, we
2828      can't just use walk_tree_without_duplicates because it would only
2829      call us for the first occurrence of NRVs in the function body.  */
2830   if (pointer_set_insert (dp->visited, *tp))
2831     *walk_subtrees = 0;
2832
2833   return NULL_TREE;
2834 }
2835
2836 /* Likewise, but used when the function returns an unconstrained type.  */
2837
2838 static tree
2839 finalize_nrv_unc_r (tree *tp, int *walk_subtrees, void *data)
2840 {
2841   struct nrv_data *dp = (struct nrv_data *)data;
2842   tree t = *tp;
2843
2844   /* No need to walk into types.  */
2845   if (TYPE_P (t))
2846     *walk_subtrees = 0;
2847
2848   /* We need to see the DECL_EXPR of NRVs before any other references so we
2849      walk the body of BIND_EXPR before walking its variables.  */
2850   else if (TREE_CODE (t) == BIND_EXPR)
2851     walk_tree (&BIND_EXPR_BODY (t), finalize_nrv_unc_r, data, NULL);
2852
2853   /* Change RETURN_EXPRs of NRVs to assign to the RESULT_DECL only the final
2854      return value built by the allocator instead of the whole construct.  */
2855   else if (TREE_CODE (t) == RETURN_EXPR
2856            && TREE_CODE (TREE_OPERAND (t, 0)) == MODIFY_EXPR)
2857     {
2858       tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
2859
2860       /* This is the construct returned by the allocator.  */
2861       if (TREE_CODE (ret_val) == COMPOUND_EXPR
2862           && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR)
2863         {
2864           if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (ret_val)))
2865             ret_val
2866               = VEC_index (constructor_elt,
2867                            CONSTRUCTOR_ELTS
2868                            (TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1)),
2869                             1)->value;
2870           else
2871             ret_val = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
2872         }
2873
2874       /* Strip useless conversions around the return value.  */
2875       if (gnat_useless_type_conversion (ret_val)
2876           || TREE_CODE (ret_val) == VIEW_CONVERT_EXPR)
2877         ret_val = TREE_OPERAND (ret_val, 0);
2878
2879       /* Strip unpadding around the return value.  */
2880       if (TREE_CODE (ret_val) == COMPONENT_REF
2881           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
2882         ret_val = TREE_OPERAND (ret_val, 0);
2883
2884       /* Assign the new return value to the RESULT_DECL.  */
2885       if (is_nrv_p (dp->nrv, ret_val))
2886         TREE_OPERAND (TREE_OPERAND (t, 0), 1)
2887           = TREE_OPERAND (DECL_INITIAL (ret_val), 0);
2888     }
2889
2890   /* Adjust the DECL_EXPR of NRVs to call the allocator and save the result
2891      into a new variable.  */
2892   else if (TREE_CODE (t) == DECL_EXPR
2893            && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
2894     {
2895       tree saved_current_function_decl = current_function_decl;
2896       tree var = DECL_EXPR_DECL (t);
2897       tree alloc, p_array, new_var, new_ret;
2898       VEC(constructor_elt,gc) *v = VEC_alloc (constructor_elt, gc, 2);
2899
2900       /* Create an artificial context to build the allocation.  */
2901       current_function_decl = decl_function_context (var);
2902       start_stmt_group ();
2903       gnat_pushlevel ();
2904
2905       /* This will return a COMPOUND_EXPR with the allocation in the first
2906          arm and the final return value in the second arm.  */
2907       alloc = build_allocator (TREE_TYPE (var), DECL_INITIAL (var),
2908                                TREE_TYPE (dp->result),
2909                                Procedure_To_Call (dp->gnat_ret),
2910                                Storage_Pool (dp->gnat_ret),
2911                                Empty, false);
2912
2913       /* The new variable is built as a reference to the allocated space.  */
2914       new_var
2915         = build_decl (DECL_SOURCE_LOCATION (var), VAR_DECL, DECL_NAME (var),
2916                       build_reference_type (TREE_TYPE (var)));
2917       DECL_BY_REFERENCE (new_var) = 1;
2918
2919       if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (alloc)))
2920         {
2921           /* The new initial value is a COMPOUND_EXPR with the allocation in
2922              the first arm and the value of P_ARRAY in the second arm.  */
2923           DECL_INITIAL (new_var)
2924             = build2 (COMPOUND_EXPR, TREE_TYPE (new_var),
2925                       TREE_OPERAND (alloc, 0),
2926                       VEC_index (constructor_elt,
2927                                  CONSTRUCTOR_ELTS (TREE_OPERAND (alloc, 1)),
2928                                                    0)->value);
2929
2930           /* Build a modified CONSTRUCTOR that references NEW_VAR.  */
2931           p_array = TYPE_FIELDS (TREE_TYPE (alloc));
2932           CONSTRUCTOR_APPEND_ELT (v, p_array,
2933                                   fold_convert (TREE_TYPE (p_array), new_var));
2934           CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (p_array),
2935                                   VEC_index (constructor_elt,
2936                                              CONSTRUCTOR_ELTS
2937                                              (TREE_OPERAND (alloc, 1)),
2938                                               1)->value);
2939           new_ret = build_constructor (TREE_TYPE (alloc), v);
2940         }
2941       else
2942         {
2943           /* The new initial value is just the allocation.  */
2944           DECL_INITIAL (new_var) = alloc;
2945           new_ret = fold_convert (TREE_TYPE (alloc), new_var);
2946         }
2947
2948       gnat_pushdecl (new_var, Empty);
2949
2950       /* Destroy the artificial context and insert the new statements.  */
2951       gnat_zaplevel ();
2952       *tp = end_stmt_group ();
2953       current_function_decl = saved_current_function_decl;
2954
2955       /* Chain NEW_VAR immediately after VAR and ignore the latter.  */
2956       DECL_CHAIN (new_var) = DECL_CHAIN (var);
2957       DECL_CHAIN (var) = new_var;
2958       DECL_IGNORED_P (var) = 1;
2959
2960       /* Save the new return value and the dereference of NEW_VAR.  */
2961       DECL_INITIAL (var)
2962         = build2 (COMPOUND_EXPR, TREE_TYPE (var), new_ret,
2963                   build1 (INDIRECT_REF, TREE_TYPE (var), new_var));
2964       /* ??? Kludge to avoid messing up during inlining.  */
2965       DECL_CONTEXT (var) = NULL_TREE;
2966     }
2967
2968   /* And replace all uses of NRVs with the dereference of NEW_VAR.  */
2969   else if (is_nrv_p (dp->nrv, t))
2970     *tp = TREE_OPERAND (DECL_INITIAL (t), 1);
2971
2972   /* Avoid walking into the same tree more than once.  Unfortunately, we
2973      can't just use walk_tree_without_duplicates because it would only
2974      call us for the first occurrence of NRVs in the function body.  */
2975   if (pointer_set_insert (dp->visited, *tp))
2976     *walk_subtrees = 0;
2977
2978   return NULL_TREE;
2979 }
2980
2981 /* Finalize the Named Return Value optimization for FNDECL.  The NRV bitmap
2982    contains the candidates for Named Return Value and OTHER is a list of
2983    the other return values.  GNAT_RET is a representative return node.  */
2984
2985 static void
2986 finalize_nrv (tree fndecl, bitmap nrv, VEC(tree,gc) *other, Node_Id gnat_ret)
2987 {
2988   struct cgraph_node *node;
2989   struct nrv_data data;
2990   walk_tree_fn func;
2991   unsigned int i;
2992   tree iter;
2993
2994   /* We shouldn't be applying the optimization to return types that we aren't
2995      allowed to manipulate freely.  */
2996   gcc_assert (!TREE_ADDRESSABLE (TREE_TYPE (TREE_TYPE (fndecl))));
2997
2998   /* Prune the candidates that are referenced by other return values.  */
2999   data.nrv = nrv;
3000   data.result = NULL_TREE;
3001   data.visited = NULL;
3002   for (i = 0; VEC_iterate(tree, other, i, iter); i++)
3003     walk_tree_without_duplicates (&iter, prune_nrv_r, &data);
3004   if (bitmap_empty_p (nrv))
3005     return;
3006
3007   /* Prune also the candidates that are referenced by nested functions.  */
3008   node = cgraph_get_create_node (fndecl);
3009   for (node = node->nested; node; node = node->next_nested)
3010     walk_tree_without_duplicates (&DECL_SAVED_TREE (node->decl), prune_nrv_r,
3011                                   &data);
3012   if (bitmap_empty_p (nrv))
3013     return;
3014
3015   /* Extract a set of NRVs with non-overlapping live ranges.  */
3016   if (!prune_nrv_in_block (nrv, DECL_INITIAL (fndecl)))
3017     return;
3018
3019   /* Adjust the relevant RETURN_EXPRs and replace the occurrences of NRVs.  */
3020   data.nrv = nrv;
3021   data.result = DECL_RESULT (fndecl);
3022   data.gnat_ret = gnat_ret;
3023   data.visited = pointer_set_create ();
3024   if (TYPE_RETURN_UNCONSTRAINED_P (TREE_TYPE (fndecl)))
3025     func = finalize_nrv_unc_r;
3026   else
3027     func = finalize_nrv_r;
3028   walk_tree (&DECL_SAVED_TREE (fndecl), func, &data, NULL);
3029   pointer_set_destroy (data.visited);
3030 }
3031
3032 /* Return true if RET_VAL can be used as a Named Return Value for the
3033    anonymous return object RET_OBJ.  */
3034
3035 static bool
3036 return_value_ok_for_nrv_p (tree ret_obj, tree ret_val)
3037 {
3038   if (TREE_CODE (ret_val) != VAR_DECL)
3039     return false;
3040
3041   if (TREE_THIS_VOLATILE (ret_val))
3042     return false;
3043
3044   if (DECL_CONTEXT (ret_val) != current_function_decl)
3045     return false;
3046
3047   if (TREE_STATIC (ret_val))
3048     return false;
3049
3050   if (TREE_ADDRESSABLE (ret_val))
3051     return false;
3052
3053   if (ret_obj && DECL_ALIGN (ret_val) > DECL_ALIGN (ret_obj))
3054     return false;
3055
3056   return true;
3057 }
3058
3059 /* Build a RETURN_EXPR.  If RET_VAL is non-null, build a RETURN_EXPR around
3060    the assignment of RET_VAL to RET_OBJ.  Otherwise build a bare RETURN_EXPR
3061    around RESULT_OBJ, which may be null in this case.  */
3062
3063 static tree
3064 build_return_expr (tree ret_obj, tree ret_val)
3065 {
3066   tree result_expr;
3067
3068   if (ret_val)
3069     {
3070       /* The gimplifier explicitly enforces the following invariant:
3071
3072               RETURN_EXPR
3073                   |
3074               MODIFY_EXPR
3075               /        \
3076              /          \
3077          RET_OBJ        ...
3078
3079          As a consequence, type consistency dictates that we use the type
3080          of the RET_OBJ as the operation type.  */
3081       tree operation_type = TREE_TYPE (ret_obj);
3082
3083       /* Convert the right operand to the operation type.  Note that it's the
3084          same transformation as in the MODIFY_EXPR case of build_binary_op,
3085          with the assumption that the type cannot involve a placeholder.  */
3086       if (operation_type != TREE_TYPE (ret_val))
3087         ret_val = convert (operation_type, ret_val);
3088
3089       result_expr = build2 (MODIFY_EXPR, void_type_node, ret_obj, ret_val);
3090
3091       /* If the function returns an aggregate type, find out whether this is
3092          a candidate for Named Return Value.  If so, record it.  Otherwise,
3093          if this is an expression of some kind, record it elsewhere.  */
3094       if (optimize
3095           && AGGREGATE_TYPE_P (operation_type)
3096           && !TYPE_IS_FAT_POINTER_P (operation_type)
3097           && aggregate_value_p (operation_type, current_function_decl))
3098         {
3099           /* Recognize the temporary created for a return value with variable
3100              size in call_to_gnu.  We want to eliminate it if possible.  */
3101           if (TREE_CODE (ret_val) == COMPOUND_EXPR
3102               && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
3103               && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
3104                  == TREE_OPERAND (ret_val, 1))
3105             ret_val = TREE_OPERAND (ret_val, 1);
3106
3107           /* Strip useless conversions around the return value.  */
3108           if (gnat_useless_type_conversion (ret_val))
3109             ret_val = TREE_OPERAND (ret_val, 0);
3110
3111           /* Now apply the test to the return value.  */
3112           if (return_value_ok_for_nrv_p (ret_obj, ret_val))
3113             {
3114               if (!f_named_ret_val)
3115                 f_named_ret_val = BITMAP_GGC_ALLOC ();
3116               bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
3117             }
3118
3119           /* Note that we need not care about CONSTRUCTORs here, as they are
3120              totally transparent given the read-compose-write semantics of
3121              assignments from CONSTRUCTORs.  */
3122           else if (EXPR_P (ret_val))
3123             VEC_safe_push (tree, gc, f_other_ret_val, ret_val);
3124         }
3125     }
3126   else
3127     result_expr = ret_obj;
3128
3129   return build1 (RETURN_EXPR, void_type_node, result_expr);
3130 }
3131
3132 /* Build a stub for the subprogram specified by the GCC tree GNU_SUBPROG
3133    and the GNAT node GNAT_SUBPROG.  */
3134
3135 static void
3136 build_function_stub (tree gnu_subprog, Entity_Id gnat_subprog)
3137 {
3138   tree gnu_subprog_type, gnu_subprog_addr, gnu_subprog_call;
3139   tree gnu_subprog_param, gnu_stub_param, gnu_param;
3140   tree gnu_stub_decl = DECL_FUNCTION_STUB (gnu_subprog);
3141   VEC(tree,gc) *gnu_param_vec = NULL;
3142
3143   gnu_subprog_type = TREE_TYPE (gnu_subprog);
3144
3145   /* Initialize the information structure for the function.  */
3146   allocate_struct_function (gnu_stub_decl, false);
3147   set_cfun (NULL);
3148
3149   begin_subprog_body (gnu_stub_decl);
3150
3151   start_stmt_group ();
3152   gnat_pushlevel ();
3153
3154   /* Loop over the parameters of the stub and translate any of them
3155      passed by descriptor into a by reference one.  */
3156   for (gnu_stub_param = DECL_ARGUMENTS (gnu_stub_decl),
3157        gnu_subprog_param = DECL_ARGUMENTS (gnu_subprog);
3158        gnu_stub_param;
3159        gnu_stub_param = DECL_CHAIN (gnu_stub_param),
3160        gnu_subprog_param = DECL_CHAIN (gnu_subprog_param))
3161     {
3162       if (DECL_BY_DESCRIPTOR_P (gnu_stub_param))
3163         {
3164           gcc_assert (DECL_BY_REF_P (gnu_subprog_param));
3165           gnu_param
3166             = convert_vms_descriptor (TREE_TYPE (gnu_subprog_param),
3167                                       gnu_stub_param,
3168                                       DECL_PARM_ALT_TYPE (gnu_stub_param),
3169                                       DECL_BY_DOUBLE_REF_P (gnu_subprog_param),
3170                                       gnat_subprog);
3171         }
3172       else
3173         gnu_param = gnu_stub_param;
3174
3175       VEC_safe_push (tree, gc, gnu_param_vec, gnu_param);
3176     }
3177
3178   /* Invoke the internal subprogram.  */
3179   gnu_subprog_addr = build1 (ADDR_EXPR, build_pointer_type (gnu_subprog_type),
3180                              gnu_subprog);
3181   gnu_subprog_call = build_call_vec (TREE_TYPE (gnu_subprog_type),
3182                                      gnu_subprog_addr, gnu_param_vec);
3183
3184   /* Propagate the return value, if any.  */
3185   if (VOID_TYPE_P (TREE_TYPE (gnu_subprog_type)))
3186     add_stmt (gnu_subprog_call);
3187   else
3188     add_stmt (build_return_expr (DECL_RESULT (gnu_stub_decl),
3189                                  gnu_subprog_call));
3190
3191   gnat_poplevel ();
3192   end_subprog_body (end_stmt_group ());
3193   rest_of_subprog_body_compilation (gnu_stub_decl);
3194 }
3195 \f
3196 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Subprogram_Body.  We
3197    don't return anything.  */
3198
3199 static void
3200 Subprogram_Body_to_gnu (Node_Id gnat_node)
3201 {
3202   /* Defining identifier of a parameter to the subprogram.  */
3203   Entity_Id gnat_param;
3204   /* The defining identifier for the subprogram body. Note that if a
3205      specification has appeared before for this body, then the identifier
3206      occurring in that specification will also be a defining identifier and all
3207      the calls to this subprogram will point to that specification.  */
3208   Entity_Id gnat_subprog_id
3209     = (Present (Corresponding_Spec (gnat_node))
3210        ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
3211   /* The FUNCTION_DECL node corresponding to the subprogram spec.   */
3212   tree gnu_subprog_decl;
3213   /* Its RESULT_DECL node.  */
3214   tree gnu_result_decl;
3215   /* Its FUNCTION_TYPE node.  */
3216   tree gnu_subprog_type;
3217   /* The TYPE_CI_CO_LIST of its FUNCTION_TYPE node, if any.  */
3218   tree gnu_cico_list;
3219   /* The entry in the CI_CO_LIST that represents a function return, if any.  */
3220   tree gnu_return_var_elmt = NULL_TREE;
3221   tree gnu_result;
3222   struct language_function *gnu_subprog_language;
3223   VEC(parm_attr,gc) *cache;
3224
3225   /* If this is a generic object or if it has been eliminated,
3226      ignore it.  */
3227   if (Ekind (gnat_subprog_id) == E_Generic_Procedure
3228       || Ekind (gnat_subprog_id) == E_Generic_Function
3229       || Is_Eliminated (gnat_subprog_id))
3230     return;
3231
3232   /* If this subprogram acts as its own spec, define it.  Otherwise, just get
3233      the already-elaborated tree node.  However, if this subprogram had its
3234      elaboration deferred, we will already have made a tree node for it.  So
3235      treat it as not being defined in that case.  Such a subprogram cannot
3236      have an address clause or a freeze node, so this test is safe, though it
3237      does disable some otherwise-useful error checking.  */
3238   gnu_subprog_decl
3239     = gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE,
3240                           Acts_As_Spec (gnat_node)
3241                           && !present_gnu_tree (gnat_subprog_id));
3242   gnu_result_decl = DECL_RESULT (gnu_subprog_decl);
3243   gnu_subprog_type = TREE_TYPE (gnu_subprog_decl);
3244   gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
3245   if (gnu_cico_list)
3246     gnu_return_var_elmt = value_member (void_type_node, gnu_cico_list);
3247
3248   /* If the function returns by invisible reference, make it explicit in the
3249      function body.  See gnat_to_gnu_entity, E_Subprogram_Type case.
3250      Handle the explicit case here and the copy-in/copy-out case below.  */
3251   if (TREE_ADDRESSABLE (gnu_subprog_type) && !gnu_return_var_elmt)
3252     {
3253       TREE_TYPE (gnu_result_decl)
3254         = build_reference_type (TREE_TYPE (gnu_result_decl));
3255       relayout_decl (gnu_result_decl);
3256     }
3257
3258   /* Set the line number in the decl to correspond to that of the body so that
3259      the line number notes are written correctly.  */
3260   Sloc_to_locus (Sloc (gnat_node), &DECL_SOURCE_LOCATION (gnu_subprog_decl));
3261
3262   /* Initialize the information structure for the function.  */
3263   allocate_struct_function (gnu_subprog_decl, false);
3264   gnu_subprog_language = ggc_alloc_cleared_language_function ();
3265   DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language = gnu_subprog_language;
3266   set_cfun (NULL);
3267
3268   begin_subprog_body (gnu_subprog_decl);
3269
3270   /* If there are In Out or Out parameters, we need to ensure that the return
3271      statement properly copies them out.  We do this by making a new block and
3272      converting any return into a goto to a label at the end of the block.  */
3273   if (gnu_cico_list)
3274     {
3275       tree gnu_return_var = NULL_TREE;
3276
3277       VEC_safe_push (tree, gc, gnu_return_label_stack,
3278                      create_artificial_label (input_location));
3279
3280       start_stmt_group ();
3281       gnat_pushlevel ();
3282
3283       /* If this is a function with In Out or Out parameters, we also need a
3284          variable for the return value to be placed.  */
3285       if (gnu_return_var_elmt)
3286         {
3287           tree gnu_return_type
3288             = TREE_TYPE (TREE_PURPOSE (gnu_return_var_elmt));
3289
3290           /* If the function returns by invisible reference, make it
3291              explicit in the function body.  See gnat_to_gnu_entity,
3292              E_Subprogram_Type case.  */
3293           if (TREE_ADDRESSABLE (gnu_subprog_type))
3294             gnu_return_type = build_reference_type (gnu_return_type);
3295
3296           gnu_return_var
3297             = create_var_decl (get_identifier ("RETVAL"), NULL_TREE,
3298                                gnu_return_type, NULL_TREE, false, false,
3299                                false, false, NULL, gnat_subprog_id);
3300           TREE_VALUE (gnu_return_var_elmt) = gnu_return_var;
3301         }
3302
3303       VEC_safe_push (tree, gc, gnu_return_var_stack, gnu_return_var);
3304
3305       /* See whether there are parameters for which we don't have a GCC tree
3306          yet.  These must be Out parameters.  Make a VAR_DECL for them and
3307          put it into TYPE_CI_CO_LIST, which must contain an empty entry too.
3308          We can match up the entries because TYPE_CI_CO_LIST is in the order
3309          of the parameters.  */
3310       for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3311            Present (gnat_param);
3312            gnat_param = Next_Formal_With_Extras (gnat_param))
3313         if (!present_gnu_tree (gnat_param))
3314           {
3315             tree gnu_cico_entry = gnu_cico_list;
3316
3317             /* Skip any entries that have been already filled in; they must
3318                correspond to In Out parameters.  */
3319             while (gnu_cico_entry && TREE_VALUE (gnu_cico_entry))
3320               gnu_cico_entry = TREE_CHAIN (gnu_cico_entry);
3321
3322             /* Do any needed references for padded types.  */
3323             TREE_VALUE (gnu_cico_entry)
3324               = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_entry)),
3325                          gnat_to_gnu_entity (gnat_param, NULL_TREE, 1));
3326           }
3327     }
3328   else
3329     VEC_safe_push (tree, gc, gnu_return_label_stack, NULL_TREE);
3330
3331   /* Get a tree corresponding to the code for the subprogram.  */
3332   start_stmt_group ();
3333   gnat_pushlevel ();
3334
3335   /* On VMS, establish our condition handler to possibly turn a condition into
3336      the corresponding exception if the subprogram has a foreign convention or
3337      is exported.
3338
3339      To ensure proper execution of local finalizations on condition instances,
3340      we must turn a condition into the corresponding exception even if there
3341      is no applicable Ada handler, and need at least one condition handler per
3342      possible call chain involving GNAT code.  OTOH, establishing the handler
3343      has a cost so we want to minimize the number of subprograms into which
3344      this happens.  The foreign or exported condition is expected to satisfy
3345      all the constraints.  */
3346   if (TARGET_ABI_OPEN_VMS
3347       && (Has_Foreign_Convention (gnat_subprog_id)
3348           || Is_Exported (gnat_subprog_id)))
3349     establish_gnat_vms_condition_handler ();
3350
3351   process_decls (Declarations (gnat_node), Empty, Empty, true, true);
3352
3353   /* Generate the code of the subprogram itself.  A return statement will be
3354      present and any Out parameters will be handled there.  */
3355   add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
3356   gnat_poplevel ();
3357   gnu_result = end_stmt_group ();
3358
3359   /* If we populated the parameter attributes cache, we need to make sure that
3360      the cached expressions are evaluated on all the possible paths leading to
3361      their uses.  So we force their evaluation on entry of the function.  */
3362   cache = gnu_subprog_language->parm_attr_cache;
3363   if (cache)
3364     {
3365       struct parm_attr_d *pa;
3366       int i;
3367
3368       start_stmt_group ();
3369
3370       FOR_EACH_VEC_ELT (parm_attr, cache, i, pa)
3371         {
3372           if (pa->first)
3373             add_stmt_with_node_force (pa->first, gnat_node);
3374           if (pa->last)
3375             add_stmt_with_node_force (pa->last, gnat_node);
3376           if (pa->length)
3377             add_stmt_with_node_force (pa->length, gnat_node);
3378         }
3379
3380       add_stmt (gnu_result);
3381       gnu_result = end_stmt_group ();
3382
3383       gnu_subprog_language->parm_attr_cache = NULL;
3384     }
3385
3386   /* If we are dealing with a return from an Ada procedure with parameters
3387      passed by copy-in/copy-out, we need to return a record containing the
3388      final values of these parameters.  If the list contains only one entry,
3389      return just that entry though.
3390
3391      For a full description of the copy-in/copy-out parameter mechanism, see
3392      the part of the gnat_to_gnu_entity routine dealing with the translation
3393      of subprograms.
3394
3395      We need to make a block that contains the definition of that label and
3396      the copying of the return value.  It first contains the function, then
3397      the label and copy statement.  */
3398   if (gnu_cico_list)
3399     {
3400       tree gnu_retval;
3401
3402       add_stmt (gnu_result);
3403       add_stmt (build1 (LABEL_EXPR, void_type_node,
3404                         VEC_last (tree, gnu_return_label_stack)));
3405
3406       if (list_length (gnu_cico_list) == 1)
3407         gnu_retval = TREE_VALUE (gnu_cico_list);
3408       else
3409         gnu_retval = build_constructor_from_list (TREE_TYPE (gnu_subprog_type),
3410                                                   gnu_cico_list);
3411
3412       add_stmt_with_node (build_return_expr (gnu_result_decl, gnu_retval),
3413                           End_Label (Handled_Statement_Sequence (gnat_node)));
3414       gnat_poplevel ();
3415       gnu_result = end_stmt_group ();
3416     }
3417
3418   VEC_pop (tree, gnu_return_label_stack);
3419
3420   /* Attempt setting the end_locus of our GCC body tree, typically a
3421      BIND_EXPR or STATEMENT_LIST, then the end_locus of our GCC subprogram
3422      declaration tree.  */
3423   set_end_locus_from_node (gnu_result, gnat_node);
3424   set_end_locus_from_node (gnu_subprog_decl, gnat_node);
3425
3426   end_subprog_body (gnu_result);
3427
3428   /* Finally annotate the parameters and disconnect the trees for parameters
3429      that we have turned into variables since they are now unusable.  */
3430   for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3431        Present (gnat_param);
3432        gnat_param = Next_Formal_With_Extras (gnat_param))
3433     {
3434       tree gnu_param = get_gnu_tree (gnat_param);
3435       bool is_var_decl = (TREE_CODE (gnu_param) == VAR_DECL);
3436
3437       annotate_object (gnat_param, TREE_TYPE (gnu_param), NULL_TREE,
3438                        DECL_BY_REF_P (gnu_param),
3439                        !is_var_decl && DECL_BY_DOUBLE_REF_P (gnu_param));
3440
3441       if (is_var_decl)
3442         save_gnu_tree (gnat_param, NULL_TREE, false);
3443     }
3444
3445   /* Disconnect the variable created for the return value.  */
3446   if (gnu_return_var_elmt)
3447     TREE_VALUE (gnu_return_var_elmt) = void_type_node;
3448
3449   /* If the function returns an aggregate type and we have candidates for
3450      a Named Return Value, finalize the optimization.  */
3451   if (optimize && gnu_subprog_language->named_ret_val)
3452     {
3453       finalize_nrv (gnu_subprog_decl,
3454                     gnu_subprog_language->named_ret_val,
3455                     gnu_subprog_language->other_ret_val,
3456                     gnu_subprog_language->gnat_ret);
3457       gnu_subprog_language->named_ret_val = NULL;
3458       gnu_subprog_language->other_ret_val = NULL;
3459     }
3460
3461   rest_of_subprog_body_compilation (gnu_subprog_decl);
3462
3463   /* If there is a stub associated with the function, build it now.  */
3464   if (DECL_FUNCTION_STUB (gnu_subprog_decl))
3465     build_function_stub (gnu_subprog_decl, gnat_subprog_id);
3466
3467   mark_out_of_scope (Defining_Unit_Name (Specification (gnat_node)));
3468 }
3469 \f
3470 /* Return true if GNAT_NODE requires atomic synchronization.  */
3471
3472 static bool
3473 atomic_sync_required_p (Node_Id gnat_node)
3474 {
3475   const Node_Id gnat_parent = Parent (gnat_node);
3476   Node_Kind kind;
3477   unsigned char attr_id;
3478
3479   /* First, scan the node to find the Atomic_Sync_Required flag.  */
3480   kind = Nkind (gnat_node);
3481   if (kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
3482     {
3483       gnat_node = Expression (gnat_node);
3484       kind = Nkind (gnat_node);
3485     }
3486
3487   switch (kind)
3488     {
3489     case N_Expanded_Name:
3490     case N_Explicit_Dereference:
3491     case N_Identifier:
3492     case N_Indexed_Component:
3493     case N_Selected_Component:
3494       if (!Atomic_Sync_Required (gnat_node))
3495         return false;
3496       break;
3497
3498     default:
3499       return false;
3500     }
3501
3502   /* Then, scan the parent to find out cases where the flag is irrelevant.  */
3503   kind = Nkind (gnat_parent);
3504   switch (kind)
3505     {
3506     case N_Attribute_Reference:
3507       attr_id = Get_Attribute_Id (Attribute_Name (gnat_parent));
3508       /* Do not mess up machine code insertions.  */
3509       if (attr_id == Attr_Asm_Input || attr_id == Attr_Asm_Output)
3510         return false;
3511       break;
3512
3513     case N_Object_Renaming_Declaration:
3514       /* Do not generate a function call as a renamed object.  */
3515       return false;
3516
3517     default:
3518       break;
3519     }
3520
3521   return true;
3522 }
3523 \f
3524 /* Create a temporary variable with PREFIX and TYPE, and return it.  */
3525
3526 static tree
3527 create_temporary (const char *prefix, tree type)
3528 {
3529   tree gnu_temp = create_var_decl (create_tmp_var_name (prefix), NULL_TREE,
3530                                    type, NULL_TREE, false, false, false, false,
3531                                    NULL, Empty);
3532   DECL_ARTIFICIAL (gnu_temp) = 1;
3533   DECL_IGNORED_P (gnu_temp) = 1;
3534
3535   return gnu_temp;
3536 }
3537
3538 /* Create a temporary variable with PREFIX and initialize it with GNU_INIT.
3539    Put the initialization statement into GNU_INIT_STMT and annotate it with
3540    the SLOC of GNAT_NODE.  Return the temporary variable.  */
3541
3542 static tree
3543 create_init_temporary (const char *prefix, tree gnu_init, tree *gnu_init_stmt,
3544                        Node_Id gnat_node)
3545 {
3546   tree gnu_temp = create_temporary (prefix, TREE_TYPE (gnu_init));
3547
3548   *gnu_init_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_temp, gnu_init);
3549   set_expr_location_from_node (*gnu_init_stmt, gnat_node);
3550
3551   return gnu_temp;
3552 }
3553
3554 /* Subroutine of gnat_to_gnu to translate gnat_node, either an N_Function_Call
3555    or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
3556    GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
3557    If GNU_TARGET is non-null, this must be a function call on the RHS of a
3558    N_Assignment_Statement and the result is to be placed into that object.
3559    If, in addition, ATOMIC_SYNC is true, then the assignment to GNU_TARGET
3560    requires atomic synchronization.  */
3561
3562 static tree
3563 call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target,
3564              bool atomic_sync)
3565 {
3566   const bool function_call = (Nkind (gnat_node) == N_Function_Call);
3567   const bool returning_value = (function_call && !gnu_target);
3568   /* The GCC node corresponding to the GNAT subprogram name.  This can either
3569      be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
3570      or an indirect reference expression (an INDIRECT_REF node) pointing to a
3571      subprogram.  */
3572   tree gnu_subprog = gnat_to_gnu (Name (gnat_node));
3573   /* The FUNCTION_TYPE node giving the GCC type of the subprogram.  */
3574   tree gnu_subprog_type = TREE_TYPE (gnu_subprog);
3575   /* The return type of the FUNCTION_TYPE.  */
3576   tree gnu_result_type = TREE_TYPE (gnu_subprog_type);
3577   tree gnu_subprog_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_subprog);
3578   VEC(tree,gc) *gnu_actual_vec = NULL;
3579   tree gnu_name_list = NULL_TREE;
3580   tree gnu_stmt_list = NULL_TREE;
3581   tree gnu_after_list = NULL_TREE;
3582   tree gnu_retval = NULL_TREE;
3583   tree gnu_call, gnu_result;
3584   bool went_into_elab_proc = false;
3585   bool pushed_binding_level = false;
3586   Entity_Id gnat_formal;
3587   Node_Id gnat_actual;
3588
3589   gcc_assert (TREE_CODE (gnu_subprog_type) == FUNCTION_TYPE);
3590
3591   /* If we are calling a stubbed function, raise Program_Error, but Elaborate
3592      all our args first.  */
3593   if (TREE_CODE (gnu_subprog) == FUNCTION_DECL && DECL_STUBBED_P (gnu_subprog))
3594     {
3595       tree call_expr = build_call_raise (PE_Stubbed_Subprogram_Called,
3596                                          gnat_node, N_Raise_Program_Error);
3597
3598       for (gnat_actual = First_Actual (gnat_node);
3599            Present (gnat_actual);
3600            gnat_actual = Next_Actual (gnat_actual))
3601         add_stmt (gnat_to_gnu (gnat_actual));
3602
3603       if (returning_value)
3604         {
3605           *gnu_result_type_p = gnu_result_type;
3606           return build1 (NULL_EXPR, gnu_result_type, call_expr);
3607         }
3608
3609       return call_expr;
3610     }
3611
3612   /* The only way we can be making a call via an access type is if Name is an
3613      explicit dereference.  In that case, get the list of formal args from the
3614      type the access type is pointing to.  Otherwise, get the formals from the
3615      entity being called.  */
3616   if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
3617     gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
3618   else if (Nkind (Name (gnat_node)) == N_Attribute_Reference)
3619     /* Assume here that this must be 'Elab_Body or 'Elab_Spec.  */
3620     gnat_formal = Empty;
3621   else
3622     gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
3623
3624   /* The lifetime of the temporaries created for the call ends right after the
3625      return value is copied, so we can give them the scope of the elaboration
3626      routine at top level.  */
3627   if (!current_function_decl)
3628     {
3629       current_function_decl = get_elaboration_procedure ();
3630       went_into_elab_proc = true;
3631     }
3632
3633   /* First, create the temporary for the return value if we need it: for a
3634      variable-sized return type if there is no target and this is not an
3635      object declaration, or else there is a target and it is a slice or an
3636      array with fixed size, as the gimplifier doesn't handle these cases;
3637      otherwise for a function with copy-in/copy-out parameters if there is
3638      no target, because we need to preserve the return value before copying
3639      back the parameters.  This must be done before we push a binding level
3640      around the call as we will pop it before copying the return value.  */
3641   if (function_call
3642       && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
3643            && ((!gnu_target
3644                 && Nkind (Parent (gnat_node)) != N_Object_Declaration)
3645                || (gnu_target
3646                    && (TREE_CODE (gnu_target) == ARRAY_RANGE_REF
3647                        || (TREE_CODE (TREE_TYPE (gnu_target)) == ARRAY_TYPE
3648                            && TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_target)))
3649                               == INTEGER_CST)))))
3650           || (!gnu_target && TYPE_CI_CO_LIST (gnu_subprog_type))))
3651     gnu_retval = create_temporary ("R", gnu_result_type);
3652
3653   /* Create the list of the actual parameters as GCC expects it, namely a
3654      chain of TREE_LIST nodes in which the TREE_VALUE field of each node
3655      is an expression and the TREE_PURPOSE field is null.  But skip Out
3656      parameters not passed by reference and that need not be copied in.  */
3657   for (gnat_actual = First_Actual (gnat_node);
3658        Present (gnat_actual);
3659        gnat_formal = Next_Formal_With_Extras (gnat_formal),
3660        gnat_actual = Next_Actual (gnat_actual))
3661     {
3662       tree gnu_formal = present_gnu_tree (gnat_formal)
3663                         ? get_gnu_tree (gnat_formal) : NULL_TREE;
3664       tree gnu_formal_type = gnat_to_gnu_type (Etype (gnat_formal));
3665       const bool is_true_formal_parm
3666         = gnu_formal && TREE_CODE (gnu_formal) == PARM_DECL;
3667       const bool is_by_ref_formal_parm
3668         = is_true_formal_parm
3669           && (DECL_BY_REF_P (gnu_formal)
3670               || DECL_BY_COMPONENT_PTR_P (gnu_formal)
3671               || DECL_BY_DESCRIPTOR_P (gnu_formal));
3672       /* In the Out or In Out case, we must suppress conversions that yield
3673          an lvalue but can nevertheless cause the creation of a temporary,
3674          because we need the real object in this case, either to pass its
3675          address if it's passed by reference or as target of the back copy
3676          done after the call if it uses the copy-in/copy-out mechanism.
3677          We do it in the In case too, except for an unchecked conversion
3678          because it alone can cause the actual to be misaligned and the
3679          addressability test is applied to the real object.  */
3680       const bool suppress_type_conversion
3681         = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
3682             && Ekind (gnat_formal) != E_In_Parameter)
3683            || (Nkind (gnat_actual) == N_Type_Conversion
3684                && Is_Composite_Type (Underlying_Type (Etype (gnat_formal)))));
3685       Node_Id gnat_name = suppress_type_conversion
3686                           ? Expression (gnat_actual) : gnat_actual;
3687       tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
3688       tree gnu_actual;
3689
3690       /* If it's possible we may need to use this expression twice, make sure
3691          that any side-effects are handled via SAVE_EXPRs; likewise if we need
3692          to force side-effects before the call.
3693          ??? This is more conservative than we need since we don't need to do
3694          this for pass-by-ref with no conversion.  */
3695       if (Ekind (gnat_formal) != E_In_Parameter)
3696         gnu_name = gnat_stabilize_reference (gnu_name, true, NULL);
3697
3698       /* If we are passing a non-addressable parameter by reference, pass the
3699          address of a copy.  In the Out or In Out case, set up to copy back
3700          out after the call.  */
3701       if (is_by_ref_formal_parm
3702           && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
3703           && !addressable_p (gnu_name, gnu_name_type))
3704         {
3705           bool in_param = (Ekind (gnat_formal) == E_In_Parameter);
3706           tree gnu_orig = gnu_name, gnu_temp, gnu_stmt;
3707
3708           /* Do not issue warnings for CONSTRUCTORs since this is not a copy
3709              but sort of an instantiation for them.  */
3710           if (TREE_CODE (gnu_name) == CONSTRUCTOR)
3711             ;
3712
3713           /* If the type is passed by reference, a copy is not allowed.  */
3714           else if (TREE_ADDRESSABLE (gnu_formal_type))
3715             post_error ("misaligned actual cannot be passed by reference",
3716                         gnat_actual);
3717
3718           /* For users of Starlet we issue a warning because the interface
3719              apparently assumes that by-ref parameters outlive the procedure
3720              invocation.  The code still will not work as intended, but we
3721              cannot do much better since low-level parts of the back-end
3722              would allocate temporaries at will because of the misalignment
3723              if we did not do so here.  */
3724           else if (Is_Valued_Procedure (Entity (Name (gnat_node))))
3725             {
3726               post_error
3727                 ("?possible violation of implicit assumption", gnat_actual);
3728               post_error_ne
3729                 ("?made by pragma Import_Valued_Procedure on &", gnat_actual,
3730                  Entity (Name (gnat_node)));
3731               post_error_ne ("?because of misalignment of &", gnat_actual,
3732                              gnat_formal);
3733             }
3734
3735           /* If the actual type of the object is already the nominal type,
3736              we have nothing to do, except if the size is self-referential
3737              in which case we'll remove the unpadding below.  */
3738           if (TREE_TYPE (gnu_name) == gnu_name_type
3739               && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_name_type)))
3740             ;
3741
3742           /* Otherwise remove the unpadding from all the objects.  */
3743           else if (TREE_CODE (gnu_name) == COMPONENT_REF
3744                    && TYPE_IS_PADDING_P
3745                       (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))
3746             gnu_orig = gnu_name = TREE_OPERAND (gnu_name, 0);
3747
3748           /* Otherwise convert to the nominal type of the object if needed.
3749              There are several cases in which we need to make the temporary
3750              using this type instead of the actual type of the object when
3751              they are distinct, because the expectations of the callee would
3752              otherwise not be met:
3753                - if it's a justified modular type,
3754                - if the actual type is a smaller form of it,
3755                - if it's a smaller form of the actual type.  */
3756           else if ((TREE_CODE (gnu_name_type) == RECORD_TYPE
3757                     && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
3758                         || smaller_form_type_p (TREE_TYPE (gnu_name),
3759                                                 gnu_name_type)))
3760                    || (INTEGRAL_TYPE_P (gnu_name_type)
3761                        && smaller_form_type_p (gnu_name_type,
3762                                                TREE_TYPE (gnu_name))))
3763             gnu_name = convert (gnu_name_type, gnu_name);
3764
3765           /* If this is an In Out or Out parameter and we're returning a value,
3766              we need to create a temporary for the return value because we must
3767              preserve it before copying back at the very end.  */
3768           if (!in_param && returning_value && !gnu_retval)
3769             gnu_retval = create_temporary ("R", gnu_result_type);
3770
3771           /* If we haven't pushed a binding level, push a new one.  This will
3772              narrow the lifetime of the temporary we are about to make as much
3773              as possible.  The drawback is that we'd need to create a temporary
3774              for the return value, if any (see comment before the loop).  So do
3775              it only when this temporary was already created just above.  */
3776           if (!pushed_binding_level && !(in_param && returning_value))
3777             {
3778               start_stmt_group ();
3779               gnat_pushlevel ();
3780               pushed_binding_level = true;
3781             }
3782
3783           /* Create an explicit temporary holding the copy.  */
3784           gnu_temp
3785             = create_init_temporary ("A", gnu_name, &gnu_stmt, gnat_actual);
3786
3787           /* But initialize it on the fly like for an implicit temporary as
3788              we aren't necessarily having a statement list.  */
3789           gnu_name = build_compound_expr (TREE_TYPE (gnu_name), gnu_stmt,
3790                                           gnu_temp);
3791
3792           /* Set up to move the copy back to the original if needed.  */
3793           if (!in_param)
3794             {
3795               gnu_stmt = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_orig,
3796                                           gnu_temp);
3797               set_expr_location_from_node (gnu_stmt, gnat_node);
3798               append_to_statement_list (gnu_stmt, &gnu_after_list);
3799             }
3800         }
3801
3802       /* Start from the real object and build the actual.  */
3803       gnu_actual = gnu_name;
3804
3805       /* If this is an atomic access of an In or In Out parameter for which
3806          synchronization is required, build the atomic load.  */
3807       if (is_true_formal_parm
3808           && !is_by_ref_formal_parm
3809           && Ekind (gnat_formal) != E_Out_Parameter
3810           && atomic_sync_required_p (gnat_actual))
3811         gnu_actual = build_atomic_load (gnu_actual);
3812
3813       /* If this was a procedure call, we may not have removed any padding.
3814          So do it here for the part we will use as an input, if any.  */
3815       if (Ekind (gnat_formal) != E_Out_Parameter
3816           && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
3817         gnu_actual
3818           = convert (get_unpadded_type (Etype (gnat_actual)), gnu_actual);
3819
3820       /* Put back the conversion we suppressed above in the computation of the
3821          real object.  And even if we didn't suppress any conversion there, we
3822          may have suppressed a conversion to the Etype of the actual earlier,
3823          since the parent is a procedure call, so put it back here.  */
3824       if (suppress_type_conversion
3825           && Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
3826         gnu_actual
3827           = unchecked_convert (gnat_to_gnu_type (Etype (gnat_actual)),
3828                                gnu_actual, No_Truncation (gnat_actual));
3829       else
3830         gnu_actual
3831           = convert (gnat_to_gnu_type (Etype (gnat_actual)), gnu_actual);
3832
3833       /* Make sure that the actual is in range of the formal's type.  */
3834       if (Ekind (gnat_formal) != E_Out_Parameter
3835           && Do_Range_Check (gnat_actual))
3836         gnu_actual
3837           = emit_range_check (gnu_actual, Etype (gnat_formal), gnat_actual);
3838
3839       /* Unless this is an In parameter, we must remove any justified modular
3840          building from GNU_NAME to get an lvalue.  */
3841       if (Ekind (gnat_formal) != E_In_Parameter
3842           && TREE_CODE (gnu_name) == CONSTRUCTOR
3843           && TREE_CODE (TREE_TYPE (gnu_name)) == RECORD_TYPE
3844           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (gnu_name)))
3845         gnu_name
3846           = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_name))), gnu_name);
3847
3848       /* If we have not saved a GCC object for the formal, it means it is an
3849          Out parameter not passed by reference and that need not be copied in.
3850          Otherwise, first see if the parameter is passed by reference.  */
3851       if (is_true_formal_parm && DECL_BY_REF_P (gnu_formal))
3852         {
3853           if (Ekind (gnat_formal) != E_In_Parameter)
3854             {
3855               /* In Out or Out parameters passed by reference don't use the
3856                  copy-in/copy-out mechanism so the address of the real object
3857                  must be passed to the function.  */
3858               gnu_actual = gnu_name;
3859
3860               /* If we have a padded type, be sure we've removed padding.  */
3861               if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
3862                 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
3863                                       gnu_actual);
3864
3865               /* If we have the constructed subtype of an aliased object
3866                  with an unconstrained nominal subtype, the type of the
3867                  actual includes the template, although it is formally
3868                  constrained.  So we need to convert it back to the real
3869                  constructed subtype to retrieve the constrained part
3870                  and takes its address.  */
3871               if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
3872                   && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
3873                   && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
3874                   && Is_Array_Type (Etype (gnat_actual)))
3875                 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
3876                                       gnu_actual);
3877             }
3878
3879           /* There is no need to convert the actual to the formal's type before
3880              taking its address.  The only exception is for unconstrained array
3881              types because of the way we build fat pointers.  */
3882           if (TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
3883             {
3884               /* Put back a view conversion for In Out or Out parameters.  */
3885               if (Ekind (gnat_formal) != E_In_Parameter)
3886                 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
3887                                       gnu_actual);
3888               gnu_actual = convert (gnu_formal_type, gnu_actual);
3889             }
3890
3891           /* The symmetry of the paths to the type of an entity is broken here
3892              since arguments don't know that they will be passed by ref.  */
3893           gnu_formal_type = TREE_TYPE (gnu_formal);
3894
3895           if (DECL_BY_DOUBLE_REF_P (gnu_formal))
3896             gnu_actual
3897               = build_unary_op (ADDR_EXPR, TREE_TYPE (gnu_formal_type),
3898                                 gnu_actual);
3899
3900           gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
3901         }
3902       else if (is_true_formal_parm && DECL_BY_COMPONENT_PTR_P (gnu_formal))
3903         {
3904           gnu_formal_type = TREE_TYPE (gnu_formal);
3905           gnu_actual = maybe_implicit_deref (gnu_actual);
3906           gnu_actual = maybe_unconstrained_array (gnu_actual);
3907
3908           if (TYPE_IS_PADDING_P (gnu_formal_type))
3909             {
3910               gnu_formal_type = TREE_TYPE (TYPE_FIELDS (gnu_formal_type));
3911               gnu_actual = convert (gnu_formal_type, gnu_actual);
3912             }
3913
3914           /* Take the address of the object and convert to the proper pointer
3915              type.  We'd like to actually compute the address of the beginning
3916              of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
3917              possibility that the ARRAY_REF might return a constant and we'd be
3918              getting the wrong address.  Neither approach is exactly correct,
3919              but this is the most likely to work in all cases.  */
3920           gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
3921         }
3922       else if (is_true_formal_parm && DECL_BY_DESCRIPTOR_P (gnu_formal))
3923         {
3924           gnu_actual = convert (gnu_formal_type, gnu_actual);
3925
3926           /* If this is 'Null_Parameter, pass a zero descriptor.  */
3927           if ((TREE_CODE (gnu_actual) == INDIRECT_REF
3928                || TREE_CODE (gnu_actual) == UNCONSTRAINED_ARRAY_REF)
3929               && TREE_PRIVATE (gnu_actual))
3930             gnu_actual
3931               = convert (DECL_ARG_TYPE (gnu_formal), integer_zero_node);
3932           else
3933             gnu_actual = build_unary_op (ADDR_EXPR, NULL_TREE,
3934                                          fill_vms_descriptor
3935                                          (TREE_TYPE (TREE_TYPE (gnu_formal)),
3936                                           gnu_actual, gnat_actual));
3937         }
3938       else
3939         {
3940           tree gnu_size;
3941
3942           if (Ekind (gnat_formal) != E_In_Parameter)
3943             gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
3944
3945           if (!is_true_formal_parm)
3946             {
3947               /* Make sure side-effects are evaluated before the call.  */
3948               if (TREE_SIDE_EFFECTS (gnu_name))
3949                 append_to_statement_list (gnu_name, &gnu_stmt_list);
3950               continue;
3951             }
3952
3953           gnu_actual = convert (gnu_formal_type, gnu_actual);
3954
3955           /* If this is 'Null_Parameter, pass a zero even though we are
3956              dereferencing it.  */
3957           if (TREE_CODE (gnu_actual) == INDIRECT_REF
3958               && TREE_PRIVATE (gnu_actual)
3959               && (gnu_size = TYPE_SIZE (TREE_TYPE (gnu_actual)))
3960               && TREE_CODE (gnu_size) == INTEGER_CST
3961               && compare_tree_int (gnu_size, BITS_PER_WORD) <= 0)
3962             gnu_actual
3963               = unchecked_convert (DECL_ARG_TYPE (gnu_formal),
3964                                    convert (gnat_type_for_size
3965                                             (TREE_INT_CST_LOW (gnu_size), 1),
3966                                             integer_zero_node),
3967                                    false);
3968           else
3969             gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
3970         }
3971
3972       VEC_safe_push (tree, gc, gnu_actual_vec, gnu_actual);
3973     }
3974
3975   gnu_call
3976     = build_call_vec (gnu_result_type, gnu_subprog_addr, gnu_actual_vec);
3977   set_expr_location_from_node (gnu_call, gnat_node);
3978
3979   /* If we have created a temporary for the return value, initialize it.  */
3980   if (gnu_retval)
3981     {
3982       tree gnu_stmt
3983         = build_binary_op (INIT_EXPR, NULL_TREE, gnu_retval, gnu_call);
3984       set_expr_location_from_node (gnu_stmt, gnat_node);
3985       append_to_statement_list (gnu_stmt, &gnu_stmt_list);
3986       gnu_call = gnu_retval;
3987     }
3988
3989   /* If this is a subprogram with copy-in/copy-out parameters, we need to
3990      unpack the valued returned from the function into the In Out or Out
3991      parameters.  We deal with the function return (if this is an Ada
3992      function) below.  */
3993   if (TYPE_CI_CO_LIST (gnu_subprog_type))
3994     {
3995       /* List of FIELD_DECLs associated with the PARM_DECLs of the copy-in/
3996          copy-out parameters.  */
3997       tree gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
3998       const int length = list_length (gnu_cico_list);
3999
4000       /* The call sequence must contain one and only one call, even though the
4001          function is pure.  Save the result into a temporary if needed.  */
4002       if (length > 1)
4003         {
4004           if (!gnu_retval)
4005             {
4006               tree gnu_stmt;
4007               /* If we haven't pushed a binding level, push a new one.  This
4008                  will narrow the lifetime of the temporary we are about to
4009                  make as much as possible.  */
4010               if (!pushed_binding_level)
4011                 {
4012                   start_stmt_group ();
4013                   gnat_pushlevel ();
4014                   pushed_binding_level = true;
4015                 }
4016               gnu_call
4017                 = create_init_temporary ("P", gnu_call, &gnu_stmt, gnat_node);
4018               append_to_statement_list (gnu_stmt, &gnu_stmt_list);
4019             }
4020
4021           gnu_name_list = nreverse (gnu_name_list);
4022         }
4023
4024       /* The first entry is for the actual return value if this is a
4025          function, so skip it.  */
4026       if (TREE_VALUE (gnu_cico_list) == void_type_node)
4027         gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4028
4029       if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
4030         gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
4031       else
4032         gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
4033
4034       for (gnat_actual = First_Actual (gnat_node);
4035            Present (gnat_actual);
4036            gnat_formal = Next_Formal_With_Extras (gnat_formal),
4037            gnat_actual = Next_Actual (gnat_actual))
4038         /* If we are dealing with a copy-in/copy-out parameter, we must
4039            retrieve its value from the record returned in the call.  */
4040         if (!(present_gnu_tree (gnat_formal)
4041               && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
4042               && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
4043                   || (TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
4044                       && ((DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))
4045                            || (DECL_BY_DESCRIPTOR_P
4046                                (get_gnu_tree (gnat_formal))))))))
4047             && Ekind (gnat_formal) != E_In_Parameter)
4048           {
4049             /* Get the value to assign to this Out or In Out parameter.  It is
4050                either the result of the function if there is only a single such
4051                parameter or the appropriate field from the record returned.  */
4052             tree gnu_result
4053               = length == 1
4054                 ? gnu_call
4055                 : build_component_ref (gnu_call, NULL_TREE,
4056                                        TREE_PURPOSE (gnu_cico_list), false);
4057
4058             /* If the actual is a conversion, get the inner expression, which
4059                will be the real destination, and convert the result to the
4060                type of the actual parameter.  */
4061             tree gnu_actual
4062               = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
4063
4064             /* If the result is a padded type, remove the padding.  */
4065             if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
4066               gnu_result
4067                 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
4068                            gnu_result);
4069
4070             /* If the actual is a type conversion, the real target object is
4071                denoted by the inner Expression and we need to convert the
4072                result to the associated type.
4073                We also need to convert our gnu assignment target to this type
4074                if the corresponding GNU_NAME was constructed from the GNAT
4075                conversion node and not from the inner Expression.  */
4076             if (Nkind (gnat_actual) == N_Type_Conversion)
4077               {
4078                 gnu_result
4079                   = convert_with_check
4080                     (Etype (Expression (gnat_actual)), gnu_result,
4081                      Do_Overflow_Check (gnat_actual),
4082                      Do_Range_Check (Expression (gnat_actual)),
4083                      Float_Truncate (gnat_actual), gnat_actual);
4084
4085                 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
4086                   gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
4087               }
4088
4089             /* Unchecked conversions as actuals for Out parameters are not
4090                allowed in user code because they are not variables, but do
4091                occur in front-end expansions.  The associated GNU_NAME is
4092                always obtained from the inner expression in such cases.  */
4093             else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4094               gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
4095                                               gnu_result,
4096                                               No_Truncation (gnat_actual));
4097             else
4098               {
4099                 if (Do_Range_Check (gnat_actual))
4100                   gnu_result
4101                     = emit_range_check (gnu_result, Etype (gnat_actual),
4102                                         gnat_actual);
4103
4104                 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
4105                       && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
4106                   gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
4107               }
4108
4109             if (atomic_sync_required_p (gnat_actual))
4110               gnu_result = build_atomic_store (gnu_actual, gnu_result);
4111             else
4112               gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
4113                                             gnu_actual, gnu_result);
4114             set_expr_location_from_node (gnu_result, gnat_node);
4115             append_to_statement_list (gnu_result, &gnu_stmt_list);
4116             gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4117             gnu_name_list = TREE_CHAIN (gnu_name_list);
4118           }
4119     }
4120
4121   /* If this is a function call, the result is the call expression unless a
4122      target is specified, in which case we copy the result into the target
4123      and return the assignment statement.  */
4124   if (function_call)
4125     {
4126       /* If this is a function with copy-in/copy-out parameters, extract the
4127          return value from it and update the return type.  */
4128       if (TYPE_CI_CO_LIST (gnu_subprog_type))
4129         {
4130           tree gnu_elmt = value_member (void_type_node,
4131                                         TYPE_CI_CO_LIST (gnu_subprog_type));
4132           gnu_call = build_component_ref (gnu_call, NULL_TREE,
4133                                           TREE_PURPOSE (gnu_elmt), false);
4134           gnu_result_type = TREE_TYPE (gnu_call);
4135         }
4136
4137       /* If the function returns an unconstrained array or by direct reference,
4138          we have to dereference the pointer.  */
4139       if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type)
4140           || TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type))
4141         gnu_call = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_call);
4142
4143       if (gnu_target)
4144         {
4145           Node_Id gnat_parent = Parent (gnat_node);
4146           enum tree_code op_code;
4147
4148           /* If range check is needed, emit code to generate it.  */
4149           if (Do_Range_Check (gnat_node))
4150             gnu_call
4151               = emit_range_check (gnu_call, Etype (Name (gnat_parent)),
4152                                   gnat_parent);
4153
4154           /* ??? If the return type has variable size, then force the return
4155              slot optimization as we would not be able to create a temporary.
4156              Likewise if it was unconstrained as we would copy too much data.
4157              That's what has been done historically.  */
4158           if (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
4159               || (TYPE_IS_PADDING_P (gnu_result_type)
4160                   && CONTAINS_PLACEHOLDER_P
4161                      (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS (gnu_result_type))))))
4162             op_code = INIT_EXPR;
4163           else
4164             op_code = MODIFY_EXPR;
4165
4166           if (atomic_sync)
4167             gnu_call = build_atomic_store (gnu_target, gnu_call);
4168           else
4169             gnu_call
4170               = build_binary_op (op_code, NULL_TREE, gnu_target, gnu_call);
4171           set_expr_location_from_node (gnu_call, gnat_parent);
4172           append_to_statement_list (gnu_call, &gnu_stmt_list);
4173         }
4174       else
4175         *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
4176     }
4177
4178   /* Otherwise, if this is a procedure call statement without copy-in/copy-out
4179      parameters, the result is just the call statement.  */
4180   else if (!TYPE_CI_CO_LIST (gnu_subprog_type))
4181     append_to_statement_list (gnu_call, &gnu_stmt_list);
4182
4183   /* Finally, add the copy back statements, if any.  */
4184   append_to_statement_list (gnu_after_list, &gnu_stmt_list);
4185
4186   if (went_into_elab_proc)
4187     current_function_decl = NULL_TREE;
4188
4189   /* If we have pushed a binding level, pop it and finish up the enclosing
4190      statement group.  */
4191   if (pushed_binding_level)
4192     {
4193       add_stmt (gnu_stmt_list);
4194       gnat_poplevel ();
4195       gnu_result = end_stmt_group ();
4196     }
4197
4198   /* Otherwise, retrieve the statement list, if any.  */
4199   else if (gnu_stmt_list)
4200     gnu_result = gnu_stmt_list;
4201
4202   /* Otherwise, just return the call expression.  */
4203   else
4204     return gnu_call;
4205
4206   /* If we nevertheless need a value, make a COMPOUND_EXPR to return it.
4207      But first simplify if we have only one statement in the list.  */
4208   if (returning_value)
4209     {
4210       tree first = expr_first (gnu_result), last = expr_last (gnu_result);
4211       if (first == last)
4212         gnu_result = first;
4213       gnu_result
4214         = build_compound_expr (TREE_TYPE (gnu_call), gnu_result, gnu_call);
4215     }
4216
4217   return gnu_result;
4218 }
4219 \f
4220 /* Subroutine of gnat_to_gnu to translate gnat_node, an
4221    N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned.  */
4222
4223 static tree
4224 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
4225 {
4226   tree gnu_jmpsave_decl = NULL_TREE;
4227   tree gnu_jmpbuf_decl = NULL_TREE;
4228   /* If just annotating, ignore all EH and cleanups.  */
4229   bool gcc_zcx = (!type_annotate_only
4230                   && Present (Exception_Handlers (gnat_node))
4231                   && Exception_Mechanism == Back_End_Exceptions);
4232   bool setjmp_longjmp
4233     = (!type_annotate_only && Present (Exception_Handlers (gnat_node))
4234        && Exception_Mechanism == Setjmp_Longjmp);
4235   bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
4236   bool binding_for_block = (at_end || gcc_zcx || setjmp_longjmp);
4237   tree gnu_inner_block; /* The statement(s) for the block itself.  */
4238   tree gnu_result;
4239   tree gnu_expr;
4240   Node_Id gnat_temp;
4241
4242   /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes
4243      and we have our own SJLJ mechanism.  To call the GCC mechanism, we call
4244      add_cleanup, and when we leave the binding, end_stmt_group will create
4245      the TRY_FINALLY_EXPR.
4246
4247      ??? The region level calls down there have been specifically put in place
4248      for a ZCX context and currently the order in which things are emitted
4249      (region/handlers) is different from the SJLJ case. Instead of putting
4250      other calls with different conditions at other places for the SJLJ case,
4251      it seems cleaner to reorder things for the SJLJ case and generalize the
4252      condition to make it not ZCX specific.
4253
4254      If there are any exceptions or cleanup processing involved, we need an
4255      outer statement group (for Setjmp_Longjmp) and binding level.  */
4256   if (binding_for_block)
4257     {
4258       start_stmt_group ();
4259       gnat_pushlevel ();
4260     }
4261
4262   /* If using setjmp_longjmp, make the variables for the setjmp buffer and save
4263      area for address of previous buffer.  Do this first since we need to have
4264      the setjmp buf known for any decls in this block.  */
4265   if (setjmp_longjmp)
4266     {
4267       gnu_jmpsave_decl
4268         = create_var_decl (get_identifier ("JMPBUF_SAVE"), NULL_TREE,
4269                            jmpbuf_ptr_type,
4270                            build_call_n_expr (get_jmpbuf_decl, 0),
4271                            false, false, false, false, NULL, gnat_node);
4272       DECL_ARTIFICIAL (gnu_jmpsave_decl) = 1;
4273
4274       /* The __builtin_setjmp receivers will immediately reinstall it.  Now
4275          because of the unstructured form of EH used by setjmp_longjmp, there
4276          might be forward edges going to __builtin_setjmp receivers on which
4277          it is uninitialized, although they will never be actually taken.  */
4278       TREE_NO_WARNING (gnu_jmpsave_decl) = 1;
4279       gnu_jmpbuf_decl
4280         = create_var_decl (get_identifier ("JMP_BUF"), NULL_TREE,
4281                            jmpbuf_type,
4282                            NULL_TREE,
4283                            false, false, false, false, NULL, gnat_node);
4284       DECL_ARTIFICIAL (gnu_jmpbuf_decl) = 1;
4285
4286       set_block_jmpbuf_decl (gnu_jmpbuf_decl);
4287
4288       /* When we exit this block, restore the saved value.  */
4289       add_cleanup (build_call_n_expr (set_jmpbuf_decl, 1, gnu_jmpsave_decl),
4290                    End_Label (gnat_node));
4291     }
4292
4293   /* If we are to call a function when exiting this block, add a cleanup
4294      to the binding level we made above.  Note that add_cleanup is FIFO
4295      so we must register this cleanup after the EH cleanup just above.  */
4296   if (at_end)
4297     add_cleanup (build_call_n_expr (gnat_to_gnu (At_End_Proc (gnat_node)), 0),
4298                  End_Label (gnat_node));
4299
4300   /* Now build the tree for the declarations and statements inside this block.
4301      If this is SJLJ, set our jmp_buf as the current buffer.  */
4302   start_stmt_group ();
4303
4304   if (setjmp_longjmp)
4305     add_stmt (build_call_n_expr (set_jmpbuf_decl, 1,
4306                                  build_unary_op (ADDR_EXPR, NULL_TREE,
4307                                                  gnu_jmpbuf_decl)));
4308
4309   if (Present (First_Real_Statement (gnat_node)))
4310     process_decls (Statements (gnat_node), Empty,
4311                    First_Real_Statement (gnat_node), true, true);
4312
4313   /* Generate code for each statement in the block.  */
4314   for (gnat_temp = (Present (First_Real_Statement (gnat_node))
4315                     ? First_Real_Statement (gnat_node)
4316                     : First (Statements (gnat_node)));
4317        Present (gnat_temp); gnat_temp = Next (gnat_temp))
4318     add_stmt (gnat_to_gnu (gnat_temp));
4319   gnu_inner_block = end_stmt_group ();
4320
4321   /* Now generate code for the two exception models, if either is relevant for
4322      this block.  */
4323   if (setjmp_longjmp)
4324     {
4325       tree *gnu_else_ptr = 0;
4326       tree gnu_handler;
4327
4328       /* Make a binding level for the exception handling declarations and code
4329          and set up gnu_except_ptr_stack for the handlers to use.  */
4330       start_stmt_group ();
4331       gnat_pushlevel ();
4332
4333       VEC_safe_push (tree, gc, gnu_except_ptr_stack,
4334                      create_var_decl (get_identifier ("EXCEPT_PTR"), NULL_TREE,
4335                                       build_pointer_type (except_type_node),
4336                                       build_call_n_expr (get_excptr_decl, 0),
4337                                       false, false, false, false,
4338                                       NULL, gnat_node));
4339
4340       /* Generate code for each handler. The N_Exception_Handler case does the
4341          real work and returns a COND_EXPR for each handler, which we chain
4342          together here.  */
4343       for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
4344            Present (gnat_temp); gnat_temp = Next_Non_Pragma (gnat_temp))
4345         {
4346           gnu_expr = gnat_to_gnu (gnat_temp);
4347
4348           /* If this is the first one, set it as the outer one. Otherwise,
4349              point the "else" part of the previous handler to us. Then point
4350              to our "else" part.  */
4351           if (!gnu_else_ptr)
4352             add_stmt (gnu_expr);
4353           else
4354             *gnu_else_ptr = gnu_expr;
4355
4356           gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
4357         }
4358
4359       /* If none of the exception handlers did anything, re-raise but do not
4360          defer abortion.  */
4361       gnu_expr = build_call_n_expr (raise_nodefer_decl, 1,
4362                                     VEC_last (tree, gnu_except_ptr_stack));
4363       set_expr_location_from_node
4364         (gnu_expr,
4365          Present (End_Label (gnat_node)) ? End_Label (gnat_node) : gnat_node);
4366
4367       if (gnu_else_ptr)
4368         *gnu_else_ptr = gnu_expr;
4369       else
4370         add_stmt (gnu_expr);
4371
4372       /* End the binding level dedicated to the exception handlers and get the
4373          whole statement group.  */
4374       VEC_pop (tree, gnu_except_ptr_stack);
4375       gnat_poplevel ();
4376       gnu_handler = end_stmt_group ();
4377
4378       /* If the setjmp returns 1, we restore our incoming longjmp value and
4379          then check the handlers.  */
4380       start_stmt_group ();
4381       add_stmt_with_node (build_call_n_expr (set_jmpbuf_decl, 1,
4382                                              gnu_jmpsave_decl),
4383                           gnat_node);
4384       add_stmt (gnu_handler);
4385       gnu_handler = end_stmt_group ();
4386
4387       /* This block is now "if (setjmp) ... <handlers> else <block>".  */
4388       gnu_result = build3 (COND_EXPR, void_type_node,
4389                            (build_call_n_expr
4390                             (setjmp_decl, 1,
4391                              build_unary_op (ADDR_EXPR, NULL_TREE,
4392                                              gnu_jmpbuf_decl))),
4393                            gnu_handler, gnu_inner_block);
4394     }
4395   else if (gcc_zcx)
4396     {
4397       tree gnu_handlers;
4398
4399       /* First make a block containing the handlers.  */
4400       start_stmt_group ();
4401       for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
4402            Present (gnat_temp);
4403            gnat_temp = Next_Non_Pragma (gnat_temp))
4404         add_stmt (gnat_to_gnu (gnat_temp));
4405       gnu_handlers = end_stmt_group ();
4406
4407       /* Now make the TRY_CATCH_EXPR for the block.  */
4408       gnu_result = build2 (TRY_CATCH_EXPR, void_type_node,
4409                            gnu_inner_block, gnu_handlers);
4410     }
4411   else
4412     gnu_result = gnu_inner_block;
4413
4414   /* Now close our outer block, if we had to make one.  */
4415   if (binding_for_block)
4416     {
4417       add_stmt (gnu_result);
4418       gnat_poplevel ();
4419       gnu_result = end_stmt_group ();
4420     }
4421
4422   return gnu_result;
4423 }
4424 \f
4425 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
4426    to a GCC tree, which is returned.  This is the variant for Setjmp_Longjmp
4427    exception handling.  */
4428
4429 static tree
4430 Exception_Handler_to_gnu_sjlj (Node_Id gnat_node)
4431 {
4432   /* Unless this is "Others" or the special "Non-Ada" exception for Ada, make
4433      an "if" statement to select the proper exceptions.  For "Others", exclude
4434      exceptions where Handled_By_Others is nonzero unless the All_Others flag
4435      is set. For "Non-ada", accept an exception if "Lang" is 'V'.  */
4436   tree gnu_choice = boolean_false_node;
4437   tree gnu_body = build_stmt_group (Statements (gnat_node), false);
4438   Node_Id gnat_temp;
4439
4440   for (gnat_temp = First (Exception_Choices (gnat_node));
4441        gnat_temp; gnat_temp = Next (gnat_temp))
4442     {
4443       tree this_choice;
4444
4445       if (Nkind (gnat_temp) == N_Others_Choice)
4446         {
4447           if (All_Others (gnat_temp))
4448             this_choice = boolean_true_node;
4449           else
4450             this_choice
4451               = build_binary_op
4452                 (EQ_EXPR, boolean_type_node,
4453                  convert
4454                  (integer_type_node,
4455                   build_component_ref
4456                   (build_unary_op
4457                    (INDIRECT_REF, NULL_TREE,
4458                     VEC_last (tree, gnu_except_ptr_stack)),
4459                    get_identifier ("not_handled_by_others"), NULL_TREE,
4460                    false)),
4461                  integer_zero_node);
4462         }
4463
4464       else if (Nkind (gnat_temp) == N_Identifier
4465                || Nkind (gnat_temp) == N_Expanded_Name)
4466         {
4467           Entity_Id gnat_ex_id = Entity (gnat_temp);
4468           tree gnu_expr;
4469
4470           /* Exception may be a renaming. Recover original exception which is
4471              the one elaborated and registered.  */
4472           if (Present (Renamed_Object (gnat_ex_id)))
4473             gnat_ex_id = Renamed_Object (gnat_ex_id);
4474
4475           gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
4476
4477           this_choice
4478             = build_binary_op
4479               (EQ_EXPR, boolean_type_node,
4480                VEC_last (tree, gnu_except_ptr_stack),
4481                convert (TREE_TYPE (VEC_last (tree, gnu_except_ptr_stack)),
4482                         build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr)));
4483
4484           /* If this is the distinguished exception "Non_Ada_Error" (and we are
4485              in VMS mode), also allow a non-Ada exception (a VMS condition) t
4486              match.  */
4487           if (Is_Non_Ada_Error (Entity (gnat_temp)))
4488             {
4489               tree gnu_comp
4490                 = build_component_ref
4491                   (build_unary_op (INDIRECT_REF, NULL_TREE,
4492                                    VEC_last (tree, gnu_except_ptr_stack)),
4493                    get_identifier ("lang"), NULL_TREE, false);
4494
4495               this_choice
4496                 = build_binary_op
4497                   (TRUTH_ORIF_EXPR, boolean_type_node,
4498                    build_binary_op (EQ_EXPR, boolean_type_node, gnu_comp,
4499                                     build_int_cst (TREE_TYPE (gnu_comp), 'V')),
4500                    this_choice);
4501             }
4502         }
4503       else
4504         gcc_unreachable ();
4505
4506       gnu_choice = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
4507                                     gnu_choice, this_choice);
4508     }
4509
4510   return build3 (COND_EXPR, void_type_node, gnu_choice, gnu_body, NULL_TREE);
4511 }
4512 \f
4513 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
4514    to a GCC tree, which is returned.  This is the variant for ZCX.  */
4515
4516 static tree
4517 Exception_Handler_to_gnu_zcx (Node_Id gnat_node)
4518 {
4519   tree gnu_etypes_list = NULL_TREE;
4520   tree gnu_expr;
4521   tree gnu_etype;
4522   tree gnu_current_exc_ptr;
4523   tree prev_gnu_incoming_exc_ptr;
4524   Node_Id gnat_temp;
4525
4526   /* We build a TREE_LIST of nodes representing what exception types this
4527      handler can catch, with special cases for others and all others cases.
4528
4529      Each exception type is actually identified by a pointer to the exception
4530      id, or to a dummy object for "others" and "all others".  */
4531   for (gnat_temp = First (Exception_Choices (gnat_node));
4532        gnat_temp; gnat_temp = Next (gnat_temp))
4533     {
4534       if (Nkind (gnat_temp) == N_Others_Choice)
4535         {
4536           tree gnu_expr
4537             = All_Others (gnat_temp) ? all_others_decl : others_decl;
4538
4539           gnu_etype
4540             = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
4541         }
4542       else if (Nkind (gnat_temp) == N_Identifier
4543                || Nkind (gnat_temp) == N_Expanded_Name)
4544         {
4545           Entity_Id gnat_ex_id = Entity (gnat_temp);
4546
4547           /* Exception may be a renaming. Recover original exception which is
4548              the one elaborated and registered.  */
4549           if (Present (Renamed_Object (gnat_ex_id)))
4550             gnat_ex_id = Renamed_Object (gnat_ex_id);
4551
4552           gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
4553           gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
4554
4555           /* The Non_Ada_Error case for VMS exceptions is handled
4556              by the personality routine.  */
4557         }
4558       else
4559         gcc_unreachable ();
4560
4561       /* The GCC interface expects NULL to be passed for catch all handlers, so
4562          it would be quite tempting to set gnu_etypes_list to NULL if gnu_etype
4563          is integer_zero_node.  It would not work, however, because GCC's
4564          notion of "catch all" is stronger than our notion of "others".  Until
4565          we correctly use the cleanup interface as well, doing that would
4566          prevent the "all others" handlers from being seen, because nothing
4567          can be caught beyond a catch all from GCC's point of view.  */
4568       gnu_etypes_list = tree_cons (NULL_TREE, gnu_etype, gnu_etypes_list);
4569     }
4570
4571   start_stmt_group ();
4572   gnat_pushlevel ();
4573
4574   /* Expand a call to the begin_handler hook at the beginning of the handler,
4575      and arrange for a call to the end_handler hook to occur on every possible
4576      exit path.
4577
4578      The hooks expect a pointer to the low level occurrence. This is required
4579      for our stack management scheme because a raise inside the handler pushes
4580      a new occurrence on top of the stack, which means that this top does not
4581      necessarily match the occurrence this handler was dealing with.
4582
4583      __builtin_eh_pointer references the exception occurrence being
4584      propagated. Upon handler entry, this is the exception for which the
4585      handler is triggered. This might not be the case upon handler exit,
4586      however, as we might have a new occurrence propagated by the handler's
4587      body, and the end_handler hook called as a cleanup in this context.
4588
4589      We use a local variable to retrieve the incoming value at handler entry
4590      time, and reuse it to feed the end_handler hook's argument at exit.  */
4591
4592   gnu_current_exc_ptr
4593     = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
4594                        1, integer_zero_node);
4595   prev_gnu_incoming_exc_ptr = gnu_incoming_exc_ptr;
4596   gnu_incoming_exc_ptr = create_var_decl (get_identifier ("EXPTR"), NULL_TREE,
4597                                           ptr_type_node, gnu_current_exc_ptr,
4598                                           false, false, false, false,
4599                                           NULL, gnat_node);
4600
4601   add_stmt_with_node (build_call_n_expr (begin_handler_decl, 1,
4602                                          gnu_incoming_exc_ptr),
4603                       gnat_node);
4604   /* ??? We don't seem to have an End_Label at hand to set the location.  */
4605   add_cleanup (build_call_n_expr (end_handler_decl, 1, gnu_incoming_exc_ptr),
4606                Empty);
4607   add_stmt_list (Statements (gnat_node));
4608   gnat_poplevel ();
4609
4610   gnu_incoming_exc_ptr = prev_gnu_incoming_exc_ptr;
4611
4612   return build2 (CATCH_EXPR, void_type_node, gnu_etypes_list,
4613                  end_stmt_group ());
4614 }
4615 \f
4616 /* Subroutine of gnat_to_gnu to generate code for an N_Compilation unit.  */
4617
4618 static void
4619 Compilation_Unit_to_gnu (Node_Id gnat_node)
4620 {
4621   const Node_Id gnat_unit = Unit (gnat_node);
4622   const bool body_p = (Nkind (gnat_unit) == N_Package_Body
4623                        || Nkind (gnat_unit) == N_Subprogram_Body);
4624   const Entity_Id gnat_unit_entity = Defining_Entity (gnat_unit);
4625   /* Make the decl for the elaboration procedure.  */
4626   tree gnu_elab_proc_decl
4627     = create_subprog_decl
4628       (create_concat_name (gnat_unit_entity, body_p ? "elabb" : "elabs"),
4629        NULL_TREE, void_ftype, NULL_TREE, false, true, false, true, NULL,
4630        gnat_unit);
4631   struct elab_info *info;
4632
4633   VEC_safe_push (tree, gc, gnu_elab_proc_stack, gnu_elab_proc_decl);
4634   DECL_ELABORATION_PROC_P (gnu_elab_proc_decl) = 1;
4635
4636   /* Initialize the information structure for the function.  */
4637   allocate_struct_function (gnu_elab_proc_decl, false);
4638   set_cfun (NULL);
4639
4640   current_function_decl = NULL_TREE;
4641
4642   start_stmt_group ();
4643   gnat_pushlevel ();
4644
4645   /* For a body, first process the spec if there is one.  */
4646   if (Nkind (gnat_unit) == N_Package_Body
4647       || (Nkind (gnat_unit) == N_Subprogram_Body && !Acts_As_Spec (gnat_node)))
4648     add_stmt (gnat_to_gnu (Library_Unit (gnat_node)));
4649
4650   if (type_annotate_only && gnat_node == Cunit (Main_Unit))
4651     {
4652       elaborate_all_entities (gnat_node);
4653
4654       if (Nkind (gnat_unit) == N_Subprogram_Declaration
4655           || Nkind (gnat_unit) == N_Generic_Package_Declaration
4656           || Nkind (gnat_unit) == N_Generic_Subprogram_Declaration)
4657         return;
4658     }
4659
4660   process_decls (Declarations (Aux_Decls_Node (gnat_node)), Empty, Empty,
4661                  true, true);
4662   add_stmt (gnat_to_gnu (gnat_unit));
4663
4664   /* If we can inline, generate code for all the inlined subprograms.  */
4665   if (optimize)
4666     {
4667       Entity_Id gnat_entity;
4668
4669       for (gnat_entity = First_Inlined_Subprogram (gnat_node);
4670            Present (gnat_entity);
4671            gnat_entity = Next_Inlined_Subprogram (gnat_entity))
4672         {
4673           Node_Id gnat_body = Parent (Declaration_Node (gnat_entity));
4674
4675           if (Nkind (gnat_body) != N_Subprogram_Body)
4676             {
4677               /* ??? This really should always be present.  */
4678               if (No (Corresponding_Body (gnat_body)))
4679                 continue;
4680               gnat_body
4681                 = Parent (Declaration_Node (Corresponding_Body (gnat_body)));
4682             }
4683
4684           if (Present (gnat_body))
4685             {
4686               /* Define the entity first so we set DECL_EXTERNAL.  */
4687               gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
4688               add_stmt (gnat_to_gnu (gnat_body));
4689             }
4690         }
4691     }
4692
4693   /* Process any pragmas and actions following the unit.  */
4694   add_stmt_list (Pragmas_After (Aux_Decls_Node (gnat_node)));
4695   add_stmt_list (Actions (Aux_Decls_Node (gnat_node)));
4696   finalize_from_with_types ();
4697
4698   /* Save away what we've made so far and record this potential elaboration
4699      procedure.  */
4700   info = ggc_alloc_elab_info ();
4701   set_current_block_context (gnu_elab_proc_decl);
4702   gnat_poplevel ();
4703   DECL_SAVED_TREE (gnu_elab_proc_decl) = end_stmt_group ();
4704
4705   set_end_locus_from_node (gnu_elab_proc_decl, gnat_unit);
4706
4707   info->next = elab_info_list;
4708   info->elab_proc = gnu_elab_proc_decl;
4709   info->gnat_node = gnat_node;
4710   elab_info_list = info;
4711
4712   /* Generate elaboration code for this unit, if necessary, and say whether
4713      we did or not.  */
4714   VEC_pop (tree, gnu_elab_proc_stack);
4715
4716   /* Invalidate the global renaming pointers.  This is necessary because
4717      stabilization of the renamed entities may create SAVE_EXPRs which
4718      have been tied to a specific elaboration routine just above.  */
4719   invalidate_global_renaming_pointers ();
4720 }
4721 \f
4722 /* Return true if GNAT_NODE is on the LHS of an assignment or an actual
4723    parameter of a call.  */
4724
4725 static bool
4726 lhs_or_actual_p (Node_Id gnat_node)
4727 {
4728   Node_Id gnat_parent = Parent (gnat_node);
4729   Node_Kind kind = Nkind (gnat_parent);
4730
4731   if (kind == N_Assignment_Statement && Name (gnat_parent) == gnat_node)
4732     return true;
4733
4734   if ((kind == N_Procedure_Call_Statement || kind == N_Function_Call)
4735       && Name (gnat_parent) != gnat_node)
4736     return true;
4737
4738   if (kind == N_Parameter_Association)
4739     return true;
4740
4741   return false;
4742 }
4743
4744 /* Return true if either GNAT_NODE or a view of GNAT_NODE is on the LHS
4745    of an assignment or an actual parameter of a call.  */
4746
4747 static bool
4748 present_in_lhs_or_actual_p (Node_Id gnat_node)
4749 {
4750   Node_Kind kind;
4751
4752   if (lhs_or_actual_p (gnat_node))
4753     return true;
4754
4755   kind = Nkind (Parent (gnat_node));
4756
4757   if ((kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
4758       && lhs_or_actual_p (Parent (gnat_node)))
4759     return true;
4760
4761   return false;
4762 }
4763
4764 /* Return true if GNAT_NODE, an unchecked type conversion, is a no-op as far
4765    as gigi is concerned.  This is used to avoid conversions on the LHS.  */
4766
4767 static bool
4768 unchecked_conversion_nop (Node_Id gnat_node)
4769 {
4770   Entity_Id from_type, to_type;
4771
4772   /* The conversion must be on the LHS of an assignment or an actual parameter
4773      of a call.  Otherwise, even if the conversion was essentially a no-op, it
4774      could de facto ensure type consistency and this should be preserved.  */
4775   if (!lhs_or_actual_p (gnat_node))
4776     return false;
4777
4778   from_type = Etype (Expression (gnat_node));
4779
4780   /* We're interested in artificial conversions generated by the front-end
4781      to make private types explicit, e.g. in Expand_Assign_Array.  */
4782   if (!Is_Private_Type (from_type))
4783     return false;
4784
4785   from_type = Underlying_Type (from_type);
4786   to_type = Etype (gnat_node);
4787
4788   /* The direct conversion to the underlying type is a no-op.  */
4789   if (to_type == from_type)
4790     return true;
4791
4792   /* For an array subtype, the conversion to the PAT is a no-op.  */
4793   if (Ekind (from_type) == E_Array_Subtype
4794       && to_type == Packed_Array_Type (from_type))
4795     return true;
4796
4797   /* For a record subtype, the conversion to the type is a no-op.  */
4798   if (Ekind (from_type) == E_Record_Subtype
4799       && to_type == Etype (from_type))
4800     return true;
4801
4802   return false;
4803 }
4804
4805 /* This function is the driver of the GNAT to GCC tree transformation process.
4806    It is the entry point of the tree transformer.  GNAT_NODE is the root of
4807    some GNAT tree.  Return the root of the corresponding GCC tree.  If this
4808    is an expression, return the GCC equivalent of the expression.  If this
4809    is a statement, return the statement or add it to the current statement
4810    group, in which case anything returned is to be interpreted as occurring
4811    after anything added.  */
4812
4813 tree
4814 gnat_to_gnu (Node_Id gnat_node)
4815 {
4816   const Node_Kind kind = Nkind (gnat_node);
4817   bool went_into_elab_proc = false;
4818   tree gnu_result = error_mark_node; /* Default to no value.  */
4819   tree gnu_result_type = void_type_node;
4820   tree gnu_expr, gnu_lhs, gnu_rhs;
4821   Node_Id gnat_temp;
4822
4823   /* Save node number for error message and set location information.  */
4824   error_gnat_node = gnat_node;
4825   Sloc_to_locus (Sloc (gnat_node), &input_location);
4826
4827   /* If this node is a statement and we are only annotating types, return an
4828      empty statement list.  */
4829   if (type_annotate_only && IN (kind, N_Statement_Other_Than_Procedure_Call))
4830     return alloc_stmt_list ();
4831
4832   /* If this node is a non-static subexpression and we are only annotating
4833      types, make this into a NULL_EXPR.  */
4834   if (type_annotate_only
4835       && IN (kind, N_Subexpr)
4836       && kind != N_Identifier
4837       && !Compile_Time_Known_Value (gnat_node))
4838     return build1 (NULL_EXPR, get_unpadded_type (Etype (gnat_node)),
4839                    build_call_raise (CE_Range_Check_Failed, gnat_node,
4840                                      N_Raise_Constraint_Error));
4841
4842   if ((IN (kind, N_Statement_Other_Than_Procedure_Call)
4843        && kind != N_Null_Statement)
4844       || kind == N_Procedure_Call_Statement
4845       || kind == N_Label
4846       || kind == N_Implicit_Label_Declaration
4847       || kind == N_Handled_Sequence_Of_Statements
4848       || (IN (kind, N_Raise_xxx_Error) && Ekind (Etype (gnat_node)) == E_Void))
4849     {
4850       tree current_elab_proc = get_elaboration_procedure ();
4851
4852       /* If this is a statement and we are at top level, it must be part of
4853          the elaboration procedure, so mark us as being in that procedure.  */
4854       if (!current_function_decl)
4855         {
4856           current_function_decl = current_elab_proc;
4857           went_into_elab_proc = true;
4858         }
4859
4860       /* If we are in the elaboration procedure, check if we are violating a
4861          No_Elaboration_Code restriction by having a statement there.  Don't
4862          check for a possible No_Elaboration_Code restriction violation on
4863          N_Handled_Sequence_Of_Statements, as we want to signal an error on
4864          every nested real statement instead.  This also avoids triggering
4865          spurious errors on dummy (empty) sequences created by the front-end
4866          for package bodies in some cases.  */
4867       if (current_function_decl == current_elab_proc
4868           && kind != N_Handled_Sequence_Of_Statements)
4869         Check_Elaboration_Code_Allowed (gnat_node);
4870     }
4871
4872   switch (kind)
4873     {
4874       /********************************/
4875       /* Chapter 2: Lexical Elements  */
4876       /********************************/
4877
4878     case N_Identifier:
4879     case N_Expanded_Name:
4880     case N_Operator_Symbol:
4881     case N_Defining_Identifier:
4882       gnu_result = Identifier_to_gnu (gnat_node, &gnu_result_type);
4883
4884       /* If this is an atomic access on the RHS for which synchronization is
4885          required, build the atomic load.  */
4886       if (atomic_sync_required_p (gnat_node)
4887           && !present_in_lhs_or_actual_p (gnat_node))
4888         gnu_result = build_atomic_load (gnu_result);
4889       break;
4890
4891     case N_Integer_Literal:
4892       {
4893         tree gnu_type;
4894
4895         /* Get the type of the result, looking inside any padding and
4896            justified modular types.  Then get the value in that type.  */
4897         gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
4898
4899         if (TREE_CODE (gnu_type) == RECORD_TYPE
4900             && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
4901           gnu_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
4902
4903         gnu_result = UI_To_gnu (Intval (gnat_node), gnu_type);
4904
4905         /* If the result overflows (meaning it doesn't fit in its base type),
4906            abort.  We would like to check that the value is within the range
4907            of the subtype, but that causes problems with subtypes whose usage
4908            will raise Constraint_Error and with biased representation, so
4909            we don't.  */
4910         gcc_assert (!TREE_OVERFLOW (gnu_result));
4911       }
4912       break;
4913
4914     case N_Character_Literal:
4915       /* If a Entity is present, it means that this was one of the
4916          literals in a user-defined character type.  In that case,
4917          just return the value in the CONST_DECL.  Otherwise, use the
4918          character code.  In that case, the base type should be an
4919          INTEGER_TYPE, but we won't bother checking for that.  */
4920       gnu_result_type = get_unpadded_type (Etype (gnat_node));
4921       if (Present (Entity (gnat_node)))
4922         gnu_result = DECL_INITIAL (get_gnu_tree (Entity (gnat_node)));
4923       else
4924         gnu_result
4925           = build_int_cst_type
4926               (gnu_result_type, UI_To_CC (Char_Literal_Value (gnat_node)));
4927       break;
4928
4929     case N_Real_Literal:
4930       /* If this is of a fixed-point type, the value we want is the
4931          value of the corresponding integer.  */
4932       if (IN (Ekind (Underlying_Type (Etype (gnat_node))), Fixed_Point_Kind))
4933         {
4934           gnu_result_type = get_unpadded_type (Etype (gnat_node));
4935           gnu_result = UI_To_gnu (Corresponding_Integer_Value (gnat_node),
4936                                   gnu_result_type);
4937           gcc_assert (!TREE_OVERFLOW (gnu_result));
4938         }
4939
4940       /* We should never see a Vax_Float type literal, since the front end
4941          is supposed to transform these using appropriate conversions.  */
4942       else if (Vax_Float (Underlying_Type (Etype (gnat_node))))
4943         gcc_unreachable ();
4944
4945       else
4946         {
4947           Ureal ur_realval = Realval (gnat_node);
4948
4949           gnu_result_type = get_unpadded_type (Etype (gnat_node));
4950
4951           /* If the real value is zero, so is the result.  Otherwise,
4952              convert it to a machine number if it isn't already.  That
4953              forces BASE to 0 or 2 and simplifies the rest of our logic.  */
4954           if (UR_Is_Zero (ur_realval))
4955             gnu_result = convert (gnu_result_type, integer_zero_node);
4956           else
4957             {
4958               if (!Is_Machine_Number (gnat_node))
4959                 ur_realval
4960                   = Machine (Base_Type (Underlying_Type (Etype (gnat_node))),
4961                              ur_realval, Round_Even, gnat_node);
4962
4963               gnu_result
4964                 = UI_To_gnu (Numerator (ur_realval), gnu_result_type);
4965
4966               /* If we have a base of zero, divide by the denominator.
4967                  Otherwise, the base must be 2 and we scale the value, which
4968                  we know can fit in the mantissa of the type (hence the use
4969                  of that type above).  */
4970               if (No (Rbase (ur_realval)))
4971                 gnu_result
4972                   = build_binary_op (RDIV_EXPR,
4973                                      get_base_type (gnu_result_type),
4974                                      gnu_result,
4975                                      UI_To_gnu (Denominator (ur_realval),
4976                                                 gnu_result_type));
4977               else
4978                 {
4979                   REAL_VALUE_TYPE tmp;
4980
4981                   gcc_assert (Rbase (ur_realval) == 2);
4982                   real_ldexp (&tmp, &TREE_REAL_CST (gnu_result),
4983                               - UI_To_Int (Denominator (ur_realval)));
4984                   gnu_result = build_real (gnu_result_type, tmp);
4985                 }
4986             }
4987
4988           /* Now see if we need to negate the result.  Do it this way to
4989              properly handle -0.  */
4990           if (UR_Is_Negative (Realval (gnat_node)))
4991             gnu_result
4992               = build_unary_op (NEGATE_EXPR, get_base_type (gnu_result_type),
4993                                 gnu_result);
4994         }
4995
4996       break;
4997
4998     case N_String_Literal:
4999       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5000       if (TYPE_PRECISION (TREE_TYPE (gnu_result_type)) == HOST_BITS_PER_CHAR)
5001         {
5002           String_Id gnat_string = Strval (gnat_node);
5003           int length = String_Length (gnat_string);
5004           int i;
5005           char *string;
5006           if (length >= ALLOCA_THRESHOLD)
5007             string = XNEWVEC (char, length + 1);
5008           else
5009             string = (char *) alloca (length + 1);
5010
5011           /* Build the string with the characters in the literal.  Note
5012              that Ada strings are 1-origin.  */
5013           for (i = 0; i < length; i++)
5014             string[i] = Get_String_Char (gnat_string, i + 1);
5015
5016           /* Put a null at the end of the string in case it's in a context
5017              where GCC will want to treat it as a C string.  */
5018           string[i] = 0;
5019
5020           gnu_result = build_string (length, string);
5021
5022           /* Strings in GCC don't normally have types, but we want
5023              this to not be converted to the array type.  */
5024           TREE_TYPE (gnu_result) = gnu_result_type;
5025
5026           if (length >= ALLOCA_THRESHOLD)
5027             free (string);
5028         }
5029       else
5030         {
5031           /* Build a list consisting of each character, then make
5032              the aggregate.  */
5033           String_Id gnat_string = Strval (gnat_node);
5034           int length = String_Length (gnat_string);
5035           int i;
5036           tree gnu_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
5037           VEC(constructor_elt,gc) *gnu_vec
5038             = VEC_alloc (constructor_elt, gc, length);
5039
5040           for (i = 0; i < length; i++)
5041             {
5042               tree t = build_int_cst (TREE_TYPE (gnu_result_type),
5043                                       Get_String_Char (gnat_string, i + 1));
5044
5045               CONSTRUCTOR_APPEND_ELT (gnu_vec, gnu_idx, t);
5046               gnu_idx = int_const_binop (PLUS_EXPR, gnu_idx, integer_one_node);
5047             }
5048
5049           gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
5050         }
5051       break;
5052
5053     case N_Pragma:
5054       gnu_result = Pragma_to_gnu (gnat_node);
5055       break;
5056
5057     /**************************************/
5058     /* Chapter 3: Declarations and Types  */
5059     /**************************************/
5060
5061     case N_Subtype_Declaration:
5062     case N_Full_Type_Declaration:
5063     case N_Incomplete_Type_Declaration:
5064     case N_Private_Type_Declaration:
5065     case N_Private_Extension_Declaration:
5066     case N_Task_Type_Declaration:
5067       process_type (Defining_Entity (gnat_node));
5068       gnu_result = alloc_stmt_list ();
5069       break;
5070
5071     case N_Object_Declaration:
5072     case N_Exception_Declaration:
5073       gnat_temp = Defining_Entity (gnat_node);
5074       gnu_result = alloc_stmt_list ();
5075
5076       /* If we are just annotating types and this object has an unconstrained
5077          or task type, don't elaborate it.   */
5078       if (type_annotate_only
5079           && (((Is_Array_Type (Etype (gnat_temp))
5080                 || Is_Record_Type (Etype (gnat_temp)))
5081                && !Is_Constrained (Etype (gnat_temp)))
5082             || Is_Concurrent_Type (Etype (gnat_temp))))
5083         break;
5084
5085       if (Present (Expression (gnat_node))
5086           && !(kind == N_Object_Declaration && No_Initialization (gnat_node))
5087           && (!type_annotate_only
5088               || Compile_Time_Known_Value (Expression (gnat_node))))
5089         {
5090           gnu_expr = gnat_to_gnu (Expression (gnat_node));
5091           if (Do_Range_Check (Expression (gnat_node)))
5092             gnu_expr
5093               = emit_range_check (gnu_expr, Etype (gnat_temp), gnat_node);
5094
5095           /* If this object has its elaboration delayed, we must force
5096              evaluation of GNU_EXPR right now and save it for when the object
5097              is frozen.  */
5098           if (Present (Freeze_Node (gnat_temp)))
5099             {
5100               if (TREE_CONSTANT (gnu_expr))
5101                 ;
5102               else if (global_bindings_p ())
5103                 gnu_expr
5104                   = create_var_decl (create_concat_name (gnat_temp, "init"),
5105                                      NULL_TREE, TREE_TYPE (gnu_expr), gnu_expr,
5106                                      false, false, false, false,
5107                                      NULL, gnat_temp);
5108               else
5109                 gnu_expr = gnat_save_expr (gnu_expr);
5110
5111               save_gnu_tree (gnat_node, gnu_expr, true);
5112             }
5113         }
5114       else
5115         gnu_expr = NULL_TREE;
5116
5117       if (type_annotate_only && gnu_expr && TREE_CODE (gnu_expr) == ERROR_MARK)
5118         gnu_expr = NULL_TREE;
5119
5120       /* If this is a deferred constant with an address clause, we ignore the
5121          full view since the clause is on the partial view and we cannot have
5122          2 different GCC trees for the object.  The only bits of the full view
5123          we will use is the initializer, but it will be directly fetched.  */
5124       if (Ekind(gnat_temp) == E_Constant
5125           && Present (Address_Clause (gnat_temp))
5126           && Present (Full_View (gnat_temp)))
5127         save_gnu_tree (Full_View (gnat_temp), error_mark_node, true);
5128
5129       if (No (Freeze_Node (gnat_temp)))
5130         gnat_to_gnu_entity (gnat_temp, gnu_expr, 1);
5131       break;
5132
5133     case N_Object_Renaming_Declaration:
5134       gnat_temp = Defining_Entity (gnat_node);
5135
5136       /* Don't do anything if this renaming is handled by the front end or if
5137          we are just annotating types and this object has a composite or task
5138          type, don't elaborate it.  We return the result in case it has any
5139          SAVE_EXPRs in it that need to be evaluated here.  */
5140       if (!Is_Renaming_Of_Object (gnat_temp)
5141           && ! (type_annotate_only
5142                 && (Is_Array_Type (Etype (gnat_temp))
5143                     || Is_Record_Type (Etype (gnat_temp))
5144                     || Is_Concurrent_Type (Etype (gnat_temp)))))
5145         gnu_result
5146           = gnat_to_gnu_entity (gnat_temp,
5147                                 gnat_to_gnu (Renamed_Object (gnat_temp)), 1);
5148       else
5149         gnu_result = alloc_stmt_list ();
5150       break;
5151
5152     case N_Implicit_Label_Declaration:
5153       gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
5154       gnu_result = alloc_stmt_list ();
5155       break;
5156
5157     case N_Exception_Renaming_Declaration:
5158     case N_Number_Declaration:
5159     case N_Package_Renaming_Declaration:
5160     case N_Subprogram_Renaming_Declaration:
5161       /* These are fully handled in the front end.  */
5162       gnu_result = alloc_stmt_list ();
5163       break;
5164
5165     /*************************************/
5166     /* Chapter 4: Names and Expressions  */
5167     /*************************************/
5168
5169     case N_Explicit_Dereference:
5170       gnu_result = gnat_to_gnu (Prefix (gnat_node));
5171       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5172       gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
5173
5174       /* If this is an atomic access on the RHS for which synchronization is
5175          required, build the atomic load.  */
5176       if (atomic_sync_required_p (gnat_node)
5177           && !present_in_lhs_or_actual_p (gnat_node))
5178         gnu_result = build_atomic_load (gnu_result);
5179       break;
5180
5181     case N_Indexed_Component:
5182       {
5183         tree gnu_array_object = gnat_to_gnu (Prefix (gnat_node));
5184         tree gnu_type;
5185         int ndim;
5186         int i;
5187         Node_Id *gnat_expr_array;
5188
5189         gnu_array_object = maybe_implicit_deref (gnu_array_object);
5190
5191         /* Convert vector inputs to their representative array type, to fit
5192            what the code below expects.  */
5193         gnu_array_object = maybe_vector_array (gnu_array_object);
5194
5195         gnu_array_object = maybe_unconstrained_array (gnu_array_object);
5196
5197         /* If we got a padded type, remove it too.  */
5198         if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_array_object)))
5199           gnu_array_object
5200             = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_array_object))),
5201                        gnu_array_object);
5202
5203         gnu_result = gnu_array_object;
5204
5205         /* First compute the number of dimensions of the array, then
5206            fill the expression array, the order depending on whether
5207            this is a Convention_Fortran array or not.  */
5208         for (ndim = 1, gnu_type = TREE_TYPE (gnu_array_object);
5209              TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
5210              && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type));
5211              ndim++, gnu_type = TREE_TYPE (gnu_type))
5212           ;
5213
5214         gnat_expr_array = XALLOCAVEC (Node_Id, ndim);
5215
5216         if (TYPE_CONVENTION_FORTRAN_P (TREE_TYPE (gnu_array_object)))
5217           for (i = ndim - 1, gnat_temp = First (Expressions (gnat_node));
5218                i >= 0;
5219                i--, gnat_temp = Next (gnat_temp))
5220             gnat_expr_array[i] = gnat_temp;
5221         else
5222           for (i = 0, gnat_temp = First (Expressions (gnat_node));
5223                i < ndim;
5224                i++, gnat_temp = Next (gnat_temp))
5225             gnat_expr_array[i] = gnat_temp;
5226
5227         for (i = 0, gnu_type = TREE_TYPE (gnu_array_object);
5228              i < ndim; i++, gnu_type = TREE_TYPE (gnu_type))
5229           {
5230             gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
5231             gnat_temp = gnat_expr_array[i];
5232             gnu_expr = gnat_to_gnu (gnat_temp);
5233
5234             if (Do_Range_Check (gnat_temp))
5235               gnu_expr
5236                 = emit_index_check
5237                   (gnu_array_object, gnu_expr,
5238                    TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
5239                    TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
5240                    gnat_temp);
5241
5242             gnu_result = build_binary_op (ARRAY_REF, NULL_TREE,
5243                                           gnu_result, gnu_expr);
5244           }
5245
5246         gnu_result_type = get_unpadded_type (Etype (gnat_node));
5247
5248         /* If this is an atomic access on the RHS for which synchronization is
5249            required, build the atomic load.  */
5250         if (atomic_sync_required_p (gnat_node)
5251             && !present_in_lhs_or_actual_p (gnat_node))
5252           gnu_result = build_atomic_load (gnu_result);
5253       }
5254       break;
5255
5256     case N_Slice:
5257       {
5258         Node_Id gnat_range_node = Discrete_Range (gnat_node);
5259         tree gnu_type;
5260
5261         gnu_result = gnat_to_gnu (Prefix (gnat_node));
5262         gnu_result_type = get_unpadded_type (Etype (gnat_node));
5263
5264         /* Do any implicit dereferences of the prefix and do any needed
5265            range check.  */
5266         gnu_result = maybe_implicit_deref (gnu_result);
5267         gnu_result = maybe_unconstrained_array (gnu_result);
5268         gnu_type = TREE_TYPE (gnu_result);
5269         if (Do_Range_Check (gnat_range_node))
5270           {
5271             /* Get the bounds of the slice.  */
5272             tree gnu_index_type
5273               = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_result_type));
5274             tree gnu_min_expr = TYPE_MIN_VALUE (gnu_index_type);
5275             tree gnu_max_expr = TYPE_MAX_VALUE (gnu_index_type);
5276             /* Get the permitted bounds.  */
5277             tree gnu_base_index_type
5278               = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
5279             tree gnu_base_min_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
5280               (TYPE_MIN_VALUE (gnu_base_index_type), gnu_result);
5281             tree gnu_base_max_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
5282               (TYPE_MAX_VALUE (gnu_base_index_type), gnu_result);
5283             tree gnu_expr_l, gnu_expr_h, gnu_expr_type;
5284
5285            gnu_min_expr = gnat_protect_expr (gnu_min_expr);
5286            gnu_max_expr = gnat_protect_expr (gnu_max_expr);
5287
5288             /* Derive a good type to convert everything to.  */
5289             gnu_expr_type = get_base_type (gnu_index_type);
5290
5291             /* Test whether the minimum slice value is too small.  */
5292             gnu_expr_l = build_binary_op (LT_EXPR, boolean_type_node,
5293                                           convert (gnu_expr_type,
5294                                                    gnu_min_expr),
5295                                           convert (gnu_expr_type,
5296                                                    gnu_base_min_expr));
5297
5298             /* Test whether the maximum slice value is too large.  */
5299             gnu_expr_h = build_binary_op (GT_EXPR, boolean_type_node,
5300                                           convert (gnu_expr_type,
5301                                                    gnu_max_expr),
5302                                           convert (gnu_expr_type,
5303                                                    gnu_base_max_expr));
5304
5305             /* Build a slice index check that returns the low bound,
5306                assuming the slice is not empty.  */
5307             gnu_expr = emit_check
5308               (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
5309                                 gnu_expr_l, gnu_expr_h),
5310                gnu_min_expr, CE_Index_Check_Failed, gnat_node);
5311
5312            /* Build a conditional expression that does the index checks and
5313               returns the low bound if the slice is not empty (max >= min),
5314               and returns the naked low bound otherwise (max < min), unless
5315               it is non-constant and the high bound is; this prevents VRP
5316               from inferring bogus ranges on the unlikely path.  */
5317             gnu_expr = fold_build3 (COND_EXPR, gnu_expr_type,
5318                                     build_binary_op (GE_EXPR, gnu_expr_type,
5319                                                      convert (gnu_expr_type,
5320                                                               gnu_max_expr),
5321                                                      convert (gnu_expr_type,
5322                                                               gnu_min_expr)),
5323                                     gnu_expr,
5324                                     TREE_CODE (gnu_min_expr) != INTEGER_CST
5325                                     && TREE_CODE (gnu_max_expr) == INTEGER_CST
5326                                     ? gnu_max_expr : gnu_min_expr);
5327           }
5328         else
5329           /* Simply return the naked low bound.  */
5330           gnu_expr = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
5331
5332         /* If this is a slice with non-constant size of an array with constant
5333            size, set the maximum size for the allocation of temporaries.  */
5334         if (!TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_result_type))
5335             && TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_type)))
5336           TYPE_ARRAY_MAX_SIZE (gnu_result_type) = TYPE_SIZE_UNIT (gnu_type);
5337
5338         gnu_result = build_binary_op (ARRAY_RANGE_REF, gnu_result_type,
5339                                       gnu_result, gnu_expr);
5340       }
5341       break;
5342
5343     case N_Selected_Component:
5344       {
5345         tree gnu_prefix = gnat_to_gnu (Prefix (gnat_node));
5346         Entity_Id gnat_field = Entity (Selector_Name (gnat_node));
5347         Entity_Id gnat_pref_type = Etype (Prefix (gnat_node));
5348         tree gnu_field;
5349
5350         while (IN (Ekind (gnat_pref_type), Incomplete_Or_Private_Kind)
5351                || IN (Ekind (gnat_pref_type), Access_Kind))
5352           {
5353             if (IN (Ekind (gnat_pref_type), Incomplete_Or_Private_Kind))
5354               gnat_pref_type = Underlying_Type (gnat_pref_type);
5355             else if (IN (Ekind (gnat_pref_type), Access_Kind))
5356               gnat_pref_type = Designated_Type (gnat_pref_type);
5357           }
5358
5359         gnu_prefix = maybe_implicit_deref (gnu_prefix);
5360
5361         /* For discriminant references in tagged types always substitute the
5362            corresponding discriminant as the actual selected component.  */
5363         if (Is_Tagged_Type (gnat_pref_type))
5364           while (Present (Corresponding_Discriminant (gnat_field)))
5365             gnat_field = Corresponding_Discriminant (gnat_field);
5366
5367         /* For discriminant references of untagged types always substitute the
5368            corresponding stored discriminant.  */
5369         else if (Present (Corresponding_Discriminant (gnat_field)))
5370           gnat_field = Original_Record_Component (gnat_field);
5371
5372         /* Handle extracting the real or imaginary part of a complex.
5373            The real part is the first field and the imaginary the last.  */
5374         if (TREE_CODE (TREE_TYPE (gnu_prefix)) == COMPLEX_TYPE)
5375           gnu_result = build_unary_op (Present (Next_Entity (gnat_field))
5376                                        ? REALPART_EXPR : IMAGPART_EXPR,
5377                                        NULL_TREE, gnu_prefix);
5378         else
5379           {
5380             gnu_field = gnat_to_gnu_field_decl (gnat_field);
5381
5382             /* If there are discriminants, the prefix might be evaluated more
5383                than once, which is a problem if it has side-effects.  */
5384             if (Has_Discriminants (Is_Access_Type (Etype (Prefix (gnat_node)))
5385                                    ? Designated_Type (Etype
5386                                                       (Prefix (gnat_node)))
5387                                    : Etype (Prefix (gnat_node))))
5388               gnu_prefix = gnat_stabilize_reference (gnu_prefix, false, NULL);
5389
5390             gnu_result
5391               = build_component_ref (gnu_prefix, NULL_TREE, gnu_field,
5392                                      (Nkind (Parent (gnat_node))
5393                                       == N_Attribute_Reference)
5394                                      && lvalue_required_for_attribute_p
5395                                         (Parent (gnat_node)));
5396           }
5397
5398         gnu_result_type = get_unpadded_type (Etype (gnat_node));
5399
5400         /* If this is an atomic access on the RHS for which synchronization is
5401            required, build the atomic load.  */
5402         if (atomic_sync_required_p (gnat_node)
5403             && !present_in_lhs_or_actual_p (gnat_node))
5404           gnu_result = build_atomic_load (gnu_result);
5405       }
5406       break;
5407
5408     case N_Attribute_Reference:
5409       {
5410         /* The attribute designator.  */
5411         const int attr = Get_Attribute_Id (Attribute_Name (gnat_node));
5412
5413         /* The Elab_Spec and Elab_Body attributes are special in that Prefix
5414            is a unit, not an object with a GCC equivalent.  */
5415         if (attr == Attr_Elab_Spec || attr == Attr_Elab_Body)
5416           return
5417             create_subprog_decl (create_concat_name
5418                                  (Entity (Prefix (gnat_node)),
5419                                   attr == Attr_Elab_Body ? "elabb" : "elabs"),
5420                                  NULL_TREE, void_ftype, NULL_TREE, false,
5421                                  true, true, true, NULL, gnat_node);
5422
5423         gnu_result = Attribute_to_gnu (gnat_node, &gnu_result_type, attr);
5424       }
5425       break;
5426
5427     case N_Reference:
5428       /* Like 'Access as far as we are concerned.  */
5429       gnu_result = gnat_to_gnu (Prefix (gnat_node));
5430       gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
5431       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5432       break;
5433
5434     case N_Aggregate:
5435     case N_Extension_Aggregate:
5436       {
5437         tree gnu_aggr_type;
5438
5439         /* ??? It is wrong to evaluate the type now, but there doesn't
5440            seem to be any other practical way of doing it.  */
5441
5442         gcc_assert (!Expansion_Delayed (gnat_node));
5443
5444         gnu_aggr_type = gnu_result_type
5445           = get_unpadded_type (Etype (gnat_node));
5446
5447         if (TREE_CODE (gnu_result_type) == RECORD_TYPE
5448             && TYPE_CONTAINS_TEMPLATE_P (gnu_result_type))
5449           gnu_aggr_type
5450             = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_result_type)));
5451         else if (TREE_CODE (gnu_result_type) == VECTOR_TYPE)
5452           gnu_aggr_type = TYPE_REPRESENTATIVE_ARRAY (gnu_result_type);
5453
5454         if (Null_Record_Present (gnat_node))
5455           gnu_result = gnat_build_constructor (gnu_aggr_type, NULL);
5456
5457         else if (TREE_CODE (gnu_aggr_type) == RECORD_TYPE
5458                  || TREE_CODE (gnu_aggr_type) == UNION_TYPE)
5459           gnu_result
5460             = assoc_to_constructor (Etype (gnat_node),
5461                                     First (Component_Associations (gnat_node)),
5462                                     gnu_aggr_type);
5463         else if (TREE_CODE (gnu_aggr_type) == ARRAY_TYPE)
5464           gnu_result = pos_to_constructor (First (Expressions (gnat_node)),
5465                                            gnu_aggr_type,
5466                                            Component_Type (Etype (gnat_node)));
5467         else if (TREE_CODE (gnu_aggr_type) == COMPLEX_TYPE)
5468           gnu_result
5469             = build_binary_op
5470               (COMPLEX_EXPR, gnu_aggr_type,
5471                gnat_to_gnu (Expression (First
5472                                         (Component_Associations (gnat_node)))),
5473                gnat_to_gnu (Expression
5474                             (Next
5475                              (First (Component_Associations (gnat_node))))));
5476         else
5477           gcc_unreachable ();
5478
5479         gnu_result = convert (gnu_result_type, gnu_result);
5480       }
5481       break;
5482
5483     case N_Null:
5484       if (TARGET_VTABLE_USES_DESCRIPTORS
5485           && Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
5486           && Is_Dispatch_Table_Entity (Etype (gnat_node)))
5487         gnu_result = null_fdesc_node;
5488       else
5489         gnu_result = null_pointer_node;
5490       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5491       break;
5492
5493     case N_Type_Conversion:
5494     case N_Qualified_Expression:
5495       /* Get the operand expression.  */
5496       gnu_result = gnat_to_gnu (Expression (gnat_node));
5497       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5498
5499       gnu_result
5500         = convert_with_check (Etype (gnat_node), gnu_result,
5501                               Do_Overflow_Check (gnat_node),
5502                               Do_Range_Check (Expression (gnat_node)),
5503                               kind == N_Type_Conversion
5504                               && Float_Truncate (gnat_node), gnat_node);
5505       break;
5506
5507     case N_Unchecked_Type_Conversion:
5508       gnu_result = gnat_to_gnu (Expression (gnat_node));
5509
5510       /* Skip further processing if the conversion is deemed a no-op.  */
5511       if (unchecked_conversion_nop (gnat_node))
5512         {
5513           gnu_result_type = TREE_TYPE (gnu_result);
5514           break;
5515         }
5516
5517       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5518
5519       /* If the result is a pointer type, see if we are improperly
5520          converting to a stricter alignment.  */
5521       if (STRICT_ALIGNMENT && POINTER_TYPE_P (gnu_result_type)
5522           && IN (Ekind (Etype (gnat_node)), Access_Kind))
5523         {
5524           unsigned int align = known_alignment (gnu_result);
5525           tree gnu_obj_type = TREE_TYPE (gnu_result_type);
5526           unsigned int oalign = TYPE_ALIGN (gnu_obj_type);
5527
5528           if (align != 0 && align < oalign && !TYPE_ALIGN_OK (gnu_obj_type))
5529             post_error_ne_tree_2
5530               ("?source alignment (^) '< alignment of & (^)",
5531                gnat_node, Designated_Type (Etype (gnat_node)),
5532                size_int (align / BITS_PER_UNIT), oalign / BITS_PER_UNIT);
5533         }
5534
5535       /* If we are converting a descriptor to a function pointer, first
5536          build the pointer.  */
5537       if (TARGET_VTABLE_USES_DESCRIPTORS
5538           && TREE_TYPE (gnu_result) == fdesc_type_node
5539           && POINTER_TYPE_P (gnu_result_type))
5540         gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
5541
5542       gnu_result = unchecked_convert (gnu_result_type, gnu_result,
5543                                       No_Truncation (gnat_node));
5544       break;
5545
5546     case N_In:
5547     case N_Not_In:
5548       {
5549         tree gnu_obj = gnat_to_gnu (Left_Opnd (gnat_node));
5550         Node_Id gnat_range = Right_Opnd (gnat_node);
5551         tree gnu_low, gnu_high;
5552
5553         /* GNAT_RANGE is either an N_Range node or an identifier denoting a
5554            subtype.  */
5555         if (Nkind (gnat_range) == N_Range)
5556           {
5557             gnu_low = gnat_to_gnu (Low_Bound (gnat_range));
5558             gnu_high = gnat_to_gnu (High_Bound (gnat_range));
5559           }
5560         else if (Nkind (gnat_range) == N_Identifier
5561                  || Nkind (gnat_range) == N_Expanded_Name)
5562           {
5563             tree gnu_range_type = get_unpadded_type (Entity (gnat_range));
5564
5565             gnu_low = TYPE_MIN_VALUE (gnu_range_type);
5566             gnu_high = TYPE_MAX_VALUE (gnu_range_type);
5567           }
5568         else
5569           gcc_unreachable ();
5570
5571         gnu_result_type = get_unpadded_type (Etype (gnat_node));
5572
5573         /* If LOW and HIGH are identical, perform an equality test.  Otherwise,
5574            ensure that GNU_OBJ is evaluated only once and perform a full range
5575            test.  */
5576         if (operand_equal_p (gnu_low, gnu_high, 0))
5577           gnu_result
5578             = build_binary_op (EQ_EXPR, gnu_result_type, gnu_obj, gnu_low);
5579         else
5580           {
5581             tree t1, t2;
5582             gnu_obj = gnat_protect_expr (gnu_obj);
5583             t1 = build_binary_op (GE_EXPR, gnu_result_type, gnu_obj, gnu_low);
5584             if (EXPR_P (t1))
5585               set_expr_location_from_node (t1, gnat_node);
5586             t2 = build_binary_op (LE_EXPR, gnu_result_type, gnu_obj, gnu_high);
5587             if (EXPR_P (t2))
5588               set_expr_location_from_node (t2, gnat_node);
5589             gnu_result
5590               = build_binary_op (TRUTH_ANDIF_EXPR, gnu_result_type, t1, t2);
5591           }
5592
5593         if (kind == N_Not_In)
5594           gnu_result
5595             = invert_truthvalue_loc (EXPR_LOCATION (gnu_result), gnu_result);
5596       }
5597       break;
5598
5599     case N_Op_Divide:
5600       gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
5601       gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
5602       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5603       gnu_result = build_binary_op (FLOAT_TYPE_P (gnu_result_type)
5604                                     ? RDIV_EXPR
5605                                     : (Rounded_Result (gnat_node)
5606                                        ? ROUND_DIV_EXPR : TRUNC_DIV_EXPR),
5607                                     gnu_result_type, gnu_lhs, gnu_rhs);
5608       break;
5609
5610     case N_Op_Or:    case N_Op_And:      case N_Op_Xor:
5611       /* These can either be operations on booleans or on modular types.
5612          Fall through for boolean types since that's the way GNU_CODES is
5613          set up.  */
5614       if (IN (Ekind (Underlying_Type (Etype (gnat_node))),
5615               Modular_Integer_Kind))
5616         {
5617           enum tree_code code
5618             = (kind == N_Op_Or ? BIT_IOR_EXPR
5619                : kind == N_Op_And ? BIT_AND_EXPR
5620                : BIT_XOR_EXPR);
5621
5622           gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
5623           gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
5624           gnu_result_type = get_unpadded_type (Etype (gnat_node));
5625           gnu_result = build_binary_op (code, gnu_result_type,
5626                                         gnu_lhs, gnu_rhs);
5627           break;
5628         }
5629
5630       /* ... fall through ... */
5631
5632     case N_Op_Eq:    case N_Op_Ne:       case N_Op_Lt:
5633     case N_Op_Le:    case N_Op_Gt:       case N_Op_Ge:
5634     case N_Op_Add:   case N_Op_Subtract: case N_Op_Multiply:
5635     case N_Op_Mod:   case N_Op_Rem:
5636     case N_Op_Rotate_Left:
5637     case N_Op_Rotate_Right:
5638     case N_Op_Shift_Left:
5639     case N_Op_Shift_Right:
5640     case N_Op_Shift_Right_Arithmetic:
5641     case N_And_Then: case N_Or_Else:
5642       {
5643         enum tree_code code = gnu_codes[kind];
5644         bool ignore_lhs_overflow = false;
5645         location_t saved_location = input_location;
5646         tree gnu_type;
5647
5648         gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
5649         gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
5650         gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
5651
5652         /* Pending generic support for efficient vector logical operations in
5653            GCC, convert vectors to their representative array type view and
5654            fallthrough.  */
5655         gnu_lhs = maybe_vector_array (gnu_lhs);
5656         gnu_rhs = maybe_vector_array (gnu_rhs);
5657
5658         /* If this is a comparison operator, convert any references to
5659            an unconstrained array value into a reference to the
5660            actual array.  */
5661         if (TREE_CODE_CLASS (code) == tcc_comparison)
5662           {
5663             gnu_lhs = maybe_unconstrained_array (gnu_lhs);
5664             gnu_rhs = maybe_unconstrained_array (gnu_rhs);
5665           }
5666
5667         /* If the result type is a private type, its full view may be a
5668            numeric subtype. The representation we need is that of its base
5669            type, given that it is the result of an arithmetic operation.  */
5670         else if (Is_Private_Type (Etype (gnat_node)))
5671           gnu_type = gnu_result_type
5672             = get_unpadded_type (Base_Type (Full_View (Etype (gnat_node))));
5673
5674         /* If this is a shift whose count is not guaranteed to be correct,
5675            we need to adjust the shift count.  */
5676         if (IN (kind, N_Op_Shift) && !Shift_Count_OK (gnat_node))
5677           {
5678             tree gnu_count_type = get_base_type (TREE_TYPE (gnu_rhs));
5679             tree gnu_max_shift
5680               = convert (gnu_count_type, TYPE_SIZE (gnu_type));
5681
5682             if (kind == N_Op_Rotate_Left || kind == N_Op_Rotate_Right)
5683               gnu_rhs = build_binary_op (TRUNC_MOD_EXPR, gnu_count_type,
5684                                          gnu_rhs, gnu_max_shift);
5685             else if (kind == N_Op_Shift_Right_Arithmetic)
5686               gnu_rhs
5687                 = build_binary_op
5688                   (MIN_EXPR, gnu_count_type,
5689                    build_binary_op (MINUS_EXPR,
5690                                     gnu_count_type,
5691                                     gnu_max_shift,
5692                                     convert (gnu_count_type,
5693                                              integer_one_node)),
5694                    gnu_rhs);
5695           }
5696
5697         /* For right shifts, the type says what kind of shift to do,
5698            so we may need to choose a different type.  In this case,
5699            we have to ignore integer overflow lest it propagates all
5700            the way down and causes a CE to be explicitly raised.  */
5701         if (kind == N_Op_Shift_Right && !TYPE_UNSIGNED (gnu_type))
5702           {
5703             gnu_type = gnat_unsigned_type (gnu_type);
5704             ignore_lhs_overflow = true;
5705           }
5706         else if (kind == N_Op_Shift_Right_Arithmetic
5707                  && TYPE_UNSIGNED (gnu_type))
5708           {
5709             gnu_type = gnat_signed_type (gnu_type);
5710             ignore_lhs_overflow = true;
5711           }
5712
5713         if (gnu_type != gnu_result_type)
5714           {
5715             tree gnu_old_lhs = gnu_lhs;
5716             gnu_lhs = convert (gnu_type, gnu_lhs);
5717             if (TREE_CODE (gnu_lhs) == INTEGER_CST && ignore_lhs_overflow)
5718               TREE_OVERFLOW (gnu_lhs) = TREE_OVERFLOW (gnu_old_lhs);
5719             gnu_rhs = convert (gnu_type, gnu_rhs);
5720           }
5721
5722         /* Instead of expanding overflow checks for addition, subtraction
5723            and multiplication itself, the front end will leave this to
5724            the back end when Backend_Overflow_Checks_On_Target is set.
5725            As the GCC back end itself does not know yet how to properly
5726            do overflow checking, do it here.  The goal is to push
5727            the expansions further into the back end over time.  */
5728         if (Do_Overflow_Check (gnat_node) && Backend_Overflow_Checks_On_Target
5729             && (kind == N_Op_Add
5730                 || kind == N_Op_Subtract
5731                 || kind == N_Op_Multiply)
5732             && !TYPE_UNSIGNED (gnu_type)
5733             && !FLOAT_TYPE_P (gnu_type))
5734           gnu_result = build_binary_op_trapv (code, gnu_type,
5735                                               gnu_lhs, gnu_rhs, gnat_node);
5736         else
5737           {
5738             /* Some operations, e.g. comparisons of arrays, generate complex
5739                trees that need to be annotated while they are being built.  */
5740             input_location = saved_location;
5741             gnu_result = build_binary_op (code, gnu_type, gnu_lhs, gnu_rhs);
5742           }
5743
5744         /* If this is a logical shift with the shift count not verified,
5745            we must return zero if it is too large.  We cannot compensate
5746            above in this case.  */
5747         if ((kind == N_Op_Shift_Left || kind == N_Op_Shift_Right)
5748             && !Shift_Count_OK (gnat_node))
5749           gnu_result
5750             = build_cond_expr
5751               (gnu_type,
5752                build_binary_op (GE_EXPR, boolean_type_node,
5753                                 gnu_rhs,
5754                                 convert (TREE_TYPE (gnu_rhs),
5755                                          TYPE_SIZE (gnu_type))),
5756                convert (gnu_type, integer_zero_node),
5757                gnu_result);
5758       }
5759       break;
5760
5761     case N_Conditional_Expression:
5762       {
5763         tree gnu_cond = gnat_to_gnu (First (Expressions (gnat_node)));
5764         tree gnu_true = gnat_to_gnu (Next (First (Expressions (gnat_node))));
5765         tree gnu_false
5766           = gnat_to_gnu (Next (Next (First (Expressions (gnat_node)))));
5767
5768         gnu_result_type = get_unpadded_type (Etype (gnat_node));
5769         gnu_result
5770           = build_cond_expr (gnu_result_type, gnu_cond, gnu_true, gnu_false);
5771       }
5772       break;
5773
5774     case N_Op_Plus:
5775       gnu_result = gnat_to_gnu (Right_Opnd (gnat_node));
5776       gnu_result_type = get_unpadded_type (Etype (gnat_node));
5777       break;
5778
5779     case N_Op_Not:
5780       /* This case can apply to a boolean or a modular type.
5781          Fall through for a boolean operand since GNU_CODES is set
5782          up to handle this.  */
5783       if (Is_Modular_Integer_Type (Etype (gnat_node))
5784           || (Ekind (Etype (gnat_node)) == E_Private_Type
5785               && Is_Modular_Integer_Type (Full_View (Etype (gnat_node)))))
5786         {
5787           gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
5788           gnu_result_type = get_unpadded_type (Etype (gnat_node));
5789           gnu_result = build_unary_op (BIT_NOT_EXPR, gnu_result_type,
5790                                        gnu_expr);
5791           break;
5792         }
5793
5794       /* ... fall through ... */
5795
5796     case N_Op_Minus:  case N_Op_Abs:
5797       gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
5798
5799       if (Ekind (Etype (gnat_node)) != E_Private_Type)
5800         gnu_result_type = get_unpadded_type (Etype (gnat_node));
5801       else
5802         gnu_result_type = get_unpadded_type (Base_Type
5803                                              (Full_View (Etype (gnat_node))));
5804
5805       if (Do_Overflow_Check (gnat_node)
5806           && !TYPE_UNSIGNED (gnu_result_type)
5807           && !FLOAT_TYPE_P (gnu_result_type))
5808         gnu_result
5809           = build_unary_op_trapv (gnu_codes[kind],
5810                                   gnu_result_type, gnu_expr, gnat_node);
5811       else
5812         gnu_result = build_unary_op (gnu_codes[kind],
5813                                      gnu_result_type, gnu_expr);
5814       break;
5815
5816     case N_Allocator:
5817       {
5818         tree gnu_init = 0;
5819         tree gnu_type;
5820         bool ignore_init_type = false;
5821
5822         gnat_temp = Expression (gnat_node);
5823
5824         /* The Expression operand can either be an N_Identifier or
5825            Expanded_Name, which must represent a type, or a
5826            N_Qualified_Expression, which contains both the object type and an
5827            initial value for the object.  */
5828         if (Nkind (gnat_temp) == N_Identifier
5829             || Nkind (gnat_temp) == N_Expanded_Name)
5830           gnu_type = gnat_to_gnu_type (Entity (gnat_temp));
5831         else if (Nkind (gnat_temp) == N_Qualified_Expression)
5832           {
5833             Entity_Id gnat_desig_type
5834               = Designated_Type (Underlying_Type (Etype (gnat_node)));
5835
5836             ignore_init_type = Has_Constrained_Partial_View (gnat_desig_type);
5837             gnu_init = gnat_to_gnu (Expression (gnat_temp));
5838
5839             gnu_init = maybe_unconstrained_array (gnu_init);
5840             if (Do_Range_Check (Expression (gnat_temp)))
5841               gnu_init
5842                 = emit_range_check (gnu_init, gnat_desig_type, gnat_temp);
5843
5844             if (Is_Elementary_Type (gnat_desig_type)
5845                 || Is_Constrained (gnat_desig_type))
5846               {
5847                 gnu_type = gnat_to_gnu_type (gnat_desig_type);
5848                 gnu_init = convert (gnu_type, gnu_init);
5849               }
5850             else
5851               {
5852                 gnu_type = gnat_to_gnu_type (Etype (Expression (gnat_temp)));
5853                 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
5854                   gnu_type = TREE_TYPE (gnu_init);
5855
5856                 gnu_init = convert (gnu_type, gnu_init);
5857               }
5858           }
5859         else
5860           gcc_unreachable ();
5861
5862         gnu_result_type = get_unpadded_type (Etype (gnat_node));
5863         return build_allocator (gnu_type, gnu_init, gnu_result_type,
5864                                 Procedure_To_Call (gnat_node),
5865                                 Storage_Pool (gnat_node), gnat_node,
5866                                 ignore_init_type);
5867       }
5868       break;
5869
5870     /**************************/
5871     /* Chapter 5: Statements  */
5872     /**************************/
5873
5874     case N_Label:
5875       gnu_result = build1 (LABEL_EXPR, void_type_node,
5876                            gnat_to_gnu (Identifier (gnat_node)));
5877       break;
5878
5879     case N_Null_Statement:
5880       /* When not optimizing, turn null statements from source into gotos to
5881          the next statement that the middle-end knows how to preserve.  */
5882       if (!optimize && Comes_From_Source (gnat_node))
5883         {
5884           tree stmt, label = create_label_decl (NULL_TREE, gnat_node);
5885           DECL_IGNORED_P (label) = 1;
5886           start_stmt_group ();
5887           stmt = build1 (GOTO_EXPR, void_type_node, label);
5888           set_expr_location_from_node (stmt, gnat_node);
5889           add_stmt (stmt);
5890           stmt = build1 (LABEL_EXPR, void_type_node, label);
5891           set_expr_location_from_node (stmt, gnat_node);
5892           add_stmt (stmt);
5893           gnu_result = end_stmt_group ();
5894         }
5895       else
5896         gnu_result = alloc_stmt_list ();
5897       break;
5898
5899     case N_Assignment_Statement:
5900       /* Get the LHS and RHS of the statement and convert any reference to an
5901          unconstrained array into a reference to the underlying array.  */
5902       gnu_lhs = maybe_unconstrained_array (gnat_to_gnu (Name (gnat_node)));
5903
5904       /* If the type has a size that overflows, convert this into raise of
5905          Storage_Error: execution shouldn't have gotten here anyway.  */
5906       if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))) == INTEGER_CST
5907            && TREE_OVERFLOW (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))))
5908         gnu_result = build_call_raise (SE_Object_Too_Large, gnat_node,
5909                                        N_Raise_Storage_Error);
5910       else if (Nkind (Expression (gnat_node)) == N_Function_Call)
5911         gnu_result
5912           = call_to_gnu (Expression (gnat_node), &gnu_result_type, gnu_lhs,
5913                          atomic_sync_required_p (Name (gnat_node)));
5914       else
5915         {
5916           gnu_rhs
5917             = maybe_unconstrained_array (gnat_to_gnu (Expression (gnat_node)));
5918
5919           /* If range check is needed, emit code to generate it.  */
5920           if (Do_Range_Check (Expression (gnat_node)))
5921             gnu_rhs = emit_range_check (gnu_rhs, Etype (Name (gnat_node)),
5922                                         gnat_node);
5923
5924           if (atomic_sync_required_p (Name (gnat_node)))
5925             gnu_result = build_atomic_store (gnu_lhs, gnu_rhs);
5926           else
5927             gnu_result
5928               = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_lhs, gnu_rhs);
5929
5930           /* If the type being assigned is an array type and the two sides are
5931              not completely disjoint, play safe and use memmove.  But don't do
5932              it for a bit-packed array as it might not be byte-aligned.  */
5933           if (TREE_CODE (gnu_result) == MODIFY_EXPR
5934               && Is_Array_Type (Etype (Name (gnat_node)))
5935               && !Is_Bit_Packed_Array (Etype (Name (gnat_node)))
5936               && !(Forwards_OK (gnat_node) && Backwards_OK (gnat_node)))
5937             {
5938               tree to, from, size, to_ptr, from_ptr, t;
5939
5940               to = TREE_OPERAND (gnu_result, 0);
5941               from = TREE_OPERAND (gnu_result, 1);
5942
5943               size = TYPE_SIZE_UNIT (TREE_TYPE (from));
5944               size = SUBSTITUTE_PLACEHOLDER_IN_EXPR (size, from);
5945
5946               to_ptr = build_fold_addr_expr (to);
5947               from_ptr = build_fold_addr_expr (from);
5948
5949               t = builtin_decl_implicit (BUILT_IN_MEMMOVE);
5950               gnu_result = build_call_expr (t, 3, to_ptr, from_ptr, size);
5951            }
5952         }
5953       break;
5954
5955     case N_If_Statement:
5956       {
5957         tree *gnu_else_ptr; /* Point to put next "else if" or "else".  */
5958
5959         /* Make the outer COND_EXPR.  Avoid non-determinism.  */
5960         gnu_result = build3 (COND_EXPR, void_type_node,
5961                              gnat_to_gnu (Condition (gnat_node)),
5962                              NULL_TREE, NULL_TREE);
5963         COND_EXPR_THEN (gnu_result)
5964           = build_stmt_group (Then_Statements (gnat_node), false);
5965         TREE_SIDE_EFFECTS (gnu_result) = 1;
5966         gnu_else_ptr = &COND_EXPR_ELSE (gnu_result);
5967
5968         /* Now make a COND_EXPR for each of the "else if" parts.  Put each
5969            into the previous "else" part and point to where to put any
5970            outer "else".  Also avoid non-determinism.  */
5971         if (Present (Elsif_Parts (gnat_node)))
5972           for (gnat_temp = First (Elsif_Parts (gnat_node));
5973                Present (gnat_temp); gnat_temp = Next (gnat_temp))
5974             {
5975               gnu_expr = build3 (COND_EXPR, void_type_node,
5976                                  gnat_to_gnu (Condition (gnat_temp)),
5977                                  NULL_TREE, NULL_TREE);
5978               COND_EXPR_THEN (gnu_expr)
5979                 = build_stmt_group (Then_Statements (gnat_temp), false);
5980               TREE_SIDE_EFFECTS (gnu_expr) = 1;
5981               set_expr_location_from_node (gnu_expr, gnat_temp);
5982               *gnu_else_ptr = gnu_expr;
5983               gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
5984             }
5985
5986         *gnu_else_ptr = build_stmt_group (Else_Statements (gnat_node), false);
5987       }
5988       break;
5989
5990     case N_Case_Statement:
5991       gnu_result = Case_Statement_to_gnu (gnat_node);
5992       break;
5993
5994     case N_Loop_Statement:
5995       gnu_result = Loop_Statement_to_gnu (gnat_node);
5996       break;
5997
5998     case N_Block_Statement:
5999       start_stmt_group ();
6000       gnat_pushlevel ();
6001       process_decls (Declarations (gnat_node), Empty, Empty, true, true);
6002       add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
6003       gnat_poplevel ();
6004       gnu_result = end_stmt_group ();
6005
6006       if (Present (Identifier (gnat_node)))
6007         mark_out_of_scope (Entity (Identifier (gnat_node)));
6008       break;
6009
6010     case N_Exit_Statement:
6011       gnu_result
6012         = build2 (EXIT_STMT, void_type_node,
6013                   (Present (Condition (gnat_node))
6014                    ? gnat_to_gnu (Condition (gnat_node)) : NULL_TREE),
6015                   (Present (Name (gnat_node))
6016                    ? get_gnu_tree (Entity (Name (gnat_node)))
6017                    : VEC_last (loop_info, gnu_loop_stack)->label));
6018       break;
6019
6020     case N_Return_Statement:
6021       {
6022         tree gnu_ret_obj, gnu_ret_val;
6023
6024         /* If the subprogram is a function, we must return the expression.  */
6025         if (Present (Expression (gnat_node)))
6026           {
6027             tree gnu_subprog_type = TREE_TYPE (current_function_decl);
6028
6029             /* If this function has copy-in/copy-out parameters, get the real
6030                object for the return.  See Subprogram_to_gnu.  */
6031             if (TYPE_CI_CO_LIST (gnu_subprog_type))
6032               gnu_ret_obj = VEC_last (tree, gnu_return_var_stack);
6033             else
6034               gnu_ret_obj = DECL_RESULT (current_function_decl);
6035
6036             /* Get the GCC tree for the expression to be returned.  */
6037             gnu_ret_val = gnat_to_gnu (Expression (gnat_node));
6038
6039             /* Do not remove the padding from GNU_RET_VAL if the inner type is
6040                self-referential since we want to allocate the fixed size.  */
6041             if (TREE_CODE (gnu_ret_val) == COMPONENT_REF
6042                 && TYPE_IS_PADDING_P
6043                    (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0)))
6044                 && CONTAINS_PLACEHOLDER_P
6045                    (TYPE_SIZE (TREE_TYPE (gnu_ret_val))))
6046               gnu_ret_val = TREE_OPERAND (gnu_ret_val, 0);
6047
6048             /* If the function returns by direct reference, return a pointer
6049                to the return value.  */
6050             if (TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type)
6051                 || By_Ref (gnat_node))
6052               gnu_ret_val = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_ret_val);
6053
6054             /* Otherwise, if it returns an unconstrained array, we have to
6055                allocate a new version of the result and return it.  */
6056             else if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type))
6057               {
6058                 gnu_ret_val = maybe_unconstrained_array (gnu_ret_val);
6059
6060                 /* And find out whether this is a candidate for Named Return
6061                    Value.  If so, record it.  */
6062                 if (!TYPE_CI_CO_LIST (gnu_subprog_type) && optimize)
6063                   {
6064                     tree ret_val = gnu_ret_val;
6065
6066                     /* Strip useless conversions around the return value.  */
6067                     if (gnat_useless_type_conversion (ret_val))
6068                       ret_val = TREE_OPERAND (ret_val, 0);
6069
6070                     /* Strip unpadding around the return value.  */
6071                     if (TREE_CODE (ret_val) == COMPONENT_REF
6072                         && TYPE_IS_PADDING_P
6073                            (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
6074                       ret_val = TREE_OPERAND (ret_val, 0);
6075
6076                     /* Now apply the test to the return value.  */
6077                     if (return_value_ok_for_nrv_p (NULL_TREE, ret_val))
6078                       {
6079                         if (!f_named_ret_val)
6080                           f_named_ret_val = BITMAP_GGC_ALLOC ();
6081                         bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
6082                         if (!f_gnat_ret)
6083                           f_gnat_ret = gnat_node;
6084                       }
6085                   }
6086
6087                 gnu_ret_val = build_allocator (TREE_TYPE (gnu_ret_val),
6088                                                gnu_ret_val,
6089                                                TREE_TYPE (gnu_ret_obj),
6090                                                Procedure_To_Call (gnat_node),
6091                                                Storage_Pool (gnat_node),
6092                                                gnat_node, false);
6093               }
6094
6095             /* Otherwise, if it returns by invisible reference, dereference
6096                the pointer it is passed using the type of the return value
6097                and build the copy operation manually.  This ensures that we
6098                don't copy too much data, for example if the return type is
6099                unconstrained with a maximum size.  */
6100             else if (TREE_ADDRESSABLE (gnu_subprog_type))
6101               {
6102                 tree gnu_ret_deref
6103                   = build_unary_op (INDIRECT_REF, TREE_TYPE (gnu_ret_val),
6104                                     gnu_ret_obj);
6105                 gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
6106                                               gnu_ret_deref, gnu_ret_val);
6107                 add_stmt_with_node (gnu_result, gnat_node);
6108                 gnu_ret_val = NULL_TREE;
6109               }
6110           }
6111
6112         else
6113           gnu_ret_obj = gnu_ret_val = NULL_TREE;
6114
6115         /* If we have a return label defined, convert this into a branch to
6116            that label.  The return proper will be handled elsewhere.  */
6117         if (VEC_last (tree, gnu_return_label_stack))
6118           {
6119             if (gnu_ret_obj)
6120               add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_ret_obj,
6121                                          gnu_ret_val));
6122
6123             gnu_result = build1 (GOTO_EXPR, void_type_node,
6124                                  VEC_last (tree, gnu_return_label_stack));
6125
6126             /* When not optimizing, make sure the return is preserved.  */
6127             if (!optimize && Comes_From_Source (gnat_node))
6128               DECL_ARTIFICIAL (VEC_last (tree, gnu_return_label_stack)) = 0;
6129           }
6130
6131         /* Otherwise, build a regular return.  */
6132         else
6133           gnu_result = build_return_expr (gnu_ret_obj, gnu_ret_val);
6134       }
6135       break;
6136
6137     case N_Goto_Statement:
6138       gnu_result
6139         = build1 (GOTO_EXPR, void_type_node, gnat_to_gnu (Name (gnat_node)));
6140       break;
6141
6142     /***************************/
6143     /* Chapter 6: Subprograms  */
6144     /***************************/
6145
6146     case N_Subprogram_Declaration:
6147       /* Unless there is a freeze node, declare the subprogram.  We consider
6148          this a "definition" even though we're not generating code for
6149          the subprogram because we will be making the corresponding GCC
6150          node here.  */
6151
6152       if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
6153         gnat_to_gnu_entity (Defining_Entity (Specification (gnat_node)),
6154                             NULL_TREE, 1);
6155       gnu_result = alloc_stmt_list ();
6156       break;
6157
6158     case N_Abstract_Subprogram_Declaration:
6159       /* This subprogram doesn't exist for code generation purposes, but we
6160          have to elaborate the types of any parameters and result, unless
6161          they are imported types (nothing to generate in this case).
6162
6163          The parameter list may contain types with freeze nodes, e.g. not null
6164          subtypes, so the subprogram itself may carry a freeze node, in which
6165          case its elaboration must be deferred.  */
6166
6167       /* Process the parameter types first.  */
6168       if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
6169       for (gnat_temp
6170            = First_Formal_With_Extras
6171               (Defining_Entity (Specification (gnat_node)));
6172            Present (gnat_temp);
6173            gnat_temp = Next_Formal_With_Extras (gnat_temp))
6174         if (Is_Itype (Etype (gnat_temp))
6175             && !From_With_Type (Etype (gnat_temp)))
6176           gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
6177
6178       /* Then the result type, set to Standard_Void_Type for procedures.  */
6179       {
6180         Entity_Id gnat_temp_type
6181           = Etype (Defining_Entity (Specification (gnat_node)));
6182
6183         if (Is_Itype (gnat_temp_type) && !From_With_Type (gnat_temp_type))
6184           gnat_to_gnu_entity (Etype (gnat_temp_type), NULL_TREE, 0);
6185       }
6186
6187       gnu_result = alloc_stmt_list ();
6188       break;
6189
6190     case N_Defining_Program_Unit_Name:
6191       /* For a child unit identifier go up a level to get the specification.
6192          We get this when we try to find the spec of a child unit package
6193          that is the compilation unit being compiled.  */
6194       gnu_result = gnat_to_gnu (Parent (gnat_node));
6195       break;
6196
6197     case N_Subprogram_Body:
6198       Subprogram_Body_to_gnu (gnat_node);
6199       gnu_result = alloc_stmt_list ();
6200       break;
6201
6202     case N_Function_Call:
6203     case N_Procedure_Call_Statement:
6204       gnu_result = call_to_gnu (gnat_node, &gnu_result_type, NULL_TREE, false);
6205       break;
6206
6207     /************************/
6208     /* Chapter 7: Packages  */
6209     /************************/
6210
6211     case N_Package_Declaration:
6212       gnu_result = gnat_to_gnu (Specification (gnat_node));
6213       break;
6214
6215     case N_Package_Specification:
6216
6217       start_stmt_group ();
6218       process_decls (Visible_Declarations (gnat_node),
6219                      Private_Declarations (gnat_node), Empty, true, true);
6220       gnu_result = end_stmt_group ();
6221       break;
6222
6223     case N_Package_Body:
6224
6225       /* If this is the body of a generic package - do nothing.  */
6226       if (Ekind (Corresponding_Spec (gnat_node)) == E_Generic_Package)
6227         {
6228           gnu_result = alloc_stmt_list ();
6229           break;
6230         }
6231
6232       start_stmt_group ();
6233       process_decls (Declarations (gnat_node), Empty, Empty, true, true);
6234
6235       if (Present (Handled_Statement_Sequence (gnat_node)))
6236         add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
6237
6238       gnu_result = end_stmt_group ();
6239       break;
6240
6241     /********************************/
6242     /* Chapter 8: Visibility Rules  */
6243     /********************************/
6244
6245     case N_Use_Package_Clause:
6246     case N_Use_Type_Clause:
6247       /* Nothing to do here - but these may appear in list of declarations.  */
6248       gnu_result = alloc_stmt_list ();
6249       break;
6250
6251     /*********************/
6252     /* Chapter 9: Tasks  */
6253     /*********************/
6254
6255     case N_Protected_Type_Declaration:
6256       gnu_result = alloc_stmt_list ();
6257       break;
6258
6259     case N_Single_Task_Declaration:
6260       gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
6261       gnu_result = alloc_stmt_list ();
6262       break;
6263
6264     /*********************************************************/
6265     /* Chapter 10: Program Structure and Compilation Issues  */
6266     /*********************************************************/
6267
6268     case N_Compilation_Unit:
6269       /* This is not called for the main unit on which gigi is invoked.  */
6270       Compilation_Unit_to_gnu (gnat_node);
6271       gnu_result = alloc_stmt_list ();
6272       break;
6273
6274     case N_Subprogram_Body_Stub:
6275     case N_Package_Body_Stub:
6276     case N_Protected_Body_Stub:
6277     case N_Task_Body_Stub:
6278       /* Simply process whatever unit is being inserted.  */
6279       gnu_result = gnat_to_gnu (Unit (Library_Unit (gnat_node)));
6280       break;
6281
6282     case N_Subunit:
6283       gnu_result = gnat_to_gnu (Proper_Body (gnat_node));
6284       break;
6285
6286     /***************************/
6287     /* Chapter 11: Exceptions  */
6288     /***************************/
6289
6290     case N_Handled_Sequence_Of_Statements:
6291       /* If there is an At_End procedure attached to this node, and the EH
6292          mechanism is SJLJ, we must have at least a corresponding At_End
6293          handler, unless the No_Exception_Handlers restriction is set.  */
6294       gcc_assert (type_annotate_only
6295                   || Exception_Mechanism != Setjmp_Longjmp
6296                   || No (At_End_Proc (gnat_node))
6297                   || Present (Exception_Handlers (gnat_node))
6298                   || No_Exception_Handlers_Set ());
6299
6300       gnu_result = Handled_Sequence_Of_Statements_to_gnu (gnat_node);
6301       break;
6302
6303     case N_Exception_Handler:
6304       if (Exception_Mechanism == Setjmp_Longjmp)
6305         gnu_result = Exception_Handler_to_gnu_sjlj (gnat_node);
6306       else if (Exception_Mechanism == Back_End_Exceptions)
6307         gnu_result = Exception_Handler_to_gnu_zcx (gnat_node);
6308       else
6309         gcc_unreachable ();
6310       break;
6311
6312     case N_Raise_Statement:
6313       /* Only for reraise in back-end exceptions mode.  */
6314       gcc_assert (No (Name (gnat_node))
6315                   && Exception_Mechanism == Back_End_Exceptions);
6316
6317       start_stmt_group ();
6318       gnat_pushlevel ();
6319
6320       /* Clear the current exception pointer so that the occurrence won't be
6321          deallocated.  */
6322       gnu_expr = create_var_decl (get_identifier ("SAVED_EXPTR"), NULL_TREE,
6323                                   ptr_type_node, gnu_incoming_exc_ptr,
6324                                   false, false, false, false, NULL, gnat_node);
6325
6326       add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_incoming_exc_ptr,
6327                                  convert (ptr_type_node, integer_zero_node)));
6328       add_stmt (build_call_n_expr (reraise_zcx_decl, 1, gnu_expr));
6329       gnat_poplevel ();
6330       gnu_result = end_stmt_group ();
6331       break;
6332
6333     case N_Push_Constraint_Error_Label:
6334       push_exception_label_stack (&gnu_constraint_error_label_stack,
6335                                   Exception_Label (gnat_node));
6336       break;
6337
6338     case N_Push_Storage_Error_Label:
6339       push_exception_label_stack (&gnu_storage_error_label_stack,
6340                                   Exception_Label (gnat_node));
6341       break;
6342
6343     case N_Push_Program_Error_Label:
6344       push_exception_label_stack (&gnu_program_error_label_stack,
6345                                   Exception_Label (gnat_node));
6346       break;
6347
6348     case N_Pop_Constraint_Error_Label:
6349       VEC_pop (tree, gnu_constraint_error_label_stack);
6350       break;
6351
6352     case N_Pop_Storage_Error_Label:
6353       VEC_pop (tree, gnu_storage_error_label_stack);
6354       break;
6355
6356     case N_Pop_Program_Error_Label:
6357       VEC_pop (tree, gnu_program_error_label_stack);
6358       break;
6359
6360     /******************************/
6361     /* Chapter 12: Generic Units  */
6362     /******************************/
6363
6364     case N_Generic_Function_Renaming_Declaration:
6365     case N_Generic_Package_Renaming_Declaration:
6366     case N_Generic_Procedure_Renaming_Declaration:
6367     case N_Generic_Package_Declaration:
6368     case N_Generic_Subprogram_Declaration:
6369     case N_Package_Instantiation:
6370     case N_Procedure_Instantiation:
6371     case N_Function_Instantiation:
6372       /* These nodes can appear on a declaration list but there is nothing to
6373          to be done with them.  */
6374       gnu_result = alloc_stmt_list ();
6375       break;
6376
6377     /**************************************************/
6378     /* Chapter 13: Representation Clauses and         */
6379     /*             Implementation-Dependent Features  */
6380     /**************************************************/
6381
6382     case N_Attribute_Definition_Clause:
6383       gnu_result = alloc_stmt_list ();
6384
6385       /* The only one we need to deal with is 'Address since, for the others,
6386          the front-end puts the information elsewhere.  */
6387       if (Get_Attribute_Id (Chars (gnat_node)) != Attr_Address)
6388         break;
6389
6390       /* And we only deal with 'Address if the object has a Freeze node.  */
6391       gnat_temp = Entity (Name (gnat_node));
6392       if (No (Freeze_Node (gnat_temp)))
6393         break;
6394
6395       /* Get the value to use as the address and save it as the equivalent
6396          for the object.  When it is frozen, gnat_to_gnu_entity will do the
6397          right thing.  */
6398       save_gnu_tree (gnat_temp, gnat_to_gnu (Expression (gnat_node)), true);
6399       break;
6400
6401     case N_Enumeration_Representation_Clause:
6402     case N_Record_Representation_Clause:
6403     case N_At_Clause:
6404       /* We do nothing with these.  SEM puts the information elsewhere.  */
6405       gnu_result = alloc_stmt_list ();
6406       break;
6407
6408     case N_Code_Statement:
6409       if (!type_annotate_only)
6410         {
6411           tree gnu_template = gnat_to_gnu (Asm_Template (gnat_node));
6412           tree gnu_inputs = NULL_TREE, gnu_outputs = NULL_TREE;
6413           tree gnu_clobbers = NULL_TREE, tail;
6414           bool allows_mem, allows_reg, fake;
6415           int ninputs, noutputs, i;
6416           const char **oconstraints;
6417           const char *constraint;
6418           char *clobber;
6419
6420           /* First retrieve the 3 operand lists built by the front-end.  */
6421           Setup_Asm_Outputs (gnat_node);
6422           while (Present (gnat_temp = Asm_Output_Variable ()))
6423             {
6424               tree gnu_value = gnat_to_gnu (gnat_temp);
6425               tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
6426                                                  (Asm_Output_Constraint ()));
6427
6428               gnu_outputs = tree_cons (gnu_constr, gnu_value, gnu_outputs);
6429               Next_Asm_Output ();
6430             }
6431
6432           Setup_Asm_Inputs (gnat_node);
6433           while (Present (gnat_temp = Asm_Input_Value ()))
6434             {
6435               tree gnu_value = gnat_to_gnu (gnat_temp);
6436               tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
6437                                                  (Asm_Input_Constraint ()));
6438
6439               gnu_inputs = tree_cons (gnu_constr, gnu_value, gnu_inputs);
6440               Next_Asm_Input ();
6441             }
6442
6443           Clobber_Setup (gnat_node);
6444           while ((clobber = Clobber_Get_Next ()))
6445             gnu_clobbers
6446               = tree_cons (NULL_TREE,
6447                            build_string (strlen (clobber) + 1, clobber),
6448                            gnu_clobbers);
6449
6450           /* Then perform some standard checking and processing on the
6451              operands.  In particular, mark them addressable if needed.  */
6452           gnu_outputs = nreverse (gnu_outputs);
6453           noutputs = list_length (gnu_outputs);
6454           gnu_inputs = nreverse (gnu_inputs);
6455           ninputs = list_length (gnu_inputs);
6456           oconstraints = XALLOCAVEC (const char *, noutputs);
6457
6458           for (i = 0, tail = gnu_outputs; tail; ++i, tail = TREE_CHAIN (tail))
6459             {
6460               tree output = TREE_VALUE (tail);
6461               constraint
6462                 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
6463               oconstraints[i] = constraint;
6464
6465               if (parse_output_constraint (&constraint, i, ninputs, noutputs,
6466                                            &allows_mem, &allows_reg, &fake))
6467                 {
6468                   /* If the operand is going to end up in memory,
6469                      mark it addressable.  Note that we don't test
6470                      allows_mem like in the input case below; this
6471                      is modelled on the C front-end.  */
6472                   if (!allows_reg)
6473                     {
6474                       output = remove_conversions (output, false);
6475                       if (TREE_CODE (output) == CONST_DECL
6476                           && DECL_CONST_CORRESPONDING_VAR (output))
6477                         output = DECL_CONST_CORRESPONDING_VAR (output);
6478                       if (!gnat_mark_addressable (output))
6479                         output = error_mark_node;
6480                     }
6481                 }
6482               else
6483                 output = error_mark_node;
6484
6485               TREE_VALUE (tail) = output;
6486             }
6487
6488           for (i = 0, tail = gnu_inputs; tail; ++i, tail = TREE_CHAIN (tail))
6489             {
6490               tree input = TREE_VALUE (tail);
6491               constraint
6492                 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
6493
6494               if (parse_input_constraint (&constraint, i, ninputs, noutputs,
6495                                           0, oconstraints,
6496                                           &allows_mem, &allows_reg))
6497                 {
6498                   /* If the operand is going to end up in memory,
6499                      mark it addressable.  */
6500                   if (!allows_reg && allows_mem)
6501                     {
6502                       input = remove_conversions (input, false);
6503                       if (TREE_CODE (input) == CONST_DECL
6504                           && DECL_CONST_CORRESPONDING_VAR (input))
6505                         input = DECL_CONST_CORRESPONDING_VAR (input);
6506                       if (!gnat_mark_addressable (input))
6507                         input = error_mark_node;
6508                     }
6509                 }
6510               else
6511                 input = error_mark_node;
6512
6513               TREE_VALUE (tail) = input;
6514             }
6515
6516           gnu_result = build5 (ASM_EXPR,  void_type_node,
6517                                gnu_template, gnu_outputs,
6518                                gnu_inputs, gnu_clobbers, NULL_TREE);
6519           ASM_VOLATILE_P (gnu_result) = Is_Asm_Volatile (gnat_node);
6520         }
6521       else
6522         gnu_result = alloc_stmt_list ();
6523
6524       break;
6525
6526     /****************/
6527     /* Added Nodes  */
6528     /****************/
6529
6530     case N_Expression_With_Actions:
6531       gnu_result_type = get_unpadded_type (Etype (gnat_node));
6532       /* This construct doesn't define a scope so we don't wrap the statement
6533          list in a BIND_EXPR; however, we wrap it in a SAVE_EXPR to protect it
6534          from unsharing.  */
6535       gnu_result = build_stmt_group (Actions (gnat_node), false);
6536       gnu_result = build1 (SAVE_EXPR, void_type_node, gnu_result);
6537       TREE_SIDE_EFFECTS (gnu_result) = 1;
6538       gnu_expr = gnat_to_gnu (Expression (gnat_node));
6539       gnu_result
6540         = build_compound_expr (TREE_TYPE (gnu_expr), gnu_result, gnu_expr);
6541       break;
6542
6543     case N_Freeze_Entity:
6544       start_stmt_group ();
6545       process_freeze_entity (gnat_node);
6546       process_decls (Actions (gnat_node), Empty, Empty, true, true);
6547       gnu_result = end_stmt_group ();
6548       break;
6549
6550     case N_Itype_Reference:
6551       if (!present_gnu_tree (Itype (gnat_node)))
6552         process_type (Itype (gnat_node));
6553
6554       gnu_result = alloc_stmt_list ();
6555       break;
6556
6557     case N_Free_Statement:
6558       if (!type_annotate_only)
6559         {
6560           tree gnu_ptr = gnat_to_gnu (Expression (gnat_node));
6561           tree gnu_ptr_type = TREE_TYPE (gnu_ptr);
6562           tree gnu_obj_type;
6563           tree gnu_actual_obj_type = 0;
6564           tree gnu_obj_size;
6565
6566           /* If this is a thin pointer, we must dereference it to create
6567              a fat pointer, then go back below to a thin pointer.  The
6568              reason for this is that we need a fat pointer someplace in
6569              order to properly compute the size.  */
6570           if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
6571             gnu_ptr = build_unary_op (ADDR_EXPR, NULL_TREE,
6572                                       build_unary_op (INDIRECT_REF, NULL_TREE,
6573                                                       gnu_ptr));
6574
6575           /* If this is an unconstrained array, we know the object must
6576              have been allocated with the template in front of the object.
6577              So pass the template address, but get the total size.  Do this
6578              by converting to a thin pointer.  */
6579           if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
6580             gnu_ptr
6581               = convert (build_pointer_type
6582                          (TYPE_OBJECT_RECORD_TYPE
6583                           (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
6584                          gnu_ptr);
6585
6586           gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
6587
6588           if (Present (Actual_Designated_Subtype (gnat_node)))
6589             {
6590               gnu_actual_obj_type
6591                 = gnat_to_gnu_type (Actual_Designated_Subtype (gnat_node));
6592
6593               if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
6594                 gnu_actual_obj_type
6595                   = build_unc_object_type_from_ptr (gnu_ptr_type,
6596                                                     gnu_actual_obj_type,
6597                                                     get_identifier ("DEALLOC"),
6598                                                     false);
6599             }
6600           else
6601             gnu_actual_obj_type = gnu_obj_type;
6602
6603           gnu_obj_size = TYPE_SIZE_UNIT (gnu_actual_obj_type);
6604
6605           if (TREE_CODE (gnu_obj_type) == RECORD_TYPE
6606               && TYPE_CONTAINS_TEMPLATE_P (gnu_obj_type))
6607             {
6608               tree gnu_char_ptr_type
6609                 = build_pointer_type (unsigned_char_type_node);
6610               tree gnu_pos = byte_position (TYPE_FIELDS (gnu_obj_type));
6611               gnu_ptr = convert (gnu_char_ptr_type, gnu_ptr);
6612               gnu_ptr = build_binary_op (POINTER_PLUS_EXPR, gnu_char_ptr_type,
6613                                          gnu_ptr, gnu_pos);
6614             }
6615
6616           gnu_result
6617               = build_call_alloc_dealloc (gnu_ptr, gnu_obj_size, gnu_obj_type,
6618                                           Procedure_To_Call (gnat_node),
6619                                           Storage_Pool (gnat_node),
6620                                           gnat_node);
6621         }
6622       break;
6623
6624     case N_Raise_Constraint_Error:
6625     case N_Raise_Program_Error:
6626     case N_Raise_Storage_Error:
6627       {
6628         const int reason = UI_To_Int (Reason (gnat_node));
6629         const Node_Id gnat_cond = Condition (gnat_node);
6630         const bool with_extra_info = Exception_Extra_Info
6631                                      && !No_Exception_Handlers_Set ()
6632                                      && !get_exception_label (kind);
6633         tree gnu_cond = NULL_TREE;
6634
6635         if (type_annotate_only)
6636           {
6637             gnu_result = alloc_stmt_list ();
6638             break;
6639           }
6640
6641         gnu_result_type = get_unpadded_type (Etype (gnat_node));
6642
6643         switch (reason)
6644           {
6645           case CE_Access_Check_Failed:
6646             if (with_extra_info)
6647               gnu_result = build_call_raise_column (reason, gnat_node);
6648             break;
6649
6650           case CE_Index_Check_Failed:
6651           case CE_Range_Check_Failed:
6652           case CE_Invalid_Data:
6653             if (Present (gnat_cond)
6654                 && Nkind (gnat_cond) == N_Op_Not
6655                 && Nkind (Right_Opnd (gnat_cond)) == N_In
6656                 && Nkind (Right_Opnd (Right_Opnd (gnat_cond))) == N_Range)
6657               {
6658                 Node_Id gnat_index = Left_Opnd (Right_Opnd (gnat_cond));
6659                 Node_Id gnat_type = Etype (gnat_index);
6660                 Node_Id gnat_range = Right_Opnd (Right_Opnd (gnat_cond));
6661                 tree gnu_index = gnat_to_gnu (gnat_index);
6662                 tree gnu_low_bound = gnat_to_gnu (Low_Bound (gnat_range));
6663                 tree gnu_high_bound = gnat_to_gnu (High_Bound (gnat_range));
6664                 struct range_check_info_d *rci;
6665
6666                 if (with_extra_info
6667                     && Known_Esize (gnat_type)
6668                     && UI_To_Int (Esize (gnat_type)) <= 32)
6669                   gnu_result
6670                     = build_call_raise_range (reason, gnat_node, gnu_index,
6671                                               gnu_low_bound, gnu_high_bound);
6672
6673                 /* If loop unswitching is enabled, we try to compute invariant
6674                    conditions for checks applied to iteration variables, i.e.
6675                    conditions that are both independent of the variable and
6676                    necessary in order for the check to fail in the course of
6677                    some iteration, and prepend them to the original condition
6678                    of the checks.  This will make it possible later for the
6679                    loop unswitching pass to replace the loop with two loops,
6680                    one of which has the checks eliminated and the other has
6681                    the original checks reinstated, and a run time selection.
6682                    The former loop will be suitable for vectorization.  */
6683                 if (flag_unswitch_loops
6684                     && (gnu_low_bound = gnat_invariant_expr (gnu_low_bound))
6685                     && (gnu_high_bound = gnat_invariant_expr (gnu_high_bound))
6686                     && (rci = push_range_check_info (gnu_index)))
6687                   {
6688                     rci->low_bound = gnu_low_bound;
6689                     rci->high_bound = gnu_high_bound;
6690                     rci->type = gnat_to_gnu_type (gnat_type);
6691                     rci->invariant_cond = build1 (SAVE_EXPR, boolean_type_node,
6692                                                   boolean_true_node);
6693                     gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
6694                                                 boolean_type_node,
6695                                                 rci->invariant_cond,
6696                                                 gnat_to_gnu (gnat_cond));
6697                   }
6698               }
6699             break;
6700
6701           default:
6702             break;
6703           }
6704
6705         if (gnu_result == error_mark_node)
6706           gnu_result = build_call_raise (reason, gnat_node, kind);
6707
6708         set_expr_location_from_node (gnu_result, gnat_node);
6709
6710         /* If the type is VOID, this is a statement, so we need to generate
6711            the code for the call.  Handle a condition, if there is one.  */
6712         if (VOID_TYPE_P (gnu_result_type))
6713           {
6714             if (Present (gnat_cond))
6715               {
6716                 if (!gnu_cond)
6717                   gnu_cond = gnat_to_gnu (gnat_cond);
6718                 gnu_result
6719                   = build3 (COND_EXPR, void_type_node, gnu_cond, gnu_result,
6720                             alloc_stmt_list ());
6721               }
6722           }
6723         else
6724           gnu_result = build1 (NULL_EXPR, gnu_result_type, gnu_result);
6725       }
6726       break;
6727
6728     case N_Validate_Unchecked_Conversion:
6729       {
6730         Entity_Id gnat_target_type = Target_Type (gnat_node);
6731         tree gnu_source_type = gnat_to_gnu_type (Source_Type (gnat_node));
6732         tree gnu_target_type = gnat_to_gnu_type (gnat_target_type);
6733
6734         /* No need for any warning in this case.  */
6735         if (!flag_strict_aliasing)
6736           ;
6737
6738         /* If the result is a pointer type, see if we are either converting
6739            from a non-pointer or from a pointer to a type with a different
6740            alias set and warn if so.  If the result is defined in the same
6741            unit as this unchecked conversion, we can allow this because we
6742            can know to make the pointer type behave properly.  */
6743         else if (POINTER_TYPE_P (gnu_target_type)
6744                  && !In_Same_Source_Unit (gnat_target_type, gnat_node)
6745                  && !No_Strict_Aliasing (Underlying_Type (gnat_target_type)))
6746           {
6747             tree gnu_source_desig_type = POINTER_TYPE_P (gnu_source_type)
6748                                          ? TREE_TYPE (gnu_source_type)
6749                                          : NULL_TREE;
6750             tree gnu_target_desig_type = TREE_TYPE (gnu_target_type);
6751
6752             if ((TYPE_DUMMY_P (gnu_target_desig_type)
6753                  || get_alias_set (gnu_target_desig_type) != 0)
6754                 && (!POINTER_TYPE_P (gnu_source_type)
6755                     || (TYPE_DUMMY_P (gnu_source_desig_type)
6756                         != TYPE_DUMMY_P (gnu_target_desig_type))
6757                     || (TYPE_DUMMY_P (gnu_source_desig_type)
6758                         && gnu_source_desig_type != gnu_target_desig_type)
6759                     || !alias_sets_conflict_p
6760                         (get_alias_set (gnu_source_desig_type),
6761                          get_alias_set (gnu_target_desig_type))))
6762               {
6763                 post_error_ne
6764                   ("?possible aliasing problem for type&",
6765                    gnat_node, Target_Type (gnat_node));
6766                 post_error
6767                   ("\\?use -fno-strict-aliasing switch for references",
6768                    gnat_node);
6769                 post_error_ne
6770                   ("\\?or use `pragma No_Strict_Aliasing (&);`",
6771                    gnat_node, Target_Type (gnat_node));
6772               }
6773           }
6774
6775         /* But if the result is a fat pointer type, we have no mechanism to
6776            do that, so we unconditionally warn in problematic cases.  */
6777         else if (TYPE_IS_FAT_POINTER_P (gnu_target_type))
6778           {
6779             tree gnu_source_array_type
6780               = TYPE_IS_FAT_POINTER_P (gnu_source_type)
6781                 ? TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_source_type)))
6782                 : NULL_TREE;
6783             tree gnu_target_array_type
6784               = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_target_type)));
6785
6786             if ((TYPE_DUMMY_P (gnu_target_array_type)
6787                  || get_alias_set (gnu_target_array_type) != 0)
6788                 && (!TYPE_IS_FAT_POINTER_P (gnu_source_type)
6789                     || (TYPE_DUMMY_P (gnu_source_array_type)
6790                         != TYPE_DUMMY_P (gnu_target_array_type))
6791                     || (TYPE_DUMMY_P (gnu_source_array_type)
6792                         && gnu_source_array_type != gnu_target_array_type)
6793                     || !alias_sets_conflict_p
6794                         (get_alias_set (gnu_source_array_type),
6795                          get_alias_set (gnu_target_array_type))))
6796               {
6797                 post_error_ne
6798                   ("?possible aliasing problem for type&",
6799                    gnat_node, Target_Type (gnat_node));
6800                 post_error
6801                   ("\\?use -fno-strict-aliasing switch for references",
6802                    gnat_node);
6803               }
6804           }
6805       }
6806       gnu_result = alloc_stmt_list ();
6807       break;
6808
6809     default:
6810       /* SCIL nodes require no processing for GCC.  Other nodes should only
6811          be present when annotating types.  */
6812       gcc_assert (IN (kind, N_SCIL_Node) || type_annotate_only);
6813       gnu_result = alloc_stmt_list ();
6814     }
6815
6816   /* If we pushed the processing of the elaboration routine, pop it back.  */
6817   if (went_into_elab_proc)
6818     current_function_decl = NULL_TREE;
6819
6820   /* When not optimizing, turn boolean rvalues B into B != false tests
6821      so that the code just below can put the location information of the
6822      reference to B on the inequality operator for better debug info.  */
6823   if (!optimize
6824       && TREE_CODE (gnu_result) != INTEGER_CST
6825       && (kind == N_Identifier
6826           || kind == N_Expanded_Name
6827           || kind == N_Explicit_Dereference
6828           || kind == N_Function_Call
6829           || kind == N_Indexed_Component
6830           || kind == N_Selected_Component)
6831       && TREE_CODE (get_base_type (gnu_result_type)) == BOOLEAN_TYPE
6832       && !lvalue_required_p (gnat_node, gnu_result_type, false, false, false))
6833     gnu_result = build_binary_op (NE_EXPR, gnu_result_type,
6834                                   convert (gnu_result_type, gnu_result),
6835                                   convert (gnu_result_type,
6836                                            boolean_false_node));
6837
6838   /* Set the location information on the result.  Note that we may have
6839      no result if we tried to build a CALL_EXPR node to a procedure with
6840      no side-effects and optimization is enabled.  */
6841   if (gnu_result && EXPR_P (gnu_result))
6842     set_gnu_expr_location_from_node (gnu_result, gnat_node);
6843
6844   /* If we're supposed to return something of void_type, it means we have
6845      something we're elaborating for effect, so just return.  */
6846   if (TREE_CODE (gnu_result_type) == VOID_TYPE)
6847     return gnu_result;
6848
6849   /* If the result is a constant that overflowed, raise Constraint_Error.  */
6850   if (TREE_CODE (gnu_result) == INTEGER_CST && TREE_OVERFLOW (gnu_result))
6851     {
6852       post_error ("?`Constraint_Error` will be raised at run time", gnat_node);
6853       gnu_result
6854         = build1 (NULL_EXPR, gnu_result_type,
6855                   build_call_raise (CE_Overflow_Check_Failed, gnat_node,
6856                                     N_Raise_Constraint_Error));
6857     }
6858
6859   /* If our result has side-effects and is of an unconstrained type,
6860      make a SAVE_EXPR so that we can be sure it will only be referenced
6861      once.  Note we must do this before any conversions.  */
6862   if (TREE_SIDE_EFFECTS (gnu_result)
6863       && (TREE_CODE (gnu_result_type) == UNCONSTRAINED_ARRAY_TYPE
6864           || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))))
6865     gnu_result = gnat_stabilize_reference (gnu_result, false, NULL);
6866
6867   /* Now convert the result to the result type, unless we are in one of the
6868      following cases:
6869
6870        1. If this is the LHS of an assignment or an actual parameter of a
6871           call, return the result almost unmodified since the RHS will have
6872           to be converted to our type in that case, unless the result type
6873           has a simpler size.  Likewise if there is just a no-op unchecked
6874           conversion in-between.  Similarly, don't convert integral types
6875           that are the operands of an unchecked conversion since we need
6876           to ignore those conversions (for 'Valid).
6877
6878        2. If we have a label (which doesn't have any well-defined type), a
6879           field or an error, return the result almost unmodified.  Similarly,
6880           if the two types are record types with the same name, don't convert.
6881           This will be the case when we are converting from a packable version
6882           of a type to its original type and we need those conversions to be
6883           NOPs in order for assignments into these types to work properly.
6884
6885        3. If the type is void or if we have no result, return error_mark_node
6886           to show we have no result.
6887
6888        4. Finally, if the type of the result is already correct.  */
6889
6890   if (Present (Parent (gnat_node))
6891       && (lhs_or_actual_p (gnat_node)
6892           || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
6893               && unchecked_conversion_nop (Parent (gnat_node)))
6894           || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
6895               && !AGGREGATE_TYPE_P (gnu_result_type)
6896               && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))))
6897       && !(TYPE_SIZE (gnu_result_type)
6898            && TYPE_SIZE (TREE_TYPE (gnu_result))
6899            && (AGGREGATE_TYPE_P (gnu_result_type)
6900                == AGGREGATE_TYPE_P (TREE_TYPE (gnu_result)))
6901            && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) == INTEGER_CST
6902                 && (TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_result)))
6903                     != INTEGER_CST))
6904                || (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
6905                    && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))
6906                    && (CONTAINS_PLACEHOLDER_P
6907                        (TYPE_SIZE (TREE_TYPE (gnu_result))))))
6908            && !(TREE_CODE (gnu_result_type) == RECORD_TYPE
6909                 && TYPE_JUSTIFIED_MODULAR_P (gnu_result_type))))
6910     {
6911       /* Remove padding only if the inner object is of self-referential
6912          size: in that case it must be an object of unconstrained type
6913          with a default discriminant and we want to avoid copying too
6914          much data.  */
6915       if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result))
6916           && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS
6917                                      (TREE_TYPE (gnu_result))))))
6918         gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
6919                               gnu_result);
6920     }
6921
6922   else if (TREE_CODE (gnu_result) == LABEL_DECL
6923            || TREE_CODE (gnu_result) == FIELD_DECL
6924            || TREE_CODE (gnu_result) == ERROR_MARK
6925            || (TYPE_NAME (gnu_result_type)
6926                == TYPE_NAME (TREE_TYPE (gnu_result))
6927                && TREE_CODE (gnu_result_type) == RECORD_TYPE
6928                && TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE))
6929     {
6930       /* Remove any padding.  */
6931       if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
6932         gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
6933                               gnu_result);
6934     }
6935
6936   else if (gnu_result == error_mark_node || gnu_result_type == void_type_node)
6937     gnu_result = error_mark_node;
6938
6939   else if (gnu_result_type != TREE_TYPE (gnu_result))
6940     gnu_result = convert (gnu_result_type, gnu_result);
6941
6942   /* We don't need any NOP_EXPR or NON_LVALUE_EXPR on the result.  */
6943   while ((TREE_CODE (gnu_result) == NOP_EXPR
6944           || TREE_CODE (gnu_result) == NON_LVALUE_EXPR)
6945          && TREE_TYPE (TREE_OPERAND (gnu_result, 0)) == TREE_TYPE (gnu_result))
6946     gnu_result = TREE_OPERAND (gnu_result, 0);
6947
6948   return gnu_result;
6949 }
6950 \f
6951 /* Subroutine of above to push the exception label stack.  GNU_STACK is
6952    a pointer to the stack to update and GNAT_LABEL, if present, is the
6953    label to push onto the stack.  */
6954
6955 static void
6956 push_exception_label_stack (VEC(tree,gc) **gnu_stack, Entity_Id gnat_label)
6957 {
6958   tree gnu_label = (Present (gnat_label)
6959                     ? gnat_to_gnu_entity (gnat_label, NULL_TREE, 0)
6960                     : NULL_TREE);
6961
6962   VEC_safe_push (tree, gc, *gnu_stack, gnu_label);
6963 }
6964 \f
6965 /* Record the current code position in GNAT_NODE.  */
6966
6967 static void
6968 record_code_position (Node_Id gnat_node)
6969 {
6970   tree stmt_stmt = build1 (STMT_STMT, void_type_node, NULL_TREE);
6971
6972   add_stmt_with_node (stmt_stmt, gnat_node);
6973   save_gnu_tree (gnat_node, stmt_stmt, true);
6974 }
6975
6976 /* Insert the code for GNAT_NODE at the position saved for that node.  */
6977
6978 static void
6979 insert_code_for (Node_Id gnat_node)
6980 {
6981   STMT_STMT_STMT (get_gnu_tree (gnat_node)) = gnat_to_gnu (gnat_node);
6982   save_gnu_tree (gnat_node, NULL_TREE, true);
6983 }
6984 \f
6985 /* Start a new statement group chained to the previous group.  */
6986
6987 void
6988 start_stmt_group (void)
6989 {
6990   struct stmt_group *group = stmt_group_free_list;
6991
6992   /* First see if we can get one from the free list.  */
6993   if (group)
6994     stmt_group_free_list = group->previous;
6995   else
6996     group = ggc_alloc_stmt_group ();
6997
6998   group->previous = current_stmt_group;
6999   group->stmt_list = group->block = group->cleanups = NULL_TREE;
7000   current_stmt_group = group;
7001 }
7002
7003 /* Add GNU_STMT to the current statement group.  If it is an expression with
7004    no effects, it is ignored.  */
7005
7006 void
7007 add_stmt (tree gnu_stmt)
7008 {
7009   append_to_statement_list (gnu_stmt, &current_stmt_group->stmt_list);
7010 }
7011
7012 /* Similar, but the statement is always added, regardless of side-effects.  */
7013
7014 void
7015 add_stmt_force (tree gnu_stmt)
7016 {
7017   append_to_statement_list_force (gnu_stmt, &current_stmt_group->stmt_list);
7018 }
7019
7020 /* Like add_stmt, but set the location of GNU_STMT to that of GNAT_NODE.  */
7021
7022 void
7023 add_stmt_with_node (tree gnu_stmt, Node_Id gnat_node)
7024 {
7025   if (Present (gnat_node))
7026     set_expr_location_from_node (gnu_stmt, gnat_node);
7027   add_stmt (gnu_stmt);
7028 }
7029
7030 /* Similar, but the statement is always added, regardless of side-effects.  */
7031
7032 void
7033 add_stmt_with_node_force (tree gnu_stmt, Node_Id gnat_node)
7034 {
7035   if (Present (gnat_node))
7036     set_expr_location_from_node (gnu_stmt, gnat_node);
7037   add_stmt_force (gnu_stmt);
7038 }
7039
7040 /* Add a declaration statement for GNU_DECL to the current statement group.
7041    Get SLOC from Entity_Id.  */
7042
7043 void
7044 add_decl_expr (tree gnu_decl, Entity_Id gnat_entity)
7045 {
7046   tree type = TREE_TYPE (gnu_decl);
7047   tree gnu_stmt, gnu_init, t;
7048
7049   /* If this is a variable that Gigi is to ignore, we may have been given
7050      an ERROR_MARK.  So test for it.  We also might have been given a
7051      reference for a renaming.  So only do something for a decl.  Also
7052      ignore a TYPE_DECL for an UNCONSTRAINED_ARRAY_TYPE.  */
7053   if (!DECL_P (gnu_decl)
7054       || (TREE_CODE (gnu_decl) == TYPE_DECL
7055           && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE))
7056     return;
7057
7058   gnu_stmt = build1 (DECL_EXPR, void_type_node, gnu_decl);
7059
7060   /* If we are global, we don't want to actually output the DECL_EXPR for
7061      this decl since we already have evaluated the expressions in the
7062      sizes and positions as globals and doing it again would be wrong.  */
7063   if (global_bindings_p ())
7064     {
7065       /* Mark everything as used to prevent node sharing with subprograms.
7066          Note that walk_tree knows how to deal with TYPE_DECL, but neither
7067          VAR_DECL nor CONST_DECL.  This appears to be somewhat arbitrary.  */
7068       MARK_VISITED (gnu_stmt);
7069       if (TREE_CODE (gnu_decl) == VAR_DECL
7070           || TREE_CODE (gnu_decl) == CONST_DECL)
7071         {
7072           MARK_VISITED (DECL_SIZE (gnu_decl));
7073           MARK_VISITED (DECL_SIZE_UNIT (gnu_decl));
7074           MARK_VISITED (DECL_INITIAL (gnu_decl));
7075         }
7076       /* In any case, we have to deal with our own TYPE_ADA_SIZE field.  */
7077       else if (TREE_CODE (gnu_decl) == TYPE_DECL
7078                && RECORD_OR_UNION_TYPE_P (type)
7079                && !TYPE_FAT_POINTER_P (type))
7080         MARK_VISITED (TYPE_ADA_SIZE (type));
7081     }
7082   else if (!DECL_EXTERNAL (gnu_decl))
7083     add_stmt_with_node (gnu_stmt, gnat_entity);
7084
7085   /* If this is a variable and an initializer is attached to it, it must be
7086      valid for the context.  Similar to init_const in create_var_decl_1.  */
7087   if (TREE_CODE (gnu_decl) == VAR_DECL
7088       && (gnu_init = DECL_INITIAL (gnu_decl)) != NULL_TREE
7089       && (!gnat_types_compatible_p (type, TREE_TYPE (gnu_init))
7090           || (TREE_STATIC (gnu_decl)
7091               && !initializer_constant_valid_p (gnu_init,
7092                                                 TREE_TYPE (gnu_init)))))
7093     {
7094       /* If GNU_DECL has a padded type, convert it to the unpadded
7095          type so the assignment is done properly.  */
7096       if (TYPE_IS_PADDING_P (type))
7097         t = convert (TREE_TYPE (TYPE_FIELDS (type)), gnu_decl);
7098       else
7099         t = gnu_decl;
7100
7101       gnu_stmt = build_binary_op (INIT_EXPR, NULL_TREE, t, gnu_init);
7102
7103       DECL_INITIAL (gnu_decl) = NULL_TREE;
7104       if (TREE_READONLY (gnu_decl))
7105         {
7106           TREE_READONLY (gnu_decl) = 0;
7107           DECL_READONLY_ONCE_ELAB (gnu_decl) = 1;
7108         }
7109
7110       add_stmt_with_node (gnu_stmt, gnat_entity);
7111     }
7112 }
7113
7114 /* Callback for walk_tree to mark the visited trees rooted at *TP.  */
7115
7116 static tree
7117 mark_visited_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
7118 {
7119   tree t = *tp;
7120
7121   if (TREE_VISITED (t))
7122     *walk_subtrees = 0;
7123
7124   /* Don't mark a dummy type as visited because we want to mark its sizes
7125      and fields once it's filled in.  */
7126   else if (!TYPE_IS_DUMMY_P (t))
7127     TREE_VISITED (t) = 1;
7128
7129   if (TYPE_P (t))
7130     TYPE_SIZES_GIMPLIFIED (t) = 1;
7131
7132   return NULL_TREE;
7133 }
7134
7135 /* Mark nodes rooted at T with TREE_VISITED and types as having their
7136    sized gimplified.  We use this to indicate all variable sizes and
7137    positions in global types may not be shared by any subprogram.  */
7138
7139 void
7140 mark_visited (tree t)
7141 {
7142   walk_tree (&t, mark_visited_r, NULL, NULL);
7143 }
7144
7145 /* Add GNU_CLEANUP, a cleanup action, to the current code group and
7146    set its location to that of GNAT_NODE if present.  */
7147
7148 static void
7149 add_cleanup (tree gnu_cleanup, Node_Id gnat_node)
7150 {
7151   if (Present (gnat_node))
7152     set_expr_location_from_node (gnu_cleanup, gnat_node);
7153   append_to_statement_list (gnu_cleanup, &current_stmt_group->cleanups);
7154 }
7155
7156 /* Set the BLOCK node corresponding to the current code group to GNU_BLOCK.  */
7157
7158 void
7159 set_block_for_group (tree gnu_block)
7160 {
7161   gcc_assert (!current_stmt_group->block);
7162   current_stmt_group->block = gnu_block;
7163 }
7164
7165 /* Return code corresponding to the current code group.  It is normally
7166    a STATEMENT_LIST, but may also be a BIND_EXPR or TRY_FINALLY_EXPR if
7167    BLOCK or cleanups were set.  */
7168
7169 tree
7170 end_stmt_group (void)
7171 {
7172   struct stmt_group *group = current_stmt_group;
7173   tree gnu_retval = group->stmt_list;
7174
7175   /* If this is a null list, allocate a new STATEMENT_LIST.  Then, if there
7176      are cleanups, make a TRY_FINALLY_EXPR.  Last, if there is a BLOCK,
7177      make a BIND_EXPR.  Note that we nest in that because the cleanup may
7178      reference variables in the block.  */
7179   if (gnu_retval == NULL_TREE)
7180     gnu_retval = alloc_stmt_list ();
7181
7182   if (group->cleanups)
7183     gnu_retval = build2 (TRY_FINALLY_EXPR, void_type_node, gnu_retval,
7184                          group->cleanups);
7185
7186   if (current_stmt_group->block)
7187     gnu_retval = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (group->block),
7188                          gnu_retval, group->block);
7189
7190   /* Remove this group from the stack and add it to the free list.  */
7191   current_stmt_group = group->previous;
7192   group->previous = stmt_group_free_list;
7193   stmt_group_free_list = group;
7194
7195   return gnu_retval;
7196 }
7197
7198 /* Add a list of statements from GNAT_LIST, a possibly-empty list of
7199    statements.*/
7200
7201 static void
7202 add_stmt_list (List_Id gnat_list)
7203 {
7204   Node_Id gnat_node;
7205
7206   if (Present (gnat_list))
7207     for (gnat_node = First (gnat_list); Present (gnat_node);
7208          gnat_node = Next (gnat_node))
7209       add_stmt (gnat_to_gnu (gnat_node));
7210 }
7211
7212 /* Build a tree from GNAT_LIST, a possibly-empty list of statements.
7213    If BINDING_P is true, push and pop a binding level around the list.  */
7214
7215 static tree
7216 build_stmt_group (List_Id gnat_list, bool binding_p)
7217 {
7218   start_stmt_group ();
7219   if (binding_p)
7220     gnat_pushlevel ();
7221
7222   add_stmt_list (gnat_list);
7223   if (binding_p)
7224     gnat_poplevel ();
7225
7226   return end_stmt_group ();
7227 }
7228 \f
7229 /* Generate GIMPLE in place for the expression at *EXPR_P.  */
7230
7231 int
7232 gnat_gimplify_expr (tree *expr_p, gimple_seq *pre_p,
7233                     gimple_seq *post_p ATTRIBUTE_UNUSED)
7234 {
7235   tree expr = *expr_p;
7236   tree op;
7237
7238   if (IS_ADA_STMT (expr))
7239     return gnat_gimplify_stmt (expr_p);
7240
7241   switch (TREE_CODE (expr))
7242     {
7243     case NULL_EXPR:
7244       /* If this is for a scalar, just make a VAR_DECL for it.  If for
7245          an aggregate, get a null pointer of the appropriate type and
7246          dereference it.  */
7247       if (AGGREGATE_TYPE_P (TREE_TYPE (expr)))
7248         *expr_p = build1 (INDIRECT_REF, TREE_TYPE (expr),
7249                           convert (build_pointer_type (TREE_TYPE (expr)),
7250                                    integer_zero_node));
7251       else
7252         {
7253           *expr_p = create_tmp_var (TREE_TYPE (expr), NULL);
7254           TREE_NO_WARNING (*expr_p) = 1;
7255         }
7256
7257       gimplify_and_add (TREE_OPERAND (expr, 0), pre_p);
7258       return GS_OK;
7259
7260     case UNCONSTRAINED_ARRAY_REF:
7261       /* We should only do this if we are just elaborating for side-effects,
7262          but we can't know that yet.  */
7263       *expr_p = TREE_OPERAND (*expr_p, 0);
7264       return GS_OK;
7265
7266     case ADDR_EXPR:
7267       op = TREE_OPERAND (expr, 0);
7268
7269       /* If we are taking the address of a constant CONSTRUCTOR, make sure it
7270          is put into static memory.  We know that it's going to be read-only
7271          given the semantics we have and it must be in static memory when the
7272          reference is in an elaboration procedure.  */
7273       if (TREE_CODE (op) == CONSTRUCTOR && TREE_CONSTANT (op))
7274         {
7275           tree addr = build_fold_addr_expr (tree_output_constant_def (op));
7276           *expr_p = fold_convert (TREE_TYPE (expr), addr);
7277           return GS_ALL_DONE;
7278         }
7279
7280       /* Otherwise, if we are taking the address of a non-constant CONSTRUCTOR
7281          or of a call, explicitly create the local temporary.  That's required
7282          if the type is passed by reference.  */
7283       if (TREE_CODE (op) == CONSTRUCTOR || TREE_CODE (op) == CALL_EXPR)
7284         {
7285           tree mod, new_var = create_tmp_var_raw (TREE_TYPE (op), "C");
7286           TREE_ADDRESSABLE (new_var) = 1;
7287           gimple_add_tmp_var (new_var);
7288
7289           mod = build2 (INIT_EXPR, TREE_TYPE (new_var), new_var, op);
7290           gimplify_and_add (mod, pre_p);
7291
7292           TREE_OPERAND (expr, 0) = new_var;
7293           recompute_tree_invariant_for_addr_expr (expr);
7294           return GS_ALL_DONE;
7295         }
7296
7297       return GS_UNHANDLED;
7298
7299     case VIEW_CONVERT_EXPR:
7300       op = TREE_OPERAND (expr, 0);
7301
7302       /* If we are view-converting a CONSTRUCTOR or a call from an aggregate
7303          type to a scalar one, explicitly create the local temporary.  That's
7304          required if the type is passed by reference.  */
7305       if ((TREE_CODE (op) == CONSTRUCTOR || TREE_CODE (op) == CALL_EXPR)
7306           && AGGREGATE_TYPE_P (TREE_TYPE (op))
7307           && !AGGREGATE_TYPE_P (TREE_TYPE (expr)))
7308         {
7309           tree mod, new_var = create_tmp_var_raw (TREE_TYPE (op), "C");
7310           gimple_add_tmp_var (new_var);
7311
7312           mod = build2 (INIT_EXPR, TREE_TYPE (new_var), new_var, op);
7313           gimplify_and_add (mod, pre_p);
7314
7315           TREE_OPERAND (expr, 0) = new_var;
7316           return GS_OK;
7317         }
7318
7319       return GS_UNHANDLED;
7320
7321     case DECL_EXPR:
7322       op = DECL_EXPR_DECL (expr);
7323
7324       /* The expressions for the RM bounds must be gimplified to ensure that
7325          they are properly elaborated.  See gimplify_decl_expr.  */
7326       if ((TREE_CODE (op) == TYPE_DECL || TREE_CODE (op) == VAR_DECL)
7327           && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (op)))
7328         switch (TREE_CODE (TREE_TYPE (op)))
7329           {
7330           case INTEGER_TYPE:
7331           case ENUMERAL_TYPE:
7332           case BOOLEAN_TYPE:
7333           case REAL_TYPE:
7334             {
7335               tree type = TYPE_MAIN_VARIANT (TREE_TYPE (op)), t, val;
7336
7337               val = TYPE_RM_MIN_VALUE (type);
7338               if (val)
7339                 {
7340                   gimplify_one_sizepos (&val, pre_p);
7341                   for (t = type; t; t = TYPE_NEXT_VARIANT (t))
7342                     SET_TYPE_RM_MIN_VALUE (t, val);
7343                 }
7344
7345               val = TYPE_RM_MAX_VALUE (type);
7346               if (val)
7347                 {
7348                   gimplify_one_sizepos (&val, pre_p);
7349                   for (t = type; t; t = TYPE_NEXT_VARIANT (t))
7350                     SET_TYPE_RM_MAX_VALUE (t, val);
7351                 }
7352
7353             }
7354             break;
7355
7356           default:
7357             break;
7358           }
7359
7360       /* ... fall through ... */
7361
7362     default:
7363       return GS_UNHANDLED;
7364     }
7365 }
7366
7367 /* Generate GIMPLE in place for the statement at *STMT_P.  */
7368
7369 static enum gimplify_status
7370 gnat_gimplify_stmt (tree *stmt_p)
7371 {
7372   tree stmt = *stmt_p;
7373
7374   switch (TREE_CODE (stmt))
7375     {
7376     case STMT_STMT:
7377       *stmt_p = STMT_STMT_STMT (stmt);
7378       return GS_OK;
7379
7380     case LOOP_STMT:
7381       {
7382         tree gnu_start_label = create_artificial_label (input_location);
7383         tree gnu_cond = LOOP_STMT_COND (stmt);
7384         tree gnu_update = LOOP_STMT_UPDATE (stmt);
7385         tree gnu_end_label = LOOP_STMT_LABEL (stmt);
7386         tree t;
7387
7388         /* Build the condition expression from the test, if any.  */
7389         if (gnu_cond)
7390           gnu_cond
7391             = build3 (COND_EXPR, void_type_node, gnu_cond, alloc_stmt_list (),
7392                       build1 (GOTO_EXPR, void_type_node, gnu_end_label));
7393
7394         /* Set to emit the statements of the loop.  */
7395         *stmt_p = NULL_TREE;
7396
7397         /* We first emit the start label and then a conditional jump to the
7398            end label if there's a top condition, then the update if it's at
7399            the top, then the body of the loop, then a conditional jump to
7400            the end label if there's a bottom condition, then the update if
7401            it's at the bottom, and finally a jump to the start label and the
7402            definition of the end label.  */
7403         append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
7404                                           gnu_start_label),
7405                                   stmt_p);
7406
7407         if (gnu_cond && !LOOP_STMT_BOTTOM_COND_P (stmt))
7408           append_to_statement_list (gnu_cond, stmt_p);
7409
7410         if (gnu_update && LOOP_STMT_TOP_UPDATE_P (stmt))
7411           append_to_statement_list (gnu_update, stmt_p);
7412
7413         append_to_statement_list (LOOP_STMT_BODY (stmt), stmt_p);
7414
7415         if (gnu_cond && LOOP_STMT_BOTTOM_COND_P (stmt))
7416           append_to_statement_list (gnu_cond, stmt_p);
7417
7418         if (gnu_update && !LOOP_STMT_TOP_UPDATE_P (stmt))
7419           append_to_statement_list (gnu_update, stmt_p);
7420
7421         t = build1 (GOTO_EXPR, void_type_node, gnu_start_label);
7422         SET_EXPR_LOCATION (t, DECL_SOURCE_LOCATION (gnu_end_label));
7423         append_to_statement_list (t, stmt_p);
7424
7425         append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
7426                                           gnu_end_label),
7427                                   stmt_p);
7428         return GS_OK;
7429       }
7430
7431     case EXIT_STMT:
7432       /* Build a statement to jump to the corresponding end label, then
7433          see if it needs to be conditional.  */
7434       *stmt_p = build1 (GOTO_EXPR, void_type_node, EXIT_STMT_LABEL (stmt));
7435       if (EXIT_STMT_COND (stmt))
7436         *stmt_p = build3 (COND_EXPR, void_type_node,
7437                           EXIT_STMT_COND (stmt), *stmt_p, alloc_stmt_list ());
7438       return GS_OK;
7439
7440     default:
7441       gcc_unreachable ();
7442     }
7443 }
7444 \f
7445 /* Force references to each of the entities in packages withed by GNAT_NODE.
7446    Operate recursively but check that we aren't elaborating something more
7447    than once.
7448
7449    This routine is exclusively called in type_annotate mode, to compute DDA
7450    information for types in withed units, for ASIS use.  */
7451
7452 static void
7453 elaborate_all_entities (Node_Id gnat_node)
7454 {
7455   Entity_Id gnat_with_clause, gnat_entity;
7456
7457   /* Process each unit only once.  As we trace the context of all relevant
7458      units transitively, including generic bodies, we may encounter the
7459      same generic unit repeatedly.  */
7460   if (!present_gnu_tree (gnat_node))
7461      save_gnu_tree (gnat_node, integer_zero_node, true);
7462
7463   /* Save entities in all context units.  A body may have an implicit_with
7464      on its own spec, if the context includes a child unit, so don't save
7465      the spec twice.  */
7466   for (gnat_with_clause = First (Context_Items (gnat_node));
7467        Present (gnat_with_clause);
7468        gnat_with_clause = Next (gnat_with_clause))
7469     if (Nkind (gnat_with_clause) == N_With_Clause
7470         && !present_gnu_tree (Library_Unit (gnat_with_clause))
7471         && Library_Unit (gnat_with_clause) != Library_Unit (Cunit (Main_Unit)))
7472       {
7473         elaborate_all_entities (Library_Unit (gnat_with_clause));
7474
7475         if (Ekind (Entity (Name (gnat_with_clause))) == E_Package)
7476           {
7477             for (gnat_entity = First_Entity (Entity (Name (gnat_with_clause)));
7478                  Present (gnat_entity);
7479                  gnat_entity = Next_Entity (gnat_entity))
7480               if (Is_Public (gnat_entity)
7481                   && Convention (gnat_entity) != Convention_Intrinsic
7482                   && Ekind (gnat_entity) != E_Package
7483                   && Ekind (gnat_entity) != E_Package_Body
7484                   && Ekind (gnat_entity) != E_Operator
7485                   && !(IN (Ekind (gnat_entity), Type_Kind)
7486                        && !Is_Frozen (gnat_entity))
7487                   && !((Ekind (gnat_entity) == E_Procedure
7488                         || Ekind (gnat_entity) == E_Function)
7489                        && Is_Intrinsic_Subprogram (gnat_entity))
7490                   && !IN (Ekind (gnat_entity), Named_Kind)
7491                   && !IN (Ekind (gnat_entity), Generic_Unit_Kind))
7492                 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
7493           }
7494         else if (Ekind (Entity (Name (gnat_with_clause))) == E_Generic_Package)
7495           {
7496             Node_Id gnat_body
7497               = Corresponding_Body (Unit (Library_Unit (gnat_with_clause)));
7498
7499             /* Retrieve compilation unit node of generic body.  */
7500             while (Present (gnat_body)
7501                    && Nkind (gnat_body) != N_Compilation_Unit)
7502               gnat_body = Parent (gnat_body);
7503
7504             /* If body is available, elaborate its context.  */
7505             if (Present (gnat_body))
7506               elaborate_all_entities (gnat_body);
7507           }
7508       }
7509
7510   if (Nkind (Unit (gnat_node)) == N_Package_Body)
7511     elaborate_all_entities (Library_Unit (gnat_node));
7512 }
7513 \f
7514 /* Do the processing of GNAT_NODE, an N_Freeze_Entity.  */
7515
7516 static void
7517 process_freeze_entity (Node_Id gnat_node)
7518 {
7519   const Entity_Id gnat_entity = Entity (gnat_node);
7520   const Entity_Kind kind = Ekind (gnat_entity);
7521   tree gnu_old, gnu_new;
7522
7523   /* If this is a package, we need to generate code for the package.  */
7524   if (kind == E_Package)
7525     {
7526       insert_code_for
7527         (Parent (Corresponding_Body
7528                  (Parent (Declaration_Node (gnat_entity)))));
7529       return;
7530     }
7531
7532   /* Don't do anything for class-wide types as they are always transformed
7533      into their root type.  */
7534   if (kind == E_Class_Wide_Type)
7535     return;
7536
7537   /* Check for an old definition.  This freeze node might be for an Itype.  */
7538   gnu_old
7539     = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : NULL_TREE;
7540
7541   /* If this entity has an address representation clause, GNU_OLD is the
7542      address, so discard it here.  */
7543   if (Present (Address_Clause (gnat_entity)))
7544     gnu_old = NULL_TREE;
7545
7546   /* Don't do anything for subprograms that may have been elaborated before
7547      their freeze nodes.  This can happen, for example, because of an inner
7548      call in an instance body or because of previous compilation of a spec
7549      for inlining purposes.  */
7550   if (gnu_old
7551       && ((TREE_CODE (gnu_old) == FUNCTION_DECL
7552            && (kind == E_Function || kind == E_Procedure))
7553           || (TREE_CODE (TREE_TYPE (gnu_old)) == FUNCTION_TYPE
7554               && kind == E_Subprogram_Type)))
7555     return;
7556
7557   /* If we have a non-dummy type old tree, we have nothing to do, except
7558      aborting if this is the public view of a private type whose full view was
7559      not delayed, as this node was never delayed as it should have been.  We
7560      let this happen for concurrent types and their Corresponding_Record_Type,
7561      however, because each might legitimately be elaborated before its own
7562      freeze node, e.g. while processing the other.  */
7563   if (gnu_old
7564       && !(TREE_CODE (gnu_old) == TYPE_DECL
7565            && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old))))
7566     {
7567       gcc_assert ((IN (kind, Incomplete_Or_Private_Kind)
7568                    && Present (Full_View (gnat_entity))
7569                    && No (Freeze_Node (Full_View (gnat_entity))))
7570                   || Is_Concurrent_Type (gnat_entity)
7571                   || (IN (kind, Record_Kind)
7572                       && Is_Concurrent_Record_Type (gnat_entity)));
7573       return;
7574     }
7575
7576   /* Reset the saved tree, if any, and elaborate the object or type for real.
7577      If there is a full view, elaborate it and use the result.  And, if this
7578      is the root type of a class-wide type, reuse it for the latter.  */
7579   if (gnu_old)
7580     {
7581       save_gnu_tree (gnat_entity, NULL_TREE, false);
7582       if (IN (kind, Incomplete_Or_Private_Kind)
7583           && Present (Full_View (gnat_entity))
7584           && present_gnu_tree (Full_View (gnat_entity)))
7585         save_gnu_tree (Full_View (gnat_entity), NULL_TREE, false);
7586       if (IN (kind, Type_Kind)
7587           && Present (Class_Wide_Type (gnat_entity))
7588           && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
7589         save_gnu_tree (Class_Wide_Type (gnat_entity), NULL_TREE, false);
7590     }
7591
7592   if (IN (kind, Incomplete_Or_Private_Kind)
7593       && Present (Full_View (gnat_entity)))
7594     {
7595       gnu_new = gnat_to_gnu_entity (Full_View (gnat_entity), NULL_TREE, 1);
7596
7597       /* Propagate back-annotations from full view to partial view.  */
7598       if (Unknown_Alignment (gnat_entity))
7599         Set_Alignment (gnat_entity, Alignment (Full_View (gnat_entity)));
7600
7601       if (Unknown_Esize (gnat_entity))
7602         Set_Esize (gnat_entity, Esize (Full_View (gnat_entity)));
7603
7604       if (Unknown_RM_Size (gnat_entity))
7605         Set_RM_Size (gnat_entity, RM_Size (Full_View (gnat_entity)));
7606
7607       /* The above call may have defined this entity (the simplest example
7608          of this is when we have a private enumeral type since the bounds
7609          will have the public view).  */
7610       if (!present_gnu_tree (gnat_entity))
7611         save_gnu_tree (gnat_entity, gnu_new, false);
7612     }
7613   else
7614     {
7615       tree gnu_init
7616         = (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration
7617            && present_gnu_tree (Declaration_Node (gnat_entity)))
7618           ? get_gnu_tree (Declaration_Node (gnat_entity)) : NULL_TREE;
7619
7620       gnu_new = gnat_to_gnu_entity (gnat_entity, gnu_init, 1);
7621     }
7622
7623   if (IN (kind, Type_Kind)
7624       && Present (Class_Wide_Type (gnat_entity))
7625       && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
7626     save_gnu_tree (Class_Wide_Type (gnat_entity), gnu_new, false);
7627
7628   /* If we have an old type and we've made pointers to this type, update those
7629      pointers.  If this is a Taft amendment type in the main unit, we need to
7630      mark the type as used since other units referencing it don't see the full
7631      declaration and, therefore, cannot mark it as used themselves.  */
7632   if (gnu_old)
7633     {
7634       update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
7635                          TREE_TYPE (gnu_new));
7636       if (DECL_TAFT_TYPE_P (gnu_old))
7637         used_types_insert (TREE_TYPE (gnu_new));
7638     }
7639 }
7640 \f
7641 /* Elaborate decls in the lists GNAT_DECLS and GNAT_DECLS2, if present.
7642    We make two passes, one to elaborate anything other than bodies (but
7643    we declare a function if there was no spec).  The second pass
7644    elaborates the bodies.
7645
7646    GNAT_END_LIST gives the element in the list past the end.  Normally,
7647    this is Empty, but can be First_Real_Statement for a
7648    Handled_Sequence_Of_Statements.
7649
7650    We make a complete pass through both lists if PASS1P is true, then make
7651    the second pass over both lists if PASS2P is true.  The lists usually
7652    correspond to the public and private parts of a package.  */
7653
7654 static void
7655 process_decls (List_Id gnat_decls, List_Id gnat_decls2,
7656                Node_Id gnat_end_list, bool pass1p, bool pass2p)
7657 {
7658   List_Id gnat_decl_array[2];
7659   Node_Id gnat_decl;
7660   int i;
7661
7662   gnat_decl_array[0] = gnat_decls, gnat_decl_array[1] = gnat_decls2;
7663
7664   if (pass1p)
7665     for (i = 0; i <= 1; i++)
7666       if (Present (gnat_decl_array[i]))
7667         for (gnat_decl = First (gnat_decl_array[i]);
7668              gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
7669           {
7670             /* For package specs, we recurse inside the declarations,
7671                thus taking the two pass approach inside the boundary.  */
7672             if (Nkind (gnat_decl) == N_Package_Declaration
7673                 && (Nkind (Specification (gnat_decl)
7674                            == N_Package_Specification)))
7675               process_decls (Visible_Declarations (Specification (gnat_decl)),
7676                              Private_Declarations (Specification (gnat_decl)),
7677                              Empty, true, false);
7678
7679             /* Similarly for any declarations in the actions of a
7680                freeze node.  */
7681             else if (Nkind (gnat_decl) == N_Freeze_Entity)
7682               {
7683                 process_freeze_entity (gnat_decl);
7684                 process_decls (Actions (gnat_decl), Empty, Empty, true, false);
7685               }
7686
7687             /* Package bodies with freeze nodes get their elaboration deferred
7688                until the freeze node, but the code must be placed in the right
7689                place, so record the code position now.  */
7690             else if (Nkind (gnat_decl) == N_Package_Body
7691                      && Present (Freeze_Node (Corresponding_Spec (gnat_decl))))
7692               record_code_position (gnat_decl);
7693
7694             else if (Nkind (gnat_decl) == N_Package_Body_Stub
7695                      && Present (Library_Unit (gnat_decl))
7696                      && Present (Freeze_Node
7697                                  (Corresponding_Spec
7698                                   (Proper_Body (Unit
7699                                                 (Library_Unit (gnat_decl)))))))
7700               record_code_position
7701                 (Proper_Body (Unit (Library_Unit (gnat_decl))));
7702
7703             /* We defer most subprogram bodies to the second pass.  */
7704             else if (Nkind (gnat_decl) == N_Subprogram_Body)
7705               {
7706                 if (Acts_As_Spec (gnat_decl))
7707                   {
7708                     Node_Id gnat_subprog_id = Defining_Entity (gnat_decl);
7709
7710                     if (Ekind (gnat_subprog_id) != E_Generic_Procedure
7711                         && Ekind (gnat_subprog_id) != E_Generic_Function)
7712                       gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
7713                   }
7714               }
7715
7716             /* For bodies and stubs that act as their own specs, the entity
7717                itself must be elaborated in the first pass, because it may
7718                be used in other declarations.  */
7719             else if (Nkind (gnat_decl) == N_Subprogram_Body_Stub)
7720               {
7721                 Node_Id gnat_subprog_id
7722                   = Defining_Entity (Specification (gnat_decl));
7723
7724                     if (Ekind (gnat_subprog_id) != E_Subprogram_Body
7725                         && Ekind (gnat_subprog_id) != E_Generic_Procedure
7726                         && Ekind (gnat_subprog_id) != E_Generic_Function)
7727                       gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
7728               }
7729
7730             /* Concurrent stubs stand for the corresponding subprogram bodies,
7731                which are deferred like other bodies.  */
7732             else if (Nkind (gnat_decl) == N_Task_Body_Stub
7733                      || Nkind (gnat_decl) == N_Protected_Body_Stub)
7734               ;
7735
7736             else
7737               add_stmt (gnat_to_gnu (gnat_decl));
7738           }
7739
7740   /* Here we elaborate everything we deferred above except for package bodies,
7741      which are elaborated at their freeze nodes.  Note that we must also
7742      go inside things (package specs and freeze nodes) the first pass did.  */
7743   if (pass2p)
7744     for (i = 0; i <= 1; i++)
7745       if (Present (gnat_decl_array[i]))
7746         for (gnat_decl = First (gnat_decl_array[i]);
7747              gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
7748           {
7749             if (Nkind (gnat_decl) == N_Subprogram_Body
7750                 || Nkind (gnat_decl) == N_Subprogram_Body_Stub
7751                 || Nkind (gnat_decl) == N_Task_Body_Stub
7752                 || Nkind (gnat_decl) == N_Protected_Body_Stub)
7753               add_stmt (gnat_to_gnu (gnat_decl));
7754
7755             else if (Nkind (gnat_decl) == N_Package_Declaration
7756                      && (Nkind (Specification (gnat_decl)
7757                                 == N_Package_Specification)))
7758               process_decls (Visible_Declarations (Specification (gnat_decl)),
7759                              Private_Declarations (Specification (gnat_decl)),
7760                              Empty, false, true);
7761
7762             else if (Nkind (gnat_decl) == N_Freeze_Entity)
7763               process_decls (Actions (gnat_decl), Empty, Empty, false, true);
7764           }
7765 }
7766 \f
7767 /* Make a unary operation of kind CODE using build_unary_op, but guard
7768    the operation by an overflow check.  CODE can be one of NEGATE_EXPR
7769    or ABS_EXPR.  GNU_TYPE is the type desired for the result.  Usually
7770    the operation is to be performed in that type.  GNAT_NODE is the gnat
7771    node conveying the source location for which the error should be
7772    signaled.  */
7773
7774 static tree
7775 build_unary_op_trapv (enum tree_code code, tree gnu_type, tree operand,
7776                       Node_Id gnat_node)
7777 {
7778   gcc_assert (code == NEGATE_EXPR || code == ABS_EXPR);
7779
7780   operand = gnat_protect_expr (operand);
7781
7782   return emit_check (build_binary_op (EQ_EXPR, boolean_type_node,
7783                                       operand, TYPE_MIN_VALUE (gnu_type)),
7784                      build_unary_op (code, gnu_type, operand),
7785                      CE_Overflow_Check_Failed, gnat_node);
7786 }
7787
7788 /* Make a binary operation of kind CODE using build_binary_op, but guard
7789    the operation by an overflow check.  CODE can be one of PLUS_EXPR,
7790    MINUS_EXPR or MULT_EXPR.  GNU_TYPE is the type desired for the result.
7791    Usually the operation is to be performed in that type.  GNAT_NODE is
7792    the GNAT node conveying the source location for which the error should
7793    be signaled.  */
7794
7795 static tree
7796 build_binary_op_trapv (enum tree_code code, tree gnu_type, tree left,
7797                        tree right, Node_Id gnat_node)
7798 {
7799   tree lhs = gnat_protect_expr (left);
7800   tree rhs = gnat_protect_expr (right);
7801   tree type_max = TYPE_MAX_VALUE (gnu_type);
7802   tree type_min = TYPE_MIN_VALUE (gnu_type);
7803   tree gnu_expr;
7804   tree tmp1, tmp2;
7805   tree zero = convert (gnu_type, integer_zero_node);
7806   tree rhs_lt_zero;
7807   tree check_pos;
7808   tree check_neg;
7809   tree check;
7810   int precision = TYPE_PRECISION (gnu_type);
7811
7812   gcc_assert (!(precision & (precision - 1))); /* ensure power of 2 */
7813
7814   /* Prefer a constant or known-positive rhs to simplify checks.  */
7815   if (!TREE_CONSTANT (rhs)
7816       && commutative_tree_code (code)
7817       && (TREE_CONSTANT (lhs) || (!tree_expr_nonnegative_p (rhs)
7818                                   && tree_expr_nonnegative_p (lhs))))
7819     {
7820       tree tmp = lhs;
7821       lhs = rhs;
7822       rhs = tmp;
7823     }
7824
7825   rhs_lt_zero = tree_expr_nonnegative_p (rhs)
7826                 ? boolean_false_node
7827                 : build_binary_op (LT_EXPR, boolean_type_node, rhs, zero);
7828
7829   /* ??? Should use more efficient check for operand_equal_p (lhs, rhs, 0) */
7830
7831   /* Try a few strategies that may be cheaper than the general
7832      code at the end of the function, if the rhs is not known.
7833      The strategies are:
7834        - Call library function for 64-bit multiplication (complex)
7835        - Widen, if input arguments are sufficiently small
7836        - Determine overflow using wrapped result for addition/subtraction.  */
7837
7838   if (!TREE_CONSTANT (rhs))
7839     {
7840       /* Even for add/subtract double size to get another base type.  */
7841       int needed_precision = precision * 2;
7842
7843       if (code == MULT_EXPR && precision == 64)
7844         {
7845           tree int_64 = gnat_type_for_size (64, 0);
7846
7847           return convert (gnu_type, build_call_n_expr (mulv64_decl, 2,
7848                                                        convert (int_64, lhs),
7849                                                        convert (int_64, rhs)));
7850         }
7851
7852       else if (needed_precision <= BITS_PER_WORD
7853                || (code == MULT_EXPR
7854                    && needed_precision <= LONG_LONG_TYPE_SIZE))
7855         {
7856           tree wide_type = gnat_type_for_size (needed_precision, 0);
7857
7858           tree wide_result = build_binary_op (code, wide_type,
7859                                               convert (wide_type, lhs),
7860                                               convert (wide_type, rhs));
7861
7862           tree check = build_binary_op
7863             (TRUTH_ORIF_EXPR, boolean_type_node,
7864              build_binary_op (LT_EXPR, boolean_type_node, wide_result,
7865                               convert (wide_type, type_min)),
7866              build_binary_op (GT_EXPR, boolean_type_node, wide_result,
7867                               convert (wide_type, type_max)));
7868
7869           tree result = convert (gnu_type, wide_result);
7870
7871           return
7872             emit_check (check, result, CE_Overflow_Check_Failed, gnat_node);
7873         }
7874
7875       else if (code == PLUS_EXPR || code == MINUS_EXPR)
7876         {
7877           tree unsigned_type = gnat_type_for_size (precision, 1);
7878           tree wrapped_expr = convert
7879             (gnu_type, build_binary_op (code, unsigned_type,
7880                                         convert (unsigned_type, lhs),
7881                                         convert (unsigned_type, rhs)));
7882
7883           tree result = convert
7884             (gnu_type, build_binary_op (code, gnu_type, lhs, rhs));
7885
7886           /* Overflow when (rhs < 0) ^ (wrapped_expr < lhs)), for addition
7887              or when (rhs < 0) ^ (wrapped_expr > lhs) for subtraction.  */
7888           tree check = build_binary_op
7889             (TRUTH_XOR_EXPR, boolean_type_node, rhs_lt_zero,
7890              build_binary_op (code == PLUS_EXPR ? LT_EXPR : GT_EXPR,
7891                               boolean_type_node, wrapped_expr, lhs));
7892
7893           return
7894             emit_check (check, result, CE_Overflow_Check_Failed, gnat_node);
7895         }
7896    }
7897
7898   switch (code)
7899     {
7900     case PLUS_EXPR:
7901       /* When rhs >= 0, overflow when lhs > type_max - rhs.  */
7902       check_pos = build_binary_op (GT_EXPR, boolean_type_node, lhs,
7903                                    build_binary_op (MINUS_EXPR, gnu_type,
7904                                                     type_max, rhs)),
7905
7906       /* When rhs < 0, overflow when lhs < type_min - rhs.  */
7907       check_neg = build_binary_op (LT_EXPR, boolean_type_node, lhs,
7908                                    build_binary_op (MINUS_EXPR, gnu_type,
7909                                                     type_min, rhs));
7910       break;
7911
7912     case MINUS_EXPR:
7913       /* When rhs >= 0, overflow when lhs < type_min + rhs.  */
7914       check_pos = build_binary_op (LT_EXPR, boolean_type_node, lhs,
7915                                    build_binary_op (PLUS_EXPR, gnu_type,
7916                                                     type_min, rhs)),
7917
7918       /* When rhs < 0, overflow when lhs > type_max + rhs.  */
7919       check_neg = build_binary_op (GT_EXPR, boolean_type_node, lhs,
7920                                    build_binary_op (PLUS_EXPR, gnu_type,
7921                                                     type_max, rhs));
7922       break;
7923
7924     case MULT_EXPR:
7925       /* The check here is designed to be efficient if the rhs is constant,
7926          but it will work for any rhs by using integer division.
7927          Four different check expressions determine whether X * C overflows,
7928          depending on C.
7929            C ==  0  =>  false
7930            C  >  0  =>  X > type_max / C || X < type_min / C
7931            C == -1  =>  X == type_min
7932            C  < -1  =>  X > type_min / C || X < type_max / C */
7933
7934       tmp1 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
7935       tmp2 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
7936
7937       check_pos
7938         = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
7939                            build_binary_op (NE_EXPR, boolean_type_node, zero,
7940                                             rhs),
7941                            build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
7942                                             build_binary_op (GT_EXPR,
7943                                                              boolean_type_node,
7944                                                              lhs, tmp1),
7945                                             build_binary_op (LT_EXPR,
7946                                                              boolean_type_node,
7947                                                              lhs, tmp2)));
7948
7949       check_neg
7950         = fold_build3 (COND_EXPR, boolean_type_node,
7951                        build_binary_op (EQ_EXPR, boolean_type_node, rhs,
7952                                         build_int_cst (gnu_type, -1)),
7953                        build_binary_op (EQ_EXPR, boolean_type_node, lhs,
7954                                         type_min),
7955                        build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
7956                                         build_binary_op (GT_EXPR,
7957                                                          boolean_type_node,
7958                                                          lhs, tmp2),
7959                                         build_binary_op (LT_EXPR,
7960                                                          boolean_type_node,
7961                                                          lhs, tmp1)));
7962       break;
7963
7964     default:
7965       gcc_unreachable();
7966     }
7967
7968   gnu_expr = build_binary_op (code, gnu_type, lhs, rhs);
7969
7970   /* If we can fold the expression to a constant, just return it.
7971      The caller will deal with overflow, no need to generate a check.  */
7972   if (TREE_CONSTANT (gnu_expr))
7973     return gnu_expr;
7974
7975   check = fold_build3 (COND_EXPR, boolean_type_node, rhs_lt_zero, check_neg,
7976                        check_pos);
7977
7978   return emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
7979 }
7980
7981 /* Emit code for a range check.  GNU_EXPR is the expression to be checked,
7982    GNAT_RANGE_TYPE the gnat type or subtype containing the bounds against
7983    which we have to check.  GNAT_NODE is the GNAT node conveying the source
7984    location for which the error should be signaled.  */
7985
7986 static tree
7987 emit_range_check (tree gnu_expr, Entity_Id gnat_range_type, Node_Id gnat_node)
7988 {
7989   tree gnu_range_type = get_unpadded_type (gnat_range_type);
7990   tree gnu_low  = TYPE_MIN_VALUE (gnu_range_type);
7991   tree gnu_high = TYPE_MAX_VALUE (gnu_range_type);
7992   tree gnu_compare_type = get_base_type (TREE_TYPE (gnu_expr));
7993
7994   /* If GNU_EXPR has GNAT_RANGE_TYPE as its base type, no check is needed.
7995      This can for example happen when translating 'Val or 'Value.  */
7996   if (gnu_compare_type == gnu_range_type)
7997     return gnu_expr;
7998
7999   /* If GNU_EXPR has an integral type that is narrower than GNU_RANGE_TYPE,
8000      we can't do anything since we might be truncating the bounds.  No
8001      check is needed in this case.  */
8002   if (INTEGRAL_TYPE_P (TREE_TYPE (gnu_expr))
8003       && (TYPE_PRECISION (gnu_compare_type)
8004           < TYPE_PRECISION (get_base_type (gnu_range_type))))
8005     return gnu_expr;
8006
8007   /* Checked expressions must be evaluated only once.  */
8008   gnu_expr = gnat_protect_expr (gnu_expr);
8009
8010   /* Note that the form of the check is
8011         (not (expr >= lo)) or (not (expr <= hi))
8012      the reason for this slightly convoluted form is that NaNs
8013      are not considered to be in range in the float case.  */
8014   return emit_check
8015     (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8016                       invert_truthvalue
8017                       (build_binary_op (GE_EXPR, boolean_type_node,
8018                                        convert (gnu_compare_type, gnu_expr),
8019                                        convert (gnu_compare_type, gnu_low))),
8020                       invert_truthvalue
8021                       (build_binary_op (LE_EXPR, boolean_type_node,
8022                                         convert (gnu_compare_type, gnu_expr),
8023                                         convert (gnu_compare_type,
8024                                                  gnu_high)))),
8025      gnu_expr, CE_Range_Check_Failed, gnat_node);
8026 }
8027 \f
8028 /* Emit code for an index check.  GNU_ARRAY_OBJECT is the array object which
8029    we are about to index, GNU_EXPR is the index expression to be checked,
8030    GNU_LOW and GNU_HIGH are the lower and upper bounds against which GNU_EXPR
8031    has to be checked.  Note that for index checking we cannot simply use the
8032    emit_range_check function (although very similar code needs to be generated
8033    in both cases) since for index checking the array type against which we are
8034    checking the indices may be unconstrained and consequently we need to get
8035    the actual index bounds from the array object itself (GNU_ARRAY_OBJECT).
8036    The place where we need to do that is in subprograms having unconstrained
8037    array formal parameters.  GNAT_NODE is the GNAT node conveying the source
8038    location for which the error should be signaled.  */
8039
8040 static tree
8041 emit_index_check (tree gnu_array_object, tree gnu_expr, tree gnu_low,
8042                   tree gnu_high, Node_Id gnat_node)
8043 {
8044   tree gnu_expr_check;
8045
8046   /* Checked expressions must be evaluated only once.  */
8047   gnu_expr = gnat_protect_expr (gnu_expr);
8048
8049   /* Must do this computation in the base type in case the expression's
8050      type is an unsigned subtypes.  */
8051   gnu_expr_check = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
8052
8053   /* If GNU_LOW or GNU_HIGH are a PLACEHOLDER_EXPR, qualify them by
8054      the object we are handling.  */
8055   gnu_low = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_low, gnu_array_object);
8056   gnu_high = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_high, gnu_array_object);
8057
8058   return emit_check
8059     (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8060                       build_binary_op (LT_EXPR, boolean_type_node,
8061                                        gnu_expr_check,
8062                                        convert (TREE_TYPE (gnu_expr_check),
8063                                                 gnu_low)),
8064                       build_binary_op (GT_EXPR, boolean_type_node,
8065                                        gnu_expr_check,
8066                                        convert (TREE_TYPE (gnu_expr_check),
8067                                                 gnu_high))),
8068      gnu_expr, CE_Index_Check_Failed, gnat_node);
8069 }
8070 \f
8071 /* GNU_COND contains the condition corresponding to an access, discriminant or
8072    range check of value GNU_EXPR.  Build a COND_EXPR that returns GNU_EXPR if
8073    GNU_COND is false and raises a CONSTRAINT_ERROR if GNU_COND is true.
8074    REASON is the code that says why the exception was raised.  GNAT_NODE is
8075    the GNAT node conveying the source location for which the error should be
8076    signaled.  */
8077
8078 static tree
8079 emit_check (tree gnu_cond, tree gnu_expr, int reason, Node_Id gnat_node)
8080 {
8081   tree gnu_call
8082     = build_call_raise (reason, gnat_node, N_Raise_Constraint_Error);
8083   tree gnu_result
8084     = fold_build3 (COND_EXPR, TREE_TYPE (gnu_expr), gnu_cond,
8085                    build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr), gnu_call,
8086                            convert (TREE_TYPE (gnu_expr), integer_zero_node)),
8087                    gnu_expr);
8088
8089   /* GNU_RESULT has side effects if and only if GNU_EXPR has:
8090      we don't need to evaluate it just for the check.  */
8091   TREE_SIDE_EFFECTS (gnu_result) = TREE_SIDE_EFFECTS (gnu_expr);
8092
8093   return gnu_result;
8094 }
8095 \f
8096 /* Return an expression that converts GNU_EXPR to GNAT_TYPE, doing overflow
8097    checks if OVERFLOW_P is true and range checks if RANGE_P is true.
8098    GNAT_TYPE is known to be an integral type.  If TRUNCATE_P true, do a
8099    float to integer conversion with truncation; otherwise round.
8100    GNAT_NODE is the GNAT node conveying the source location for which the
8101    error should be signaled.  */
8102
8103 static tree
8104 convert_with_check (Entity_Id gnat_type, tree gnu_expr, bool overflowp,
8105                     bool rangep, bool truncatep, Node_Id gnat_node)
8106 {
8107   tree gnu_type = get_unpadded_type (gnat_type);
8108   tree gnu_in_type = TREE_TYPE (gnu_expr);
8109   tree gnu_in_basetype = get_base_type (gnu_in_type);
8110   tree gnu_base_type = get_base_type (gnu_type);
8111   tree gnu_result = gnu_expr;
8112
8113   /* If we are not doing any checks, the output is an integral type, and
8114      the input is not a floating type, just do the conversion.  This
8115      shortcut is required to avoid problems with packed array types
8116      and simplifies code in all cases anyway.   */
8117   if (!rangep && !overflowp && INTEGRAL_TYPE_P (gnu_base_type)
8118       && !FLOAT_TYPE_P (gnu_in_type))
8119     return convert (gnu_type, gnu_expr);
8120
8121   /* First convert the expression to its base type.  This
8122      will never generate code, but makes the tests below much simpler.
8123      But don't do this if converting from an integer type to an unconstrained
8124      array type since then we need to get the bounds from the original
8125      (unpacked) type.  */
8126   if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
8127     gnu_result = convert (gnu_in_basetype, gnu_result);
8128
8129   /* If overflow checks are requested,  we need to be sure the result will
8130      fit in the output base type.  But don't do this if the input
8131      is integer and the output floating-point.  */
8132   if (overflowp
8133       && !(FLOAT_TYPE_P (gnu_base_type) && INTEGRAL_TYPE_P (gnu_in_basetype)))
8134     {
8135       /* Ensure GNU_EXPR only gets evaluated once.  */
8136       tree gnu_input = gnat_protect_expr (gnu_result);
8137       tree gnu_cond = boolean_false_node;
8138       tree gnu_in_lb = TYPE_MIN_VALUE (gnu_in_basetype);
8139       tree gnu_in_ub = TYPE_MAX_VALUE (gnu_in_basetype);
8140       tree gnu_out_lb = TYPE_MIN_VALUE (gnu_base_type);
8141       tree gnu_out_ub = TYPE_MAX_VALUE (gnu_base_type);
8142
8143       /* Convert the lower bounds to signed types, so we're sure we're
8144          comparing them properly.  Likewise, convert the upper bounds
8145          to unsigned types.  */
8146       if (INTEGRAL_TYPE_P (gnu_in_basetype) && TYPE_UNSIGNED (gnu_in_basetype))
8147         gnu_in_lb = convert (gnat_signed_type (gnu_in_basetype), gnu_in_lb);
8148
8149       if (INTEGRAL_TYPE_P (gnu_in_basetype)
8150           && !TYPE_UNSIGNED (gnu_in_basetype))
8151         gnu_in_ub = convert (gnat_unsigned_type (gnu_in_basetype), gnu_in_ub);
8152
8153       if (INTEGRAL_TYPE_P (gnu_base_type) && TYPE_UNSIGNED (gnu_base_type))
8154         gnu_out_lb = convert (gnat_signed_type (gnu_base_type), gnu_out_lb);
8155
8156       if (INTEGRAL_TYPE_P (gnu_base_type) && !TYPE_UNSIGNED (gnu_base_type))
8157         gnu_out_ub = convert (gnat_unsigned_type (gnu_base_type), gnu_out_ub);
8158
8159       /* Check each bound separately and only if the result bound
8160          is tighter than the bound on the input type.  Note that all the
8161          types are base types, so the bounds must be constant. Also,
8162          the comparison is done in the base type of the input, which
8163          always has the proper signedness.  First check for input
8164          integer (which means output integer), output float (which means
8165          both float), or mixed, in which case we always compare.
8166          Note that we have to do the comparison which would *fail* in the
8167          case of an error since if it's an FP comparison and one of the
8168          values is a NaN or Inf, the comparison will fail.  */
8169       if (INTEGRAL_TYPE_P (gnu_in_basetype)
8170           ? tree_int_cst_lt (gnu_in_lb, gnu_out_lb)
8171           : (FLOAT_TYPE_P (gnu_base_type)
8172              ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_in_lb),
8173                                  TREE_REAL_CST (gnu_out_lb))
8174              : 1))
8175         gnu_cond
8176           = invert_truthvalue
8177             (build_binary_op (GE_EXPR, boolean_type_node,
8178                               gnu_input, convert (gnu_in_basetype,
8179                                                   gnu_out_lb)));
8180
8181       if (INTEGRAL_TYPE_P (gnu_in_basetype)
8182           ? tree_int_cst_lt (gnu_out_ub, gnu_in_ub)
8183           : (FLOAT_TYPE_P (gnu_base_type)
8184              ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_out_ub),
8185                                  TREE_REAL_CST (gnu_in_lb))
8186              : 1))
8187         gnu_cond
8188           = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, gnu_cond,
8189                              invert_truthvalue
8190                              (build_binary_op (LE_EXPR, boolean_type_node,
8191                                                gnu_input,
8192                                                convert (gnu_in_basetype,
8193                                                         gnu_out_ub))));
8194
8195       if (!integer_zerop (gnu_cond))
8196         gnu_result = emit_check (gnu_cond, gnu_input,
8197                                  CE_Overflow_Check_Failed, gnat_node);
8198     }
8199
8200   /* Now convert to the result base type.  If this is a non-truncating
8201      float-to-integer conversion, round.  */
8202   if (INTEGRAL_TYPE_P (gnu_base_type) && FLOAT_TYPE_P (gnu_in_basetype)
8203       && !truncatep)
8204     {
8205       REAL_VALUE_TYPE half_minus_pred_half, pred_half;
8206       tree gnu_conv, gnu_zero, gnu_comp, calc_type;
8207       tree gnu_pred_half, gnu_add_pred_half, gnu_subtract_pred_half;
8208       const struct real_format *fmt;
8209
8210       /* The following calculations depend on proper rounding to even
8211          of each arithmetic operation. In order to prevent excess
8212          precision from spoiling this property, use the widest hardware
8213          floating-point type if FP_ARITH_MAY_WIDEN is true.  */
8214       calc_type
8215         = FP_ARITH_MAY_WIDEN ? longest_float_type_node : gnu_in_basetype;
8216
8217       /* FIXME: Should not have padding in the first place.  */
8218       if (TYPE_IS_PADDING_P (calc_type))
8219         calc_type = TREE_TYPE (TYPE_FIELDS (calc_type));
8220
8221       /* Compute the exact value calc_type'Pred (0.5) at compile time.  */
8222       fmt = REAL_MODE_FORMAT (TYPE_MODE (calc_type));
8223       real_2expN (&half_minus_pred_half, -(fmt->p) - 1, TYPE_MODE (calc_type));
8224       REAL_ARITHMETIC (pred_half, MINUS_EXPR, dconsthalf,
8225                        half_minus_pred_half);
8226       gnu_pred_half = build_real (calc_type, pred_half);
8227
8228       /* If the input is strictly negative, subtract this value
8229          and otherwise add it from the input.  For 0.5, the result
8230          is exactly between 1.0 and the machine number preceding 1.0
8231          (for calc_type).  Since the last bit of 1.0 is even, this 0.5
8232          will round to 1.0, while all other number with an absolute
8233          value less than 0.5 round to 0.0.  For larger numbers exactly
8234          halfway between integers, rounding will always be correct as
8235          the true mathematical result will be closer to the higher
8236          integer compared to the lower one.  So, this constant works
8237          for all floating-point numbers.
8238
8239          The reason to use the same constant with subtract/add instead
8240          of a positive and negative constant is to allow the comparison
8241          to be scheduled in parallel with retrieval of the constant and
8242          conversion of the input to the calc_type (if necessary).  */
8243
8244       gnu_zero = convert (gnu_in_basetype, integer_zero_node);
8245       gnu_result = gnat_protect_expr (gnu_result);
8246       gnu_conv = convert (calc_type, gnu_result);
8247       gnu_comp
8248         = fold_build2 (GE_EXPR, boolean_type_node, gnu_result, gnu_zero);
8249       gnu_add_pred_half
8250         = fold_build2 (PLUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
8251       gnu_subtract_pred_half
8252         = fold_build2 (MINUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
8253       gnu_result = fold_build3 (COND_EXPR, calc_type, gnu_comp,
8254                                 gnu_add_pred_half, gnu_subtract_pred_half);
8255     }
8256
8257   if (TREE_CODE (gnu_base_type) == INTEGER_TYPE
8258       && TYPE_HAS_ACTUAL_BOUNDS_P (gnu_base_type)
8259       && TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
8260     gnu_result = unchecked_convert (gnu_base_type, gnu_result, false);
8261   else
8262     gnu_result = convert (gnu_base_type, gnu_result);
8263
8264   /* Finally, do the range check if requested.  Note that if the result type
8265      is a modular type, the range check is actually an overflow check.  */
8266   if (rangep
8267       || (TREE_CODE (gnu_base_type) == INTEGER_TYPE
8268           && TYPE_MODULAR_P (gnu_base_type) && overflowp))
8269     gnu_result = emit_range_check (gnu_result, gnat_type, gnat_node);
8270
8271   return convert (gnu_type, gnu_result);
8272 }
8273 \f
8274 /* Return true if GNU_EXPR can be directly addressed.  This is the case
8275    unless it is an expression involving computation or if it involves a
8276    reference to a bitfield or to an object not sufficiently aligned for
8277    its type.  If GNU_TYPE is non-null, return true only if GNU_EXPR can
8278    be directly addressed as an object of this type.
8279
8280    *** Notes on addressability issues in the Ada compiler ***
8281
8282    This predicate is necessary in order to bridge the gap between Gigi
8283    and the middle-end about addressability of GENERIC trees.  A tree
8284    is said to be addressable if it can be directly addressed, i.e. if
8285    its address can be taken, is a multiple of the type's alignment on
8286    strict-alignment architectures and returns the first storage unit
8287    assigned to the object represented by the tree.
8288
8289    In the C family of languages, everything is in practice addressable
8290    at the language level, except for bit-fields.  This means that these
8291    compilers will take the address of any tree that doesn't represent
8292    a bit-field reference and expect the result to be the first storage
8293    unit assigned to the object.  Even in cases where this will result
8294    in unaligned accesses at run time, nothing is supposed to be done
8295    and the program is considered as erroneous instead (see PR c/18287).
8296
8297    The implicit assumptions made in the middle-end are in keeping with
8298    the C viewpoint described above:
8299      - the address of a bit-field reference is supposed to be never
8300        taken; the compiler (generally) will stop on such a construct,
8301      - any other tree is addressable if it is formally addressable,
8302        i.e. if it is formally allowed to be the operand of ADDR_EXPR.
8303
8304    In Ada, the viewpoint is the opposite one: nothing is addressable
8305    at the language level unless explicitly declared so.  This means
8306    that the compiler will both make sure that the trees representing
8307    references to addressable ("aliased" in Ada parlance) objects are
8308    addressable and make no real attempts at ensuring that the trees
8309    representing references to non-addressable objects are addressable.
8310
8311    In the first case, Ada is effectively equivalent to C and handing
8312    down the direct result of applying ADDR_EXPR to these trees to the
8313    middle-end works flawlessly.  In the second case, Ada cannot afford
8314    to consider the program as erroneous if the address of trees that
8315    are not addressable is requested for technical reasons, unlike C;
8316    as a consequence, the Ada compiler must arrange for either making
8317    sure that this address is not requested in the middle-end or for
8318    compensating by inserting temporaries if it is requested in Gigi.
8319
8320    The first goal can be achieved because the middle-end should not
8321    request the address of non-addressable trees on its own; the only
8322    exception is for the invocation of low-level block operations like
8323    memcpy, for which the addressability requirements are lower since
8324    the type's alignment can be disregarded.  In practice, this means
8325    that Gigi must make sure that such operations cannot be applied to
8326    non-BLKmode bit-fields.
8327
8328    The second goal is achieved by means of the addressable_p predicate,
8329    which computes whether a temporary must be inserted by Gigi when the
8330    address of a tree is requested; if so, the address of the temporary
8331    will be used in lieu of that of the original tree and some glue code
8332    generated to connect everything together.  */
8333
8334 static bool
8335 addressable_p (tree gnu_expr, tree gnu_type)
8336 {
8337   /* For an integral type, the size of the actual type of the object may not
8338      be greater than that of the expected type, otherwise an indirect access
8339      in the latter type wouldn't correctly set all the bits of the object.  */
8340   if (gnu_type
8341       && INTEGRAL_TYPE_P (gnu_type)
8342       && smaller_form_type_p (gnu_type, TREE_TYPE (gnu_expr)))
8343     return false;
8344
8345   /* The size of the actual type of the object may not be smaller than that
8346      of the expected type, otherwise an indirect access in the latter type
8347      would be larger than the object.  But only record types need to be
8348      considered in practice for this case.  */
8349   if (gnu_type
8350       && TREE_CODE (gnu_type) == RECORD_TYPE
8351       && smaller_form_type_p (TREE_TYPE (gnu_expr), gnu_type))
8352     return false;
8353
8354   switch (TREE_CODE (gnu_expr))
8355     {
8356     case VAR_DECL:
8357     case PARM_DECL:
8358     case FUNCTION_DECL:
8359     case RESULT_DECL:
8360       /* All DECLs are addressable: if they are in a register, we can force
8361          them to memory.  */
8362       return true;
8363
8364     case UNCONSTRAINED_ARRAY_REF:
8365     case INDIRECT_REF:
8366       /* Taking the address of a dereference yields the original pointer.  */
8367       return true;
8368
8369     case STRING_CST:
8370     case INTEGER_CST:
8371       /* Taking the address yields a pointer to the constant pool.  */
8372       return true;
8373
8374     case CONSTRUCTOR:
8375       /* Taking the address of a static constructor yields a pointer to the
8376          tree constant pool.  */
8377       return TREE_STATIC (gnu_expr) ? true : false;
8378
8379     case NULL_EXPR:
8380     case SAVE_EXPR:
8381     case CALL_EXPR:
8382     case PLUS_EXPR:
8383     case MINUS_EXPR:
8384     case BIT_IOR_EXPR:
8385     case BIT_XOR_EXPR:
8386     case BIT_AND_EXPR:
8387     case BIT_NOT_EXPR:
8388       /* All rvalues are deemed addressable since taking their address will
8389          force a temporary to be created by the middle-end.  */
8390       return true;
8391
8392     case COMPOUND_EXPR:
8393       /* The address of a compound expression is that of its 2nd operand.  */
8394       return addressable_p (TREE_OPERAND (gnu_expr, 1), gnu_type);
8395
8396     case COND_EXPR:
8397       /* We accept &COND_EXPR as soon as both operands are addressable and
8398          expect the outcome to be the address of the selected operand.  */
8399       return (addressable_p (TREE_OPERAND (gnu_expr, 1), NULL_TREE)
8400               && addressable_p (TREE_OPERAND (gnu_expr, 2), NULL_TREE));
8401
8402     case COMPONENT_REF:
8403       return (((!DECL_BIT_FIELD (TREE_OPERAND (gnu_expr, 1))
8404                 /* Even with DECL_BIT_FIELD cleared, we have to ensure that
8405                    the field is sufficiently aligned, in case it is subject
8406                    to a pragma Component_Alignment.  But we don't need to
8407                    check the alignment of the containing record, as it is
8408                    guaranteed to be not smaller than that of its most
8409                    aligned field that is not a bit-field.  */
8410                 && (!STRICT_ALIGNMENT
8411                     || DECL_ALIGN (TREE_OPERAND (gnu_expr, 1))
8412                        >= TYPE_ALIGN (TREE_TYPE (gnu_expr))))
8413                /* The field of a padding record is always addressable.  */
8414                || TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
8415               && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8416
8417     case ARRAY_REF:  case ARRAY_RANGE_REF:
8418     case REALPART_EXPR:  case IMAGPART_EXPR:
8419     case NOP_EXPR:
8420       return addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE);
8421
8422     case CONVERT_EXPR:
8423       return (AGGREGATE_TYPE_P (TREE_TYPE (gnu_expr))
8424               && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8425
8426     case VIEW_CONVERT_EXPR:
8427       {
8428         /* This is addressable if we can avoid a copy.  */
8429         tree type = TREE_TYPE (gnu_expr);
8430         tree inner_type = TREE_TYPE (TREE_OPERAND (gnu_expr, 0));
8431         return (((TYPE_MODE (type) == TYPE_MODE (inner_type)
8432                   && (!STRICT_ALIGNMENT
8433                       || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
8434                       || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT))
8435                  || ((TYPE_MODE (type) == BLKmode
8436                       || TYPE_MODE (inner_type) == BLKmode)
8437                      && (!STRICT_ALIGNMENT
8438                          || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
8439                          || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT
8440                          || TYPE_ALIGN_OK (type)
8441                          || TYPE_ALIGN_OK (inner_type))))
8442                 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8443       }
8444
8445     default:
8446       return false;
8447     }
8448 }
8449 \f
8450 /* Do the processing for the declaration of a GNAT_ENTITY, a type.  If
8451    a separate Freeze node exists, delay the bulk of the processing.  Otherwise
8452    make a GCC type for GNAT_ENTITY and set up the correspondence.  */
8453
8454 void
8455 process_type (Entity_Id gnat_entity)
8456 {
8457   tree gnu_old
8458     = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : 0;
8459   tree gnu_new;
8460
8461   /* If we are to delay elaboration of this type, just do any
8462      elaborations needed for expressions within the declaration and
8463      make a dummy type entry for this node and its Full_View (if
8464      any) in case something points to it.  Don't do this if it
8465      has already been done (the only way that can happen is if
8466      the private completion is also delayed).  */
8467   if (Present (Freeze_Node (gnat_entity))
8468       || (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
8469           && Present (Full_View (gnat_entity))
8470           && Freeze_Node (Full_View (gnat_entity))
8471           && !present_gnu_tree (Full_View (gnat_entity))))
8472     {
8473       elaborate_entity (gnat_entity);
8474
8475       if (!gnu_old)
8476         {
8477           tree gnu_decl = TYPE_STUB_DECL (make_dummy_type (gnat_entity));
8478           save_gnu_tree (gnat_entity, gnu_decl, false);
8479           if (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
8480               && Present (Full_View (gnat_entity)))
8481             {
8482               if (Has_Completion_In_Body (gnat_entity))
8483                 DECL_TAFT_TYPE_P (gnu_decl) = 1;
8484               save_gnu_tree (Full_View (gnat_entity), gnu_decl, false);
8485             }
8486         }
8487
8488       return;
8489     }
8490
8491   /* If we saved away a dummy type for this node it means that this
8492      made the type that corresponds to the full type of an incomplete
8493      type.  Clear that type for now and then update the type in the
8494      pointers.  */
8495   if (gnu_old)
8496     {
8497       gcc_assert (TREE_CODE (gnu_old) == TYPE_DECL
8498                   && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old)));
8499
8500       save_gnu_tree (gnat_entity, NULL_TREE, false);
8501     }
8502
8503   /* Now fully elaborate the type.  */
8504   gnu_new = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 1);
8505   gcc_assert (TREE_CODE (gnu_new) == TYPE_DECL);
8506
8507   /* If we have an old type and we've made pointers to this type, update those
8508      pointers.  If this is a Taft amendment type in the main unit, we need to
8509      mark the type as used since other units referencing it don't see the full
8510      declaration and, therefore, cannot mark it as used themselves.  */
8511   if (gnu_old)
8512     {
8513       update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
8514                          TREE_TYPE (gnu_new));
8515       if (DECL_TAFT_TYPE_P (gnu_old))
8516         used_types_insert (TREE_TYPE (gnu_new));
8517     }
8518
8519   /* If this is a record type corresponding to a task or protected type
8520      that is a completion of an incomplete type, perform a similar update
8521      on the type.  ??? Including protected types here is a guess.  */
8522   if (IN (Ekind (gnat_entity), Record_Kind)
8523       && Is_Concurrent_Record_Type (gnat_entity)
8524       && present_gnu_tree (Corresponding_Concurrent_Type (gnat_entity)))
8525     {
8526       tree gnu_task_old
8527         = get_gnu_tree (Corresponding_Concurrent_Type (gnat_entity));
8528
8529       save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
8530                      NULL_TREE, false);
8531       save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
8532                      gnu_new, false);
8533
8534       update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_task_old)),
8535                          TREE_TYPE (gnu_new));
8536     }
8537 }
8538 \f
8539 /* GNAT_ENTITY is the type of the resulting constructor, GNAT_ASSOC is the
8540    front of the Component_Associations of an N_Aggregate and GNU_TYPE is the
8541    GCC type of the corresponding record type.  Return the CONSTRUCTOR.  */
8542
8543 static tree
8544 assoc_to_constructor (Entity_Id gnat_entity, Node_Id gnat_assoc, tree gnu_type)
8545 {
8546   tree gnu_list = NULL_TREE, gnu_result;
8547
8548   /* We test for GNU_FIELD being empty in the case where a variant
8549      was the last thing since we don't take things off GNAT_ASSOC in
8550      that case.  We check GNAT_ASSOC in case we have a variant, but it
8551      has no fields.  */
8552
8553   for (; Present (gnat_assoc); gnat_assoc = Next (gnat_assoc))
8554     {
8555       Node_Id gnat_field = First (Choices (gnat_assoc));
8556       tree gnu_field = gnat_to_gnu_field_decl (Entity (gnat_field));
8557       tree gnu_expr = gnat_to_gnu (Expression (gnat_assoc));
8558
8559       /* The expander is supposed to put a single component selector name
8560          in every record component association.  */
8561       gcc_assert (No (Next (gnat_field)));
8562
8563       /* Ignore fields that have Corresponding_Discriminants since we'll
8564          be setting that field in the parent.  */
8565       if (Present (Corresponding_Discriminant (Entity (gnat_field)))
8566           && Is_Tagged_Type (Scope (Entity (gnat_field))))
8567         continue;
8568
8569       /* Also ignore discriminants of Unchecked_Unions.  */
8570       if (Is_Unchecked_Union (gnat_entity)
8571           && Ekind (Entity (gnat_field)) == E_Discriminant)
8572         continue;
8573
8574       /* Before assigning a value in an aggregate make sure range checks
8575          are done if required.  Then convert to the type of the field.  */
8576       if (Do_Range_Check (Expression (gnat_assoc)))
8577         gnu_expr = emit_range_check (gnu_expr, Etype (gnat_field), Empty);
8578
8579       gnu_expr = convert (TREE_TYPE (gnu_field), gnu_expr);
8580
8581       /* Add the field and expression to the list.  */
8582       gnu_list = tree_cons (gnu_field, gnu_expr, gnu_list);
8583     }
8584
8585   gnu_result = extract_values (gnu_list, gnu_type);
8586
8587 #ifdef ENABLE_CHECKING
8588   /* Verify that every entry in GNU_LIST was used.  */
8589   for (; gnu_list; gnu_list = TREE_CHAIN (gnu_list))
8590     gcc_assert (TREE_ADDRESSABLE (gnu_list));
8591 #endif
8592
8593   return gnu_result;
8594 }
8595
8596 /* Build a possibly nested constructor for array aggregates.  GNAT_EXPR is
8597    the first element of an array aggregate.  It may itself be an aggregate.
8598    GNU_ARRAY_TYPE is the GCC type corresponding to the array aggregate.
8599    GNAT_COMPONENT_TYPE is the type of the array component; it is needed
8600    for range checking.  */
8601
8602 static tree
8603 pos_to_constructor (Node_Id gnat_expr, tree gnu_array_type,
8604                     Entity_Id gnat_component_type)
8605 {
8606   tree gnu_index = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_array_type));
8607   tree gnu_expr;
8608   VEC(constructor_elt,gc) *gnu_expr_vec = NULL;
8609
8610   for ( ; Present (gnat_expr); gnat_expr = Next (gnat_expr))
8611     {
8612       /* If the expression is itself an array aggregate then first build the
8613          innermost constructor if it is part of our array (multi-dimensional
8614          case).  */
8615       if (Nkind (gnat_expr) == N_Aggregate
8616           && TREE_CODE (TREE_TYPE (gnu_array_type)) == ARRAY_TYPE
8617           && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_array_type)))
8618         gnu_expr = pos_to_constructor (First (Expressions (gnat_expr)),
8619                                        TREE_TYPE (gnu_array_type),
8620                                        gnat_component_type);
8621       else
8622         {
8623           gnu_expr = gnat_to_gnu (gnat_expr);
8624
8625           /* Before assigning the element to the array, make sure it is
8626              in range.  */
8627           if (Do_Range_Check (gnat_expr))
8628             gnu_expr = emit_range_check (gnu_expr, gnat_component_type, Empty);
8629         }
8630
8631       CONSTRUCTOR_APPEND_ELT (gnu_expr_vec, gnu_index,
8632                               convert (TREE_TYPE (gnu_array_type), gnu_expr));
8633
8634       gnu_index = int_const_binop (PLUS_EXPR, gnu_index, integer_one_node);
8635     }
8636
8637   return gnat_build_constructor (gnu_array_type, gnu_expr_vec);
8638 }
8639 \f
8640 /* Subroutine of assoc_to_constructor: VALUES is a list of field associations,
8641    some of which are from RECORD_TYPE.  Return a CONSTRUCTOR consisting
8642    of the associations that are from RECORD_TYPE.  If we see an internal
8643    record, make a recursive call to fill it in as well.  */
8644
8645 static tree
8646 extract_values (tree values, tree record_type)
8647 {
8648   tree field, tem;
8649   VEC(constructor_elt,gc) *v = NULL;
8650
8651   for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
8652     {
8653       tree value = 0;
8654
8655       /* _Parent is an internal field, but may have values in the aggregate,
8656          so check for values first.  */
8657       if ((tem = purpose_member (field, values)))
8658         {
8659           value = TREE_VALUE (tem);
8660           TREE_ADDRESSABLE (tem) = 1;
8661         }
8662
8663       else if (DECL_INTERNAL_P (field))
8664         {
8665           value = extract_values (values, TREE_TYPE (field));
8666           if (TREE_CODE (value) == CONSTRUCTOR
8667               && VEC_empty (constructor_elt, CONSTRUCTOR_ELTS (value)))
8668             value = 0;
8669         }
8670       else
8671         /* If we have a record subtype, the names will match, but not the
8672            actual FIELD_DECLs.  */
8673         for (tem = values; tem; tem = TREE_CHAIN (tem))
8674           if (DECL_NAME (TREE_PURPOSE (tem)) == DECL_NAME (field))
8675             {
8676               value = convert (TREE_TYPE (field), TREE_VALUE (tem));
8677               TREE_ADDRESSABLE (tem) = 1;
8678             }
8679
8680       if (!value)
8681         continue;
8682
8683       CONSTRUCTOR_APPEND_ELT (v, field, value);
8684     }
8685
8686   return gnat_build_constructor (record_type, v);
8687 }
8688 \f
8689 /* EXP is to be treated as an array or record.  Handle the cases when it is
8690    an access object and perform the required dereferences.  */
8691
8692 static tree
8693 maybe_implicit_deref (tree exp)
8694 {
8695   /* If the type is a pointer, dereference it.  */
8696   if (POINTER_TYPE_P (TREE_TYPE (exp))
8697       || TYPE_IS_FAT_POINTER_P (TREE_TYPE (exp)))
8698     exp = build_unary_op (INDIRECT_REF, NULL_TREE, exp);
8699
8700   /* If we got a padded type, remove it too.  */
8701   if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
8702     exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
8703
8704   return exp;
8705 }
8706 \f
8707 /* Convert SLOC into LOCUS.  Return true if SLOC corresponds to a source code
8708    location and false if it doesn't.  In the former case, set the Gigi global
8709    variable REF_FILENAME to the simple debug file name as given by sinput.  */
8710
8711 bool
8712 Sloc_to_locus (Source_Ptr Sloc, location_t *locus)
8713 {
8714   if (Sloc == No_Location)
8715     return false;
8716
8717   if (Sloc <= Standard_Location)
8718     {
8719       *locus = BUILTINS_LOCATION;
8720       return false;
8721     }
8722   else
8723     {
8724       Source_File_Index file = Get_Source_File_Index (Sloc);
8725       Logical_Line_Number line = Get_Logical_Line_Number (Sloc);
8726       Column_Number column = Get_Column_Number (Sloc);
8727       struct line_map *map = LINEMAPS_ORDINARY_MAP_AT (line_table, file - 1);
8728
8729       /* We can have zero if pragma Source_Reference is in effect.  */
8730       if (line < 1)
8731         line = 1;
8732
8733       /* Translate the location.  */
8734       *locus = linemap_position_for_line_and_column (map, line, column);
8735     }
8736
8737   ref_filename
8738     = IDENTIFIER_POINTER
8739       (get_identifier
8740        (Get_Name_String (Debug_Source_Name (Get_Source_File_Index (Sloc)))));;
8741
8742   return true;
8743 }
8744
8745 /* Similar to set_expr_location, but start with the Sloc of GNAT_NODE and
8746    don't do anything if it doesn't correspond to a source location.  */
8747
8748 static void
8749 set_expr_location_from_node (tree node, Node_Id gnat_node)
8750 {
8751   location_t locus;
8752
8753   if (!Sloc_to_locus (Sloc (gnat_node), &locus))
8754     return;
8755
8756   SET_EXPR_LOCATION (node, locus);
8757 }
8758
8759 /* More elaborate version of set_expr_location_from_node to be used in more
8760    general contexts, for example the result of the translation of a generic
8761    GNAT node.  */
8762
8763 static void
8764 set_gnu_expr_location_from_node (tree node, Node_Id gnat_node)
8765 {
8766   /* Set the location information on the node if it is a real expression.
8767      References can be reused for multiple GNAT nodes and they would get
8768      the location information of their last use.  Also make sure not to
8769      overwrite an existing location as it is probably more precise.  */
8770
8771   switch (TREE_CODE (node))
8772     {
8773     CASE_CONVERT:
8774     case NON_LVALUE_EXPR:
8775       break;
8776
8777     case COMPOUND_EXPR:
8778       if (EXPR_P (TREE_OPERAND (node, 1)))
8779         set_gnu_expr_location_from_node (TREE_OPERAND (node, 1), gnat_node);
8780
8781       /* ... fall through ... */
8782
8783     default:
8784       if (!REFERENCE_CLASS_P (node) && !EXPR_HAS_LOCATION (node))
8785         {
8786           set_expr_location_from_node (node, gnat_node);
8787           set_end_locus_from_node (node, gnat_node);
8788         }
8789       break;
8790     }
8791 }
8792 \f
8793 /* Return a colon-separated list of encodings contained in encoded Ada
8794    name.  */
8795
8796 static const char *
8797 extract_encoding (const char *name)
8798 {
8799   char *encoding = (char *) ggc_alloc_atomic (strlen (name));
8800   get_encoding (name, encoding);
8801   return encoding;
8802 }
8803
8804 /* Extract the Ada name from an encoded name.  */
8805
8806 static const char *
8807 decode_name (const char *name)
8808 {
8809   char *decoded = (char *) ggc_alloc_atomic (strlen (name) * 2 + 60);
8810   __gnat_decode (name, decoded, 0);
8811   return decoded;
8812 }
8813 \f
8814 /* Post an error message.  MSG is the error message, properly annotated.
8815    NODE is the node at which to post the error and the node to use for the
8816    '&' substitution.  */
8817
8818 void
8819 post_error (const char *msg, Node_Id node)
8820 {
8821   String_Template temp;
8822   Fat_Pointer fp;
8823
8824   temp.Low_Bound = 1, temp.High_Bound = strlen (msg);
8825   fp.Array = msg, fp.Bounds = &temp;
8826   if (Present (node))
8827     Error_Msg_N (fp, node);
8828 }
8829
8830 /* Similar to post_error, but NODE is the node at which to post the error and
8831    ENT is the node to use for the '&' substitution.  */
8832
8833 void
8834 post_error_ne (const char *msg, Node_Id node, Entity_Id ent)
8835 {
8836   String_Template temp;
8837   Fat_Pointer fp;
8838
8839   temp.Low_Bound = 1, temp.High_Bound = strlen (msg);
8840   fp.Array = msg, fp.Bounds = &temp;
8841   if (Present (node))
8842     Error_Msg_NE (fp, node, ent);
8843 }
8844
8845 /* Similar to post_error_ne, but NUM is the number to use for the '^'.  */
8846
8847 void
8848 post_error_ne_num (const char *msg, Node_Id node, Entity_Id ent, int num)
8849 {
8850   Error_Msg_Uint_1 = UI_From_Int (num);
8851   post_error_ne (msg, node, ent);
8852 }
8853
8854 /* Set the end_locus information for GNU_NODE, if any, from an explicit end
8855    location associated with GNAT_NODE or GNAT_NODE itself, whichever makes
8856    most sense.  Return true if a sensible assignment was performed.  */
8857
8858 static bool
8859 set_end_locus_from_node (tree gnu_node, Node_Id gnat_node)
8860 {
8861   Node_Id gnat_end_label = Empty;
8862   location_t end_locus;
8863
8864   /* Pick the GNAT node of which we'll take the sloc to assign to the GCC node
8865      end_locus when there is one.  We consider only GNAT nodes with a possible
8866      End_Label attached.  If the End_Label actually was unassigned, fallback
8867      on the orginal node.  We'd better assign an explicit sloc associated with
8868      the outer construct in any case.  */
8869
8870   switch (Nkind (gnat_node))
8871     {
8872     case N_Package_Body:
8873     case N_Subprogram_Body:
8874     case N_Block_Statement:
8875       gnat_end_label = End_Label (Handled_Statement_Sequence (gnat_node));
8876       break;
8877
8878     case N_Package_Declaration:
8879       gnat_end_label = End_Label (Specification (gnat_node));
8880       break;
8881
8882     default:
8883       return false;
8884     }
8885
8886   gnat_node = Present (gnat_end_label) ? gnat_end_label : gnat_node;
8887
8888   /* Some expanded subprograms have neither an End_Label nor a Sloc
8889      attached.  Notify that to callers.  */
8890
8891   if (!Sloc_to_locus (Sloc (gnat_node), &end_locus))
8892     return false;
8893
8894   switch (TREE_CODE (gnu_node))
8895     {
8896     case BIND_EXPR:
8897       BLOCK_SOURCE_END_LOCATION (BIND_EXPR_BLOCK (gnu_node)) = end_locus;
8898       return true;
8899
8900     case FUNCTION_DECL:
8901       DECL_STRUCT_FUNCTION (gnu_node)->function_end_locus = end_locus;
8902       return true;
8903
8904     default:
8905       return false;
8906     }
8907 }
8908 \f
8909 /* Similar to post_error_ne, but T is a GCC tree representing the number to
8910    write.  If T represents a constant, the text inside curly brackets in
8911    MSG will be output (presumably including a '^').  Otherwise it will not
8912    be output and the text inside square brackets will be output instead.  */
8913
8914 void
8915 post_error_ne_tree (const char *msg, Node_Id node, Entity_Id ent, tree t)
8916 {
8917   char *new_msg = XALLOCAVEC (char, strlen (msg) + 1);
8918   char start_yes, end_yes, start_no, end_no;
8919   const char *p;
8920   char *q;
8921
8922   if (TREE_CODE (t) == INTEGER_CST)
8923     {
8924       Error_Msg_Uint_1 = UI_From_gnu (t);
8925       start_yes = '{', end_yes = '}', start_no = '[', end_no = ']';
8926     }
8927   else
8928     start_yes = '[', end_yes = ']', start_no = '{', end_no = '}';
8929
8930   for (p = msg, q = new_msg; *p; p++)
8931     {
8932       if (*p == start_yes)
8933         for (p++; *p != end_yes; p++)
8934           *q++ = *p;
8935       else if (*p == start_no)
8936         for (p++; *p != end_no; p++)
8937           ;
8938       else
8939         *q++ = *p;
8940     }
8941
8942   *q = 0;
8943
8944   post_error_ne (new_msg, node, ent);
8945 }
8946
8947 /* Similar to post_error_ne_tree, but NUM is a second integer to write.  */
8948
8949 void
8950 post_error_ne_tree_2 (const char *msg, Node_Id node, Entity_Id ent, tree t,
8951                       int num)
8952 {
8953   Error_Msg_Uint_2 = UI_From_Int (num);
8954   post_error_ne_tree (msg, node, ent, t);
8955 }
8956 \f
8957 /* Initialize the table that maps GNAT codes to GCC codes for simple
8958    binary and unary operations.  */
8959
8960 static void
8961 init_code_table (void)
8962 {
8963   gnu_codes[N_And_Then] = TRUTH_ANDIF_EXPR;
8964   gnu_codes[N_Or_Else] = TRUTH_ORIF_EXPR;
8965
8966   gnu_codes[N_Op_And] = TRUTH_AND_EXPR;
8967   gnu_codes[N_Op_Or] = TRUTH_OR_EXPR;
8968   gnu_codes[N_Op_Xor] = TRUTH_XOR_EXPR;
8969   gnu_codes[N_Op_Eq] = EQ_EXPR;
8970   gnu_codes[N_Op_Ne] = NE_EXPR;
8971   gnu_codes[N_Op_Lt] = LT_EXPR;
8972   gnu_codes[N_Op_Le] = LE_EXPR;
8973   gnu_codes[N_Op_Gt] = GT_EXPR;
8974   gnu_codes[N_Op_Ge] = GE_EXPR;
8975   gnu_codes[N_Op_Add] = PLUS_EXPR;
8976   gnu_codes[N_Op_Subtract] = MINUS_EXPR;
8977   gnu_codes[N_Op_Multiply] = MULT_EXPR;
8978   gnu_codes[N_Op_Mod] = FLOOR_MOD_EXPR;
8979   gnu_codes[N_Op_Rem] = TRUNC_MOD_EXPR;
8980   gnu_codes[N_Op_Minus] = NEGATE_EXPR;
8981   gnu_codes[N_Op_Abs] = ABS_EXPR;
8982   gnu_codes[N_Op_Not] = TRUTH_NOT_EXPR;
8983   gnu_codes[N_Op_Rotate_Left] = LROTATE_EXPR;
8984   gnu_codes[N_Op_Rotate_Right] = RROTATE_EXPR;
8985   gnu_codes[N_Op_Shift_Left] = LSHIFT_EXPR;
8986   gnu_codes[N_Op_Shift_Right] = RSHIFT_EXPR;
8987   gnu_codes[N_Op_Shift_Right_Arithmetic] = RSHIFT_EXPR;
8988 }
8989
8990 /* Return a label to branch to for the exception type in KIND or NULL_TREE
8991    if none.  */
8992
8993 tree
8994 get_exception_label (char kind)
8995 {
8996   if (kind == N_Raise_Constraint_Error)
8997     return VEC_last (tree, gnu_constraint_error_label_stack);
8998   else if (kind == N_Raise_Storage_Error)
8999     return VEC_last (tree, gnu_storage_error_label_stack);
9000   else if (kind == N_Raise_Program_Error)
9001     return VEC_last (tree, gnu_program_error_label_stack);
9002   else
9003     return NULL_TREE;
9004 }
9005
9006 /* Return the decl for the current elaboration procedure.  */
9007
9008 tree
9009 get_elaboration_procedure (void)
9010 {
9011   return VEC_last (tree, gnu_elab_proc_stack);
9012 }
9013
9014 #include "gt-ada-trans.h"