OSDN Git Service

* gcc-interface/trans.c (gigi): Do not start statement group.
[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-2010, Free Software Foundation, Inc.         *
10  *                                                                          *
11  * GNAT is free software;  you can  redistribute it  and/or modify it under *
12  * terms of the  GNU General Public License as published  by the Free Soft- *
13  * ware  Foundation;  either version 3,  or (at your option) any later ver- *
14  * sion.  GNAT is distributed in the hope that it will be useful, but WITH- *
15  * OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY *
16  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License *
17  * for  more details.  You should have  received  a copy of the GNU General *
18  * Public License  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 "expr.h"
33 #include "ggc.h"
34 #include "output.h"
35 #include "tree-iterator.h"
36 #include "gimple.h"
37
38 #include "ada.h"
39 #include "adadecode.h"
40 #include "types.h"
41 #include "atree.h"
42 #include "elists.h"
43 #include "namet.h"
44 #include "nlists.h"
45 #include "snames.h"
46 #include "stringt.h"
47 #include "uintp.h"
48 #include "urealp.h"
49 #include "fe.h"
50 #include "sinfo.h"
51 #include "einfo.h"
52 #include "gadaint.h"
53 #include "ada-tree.h"
54 #include "gigi.h"
55
56 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
57    for fear of running out of stack space.  If we need more, we use xmalloc
58    instead.  */
59 #define ALLOCA_THRESHOLD 1000
60
61 /* Let code below know whether we are targetting VMS without need of
62    intrusive preprocessor directives.  */
63 #ifndef TARGET_ABI_OPEN_VMS
64 #define TARGET_ABI_OPEN_VMS 0
65 #endif
66
67 /* For efficient float-to-int rounding, it is necessary to know whether
68    floating-point arithmetic may use wider intermediate results.  When
69    FP_ARITH_MAY_WIDEN is not defined, be conservative and only assume
70    that arithmetic does not widen if double precision is emulated.  */
71 #ifndef FP_ARITH_MAY_WIDEN
72 #if defined(HAVE_extendsfdf2)
73 #define FP_ARITH_MAY_WIDEN HAVE_extendsfdf2
74 #else
75 #define FP_ARITH_MAY_WIDEN 0
76 #endif
77 #endif
78
79 /* Pointers to front-end tables accessed through macros.  */
80 struct Node *Nodes_Ptr;
81 Node_Id *Next_Node_Ptr;
82 Node_Id *Prev_Node_Ptr;
83 struct Elist_Header *Elists_Ptr;
84 struct Elmt_Item *Elmts_Ptr;
85 struct String_Entry *Strings_Ptr;
86 Char_Code *String_Chars_Ptr;
87 struct List_Header *List_Headers_Ptr;
88
89 /* Highest number in the front-end node table.  */
90 int max_gnat_nodes;
91
92 /* Current node being treated, in case abort called.  */
93 Node_Id error_gnat_node;
94
95 /* True when gigi is being called on an analyzed but unexpanded
96    tree, and the only purpose of the call is to properly annotate
97    types with representation information.  */
98 bool type_annotate_only;
99
100 /* Current filename without path.  */
101 const char *ref_filename;
102
103 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
104    of unconstrained array IN parameters to avoid emitting a great deal of
105    redundant instructions to recompute them each time.  */
106 struct GTY (()) parm_attr_d {
107   int id; /* GTY doesn't like Entity_Id.  */
108   int dim;
109   tree first;
110   tree last;
111   tree length;
112 };
113
114 typedef struct parm_attr_d *parm_attr;
115
116 DEF_VEC_P(parm_attr);
117 DEF_VEC_ALLOC_P(parm_attr,gc);
118
119 struct GTY(()) language_function {
120   VEC(parm_attr,gc) *parm_attr_cache;
121 };
122
123 #define f_parm_attr_cache \
124   DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
125
126 /* A structure used to gather together information about a statement group.
127    We use this to gather related statements, for example the "then" part
128    of a IF.  In the case where it represents a lexical scope, we may also
129    have a BLOCK node corresponding to it and/or cleanups.  */
130
131 struct GTY((chain_next ("%h.previous"))) stmt_group {
132   struct stmt_group *previous;  /* Previous code group.  */
133   tree stmt_list;               /* List of statements for this code group.  */
134   tree block;                   /* BLOCK for this code group, if any.  */
135   tree cleanups;                /* Cleanups for this code group, if any.  */
136 };
137
138 static GTY(()) struct stmt_group *current_stmt_group;
139
140 /* List of unused struct stmt_group nodes.  */
141 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
142
143 /* A structure used to record information on elaboration procedures
144    we've made and need to process.
145
146    ??? gnat_node should be Node_Id, but gengtype gets confused.  */
147
148 struct GTY((chain_next ("%h.next"))) elab_info {
149   struct elab_info *next;       /* Pointer to next in chain.  */
150   tree elab_proc;               /* Elaboration procedure.  */
151   int gnat_node;                /* The N_Compilation_Unit.  */
152 };
153
154 static GTY(()) struct elab_info *elab_info_list;
155
156 /* Free list of TREE_LIST nodes used for stacks.  */
157 static GTY((deletable)) tree gnu_stack_free_list;
158
159 /* List of TREE_LIST nodes representing a stack of exception pointer
160    variables.  TREE_VALUE is the VAR_DECL that stores the address of
161    the raised exception.  Nonzero means we are in an exception
162    handler.  Not used in the zero-cost case.  */
163 static GTY(()) tree gnu_except_ptr_stack;
164
165 /* List of TREE_LIST nodes used to store the current elaboration procedure
166    decl.  TREE_VALUE is the decl.  */
167 static GTY(()) tree gnu_elab_proc_stack;
168
169 /* Variable that stores a list of labels to be used as a goto target instead of
170    a return in some functions.  See processing for N_Subprogram_Body.  */
171 static GTY(()) tree gnu_return_label_stack;
172
173 /* List of TREE_LIST nodes representing a stack of LOOP_STMT nodes.
174    TREE_VALUE of each entry is the label of the corresponding LOOP_STMT.  */
175 static GTY(()) tree gnu_loop_label_stack;
176
177 /* List of TREE_LIST nodes representing labels for switch statements.
178    TREE_VALUE of each entry is the label at the end of the switch.  */
179 static GTY(()) tree gnu_switch_label_stack;
180
181 /* List of TREE_LIST nodes containing the stacks for N_{Push,Pop}_*_Label.  */
182 static GTY(()) tree gnu_constraint_error_label_stack;
183 static GTY(()) tree gnu_storage_error_label_stack;
184 static GTY(()) tree gnu_program_error_label_stack;
185
186 /* Map GNAT tree codes to GCC tree codes for simple expressions.  */
187 static enum tree_code gnu_codes[Number_Node_Kinds];
188
189 static void init_code_table (void);
190 static void Compilation_Unit_to_gnu (Node_Id);
191 static void record_code_position (Node_Id);
192 static void insert_code_for (Node_Id);
193 static void add_cleanup (tree, Node_Id);
194 static tree unshare_save_expr (tree *, int *, void *);
195 static void add_stmt_list (List_Id);
196 static void push_exception_label_stack (tree *, Entity_Id);
197 static tree build_stmt_group (List_Id, bool);
198 static void push_stack (tree *, tree, tree);
199 static void pop_stack (tree *);
200 static enum gimplify_status gnat_gimplify_stmt (tree *);
201 static void elaborate_all_entities (Node_Id);
202 static void process_freeze_entity (Node_Id);
203 static void process_inlined_subprograms (Node_Id);
204 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
205 static tree emit_range_check (tree, Node_Id, Node_Id);
206 static tree emit_index_check (tree, tree, tree, tree, Node_Id);
207 static tree emit_check (tree, tree, int, Node_Id);
208 static tree build_unary_op_trapv (enum tree_code, tree, tree, Node_Id);
209 static tree build_binary_op_trapv (enum tree_code, tree, tree, tree, Node_Id);
210 static tree convert_with_check (Entity_Id, tree, bool, bool, bool, Node_Id);
211 static bool smaller_packable_type_p (tree, tree);
212 static bool addressable_p (tree, tree);
213 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
214 static tree extract_values (tree, tree);
215 static tree pos_to_constructor (Node_Id, tree, Entity_Id);
216 static tree maybe_implicit_deref (tree);
217 static void set_expr_location_from_node (tree, Node_Id);
218 static int lvalue_required_p (Node_Id, tree, bool, bool, bool);
219
220 /* Hooks for debug info back-ends, only supported and used in a restricted set
221    of configurations.  */
222 static const char *extract_encoding (const char *) ATTRIBUTE_UNUSED;
223 static const char *decode_name (const char *) ATTRIBUTE_UNUSED;
224 \f
225 /* This is the main program of the back-end.  It sets up all the table
226    structures and then generates code.  */
227
228 void
229 gigi (Node_Id gnat_root, int max_gnat_node, int number_name ATTRIBUTE_UNUSED,
230       struct Node *nodes_ptr, Node_Id *next_node_ptr, Node_Id *prev_node_ptr,
231       struct Elist_Header *elists_ptr, struct Elmt_Item *elmts_ptr,
232       struct String_Entry *strings_ptr, Char_Code *string_chars_ptr,
233       struct List_Header *list_headers_ptr, Nat number_file,
234       struct File_Info_Type *file_info_ptr, Entity_Id standard_boolean,
235       Entity_Id standard_integer, Entity_Id standard_long_long_float,
236       Entity_Id standard_exception_type, Int gigi_operating_mode)
237 {
238   Entity_Id gnat_literal;
239   tree long_long_float_type, exception_type, t;
240   tree int64_type = gnat_type_for_size (64, 0);
241   struct elab_info *info;
242   int i;
243
244   max_gnat_nodes = max_gnat_node;
245
246   Nodes_Ptr = nodes_ptr;
247   Next_Node_Ptr = next_node_ptr;
248   Prev_Node_Ptr = prev_node_ptr;
249   Elists_Ptr = elists_ptr;
250   Elmts_Ptr = elmts_ptr;
251   Strings_Ptr = strings_ptr;
252   String_Chars_Ptr = string_chars_ptr;
253   List_Headers_Ptr = list_headers_ptr;
254
255   type_annotate_only = (gigi_operating_mode == 1);
256
257   gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
258
259   /* Declare the name of the compilation unit as the first global
260      name in order to make the middle-end fully deterministic.  */
261   t = create_concat_name (Defining_Entity (Unit (gnat_root)), NULL);
262   first_global_object_name = ggc_strdup (IDENTIFIER_POINTER (t));
263
264   for (i = 0; i < number_file; i++)
265     {
266       /* Use the identifier table to make a permanent copy of the filename as
267          the name table gets reallocated after Gigi returns but before all the
268          debugging information is output.  The __gnat_to_canonical_file_spec
269          call translates filenames from pragmas Source_Reference that contain
270          host style syntax not understood by gdb.  */
271       const char *filename
272         = IDENTIFIER_POINTER
273            (get_identifier
274             (__gnat_to_canonical_file_spec
275              (Get_Name_String (file_info_ptr[i].File_Name))));
276
277       /* We rely on the order isomorphism between files and line maps.  */
278       gcc_assert ((int) line_table->used == i);
279
280       /* We create the line map for a source file at once, with a fixed number
281          of columns chosen to avoid jumping over the next power of 2.  */
282       linemap_add (line_table, LC_ENTER, 0, filename, 1);
283       linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
284       linemap_position_for_column (line_table, 252 - 1);
285       linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
286     }
287
288   /* Initialize ourselves.  */
289   init_code_table ();
290   init_gnat_to_gnu ();
291   init_dummy_type ();
292
293   /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
294      errors.  */
295   if (type_annotate_only)
296     {
297       TYPE_SIZE (void_type_node) = bitsize_zero_node;
298       TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
299     }
300
301   /* If the GNU type extensions to DWARF are available, setup the hooks.  */
302 #if defined (DWARF2_DEBUGGING_INFO) && defined (DWARF2_GNU_TYPE_EXTENSIONS)
303   /* We condition the name demangling and the generation of type encoding
304      strings on -gdwarf+ and always set descriptive types on.  */
305   if (use_gnu_debug_info_extensions)
306     {
307       dwarf2out_set_type_encoding_func (extract_encoding);
308       dwarf2out_set_demangle_name_func (decode_name);
309     }
310   dwarf2out_set_descriptive_type_func (get_parallel_type);
311 #endif
312
313   /* Enable GNAT stack checking method if needed */
314   if (!Stack_Check_Probes_On_Target)
315     set_stack_check_libfunc (gen_rtx_SYMBOL_REF (Pmode, "_gnat_stack_check"));
316
317   /* Retrieve alignment settings.  */
318   double_float_alignment = get_target_double_float_alignment ();
319   double_scalar_alignment = get_target_double_scalar_alignment ();
320
321   /* Record the builtin types.  Define `integer' and `unsigned char' first so
322      that dbx will output them first.  */
323   record_builtin_type ("integer", integer_type_node);
324   record_builtin_type ("unsigned char", char_type_node);
325   record_builtin_type ("long integer", long_integer_type_node);
326   unsigned_type_node = gnat_type_for_size (INT_TYPE_SIZE, 1);
327   record_builtin_type ("unsigned int", unsigned_type_node);
328   record_builtin_type (SIZE_TYPE, sizetype);
329   record_builtin_type ("boolean", boolean_type_node);
330   record_builtin_type ("void", void_type_node);
331
332   /* Save the type we made for integer as the type for Standard.Integer.  */
333   save_gnu_tree (Base_Type (standard_integer), TYPE_NAME (integer_type_node),
334                  false);
335
336   /* Save the type we made for boolean as the type for Standard.Boolean.  */
337   save_gnu_tree (Base_Type (standard_boolean), TYPE_NAME (boolean_type_node),
338                  false);
339   gnat_literal = First_Literal (Base_Type (standard_boolean));
340   t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
341   gcc_assert (t == boolean_false_node);
342   t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
343                        boolean_type_node, t, true, false, false, false,
344                        NULL, gnat_literal);
345   DECL_IGNORED_P (t) = 1;
346   save_gnu_tree (gnat_literal, t, false);
347   gnat_literal = Next_Literal (gnat_literal);
348   t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
349   gcc_assert (t == boolean_true_node);
350   t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
351                        boolean_type_node, t, true, false, false, false,
352                        NULL, gnat_literal);
353   DECL_IGNORED_P (t) = 1;
354   save_gnu_tree (gnat_literal, t, false);
355
356   void_ftype = build_function_type (void_type_node, NULL_TREE);
357   ptr_void_ftype = build_pointer_type (void_ftype);
358
359   /* Now declare runtime functions.  */
360   t = tree_cons (NULL_TREE, void_type_node, NULL_TREE);
361
362   /* malloc is a function declaration tree for a function to allocate
363      memory.  */
364   malloc_decl
365     = create_subprog_decl (get_identifier ("__gnat_malloc"), NULL_TREE,
366                            build_function_type (ptr_void_type_node,
367                                                 tree_cons (NULL_TREE,
368                                                            sizetype, t)),
369                            NULL_TREE, false, true, true, NULL, Empty);
370   DECL_IS_MALLOC (malloc_decl) = 1;
371
372   /* malloc32 is a function declaration tree for a function to allocate
373      32-bit memory on a 64-bit system.  Needed only on 64-bit VMS.  */
374   malloc32_decl
375     = create_subprog_decl (get_identifier ("__gnat_malloc32"), NULL_TREE,
376                            build_function_type (ptr_void_type_node,
377                                                 tree_cons (NULL_TREE,
378                                                            sizetype, t)),
379                            NULL_TREE, false, true, true, NULL, Empty);
380   DECL_IS_MALLOC (malloc32_decl) = 1;
381
382   /* free is a function declaration tree for a function to free memory.  */
383   free_decl
384     = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
385                            build_function_type (void_type_node,
386                                                 tree_cons (NULL_TREE,
387                                                            ptr_void_type_node,
388                                                            t)),
389                            NULL_TREE, false, true, true, NULL, Empty);
390
391   /* This is used for 64-bit multiplication with overflow checking.  */
392   mulv64_decl
393     = create_subprog_decl (get_identifier ("__gnat_mulv64"), NULL_TREE,
394                            build_function_type_list (int64_type, int64_type,
395                                                      int64_type, NULL_TREE),
396                            NULL_TREE, false, true, true, NULL, Empty);
397
398   /* Name of the _Parent field in tagged record types.  */
399   parent_name_id = get_identifier (Get_Name_String (Name_uParent));
400
401   /* Make the types and functions used for exception processing.  */
402   jmpbuf_type
403     = build_array_type (gnat_type_for_mode (Pmode, 0),
404                         build_index_type (size_int (5)));
405   record_builtin_type ("JMPBUF_T", jmpbuf_type);
406   jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
407
408   /* Functions to get and set the jumpbuf pointer for the current thread.  */
409   get_jmpbuf_decl
410     = create_subprog_decl
411     (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
412      NULL_TREE, build_function_type (jmpbuf_ptr_type, NULL_TREE),
413      NULL_TREE, false, true, true, NULL, Empty);
414   /* Avoid creating superfluous edges to __builtin_setjmp receivers.  */
415   DECL_PURE_P (get_jmpbuf_decl) = 1;
416
417   set_jmpbuf_decl
418     = create_subprog_decl
419     (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
420      NULL_TREE,
421      build_function_type (void_type_node,
422                           tree_cons (NULL_TREE, jmpbuf_ptr_type, t)),
423      NULL_TREE, false, true, true, NULL, Empty);
424
425   /* setjmp returns an integer and has one operand, which is a pointer to
426      a jmpbuf.  */
427   setjmp_decl
428     = create_subprog_decl
429       (get_identifier ("__builtin_setjmp"), NULL_TREE,
430        build_function_type (integer_type_node,
431                             tree_cons (NULL_TREE,  jmpbuf_ptr_type, t)),
432        NULL_TREE, false, true, true, NULL, Empty);
433
434   DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
435   DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
436
437   /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
438      address.  */
439   update_setjmp_buf_decl
440     = create_subprog_decl
441       (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
442        build_function_type (void_type_node,
443                             tree_cons (NULL_TREE,  jmpbuf_ptr_type, t)),
444        NULL_TREE, false, true, true, NULL, Empty);
445
446   DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
447   DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
448
449   /* Hooks to call when entering/leaving an exception handler.  */
450   begin_handler_decl
451     = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
452                            build_function_type (void_type_node,
453                                                 tree_cons (NULL_TREE,
454                                                            ptr_void_type_node,
455                                                            t)),
456                            NULL_TREE, false, true, true, NULL, Empty);
457
458   end_handler_decl
459     = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
460                            build_function_type (void_type_node,
461                                                 tree_cons (NULL_TREE,
462                                                            ptr_void_type_node,
463                                                            t)),
464                            NULL_TREE, false, true, true, NULL, Empty);
465
466   /* If in no exception handlers mode, all raise statements are redirected to
467      __gnat_last_chance_handler.  No need to redefine raise_nodefer_decl since
468      this procedure will never be called in this mode.  */
469   if (No_Exception_Handlers_Set ())
470     {
471       tree decl
472         = create_subprog_decl
473           (get_identifier ("__gnat_last_chance_handler"), NULL_TREE,
474            build_function_type (void_type_node,
475                                 tree_cons (NULL_TREE,
476                                            build_pointer_type (char_type_node),
477                                            tree_cons (NULL_TREE,
478                                                       integer_type_node,
479                                                       t))),
480            NULL_TREE, false, true, true, NULL, Empty);
481
482       for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
483         gnat_raise_decls[i] = decl;
484     }
485   else
486     /* Otherwise, make one decl for each exception reason.  */
487     for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
488       {
489         char name[17];
490
491         sprintf (name, "__gnat_rcheck_%.2d", i);
492         gnat_raise_decls[i]
493           = create_subprog_decl
494             (get_identifier (name), NULL_TREE,
495              build_function_type (void_type_node,
496                                   tree_cons (NULL_TREE,
497                                              build_pointer_type
498                                              (char_type_node),
499                                              tree_cons (NULL_TREE,
500                                                         integer_type_node,
501                                                         t))),
502              NULL_TREE, false, true, true, NULL, Empty);
503       }
504
505   for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
506     {
507       TREE_THIS_VOLATILE (gnat_raise_decls[i]) = 1;
508       TREE_SIDE_EFFECTS (gnat_raise_decls[i]) = 1;
509       TREE_TYPE (gnat_raise_decls[i])
510         = build_qualified_type (TREE_TYPE (gnat_raise_decls[i]),
511                                 TYPE_QUAL_VOLATILE);
512     }
513
514   /* Set the types that GCC and Gigi use from the front end.  We would
515      like to do this for char_type_node, but it needs to correspond to
516      the C char type.  */
517   exception_type
518     = gnat_to_gnu_entity (Base_Type (standard_exception_type),  NULL_TREE, 0);
519   except_type_node = TREE_TYPE (exception_type);
520
521   /* Make other functions used for exception processing.  */
522   get_excptr_decl
523     = create_subprog_decl
524     (get_identifier ("system__soft_links__get_gnat_exception"),
525      NULL_TREE,
526      build_function_type (build_pointer_type (except_type_node), NULL_TREE),
527      NULL_TREE, false, true, true, NULL, Empty);
528   /* Avoid creating superfluous edges to __builtin_setjmp receivers.  */
529   DECL_PURE_P (get_excptr_decl) = 1;
530
531   raise_nodefer_decl
532     = create_subprog_decl
533       (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE,
534        build_function_type (void_type_node,
535                             tree_cons (NULL_TREE,
536                                        build_pointer_type (except_type_node),
537                                        t)),
538        NULL_TREE, false, true, true, NULL, Empty);
539
540   /* Indicate that these never return.  */
541   TREE_THIS_VOLATILE (raise_nodefer_decl) = 1;
542   TREE_SIDE_EFFECTS (raise_nodefer_decl) = 1;
543   TREE_TYPE (raise_nodefer_decl)
544     = build_qualified_type (TREE_TYPE (raise_nodefer_decl),
545                             TYPE_QUAL_VOLATILE);
546
547   /* Build the special descriptor type and its null node if needed.  */
548   if (TARGET_VTABLE_USES_DESCRIPTORS)
549     {
550       tree null_node = fold_convert (ptr_void_ftype, null_pointer_node);
551       tree field_list = NULL_TREE, null_list = NULL_TREE;
552       int j;
553
554       fdesc_type_node = make_node (RECORD_TYPE);
555
556       for (j = 0; j < TARGET_VTABLE_USES_DESCRIPTORS; j++)
557         {
558           tree field = create_field_decl (NULL_TREE, ptr_void_ftype,
559                                           fdesc_type_node, 0, 0, 0, 1);
560           TREE_CHAIN (field) = field_list;
561           field_list = field;
562           null_list = tree_cons (field, null_node, null_list);
563         }
564
565       finish_record_type (fdesc_type_node, nreverse (field_list), 0, false);
566       record_builtin_type ("descriptor", fdesc_type_node);
567       null_fdesc_node = gnat_build_constructor (fdesc_type_node, null_list);
568     }
569
570   long_long_float_type
571     = gnat_to_gnu_entity (Base_Type (standard_long_long_float), NULL_TREE, 0);
572
573   if (TREE_CODE (TREE_TYPE (long_long_float_type)) == INTEGER_TYPE)
574     {
575       /* In this case, the builtin floating point types are VAX float,
576          so make up a type for use.  */
577       longest_float_type_node = make_node (REAL_TYPE);
578       TYPE_PRECISION (longest_float_type_node) = LONG_DOUBLE_TYPE_SIZE;
579       layout_type (longest_float_type_node);
580       record_builtin_type ("longest float type", longest_float_type_node);
581     }
582   else
583     longest_float_type_node = TREE_TYPE (long_long_float_type);
584
585   /* Dummy objects to materialize "others" and "all others" in the exception
586      tables.  These are exported by a-exexpr.adb, so see this unit for the
587      types to use.  */
588   others_decl
589     = create_var_decl (get_identifier ("OTHERS"),
590                        get_identifier ("__gnat_others_value"),
591                        integer_type_node, 0, 1, 0, 1, 1, 0, Empty);
592
593   all_others_decl
594     = create_var_decl (get_identifier ("ALL_OTHERS"),
595                        get_identifier ("__gnat_all_others_value"),
596                        integer_type_node, 0, 1, 0, 1, 1, 0, Empty);
597
598   main_identifier_node = get_identifier ("main");
599
600   /* Install the builtins we might need, either internally or as
601      user available facilities for Intrinsic imports.  */
602   gnat_install_builtins ();
603
604   gnu_except_ptr_stack = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
605   gnu_constraint_error_label_stack
606     = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
607   gnu_storage_error_label_stack = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
608   gnu_program_error_label_stack = tree_cons (NULL_TREE, NULL_TREE, NULL_TREE);
609
610   /* Process any Pragma Ident for the main unit.  */
611 #ifdef ASM_OUTPUT_IDENT
612   if (Present (Ident_String (Main_Unit)))
613     ASM_OUTPUT_IDENT
614       (asm_out_file,
615        TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
616 #endif
617
618   /* If we are using the GCC exception mechanism, let GCC know.  */
619   if (Exception_Mechanism == Back_End_Exceptions)
620     gnat_init_gcc_eh ();
621
622   /* Now translate the compilation unit proper.  */
623   Compilation_Unit_to_gnu (gnat_root);
624
625   /* Finally see if we have any elaboration procedures to deal with.  */
626   for (info = elab_info_list; info; info = info->next)
627     {
628       tree gnu_body = DECL_SAVED_TREE (info->elab_proc), gnu_stmts;
629
630       /* Unshare SAVE_EXPRs between subprograms.  These are not unshared by
631          the gimplifier for obvious reasons, but it turns out that we need to
632          unshare them for the global level because of SAVE_EXPRs made around
633          checks for global objects and around allocators for global objects
634          of variable size, in order to prevent node sharing in the underlying
635          expression.  Note that this implicitly assumes that the SAVE_EXPR
636          nodes themselves are not shared between subprograms, which would be
637          an upstream bug for which we would not change the outcome.  */
638       walk_tree_without_duplicates (&gnu_body, unshare_save_expr, NULL);
639
640       /* We should have a BIND_EXPR but it may not have any statements in it.
641          If it doesn't have any, we have nothing to do except for setting the
642          flag on the GNAT node.  Otherwise, process the function as others.  */
643       gnu_stmts = gnu_body;
644       if (TREE_CODE (gnu_stmts) == BIND_EXPR)
645         gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
646       if (!gnu_stmts || !STATEMENT_LIST_HEAD (gnu_stmts))
647         Set_Has_No_Elaboration_Code (info->gnat_node, 1);
648       else
649         {
650           begin_subprog_body (info->elab_proc);
651           end_subprog_body (gnu_body);
652         }
653     }
654
655   /* We cannot track the location of errors past this point.  */
656   error_gnat_node = Empty;
657 }
658 \f
659 /* Return a positive value if an lvalue is required for GNAT_NODE, which is
660    an N_Attribute_Reference.  */
661
662 static int
663 lvalue_required_for_attribute_p (Node_Id gnat_node)
664 {
665   switch (Get_Attribute_Id (Attribute_Name (gnat_node)))
666     {
667     case Attr_Pos:
668     case Attr_Val:
669     case Attr_Pred:
670     case Attr_Succ:
671     case Attr_First:
672     case Attr_Last:
673     case Attr_Range_Length:
674     case Attr_Length:
675     case Attr_Object_Size:
676     case Attr_Value_Size:
677     case Attr_Component_Size:
678     case Attr_Max_Size_In_Storage_Elements:
679     case Attr_Min:
680     case Attr_Max:
681     case Attr_Null_Parameter:
682     case Attr_Passed_By_Reference:
683     case Attr_Mechanism_Code:
684       return 0;
685
686     case Attr_Address:
687     case Attr_Access:
688     case Attr_Unchecked_Access:
689     case Attr_Unrestricted_Access:
690     case Attr_Code_Address:
691     case Attr_Pool_Address:
692     case Attr_Size:
693     case Attr_Alignment:
694     case Attr_Bit_Position:
695     case Attr_Position:
696     case Attr_First_Bit:
697     case Attr_Last_Bit:
698     case Attr_Bit:
699     default:
700       return 1;
701     }
702 }
703
704 /* Return a positive value if an lvalue is required for GNAT_NODE.  GNU_TYPE
705    is the type that will be used for GNAT_NODE in the translated GNU tree.
706    CONSTANT indicates whether the underlying object represented by GNAT_NODE
707    is constant in the Ada sense.  If it is, ADDRESS_OF_CONSTANT indicates
708    whether its value is the address of a constant and ALIASED whether it is
709    aliased.  If it isn't, ADDRESS_OF_CONSTANT and ALIASED are ignored.
710
711    The function climbs up the GNAT tree starting from the node and returns 1
712    upon encountering a node that effectively requires an lvalue downstream.
713    It returns int instead of bool to facilitate usage in non-purely binary
714    logic contexts.  */
715
716 static int
717 lvalue_required_p (Node_Id gnat_node, tree gnu_type, bool constant,
718                    bool address_of_constant, bool aliased)
719 {
720   Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
721
722   switch (Nkind (gnat_parent))
723     {
724     case N_Reference:
725       return 1;
726
727     case N_Attribute_Reference:
728       return lvalue_required_for_attribute_p (gnat_parent);
729
730     case N_Parameter_Association:
731     case N_Function_Call:
732     case N_Procedure_Call_Statement:
733       return (must_pass_by_ref (gnu_type) || default_pass_by_ref (gnu_type));
734
735     case N_Indexed_Component:
736       /* Only the array expression can require an lvalue.  */
737       if (Prefix (gnat_parent) != gnat_node)
738         return 0;
739
740       /* ??? Consider that referencing an indexed component with a
741          non-constant index forces the whole aggregate to memory.
742          Note that N_Integer_Literal is conservative, any static
743          expression in the RM sense could probably be accepted.  */
744       for (gnat_temp = First (Expressions (gnat_parent));
745            Present (gnat_temp);
746            gnat_temp = Next (gnat_temp))
747         if (Nkind (gnat_temp) != N_Integer_Literal)
748           return 1;
749
750       /* ... fall through ... */
751
752     case N_Slice:
753       /* Only the array expression can require an lvalue.  */
754       if (Prefix (gnat_parent) != gnat_node)
755         return 0;
756
757       aliased |= Has_Aliased_Components (Etype (gnat_node));
758       return lvalue_required_p (gnat_parent, gnu_type, constant,
759                                 address_of_constant, aliased);
760
761     case N_Selected_Component:
762       aliased |= Is_Aliased (Entity (Selector_Name (gnat_parent)));
763       return lvalue_required_p (gnat_parent, gnu_type, constant,
764                                 address_of_constant, aliased);
765
766     case N_Object_Renaming_Declaration:
767       /* We need to make a real renaming only if the constant object is
768          aliased or if we may use a renaming pointer; otherwise we can
769          optimize and return the rvalue.  We make an exception if the object
770          is an identifier since in this case the rvalue can be propagated
771          attached to the CONST_DECL.  */
772       return (!constant
773               || aliased
774               /* This should match the constant case of the renaming code.  */
775               || Is_Composite_Type
776                  (Underlying_Type (Etype (Name (gnat_parent))))
777               || Nkind (Name (gnat_parent)) == N_Identifier);
778
779     case N_Object_Declaration:
780       /* We cannot use a constructor if this is an atomic object because
781          the actual assignment might end up being done component-wise.  */
782       return ((Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
783                && Is_Atomic (Defining_Entity (gnat_parent)))
784               /* We don't use a constructor if this is a class-wide object
785                  because the effective type of the object is the equivalent
786                  type of the class-wide subtype and it smashes most of the
787                  data into an array of bytes to which we cannot convert.  */
788               || Ekind ((Etype (Defining_Entity (gnat_parent))))
789                  == E_Class_Wide_Subtype);
790
791     case N_Assignment_Statement:
792       /* We cannot use a constructor if the LHS is an atomic object because
793          the actual assignment might end up being done component-wise.  */
794       return (Name (gnat_parent) == gnat_node
795               || (Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
796                   && Is_Atomic (Entity (Name (gnat_parent)))));
797
798     case N_Type_Conversion:
799     case N_Qualified_Expression:
800       /* We must look through all conversions for composite types because we
801          may need to bypass an intermediate conversion to a narrower record
802          type that is generated for a formal conversion, e.g. the conversion
803          to the root type of a hierarchy of tagged types generated for the
804          formal conversion to the class-wide type.  */
805       if (!Is_Composite_Type (Underlying_Type (Etype (gnat_node))))
806         return 0;
807
808       /* ... fall through ... */
809
810     case N_Unchecked_Type_Conversion:
811       return lvalue_required_p (gnat_parent,
812                                 get_unpadded_type (Etype (gnat_parent)),
813                                 constant, address_of_constant, aliased);
814
815     case N_Allocator:
816       /* We should only reach here through the N_Qualified_Expression case
817          and, therefore, only for composite types.  Force an lvalue since
818          a block-copy to the newly allocated area of memory is made.  */
819       return 1;
820
821    case N_Explicit_Dereference:
822       /* We look through dereferences for address of constant because we need
823          to handle the special cases listed above.  */
824       if (constant && address_of_constant)
825         return lvalue_required_p (gnat_parent,
826                                   get_unpadded_type (Etype (gnat_parent)),
827                                   true, false, true);
828
829       /* ... fall through ... */
830
831     default:
832       return 0;
833     }
834
835   gcc_unreachable ();
836 }
837
838 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Identifier,
839    to a GCC tree, which is returned.  GNU_RESULT_TYPE_P is a pointer
840    to where we should place the result type.  */
841
842 static tree
843 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
844 {
845   Node_Id gnat_temp, gnat_temp_type;
846   tree gnu_result, gnu_result_type;
847
848   /* Whether we should require an lvalue for GNAT_NODE.  Needed in
849      specific circumstances only, so evaluated lazily.  < 0 means
850      unknown, > 0 means known true, 0 means known false.  */
851   int require_lvalue = -1;
852
853   /* If GNAT_NODE is a constant, whether we should use the initialization
854      value instead of the constant entity, typically for scalars with an
855      address clause when the parent doesn't require an lvalue.  */
856   bool use_constant_initializer = false;
857
858   /* If the Etype of this node does not equal the Etype of the Entity,
859      something is wrong with the entity map, probably in generic
860      instantiation. However, this does not apply to types. Since we sometime
861      have strange Ekind's, just do this test for objects. Also, if the Etype of
862      the Entity is private, the Etype of the N_Identifier is allowed to be the
863      full type and also we consider a packed array type to be the same as the
864      original type. Similarly, a class-wide type is equivalent to a subtype of
865      itself. Finally, if the types are Itypes, one may be a copy of the other,
866      which is also legal.  */
867   gnat_temp = (Nkind (gnat_node) == N_Defining_Identifier
868                ? gnat_node : Entity (gnat_node));
869   gnat_temp_type = Etype (gnat_temp);
870
871   gcc_assert (Etype (gnat_node) == gnat_temp_type
872               || (Is_Packed (gnat_temp_type)
873                   && Etype (gnat_node) == Packed_Array_Type (gnat_temp_type))
874               || (Is_Class_Wide_Type (Etype (gnat_node)))
875               || (IN (Ekind (gnat_temp_type), Private_Kind)
876                   && Present (Full_View (gnat_temp_type))
877                   && ((Etype (gnat_node) == Full_View (gnat_temp_type))
878                       || (Is_Packed (Full_View (gnat_temp_type))
879                           && (Etype (gnat_node)
880                               == Packed_Array_Type (Full_View
881                                                     (gnat_temp_type))))))
882               || (Is_Itype (Etype (gnat_node)) && Is_Itype (gnat_temp_type))
883               || !(Ekind (gnat_temp) == E_Variable
884                    || Ekind (gnat_temp) == E_Component
885                    || Ekind (gnat_temp) == E_Constant
886                    || Ekind (gnat_temp) == E_Loop_Parameter
887                    || IN (Ekind (gnat_temp), Formal_Kind)));
888
889   /* If this is a reference to a deferred constant whose partial view is an
890      unconstrained private type, the proper type is on the full view of the
891      constant, not on the full view of the type, which may be unconstrained.
892
893      This may be a reference to a type, for example in the prefix of the
894      attribute Position, generated for dispatching code (see Make_DT in
895      exp_disp,adb). In that case we need the type itself, not is parent,
896      in particular if it is a derived type  */
897   if (Is_Private_Type (gnat_temp_type)
898       && Has_Unknown_Discriminants (gnat_temp_type)
899       && Ekind (gnat_temp) == E_Constant
900       && Present (Full_View (gnat_temp)))
901     {
902       gnat_temp = Full_View (gnat_temp);
903       gnat_temp_type = Etype (gnat_temp);
904     }
905   else
906     {
907       /* We want to use the Actual_Subtype if it has already been elaborated,
908          otherwise the Etype.  Avoid using Actual_Subtype for packed arrays to
909          simplify things.  */
910       if ((Ekind (gnat_temp) == E_Constant
911            || Ekind (gnat_temp) == E_Variable || Is_Formal (gnat_temp))
912           && !(Is_Array_Type (Etype (gnat_temp))
913                && Present (Packed_Array_Type (Etype (gnat_temp))))
914           && Present (Actual_Subtype (gnat_temp))
915           && present_gnu_tree (Actual_Subtype (gnat_temp)))
916         gnat_temp_type = Actual_Subtype (gnat_temp);
917       else
918         gnat_temp_type = Etype (gnat_node);
919     }
920
921   /* Expand the type of this identifier first, in case it is an enumeral
922      literal, which only get made when the type is expanded.  There is no
923      order-of-elaboration issue here.  */
924   gnu_result_type = get_unpadded_type (gnat_temp_type);
925
926   /* If this is a non-imported scalar constant with an address clause,
927      retrieve the value instead of a pointer to be dereferenced unless
928      an lvalue is required.  This is generally more efficient and actually
929      required if this is a static expression because it might be used
930      in a context where a dereference is inappropriate, such as a case
931      statement alternative or a record discriminant.  There is no possible
932      volatile-ness short-circuit here since Volatile constants must bei
933      imported per C.6.  */
934   if (Ekind (gnat_temp) == E_Constant
935       && Is_Scalar_Type (gnat_temp_type)
936       && !Is_Imported (gnat_temp)
937       && Present (Address_Clause (gnat_temp)))
938     {
939       require_lvalue = lvalue_required_p (gnat_node, gnu_result_type, true,
940                                           false, Is_Aliased (gnat_temp));
941       use_constant_initializer = !require_lvalue;
942     }
943
944   if (use_constant_initializer)
945     {
946       /* If this is a deferred constant, the initializer is attached to
947          the full view.  */
948       if (Present (Full_View (gnat_temp)))
949         gnat_temp = Full_View (gnat_temp);
950
951       gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_temp)));
952     }
953   else
954     gnu_result = gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0);
955
956   /* If we are in an exception handler, force this variable into memory to
957      ensure optimization does not remove stores that appear redundant but are
958      actually needed in case an exception occurs.
959
960      ??? Note that we need not do this if the variable is declared within the
961      handler, only if it is referenced in the handler and declared in an
962      enclosing block, but we have no way of testing that right now.
963
964      ??? We used to essentially set the TREE_ADDRESSABLE flag on the variable
965      here, but it can now be removed by the Tree aliasing machinery if the
966      address of the variable is never taken.  All we can do is to make the
967      variable volatile, which might incur the generation of temporaries just
968      to access the memory in some circumstances.  This can be avoided for
969      variables of non-constant size because they are automatically allocated
970      to memory.  There might be no way of allocating a proper temporary for
971      them in any case.  We only do this for SJLJ though.  */
972   if (TREE_VALUE (gnu_except_ptr_stack)
973       && TREE_CODE (gnu_result) == VAR_DECL
974       && TREE_CODE (DECL_SIZE_UNIT (gnu_result)) == INTEGER_CST)
975     TREE_THIS_VOLATILE (gnu_result) = TREE_SIDE_EFFECTS (gnu_result) = 1;
976
977   /* Some objects (such as parameters passed by reference, globals of
978      variable size, and renamed objects) actually represent the address
979      of the object.  In that case, we must do the dereference.  Likewise,
980      deal with parameters to foreign convention subprograms.  */
981   if (DECL_P (gnu_result)
982       && (DECL_BY_REF_P (gnu_result)
983           || (TREE_CODE (gnu_result) == PARM_DECL
984               && DECL_BY_COMPONENT_PTR_P (gnu_result))))
985     {
986       const bool read_only = DECL_POINTS_TO_READONLY_P (gnu_result);
987       tree renamed_obj;
988
989       if (TREE_CODE (gnu_result) == PARM_DECL
990           && DECL_BY_COMPONENT_PTR_P (gnu_result))
991         gnu_result
992           = build_unary_op (INDIRECT_REF, NULL_TREE,
993                             convert (build_pointer_type (gnu_result_type),
994                                      gnu_result));
995
996       /* If it's a renaming pointer and we are at the right binding level,
997          we can reference the renamed object directly, since the renamed
998          expression has been protected against multiple evaluations.  */
999       else if (TREE_CODE (gnu_result) == VAR_DECL
1000                && (renamed_obj = DECL_RENAMED_OBJECT (gnu_result))
1001                && (!DECL_RENAMING_GLOBAL_P (gnu_result)
1002                    || global_bindings_p ()))
1003         gnu_result = renamed_obj;
1004
1005       /* Return the underlying CST for a CONST_DECL like a few lines below,
1006          after dereferencing in this case.  */
1007       else if (TREE_CODE (gnu_result) == CONST_DECL)
1008         gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE,
1009                                      DECL_INITIAL (gnu_result));
1010
1011       else
1012         gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1013
1014       if (read_only)
1015         TREE_READONLY (gnu_result) = 1;
1016     }
1017
1018   /* The GNAT tree has the type of a function as the type of its result.  Also
1019      use the type of the result if the Etype is a subtype which is nominally
1020      unconstrained.  But remove any padding from the resulting type.  */
1021   if (TREE_CODE (TREE_TYPE (gnu_result)) == FUNCTION_TYPE
1022       || Is_Constr_Subt_For_UN_Aliased (gnat_temp_type))
1023     {
1024       gnu_result_type = TREE_TYPE (gnu_result);
1025       if (TYPE_IS_PADDING_P (gnu_result_type))
1026         gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
1027     }
1028
1029   /* If we have a constant declaration and its initializer at hand,
1030      try to return the latter to avoid the need to call fold in lots
1031      of places and the need of elaboration code if this Id is used as
1032      an initializer itself.  */
1033   if (TREE_CONSTANT (gnu_result)
1034       && DECL_P (gnu_result)
1035       && DECL_INITIAL (gnu_result))
1036     {
1037       bool constant_only = (TREE_CODE (gnu_result) == CONST_DECL
1038                             && !DECL_CONST_CORRESPONDING_VAR (gnu_result));
1039       bool address_of_constant = (TREE_CODE (gnu_result) == CONST_DECL
1040                                   && DECL_CONST_ADDRESS_P (gnu_result));
1041
1042       /* If there is a (corresponding) variable or this is the address of a
1043          constant, we only want to return the initializer if an lvalue isn't
1044          required.  Evaluate this now if we have not already done so.  */
1045       if ((!constant_only || address_of_constant) && require_lvalue < 0)
1046         require_lvalue
1047           = lvalue_required_p (gnat_node, gnu_result_type, true,
1048                                address_of_constant, Is_Aliased (gnat_temp));
1049
1050       if ((constant_only && !address_of_constant) || !require_lvalue)
1051         gnu_result = unshare_expr (DECL_INITIAL (gnu_result));
1052     }
1053
1054   *gnu_result_type_p = gnu_result_type;
1055   return gnu_result;
1056 }
1057 \f
1058 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Pragma.  Return
1059    any statements we generate.  */
1060
1061 static tree
1062 Pragma_to_gnu (Node_Id gnat_node)
1063 {
1064   Node_Id gnat_temp;
1065   tree gnu_result = alloc_stmt_list ();
1066
1067   /* Check for (and ignore) unrecognized pragma and do nothing if we are just
1068      annotating types.  */
1069   if (type_annotate_only
1070       || !Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
1071     return gnu_result;
1072
1073   switch (Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node))))
1074     {
1075     case Pragma_Inspection_Point:
1076       /* Do nothing at top level: all such variables are already viewable.  */
1077       if (global_bindings_p ())
1078         break;
1079
1080       for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1081            Present (gnat_temp);
1082            gnat_temp = Next (gnat_temp))
1083         {
1084           Node_Id gnat_expr = Expression (gnat_temp);
1085           tree gnu_expr = gnat_to_gnu (gnat_expr);
1086           int use_address;
1087           enum machine_mode mode;
1088           tree asm_constraint = NULL_TREE;
1089 #ifdef ASM_COMMENT_START
1090           char *comment;
1091 #endif
1092
1093           if (TREE_CODE (gnu_expr) == UNCONSTRAINED_ARRAY_REF)
1094             gnu_expr = TREE_OPERAND (gnu_expr, 0);
1095
1096           /* Use the value only if it fits into a normal register,
1097              otherwise use the address.  */
1098           mode = TYPE_MODE (TREE_TYPE (gnu_expr));
1099           use_address = ((GET_MODE_CLASS (mode) != MODE_INT
1100                           && GET_MODE_CLASS (mode) != MODE_PARTIAL_INT)
1101                          || GET_MODE_SIZE (mode) > UNITS_PER_WORD);
1102
1103           if (use_address)
1104             gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
1105
1106 #ifdef ASM_COMMENT_START
1107           comment = concat (ASM_COMMENT_START,
1108                             " inspection point: ",
1109                             Get_Name_String (Chars (gnat_expr)),
1110                             use_address ? " address" : "",
1111                             " is in %0",
1112                             NULL);
1113           asm_constraint = build_string (strlen (comment), comment);
1114           free (comment);
1115 #endif
1116           gnu_expr = build5 (ASM_EXPR, void_type_node,
1117                              asm_constraint,
1118                              NULL_TREE,
1119                              tree_cons
1120                              (build_tree_list (NULL_TREE,
1121                                                build_string (1, "g")),
1122                               gnu_expr, NULL_TREE),
1123                              NULL_TREE, NULL_TREE);
1124           ASM_VOLATILE_P (gnu_expr) = 1;
1125           set_expr_location_from_node (gnu_expr, gnat_node);
1126           append_to_statement_list (gnu_expr, &gnu_result);
1127         }
1128       break;
1129
1130     case Pragma_Optimize:
1131       switch (Chars (Expression
1132                      (First (Pragma_Argument_Associations (gnat_node)))))
1133         {
1134         case Name_Time:  case Name_Space:
1135           if (!optimize)
1136             post_error ("insufficient -O value?", gnat_node);
1137           break;
1138
1139         case Name_Off:
1140           if (optimize)
1141             post_error ("must specify -O0?", gnat_node);
1142           break;
1143
1144         default:
1145           gcc_unreachable ();
1146         }
1147       break;
1148
1149     case Pragma_Reviewable:
1150       if (write_symbols == NO_DEBUG)
1151         post_error ("must specify -g?", gnat_node);
1152       break;
1153     }
1154
1155   return gnu_result;
1156 }
1157 \f
1158 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Attribute node,
1159    to a GCC tree, which is returned.  GNU_RESULT_TYPE_P is a pointer to
1160    where we should place the result type.  ATTRIBUTE is the attribute ID.  */
1161
1162 static tree
1163 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
1164 {
1165   tree gnu_prefix = gnat_to_gnu (Prefix (gnat_node));
1166   tree gnu_type = TREE_TYPE (gnu_prefix);
1167   tree gnu_expr, gnu_result_type, gnu_result = error_mark_node;
1168   bool prefix_unused = false;
1169
1170   /* If the input is a NULL_EXPR, make a new one.  */
1171   if (TREE_CODE (gnu_prefix) == NULL_EXPR)
1172     {
1173       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1174       *gnu_result_type_p = gnu_result_type;
1175       return build1 (NULL_EXPR, gnu_result_type, TREE_OPERAND (gnu_prefix, 0));
1176     }
1177
1178   switch (attribute)
1179     {
1180     case Attr_Pos:
1181     case Attr_Val:
1182       /* These are just conversions since representation clauses for
1183          enumeration types are handled in the front-end.  */
1184       {
1185         bool checkp = Do_Range_Check (First (Expressions (gnat_node)));
1186         gnu_result = gnat_to_gnu (First (Expressions (gnat_node)));
1187         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1188         gnu_result = convert_with_check (Etype (gnat_node), gnu_result,
1189                                          checkp, checkp, true, gnat_node);
1190       }
1191       break;
1192
1193     case Attr_Pred:
1194     case Attr_Succ:
1195       /* These just add or subtract the constant 1 since representation
1196          clauses for enumeration types are handled in the front-end.  */
1197       gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
1198       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1199
1200       if (Do_Range_Check (First (Expressions (gnat_node))))
1201         {
1202           gnu_expr = gnat_protect_expr (gnu_expr);
1203           gnu_expr
1204             = emit_check
1205               (build_binary_op (EQ_EXPR, integer_type_node,
1206                                 gnu_expr,
1207                                 attribute == Attr_Pred
1208                                 ? TYPE_MIN_VALUE (gnu_result_type)
1209                                 : TYPE_MAX_VALUE (gnu_result_type)),
1210                gnu_expr, CE_Range_Check_Failed, gnat_node);
1211         }
1212
1213       gnu_result
1214         = build_binary_op (attribute == Attr_Pred ? MINUS_EXPR : PLUS_EXPR,
1215                            gnu_result_type, gnu_expr,
1216                            convert (gnu_result_type, integer_one_node));
1217       break;
1218
1219     case Attr_Address:
1220     case Attr_Unrestricted_Access:
1221       /* Conversions don't change addresses but can cause us to miss the
1222          COMPONENT_REF case below, so strip them off.  */
1223       gnu_prefix = remove_conversions (gnu_prefix,
1224                                        !Must_Be_Byte_Aligned (gnat_node));
1225
1226       /* If we are taking 'Address of an unconstrained object, this is the
1227          pointer to the underlying array.  */
1228       if (attribute == Attr_Address)
1229         gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1230
1231       /* If we are building a static dispatch table, we have to honor
1232          TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
1233          with the C++ ABI.  We do it in the non-static case as well,
1234          see gnat_to_gnu_entity, case E_Access_Subprogram_Type.  */
1235       else if (TARGET_VTABLE_USES_DESCRIPTORS
1236                && Is_Dispatch_Table_Entity (Etype (gnat_node)))
1237         {
1238           tree gnu_field, gnu_list = NULL_TREE, t;
1239           /* Descriptors can only be built here for top-level functions.  */
1240           bool build_descriptor = (global_bindings_p () != 0);
1241           int i;
1242
1243           gnu_result_type = get_unpadded_type (Etype (gnat_node));
1244
1245           /* If we're not going to build the descriptor, we have to retrieve
1246              the one which will be built by the linker (or by the compiler
1247              later if a static chain is requested).  */
1248           if (!build_descriptor)
1249             {
1250               gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
1251               gnu_result = fold_convert (build_pointer_type (gnu_result_type),
1252                                          gnu_result);
1253               gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
1254             }
1255
1256           for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
1257                i < TARGET_VTABLE_USES_DESCRIPTORS;
1258                gnu_field = TREE_CHAIN (gnu_field), i++)
1259             {
1260               if (build_descriptor)
1261                 {
1262                   t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
1263                               build_int_cst (NULL_TREE, i));
1264                   TREE_CONSTANT (t) = 1;
1265                 }
1266               else
1267                 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
1268                             gnu_field, NULL_TREE);
1269
1270               gnu_list = tree_cons (gnu_field, t, gnu_list);
1271             }
1272
1273           gnu_result = gnat_build_constructor (gnu_result_type, gnu_list);
1274           break;
1275         }
1276
1277       /* ... fall through ... */
1278
1279     case Attr_Access:
1280     case Attr_Unchecked_Access:
1281     case Attr_Code_Address:
1282       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1283       gnu_result
1284         = build_unary_op (((attribute == Attr_Address
1285                             || attribute == Attr_Unrestricted_Access)
1286                            && !Must_Be_Byte_Aligned (gnat_node))
1287                           ? ATTR_ADDR_EXPR : ADDR_EXPR,
1288                           gnu_result_type, gnu_prefix);
1289
1290       /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
1291          don't try to build a trampoline.  */
1292       if (attribute == Attr_Code_Address)
1293         {
1294           for (gnu_expr = gnu_result;
1295                CONVERT_EXPR_P (gnu_expr);
1296                gnu_expr = TREE_OPERAND (gnu_expr, 0))
1297             TREE_CONSTANT (gnu_expr) = 1;
1298
1299           if (TREE_CODE (gnu_expr) == ADDR_EXPR)
1300             TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
1301         }
1302
1303       /* For other address attributes applied to a nested function,
1304          find an inner ADDR_EXPR and annotate it so that we can issue
1305          a useful warning with -Wtrampolines.  */
1306       else if (TREE_CODE (TREE_TYPE (gnu_prefix)) == FUNCTION_TYPE)
1307         {
1308           for (gnu_expr = gnu_result;
1309                CONVERT_EXPR_P (gnu_expr);
1310                gnu_expr = TREE_OPERAND (gnu_expr, 0))
1311             ;
1312
1313           if (TREE_CODE (gnu_expr) == ADDR_EXPR
1314               && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
1315             {
1316               set_expr_location_from_node (gnu_expr, gnat_node);
1317
1318               /* Check that we're not violating the No_Implicit_Dynamic_Code
1319                  restriction.  Be conservative if we don't know anything
1320                  about the trampoline strategy for the target.  */
1321               Check_Implicit_Dynamic_Code_Allowed (gnat_node);
1322             }
1323         }
1324       break;
1325
1326     case Attr_Pool_Address:
1327       {
1328         tree gnu_obj_type;
1329         tree gnu_ptr = gnu_prefix;
1330
1331         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1332
1333         /* If this is an unconstrained array, we know the object has been
1334            allocated with the template in front of the object.  So compute
1335            the template address.  */
1336         if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
1337           gnu_ptr
1338             = convert (build_pointer_type
1339                        (TYPE_OBJECT_RECORD_TYPE
1340                         (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
1341                        gnu_ptr);
1342
1343         gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
1344         if (TREE_CODE (gnu_obj_type) == RECORD_TYPE
1345             && TYPE_CONTAINS_TEMPLATE_P (gnu_obj_type))
1346           {
1347             tree gnu_char_ptr_type = build_pointer_type (char_type_node);
1348             tree gnu_pos = byte_position (TYPE_FIELDS (gnu_obj_type));
1349             tree gnu_byte_offset
1350               = convert (sizetype,
1351                          size_diffop (size_zero_node, gnu_pos));
1352             gnu_byte_offset = fold_build1 (NEGATE_EXPR, sizetype, gnu_byte_offset);
1353
1354             gnu_ptr = convert (gnu_char_ptr_type, gnu_ptr);
1355             gnu_ptr = build_binary_op (POINTER_PLUS_EXPR, gnu_char_ptr_type,
1356                                        gnu_ptr, gnu_byte_offset);
1357           }
1358
1359         gnu_result = convert (gnu_result_type, gnu_ptr);
1360       }
1361       break;
1362
1363     case Attr_Size:
1364     case Attr_Object_Size:
1365     case Attr_Value_Size:
1366     case Attr_Max_Size_In_Storage_Elements:
1367       gnu_expr = gnu_prefix;
1368
1369       /* Remove NOPs and conversions between original and packable version
1370          from GNU_EXPR, and conversions from GNU_PREFIX.  We use GNU_EXPR
1371          to see if a COMPONENT_REF was involved.  */
1372       while (TREE_CODE (gnu_expr) == NOP_EXPR
1373              || (TREE_CODE (gnu_expr) == VIEW_CONVERT_EXPR
1374                  && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
1375                  && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
1376                     == RECORD_TYPE
1377                  && TYPE_NAME (TREE_TYPE (gnu_expr))
1378                     == TYPE_NAME (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))))
1379         gnu_expr = TREE_OPERAND (gnu_expr, 0);
1380
1381       gnu_prefix = remove_conversions (gnu_prefix, true);
1382       prefix_unused = true;
1383       gnu_type = TREE_TYPE (gnu_prefix);
1384
1385       /* Replace an unconstrained array type with the type of the underlying
1386          array.  We can't do this with a call to maybe_unconstrained_array
1387          since we may have a TYPE_DECL.  For 'Max_Size_In_Storage_Elements,
1388          use the record type that will be used to allocate the object and its
1389          template.  */
1390       if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1391         {
1392           gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1393           if (attribute != Attr_Max_Size_In_Storage_Elements)
1394             gnu_type = TREE_TYPE (TREE_CHAIN (TYPE_FIELDS (gnu_type)));
1395         }
1396
1397       /* If we're looking for the size of a field, return the field size.
1398          Otherwise, if the prefix is an object, or if we're looking for
1399          'Object_Size or 'Max_Size_In_Storage_Elements, the result is the
1400          GCC size of the type.  Otherwise, it is the RM size of the type.  */
1401       if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1402         gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
1403       else if (TREE_CODE (gnu_prefix) != TYPE_DECL
1404                || attribute == Attr_Object_Size
1405                || attribute == Attr_Max_Size_In_Storage_Elements)
1406         {
1407           /* If the prefix is an object of a padded type, the GCC size isn't
1408              relevant to the programmer.  Normally what we want is the RM size,
1409              which was set from the specified size, but if it was not set, we
1410              want the size of the field.  Using the MAX of those two produces
1411              the right result in all cases.  Don't use the size of the field
1412              if it's self-referential, since that's never what's wanted.  */
1413           if (TREE_CODE (gnu_prefix) != TYPE_DECL
1414               && TYPE_IS_PADDING_P (gnu_type)
1415               && TREE_CODE (gnu_expr) == COMPONENT_REF)
1416             {
1417               gnu_result = rm_size (gnu_type);
1418               if (!CONTAINS_PLACEHOLDER_P
1419                    (DECL_SIZE (TREE_OPERAND (gnu_expr, 1))))
1420                 gnu_result
1421                   = size_binop (MAX_EXPR, gnu_result,
1422                                 DECL_SIZE (TREE_OPERAND (gnu_expr, 1)));
1423             }
1424           else if (Nkind (Prefix (gnat_node)) == N_Explicit_Dereference)
1425             {
1426               Node_Id gnat_deref = Prefix (gnat_node);
1427               Node_Id gnat_actual_subtype
1428                 = Actual_Designated_Subtype (gnat_deref);
1429               tree gnu_ptr_type
1430                 = TREE_TYPE (gnat_to_gnu (Prefix (gnat_deref)));
1431
1432               if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
1433                   && Present (gnat_actual_subtype))
1434                 {
1435                   tree gnu_actual_obj_type
1436                     = gnat_to_gnu_type (gnat_actual_subtype);
1437                   gnu_type
1438                     = build_unc_object_type_from_ptr (gnu_ptr_type,
1439                                                       gnu_actual_obj_type,
1440                                                       get_identifier ("SIZE"));
1441                 }
1442
1443               gnu_result = TYPE_SIZE (gnu_type);
1444             }
1445           else
1446             gnu_result = TYPE_SIZE (gnu_type);
1447         }
1448       else
1449         gnu_result = rm_size (gnu_type);
1450
1451       gcc_assert (gnu_result);
1452
1453       /* Deal with a self-referential size by returning the maximum size for
1454          a type and by qualifying the size with the object for 'Size of an
1455          object.  */
1456       if (CONTAINS_PLACEHOLDER_P (gnu_result))
1457         {
1458           if (TREE_CODE (gnu_prefix) != TYPE_DECL)
1459             gnu_result = substitute_placeholder_in_expr (gnu_result, gnu_expr);
1460           else
1461             gnu_result = max_size (gnu_result, true);
1462         }
1463
1464       /* If the type contains a template, subtract its size.  */
1465       if (TREE_CODE (gnu_type) == RECORD_TYPE
1466           && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
1467         gnu_result = size_binop (MINUS_EXPR, gnu_result,
1468                                  DECL_SIZE (TYPE_FIELDS (gnu_type)));
1469
1470       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1471
1472       if (attribute == Attr_Max_Size_In_Storage_Elements)
1473         gnu_result = fold_build2 (CEIL_DIV_EXPR, bitsizetype,
1474                                   gnu_result, bitsize_unit_node);
1475       break;
1476
1477     case Attr_Alignment:
1478       {
1479         unsigned int align;
1480
1481         if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1482             && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1483           gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1484
1485         gnu_type = TREE_TYPE (gnu_prefix);
1486         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1487         prefix_unused = true;
1488
1489         if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1490           align = DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1)) / BITS_PER_UNIT;
1491         else
1492           {
1493             Node_Id gnat_prefix = Prefix (gnat_node);
1494             Entity_Id gnat_type = Etype (gnat_prefix);
1495             unsigned int double_align;
1496             bool is_capped_double, align_clause;
1497
1498             /* If the default alignment of "double" or larger scalar types is
1499                specifically capped and there is an alignment clause neither
1500                on the type nor on the prefix itself, return the cap.  */
1501             if ((double_align = double_float_alignment) > 0)
1502               is_capped_double
1503                 = is_double_float_or_array (gnat_type, &align_clause);
1504             else if ((double_align = double_scalar_alignment) > 0)
1505               is_capped_double
1506                 = is_double_scalar_or_array (gnat_type, &align_clause);
1507             else
1508               is_capped_double = align_clause = false;
1509
1510             if (is_capped_double
1511                 && Nkind (gnat_prefix) == N_Identifier
1512                 && Present (Alignment_Clause (Entity (gnat_prefix))))
1513               align_clause = true;
1514
1515             if (is_capped_double && !align_clause)
1516               align = double_align;
1517             else
1518               align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
1519           }
1520
1521         gnu_result = size_int (align);
1522       }
1523       break;
1524
1525     case Attr_First:
1526     case Attr_Last:
1527     case Attr_Range_Length:
1528       prefix_unused = true;
1529
1530       if (INTEGRAL_TYPE_P (gnu_type) || TREE_CODE (gnu_type) == REAL_TYPE)
1531         {
1532           gnu_result_type = get_unpadded_type (Etype (gnat_node));
1533
1534           if (attribute == Attr_First)
1535             gnu_result = TYPE_MIN_VALUE (gnu_type);
1536           else if (attribute == Attr_Last)
1537             gnu_result = TYPE_MAX_VALUE (gnu_type);
1538           else
1539             gnu_result
1540               = build_binary_op
1541                 (MAX_EXPR, get_base_type (gnu_result_type),
1542                  build_binary_op
1543                  (PLUS_EXPR, get_base_type (gnu_result_type),
1544                   build_binary_op (MINUS_EXPR,
1545                                    get_base_type (gnu_result_type),
1546                                    convert (gnu_result_type,
1547                                             TYPE_MAX_VALUE (gnu_type)),
1548                                    convert (gnu_result_type,
1549                                             TYPE_MIN_VALUE (gnu_type))),
1550                   convert (gnu_result_type, integer_one_node)),
1551                  convert (gnu_result_type, integer_zero_node));
1552
1553           break;
1554         }
1555
1556       /* ... fall through ... */
1557
1558     case Attr_Length:
1559       {
1560         int Dimension = (Present (Expressions (gnat_node))
1561                          ? UI_To_Int (Intval (First (Expressions (gnat_node))))
1562                          : 1), i;
1563         struct parm_attr_d *pa = NULL;
1564         Entity_Id gnat_param = Empty;
1565
1566         /* Make sure any implicit dereference gets done.  */
1567         gnu_prefix = maybe_implicit_deref (gnu_prefix);
1568         gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1569         /* We treat unconstrained array In parameters specially.  */
1570         if (Nkind (Prefix (gnat_node)) == N_Identifier
1571             && !Is_Constrained (Etype (Prefix (gnat_node)))
1572             && Ekind (Entity (Prefix (gnat_node))) == E_In_Parameter)
1573           gnat_param = Entity (Prefix (gnat_node));
1574         gnu_type = TREE_TYPE (gnu_prefix);
1575         prefix_unused = true;
1576         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1577
1578         if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
1579           {
1580             int ndim;
1581             tree gnu_type_temp;
1582
1583             for (ndim = 1, gnu_type_temp = gnu_type;
1584                  TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
1585                  && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
1586                  ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
1587               ;
1588
1589             Dimension = ndim + 1 - Dimension;
1590           }
1591
1592         for (i = 1; i < Dimension; i++)
1593           gnu_type = TREE_TYPE (gnu_type);
1594
1595         gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
1596
1597         /* When not optimizing, look up the slot associated with the parameter
1598            and the dimension in the cache and create a new one on failure.  */
1599         if (!optimize && Present (gnat_param))
1600           {
1601             for (i = 0; VEC_iterate (parm_attr, f_parm_attr_cache, i, pa); i++)
1602               if (pa->id == gnat_param && pa->dim == Dimension)
1603                 break;
1604
1605             if (!pa)
1606               {
1607                 pa = GGC_CNEW (struct parm_attr_d);
1608                 pa->id = gnat_param;
1609                 pa->dim = Dimension;
1610                 VEC_safe_push (parm_attr, gc, f_parm_attr_cache, pa);
1611               }
1612           }
1613
1614         /* Return the cached expression or build a new one.  */
1615         if (attribute == Attr_First)
1616           {
1617             if (pa && pa->first)
1618               {
1619                 gnu_result = pa->first;
1620                 break;
1621               }
1622
1623             gnu_result
1624               = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
1625           }
1626
1627         else if (attribute == Attr_Last)
1628           {
1629             if (pa && pa->last)
1630               {
1631                 gnu_result = pa->last;
1632                 break;
1633               }
1634
1635             gnu_result
1636               = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
1637           }
1638
1639         else /* attribute == Attr_Range_Length || attribute == Attr_Length  */
1640           {
1641             if (pa && pa->length)
1642               {
1643                 gnu_result = pa->length;
1644                 break;
1645               }
1646             else
1647               {
1648                 /* We used to compute the length as max (hb - lb + 1, 0),
1649                    which could overflow for some cases of empty arrays, e.g.
1650                    when lb == index_type'first.  We now compute the length as
1651                    (hb >= lb) ? hb - lb + 1 : 0, which would only overflow in
1652                    much rarer cases, for extremely large arrays we expect
1653                    never to encounter in practice.  In addition, the former
1654                    computation required the use of potentially constraining
1655                    signed arithmetic while the latter doesn't.  Note that
1656                    the comparison must be done in the original index type,
1657                    to avoid any overflow during the conversion.  */
1658                 tree comp_type = get_base_type (gnu_result_type);
1659                 tree index_type = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
1660                 tree lb = TYPE_MIN_VALUE (index_type);
1661                 tree hb = TYPE_MAX_VALUE (index_type);
1662                 gnu_result
1663                   = build_binary_op (PLUS_EXPR, comp_type,
1664                                      build_binary_op (MINUS_EXPR,
1665                                                       comp_type,
1666                                                       convert (comp_type, hb),
1667                                                       convert (comp_type, lb)),
1668                                      convert (comp_type, integer_one_node));
1669                 gnu_result
1670                   = build_cond_expr (comp_type,
1671                                      build_binary_op (GE_EXPR,
1672                                                       integer_type_node,
1673                                                       hb, lb),
1674                                      gnu_result,
1675                                      convert (comp_type, integer_zero_node));
1676               }
1677           }
1678
1679         /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
1680            handling.  Note that these attributes could not have been used on
1681            an unconstrained array type.  */
1682         gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
1683
1684         /* Cache the expression we have just computed.  Since we want to do it
1685            at runtime, we force the use of a SAVE_EXPR and let the gimplifier
1686            create the temporary.  */
1687         if (pa)
1688           {
1689             gnu_result
1690               = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
1691             TREE_SIDE_EFFECTS (gnu_result) = 1;
1692             if (attribute == Attr_First)
1693               pa->first = gnu_result;
1694             else if (attribute == Attr_Last)
1695               pa->last = gnu_result;
1696             else
1697               pa->length = gnu_result;
1698           }
1699
1700         /* Set the source location onto the predicate of the condition in the
1701            'Length case but do not do it if the expression is cached to avoid
1702            messing up the debug info.  */
1703         else if ((attribute == Attr_Range_Length || attribute == Attr_Length)
1704                  && TREE_CODE (gnu_result) == COND_EXPR
1705                  && EXPR_P (TREE_OPERAND (gnu_result, 0)))
1706           set_expr_location_from_node (TREE_OPERAND (gnu_result, 0),
1707                                        gnat_node);
1708
1709         break;
1710       }
1711
1712     case Attr_Bit_Position:
1713     case Attr_Position:
1714     case Attr_First_Bit:
1715     case Attr_Last_Bit:
1716     case Attr_Bit:
1717       {
1718         HOST_WIDE_INT bitsize;
1719         HOST_WIDE_INT bitpos;
1720         tree gnu_offset;
1721         tree gnu_field_bitpos;
1722         tree gnu_field_offset;
1723         tree gnu_inner;
1724         enum machine_mode mode;
1725         int unsignedp, volatilep;
1726
1727         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1728         gnu_prefix = remove_conversions (gnu_prefix, true);
1729         prefix_unused = true;
1730
1731         /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
1732            the result is 0.  Don't allow 'Bit on a bare component, though.  */
1733         if (attribute == Attr_Bit
1734             && TREE_CODE (gnu_prefix) != COMPONENT_REF
1735             && TREE_CODE (gnu_prefix) != FIELD_DECL)
1736           {
1737             gnu_result = integer_zero_node;
1738             break;
1739           }
1740
1741         else
1742           gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
1743                       || (attribute == Attr_Bit_Position
1744                           && TREE_CODE (gnu_prefix) == FIELD_DECL));
1745
1746         get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
1747                              &mode, &unsignedp, &volatilep, false);
1748
1749         if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1750           {
1751             gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
1752             gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
1753
1754             for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
1755                  TREE_CODE (gnu_inner) == COMPONENT_REF
1756                  && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
1757                  gnu_inner = TREE_OPERAND (gnu_inner, 0))
1758               {
1759                 gnu_field_bitpos
1760                   = size_binop (PLUS_EXPR, gnu_field_bitpos,
1761                                 bit_position (TREE_OPERAND (gnu_inner, 1)));
1762                 gnu_field_offset
1763                   = size_binop (PLUS_EXPR, gnu_field_offset,
1764                                 byte_position (TREE_OPERAND (gnu_inner, 1)));
1765               }
1766           }
1767         else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
1768           {
1769             gnu_field_bitpos = bit_position (gnu_prefix);
1770             gnu_field_offset = byte_position (gnu_prefix);
1771           }
1772         else
1773           {
1774             gnu_field_bitpos = bitsize_zero_node;
1775             gnu_field_offset = size_zero_node;
1776           }
1777
1778         switch (attribute)
1779           {
1780           case Attr_Position:
1781             gnu_result = gnu_field_offset;
1782             break;
1783
1784           case Attr_First_Bit:
1785           case Attr_Bit:
1786             gnu_result = size_int (bitpos % BITS_PER_UNIT);
1787             break;
1788
1789           case Attr_Last_Bit:
1790             gnu_result = bitsize_int (bitpos % BITS_PER_UNIT);
1791             gnu_result = size_binop (PLUS_EXPR, gnu_result,
1792                                      TYPE_SIZE (TREE_TYPE (gnu_prefix)));
1793             gnu_result = size_binop (MINUS_EXPR, gnu_result,
1794                                      bitsize_one_node);
1795             break;
1796
1797           case Attr_Bit_Position:
1798             gnu_result = gnu_field_bitpos;
1799             break;
1800                 }
1801
1802         /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
1803            handling.  */
1804         gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
1805         break;
1806       }
1807
1808     case Attr_Min:
1809     case Attr_Max:
1810       {
1811         tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
1812         tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
1813
1814         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1815         gnu_result = build_binary_op (attribute == Attr_Min
1816                                       ? MIN_EXPR : MAX_EXPR,
1817                                       gnu_result_type, gnu_lhs, gnu_rhs);
1818       }
1819       break;
1820
1821     case Attr_Passed_By_Reference:
1822       gnu_result = size_int (default_pass_by_ref (gnu_type)
1823                              || must_pass_by_ref (gnu_type));
1824       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1825       break;
1826
1827     case Attr_Component_Size:
1828       if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1829           && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1830         gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1831
1832       gnu_prefix = maybe_implicit_deref (gnu_prefix);
1833       gnu_type = TREE_TYPE (gnu_prefix);
1834
1835       if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1836         gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
1837
1838       while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
1839              && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
1840         gnu_type = TREE_TYPE (gnu_type);
1841
1842       gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
1843
1844       /* Note this size cannot be self-referential.  */
1845       gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
1846       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1847       prefix_unused = true;
1848       break;
1849
1850     case Attr_Null_Parameter:
1851       /* This is just a zero cast to the pointer type for our prefix and
1852          dereferenced.  */
1853       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1854       gnu_result
1855         = build_unary_op (INDIRECT_REF, NULL_TREE,
1856                           convert (build_pointer_type (gnu_result_type),
1857                                    integer_zero_node));
1858       TREE_PRIVATE (gnu_result) = 1;
1859       break;
1860
1861     case Attr_Mechanism_Code:
1862       {
1863         int code;
1864         Entity_Id gnat_obj = Entity (Prefix (gnat_node));
1865
1866         prefix_unused = true;
1867         gnu_result_type = get_unpadded_type (Etype (gnat_node));
1868         if (Present (Expressions (gnat_node)))
1869           {
1870             int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
1871
1872             for (gnat_obj = First_Formal (gnat_obj); i > 1;
1873                  i--, gnat_obj = Next_Formal (gnat_obj))
1874               ;
1875           }
1876
1877         code = Mechanism (gnat_obj);
1878         if (code == Default)
1879           code = ((present_gnu_tree (gnat_obj)
1880                    && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
1881                        || ((TREE_CODE (get_gnu_tree (gnat_obj))
1882                             == PARM_DECL)
1883                            && (DECL_BY_COMPONENT_PTR_P
1884                                (get_gnu_tree (gnat_obj))))))
1885                   ? By_Reference : By_Copy);
1886         gnu_result = convert (gnu_result_type, size_int (- code));
1887       }
1888       break;
1889
1890     default:
1891       /* Say we have an unimplemented attribute.  Then set the value to be
1892          returned to be a zero and hope that's something we can convert to
1893          the type of this attribute.  */
1894       post_error ("unimplemented attribute", gnat_node);
1895       gnu_result_type = get_unpadded_type (Etype (gnat_node));
1896       gnu_result = integer_zero_node;
1897       break;
1898     }
1899
1900   /* If this is an attribute where the prefix was unused, force a use of it if
1901      it has a side-effect.  But don't do it if the prefix is just an entity
1902      name.  However, if an access check is needed, we must do it.  See second
1903      example in AARM 11.6(5.e).  */
1904   if (prefix_unused && TREE_SIDE_EFFECTS (gnu_prefix)
1905       && !Is_Entity_Name (Prefix (gnat_node)))
1906     gnu_result = fold_build2 (COMPOUND_EXPR, TREE_TYPE (gnu_result),
1907                               gnu_prefix, gnu_result);
1908
1909   *gnu_result_type_p = gnu_result_type;
1910   return gnu_result;
1911 }
1912 \f
1913 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Case_Statement,
1914    to a GCC tree, which is returned.  */
1915
1916 static tree
1917 Case_Statement_to_gnu (Node_Id gnat_node)
1918 {
1919   tree gnu_result;
1920   tree gnu_expr;
1921   Node_Id gnat_when;
1922
1923   gnu_expr = gnat_to_gnu (Expression (gnat_node));
1924   gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
1925
1926   /*  The range of values in a case statement is determined by the rules in
1927       RM 5.4(7-9). In almost all cases, this range is represented by the Etype
1928       of the expression. One exception arises in the case of a simple name that
1929       is parenthesized. This still has the Etype of the name, but since it is
1930       not a name, para 7 does not apply, and we need to go to the base type.
1931       This is the only case where parenthesization affects the dynamic
1932       semantics (i.e. the range of possible values at runtime that is covered
1933       by the others alternative.
1934
1935       Another exception is if the subtype of the expression is non-static.  In
1936       that case, we also have to use the base type.  */
1937   if (Paren_Count (Expression (gnat_node)) != 0
1938       || !Is_OK_Static_Subtype (Underlying_Type
1939                                 (Etype (Expression (gnat_node)))))
1940     gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
1941
1942   /* We build a SWITCH_EXPR that contains the code with interspersed
1943      CASE_LABEL_EXPRs for each label.  */
1944
1945   push_stack (&gnu_switch_label_stack, NULL_TREE,
1946               create_artificial_label (input_location));
1947   start_stmt_group ();
1948   for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
1949        Present (gnat_when);
1950        gnat_when = Next_Non_Pragma (gnat_when))
1951     {
1952       bool choices_added_p = false;
1953       Node_Id gnat_choice;
1954
1955       /* First compile all the different case choices for the current WHEN
1956          alternative.  */
1957       for (gnat_choice = First (Discrete_Choices (gnat_when));
1958            Present (gnat_choice); gnat_choice = Next (gnat_choice))
1959         {
1960           tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
1961
1962           switch (Nkind (gnat_choice))
1963             {
1964             case N_Range:
1965               gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
1966               gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
1967               break;
1968
1969             case N_Subtype_Indication:
1970               gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
1971                                                 (Constraint (gnat_choice))));
1972               gnu_high = gnat_to_gnu (High_Bound (Range_Expression
1973                                                   (Constraint (gnat_choice))));
1974               break;
1975
1976             case N_Identifier:
1977             case N_Expanded_Name:
1978               /* This represents either a subtype range or a static value of
1979                  some kind; Ekind says which.  */
1980               if (IN (Ekind (Entity (gnat_choice)), Type_Kind))
1981                 {
1982                   tree gnu_type = get_unpadded_type (Entity (gnat_choice));
1983
1984                   gnu_low = fold (TYPE_MIN_VALUE (gnu_type));
1985                   gnu_high = fold (TYPE_MAX_VALUE (gnu_type));
1986                   break;
1987                 }
1988
1989               /* ... fall through ... */
1990
1991             case N_Character_Literal:
1992             case N_Integer_Literal:
1993               gnu_low = gnat_to_gnu (gnat_choice);
1994               break;
1995
1996             case N_Others_Choice:
1997               break;
1998
1999             default:
2000               gcc_unreachable ();
2001             }
2002
2003           /* If the case value is a subtype that raises Constraint_Error at
2004              run-time because of a wrong bound, then gnu_low or gnu_high is
2005              not translated into an INTEGER_CST.  In such a case, we need
2006              to ensure that the when statement is not added in the tree,
2007              otherwise it will crash the gimplifier.  */
2008           if ((!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST)
2009               && (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST))
2010             {
2011               add_stmt_with_node (build3
2012                                   (CASE_LABEL_EXPR, void_type_node,
2013                                    gnu_low, gnu_high,
2014                                    create_artificial_label (input_location)),
2015                                   gnat_choice);
2016               choices_added_p = true;
2017             }
2018         }
2019
2020       /* Push a binding level here in case variables are declared as we want
2021          them to be local to this set of statements instead of to the block
2022          containing the Case statement.  */
2023       if (choices_added_p)
2024         {
2025           add_stmt (build_stmt_group (Statements (gnat_when), true));
2026           add_stmt (build1 (GOTO_EXPR, void_type_node,
2027                             TREE_VALUE (gnu_switch_label_stack)));
2028         }
2029     }
2030
2031   /* Now emit a definition of the label all the cases branched to.  */
2032   add_stmt (build1 (LABEL_EXPR, void_type_node,
2033                     TREE_VALUE (gnu_switch_label_stack)));
2034   gnu_result = build3 (SWITCH_EXPR, TREE_TYPE (gnu_expr), gnu_expr,
2035                        end_stmt_group (), NULL_TREE);
2036   pop_stack (&gnu_switch_label_stack);
2037
2038   return gnu_result;
2039 }
2040 \f
2041 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Loop_Statement,
2042    to a GCC tree, which is returned.  */
2043
2044 static tree
2045 Loop_Statement_to_gnu (Node_Id gnat_node)
2046 {
2047   /* ??? It would be nice to use "build" here, but there's no build5.  */
2048   tree gnu_loop_stmt = build_nt (LOOP_STMT, NULL_TREE, NULL_TREE,
2049                                  NULL_TREE, NULL_TREE, NULL_TREE);
2050   tree gnu_loop_var = NULL_TREE;
2051   Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
2052   tree gnu_cond_expr = NULL_TREE;
2053   tree gnu_result;
2054
2055   TREE_TYPE (gnu_loop_stmt) = void_type_node;
2056   TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
2057   LOOP_STMT_LABEL (gnu_loop_stmt) = create_artificial_label (input_location);
2058   set_expr_location_from_node (gnu_loop_stmt, gnat_node);
2059   Sloc_to_locus (Sloc (End_Label (gnat_node)),
2060                  &DECL_SOURCE_LOCATION (LOOP_STMT_LABEL (gnu_loop_stmt)));
2061
2062   /* Save the end label of this LOOP_STMT in a stack so that the corresponding
2063      N_Exit_Statement can find it.  */
2064   push_stack (&gnu_loop_label_stack, NULL_TREE,
2065               LOOP_STMT_LABEL (gnu_loop_stmt));
2066
2067   /* Set the condition under which the loop must keep going.
2068      For the case "LOOP .... END LOOP;" the condition is always true.  */
2069   if (No (gnat_iter_scheme))
2070     ;
2071
2072   /* For the case "WHILE condition LOOP ..... END LOOP;" it's immediate.  */
2073   else if (Present (Condition (gnat_iter_scheme)))
2074     LOOP_STMT_TOP_COND (gnu_loop_stmt)
2075       = gnat_to_gnu (Condition (gnat_iter_scheme));
2076
2077   /* Otherwise we have an iteration scheme and the condition is given by
2078      the bounds of the subtype of the iteration variable.  */
2079   else
2080     {
2081       Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
2082       Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
2083       Entity_Id gnat_type = Etype (gnat_loop_var);
2084       tree gnu_type = get_unpadded_type (gnat_type);
2085       tree gnu_low = TYPE_MIN_VALUE (gnu_type);
2086       tree gnu_high = TYPE_MAX_VALUE (gnu_type);
2087       tree gnu_first, gnu_last, gnu_limit;
2088       enum tree_code update_code, end_code;
2089       tree gnu_base_type = get_base_type (gnu_type);
2090
2091       /* We must disable modulo reduction for the loop variable, if any,
2092          in order for the loop comparison to be effective.  */
2093       if (Reverse_Present (gnat_loop_spec))
2094         {
2095           gnu_first = gnu_high;
2096           gnu_last = gnu_low;
2097           update_code = MINUS_NOMOD_EXPR;
2098           end_code = GE_EXPR;
2099           gnu_limit = TYPE_MIN_VALUE (gnu_base_type);
2100         }
2101       else
2102         {
2103           gnu_first = gnu_low;
2104           gnu_last = gnu_high;
2105           update_code = PLUS_NOMOD_EXPR;
2106           end_code = LE_EXPR;
2107           gnu_limit = TYPE_MAX_VALUE (gnu_base_type);
2108         }
2109
2110       /* We know the loop variable will not overflow if GNU_LAST is a constant
2111          and is not equal to GNU_LIMIT.  If it might overflow, we have to move
2112          the limit test to the end of the loop.  In that case, we have to test
2113          for an empty loop outside the loop.  */
2114       if (TREE_CODE (gnu_last) != INTEGER_CST
2115           || TREE_CODE (gnu_limit) != INTEGER_CST
2116           || tree_int_cst_equal (gnu_last, gnu_limit))
2117         {
2118           gnu_cond_expr
2119             = build3 (COND_EXPR, void_type_node,
2120                       build_binary_op (LE_EXPR, integer_type_node,
2121                                        gnu_low, gnu_high),
2122                       NULL_TREE, alloc_stmt_list ());
2123           set_expr_location_from_node (gnu_cond_expr, gnat_loop_spec);
2124         }
2125
2126       /* Open a new nesting level that will surround the loop to declare the
2127          loop index variable.  */
2128       start_stmt_group ();
2129       gnat_pushlevel ();
2130
2131       /* Declare the loop index and set it to its initial value.  */
2132       gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, 1);
2133       if (DECL_BY_REF_P (gnu_loop_var))
2134         gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
2135
2136       /* The loop variable might be a padded type, so use `convert' to get a
2137          reference to the inner variable if so.  */
2138       gnu_loop_var = convert (get_base_type (gnu_type), gnu_loop_var);
2139
2140       /* Set either the top or bottom exit condition as appropriate depending
2141          on whether or not we know an overflow cannot occur.  */
2142       if (gnu_cond_expr)
2143         LOOP_STMT_BOT_COND (gnu_loop_stmt)
2144           = build_binary_op (NE_EXPR, integer_type_node,
2145                              gnu_loop_var, gnu_last);
2146       else
2147         LOOP_STMT_TOP_COND (gnu_loop_stmt)
2148           = build_binary_op (end_code, integer_type_node,
2149                              gnu_loop_var, gnu_last);
2150
2151       LOOP_STMT_UPDATE (gnu_loop_stmt)
2152         = build_binary_op (MODIFY_EXPR, NULL_TREE,
2153                            gnu_loop_var,
2154                            build_binary_op (update_code,
2155                                             TREE_TYPE (gnu_loop_var),
2156                                             gnu_loop_var,
2157                                             convert (TREE_TYPE (gnu_loop_var),
2158                                                      integer_one_node)));
2159       set_expr_location_from_node (LOOP_STMT_UPDATE (gnu_loop_stmt),
2160                                    gnat_iter_scheme);
2161     }
2162
2163   /* If the loop was named, have the name point to this loop.  In this case,
2164      the association is not a ..._DECL node, but the end label from this
2165      LOOP_STMT.  */
2166   if (Present (Identifier (gnat_node)))
2167     save_gnu_tree (Entity (Identifier (gnat_node)),
2168                    LOOP_STMT_LABEL (gnu_loop_stmt), true);
2169
2170   /* Make the loop body into its own block, so any allocated storage will be
2171      released every iteration.  This is needed for stack allocation.  */
2172   LOOP_STMT_BODY (gnu_loop_stmt)
2173     = build_stmt_group (Statements (gnat_node), true);
2174
2175   /* If we declared a variable, then we are in a statement group for that
2176      declaration.  Add the LOOP_STMT to it and make that the "loop".  */
2177   if (gnu_loop_var)
2178     {
2179       add_stmt (gnu_loop_stmt);
2180       gnat_poplevel ();
2181       gnu_loop_stmt = end_stmt_group ();
2182     }
2183
2184   /* If we have an outer COND_EXPR, that's our result and this loop is its
2185      "true" statement.  Otherwise, the result is the LOOP_STMT.  */
2186   if (gnu_cond_expr)
2187     {
2188       COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
2189       gnu_result = gnu_cond_expr;
2190       recalculate_side_effects (gnu_cond_expr);
2191     }
2192   else
2193     gnu_result = gnu_loop_stmt;
2194
2195   pop_stack (&gnu_loop_label_stack);
2196
2197   return gnu_result;
2198 }
2199 \f
2200 /* Emit statements to establish __gnat_handle_vms_condition as a VMS condition
2201    handler for the current function.  */
2202
2203 /* This is implemented by issuing a call to the appropriate VMS specific
2204    builtin.  To avoid having VMS specific sections in the global gigi decls
2205    array, we maintain the decls of interest here.  We can't declare them
2206    inside the function because we must mark them never to be GC'd, which we
2207    can only do at the global level.  */
2208
2209 static GTY(()) tree vms_builtin_establish_handler_decl = NULL_TREE;
2210 static GTY(()) tree gnat_vms_condition_handler_decl = NULL_TREE;
2211
2212 static void
2213 establish_gnat_vms_condition_handler (void)
2214 {
2215   tree establish_stmt;
2216
2217   /* Elaborate the required decls on the first call.  Check on the decl for
2218      the gnat condition handler to decide, as this is one we create so we are
2219      sure that it will be non null on subsequent calls.  The builtin decl is
2220      looked up so remains null on targets where it is not implemented yet.  */
2221   if (gnat_vms_condition_handler_decl == NULL_TREE)
2222     {
2223       vms_builtin_establish_handler_decl
2224         = builtin_decl_for
2225           (get_identifier ("__builtin_establish_vms_condition_handler"));
2226
2227       gnat_vms_condition_handler_decl
2228         = create_subprog_decl (get_identifier ("__gnat_handle_vms_condition"),
2229                                NULL_TREE,
2230                                build_function_type_list (integer_type_node,
2231                                                          ptr_void_type_node,
2232                                                          ptr_void_type_node,
2233                                                          NULL_TREE),
2234                                NULL_TREE, 0, 1, 1, 0, Empty);
2235
2236       /* ??? DECL_CONTEXT shouldn't have been set because of DECL_EXTERNAL.  */
2237       DECL_CONTEXT (gnat_vms_condition_handler_decl) = NULL_TREE;
2238     }
2239
2240   /* Do nothing if the establish builtin is not available, which might happen
2241      on targets where the facility is not implemented.  */
2242   if (vms_builtin_establish_handler_decl == NULL_TREE)
2243     return;
2244
2245   establish_stmt
2246     = build_call_1_expr (vms_builtin_establish_handler_decl,
2247                          build_unary_op
2248                          (ADDR_EXPR, NULL_TREE,
2249                           gnat_vms_condition_handler_decl));
2250
2251   add_stmt (establish_stmt);
2252 }
2253 \f
2254 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Subprogram_Body.  We
2255    don't return anything.  */
2256
2257 static void
2258 Subprogram_Body_to_gnu (Node_Id gnat_node)
2259 {
2260   /* Defining identifier of a parameter to the subprogram.  */
2261   Entity_Id gnat_param;
2262   /* The defining identifier for the subprogram body. Note that if a
2263      specification has appeared before for this body, then the identifier
2264      occurring in that specification will also be a defining identifier and all
2265      the calls to this subprogram will point to that specification.  */
2266   Entity_Id gnat_subprog_id
2267     = (Present (Corresponding_Spec (gnat_node))
2268        ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
2269   /* The FUNCTION_DECL node corresponding to the subprogram spec.   */
2270   tree gnu_subprog_decl;
2271   /* Its RESULT_DECL node.  */
2272   tree gnu_result_decl;
2273   /* The FUNCTION_TYPE node corresponding to the subprogram spec.  */
2274   tree gnu_subprog_type;
2275   tree gnu_cico_list;
2276   tree gnu_result;
2277   VEC(parm_attr,gc) *cache;
2278
2279   /* If this is a generic object or if it has been eliminated,
2280      ignore it.  */
2281   if (Ekind (gnat_subprog_id) == E_Generic_Procedure
2282       || Ekind (gnat_subprog_id) == E_Generic_Function
2283       || Is_Eliminated (gnat_subprog_id))
2284     return;
2285
2286   /* If this subprogram acts as its own spec, define it.  Otherwise, just get
2287      the already-elaborated tree node.  However, if this subprogram had its
2288      elaboration deferred, we will already have made a tree node for it.  So
2289      treat it as not being defined in that case.  Such a subprogram cannot
2290      have an address clause or a freeze node, so this test is safe, though it
2291      does disable some otherwise-useful error checking.  */
2292   gnu_subprog_decl
2293     = gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE,
2294                           Acts_As_Spec (gnat_node)
2295                           && !present_gnu_tree (gnat_subprog_id));
2296   gnu_result_decl = DECL_RESULT (gnu_subprog_decl);
2297   gnu_subprog_type = TREE_TYPE (gnu_subprog_decl);
2298
2299   /* If the function returns by invisible reference, make it explicit in the
2300      function body.  See gnat_to_gnu_entity, E_Subprogram_Type case.  */
2301   if (TREE_ADDRESSABLE (gnu_subprog_type))
2302     {
2303       TREE_TYPE (gnu_result_decl)
2304         = build_reference_type (TREE_TYPE (gnu_result_decl));
2305       relayout_decl (gnu_result_decl);
2306     }
2307
2308   /* Propagate the debug mode.  */
2309   if (!Needs_Debug_Info (gnat_subprog_id))
2310     DECL_IGNORED_P (gnu_subprog_decl) = 1;
2311
2312   /* Set the line number in the decl to correspond to that of the body so that
2313      the line number notes are written correctly.  */
2314   Sloc_to_locus (Sloc (gnat_node), &DECL_SOURCE_LOCATION (gnu_subprog_decl));
2315
2316   /* Initialize the information structure for the function.  */
2317   allocate_struct_function (gnu_subprog_decl, false);
2318   DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language
2319     = GGC_CNEW (struct language_function);
2320
2321   begin_subprog_body (gnu_subprog_decl);
2322   gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
2323
2324   /* If there are Out parameters, we need to ensure that the return statement
2325      properly copies them out.  We do this by making a new block and converting
2326      any inner return into a goto to a label at the end of the block.  */
2327   push_stack (&gnu_return_label_stack, NULL_TREE,
2328               gnu_cico_list ? create_artificial_label (input_location)
2329               : NULL_TREE);
2330
2331   /* Get a tree corresponding to the code for the subprogram.  */
2332   start_stmt_group ();
2333   gnat_pushlevel ();
2334
2335   /* See if there are any parameters for which we don't yet have GCC entities.
2336      These must be for Out parameters for which we will be making VAR_DECL
2337      nodes here.  Fill them in to TYPE_CI_CO_LIST, which must contain the empty
2338      entry as well.  We can match up the entries because TYPE_CI_CO_LIST is in
2339      the order of the parameters.  */
2340   for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
2341        Present (gnat_param);
2342        gnat_param = Next_Formal_With_Extras (gnat_param))
2343     if (!present_gnu_tree (gnat_param))
2344       {
2345         /* Skip any entries that have been already filled in; they must
2346            correspond to In Out parameters.  */
2347         for (; gnu_cico_list && TREE_VALUE (gnu_cico_list);
2348              gnu_cico_list = TREE_CHAIN (gnu_cico_list))
2349           ;
2350
2351         /* Do any needed references for padded types.  */
2352         TREE_VALUE (gnu_cico_list)
2353           = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_list)),
2354                      gnat_to_gnu_entity (gnat_param, NULL_TREE, 1));
2355       }
2356
2357   /* On VMS, establish our condition handler to possibly turn a condition into
2358      the corresponding exception if the subprogram has a foreign convention or
2359      is exported.
2360
2361      To ensure proper execution of local finalizations on condition instances,
2362      we must turn a condition into the corresponding exception even if there
2363      is no applicable Ada handler, and need at least one condition handler per
2364      possible call chain involving GNAT code.  OTOH, establishing the handler
2365      has a cost so we want to minimize the number of subprograms into which
2366      this happens.  The foreign or exported condition is expected to satisfy
2367      all the constraints.  */
2368   if (TARGET_ABI_OPEN_VMS
2369       && (Has_Foreign_Convention (gnat_subprog_id)
2370           || Is_Exported (gnat_subprog_id)))
2371     establish_gnat_vms_condition_handler ();
2372
2373   process_decls (Declarations (gnat_node), Empty, Empty, true, true);
2374
2375   /* Generate the code of the subprogram itself.  A return statement will be
2376      present and any Out parameters will be handled there.  */
2377   add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
2378   gnat_poplevel ();
2379   gnu_result = end_stmt_group ();
2380
2381   /* If we populated the parameter attributes cache, we need to make sure
2382      that the cached expressions are evaluated on all possible paths.  */
2383   cache = DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language->parm_attr_cache;
2384   if (cache)
2385     {
2386       struct parm_attr_d *pa;
2387       int i;
2388
2389       start_stmt_group ();
2390
2391       for (i = 0; VEC_iterate (parm_attr, cache, i, pa); i++)
2392         {
2393           if (pa->first)
2394             add_stmt_with_node (pa->first, gnat_node);
2395           if (pa->last)
2396             add_stmt_with_node (pa->last, gnat_node);
2397           if (pa->length)
2398             add_stmt_with_node (pa->length, gnat_node);
2399         }
2400
2401       add_stmt (gnu_result);
2402       gnu_result = end_stmt_group ();
2403     }
2404
2405     /* If we are dealing with a return from an Ada procedure with parameters
2406        passed by copy-in/copy-out, we need to return a record containing the
2407        final values of these parameters.  If the list contains only one entry,
2408        return just that entry though.
2409
2410        For a full description of the copy-in/copy-out parameter mechanism, see
2411        the part of the gnat_to_gnu_entity routine dealing with the translation
2412        of subprograms.
2413
2414        We need to make a block that contains the definition of that label and
2415        the copying of the return value.  It first contains the function, then
2416        the label and copy statement.  */
2417   if (TREE_VALUE (gnu_return_label_stack))
2418     {
2419       tree gnu_retval;
2420
2421       start_stmt_group ();
2422       gnat_pushlevel ();
2423       add_stmt (gnu_result);
2424       add_stmt (build1 (LABEL_EXPR, void_type_node,
2425                         TREE_VALUE (gnu_return_label_stack)));
2426
2427       gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
2428       if (list_length (gnu_cico_list) == 1)
2429         gnu_retval = TREE_VALUE (gnu_cico_list);
2430       else
2431         gnu_retval = gnat_build_constructor (TREE_TYPE (gnu_subprog_type),
2432                                              gnu_cico_list);
2433
2434       add_stmt_with_node (build_return_expr (gnu_result_decl, gnu_retval),
2435                           End_Label (Handled_Statement_Sequence (gnat_node)));
2436       gnat_poplevel ();
2437       gnu_result = end_stmt_group ();
2438     }
2439
2440   pop_stack (&gnu_return_label_stack);
2441
2442   /* Set the end location.  */
2443   Sloc_to_locus
2444     ((Present (End_Label (Handled_Statement_Sequence (gnat_node)))
2445       ? Sloc (End_Label (Handled_Statement_Sequence (gnat_node)))
2446       : Sloc (gnat_node)),
2447      &DECL_STRUCT_FUNCTION (gnu_subprog_decl)->function_end_locus);
2448
2449   end_subprog_body (gnu_result);
2450
2451   /* Finally annotate the parameters and disconnect the trees for parameters
2452      that we have turned into variables since they are now unusable.  */
2453   for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
2454        Present (gnat_param);
2455        gnat_param = Next_Formal_With_Extras (gnat_param))
2456     {
2457       tree gnu_param = get_gnu_tree (gnat_param);
2458       annotate_object (gnat_param, TREE_TYPE (gnu_param), NULL_TREE,
2459                        DECL_BY_REF_P (gnu_param));
2460       if (TREE_CODE (gnu_param) == VAR_DECL)
2461         save_gnu_tree (gnat_param, NULL_TREE, false);
2462     }
2463
2464   if (DECL_FUNCTION_STUB (gnu_subprog_decl))
2465     build_function_stub (gnu_subprog_decl, gnat_subprog_id);
2466
2467   mark_out_of_scope (Defining_Unit_Name (Specification (gnat_node)));
2468 }
2469 \f
2470 /* Subroutine of gnat_to_gnu to translate gnat_node, either an N_Function_Call
2471    or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
2472    GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
2473    If GNU_TARGET is non-null, this must be a function call and the result
2474    of the call is to be placed into that object.  */
2475
2476 static tree
2477 call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target)
2478 {
2479   /* The GCC node corresponding to the GNAT subprogram name.  This can either
2480      be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
2481      or an indirect reference expression (an INDIRECT_REF node) pointing to a
2482      subprogram.  */
2483   tree gnu_subprog = gnat_to_gnu (Name (gnat_node));
2484   /* The FUNCTION_TYPE node giving the GCC type of the subprogram.  */
2485   tree gnu_subprog_type = TREE_TYPE (gnu_subprog);
2486   tree gnu_subprog_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_subprog);
2487   Entity_Id gnat_formal;
2488   Node_Id gnat_actual;
2489   tree gnu_actual_list = NULL_TREE;
2490   tree gnu_name_list = NULL_TREE;
2491   tree gnu_before_list = NULL_TREE;
2492   tree gnu_after_list = NULL_TREE;
2493   tree gnu_call;
2494
2495   gcc_assert (TREE_CODE (gnu_subprog_type) == FUNCTION_TYPE);
2496
2497   /* If we are calling a stubbed function, raise Program_Error, but Elaborate
2498      all our args first.  */
2499   if (TREE_CODE (gnu_subprog) == FUNCTION_DECL && DECL_STUBBED_P (gnu_subprog))
2500     {
2501       tree call_expr = build_call_raise (PE_Stubbed_Subprogram_Called,
2502                                          gnat_node, N_Raise_Program_Error);
2503
2504       for (gnat_actual = First_Actual (gnat_node);
2505            Present (gnat_actual);
2506            gnat_actual = Next_Actual (gnat_actual))
2507         add_stmt (gnat_to_gnu (gnat_actual));
2508
2509       if (Nkind (gnat_node) == N_Function_Call && !gnu_target)
2510         {
2511           *gnu_result_type_p = TREE_TYPE (gnu_subprog_type);
2512           return build1 (NULL_EXPR, TREE_TYPE (gnu_subprog_type), call_expr);
2513         }
2514
2515       return call_expr;
2516     }
2517
2518   /* The only way we can be making a call via an access type is if Name is an
2519      explicit dereference.  In that case, get the list of formal args from the
2520      type the access type is pointing to.  Otherwise, get the formals from the
2521      entity being called.  */
2522   if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
2523     gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
2524   else if (Nkind (Name (gnat_node)) == N_Attribute_Reference)
2525     /* Assume here that this must be 'Elab_Body or 'Elab_Spec.  */
2526     gnat_formal = Empty;
2527   else
2528     gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
2529
2530   /* Create the list of the actual parameters as GCC expects it, namely a
2531      chain of TREE_LIST nodes in which the TREE_VALUE field of each node
2532      is an expression and the TREE_PURPOSE field is null.  But skip Out
2533      parameters not passed by reference and that need not be copied in.  */
2534   for (gnat_actual = First_Actual (gnat_node);
2535        Present (gnat_actual);
2536        gnat_formal = Next_Formal_With_Extras (gnat_formal),
2537        gnat_actual = Next_Actual (gnat_actual))
2538     {
2539       tree gnu_formal = present_gnu_tree (gnat_formal)
2540                         ? get_gnu_tree (gnat_formal) : NULL_TREE;
2541       tree gnu_formal_type = gnat_to_gnu_type (Etype (gnat_formal));
2542       /* In the Out or In Out case, we must suppress conversions that yield
2543          an lvalue but can nevertheless cause the creation of a temporary,
2544          because we need the real object in this case, either to pass its
2545          address if it's passed by reference or as target of the back copy
2546          done after the call if it uses the copy-in copy-out mechanism.
2547          We do it in the In case too, except for an unchecked conversion
2548          because it alone can cause the actual to be misaligned and the
2549          addressability test is applied to the real object.  */
2550       bool suppress_type_conversion
2551         = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
2552             && Ekind (gnat_formal) != E_In_Parameter)
2553            || (Nkind (gnat_actual) == N_Type_Conversion
2554                && Is_Composite_Type (Underlying_Type (Etype (gnat_formal)))));
2555       Node_Id gnat_name = suppress_type_conversion
2556                           ? Expression (gnat_actual) : gnat_actual;
2557       tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
2558       tree gnu_actual;
2559
2560       /* If it's possible we may need to use this expression twice, make sure
2561          that any side-effects are handled via SAVE_EXPRs; likewise if we need
2562          to force side-effects before the call.
2563          ??? This is more conservative than we need since we don't need to do
2564          this for pass-by-ref with no conversion.  */
2565       if (Ekind (gnat_formal) != E_In_Parameter)
2566         gnu_name = gnat_stabilize_reference (gnu_name, true, NULL);
2567
2568       /* If we are passing a non-addressable parameter by reference, pass the
2569          address of a copy.  In the Out or In Out case, set up to copy back
2570          out after the call.  */
2571       if (gnu_formal
2572           && (DECL_BY_REF_P (gnu_formal)
2573               || (TREE_CODE (gnu_formal) == PARM_DECL
2574                   && (DECL_BY_COMPONENT_PTR_P (gnu_formal)
2575                       || (DECL_BY_DESCRIPTOR_P (gnu_formal)))))
2576           && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
2577           && !addressable_p (gnu_name, gnu_name_type))
2578         {
2579           tree gnu_copy = gnu_name;
2580
2581           /* If the actual type of the object is already the nominal type,
2582              we have nothing to do, except if the size is self-referential
2583              in which case we'll remove the unpadding below.  */
2584           if (TREE_TYPE (gnu_name) == gnu_name_type
2585               && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_name_type)))
2586             ;
2587
2588           /* Otherwise remove unpadding from the object and reset the copy.  */
2589           else if (TREE_CODE (gnu_name) == COMPONENT_REF
2590                    && TYPE_IS_PADDING_P
2591                       (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))
2592             gnu_name = gnu_copy = TREE_OPERAND (gnu_name, 0);
2593
2594           /* Otherwise convert to the nominal type of the object if it's
2595              a record type.  There are several cases in which we need to
2596              make the temporary using this type instead of the actual type
2597              of the object if they are distinct, because the expectations
2598              of the callee would otherwise not be met:
2599                - if it's a justified modular type,
2600                - if the actual type is a smaller packable version of it.  */
2601           else if (TREE_CODE (gnu_name_type) == RECORD_TYPE
2602                    && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
2603                        || smaller_packable_type_p (TREE_TYPE (gnu_name),
2604                                                    gnu_name_type)))
2605             gnu_name = convert (gnu_name_type, gnu_name);
2606
2607           /* Make a SAVE_EXPR to force the creation of a temporary.  Special
2608              code in gnat_gimplify_expr ensures that the same temporary is
2609              used as the object and copied back after the call if needed.  */
2610           gnu_name = build1 (SAVE_EXPR, TREE_TYPE (gnu_name), gnu_name);
2611           TREE_SIDE_EFFECTS (gnu_name) = 1;
2612
2613           /* If the type is passed by reference, a copy is not allowed.  */
2614           if (TREE_ADDRESSABLE (gnu_formal_type))
2615             {
2616               post_error ("misaligned actual cannot be passed by reference",
2617                           gnat_actual);
2618
2619               /* Avoid the back-end assertion on temporary creation.  */
2620               gnu_name = TREE_OPERAND (gnu_name, 0);
2621             }
2622
2623           /* For users of Starlet we issue a warning because the interface
2624              apparently assumes that by-ref parameters outlive the procedure
2625              invocation.  The code still will not work as intended, but we
2626              cannot do much better since low-level parts of the back-end
2627              would allocate temporaries at will because of the misalignment
2628              if we did not do so here.  */
2629           else if (Is_Valued_Procedure (Entity (Name (gnat_node))))
2630             {
2631               post_error
2632                 ("?possible violation of implicit assumption", gnat_actual);
2633               post_error_ne
2634                 ("?made by pragma Import_Valued_Procedure on &", gnat_actual,
2635                  Entity (Name (gnat_node)));
2636               post_error_ne ("?because of misalignment of &", gnat_actual,
2637                              gnat_formal);
2638             }
2639
2640           /* Set up to move the copy back to the original if needed.  */
2641           if (Ekind (gnat_formal) != E_In_Parameter)
2642             {
2643               tree stmt = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_copy,
2644                                            gnu_name);
2645               set_expr_location_from_node (stmt, gnat_node);
2646               append_to_statement_list (stmt, &gnu_after_list);
2647             }
2648         }
2649
2650       /* Start from the real object and build the actual.  */
2651       gnu_actual = gnu_name;
2652
2653       /* If this was a procedure call, we may not have removed any padding.
2654          So do it here for the part we will use as an input, if any.  */
2655       if (Ekind (gnat_formal) != E_Out_Parameter
2656           && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
2657         gnu_actual
2658           = convert (get_unpadded_type (Etype (gnat_actual)), gnu_actual);
2659
2660       /* Put back the conversion we suppressed above in the computation of the
2661          real object.  And even if we didn't suppress any conversion there, we
2662          may have suppressed a conversion to the Etype of the actual earlier,
2663          since the parent is a procedure call, so put it back here.  */
2664       if (suppress_type_conversion
2665           && Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
2666         gnu_actual
2667           = unchecked_convert (gnat_to_gnu_type (Etype (gnat_actual)),
2668                                gnu_actual, No_Truncation (gnat_actual));
2669       else
2670         gnu_actual
2671           = convert (gnat_to_gnu_type (Etype (gnat_actual)), gnu_actual);
2672
2673       /* Make sure that the actual is in range of the formal's type.  */
2674       if (Ekind (gnat_formal) != E_Out_Parameter
2675           && Do_Range_Check (gnat_actual))
2676         gnu_actual
2677           = emit_range_check (gnu_actual, Etype (gnat_formal), gnat_actual);
2678
2679       /* And convert it to this type.  */
2680       if (TREE_CODE (gnu_actual) != SAVE_EXPR)
2681         gnu_actual = convert (gnu_formal_type, gnu_actual);
2682
2683       /* Unless this is an In parameter, we must remove any justified modular
2684          building from GNU_NAME to get an lvalue.  */
2685       if (Ekind (gnat_formal) != E_In_Parameter
2686           && TREE_CODE (gnu_name) == CONSTRUCTOR
2687           && TREE_CODE (TREE_TYPE (gnu_name)) == RECORD_TYPE
2688           && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (gnu_name)))
2689         gnu_name
2690           = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_name))), gnu_name);
2691
2692       /* If we have not saved a GCC object for the formal, it means it is an
2693          Out parameter not passed by reference and that need not be copied in.
2694          Otherwise, first see if the PARM_DECL is passed by reference.  */
2695       if (gnu_formal
2696           && TREE_CODE (gnu_formal) == PARM_DECL
2697           && DECL_BY_REF_P (gnu_formal))
2698         {
2699           if (Ekind (gnat_formal) != E_In_Parameter)
2700             {
2701               /* In Out or Out parameters passed by reference don't use the
2702                  copy-in copy-out mechanism so the address of the real object
2703                  must be passed to the function.  */
2704               gnu_actual = gnu_name;
2705
2706               /* If we have a padded type, be sure we've removed padding.  */
2707               if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual))
2708                   && TREE_CODE (gnu_actual) != SAVE_EXPR)
2709                 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
2710                                       gnu_actual);
2711
2712               /* If we have the constructed subtype of an aliased object
2713                  with an unconstrained nominal subtype, the type of the
2714                  actual includes the template, although it is formally
2715                  constrained.  So we need to convert it back to the real
2716                  constructed subtype to retrieve the constrained part
2717                  and takes its address.  */
2718               if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
2719                   && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
2720                   && TREE_CODE (gnu_actual) != SAVE_EXPR
2721                   && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
2722                   && Is_Array_Type (Etype (gnat_actual)))
2723                 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
2724                                       gnu_actual);
2725             }
2726
2727           /* The symmetry of the paths to the type of an entity is broken here
2728              since arguments don't know that they will be passed by ref.  */
2729           gnu_formal_type = TREE_TYPE (get_gnu_tree (gnat_formal));
2730           gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
2731         }
2732       else if (gnu_formal
2733                && TREE_CODE (gnu_formal) == PARM_DECL
2734                && DECL_BY_COMPONENT_PTR_P (gnu_formal))
2735         {
2736           gnu_formal_type = TREE_TYPE (get_gnu_tree (gnat_formal));
2737           gnu_actual = maybe_implicit_deref (gnu_actual);
2738           gnu_actual = maybe_unconstrained_array (gnu_actual);
2739
2740           if (TYPE_IS_PADDING_P (gnu_formal_type))
2741             {
2742               gnu_formal_type = TREE_TYPE (TYPE_FIELDS (gnu_formal_type));
2743               gnu_actual = convert (gnu_formal_type, gnu_actual);
2744             }
2745
2746           /* Take the address of the object and convert to the proper pointer
2747              type.  We'd like to actually compute the address of the beginning
2748              of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
2749              possibility that the ARRAY_REF might return a constant and we'd be
2750              getting the wrong address.  Neither approach is exactly correct,
2751              but this is the most likely to work in all cases.  */
2752           gnu_actual = convert (gnu_formal_type,
2753                                 build_unary_op (ADDR_EXPR, NULL_TREE,
2754                                                 gnu_actual));
2755         }
2756       else if (gnu_formal
2757                && TREE_CODE (gnu_formal) == PARM_DECL
2758                && DECL_BY_DESCRIPTOR_P (gnu_formal))
2759         {
2760           /* If this is 'Null_Parameter, pass a zero descriptor.  */
2761           if ((TREE_CODE (gnu_actual) == INDIRECT_REF
2762                || TREE_CODE (gnu_actual) == UNCONSTRAINED_ARRAY_REF)
2763               && TREE_PRIVATE (gnu_actual))
2764             gnu_actual
2765               = convert (DECL_ARG_TYPE (gnu_formal), integer_zero_node);
2766           else
2767             gnu_actual = build_unary_op (ADDR_EXPR, NULL_TREE,
2768                                          fill_vms_descriptor (gnu_actual,
2769                                                               gnat_formal,
2770                                                               gnat_actual));
2771         }
2772       else
2773         {
2774           tree gnu_size;
2775
2776           if (Ekind (gnat_formal) != E_In_Parameter)
2777             gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
2778
2779           if (!(gnu_formal && TREE_CODE (gnu_formal) == PARM_DECL))
2780             {
2781               /* Make sure side-effects are evaluated before the call.  */
2782               if (TREE_SIDE_EFFECTS (gnu_name))
2783                 append_to_statement_list (gnu_name, &gnu_before_list);
2784               continue;
2785             }
2786
2787           /* If this is 'Null_Parameter, pass a zero even though we are
2788              dereferencing it.  */
2789           if (TREE_CODE (gnu_actual) == INDIRECT_REF
2790               && TREE_PRIVATE (gnu_actual)
2791               && (gnu_size = TYPE_SIZE (TREE_TYPE (gnu_actual)))
2792               && TREE_CODE (gnu_size) == INTEGER_CST
2793               && compare_tree_int (gnu_size, BITS_PER_WORD) <= 0)
2794             gnu_actual
2795               = unchecked_convert (DECL_ARG_TYPE (gnu_formal),
2796                                    convert (gnat_type_for_size
2797                                             (TREE_INT_CST_LOW (gnu_size), 1),
2798                                             integer_zero_node),
2799                                    false);
2800           else
2801             gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
2802         }
2803
2804       gnu_actual_list = tree_cons (NULL_TREE, gnu_actual, gnu_actual_list);
2805     }
2806
2807   gnu_call = build_call_list (TREE_TYPE (gnu_subprog_type), gnu_subprog_addr,
2808                               nreverse (gnu_actual_list));
2809   set_expr_location_from_node (gnu_call, gnat_node);
2810
2811   /* If it's a function call, the result is the call expression unless a target
2812      is specified, in which case we copy the result into the target and return
2813      the assignment statement.  */
2814   if (Nkind (gnat_node) == N_Function_Call)
2815     {
2816       tree gnu_result = gnu_call;
2817       enum tree_code op_code;
2818
2819       /* If the function returns an unconstrained array or by direct reference,
2820          we have to dereference the pointer.  */
2821       if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type)
2822           || TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type))
2823         gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
2824
2825       if (gnu_target)
2826         {
2827           /* ??? If the return type has non-constant size, then force the
2828              return slot optimization as we would not be able to generate
2829              a temporary.  That's what has been done historically.  */
2830           if (TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_subprog_type))))
2831             op_code = MODIFY_EXPR;
2832           else
2833             op_code = INIT_EXPR;
2834
2835           gnu_result
2836             = build_binary_op (op_code, NULL_TREE, gnu_target, gnu_result);
2837         }
2838       else
2839         *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
2840
2841       return gnu_result;
2842     }
2843
2844   /* If this is the case where the GNAT tree contains a procedure call but the
2845      Ada procedure has copy-in/copy-out parameters, then the special parameter
2846      passing mechanism must be used.  */
2847   if (TYPE_CI_CO_LIST (gnu_subprog_type))
2848     {
2849       /* List of FIELD_DECLs associated with the PARM_DECLs of the copy
2850          in copy out parameters.  */
2851       tree gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
2852       const int length = list_length (gnu_cico_list);
2853
2854       if (length > 1)
2855         {
2856           /* The call sequence must contain one and only one call, even though
2857              the function is const or pure.  So force a SAVE_EXPR.  */
2858           gnu_call = build1 (SAVE_EXPR, TREE_TYPE (gnu_call), gnu_call);
2859           TREE_SIDE_EFFECTS (gnu_call) = 1;
2860           gnu_name_list = nreverse (gnu_name_list);
2861         }
2862
2863       if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
2864         gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
2865       else
2866         gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
2867
2868       for (gnat_actual = First_Actual (gnat_node);
2869            Present (gnat_actual);
2870            gnat_formal = Next_Formal_With_Extras (gnat_formal),
2871            gnat_actual = Next_Actual (gnat_actual))
2872         /* If we are dealing with a copy in copy out parameter, we must
2873            retrieve its value from the record returned in the call.  */
2874         if (!(present_gnu_tree (gnat_formal)
2875               && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
2876               && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
2877                   || (TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
2878                       && ((DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))
2879                            || (DECL_BY_DESCRIPTOR_P
2880                                (get_gnu_tree (gnat_formal))))))))
2881             && Ekind (gnat_formal) != E_In_Parameter)
2882           {
2883             /* Get the value to assign to this Out or In Out parameter.  It is
2884                either the result of the function if there is only a single such
2885                parameter or the appropriate field from the record returned.  */
2886             tree gnu_result
2887               = length == 1
2888                 ? gnu_call
2889                 : build_component_ref (gnu_call, NULL_TREE,
2890                                        TREE_PURPOSE (gnu_cico_list), false);
2891
2892             /* If the actual is a conversion, get the inner expression, which
2893                will be the real destination, and convert the result to the
2894                type of the actual parameter.  */
2895             tree gnu_actual
2896               = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
2897
2898             /* If the result is a padded type, remove the padding.  */
2899             if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
2900               gnu_result
2901                 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
2902                            gnu_result);
2903
2904             /* If the actual is a type conversion, the real target object is
2905                denoted by the inner Expression and we need to convert the
2906                result to the associated type.
2907                We also need to convert our gnu assignment target to this type
2908                if the corresponding GNU_NAME was constructed from the GNAT
2909                conversion node and not from the inner Expression.  */
2910             if (Nkind (gnat_actual) == N_Type_Conversion)
2911               {
2912                 gnu_result
2913                   = convert_with_check
2914                     (Etype (Expression (gnat_actual)), gnu_result,
2915                      Do_Overflow_Check (gnat_actual),
2916                      Do_Range_Check (Expression (gnat_actual)),
2917                      Float_Truncate (gnat_actual), gnat_actual);
2918
2919                 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
2920                   gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
2921               }
2922
2923             /* Unchecked conversions as actuals for Out parameters are not
2924                allowed in user code because they are not variables, but do
2925                occur in front-end expansions.  The associated GNU_NAME is
2926                always obtained from the inner expression in such cases.  */
2927             else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
2928               gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
2929                                               gnu_result,
2930                                               No_Truncation (gnat_actual));
2931             else
2932               {
2933                 if (Do_Range_Check (gnat_actual))
2934                   gnu_result
2935                     = emit_range_check (gnu_result, Etype (gnat_actual),
2936                                         gnat_actual);
2937
2938                 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
2939                       && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
2940                   gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
2941               }
2942
2943             /* Undo wrapping of boolean rvalues.  */
2944             if (TREE_CODE (gnu_actual) == NE_EXPR
2945                 && TREE_CODE (get_base_type (TREE_TYPE (gnu_actual)))
2946                    == BOOLEAN_TYPE
2947                 && integer_zerop (TREE_OPERAND (gnu_actual, 1)))
2948               gnu_actual = TREE_OPERAND (gnu_actual, 0);
2949             gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
2950                                           gnu_actual, gnu_result);
2951             set_expr_location_from_node (gnu_result, gnat_node);
2952             append_to_statement_list (gnu_result, &gnu_before_list);
2953             gnu_cico_list = TREE_CHAIN (gnu_cico_list);
2954             gnu_name_list = TREE_CHAIN (gnu_name_list);
2955           }
2956     }
2957   else
2958     append_to_statement_list (gnu_call, &gnu_before_list);
2959
2960   append_to_statement_list (gnu_after_list, &gnu_before_list);
2961
2962   return gnu_before_list;
2963 }
2964 \f
2965 /* Subroutine of gnat_to_gnu to translate gnat_node, an
2966    N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned.  */
2967
2968 static tree
2969 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
2970 {
2971   tree gnu_jmpsave_decl = NULL_TREE;
2972   tree gnu_jmpbuf_decl = NULL_TREE;
2973   /* If just annotating, ignore all EH and cleanups.  */
2974   bool gcc_zcx = (!type_annotate_only
2975                   && Present (Exception_Handlers (gnat_node))
2976                   && Exception_Mechanism == Back_End_Exceptions);
2977   bool setjmp_longjmp
2978     = (!type_annotate_only && Present (Exception_Handlers (gnat_node))
2979        && Exception_Mechanism == Setjmp_Longjmp);
2980   bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
2981   bool binding_for_block = (at_end || gcc_zcx || setjmp_longjmp);
2982   tree gnu_inner_block; /* The statement(s) for the block itself.  */
2983   tree gnu_result;
2984   tree gnu_expr;
2985   Node_Id gnat_temp;
2986
2987   /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes
2988      and we have our own SJLJ mechanism.  To call the GCC mechanism, we call
2989      add_cleanup, and when we leave the binding, end_stmt_group will create
2990      the TRY_FINALLY_EXPR.
2991
2992      ??? The region level calls down there have been specifically put in place
2993      for a ZCX context and currently the order in which things are emitted
2994      (region/handlers) is different from the SJLJ case. Instead of putting
2995      other calls with different conditions at other places for the SJLJ case,
2996      it seems cleaner to reorder things for the SJLJ case and generalize the
2997      condition to make it not ZCX specific.
2998
2999      If there are any exceptions or cleanup processing involved, we need an
3000      outer statement group (for Setjmp_Longjmp) and binding level.  */
3001   if (binding_for_block)
3002     {
3003       start_stmt_group ();
3004       gnat_pushlevel ();
3005     }
3006
3007   /* If using setjmp_longjmp, make the variables for the setjmp buffer and save
3008      area for address of previous buffer.  Do this first since we need to have
3009      the setjmp buf known for any decls in this block.  */
3010   if (setjmp_longjmp)
3011     {
3012       gnu_jmpsave_decl = create_var_decl (get_identifier ("JMPBUF_SAVE"),
3013                                           NULL_TREE, jmpbuf_ptr_type,
3014                                           build_call_0_expr (get_jmpbuf_decl),
3015                                           false, false, false, false, NULL,
3016                                           gnat_node);
3017       DECL_ARTIFICIAL (gnu_jmpsave_decl) = 1;
3018
3019       /* The __builtin_setjmp receivers will immediately reinstall it.  Now
3020          because of the unstructured form of EH used by setjmp_longjmp, there
3021          might be forward edges going to __builtin_setjmp receivers on which
3022          it is uninitialized, although they will never be actually taken.  */
3023       TREE_NO_WARNING (gnu_jmpsave_decl) = 1;
3024       gnu_jmpbuf_decl = create_var_decl (get_identifier ("JMP_BUF"),
3025                                          NULL_TREE, jmpbuf_type,
3026                                          NULL_TREE, false, false, false, false,
3027                                          NULL, gnat_node);
3028       DECL_ARTIFICIAL (gnu_jmpbuf_decl) = 1;
3029
3030       set_block_jmpbuf_decl (gnu_jmpbuf_decl);
3031
3032       /* When we exit this block, restore the saved value.  */
3033       add_cleanup (build_call_1_expr (set_jmpbuf_decl, gnu_jmpsave_decl),
3034                    End_Label (gnat_node));
3035     }
3036
3037   /* If we are to call a function when exiting this block, add a cleanup
3038      to the binding level we made above.  Note that add_cleanup is FIFO
3039      so we must register this cleanup after the EH cleanup just above.  */
3040   if (at_end)
3041     add_cleanup (build_call_0_expr (gnat_to_gnu (At_End_Proc (gnat_node))),
3042                  End_Label (gnat_node));
3043
3044   /* Now build the tree for the declarations and statements inside this block.
3045      If this is SJLJ, set our jmp_buf as the current buffer.  */
3046   start_stmt_group ();
3047
3048   if (setjmp_longjmp)
3049     add_stmt (build_call_1_expr (set_jmpbuf_decl,
3050                                  build_unary_op (ADDR_EXPR, NULL_TREE,
3051                                                  gnu_jmpbuf_decl)));
3052
3053   if (Present (First_Real_Statement (gnat_node)))
3054     process_decls (Statements (gnat_node), Empty,
3055                    First_Real_Statement (gnat_node), true, true);
3056
3057   /* Generate code for each statement in the block.  */
3058   for (gnat_temp = (Present (First_Real_Statement (gnat_node))
3059                     ? First_Real_Statement (gnat_node)
3060                     : First (Statements (gnat_node)));
3061        Present (gnat_temp); gnat_temp = Next (gnat_temp))
3062     add_stmt (gnat_to_gnu (gnat_temp));
3063   gnu_inner_block = end_stmt_group ();
3064
3065   /* Now generate code for the two exception models, if either is relevant for
3066      this block.  */
3067   if (setjmp_longjmp)
3068     {
3069       tree *gnu_else_ptr = 0;
3070       tree gnu_handler;
3071
3072       /* Make a binding level for the exception handling declarations and code
3073          and set up gnu_except_ptr_stack for the handlers to use.  */
3074       start_stmt_group ();
3075       gnat_pushlevel ();
3076
3077       push_stack (&gnu_except_ptr_stack, NULL_TREE,
3078                   create_var_decl (get_identifier ("EXCEPT_PTR"),
3079                                    NULL_TREE,
3080                                    build_pointer_type (except_type_node),
3081                                    build_call_0_expr (get_excptr_decl), false,
3082                                    false, false, false, NULL, gnat_node));
3083
3084       /* Generate code for each handler. The N_Exception_Handler case does the
3085          real work and returns a COND_EXPR for each handler, which we chain
3086          together here.  */
3087       for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
3088            Present (gnat_temp); gnat_temp = Next_Non_Pragma (gnat_temp))
3089         {
3090           gnu_expr = gnat_to_gnu (gnat_temp);
3091
3092           /* If this is the first one, set it as the outer one. Otherwise,
3093              point the "else" part of the previous handler to us. Then point
3094              to our "else" part.  */
3095           if (!gnu_else_ptr)