OSDN Git Service

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