* gcc-interface/gigi.h (create_var_decl): Adjust prototype.
[official-gcc.git] / gcc / ada / gcc-interface / trans.c
blobeda1b3a63e8ed1f1f6b87c02d6a96e12089cc6c9
1 /****************************************************************************
2 * *
3 * GNAT COMPILER COMPONENTS *
4 * *
5 * T R A N S *
6 * *
7 * C Implementation File *
8 * *
9 * Copyright (C) 1992-2015, 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 ****************************************************************************/
26 #include "config.h"
27 #include "system.h"
28 #include "coretypes.h"
29 #include "target.h"
30 #include "function.h"
31 #include "bitmap.h"
32 #include "tree.h"
33 #include "gimple-expr.h"
34 #include "stringpool.h"
35 #include "cgraph.h"
36 #include "predict.h"
37 #include "diagnostic.h"
38 #include "alias.h"
39 #include "fold-const.h"
40 #include "stor-layout.h"
41 #include "stmt.h"
42 #include "varasm.h"
43 #include "output.h"
44 #include "libfuncs.h" /* For set_stack_check_libfunc. */
45 #include "tree-iterator.h"
46 #include "gimplify.h"
47 #include "opts.h"
48 #include "common/common-target.h"
50 #include "ada.h"
51 #include "adadecode.h"
52 #include "types.h"
53 #include "atree.h"
54 #include "namet.h"
55 #include "nlists.h"
56 #include "snames.h"
57 #include "stringt.h"
58 #include "uintp.h"
59 #include "urealp.h"
60 #include "fe.h"
61 #include "sinfo.h"
62 #include "einfo.h"
63 #include "gadaint.h"
64 #include "ada-tree.h"
65 #include "gigi.h"
67 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
68 for fear of running out of stack space. If we need more, we use xmalloc
69 instead. */
70 #define ALLOCA_THRESHOLD 1000
72 /* Pointers to front-end tables accessed through macros. */
73 struct Node *Nodes_Ptr;
74 struct Flags *Flags_Ptr;
75 Node_Id *Next_Node_Ptr;
76 Node_Id *Prev_Node_Ptr;
77 struct Elist_Header *Elists_Ptr;
78 struct Elmt_Item *Elmts_Ptr;
79 struct String_Entry *Strings_Ptr;
80 Char_Code *String_Chars_Ptr;
81 struct List_Header *List_Headers_Ptr;
83 /* Highest number in the front-end node table. */
84 int max_gnat_nodes;
86 /* Current node being treated, in case abort called. */
87 Node_Id error_gnat_node;
89 /* True when gigi is being called on an analyzed but unexpanded
90 tree, and the only purpose of the call is to properly annotate
91 types with representation information. */
92 bool type_annotate_only;
94 /* List of N_Validate_Unchecked_Conversion nodes in the unit. */
95 static vec<Node_Id> gnat_validate_uc_list;
97 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
98 of unconstrained array IN parameters to avoid emitting a great deal of
99 redundant instructions to recompute them each time. */
100 struct GTY (()) parm_attr_d {
101 int id; /* GTY doesn't like Entity_Id. */
102 int dim;
103 tree first;
104 tree last;
105 tree length;
108 typedef struct parm_attr_d *parm_attr;
111 struct GTY(()) language_function {
112 vec<parm_attr, va_gc> *parm_attr_cache;
113 bitmap named_ret_val;
114 vec<tree, va_gc> *other_ret_val;
115 int gnat_ret;
118 #define f_parm_attr_cache \
119 DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
121 #define f_named_ret_val \
122 DECL_STRUCT_FUNCTION (current_function_decl)->language->named_ret_val
124 #define f_other_ret_val \
125 DECL_STRUCT_FUNCTION (current_function_decl)->language->other_ret_val
127 #define f_gnat_ret \
128 DECL_STRUCT_FUNCTION (current_function_decl)->language->gnat_ret
130 /* A structure used to gather together information about a statement group.
131 We use this to gather related statements, for example the "then" part
132 of a IF. In the case where it represents a lexical scope, we may also
133 have a BLOCK node corresponding to it and/or cleanups. */
135 struct GTY((chain_next ("%h.previous"))) stmt_group {
136 struct stmt_group *previous; /* Previous code group. */
137 tree stmt_list; /* List of statements for this code group. */
138 tree block; /* BLOCK for this code group, if any. */
139 tree cleanups; /* Cleanups for this code group, if any. */
142 static GTY(()) struct stmt_group *current_stmt_group;
144 /* List of unused struct stmt_group nodes. */
145 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
147 /* A structure used to record information on elaboration procedures
148 we've made and need to process.
150 ??? gnat_node should be Node_Id, but gengtype gets confused. */
152 struct GTY((chain_next ("%h.next"))) elab_info {
153 struct elab_info *next; /* Pointer to next in chain. */
154 tree elab_proc; /* Elaboration procedure. */
155 int gnat_node; /* The N_Compilation_Unit. */
158 static GTY(()) struct elab_info *elab_info_list;
160 /* Stack of exception pointer variables. Each entry is the VAR_DECL
161 that stores the address of the raised exception. Nonzero means we
162 are in an exception handler. Not used in the zero-cost case. */
163 static GTY(()) vec<tree, va_gc> *gnu_except_ptr_stack;
165 /* In ZCX case, current exception pointer. Used to re-raise it. */
166 static GTY(()) tree gnu_incoming_exc_ptr;
168 /* Stack for storing the current elaboration procedure decl. */
169 static GTY(()) vec<tree, va_gc> *gnu_elab_proc_stack;
171 /* Stack of labels to be used as a goto target instead of a return in
172 some functions. See processing for N_Subprogram_Body. */
173 static GTY(()) vec<tree, va_gc> *gnu_return_label_stack;
175 /* Stack of variable for the return value of a function with copy-in/copy-out
176 parameters. See processing for N_Subprogram_Body. */
177 static GTY(()) vec<tree, va_gc> *gnu_return_var_stack;
179 /* Structure used to record information for a range check. */
180 struct GTY(()) range_check_info_d {
181 tree low_bound;
182 tree high_bound;
183 tree disp;
184 bool neg_p;
185 tree type;
186 tree invariant_cond;
187 tree inserted_cond;
190 typedef struct range_check_info_d *range_check_info;
193 /* Structure used to record information for a loop. */
194 struct GTY(()) loop_info_d {
195 tree stmt;
196 tree loop_var;
197 tree low_bound;
198 tree high_bound;
199 vec<range_check_info, va_gc> *checks;
200 bool artificial;
201 bool has_checks;
202 bool warned_aggressive_loop_optimizations;
205 typedef struct loop_info_d *loop_info;
208 /* Stack of loop_info structures associated with LOOP_STMT nodes. */
209 static GTY(()) vec<loop_info, va_gc> *gnu_loop_stack;
211 /* The stacks for N_{Push,Pop}_*_Label. */
212 static GTY(()) vec<tree, va_gc> *gnu_constraint_error_label_stack;
213 static GTY(()) vec<tree, va_gc> *gnu_storage_error_label_stack;
214 static GTY(()) vec<tree, va_gc> *gnu_program_error_label_stack;
216 /* Map GNAT tree codes to GCC tree codes for simple expressions. */
217 static enum tree_code gnu_codes[Number_Node_Kinds];
219 static void init_code_table (void);
220 static void Compilation_Unit_to_gnu (Node_Id);
221 static void record_code_position (Node_Id);
222 static void insert_code_for (Node_Id);
223 static void add_cleanup (tree, Node_Id);
224 static void add_stmt_list (List_Id);
225 static void push_exception_label_stack (vec<tree, va_gc> **, Entity_Id);
226 static tree build_stmt_group (List_Id, bool);
227 static inline bool stmt_group_may_fallthru (void);
228 static enum gimplify_status gnat_gimplify_stmt (tree *);
229 static void elaborate_all_entities (Node_Id);
230 static void process_freeze_entity (Node_Id);
231 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
232 static tree emit_range_check (tree, Node_Id, Node_Id);
233 static tree emit_index_check (tree, tree, tree, tree, Node_Id);
234 static tree emit_check (tree, tree, int, Node_Id);
235 static tree build_unary_op_trapv (enum tree_code, tree, tree, Node_Id);
236 static tree build_binary_op_trapv (enum tree_code, tree, tree, tree, Node_Id);
237 static tree convert_with_check (Entity_Id, tree, bool, bool, bool, Node_Id);
238 static bool addressable_p (tree, tree);
239 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
240 static tree extract_values (tree, tree);
241 static tree pos_to_constructor (Node_Id, tree, Entity_Id);
242 static void validate_unchecked_conversion (Node_Id);
243 static tree maybe_implicit_deref (tree);
244 static void set_expr_location_from_node (tree, Node_Id, bool = false);
245 static void set_gnu_expr_location_from_node (tree, Node_Id);
246 static bool set_end_locus_from_node (tree, Node_Id);
247 static int lvalue_required_p (Node_Id, tree, bool, bool, bool);
248 static tree build_raise_check (int, enum exception_info_kind);
249 static tree create_init_temporary (const char *, tree, tree *, Node_Id);
251 /* Hooks for debug info back-ends, only supported and used in a restricted set
252 of configurations. */
253 static const char *extract_encoding (const char *) ATTRIBUTE_UNUSED;
254 static const char *decode_name (const char *) ATTRIBUTE_UNUSED;
256 /* This is the main program of the back-end. It sets up all the table
257 structures and then generates code. */
259 void
260 gigi (Node_Id gnat_root,
261 int max_gnat_node,
262 int number_name ATTRIBUTE_UNUSED,
263 struct Node *nodes_ptr,
264 struct Flags *flags_ptr,
265 Node_Id *next_node_ptr,
266 Node_Id *prev_node_ptr,
267 struct Elist_Header *elists_ptr,
268 struct Elmt_Item *elmts_ptr,
269 struct String_Entry *strings_ptr,
270 Char_Code *string_chars_ptr,
271 struct List_Header *list_headers_ptr,
272 Nat number_file,
273 struct File_Info_Type *file_info_ptr,
274 Entity_Id standard_boolean,
275 Entity_Id standard_integer,
276 Entity_Id standard_character,
277 Entity_Id standard_long_long_float,
278 Entity_Id standard_exception_type,
279 Int gigi_operating_mode)
281 Node_Id gnat_iter;
282 Entity_Id gnat_literal;
283 tree t, ftype, int64_type;
284 struct elab_info *info;
285 int i;
287 max_gnat_nodes = max_gnat_node;
289 Nodes_Ptr = nodes_ptr;
290 Flags_Ptr = flags_ptr;
291 Next_Node_Ptr = next_node_ptr;
292 Prev_Node_Ptr = prev_node_ptr;
293 Elists_Ptr = elists_ptr;
294 Elmts_Ptr = elmts_ptr;
295 Strings_Ptr = strings_ptr;
296 String_Chars_Ptr = string_chars_ptr;
297 List_Headers_Ptr = list_headers_ptr;
299 type_annotate_only = (gigi_operating_mode == 1);
301 for (i = 0; i < number_file; i++)
303 /* Use the identifier table to make a permanent copy of the filename as
304 the name table gets reallocated after Gigi returns but before all the
305 debugging information is output. The __gnat_to_canonical_file_spec
306 call translates filenames from pragmas Source_Reference that contain
307 host style syntax not understood by gdb. */
308 const char *filename
309 = IDENTIFIER_POINTER
310 (get_identifier
311 (__gnat_to_canonical_file_spec
312 (Get_Name_String (file_info_ptr[i].File_Name))));
314 /* We rely on the order isomorphism between files and line maps. */
315 gcc_assert ((int) LINEMAPS_ORDINARY_USED (line_table) == i);
317 /* We create the line map for a source file at once, with a fixed number
318 of columns chosen to avoid jumping over the next power of 2. */
319 linemap_add (line_table, LC_ENTER, 0, filename, 1);
320 linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
321 linemap_position_for_column (line_table, 252 - 1);
322 linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
325 gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
327 /* Declare the name of the compilation unit as the first global
328 name in order to make the middle-end fully deterministic. */
329 t = create_concat_name (Defining_Entity (Unit (gnat_root)), NULL);
330 first_global_object_name = ggc_strdup (IDENTIFIER_POINTER (t));
332 /* Initialize ourselves. */
333 init_code_table ();
334 init_gnat_decl ();
335 init_gnat_utils ();
337 /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
338 errors. */
339 if (type_annotate_only)
341 TYPE_SIZE (void_type_node) = bitsize_zero_node;
342 TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
345 /* Enable GNAT stack checking method if needed */
346 if (!Stack_Check_Probes_On_Target)
347 set_stack_check_libfunc ("_gnat_stack_check");
349 /* Retrieve alignment settings. */
350 double_float_alignment = get_target_double_float_alignment ();
351 double_scalar_alignment = get_target_double_scalar_alignment ();
353 /* Record the builtin types. Define `integer' and `character' first so that
354 dbx will output them first. */
355 record_builtin_type ("integer", integer_type_node, false);
356 record_builtin_type ("character", unsigned_char_type_node, false);
357 record_builtin_type ("boolean", boolean_type_node, false);
358 record_builtin_type ("void", void_type_node, false);
360 /* Save the type we made for integer as the type for Standard.Integer. */
361 save_gnu_tree (Base_Type (standard_integer),
362 TYPE_NAME (integer_type_node),
363 false);
365 /* Likewise for character as the type for Standard.Character. */
366 save_gnu_tree (Base_Type (standard_character),
367 TYPE_NAME (unsigned_char_type_node),
368 false);
370 /* Likewise for boolean as the type for Standard.Boolean. */
371 save_gnu_tree (Base_Type (standard_boolean),
372 TYPE_NAME (boolean_type_node),
373 false);
374 gnat_literal = First_Literal (Base_Type (standard_boolean));
375 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
376 gcc_assert (t == boolean_false_node);
377 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
378 boolean_type_node, t, true, false, false, false, false,
379 true, false, NULL, gnat_literal);
380 save_gnu_tree (gnat_literal, t, false);
381 gnat_literal = Next_Literal (gnat_literal);
382 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
383 gcc_assert (t == boolean_true_node);
384 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
385 boolean_type_node, t, true, false, false, false, false,
386 true, false, NULL, gnat_literal);
387 save_gnu_tree (gnat_literal, t, false);
389 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
390 ptr_void_ftype = build_pointer_type (void_ftype);
392 /* Now declare run-time functions. */
393 ftype = build_function_type_list (ptr_type_node, sizetype, NULL_TREE);
395 /* malloc is a function declaration tree for a function to allocate
396 memory. */
397 malloc_decl
398 = create_subprog_decl (get_identifier ("__gnat_malloc"), NULL_TREE,
399 ftype,
400 NULL_TREE, is_disabled, false, true, true, false,
401 true, false, NULL, Empty);
402 DECL_IS_MALLOC (malloc_decl) = 1;
404 /* free is a function declaration tree for a function to free memory. */
405 free_decl
406 = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
407 build_function_type_list (void_type_node,
408 ptr_type_node,
409 NULL_TREE),
410 NULL_TREE, is_disabled, false, true, true, false,
411 true, false, NULL, Empty);
413 /* This is used for 64-bit multiplication with overflow checking. */
414 int64_type = gnat_type_for_size (64, 0);
415 mulv64_decl
416 = create_subprog_decl (get_identifier ("__gnat_mulv64"), NULL_TREE,
417 build_function_type_list (int64_type, int64_type,
418 int64_type, NULL_TREE),
419 NULL_TREE, is_disabled, false, true, true, false,
420 true, false, NULL, Empty);
422 /* Name of the _Parent field in tagged record types. */
423 parent_name_id = get_identifier (Get_Name_String (Name_uParent));
425 /* Name of the Exception_Data type defined in System.Standard_Library. */
426 exception_data_name_id
427 = get_identifier ("system__standard_library__exception_data");
429 /* Make the types and functions used for exception processing. */
430 except_type_node = gnat_to_gnu_type (Base_Type (standard_exception_type));
432 jmpbuf_type
433 = build_array_type (gnat_type_for_mode (Pmode, 0),
434 build_index_type (size_int (5)));
435 record_builtin_type ("JMPBUF_T", jmpbuf_type, true);
436 jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
438 /* Functions to get and set the jumpbuf pointer for the current thread. */
439 get_jmpbuf_decl
440 = create_subprog_decl
441 (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
442 NULL_TREE, build_function_type_list (jmpbuf_ptr_type, NULL_TREE),
443 NULL_TREE, is_disabled, false, true, true, false, true, false,
444 NULL, Empty);
446 set_jmpbuf_decl
447 = create_subprog_decl
448 (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
449 NULL_TREE, build_function_type_list (void_type_node, jmpbuf_ptr_type,
450 NULL_TREE),
451 NULL_TREE, is_disabled, false, true, true, false, true, false,
452 NULL, Empty);
454 get_excptr_decl
455 = create_subprog_decl
456 (get_identifier ("system__soft_links__get_gnat_exception"), NULL_TREE,
457 build_function_type_list (build_pointer_type (except_type_node),
458 NULL_TREE),
459 NULL_TREE, is_disabled, false, true, true, false, true, false,
460 NULL, Empty);
462 not_handled_by_others_decl = get_identifier ("not_handled_by_others");
463 for (t = TYPE_FIELDS (except_type_node); t; t = DECL_CHAIN (t))
464 if (DECL_NAME (t) == not_handled_by_others_decl)
466 not_handled_by_others_decl = t;
467 break;
469 gcc_assert (DECL_P (not_handled_by_others_decl));
471 /* setjmp returns an integer and has one operand, which is a pointer to
472 a jmpbuf. */
473 setjmp_decl
474 = create_subprog_decl
475 (get_identifier ("__builtin_setjmp"), NULL_TREE,
476 build_function_type_list (integer_type_node, jmpbuf_ptr_type,
477 NULL_TREE),
478 NULL_TREE, is_disabled, false, true, true, false, true, false,
479 NULL, Empty);
480 DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
481 DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
483 /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
484 address. */
485 update_setjmp_buf_decl
486 = create_subprog_decl
487 (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
488 build_function_type_list (void_type_node, jmpbuf_ptr_type, NULL_TREE),
489 NULL_TREE, is_disabled, false, true, true, false, true, false,
490 NULL, Empty);
491 DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
492 DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
494 /* Indicate that it never returns. */
495 raise_nodefer_decl
496 = create_subprog_decl
497 (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE,
498 build_function_type_list (void_type_node,
499 build_pointer_type (except_type_node),
500 NULL_TREE),
501 NULL_TREE, is_disabled, false, true, true, true, true, false,
502 NULL, Empty);
504 /* Indicate that these never return. */
505 reraise_zcx_decl
506 = create_subprog_decl (get_identifier ("__gnat_reraise_zcx"), NULL_TREE,
507 ftype, NULL_TREE,
508 is_disabled, false, true, true, true, true, false,
509 NULL, Empty);
511 set_exception_parameter_decl
512 = create_subprog_decl
513 (get_identifier ("__gnat_set_exception_parameter"), NULL_TREE,
514 build_function_type_list (void_type_node, ptr_type_node, ptr_type_node,
515 NULL_TREE),
516 NULL_TREE, is_disabled, false, true, true, false, true, false,
517 NULL, Empty);
519 /* Hooks to call when entering/leaving an exception handler. */
520 ftype = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
522 begin_handler_decl
523 = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
524 ftype, NULL_TREE,
525 is_disabled, false, true, true, false, true, false,
526 NULL, Empty);
528 end_handler_decl
529 = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
530 ftype, NULL_TREE,
531 is_disabled, false, true, true, false, true, false,
532 NULL, Empty);
534 unhandled_except_decl
535 = create_subprog_decl (get_identifier ("__gnat_unhandled_except_handler"),
536 NULL_TREE, ftype, NULL_TREE,
537 is_disabled, false, true, true, false, true, false,
538 NULL, Empty);
540 /* Dummy objects to materialize "others" and "all others" in the exception
541 tables. These are exported by a-exexpr-gcc.adb, so see this unit for
542 the types to use. */
543 others_decl
544 = create_var_decl (get_identifier ("OTHERS"),
545 get_identifier ("__gnat_others_value"),
546 unsigned_char_type_node, NULL_TREE,
547 true, false, true, false, false, true, false,
548 NULL, Empty);
550 all_others_decl
551 = create_var_decl (get_identifier ("ALL_OTHERS"),
552 get_identifier ("__gnat_all_others_value"),
553 unsigned_char_type_node, NULL_TREE,
554 true, false, true, false, false, true, false,
555 NULL, Empty);
557 unhandled_others_decl
558 = create_var_decl (get_identifier ("UNHANDLED_OTHERS"),
559 get_identifier ("__gnat_unhandled_others_value"),
560 unsigned_char_type_node, NULL_TREE,
561 true, false, true, false, false, true, false,
562 NULL, Empty);
564 /* If in no exception handlers mode, all raise statements are redirected to
565 __gnat_last_chance_handler. No need to redefine raise_nodefer_decl since
566 this procedure will never be called in this mode. */
567 if (No_Exception_Handlers_Set ())
569 tree decl
570 = create_subprog_decl
571 (get_identifier ("__gnat_last_chance_handler"), NULL_TREE,
572 build_function_type_list (void_type_node,
573 build_pointer_type
574 (unsigned_char_type_node),
575 integer_type_node, NULL_TREE),
576 NULL_TREE, is_disabled, false, true, true, true, true, false,
577 NULL, Empty);
578 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
579 gnat_raise_decls[i] = decl;
581 else
583 /* Otherwise, make one decl for each exception reason. */
584 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
585 gnat_raise_decls[i] = build_raise_check (i, exception_simple);
586 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls_ext); i++)
587 gnat_raise_decls_ext[i]
588 = build_raise_check (i,
589 i == CE_Index_Check_Failed
590 || i == CE_Range_Check_Failed
591 || i == CE_Invalid_Data
592 ? exception_range : exception_column);
595 /* Build the special descriptor type and its null node if needed. */
596 if (TARGET_VTABLE_USES_DESCRIPTORS)
598 tree null_node = fold_convert (ptr_void_ftype, null_pointer_node);
599 tree field_list = NULL_TREE;
600 int j;
601 vec<constructor_elt, va_gc> *null_vec = NULL;
602 constructor_elt *elt;
604 fdesc_type_node = make_node (RECORD_TYPE);
605 vec_safe_grow (null_vec, TARGET_VTABLE_USES_DESCRIPTORS);
606 elt = (null_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
608 for (j = 0; j < TARGET_VTABLE_USES_DESCRIPTORS; j++)
610 tree field
611 = create_field_decl (NULL_TREE, ptr_void_ftype, fdesc_type_node,
612 NULL_TREE, NULL_TREE, 0, 1);
613 DECL_CHAIN (field) = field_list;
614 field_list = field;
615 elt->index = field;
616 elt->value = null_node;
617 elt--;
620 finish_record_type (fdesc_type_node, nreverse (field_list), 0, false);
621 record_builtin_type ("descriptor", fdesc_type_node, true);
622 null_fdesc_node = gnat_build_constructor (fdesc_type_node, null_vec);
625 longest_float_type_node
626 = get_unpadded_type (Base_Type (standard_long_long_float));
628 main_identifier_node = get_identifier ("main");
630 /* Install the builtins we might need, either internally or as
631 user available facilities for Intrinsic imports. */
632 gnat_install_builtins ();
634 vec_safe_push (gnu_except_ptr_stack, NULL_TREE);
635 vec_safe_push (gnu_constraint_error_label_stack, NULL_TREE);
636 vec_safe_push (gnu_storage_error_label_stack, NULL_TREE);
637 vec_safe_push (gnu_program_error_label_stack, NULL_TREE);
639 /* Process any Pragma Ident for the main unit. */
640 if (Present (Ident_String (Main_Unit)))
641 targetm.asm_out.output_ident
642 (TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
644 /* If we are using the GCC exception mechanism, let GCC know. */
645 if (Back_End_Exceptions ())
646 gnat_init_gcc_eh ();
648 /* Initialize the GCC support for FP operations. */
649 gnat_init_gcc_fp ();
651 /* Force -fno-strict-aliasing if the configuration pragma was seen. */
652 if (No_Strict_Aliasing_CP)
653 flag_strict_aliasing = 0;
655 /* Save the current optimization options again after the above possible
656 global_options changes. */
657 optimization_default_node = build_optimization_node (&global_options);
658 optimization_current_node = optimization_default_node;
660 /* Now translate the compilation unit proper. */
661 Compilation_Unit_to_gnu (gnat_root);
663 /* Disable -Waggressive-loop-optimizations since we implement our own
664 version of the warning. */
665 warn_aggressive_loop_optimizations = 0;
667 /* Then process the N_Validate_Unchecked_Conversion nodes. We do this at
668 the very end to avoid having to second-guess the front-end when we run
669 into dummy nodes during the regular processing. */
670 for (i = 0; gnat_validate_uc_list.iterate (i, &gnat_iter); i++)
671 validate_unchecked_conversion (gnat_iter);
672 gnat_validate_uc_list.release ();
674 /* Finally see if we have any elaboration procedures to deal with. */
675 for (info = elab_info_list; info; info = info->next)
677 tree gnu_body = DECL_SAVED_TREE (info->elab_proc), gnu_stmts;
679 /* We should have a BIND_EXPR but it may not have any statements in it.
680 If it doesn't have any, we have nothing to do except for setting the
681 flag on the GNAT node. Otherwise, process the function as others. */
682 gnu_stmts = gnu_body;
683 if (TREE_CODE (gnu_stmts) == BIND_EXPR)
684 gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
685 if (!gnu_stmts || !STATEMENT_LIST_HEAD (gnu_stmts))
686 Set_Has_No_Elaboration_Code (info->gnat_node, 1);
687 else
689 begin_subprog_body (info->elab_proc);
690 end_subprog_body (gnu_body);
691 rest_of_subprog_body_compilation (info->elab_proc);
695 /* Destroy ourselves. */
696 destroy_gnat_decl ();
697 destroy_gnat_utils ();
699 /* We cannot track the location of errors past this point. */
700 error_gnat_node = Empty;
703 /* Return a subprogram decl corresponding to __gnat_rcheck_xx for the given
704 CHECK if KIND is EXCEPTION_SIMPLE, or else to __gnat_rcheck_xx_ext. */
706 static tree
707 build_raise_check (int check, enum exception_info_kind kind)
709 tree result, ftype;
710 const char pfx[] = "__gnat_rcheck_";
712 strcpy (Name_Buffer, pfx);
713 Name_Len = sizeof (pfx) - 1;
714 Get_RT_Exception_Name (check);
716 if (kind == exception_simple)
718 Name_Buffer[Name_Len] = 0;
719 ftype
720 = build_function_type_list (void_type_node,
721 build_pointer_type
722 (unsigned_char_type_node),
723 integer_type_node, NULL_TREE);
725 else
727 tree t = (kind == exception_column ? NULL_TREE : integer_type_node);
729 strcpy (Name_Buffer + Name_Len, "_ext");
730 Name_Buffer[Name_Len + 4] = 0;
731 ftype
732 = build_function_type_list (void_type_node,
733 build_pointer_type
734 (unsigned_char_type_node),
735 integer_type_node, integer_type_node,
736 t, t, NULL_TREE);
739 /* Indicate that it never returns. */
740 result
741 = create_subprog_decl (get_identifier (Name_Buffer), NULL_TREE,
742 ftype, NULL_TREE,
743 is_disabled, false, true, true, true, true, false,
744 NULL, Empty);
746 return result;
749 /* Return a positive value if an lvalue is required for GNAT_NODE, which is
750 an N_Attribute_Reference. */
752 static int
753 lvalue_required_for_attribute_p (Node_Id gnat_node)
755 switch (Get_Attribute_Id (Attribute_Name (gnat_node)))
757 case Attr_Pos:
758 case Attr_Val:
759 case Attr_Pred:
760 case Attr_Succ:
761 case Attr_First:
762 case Attr_Last:
763 case Attr_Range_Length:
764 case Attr_Length:
765 case Attr_Object_Size:
766 case Attr_Value_Size:
767 case Attr_Component_Size:
768 case Attr_Descriptor_Size:
769 case Attr_Max_Size_In_Storage_Elements:
770 case Attr_Min:
771 case Attr_Max:
772 case Attr_Null_Parameter:
773 case Attr_Passed_By_Reference:
774 case Attr_Mechanism_Code:
775 case Attr_Machine:
776 case Attr_Model:
777 return 0;
779 case Attr_Address:
780 case Attr_Access:
781 case Attr_Unchecked_Access:
782 case Attr_Unrestricted_Access:
783 case Attr_Code_Address:
784 case Attr_Pool_Address:
785 case Attr_Size:
786 case Attr_Alignment:
787 case Attr_Bit_Position:
788 case Attr_Position:
789 case Attr_First_Bit:
790 case Attr_Last_Bit:
791 case Attr_Bit:
792 case Attr_Asm_Input:
793 case Attr_Asm_Output:
794 default:
795 return 1;
799 /* Return a positive value if an lvalue is required for GNAT_NODE. GNU_TYPE
800 is the type that will be used for GNAT_NODE in the translated GNU tree.
801 CONSTANT indicates whether the underlying object represented by GNAT_NODE
802 is constant in the Ada sense. If it is, ADDRESS_OF_CONSTANT indicates
803 whether its value is the address of a constant and ALIASED whether it is
804 aliased. If it isn't, ADDRESS_OF_CONSTANT and ALIASED are ignored.
806 The function climbs up the GNAT tree starting from the node and returns 1
807 upon encountering a node that effectively requires an lvalue downstream.
808 It returns int instead of bool to facilitate usage in non-purely binary
809 logic contexts. */
811 static int
812 lvalue_required_p (Node_Id gnat_node, tree gnu_type, bool constant,
813 bool address_of_constant, bool aliased)
815 Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
817 switch (Nkind (gnat_parent))
819 case N_Reference:
820 return 1;
822 case N_Attribute_Reference:
823 return lvalue_required_for_attribute_p (gnat_parent);
825 case N_Parameter_Association:
826 case N_Function_Call:
827 case N_Procedure_Call_Statement:
828 /* If the parameter is by reference, an lvalue is required. */
829 return (!constant
830 || must_pass_by_ref (gnu_type)
831 || default_pass_by_ref (gnu_type));
833 case N_Indexed_Component:
834 /* Only the array expression can require an lvalue. */
835 if (Prefix (gnat_parent) != gnat_node)
836 return 0;
838 /* ??? Consider that referencing an indexed component with a variable
839 index forces the whole aggregate to memory. Note that testing only
840 for literals is conservative, any static expression in the RM sense
841 could probably be accepted with some additional work. */
842 for (gnat_temp = First (Expressions (gnat_parent));
843 Present (gnat_temp);
844 gnat_temp = Next (gnat_temp))
845 if (Nkind (gnat_temp) != N_Character_Literal
846 && Nkind (gnat_temp) != N_Integer_Literal
847 && !(Is_Entity_Name (gnat_temp)
848 && Ekind (Entity (gnat_temp)) == E_Enumeration_Literal))
849 return 1;
851 /* ... fall through ... */
853 case N_Slice:
854 /* Only the array expression can require an lvalue. */
855 if (Prefix (gnat_parent) != gnat_node)
856 return 0;
858 aliased |= Has_Aliased_Components (Etype (gnat_node));
859 return lvalue_required_p (gnat_parent, gnu_type, constant,
860 address_of_constant, aliased);
862 case N_Selected_Component:
863 aliased |= Is_Aliased (Entity (Selector_Name (gnat_parent)));
864 return lvalue_required_p (gnat_parent, gnu_type, constant,
865 address_of_constant, aliased);
867 case N_Object_Renaming_Declaration:
868 /* We need to preserve addresses through a renaming. */
869 return 1;
871 case N_Object_Declaration:
872 /* We cannot use a constructor if this is an atomic object because
873 the actual assignment might end up being done component-wise. */
874 return (!constant
875 ||(Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
876 && Is_Atomic_Or_VFA (Defining_Entity (gnat_parent)))
877 /* We don't use a constructor if this is a class-wide object
878 because the effective type of the object is the equivalent
879 type of the class-wide subtype and it smashes most of the
880 data into an array of bytes to which we cannot convert. */
881 || Ekind ((Etype (Defining_Entity (gnat_parent))))
882 == E_Class_Wide_Subtype);
884 case N_Assignment_Statement:
885 /* We cannot use a constructor if the LHS is an atomic object because
886 the actual assignment might end up being done component-wise. */
887 return (!constant
888 || Name (gnat_parent) == gnat_node
889 || (Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
890 && Is_Entity_Name (Name (gnat_parent))
891 && Is_Atomic_Or_VFA (Entity (Name (gnat_parent)))));
893 case N_Unchecked_Type_Conversion:
894 if (!constant)
895 return 1;
897 /* ... fall through ... */
899 case N_Type_Conversion:
900 case N_Qualified_Expression:
901 /* We must look through all conversions because we may need to bypass
902 an intermediate conversion that is meant to be purely formal. */
903 return lvalue_required_p (gnat_parent,
904 get_unpadded_type (Etype (gnat_parent)),
905 constant, address_of_constant, aliased);
907 case N_Allocator:
908 /* We should only reach here through the N_Qualified_Expression case.
909 Force an lvalue for composite types since a block-copy to the newly
910 allocated area of memory is made. */
911 return Is_Composite_Type (Underlying_Type (Etype (gnat_node)));
913 case N_Explicit_Dereference:
914 /* We look through dereferences for address of constant because we need
915 to handle the special cases listed above. */
916 if (constant && address_of_constant)
917 return lvalue_required_p (gnat_parent,
918 get_unpadded_type (Etype (gnat_parent)),
919 true, false, true);
921 /* ... fall through ... */
923 default:
924 return 0;
927 gcc_unreachable ();
930 /* Return true if T is a constant DECL node that can be safely replaced
931 by its initializer. */
933 static bool
934 constant_decl_with_initializer_p (tree t)
936 if (!TREE_CONSTANT (t) || !DECL_P (t) || !DECL_INITIAL (t))
937 return false;
939 /* Return false for aggregate types that contain a placeholder since
940 their initializers cannot be manipulated easily. */
941 if (AGGREGATE_TYPE_P (TREE_TYPE (t))
942 && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (t))
943 && type_contains_placeholder_p (TREE_TYPE (t)))
944 return false;
946 return true;
949 /* Return an expression equivalent to EXP but where constant DECL nodes
950 have been replaced by their initializer. */
952 static tree
953 fold_constant_decl_in_expr (tree exp)
955 enum tree_code code = TREE_CODE (exp);
956 tree op0;
958 switch (code)
960 case CONST_DECL:
961 case VAR_DECL:
962 if (!constant_decl_with_initializer_p (exp))
963 return exp;
965 return DECL_INITIAL (exp);
967 case BIT_FIELD_REF:
968 case COMPONENT_REF:
969 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
970 if (op0 == TREE_OPERAND (exp, 0))
971 return exp;
973 return fold_build3 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
974 TREE_OPERAND (exp, 2));
976 case ARRAY_REF:
977 case ARRAY_RANGE_REF:
978 /* If the index is not itself constant, then nothing can be folded. */
979 if (!TREE_CONSTANT (TREE_OPERAND (exp, 1)))
980 return exp;
981 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
982 if (op0 == TREE_OPERAND (exp, 0))
983 return exp;
985 return fold (build4 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
986 TREE_OPERAND (exp, 2), TREE_OPERAND (exp, 3)));
988 case REALPART_EXPR:
989 case IMAGPART_EXPR:
990 case VIEW_CONVERT_EXPR:
991 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
992 if (op0 == TREE_OPERAND (exp, 0))
993 return exp;
995 return fold_build1 (code, TREE_TYPE (exp), op0);
997 default:
998 return exp;
1001 gcc_unreachable ();
1004 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Identifier,
1005 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer
1006 to where we should place the result type. */
1008 static tree
1009 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
1011 Node_Id gnat_temp, gnat_temp_type;
1012 tree gnu_result, gnu_result_type;
1014 /* Whether we should require an lvalue for GNAT_NODE. Needed in
1015 specific circumstances only, so evaluated lazily. < 0 means
1016 unknown, > 0 means known true, 0 means known false. */
1017 int require_lvalue = -1;
1019 /* If GNAT_NODE is a constant, whether we should use the initialization
1020 value instead of the constant entity, typically for scalars with an
1021 address clause when the parent doesn't require an lvalue. */
1022 bool use_constant_initializer = false;
1024 /* If the Etype of this node does not equal the Etype of the Entity,
1025 something is wrong with the entity map, probably in generic
1026 instantiation. However, this does not apply to types. Since we sometime
1027 have strange Ekind's, just do this test for objects. Also, if the Etype of
1028 the Entity is private, the Etype of the N_Identifier is allowed to be the
1029 full type and also we consider a packed array type to be the same as the
1030 original type. Similarly, a class-wide type is equivalent to a subtype of
1031 itself. Finally, if the types are Itypes, one may be a copy of the other,
1032 which is also legal. */
1033 gnat_temp = ((Nkind (gnat_node) == N_Defining_Identifier
1034 || Nkind (gnat_node) == N_Defining_Operator_Symbol)
1035 ? gnat_node : Entity (gnat_node));
1036 gnat_temp_type = Etype (gnat_temp);
1038 gcc_assert (Etype (gnat_node) == gnat_temp_type
1039 || (Is_Packed (gnat_temp_type)
1040 && (Etype (gnat_node)
1041 == Packed_Array_Impl_Type (gnat_temp_type)))
1042 || (Is_Class_Wide_Type (Etype (gnat_node)))
1043 || (IN (Ekind (gnat_temp_type), Private_Kind)
1044 && Present (Full_View (gnat_temp_type))
1045 && ((Etype (gnat_node) == Full_View (gnat_temp_type))
1046 || (Is_Packed (Full_View (gnat_temp_type))
1047 && (Etype (gnat_node)
1048 == Packed_Array_Impl_Type
1049 (Full_View (gnat_temp_type))))))
1050 || (Is_Itype (Etype (gnat_node)) && Is_Itype (gnat_temp_type))
1051 || !(Ekind (gnat_temp) == E_Variable
1052 || Ekind (gnat_temp) == E_Component
1053 || Ekind (gnat_temp) == E_Constant
1054 || Ekind (gnat_temp) == E_Loop_Parameter
1055 || IN (Ekind (gnat_temp), Formal_Kind)));
1057 /* If this is a reference to a deferred constant whose partial view is an
1058 unconstrained private type, the proper type is on the full view of the
1059 constant, not on the full view of the type, which may be unconstrained.
1061 This may be a reference to a type, for example in the prefix of the
1062 attribute Position, generated for dispatching code (see Make_DT in
1063 exp_disp,adb). In that case we need the type itself, not is parent,
1064 in particular if it is a derived type */
1065 if (Ekind (gnat_temp) == E_Constant
1066 && Is_Private_Type (gnat_temp_type)
1067 && (Has_Unknown_Discriminants (gnat_temp_type)
1068 || (Present (Full_View (gnat_temp_type))
1069 && Has_Discriminants (Full_View (gnat_temp_type))))
1070 && Present (Full_View (gnat_temp)))
1072 gnat_temp = Full_View (gnat_temp);
1073 gnat_temp_type = Etype (gnat_temp);
1075 else
1077 /* We want to use the Actual_Subtype if it has already been elaborated,
1078 otherwise the Etype. Avoid using Actual_Subtype for packed arrays to
1079 simplify things. */
1080 if ((Ekind (gnat_temp) == E_Constant
1081 || Ekind (gnat_temp) == E_Variable || Is_Formal (gnat_temp))
1082 && !(Is_Array_Type (Etype (gnat_temp))
1083 && Present (Packed_Array_Impl_Type (Etype (gnat_temp))))
1084 && Present (Actual_Subtype (gnat_temp))
1085 && present_gnu_tree (Actual_Subtype (gnat_temp)))
1086 gnat_temp_type = Actual_Subtype (gnat_temp);
1087 else
1088 gnat_temp_type = Etype (gnat_node);
1091 /* Expand the type of this identifier first, in case it is an enumeral
1092 literal, which only get made when the type is expanded. There is no
1093 order-of-elaboration issue here. */
1094 gnu_result_type = get_unpadded_type (gnat_temp_type);
1096 /* If this is a non-imported elementary constant with an address clause,
1097 retrieve the value instead of a pointer to be dereferenced unless
1098 an lvalue is required. This is generally more efficient and actually
1099 required if this is a static expression because it might be used
1100 in a context where a dereference is inappropriate, such as a case
1101 statement alternative or a record discriminant. There is no possible
1102 volatile-ness short-circuit here since Volatile constants must be
1103 imported per C.6. */
1104 if (Ekind (gnat_temp) == E_Constant
1105 && Is_Elementary_Type (gnat_temp_type)
1106 && !Is_Imported (gnat_temp)
1107 && Present (Address_Clause (gnat_temp)))
1109 require_lvalue = lvalue_required_p (gnat_node, gnu_result_type, true,
1110 false, Is_Aliased (gnat_temp));
1111 use_constant_initializer = !require_lvalue;
1114 if (use_constant_initializer)
1116 /* If this is a deferred constant, the initializer is attached to
1117 the full view. */
1118 if (Present (Full_View (gnat_temp)))
1119 gnat_temp = Full_View (gnat_temp);
1121 gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_temp)));
1123 else
1124 gnu_result = gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0);
1126 /* Some objects (such as parameters passed by reference, globals of
1127 variable size, and renamed objects) actually represent the address
1128 of the object. In that case, we must do the dereference. Likewise,
1129 deal with parameters to foreign convention subprograms. */
1130 if (DECL_P (gnu_result)
1131 && (DECL_BY_REF_P (gnu_result)
1132 || (TREE_CODE (gnu_result) == PARM_DECL
1133 && DECL_BY_COMPONENT_PTR_P (gnu_result))))
1135 const bool read_only = DECL_POINTS_TO_READONLY_P (gnu_result);
1137 /* If it's a PARM_DECL to foreign convention subprogram, convert it. */
1138 if (TREE_CODE (gnu_result) == PARM_DECL
1139 && DECL_BY_COMPONENT_PTR_P (gnu_result))
1140 gnu_result
1141 = convert (build_pointer_type (gnu_result_type), gnu_result);
1143 /* If it's a CONST_DECL, return the underlying constant like below. */
1144 else if (TREE_CODE (gnu_result) == CONST_DECL
1145 && !(DECL_CONST_ADDRESS_P (gnu_result)
1146 && lvalue_required_p (gnat_node, gnu_result_type, true,
1147 true, false)))
1148 gnu_result = DECL_INITIAL (gnu_result);
1150 /* If it's a renaming pointer, get to the renamed object. */
1151 if (TREE_CODE (gnu_result) == VAR_DECL
1152 && !DECL_LOOP_PARM_P (gnu_result)
1153 && DECL_RENAMED_OBJECT (gnu_result))
1154 gnu_result = DECL_RENAMED_OBJECT (gnu_result);
1156 /* Otherwise, do the final dereference. */
1157 else
1159 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1161 if ((TREE_CODE (gnu_result) == INDIRECT_REF
1162 || TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
1163 && No (Address_Clause (gnat_temp)))
1164 TREE_THIS_NOTRAP (gnu_result) = 1;
1166 if (read_only)
1167 TREE_READONLY (gnu_result) = 1;
1171 /* If we have a constant declaration and its initializer, try to return the
1172 latter to avoid the need to call fold in lots of places and the need for
1173 elaboration code if this identifier is used as an initializer itself. */
1174 if (constant_decl_with_initializer_p (gnu_result))
1176 bool constant_only = (TREE_CODE (gnu_result) == CONST_DECL
1177 && !DECL_CONST_CORRESPONDING_VAR (gnu_result));
1178 bool address_of_constant = (TREE_CODE (gnu_result) == CONST_DECL
1179 && DECL_CONST_ADDRESS_P (gnu_result));
1181 /* If there is a (corresponding) variable or this is the address of a
1182 constant, we only want to return the initializer if an lvalue isn't
1183 required. Evaluate this now if we have not already done so. */
1184 if ((!constant_only || address_of_constant) && require_lvalue < 0)
1185 require_lvalue
1186 = lvalue_required_p (gnat_node, gnu_result_type, true,
1187 address_of_constant, Is_Aliased (gnat_temp));
1189 /* Finally retrieve the initializer if this is deemed valid. */
1190 if ((constant_only && !address_of_constant) || !require_lvalue)
1191 gnu_result = DECL_INITIAL (gnu_result);
1194 /* But for a constant renaming we couldn't do that incrementally for its
1195 definition because of the need to return an lvalue so, if the present
1196 context doesn't itself require an lvalue, we try again here. */
1197 else if (Ekind (gnat_temp) == E_Constant
1198 && Is_Elementary_Type (gnat_temp_type)
1199 && Present (Renamed_Object (gnat_temp)))
1201 if (require_lvalue < 0)
1202 require_lvalue
1203 = lvalue_required_p (gnat_node, gnu_result_type, true, false,
1204 Is_Aliased (gnat_temp));
1205 if (!require_lvalue)
1206 gnu_result = fold_constant_decl_in_expr (gnu_result);
1209 /* The GNAT tree has the type of a function set to its result type, so we
1210 adjust here. Also use the type of the result if the Etype is a subtype
1211 that is nominally unconstrained. Likewise if this is a deferred constant
1212 of a discriminated type whose full view can be elaborated statically, to
1213 avoid problematic conversions to the nominal subtype. But remove any
1214 padding from the resulting type. */
1215 if (TREE_CODE (TREE_TYPE (gnu_result)) == FUNCTION_TYPE
1216 || Is_Constr_Subt_For_UN_Aliased (gnat_temp_type)
1217 || (Ekind (gnat_temp) == E_Constant
1218 && Present (Full_View (gnat_temp))
1219 && Has_Discriminants (gnat_temp_type)
1220 && TREE_CODE (gnu_result) == CONSTRUCTOR))
1222 gnu_result_type = TREE_TYPE (gnu_result);
1223 if (TYPE_IS_PADDING_P (gnu_result_type))
1224 gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
1227 *gnu_result_type_p = gnu_result_type;
1229 return gnu_result;
1232 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Pragma. Return
1233 any statements we generate. */
1235 static tree
1236 Pragma_to_gnu (Node_Id gnat_node)
1238 tree gnu_result = alloc_stmt_list ();
1239 unsigned char pragma_id;
1240 Node_Id gnat_temp;
1242 /* Do nothing if we are just annotating types and check for (and ignore)
1243 unrecognized pragmas. */
1244 if (type_annotate_only
1245 || !Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
1246 return gnu_result;
1248 pragma_id = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node)));
1249 switch (pragma_id)
1251 case Pragma_Inspection_Point:
1252 /* Do nothing at top level: all such variables are already viewable. */
1253 if (global_bindings_p ())
1254 break;
1256 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1257 Present (gnat_temp);
1258 gnat_temp = Next (gnat_temp))
1260 Node_Id gnat_expr = Expression (gnat_temp);
1261 tree gnu_expr = gnat_to_gnu (gnat_expr);
1262 int use_address;
1263 machine_mode mode;
1264 tree asm_constraint = NULL_TREE;
1265 #ifdef ASM_COMMENT_START
1266 char *comment;
1267 #endif
1269 if (TREE_CODE (gnu_expr) == UNCONSTRAINED_ARRAY_REF)
1270 gnu_expr = TREE_OPERAND (gnu_expr, 0);
1272 /* Use the value only if it fits into a normal register,
1273 otherwise use the address. */
1274 mode = TYPE_MODE (TREE_TYPE (gnu_expr));
1275 use_address = ((GET_MODE_CLASS (mode) != MODE_INT
1276 && GET_MODE_CLASS (mode) != MODE_PARTIAL_INT)
1277 || GET_MODE_SIZE (mode) > UNITS_PER_WORD);
1279 if (use_address)
1280 gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
1282 #ifdef ASM_COMMENT_START
1283 comment = concat (ASM_COMMENT_START,
1284 " inspection point: ",
1285 Get_Name_String (Chars (gnat_expr)),
1286 use_address ? " address" : "",
1287 " is in %0",
1288 NULL);
1289 asm_constraint = build_string (strlen (comment), comment);
1290 free (comment);
1291 #endif
1292 gnu_expr = build5 (ASM_EXPR, void_type_node,
1293 asm_constraint,
1294 NULL_TREE,
1295 tree_cons
1296 (build_tree_list (NULL_TREE,
1297 build_string (1, "g")),
1298 gnu_expr, NULL_TREE),
1299 NULL_TREE, NULL_TREE);
1300 ASM_VOLATILE_P (gnu_expr) = 1;
1301 set_expr_location_from_node (gnu_expr, gnat_node);
1302 append_to_statement_list (gnu_expr, &gnu_result);
1304 break;
1306 case Pragma_Loop_Optimize:
1307 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1308 Present (gnat_temp);
1309 gnat_temp = Next (gnat_temp))
1311 tree gnu_loop_stmt = gnu_loop_stack->last ()->stmt;
1313 switch (Chars (Expression (gnat_temp)))
1315 case Name_Ivdep:
1316 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
1317 break;
1319 case Name_No_Unroll:
1320 LOOP_STMT_NO_UNROLL (gnu_loop_stmt) = 1;
1321 break;
1323 case Name_Unroll:
1324 LOOP_STMT_UNROLL (gnu_loop_stmt) = 1;
1325 break;
1327 case Name_No_Vector:
1328 LOOP_STMT_NO_VECTOR (gnu_loop_stmt) = 1;
1329 break;
1331 case Name_Vector:
1332 LOOP_STMT_VECTOR (gnu_loop_stmt) = 1;
1333 break;
1335 default:
1336 gcc_unreachable ();
1339 break;
1341 case Pragma_Optimize:
1342 switch (Chars (Expression
1343 (First (Pragma_Argument_Associations (gnat_node)))))
1345 case Name_Off:
1346 if (optimize)
1347 post_error ("must specify -O0?", gnat_node);
1348 break;
1350 case Name_Space:
1351 if (!optimize_size)
1352 post_error ("must specify -Os?", gnat_node);
1353 break;
1355 case Name_Time:
1356 if (!optimize)
1357 post_error ("insufficient -O value?", gnat_node);
1358 break;
1360 default:
1361 gcc_unreachable ();
1363 break;
1365 case Pragma_Reviewable:
1366 if (write_symbols == NO_DEBUG)
1367 post_error ("must specify -g?", gnat_node);
1368 break;
1370 case Pragma_Warning_As_Error:
1371 case Pragma_Warnings:
1373 Node_Id gnat_expr;
1374 /* Preserve the location of the pragma. */
1375 const location_t location = input_location;
1376 struct cl_option_handlers handlers;
1377 unsigned int option_index;
1378 diagnostic_t kind;
1379 bool imply;
1381 gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1383 /* This is the String form: pragma Warning{s|_As_Error}(String). */
1384 if (Nkind (Expression (gnat_temp)) == N_String_Literal)
1386 switch (pragma_id)
1388 case Pragma_Warning_As_Error:
1389 kind = DK_ERROR;
1390 imply = false;
1391 break;
1393 case Pragma_Warnings:
1394 kind = DK_WARNING;
1395 imply = true;
1396 break;
1398 default:
1399 gcc_unreachable ();
1402 gnat_expr = Expression (gnat_temp);
1405 /* This is the On/Off form: pragma Warnings (On | Off [,String]). */
1406 else if (Nkind (Expression (gnat_temp)) == N_Identifier)
1408 switch (Chars (Expression (gnat_temp)))
1410 case Name_Off:
1411 kind = DK_IGNORED;
1412 break;
1414 case Name_On:
1415 kind = DK_WARNING;
1416 break;
1418 default:
1419 gcc_unreachable ();
1422 /* Deal with optional pattern (but ignore Reason => "..."). */
1423 if (Present (Next (gnat_temp))
1424 && Chars (Next (gnat_temp)) != Name_Reason)
1426 /* pragma Warnings (On | Off, Name) is handled differently. */
1427 if (Nkind (Expression (Next (gnat_temp))) != N_String_Literal)
1428 break;
1430 gnat_expr = Expression (Next (gnat_temp));
1432 else
1433 gnat_expr = Empty;
1435 imply = false;
1438 else
1439 gcc_unreachable ();
1441 /* This is the same implementation as in the C family of compilers. */
1442 const unsigned int lang_mask = CL_Ada | CL_COMMON;
1443 if (Present (gnat_expr))
1445 tree gnu_expr = gnat_to_gnu (gnat_expr);
1446 const char *option_string = TREE_STRING_POINTER (gnu_expr);
1447 const int len = TREE_STRING_LENGTH (gnu_expr);
1448 if (len < 3 || option_string[0] != '-' || option_string[1] != 'W')
1449 break;
1450 option_index = find_opt (option_string + 1, lang_mask);
1451 if (option_index == OPT_SPECIAL_unknown)
1453 post_error ("?unknown -W switch", gnat_node);
1454 break;
1456 else if (!(cl_options[option_index].flags & CL_WARNING))
1458 post_error ("?-W switch does not control warning", gnat_node);
1459 break;
1461 else if (!(cl_options[option_index].flags & lang_mask))
1463 post_error ("?-W switch not valid for Ada", gnat_node);
1464 break;
1467 else
1468 option_index = 0;
1470 set_default_handlers (&handlers);
1471 control_warning_option (option_index, (int) kind, imply, location,
1472 lang_mask, &handlers, &global_options,
1473 &global_options_set, global_dc);
1475 break;
1477 default:
1478 break;
1481 return gnu_result;
1485 /* Check the inlining status of nested function FNDECL in the current context.
1487 If a non-inline nested function is referenced from an inline external
1488 function, we cannot honor both requests at the same time without cloning
1489 the nested function in the current unit since it is private to its unit.
1490 We could inline it as well but it's probably better to err on the side
1491 of too little inlining.
1493 This must be invoked only on nested functions present in the source code
1494 and not on nested functions generated by the compiler, e.g. finalizers,
1495 because they are not marked inline and we don't want them to block the
1496 inlining of the parent function. */
1498 static void
1499 check_inlining_for_nested_subprog (tree fndecl)
1501 if (!DECL_DECLARED_INLINE_P (fndecl)
1502 && current_function_decl
1503 && DECL_EXTERNAL (current_function_decl)
1504 && DECL_DECLARED_INLINE_P (current_function_decl))
1506 const location_t loc1 = DECL_SOURCE_LOCATION (fndecl);
1507 const location_t loc2 = DECL_SOURCE_LOCATION (current_function_decl);
1509 if (lookup_attribute ("always_inline",
1510 DECL_ATTRIBUTES (current_function_decl)))
1512 error_at (loc1, "subprogram %q+F not marked Inline_Always", fndecl);
1513 error_at (loc2, "parent subprogram cannot be inlined");
1515 else
1517 warning_at (loc1, OPT_Winline, "subprogram %q+F not marked Inline",
1518 fndecl);
1519 warning_at (loc2, OPT_Winline, "parent subprogram cannot be inlined");
1522 DECL_DECLARED_INLINE_P (current_function_decl) = 0;
1523 DECL_UNINLINABLE (current_function_decl) = 1;
1527 /* Return an expression for the length of TYPE, an integral type, computed in
1528 RESULT_TYPE, another integral type.
1530 We used to compute the length as MAX (hb - lb + 1, 0) which could overflow
1531 when lb == TYPE'First. We now compute it as (hb >= lb) ? hb - lb + 1 : 0
1532 which would only overflow in much rarer cases, for extremely large arrays
1533 we expect never to encounter in practice. Besides, the former computation
1534 required the use of potentially constraining signed arithmetics while the
1535 latter does not. Note that the comparison must be done in the original
1536 base index type in order to avoid any overflow during the conversion. */
1538 static tree
1539 get_type_length (tree type, tree result_type)
1541 tree comp_type = get_base_type (result_type);
1542 tree base_type = get_base_type (type);
1543 tree lb = convert (base_type, TYPE_MIN_VALUE (type));
1544 tree hb = convert (base_type, TYPE_MAX_VALUE (type));
1545 tree length
1546 = build_binary_op (PLUS_EXPR, comp_type,
1547 build_binary_op (MINUS_EXPR, comp_type,
1548 convert (comp_type, hb),
1549 convert (comp_type, lb)),
1550 convert (comp_type, integer_one_node));
1551 length
1552 = build_cond_expr (result_type,
1553 build_binary_op (GE_EXPR, boolean_type_node, hb, lb),
1554 convert (result_type, length),
1555 convert (result_type, integer_zero_node));
1556 return length;
1559 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Attribute node,
1560 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to
1561 where we should place the result type. ATTRIBUTE is the attribute ID. */
1563 static tree
1564 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
1566 const Node_Id gnat_prefix = Prefix (gnat_node);
1567 tree gnu_prefix, gnu_type, gnu_expr;
1568 tree gnu_result_type, gnu_result = error_mark_node;
1569 bool prefix_unused = false;
1571 /* ??? If this is an access attribute for a public subprogram to be used in
1572 a dispatch table, do not translate its type as it's useless in this case
1573 and the parameter types might be incomplete types coming from a limited
1574 context in Ada 2012 (AI05-0151). */
1575 if (Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
1576 && Is_Dispatch_Table_Entity (Etype (gnat_node))
1577 && Nkind (gnat_prefix) == N_Identifier
1578 && Is_Subprogram (Entity (gnat_prefix))
1579 && Is_Public (Entity (gnat_prefix))
1580 && !present_gnu_tree (Entity (gnat_prefix)))
1581 gnu_prefix = get_minimal_subprog_decl (Entity (gnat_prefix));
1582 else
1583 gnu_prefix = gnat_to_gnu (gnat_prefix);
1584 gnu_type = TREE_TYPE (gnu_prefix);
1586 /* If the input is a NULL_EXPR, make a new one. */
1587 if (TREE_CODE (gnu_prefix) == NULL_EXPR)
1589 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1590 *gnu_result_type_p = gnu_result_type;
1591 return build1 (NULL_EXPR, gnu_result_type, TREE_OPERAND (gnu_prefix, 0));
1594 switch (attribute)
1596 case Attr_Pos:
1597 case Attr_Val:
1598 /* These are just conversions since representation clauses for
1599 enumeration types are handled in the front-end. */
1601 bool checkp = Do_Range_Check (First (Expressions (gnat_node)));
1602 gnu_result = gnat_to_gnu (First (Expressions (gnat_node)));
1603 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1604 gnu_result = convert_with_check (Etype (gnat_node), gnu_result,
1605 checkp, checkp, true, gnat_node);
1607 break;
1609 case Attr_Pred:
1610 case Attr_Succ:
1611 /* These just add or subtract the constant 1 since representation
1612 clauses for enumeration types are handled in the front-end. */
1613 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
1614 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1616 if (Do_Range_Check (First (Expressions (gnat_node))))
1618 gnu_expr = gnat_protect_expr (gnu_expr);
1619 gnu_expr
1620 = emit_check
1621 (build_binary_op (EQ_EXPR, boolean_type_node,
1622 gnu_expr,
1623 attribute == Attr_Pred
1624 ? TYPE_MIN_VALUE (gnu_result_type)
1625 : TYPE_MAX_VALUE (gnu_result_type)),
1626 gnu_expr, CE_Range_Check_Failed, gnat_node);
1629 gnu_result
1630 = build_binary_op (attribute == Attr_Pred ? MINUS_EXPR : PLUS_EXPR,
1631 gnu_result_type, gnu_expr,
1632 convert (gnu_result_type, integer_one_node));
1633 break;
1635 case Attr_Address:
1636 case Attr_Unrestricted_Access:
1637 /* Conversions don't change addresses but can cause us to miss the
1638 COMPONENT_REF case below, so strip them off. */
1639 gnu_prefix = remove_conversions (gnu_prefix,
1640 !Must_Be_Byte_Aligned (gnat_node));
1642 /* If we are taking 'Address of an unconstrained object, this is the
1643 pointer to the underlying array. */
1644 if (attribute == Attr_Address)
1645 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1647 /* If we are building a static dispatch table, we have to honor
1648 TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
1649 with the C++ ABI. We do it in the non-static case as well,
1650 see gnat_to_gnu_entity, case E_Access_Subprogram_Type. */
1651 else if (TARGET_VTABLE_USES_DESCRIPTORS
1652 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
1654 tree gnu_field, t;
1655 /* Descriptors can only be built here for top-level functions. */
1656 bool build_descriptor = (global_bindings_p () != 0);
1657 int i;
1658 vec<constructor_elt, va_gc> *gnu_vec = NULL;
1659 constructor_elt *elt;
1661 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1663 /* If we're not going to build the descriptor, we have to retrieve
1664 the one which will be built by the linker (or by the compiler
1665 later if a static chain is requested). */
1666 if (!build_descriptor)
1668 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
1669 gnu_result = fold_convert (build_pointer_type (gnu_result_type),
1670 gnu_result);
1671 gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
1674 vec_safe_grow (gnu_vec, TARGET_VTABLE_USES_DESCRIPTORS);
1675 elt = (gnu_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
1676 for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
1677 i < TARGET_VTABLE_USES_DESCRIPTORS;
1678 gnu_field = DECL_CHAIN (gnu_field), i++)
1680 if (build_descriptor)
1682 t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
1683 build_int_cst (NULL_TREE, i));
1684 TREE_CONSTANT (t) = 1;
1686 else
1687 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
1688 gnu_field, NULL_TREE);
1690 elt->index = gnu_field;
1691 elt->value = t;
1692 elt--;
1695 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
1696 break;
1699 /* ... fall through ... */
1701 case Attr_Access:
1702 case Attr_Unchecked_Access:
1703 case Attr_Code_Address:
1704 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1705 gnu_result
1706 = build_unary_op (((attribute == Attr_Address
1707 || attribute == Attr_Unrestricted_Access)
1708 && !Must_Be_Byte_Aligned (gnat_node))
1709 ? ATTR_ADDR_EXPR : ADDR_EXPR,
1710 gnu_result_type, gnu_prefix);
1712 /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
1713 don't try to build a trampoline. */
1714 if (attribute == Attr_Code_Address)
1716 gnu_expr = remove_conversions (gnu_result, false);
1718 if (TREE_CODE (gnu_expr) == ADDR_EXPR)
1719 TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
1722 /* For 'Access, issue an error message if the prefix is a C++ method
1723 since it can use a special calling convention on some platforms,
1724 which cannot be propagated to the access type. */
1725 else if (attribute == Attr_Access
1726 && Nkind (gnat_prefix) == N_Identifier
1727 && is_cplusplus_method (Entity (gnat_prefix)))
1728 post_error ("access to C++ constructor or member function not allowed",
1729 gnat_node);
1731 /* For other address attributes applied to a nested function,
1732 find an inner ADDR_EXPR and annotate it so that we can issue
1733 a useful warning with -Wtrampolines. */
1734 else if (TREE_CODE (TREE_TYPE (gnu_prefix)) == FUNCTION_TYPE)
1736 gnu_expr = remove_conversions (gnu_result, false);
1738 if (TREE_CODE (gnu_expr) == ADDR_EXPR
1739 && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
1741 set_expr_location_from_node (gnu_expr, gnat_node);
1743 /* Also check the inlining status. */
1744 check_inlining_for_nested_subprog (TREE_OPERAND (gnu_expr, 0));
1746 /* Check that we're not violating the No_Implicit_Dynamic_Code
1747 restriction. Be conservative if we don't know anything
1748 about the trampoline strategy for the target. */
1749 Check_Implicit_Dynamic_Code_Allowed (gnat_node);
1752 break;
1754 case Attr_Pool_Address:
1756 tree gnu_ptr = gnu_prefix;
1757 tree gnu_obj_type;
1759 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1761 /* If this is fat pointer, the object must have been allocated with the
1762 template in front of the array. So compute the template address; do
1763 it by converting to a thin pointer. */
1764 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
1765 gnu_ptr
1766 = convert (build_pointer_type
1767 (TYPE_OBJECT_RECORD_TYPE
1768 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
1769 gnu_ptr);
1771 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
1773 /* If this is a thin pointer, the object must have been allocated with
1774 the template in front of the array. So compute the template address
1775 and return it. */
1776 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
1777 gnu_ptr
1778 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
1779 gnu_ptr,
1780 fold_build1 (NEGATE_EXPR, sizetype,
1781 byte_position
1782 (DECL_CHAIN
1783 TYPE_FIELDS ((gnu_obj_type)))));
1785 gnu_result = convert (gnu_result_type, gnu_ptr);
1787 break;
1789 case Attr_Size:
1790 case Attr_Object_Size:
1791 case Attr_Value_Size:
1792 case Attr_Max_Size_In_Storage_Elements:
1793 gnu_expr = gnu_prefix;
1795 /* Remove NOPs and conversions between original and packable version
1796 from GNU_EXPR, and conversions from GNU_PREFIX. We use GNU_EXPR
1797 to see if a COMPONENT_REF was involved. */
1798 while (TREE_CODE (gnu_expr) == NOP_EXPR
1799 || (TREE_CODE (gnu_expr) == VIEW_CONVERT_EXPR
1800 && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
1801 && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
1802 == RECORD_TYPE
1803 && TYPE_NAME (TREE_TYPE (gnu_expr))
1804 == TYPE_NAME (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))))
1805 gnu_expr = TREE_OPERAND (gnu_expr, 0);
1807 gnu_prefix = remove_conversions (gnu_prefix, true);
1808 prefix_unused = true;
1809 gnu_type = TREE_TYPE (gnu_prefix);
1811 /* Replace an unconstrained array type with the type of the underlying
1812 array. We can't do this with a call to maybe_unconstrained_array
1813 since we may have a TYPE_DECL. For 'Max_Size_In_Storage_Elements,
1814 use the record type that will be used to allocate the object and its
1815 template. */
1816 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1818 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1819 if (attribute != Attr_Max_Size_In_Storage_Elements)
1820 gnu_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
1823 /* If we're looking for the size of a field, return the field size. */
1824 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1825 gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
1827 /* Otherwise, if the prefix is an object, or if we are looking for
1828 'Object_Size or 'Max_Size_In_Storage_Elements, the result is the
1829 GCC size of the type. We make an exception for padded objects,
1830 as we do not take into account alignment promotions for the size.
1831 This is in keeping with the object case of gnat_to_gnu_entity. */
1832 else if ((TREE_CODE (gnu_prefix) != TYPE_DECL
1833 && !(TYPE_IS_PADDING_P (gnu_type)
1834 && TREE_CODE (gnu_expr) == COMPONENT_REF))
1835 || attribute == Attr_Object_Size
1836 || attribute == Attr_Max_Size_In_Storage_Elements)
1838 /* If this is a dereference and we have a special dynamic constrained
1839 subtype on the prefix, use it to compute the size; otherwise, use
1840 the designated subtype. */
1841 if (Nkind (gnat_prefix) == N_Explicit_Dereference)
1843 Node_Id gnat_actual_subtype
1844 = Actual_Designated_Subtype (gnat_prefix);
1845 tree gnu_ptr_type
1846 = TREE_TYPE (gnat_to_gnu (Prefix (gnat_prefix)));
1848 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
1849 && Present (gnat_actual_subtype))
1851 tree gnu_actual_obj_type
1852 = gnat_to_gnu_type (gnat_actual_subtype);
1853 gnu_type
1854 = build_unc_object_type_from_ptr (gnu_ptr_type,
1855 gnu_actual_obj_type,
1856 get_identifier ("SIZE"),
1857 false);
1861 gnu_result = TYPE_SIZE (gnu_type);
1864 /* Otherwise, the result is the RM size of the type. */
1865 else
1866 gnu_result = rm_size (gnu_type);
1868 /* Deal with a self-referential size by returning the maximum size for
1869 a type and by qualifying the size with the object otherwise. */
1870 if (CONTAINS_PLACEHOLDER_P (gnu_result))
1872 if (TREE_CODE (gnu_prefix) == TYPE_DECL)
1873 gnu_result = max_size (gnu_result, true);
1874 else
1875 gnu_result = substitute_placeholder_in_expr (gnu_result, gnu_expr);
1878 /* If the type contains a template, subtract its size. */
1879 if (TREE_CODE (gnu_type) == RECORD_TYPE
1880 && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
1881 gnu_result = size_binop (MINUS_EXPR, gnu_result,
1882 DECL_SIZE (TYPE_FIELDS (gnu_type)));
1884 /* For 'Max_Size_In_Storage_Elements, adjust the unit. */
1885 if (attribute == Attr_Max_Size_In_Storage_Elements)
1886 gnu_result = size_binop (CEIL_DIV_EXPR, gnu_result, bitsize_unit_node);
1888 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1889 break;
1891 case Attr_Alignment:
1893 unsigned int align;
1895 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1896 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1897 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1899 gnu_type = TREE_TYPE (gnu_prefix);
1900 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1901 prefix_unused = true;
1903 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1904 align = DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1)) / BITS_PER_UNIT;
1905 else
1907 Entity_Id gnat_type = Etype (gnat_prefix);
1908 unsigned int double_align;
1909 bool is_capped_double, align_clause;
1911 /* If the default alignment of "double" or larger scalar types is
1912 specifically capped and there is an alignment clause neither
1913 on the type nor on the prefix itself, return the cap. */
1914 if ((double_align = double_float_alignment) > 0)
1915 is_capped_double
1916 = is_double_float_or_array (gnat_type, &align_clause);
1917 else if ((double_align = double_scalar_alignment) > 0)
1918 is_capped_double
1919 = is_double_scalar_or_array (gnat_type, &align_clause);
1920 else
1921 is_capped_double = align_clause = false;
1923 if (is_capped_double
1924 && Nkind (gnat_prefix) == N_Identifier
1925 && Present (Alignment_Clause (Entity (gnat_prefix))))
1926 align_clause = true;
1928 if (is_capped_double && !align_clause)
1929 align = double_align;
1930 else
1931 align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
1934 gnu_result = size_int (align);
1936 break;
1938 case Attr_First:
1939 case Attr_Last:
1940 case Attr_Range_Length:
1941 prefix_unused = true;
1943 if (INTEGRAL_TYPE_P (gnu_type) || TREE_CODE (gnu_type) == REAL_TYPE)
1945 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1947 if (attribute == Attr_First)
1948 gnu_result = TYPE_MIN_VALUE (gnu_type);
1949 else if (attribute == Attr_Last)
1950 gnu_result = TYPE_MAX_VALUE (gnu_type);
1951 else
1952 gnu_result = get_type_length (gnu_type, gnu_result_type);
1953 break;
1956 /* ... fall through ... */
1958 case Attr_Length:
1960 int Dimension = (Present (Expressions (gnat_node))
1961 ? UI_To_Int (Intval (First (Expressions (gnat_node))))
1962 : 1), i;
1963 struct parm_attr_d *pa = NULL;
1964 Entity_Id gnat_param = Empty;
1965 bool unconstrained_ptr_deref = false;
1967 /* Make sure any implicit dereference gets done. */
1968 gnu_prefix = maybe_implicit_deref (gnu_prefix);
1969 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1971 /* We treat unconstrained array In parameters specially. We also note
1972 whether we are dereferencing a pointer to unconstrained array. */
1973 if (!Is_Constrained (Etype (gnat_prefix)))
1974 switch (Nkind (gnat_prefix))
1976 case N_Identifier:
1977 /* This is the direct case. */
1978 if (Ekind (Entity (gnat_prefix)) == E_In_Parameter)
1979 gnat_param = Entity (gnat_prefix);
1980 break;
1982 case N_Explicit_Dereference:
1983 /* This is the indirect case. Note that we need to be sure that
1984 the access value cannot be null as we'll hoist the load. */
1985 if (Nkind (Prefix (gnat_prefix)) == N_Identifier
1986 && Ekind (Entity (Prefix (gnat_prefix))) == E_In_Parameter)
1988 if (Can_Never_Be_Null (Entity (Prefix (gnat_prefix))))
1989 gnat_param = Entity (Prefix (gnat_prefix));
1991 else
1992 unconstrained_ptr_deref = true;
1993 break;
1995 default:
1996 break;
1999 /* If the prefix is the view conversion of a constrained array to an
2000 unconstrained form, we retrieve the constrained array because we
2001 might not be able to substitute the PLACEHOLDER_EXPR coming from
2002 the conversion. This can occur with the 'Old attribute applied
2003 to a parameter with an unconstrained type, which gets rewritten
2004 into a constrained local variable very late in the game. */
2005 if (TREE_CODE (gnu_prefix) == VIEW_CONVERT_EXPR
2006 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (gnu_prefix)))
2007 && !CONTAINS_PLACEHOLDER_P
2008 (TYPE_SIZE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
2009 gnu_type = TREE_TYPE (TREE_OPERAND (gnu_prefix, 0));
2010 else
2011 gnu_type = TREE_TYPE (gnu_prefix);
2013 prefix_unused = true;
2014 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2016 if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
2018 int ndim;
2019 tree gnu_type_temp;
2021 for (ndim = 1, gnu_type_temp = gnu_type;
2022 TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
2023 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
2024 ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
2027 Dimension = ndim + 1 - Dimension;
2030 for (i = 1; i < Dimension; i++)
2031 gnu_type = TREE_TYPE (gnu_type);
2033 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2035 /* When not optimizing, look up the slot associated with the parameter
2036 and the dimension in the cache and create a new one on failure.
2037 Don't do this when the actual subtype needs debug info (this happens
2038 with -gnatD): in elaborate_expression_1, we create variables that
2039 hold the bounds, so caching attributes isn't very interesting and
2040 causes dependency issues between these variables and cached
2041 expressions. */
2042 if (!optimize
2043 && Present (gnat_param)
2044 && !(Present (Actual_Subtype (gnat_param))
2045 && Needs_Debug_Info (Actual_Subtype (gnat_param))))
2047 FOR_EACH_VEC_SAFE_ELT (f_parm_attr_cache, i, pa)
2048 if (pa->id == gnat_param && pa->dim == Dimension)
2049 break;
2051 if (!pa)
2053 pa = ggc_cleared_alloc<parm_attr_d> ();
2054 pa->id = gnat_param;
2055 pa->dim = Dimension;
2056 vec_safe_push (f_parm_attr_cache, pa);
2060 /* Return the cached expression or build a new one. */
2061 if (attribute == Attr_First)
2063 if (pa && pa->first)
2065 gnu_result = pa->first;
2066 break;
2069 gnu_result
2070 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2073 else if (attribute == Attr_Last)
2075 if (pa && pa->last)
2077 gnu_result = pa->last;
2078 break;
2081 gnu_result
2082 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2085 else /* attribute == Attr_Range_Length || attribute == Attr_Length */
2087 if (pa && pa->length)
2089 gnu_result = pa->length;
2090 break;
2093 gnu_result
2094 = get_type_length (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)),
2095 gnu_result_type);
2098 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2099 handling. Note that these attributes could not have been used on
2100 an unconstrained array type. */
2101 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2103 /* Cache the expression we have just computed. Since we want to do it
2104 at run time, we force the use of a SAVE_EXPR and let the gimplifier
2105 create the temporary in the outermost binding level. We will make
2106 sure in Subprogram_Body_to_gnu that it is evaluated on all possible
2107 paths by forcing its evaluation on entry of the function. */
2108 if (pa)
2110 gnu_result
2111 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2112 switch (attribute)
2114 case Attr_First:
2115 pa->first = gnu_result;
2116 break;
2118 case Attr_Last:
2119 pa->last = gnu_result;
2120 break;
2122 case Attr_Length:
2123 case Attr_Range_Length:
2124 pa->length = gnu_result;
2125 break;
2127 default:
2128 gcc_unreachable ();
2132 /* Otherwise, evaluate it each time it is referenced. */
2133 else
2134 switch (attribute)
2136 case Attr_First:
2137 case Attr_Last:
2138 /* If we are dereferencing a pointer to unconstrained array, we
2139 need to capture the value because the pointed-to bounds may
2140 subsequently be released. */
2141 if (unconstrained_ptr_deref)
2142 gnu_result
2143 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2144 break;
2146 case Attr_Length:
2147 case Attr_Range_Length:
2148 /* Set the source location onto the predicate of the condition
2149 but not if the expression is cached to avoid messing up the
2150 debug info. */
2151 if (TREE_CODE (gnu_result) == COND_EXPR
2152 && EXPR_P (TREE_OPERAND (gnu_result, 0)))
2153 set_expr_location_from_node (TREE_OPERAND (gnu_result, 0),
2154 gnat_node);
2155 break;
2157 default:
2158 gcc_unreachable ();
2161 break;
2164 case Attr_Bit_Position:
2165 case Attr_Position:
2166 case Attr_First_Bit:
2167 case Attr_Last_Bit:
2168 case Attr_Bit:
2170 HOST_WIDE_INT bitsize;
2171 HOST_WIDE_INT bitpos;
2172 tree gnu_offset;
2173 tree gnu_field_bitpos;
2174 tree gnu_field_offset;
2175 tree gnu_inner;
2176 machine_mode mode;
2177 int unsignedp, reversep, volatilep;
2179 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2180 gnu_prefix = remove_conversions (gnu_prefix, true);
2181 prefix_unused = true;
2183 /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
2184 the result is 0. Don't allow 'Bit on a bare component, though. */
2185 if (attribute == Attr_Bit
2186 && TREE_CODE (gnu_prefix) != COMPONENT_REF
2187 && TREE_CODE (gnu_prefix) != FIELD_DECL)
2189 gnu_result = integer_zero_node;
2190 break;
2193 else
2194 gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
2195 || (attribute == Attr_Bit_Position
2196 && TREE_CODE (gnu_prefix) == FIELD_DECL));
2198 get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
2199 &mode, &unsignedp, &reversep, &volatilep, false);
2201 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2203 gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
2204 gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
2206 for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
2207 TREE_CODE (gnu_inner) == COMPONENT_REF
2208 && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
2209 gnu_inner = TREE_OPERAND (gnu_inner, 0))
2211 gnu_field_bitpos
2212 = size_binop (PLUS_EXPR, gnu_field_bitpos,
2213 bit_position (TREE_OPERAND (gnu_inner, 1)));
2214 gnu_field_offset
2215 = size_binop (PLUS_EXPR, gnu_field_offset,
2216 byte_position (TREE_OPERAND (gnu_inner, 1)));
2219 else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
2221 gnu_field_bitpos = bit_position (gnu_prefix);
2222 gnu_field_offset = byte_position (gnu_prefix);
2224 else
2226 gnu_field_bitpos = bitsize_zero_node;
2227 gnu_field_offset = size_zero_node;
2230 switch (attribute)
2232 case Attr_Position:
2233 gnu_result = gnu_field_offset;
2234 break;
2236 case Attr_First_Bit:
2237 case Attr_Bit:
2238 gnu_result = size_int (bitpos % BITS_PER_UNIT);
2239 break;
2241 case Attr_Last_Bit:
2242 gnu_result = bitsize_int (bitpos % BITS_PER_UNIT);
2243 gnu_result = size_binop (PLUS_EXPR, gnu_result,
2244 TYPE_SIZE (TREE_TYPE (gnu_prefix)));
2245 /* ??? Avoid a large unsigned result that will overflow when
2246 converted to the signed universal_integer. */
2247 if (integer_zerop (gnu_result))
2248 gnu_result = integer_minus_one_node;
2249 else
2250 gnu_result
2251 = size_binop (MINUS_EXPR, gnu_result, bitsize_one_node);
2252 break;
2254 case Attr_Bit_Position:
2255 gnu_result = gnu_field_bitpos;
2256 break;
2259 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2260 handling. */
2261 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2262 break;
2265 case Attr_Min:
2266 case Attr_Max:
2268 tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
2269 tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
2271 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2273 /* The result of {MIN,MAX}_EXPR is unspecified if either operand is
2274 a NaN so we implement the semantics of C99 f{min,max} to make it
2275 predictable in this case: if either operand is a NaN, the other
2276 is returned; if both operands are NaN's, a NaN is returned. */
2277 if (SCALAR_FLOAT_TYPE_P (gnu_result_type)
2278 && !Machine_Overflows_On_Target)
2280 const bool lhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_lhs);
2281 const bool rhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_rhs);
2282 tree t = builtin_decl_explicit (BUILT_IN_ISNAN);
2283 tree lhs_is_nan, rhs_is_nan;
2285 /* If the operands have side-effects, they need to be evaluated
2286 only once in spite of the multiple references in the result. */
2287 if (lhs_side_effects_p)
2288 gnu_lhs = gnat_protect_expr (gnu_lhs);
2289 if (rhs_side_effects_p)
2290 gnu_rhs = gnat_protect_expr (gnu_rhs);
2292 lhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2293 build_call_expr (t, 1, gnu_lhs),
2294 integer_zero_node);
2296 rhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2297 build_call_expr (t, 1, gnu_rhs),
2298 integer_zero_node);
2300 gnu_result = build_binary_op (attribute == Attr_Min
2301 ? MIN_EXPR : MAX_EXPR,
2302 gnu_result_type, gnu_lhs, gnu_rhs);
2303 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2304 rhs_is_nan, gnu_lhs, gnu_result);
2305 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2306 lhs_is_nan, gnu_rhs, gnu_result);
2308 /* If the operands have side-effects, they need to be evaluated
2309 before doing the tests above since the place they otherwise
2310 would end up being evaluated at run time could be wrong. */
2311 if (lhs_side_effects_p)
2312 gnu_result
2313 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_lhs, gnu_result);
2315 if (rhs_side_effects_p)
2316 gnu_result
2317 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_rhs, gnu_result);
2319 else
2320 gnu_result = build_binary_op (attribute == Attr_Min
2321 ? MIN_EXPR : MAX_EXPR,
2322 gnu_result_type, gnu_lhs, gnu_rhs);
2324 break;
2326 case Attr_Passed_By_Reference:
2327 gnu_result = size_int (default_pass_by_ref (gnu_type)
2328 || must_pass_by_ref (gnu_type));
2329 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2330 break;
2332 case Attr_Component_Size:
2333 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
2334 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
2335 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
2337 gnu_prefix = maybe_implicit_deref (gnu_prefix);
2338 gnu_type = TREE_TYPE (gnu_prefix);
2340 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
2341 gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
2343 while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
2344 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
2345 gnu_type = TREE_TYPE (gnu_type);
2347 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2349 /* Note this size cannot be self-referential. */
2350 gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
2351 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2352 prefix_unused = true;
2353 break;
2355 case Attr_Descriptor_Size:
2356 gnu_type = TREE_TYPE (gnu_prefix);
2357 gcc_assert (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE);
2359 /* What we want is the offset of the ARRAY field in the record
2360 that the thin pointer designates. */
2361 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
2362 gnu_result = bit_position (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
2363 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2364 prefix_unused = true;
2365 break;
2367 case Attr_Null_Parameter:
2368 /* This is just a zero cast to the pointer type for our prefix and
2369 dereferenced. */
2370 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2371 gnu_result
2372 = build_unary_op (INDIRECT_REF, NULL_TREE,
2373 convert (build_pointer_type (gnu_result_type),
2374 integer_zero_node));
2375 TREE_PRIVATE (gnu_result) = 1;
2376 break;
2378 case Attr_Mechanism_Code:
2380 Entity_Id gnat_obj = Entity (gnat_prefix);
2381 int code;
2383 prefix_unused = true;
2384 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2385 if (Present (Expressions (gnat_node)))
2387 int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
2389 for (gnat_obj = First_Formal (gnat_obj); i > 1;
2390 i--, gnat_obj = Next_Formal (gnat_obj))
2394 code = Mechanism (gnat_obj);
2395 if (code == Default)
2396 code = ((present_gnu_tree (gnat_obj)
2397 && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
2398 || ((TREE_CODE (get_gnu_tree (gnat_obj))
2399 == PARM_DECL)
2400 && (DECL_BY_COMPONENT_PTR_P
2401 (get_gnu_tree (gnat_obj))))))
2402 ? By_Reference : By_Copy);
2403 gnu_result = convert (gnu_result_type, size_int (- code));
2405 break;
2407 case Attr_Model:
2408 /* We treat Model as identical to Machine. This is true for at least
2409 IEEE and some other nice floating-point systems. */
2411 /* ... fall through ... */
2413 case Attr_Machine:
2414 /* The trick is to force the compiler to store the result in memory so
2415 that we do not have extra precision used. But do this only when this
2416 is necessary, i.e. if FP_ARITH_MAY_WIDEN is true and the precision of
2417 the type is lower than that of the longest floating-point type. */
2418 prefix_unused = true;
2419 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2420 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2421 gnu_result = convert (gnu_result_type, gnu_expr);
2423 if (TREE_CODE (gnu_result) != REAL_CST
2424 && fp_arith_may_widen
2425 && TYPE_PRECISION (gnu_result_type)
2426 < TYPE_PRECISION (longest_float_type_node))
2428 tree rec_type = make_node (RECORD_TYPE);
2429 tree field
2430 = create_field_decl (get_identifier ("OBJ"), gnu_result_type,
2431 rec_type, NULL_TREE, NULL_TREE, 0, 0);
2432 tree rec_val, asm_expr;
2434 finish_record_type (rec_type, field, 0, false);
2436 rec_val = build_constructor_single (rec_type, field, gnu_result);
2437 rec_val = build1 (SAVE_EXPR, rec_type, rec_val);
2439 asm_expr
2440 = build5 (ASM_EXPR, void_type_node,
2441 build_string (0, ""),
2442 tree_cons (build_tree_list (NULL_TREE,
2443 build_string (2, "=m")),
2444 rec_val, NULL_TREE),
2445 tree_cons (build_tree_list (NULL_TREE,
2446 build_string (1, "m")),
2447 rec_val, NULL_TREE),
2448 NULL_TREE, NULL_TREE);
2449 ASM_VOLATILE_P (asm_expr) = 1;
2451 gnu_result
2452 = build_compound_expr (gnu_result_type, asm_expr,
2453 build_component_ref (rec_val, field,
2454 false));
2456 break;
2458 case Attr_Deref:
2459 prefix_unused = true;
2460 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2461 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2462 /* This can be a random address so build an alias-all pointer type. */
2463 gnu_expr
2464 = convert (build_pointer_type_for_mode (gnu_result_type, ptr_mode,
2465 true),
2466 gnu_expr);
2467 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_expr);
2468 break;
2470 default:
2471 /* This abort means that we have an unimplemented attribute. */
2472 gcc_unreachable ();
2475 /* If this is an attribute where the prefix was unused, force a use of it if
2476 it has a side-effect. But don't do it if the prefix is just an entity
2477 name. However, if an access check is needed, we must do it. See second
2478 example in AARM 11.6(5.e). */
2479 if (prefix_unused
2480 && TREE_SIDE_EFFECTS (gnu_prefix)
2481 && !Is_Entity_Name (gnat_prefix))
2482 gnu_result
2483 = build_compound_expr (TREE_TYPE (gnu_result), gnu_prefix, gnu_result);
2485 *gnu_result_type_p = gnu_result_type;
2486 return gnu_result;
2489 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Case_Statement,
2490 to a GCC tree, which is returned. */
2492 static tree
2493 Case_Statement_to_gnu (Node_Id gnat_node)
2495 tree gnu_result, gnu_expr, gnu_label;
2496 Node_Id gnat_when;
2497 location_t end_locus;
2498 bool may_fallthru = false;
2500 gnu_expr = gnat_to_gnu (Expression (gnat_node));
2501 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2503 /* The range of values in a case statement is determined by the rules in
2504 RM 5.4(7-9). In almost all cases, this range is represented by the Etype
2505 of the expression. One exception arises in the case of a simple name that
2506 is parenthesized. This still has the Etype of the name, but since it is
2507 not a name, para 7 does not apply, and we need to go to the base type.
2508 This is the only case where parenthesization affects the dynamic
2509 semantics (i.e. the range of possible values at run time that is covered
2510 by the others alternative).
2512 Another exception is if the subtype of the expression is non-static. In
2513 that case, we also have to use the base type. */
2514 if (Paren_Count (Expression (gnat_node)) != 0
2515 || !Is_OK_Static_Subtype (Underlying_Type
2516 (Etype (Expression (gnat_node)))))
2517 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2519 /* We build a SWITCH_EXPR that contains the code with interspersed
2520 CASE_LABEL_EXPRs for each label. */
2521 if (!Sloc_to_locus (End_Location (gnat_node), &end_locus))
2522 end_locus = input_location;
2523 gnu_label = create_artificial_label (end_locus);
2524 start_stmt_group ();
2526 for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
2527 Present (gnat_when);
2528 gnat_when = Next_Non_Pragma (gnat_when))
2530 bool choices_added_p = false;
2531 Node_Id gnat_choice;
2533 /* First compile all the different case choices for the current WHEN
2534 alternative. */
2535 for (gnat_choice = First (Discrete_Choices (gnat_when));
2536 Present (gnat_choice);
2537 gnat_choice = Next (gnat_choice))
2539 tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2540 tree label = create_artificial_label (input_location);
2542 switch (Nkind (gnat_choice))
2544 case N_Range:
2545 gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
2546 gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
2547 break;
2549 case N_Subtype_Indication:
2550 gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
2551 (Constraint (gnat_choice))));
2552 gnu_high = gnat_to_gnu (High_Bound (Range_Expression
2553 (Constraint (gnat_choice))));
2554 break;
2556 case N_Identifier:
2557 case N_Expanded_Name:
2558 /* This represents either a subtype range or a static value of
2559 some kind; Ekind says which. */
2560 if (IN (Ekind (Entity (gnat_choice)), Type_Kind))
2562 tree gnu_type = get_unpadded_type (Entity (gnat_choice));
2564 gnu_low = TYPE_MIN_VALUE (gnu_type);
2565 gnu_high = TYPE_MAX_VALUE (gnu_type);
2566 break;
2569 /* ... fall through ... */
2571 case N_Character_Literal:
2572 case N_Integer_Literal:
2573 gnu_low = gnat_to_gnu (gnat_choice);
2574 break;
2576 case N_Others_Choice:
2577 break;
2579 default:
2580 gcc_unreachable ();
2583 /* Everything should be folded into constants at this point. */
2584 gcc_assert (!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST);
2585 gcc_assert (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST);
2587 add_stmt_with_node (build_case_label (gnu_low, gnu_high, label),
2588 gnat_choice);
2589 choices_added_p = true;
2592 /* This construct doesn't define a scope so we shouldn't push a binding
2593 level around the statement list. Except that we have always done so
2594 historically and this makes it possible to reduce stack usage. As a
2595 compromise, we keep doing it for case statements, for which this has
2596 never been problematic, but not for case expressions in Ada 2012. */
2597 if (choices_added_p)
2599 const bool is_case_expression
2600 = (Nkind (Parent (gnat_node)) == N_Expression_With_Actions);
2601 tree group
2602 = build_stmt_group (Statements (gnat_when), !is_case_expression);
2603 bool group_may_fallthru = block_may_fallthru (group);
2604 add_stmt (group);
2605 if (group_may_fallthru)
2607 tree stmt = build1 (GOTO_EXPR, void_type_node, gnu_label);
2608 SET_EXPR_LOCATION (stmt, end_locus);
2609 add_stmt (stmt);
2610 may_fallthru = true;
2615 /* Now emit a definition of the label the cases branch to, if any. */
2616 if (may_fallthru)
2617 add_stmt (build1 (LABEL_EXPR, void_type_node, gnu_label));
2618 gnu_result = build3 (SWITCH_EXPR, TREE_TYPE (gnu_expr), gnu_expr,
2619 end_stmt_group (), NULL_TREE);
2621 return gnu_result;
2624 /* Return true if we are in the body of a loop. */
2626 static inline bool
2627 inside_loop_p (void)
2629 return !vec_safe_is_empty (gnu_loop_stack);
2632 /* Find out whether EXPR is a simple additive expression based on the iteration
2633 variable of some enclosing loop in the current function. If so, return the
2634 loop and set *DISP to the displacement and *NEG_P to true if this is for a
2635 subtraction; otherwise, return NULL. */
2637 static struct loop_info_d *
2638 find_loop_for (tree expr, tree *disp = NULL, bool *neg_p = NULL)
2640 tree var, add, cst;
2641 bool minus_p;
2642 struct loop_info_d *iter = NULL;
2643 unsigned int i;
2645 if (is_simple_additive_expression (expr, &add, &cst, &minus_p))
2647 var = add;
2648 if (disp)
2649 *disp = cst;
2650 if (neg_p)
2651 *neg_p = minus_p;
2653 else
2655 var = expr;
2656 if (disp)
2657 *disp = NULL_TREE;
2658 if (neg_p)
2659 *neg_p = false;
2662 var = remove_conversions (var, false);
2664 if (TREE_CODE (var) != VAR_DECL)
2665 return NULL;
2667 if (decl_function_context (var) != current_function_decl)
2668 return NULL;
2670 gcc_assert (vec_safe_length (gnu_loop_stack) > 0);
2672 FOR_EACH_VEC_ELT_REVERSE (*gnu_loop_stack, i, iter)
2673 if (var == iter->loop_var)
2674 break;
2676 return iter;
2679 /* Return true if VAL (of type TYPE) can equal the minimum value if MAX is
2680 false, or the maximum value if MAX is true, of TYPE. */
2682 static bool
2683 can_equal_min_or_max_val_p (tree val, tree type, bool max)
2685 tree min_or_max_val = (max ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type));
2687 if (TREE_CODE (min_or_max_val) != INTEGER_CST)
2688 return true;
2690 if (TREE_CODE (val) == NOP_EXPR)
2691 val = (max
2692 ? TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val, 0)))
2693 : TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val, 0))));
2695 if (TREE_CODE (val) != INTEGER_CST)
2696 return true;
2698 if (max)
2699 return tree_int_cst_lt (val, min_or_max_val) == 0;
2700 else
2701 return tree_int_cst_lt (min_or_max_val, val) == 0;
2704 /* Return true if VAL (of type TYPE) can equal the minimum value of TYPE.
2705 If REVERSE is true, minimum value is taken as maximum value. */
2707 static inline bool
2708 can_equal_min_val_p (tree val, tree type, bool reverse)
2710 return can_equal_min_or_max_val_p (val, type, reverse);
2713 /* Return true if VAL (of type TYPE) can equal the maximum value of TYPE.
2714 If REVERSE is true, maximum value is taken as minimum value. */
2716 static inline bool
2717 can_equal_max_val_p (tree val, tree type, bool reverse)
2719 return can_equal_min_or_max_val_p (val, type, !reverse);
2722 /* Return true if VAL1 can be lower than VAL2. */
2724 static bool
2725 can_be_lower_p (tree val1, tree val2)
2727 if (TREE_CODE (val1) == NOP_EXPR)
2728 val1 = TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val1, 0)));
2730 if (TREE_CODE (val1) != INTEGER_CST)
2731 return true;
2733 if (TREE_CODE (val2) == NOP_EXPR)
2734 val2 = TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val2, 0)));
2736 if (TREE_CODE (val2) != INTEGER_CST)
2737 return true;
2739 return tree_int_cst_lt (val1, val2);
2742 /* Replace EXPR1 and EXPR2 by invariant expressions if possible. Return
2743 true if both expressions have been replaced and false otherwise. */
2745 static bool
2746 make_invariant (tree *expr1, tree *expr2)
2748 tree inv_expr1 = gnat_invariant_expr (*expr1);
2749 tree inv_expr2 = gnat_invariant_expr (*expr2);
2751 if (inv_expr1)
2752 *expr1 = inv_expr1;
2754 if (inv_expr2)
2755 *expr2 = inv_expr2;
2757 return inv_expr1 && inv_expr2;
2760 /* Helper function for walk_tree, used by independent_iterations_p below. */
2762 static tree
2763 scan_rhs_r (tree *tp, int *walk_subtrees, void *data)
2765 bitmap *params = (bitmap *)data;
2766 tree t = *tp;
2768 /* No need to walk into types or decls. */
2769 if (IS_TYPE_OR_DECL_P (t))
2770 *walk_subtrees = 0;
2772 if (TREE_CODE (t) == PARM_DECL && bitmap_bit_p (*params, DECL_UID (t)))
2773 return t;
2775 return NULL_TREE;
2778 /* Return true if STMT_LIST generates independent iterations in a loop. */
2780 static bool
2781 independent_iterations_p (tree stmt_list)
2783 tree_stmt_iterator tsi;
2784 bitmap params = BITMAP_GGC_ALLOC();
2785 auto_vec<tree> rhs;
2786 tree iter;
2787 int i;
2789 if (TREE_CODE (stmt_list) == BIND_EXPR)
2790 stmt_list = BIND_EXPR_BODY (stmt_list);
2792 /* Scan the list and return false on anything that is not either a check
2793 or an assignment to a parameter with restricted aliasing. */
2794 for (tsi = tsi_start (stmt_list); !tsi_end_p (tsi); tsi_next (&tsi))
2796 tree stmt = tsi_stmt (tsi);
2798 switch (TREE_CODE (stmt))
2800 case COND_EXPR:
2802 if (COND_EXPR_ELSE (stmt))
2803 return false;
2804 if (TREE_CODE (COND_EXPR_THEN (stmt)) != CALL_EXPR)
2805 return false;
2806 tree func = get_callee_fndecl (COND_EXPR_THEN (stmt));
2807 if (!(func && TREE_THIS_VOLATILE (func)))
2808 return false;
2809 break;
2812 case MODIFY_EXPR:
2814 tree lhs = TREE_OPERAND (stmt, 0);
2815 while (handled_component_p (lhs))
2816 lhs = TREE_OPERAND (lhs, 0);
2817 if (TREE_CODE (lhs) != INDIRECT_REF)
2818 return false;
2819 lhs = TREE_OPERAND (lhs, 0);
2820 if (!(TREE_CODE (lhs) == PARM_DECL
2821 && DECL_RESTRICTED_ALIASING_P (lhs)))
2822 return false;
2823 bitmap_set_bit (params, DECL_UID (lhs));
2824 rhs.safe_push (TREE_OPERAND (stmt, 1));
2825 break;
2828 default:
2829 return false;
2833 /* At this point we know that the list contains only statements that will
2834 modify parameters with restricted aliasing. Check that the statements
2835 don't at the time read from these parameters. */
2836 FOR_EACH_VEC_ELT (rhs, i, iter)
2837 if (walk_tree_without_duplicates (&iter, scan_rhs_r, &params))
2838 return false;
2840 return true;
2843 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Loop_Statement,
2844 to a GCC tree, which is returned. */
2846 static tree
2847 Loop_Statement_to_gnu (Node_Id gnat_node)
2849 const Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
2850 struct loop_info_d *gnu_loop_info = ggc_cleared_alloc<loop_info_d> ();
2851 tree gnu_loop_stmt = build4 (LOOP_STMT, void_type_node, NULL_TREE,
2852 NULL_TREE, NULL_TREE, NULL_TREE);
2853 tree gnu_loop_label = create_artificial_label (input_location);
2854 tree gnu_cond_expr = NULL_TREE, gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2855 tree gnu_result;
2857 /* Push the loop_info structure associated with the LOOP_STMT. */
2858 vec_safe_push (gnu_loop_stack, gnu_loop_info);
2860 /* Set location information for statement and end label. */
2861 set_expr_location_from_node (gnu_loop_stmt, gnat_node);
2862 Sloc_to_locus (Sloc (End_Label (gnat_node)),
2863 &DECL_SOURCE_LOCATION (gnu_loop_label));
2864 LOOP_STMT_LABEL (gnu_loop_stmt) = gnu_loop_label;
2866 /* Save the statement for later reuse. */
2867 gnu_loop_info->stmt = gnu_loop_stmt;
2868 gnu_loop_info->artificial = !Comes_From_Source (gnat_node);
2870 /* Set the condition under which the loop must keep going.
2871 For the case "LOOP .... END LOOP;" the condition is always true. */
2872 if (No (gnat_iter_scheme))
2875 /* For the case "WHILE condition LOOP ..... END LOOP;" it's immediate. */
2876 else if (Present (Condition (gnat_iter_scheme)))
2877 LOOP_STMT_COND (gnu_loop_stmt)
2878 = gnat_to_gnu (Condition (gnat_iter_scheme));
2880 /* Otherwise we have an iteration scheme and the condition is given by the
2881 bounds of the subtype of the iteration variable. */
2882 else
2884 Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
2885 Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
2886 Entity_Id gnat_type = Etype (gnat_loop_var);
2887 tree gnu_type = get_unpadded_type (gnat_type);
2888 tree gnu_base_type = get_base_type (gnu_type);
2889 tree gnu_one_node = convert (gnu_base_type, integer_one_node);
2890 tree gnu_loop_var, gnu_loop_iv, gnu_first, gnu_last, gnu_stmt;
2891 enum tree_code update_code, test_code, shift_code;
2892 bool reverse = Reverse_Present (gnat_loop_spec), use_iv = false;
2894 gnu_low = convert (gnu_base_type, TYPE_MIN_VALUE (gnu_type));
2895 gnu_high = convert (gnu_base_type, TYPE_MAX_VALUE (gnu_type));
2897 /* We must disable modulo reduction for the iteration variable, if any,
2898 in order for the loop comparison to be effective. */
2899 if (reverse)
2901 gnu_first = gnu_high;
2902 gnu_last = gnu_low;
2903 update_code = MINUS_NOMOD_EXPR;
2904 test_code = GE_EXPR;
2905 shift_code = PLUS_NOMOD_EXPR;
2907 else
2909 gnu_first = gnu_low;
2910 gnu_last = gnu_high;
2911 update_code = PLUS_NOMOD_EXPR;
2912 test_code = LE_EXPR;
2913 shift_code = MINUS_NOMOD_EXPR;
2916 /* We use two different strategies to translate the loop, depending on
2917 whether optimization is enabled.
2919 If it is, we generate the canonical loop form expected by the loop
2920 optimizer and the loop vectorizer, which is the do-while form:
2922 ENTRY_COND
2923 loop:
2924 TOP_UPDATE
2925 BODY
2926 BOTTOM_COND
2927 GOTO loop
2929 This avoids an implicit dependency on loop header copying and makes
2930 it possible to turn BOTTOM_COND into an inequality test.
2932 If optimization is disabled, loop header copying doesn't come into
2933 play and we try to generate the loop form with the fewer conditional
2934 branches. First, the default form, which is:
2936 loop:
2937 TOP_COND
2938 BODY
2939 BOTTOM_UPDATE
2940 GOTO loop
2942 It should catch most loops with constant ending point. Then, if we
2943 cannot, we try to generate the shifted form:
2945 loop:
2946 TOP_COND
2947 TOP_UPDATE
2948 BODY
2949 GOTO loop
2951 which should catch loops with constant starting point. Otherwise, if
2952 we cannot, we generate the fallback form:
2954 ENTRY_COND
2955 loop:
2956 BODY
2957 BOTTOM_COND
2958 BOTTOM_UPDATE
2959 GOTO loop
2961 which works in all cases. */
2963 if (optimize)
2965 /* We can use the do-while form directly if GNU_FIRST-1 doesn't
2966 overflow. */
2967 if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse))
2970 /* Otherwise, use the do-while form with the help of a special
2971 induction variable in the unsigned version of the base type
2972 or the unsigned version of the size type, whichever is the
2973 largest, in order to have wrap-around arithmetics for it. */
2974 else
2976 if (TYPE_PRECISION (gnu_base_type)
2977 > TYPE_PRECISION (size_type_node))
2978 gnu_base_type
2979 = gnat_type_for_size (TYPE_PRECISION (gnu_base_type), 1);
2980 else
2981 gnu_base_type = size_type_node;
2983 gnu_first = convert (gnu_base_type, gnu_first);
2984 gnu_last = convert (gnu_base_type, gnu_last);
2985 gnu_one_node = convert (gnu_base_type, integer_one_node);
2986 use_iv = true;
2989 gnu_first
2990 = build_binary_op (shift_code, gnu_base_type, gnu_first,
2991 gnu_one_node);
2992 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
2993 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
2995 else
2997 /* We can use the default form if GNU_LAST+1 doesn't overflow. */
2998 if (!can_equal_max_val_p (gnu_last, gnu_base_type, reverse))
3001 /* Otherwise, we can use the shifted form if neither GNU_FIRST-1 nor
3002 GNU_LAST-1 does. */
3003 else if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse)
3004 && !can_equal_min_val_p (gnu_last, gnu_base_type, reverse))
3006 gnu_first
3007 = build_binary_op (shift_code, gnu_base_type, gnu_first,
3008 gnu_one_node);
3009 gnu_last
3010 = build_binary_op (shift_code, gnu_base_type, gnu_last,
3011 gnu_one_node);
3012 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
3015 /* Otherwise, use the fallback form. */
3016 else
3017 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
3020 /* If we use the BOTTOM_COND, we can turn the test into an inequality
3021 test but we may have to add ENTRY_COND to protect the empty loop. */
3022 if (LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt))
3024 test_code = NE_EXPR;
3025 if (can_be_lower_p (gnu_high, gnu_low))
3027 gnu_cond_expr
3028 = build3 (COND_EXPR, void_type_node,
3029 build_binary_op (LE_EXPR, boolean_type_node,
3030 gnu_low, gnu_high),
3031 NULL_TREE, alloc_stmt_list ());
3032 set_expr_location_from_node (gnu_cond_expr, gnat_loop_spec);
3036 /* Open a new nesting level that will surround the loop to declare the
3037 iteration variable. */
3038 start_stmt_group ();
3039 gnat_pushlevel ();
3041 /* If we use the special induction variable, create it and set it to
3042 its initial value. Morever, the regular iteration variable cannot
3043 itself be initialized, lest the initial value wrapped around. */
3044 if (use_iv)
3046 gnu_loop_iv
3047 = create_init_temporary ("I", gnu_first, &gnu_stmt, gnat_loop_var);
3048 add_stmt (gnu_stmt);
3049 gnu_first = NULL_TREE;
3051 else
3052 gnu_loop_iv = NULL_TREE;
3054 /* Declare the iteration variable and set it to its initial value. */
3055 gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, 1);
3056 if (DECL_BY_REF_P (gnu_loop_var))
3057 gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
3058 else if (use_iv)
3060 gcc_assert (DECL_LOOP_PARM_P (gnu_loop_var));
3061 SET_DECL_INDUCTION_VAR (gnu_loop_var, gnu_loop_iv);
3063 gnu_loop_info->loop_var = gnu_loop_var;
3064 gnu_loop_info->low_bound = gnu_low;
3065 gnu_loop_info->high_bound = gnu_high;
3067 /* Do all the arithmetics in the base type. */
3068 gnu_loop_var = convert (gnu_base_type, gnu_loop_var);
3070 /* Set either the top or bottom exit condition. */
3071 if (use_iv)
3072 LOOP_STMT_COND (gnu_loop_stmt)
3073 = build_binary_op (test_code, boolean_type_node, gnu_loop_iv,
3074 gnu_last);
3075 else
3076 LOOP_STMT_COND (gnu_loop_stmt)
3077 = build_binary_op (test_code, boolean_type_node, gnu_loop_var,
3078 gnu_last);
3080 /* Set either the top or bottom update statement and give it the source
3081 location of the iteration for better coverage info. */
3082 if (use_iv)
3084 gnu_stmt
3085 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_iv,
3086 build_binary_op (update_code, gnu_base_type,
3087 gnu_loop_iv, gnu_one_node));
3088 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3089 append_to_statement_list (gnu_stmt,
3090 &LOOP_STMT_UPDATE (gnu_loop_stmt));
3091 gnu_stmt
3092 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
3093 gnu_loop_iv);
3094 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3095 append_to_statement_list (gnu_stmt,
3096 &LOOP_STMT_UPDATE (gnu_loop_stmt));
3098 else
3100 gnu_stmt
3101 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
3102 build_binary_op (update_code, gnu_base_type,
3103 gnu_loop_var, gnu_one_node));
3104 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
3105 LOOP_STMT_UPDATE (gnu_loop_stmt) = gnu_stmt;
3109 /* If the loop was named, have the name point to this loop. In this case,
3110 the association is not a DECL node, but the end label of the loop. */
3111 if (Present (Identifier (gnat_node)))
3112 save_gnu_tree (Entity (Identifier (gnat_node)), gnu_loop_label, true);
3114 /* Make the loop body into its own block, so any allocated storage will be
3115 released every iteration. This is needed for stack allocation. */
3116 LOOP_STMT_BODY (gnu_loop_stmt)
3117 = build_stmt_group (Statements (gnat_node), true);
3118 TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
3120 /* If we have an iteration scheme, then we are in a statement group. Add
3121 the LOOP_STMT to it, finish it and make it the "loop". */
3122 if (Present (gnat_iter_scheme) && No (Condition (gnat_iter_scheme)))
3124 /* First, if we have computed invariant conditions for range (or index)
3125 checks applied to the iteration variable, find out whether they can
3126 be evaluated to false at compile time; otherwise, if there are not
3127 too many of them, combine them with the original checks. If loop
3128 unswitching is enabled, do not require the loop bounds to be also
3129 invariant, as their evaluation will still be ahead of the loop. */
3130 if (vec_safe_length (gnu_loop_info->checks) > 0
3131 && (make_invariant (&gnu_low, &gnu_high) || flag_unswitch_loops))
3133 struct range_check_info_d *rci;
3134 unsigned int i, n_remaining_checks = 0;
3136 FOR_EACH_VEC_ELT (*gnu_loop_info->checks, i, rci)
3138 tree low_ok, high_ok;
3140 if (rci->low_bound)
3142 tree gnu_adjusted_low = convert (rci->type, gnu_low);
3143 if (rci->disp)
3144 gnu_adjusted_low
3145 = fold_build2 (rci->neg_p ? MINUS_EXPR : PLUS_EXPR,
3146 rci->type, gnu_adjusted_low, rci->disp);
3147 low_ok
3148 = build_binary_op (GE_EXPR, boolean_type_node,
3149 gnu_adjusted_low, rci->low_bound);
3151 else
3152 low_ok = boolean_true_node;
3154 if (rci->high_bound)
3156 tree gnu_adjusted_high = convert (rci->type, gnu_high);
3157 if (rci->disp)
3158 gnu_adjusted_high
3159 = fold_build2 (rci->neg_p ? MINUS_EXPR : PLUS_EXPR,
3160 rci->type, gnu_adjusted_high, rci->disp);
3161 high_ok
3162 = build_binary_op (LE_EXPR, boolean_type_node,
3163 gnu_adjusted_high, rci->high_bound);
3165 else
3166 high_ok = boolean_true_node;
3168 tree range_ok
3169 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
3170 low_ok, high_ok);
3172 rci->invariant_cond
3173 = build_unary_op (TRUTH_NOT_EXPR, boolean_type_node, range_ok);
3175 if (rci->invariant_cond == boolean_false_node)
3176 TREE_OPERAND (rci->inserted_cond, 0) = rci->invariant_cond;
3177 else
3178 n_remaining_checks++;
3181 /* Note that loop unswitching can only be applied a small number of
3182 times to a given loop (PARAM_MAX_UNSWITCH_LEVEL default to 3). */
3183 if (0 < n_remaining_checks && n_remaining_checks <= 3
3184 && optimize > 1 && !optimize_size)
3185 FOR_EACH_VEC_ELT (*gnu_loop_info->checks, i, rci)
3186 if (rci->invariant_cond != boolean_false_node)
3188 TREE_OPERAND (rci->inserted_cond, 0) = rci->invariant_cond;
3190 if (flag_unswitch_loops)
3191 add_stmt_with_node_force (rci->inserted_cond, gnat_node);
3195 /* Second, if loop vectorization is enabled and the iterations of the
3196 loop can easily be proved as independent, mark the loop. */
3197 if (optimize
3198 && flag_tree_loop_vectorize
3199 && independent_iterations_p (LOOP_STMT_BODY (gnu_loop_stmt)))
3200 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
3202 add_stmt (gnu_loop_stmt);
3203 gnat_poplevel ();
3204 gnu_loop_stmt = end_stmt_group ();
3207 /* If we have an outer COND_EXPR, that's our result and this loop is its
3208 "true" statement. Otherwise, the result is the LOOP_STMT. */
3209 if (gnu_cond_expr)
3211 COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
3212 TREE_SIDE_EFFECTS (gnu_cond_expr) = 1;
3213 gnu_result = gnu_cond_expr;
3215 else
3216 gnu_result = gnu_loop_stmt;
3218 gnu_loop_stack->pop ();
3220 return gnu_result;
3223 /* This page implements a form of Named Return Value optimization modelled
3224 on the C++ optimization of the same name. The main difference is that
3225 we disregard any semantical considerations when applying it here, the
3226 counterpart being that we don't try to apply it to semantically loaded
3227 return types, i.e. types with the TYPE_BY_REFERENCE_P flag set.
3229 We consider a function body of the following GENERIC form:
3231 return_type R1;
3232 [...]
3233 RETURN_EXPR [<retval> = ...]
3234 [...]
3235 RETURN_EXPR [<retval> = R1]
3236 [...]
3237 return_type Ri;
3238 [...]
3239 RETURN_EXPR [<retval> = ...]
3240 [...]
3241 RETURN_EXPR [<retval> = Ri]
3242 [...]
3244 and we try to fulfill a simple criterion that would make it possible to
3245 replace one or several Ri variables with the RESULT_DECL of the function.
3247 The first observation is that RETURN_EXPRs that don't directly reference
3248 any of the Ri variables on the RHS of their assignment are transparent wrt
3249 the optimization. This is because the Ri variables aren't addressable so
3250 any transformation applied to them doesn't affect the RHS; moreover, the
3251 assignment writes the full <retval> object so existing values are entirely
3252 discarded.
3254 This property can be extended to some forms of RETURN_EXPRs that reference
3255 the Ri variables, for example CONSTRUCTORs, but isn't true in the general
3256 case, in particular when function calls are involved.
3258 Therefore the algorithm is as follows:
3260 1. Collect the list of candidates for a Named Return Value (Ri variables
3261 on the RHS of assignments of RETURN_EXPRs) as well as the list of the
3262 other expressions on the RHS of such assignments.
3264 2. Prune the members of the first list (candidates) that are referenced
3265 by a member of the second list (expressions).
3267 3. Extract a set of candidates with non-overlapping live ranges from the
3268 first list. These are the Named Return Values.
3270 4. Adjust the relevant RETURN_EXPRs and replace the occurrences of the
3271 Named Return Values in the function with the RESULT_DECL.
3273 If the function returns an unconstrained type, things are a bit different
3274 because the anonymous return object is allocated on the secondary stack
3275 and RESULT_DECL is only a pointer to it. Each return object can be of a
3276 different size and is allocated separately so we need not care about the
3277 aforementioned overlapping issues. Therefore, we don't collect the other
3278 expressions and skip step #2 in the algorithm. */
3280 struct nrv_data
3282 bitmap nrv;
3283 tree result;
3284 Node_Id gnat_ret;
3285 hash_set<tree> *visited;
3288 /* Return true if T is a Named Return Value. */
3290 static inline bool
3291 is_nrv_p (bitmap nrv, tree t)
3293 return TREE_CODE (t) == VAR_DECL && bitmap_bit_p (nrv, DECL_UID (t));
3296 /* Helper function for walk_tree, used by finalize_nrv below. */
3298 static tree
3299 prune_nrv_r (tree *tp, int *walk_subtrees, void *data)
3301 struct nrv_data *dp = (struct nrv_data *)data;
3302 tree t = *tp;
3304 /* No need to walk into types or decls. */
3305 if (IS_TYPE_OR_DECL_P (t))
3306 *walk_subtrees = 0;
3308 if (is_nrv_p (dp->nrv, t))
3309 bitmap_clear_bit (dp->nrv, DECL_UID (t));
3311 return NULL_TREE;
3314 /* Prune Named Return Values in BLOCK and return true if there is still a
3315 Named Return Value in BLOCK or one of its sub-blocks. */
3317 static bool
3318 prune_nrv_in_block (bitmap nrv, tree block)
3320 bool has_nrv = false;
3321 tree t;
3323 /* First recurse on the sub-blocks. */
3324 for (t = BLOCK_SUBBLOCKS (block); t; t = BLOCK_CHAIN (t))
3325 has_nrv |= prune_nrv_in_block (nrv, t);
3327 /* Then make sure to keep at most one NRV per block. */
3328 for (t = BLOCK_VARS (block); t; t = DECL_CHAIN (t))
3329 if (is_nrv_p (nrv, t))
3331 if (has_nrv)
3332 bitmap_clear_bit (nrv, DECL_UID (t));
3333 else
3334 has_nrv = true;
3337 return has_nrv;
3340 /* Helper function for walk_tree, used by finalize_nrv below. */
3342 static tree
3343 finalize_nrv_r (tree *tp, int *walk_subtrees, void *data)
3345 struct nrv_data *dp = (struct nrv_data *)data;
3346 tree t = *tp;
3348 /* No need to walk into types. */
3349 if (TYPE_P (t))
3350 *walk_subtrees = 0;
3352 /* Change RETURN_EXPRs of NRVs to just refer to the RESULT_DECL; this is a
3353 nop, but differs from using NULL_TREE in that it indicates that we care
3354 about the value of the RESULT_DECL. */
3355 else if (TREE_CODE (t) == RETURN_EXPR
3356 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
3358 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1), init_expr;
3360 /* If this is the temporary created for a return value with variable
3361 size in Call_to_gnu, we replace the RHS with the init expression. */
3362 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3363 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
3364 && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
3365 == TREE_OPERAND (ret_val, 1))
3367 init_expr = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
3368 ret_val = TREE_OPERAND (ret_val, 1);
3370 else
3371 init_expr = NULL_TREE;
3373 /* Strip useless conversions around the return value. */
3374 if (gnat_useless_type_conversion (ret_val))
3375 ret_val = TREE_OPERAND (ret_val, 0);
3377 if (is_nrv_p (dp->nrv, ret_val))
3379 if (init_expr)
3380 TREE_OPERAND (TREE_OPERAND (t, 0), 1) = init_expr;
3381 else
3382 TREE_OPERAND (t, 0) = dp->result;
3386 /* Replace the DECL_EXPR of NRVs with an initialization of the RESULT_DECL,
3387 if needed. */
3388 else if (TREE_CODE (t) == DECL_EXPR
3389 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3391 tree var = DECL_EXPR_DECL (t), init;
3393 if (DECL_INITIAL (var))
3395 init = build_binary_op (INIT_EXPR, NULL_TREE, dp->result,
3396 DECL_INITIAL (var));
3397 SET_EXPR_LOCATION (init, EXPR_LOCATION (t));
3398 DECL_INITIAL (var) = NULL_TREE;
3400 else
3401 init = build_empty_stmt (EXPR_LOCATION (t));
3402 *tp = init;
3404 /* Identify the NRV to the RESULT_DECL for debugging purposes. */
3405 SET_DECL_VALUE_EXPR (var, dp->result);
3406 DECL_HAS_VALUE_EXPR_P (var) = 1;
3407 /* ??? Kludge to avoid an assertion failure during inlining. */
3408 DECL_SIZE (var) = bitsize_unit_node;
3409 DECL_SIZE_UNIT (var) = size_one_node;
3412 /* And replace all uses of NRVs with the RESULT_DECL. */
3413 else if (is_nrv_p (dp->nrv, t))
3414 *tp = convert (TREE_TYPE (t), dp->result);
3416 /* Avoid walking into the same tree more than once. Unfortunately, we
3417 can't just use walk_tree_without_duplicates because it would only
3418 call us for the first occurrence of NRVs in the function body. */
3419 if (dp->visited->add (*tp))
3420 *walk_subtrees = 0;
3422 return NULL_TREE;
3425 /* Likewise, but used when the function returns an unconstrained type. */
3427 static tree
3428 finalize_nrv_unc_r (tree *tp, int *walk_subtrees, void *data)
3430 struct nrv_data *dp = (struct nrv_data *)data;
3431 tree t = *tp;
3433 /* No need to walk into types. */
3434 if (TYPE_P (t))
3435 *walk_subtrees = 0;
3437 /* We need to see the DECL_EXPR of NRVs before any other references so we
3438 walk the body of BIND_EXPR before walking its variables. */
3439 else if (TREE_CODE (t) == BIND_EXPR)
3440 walk_tree (&BIND_EXPR_BODY (t), finalize_nrv_unc_r, data, NULL);
3442 /* Change RETURN_EXPRs of NRVs to assign to the RESULT_DECL only the final
3443 return value built by the allocator instead of the whole construct. */
3444 else if (TREE_CODE (t) == RETURN_EXPR
3445 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
3447 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
3449 /* This is the construct returned by the allocator. */
3450 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3451 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR)
3453 tree rhs = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
3455 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (ret_val)))
3456 ret_val = CONSTRUCTOR_ELT (rhs, 1)->value;
3457 else
3458 ret_val = rhs;
3461 /* Strip useless conversions around the return value. */
3462 if (gnat_useless_type_conversion (ret_val)
3463 || TREE_CODE (ret_val) == VIEW_CONVERT_EXPR)
3464 ret_val = TREE_OPERAND (ret_val, 0);
3466 /* Strip unpadding around the return value. */
3467 if (TREE_CODE (ret_val) == COMPONENT_REF
3468 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
3469 ret_val = TREE_OPERAND (ret_val, 0);
3471 /* Assign the new return value to the RESULT_DECL. */
3472 if (is_nrv_p (dp->nrv, ret_val))
3473 TREE_OPERAND (TREE_OPERAND (t, 0), 1)
3474 = TREE_OPERAND (DECL_INITIAL (ret_val), 0);
3477 /* Adjust the DECL_EXPR of NRVs to call the allocator and save the result
3478 into a new variable. */
3479 else if (TREE_CODE (t) == DECL_EXPR
3480 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3482 tree saved_current_function_decl = current_function_decl;
3483 tree var = DECL_EXPR_DECL (t);
3484 tree alloc, p_array, new_var, new_ret;
3485 vec<constructor_elt, va_gc> *v;
3486 vec_alloc (v, 2);
3488 /* Create an artificial context to build the allocation. */
3489 current_function_decl = decl_function_context (var);
3490 start_stmt_group ();
3491 gnat_pushlevel ();
3493 /* This will return a COMPOUND_EXPR with the allocation in the first
3494 arm and the final return value in the second arm. */
3495 alloc = build_allocator (TREE_TYPE (var), DECL_INITIAL (var),
3496 TREE_TYPE (dp->result),
3497 Procedure_To_Call (dp->gnat_ret),
3498 Storage_Pool (dp->gnat_ret),
3499 Empty, false);
3501 /* The new variable is built as a reference to the allocated space. */
3502 new_var
3503 = build_decl (DECL_SOURCE_LOCATION (var), VAR_DECL, DECL_NAME (var),
3504 build_reference_type (TREE_TYPE (var)));
3505 DECL_BY_REFERENCE (new_var) = 1;
3507 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (alloc)))
3509 tree cst = TREE_OPERAND (alloc, 1);
3511 /* The new initial value is a COMPOUND_EXPR with the allocation in
3512 the first arm and the value of P_ARRAY in the second arm. */
3513 DECL_INITIAL (new_var)
3514 = build2 (COMPOUND_EXPR, TREE_TYPE (new_var),
3515 TREE_OPERAND (alloc, 0),
3516 CONSTRUCTOR_ELT (cst, 0)->value);
3518 /* Build a modified CONSTRUCTOR that references NEW_VAR. */
3519 p_array = TYPE_FIELDS (TREE_TYPE (alloc));
3520 CONSTRUCTOR_APPEND_ELT (v, p_array,
3521 fold_convert (TREE_TYPE (p_array), new_var));
3522 CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (p_array),
3523 CONSTRUCTOR_ELT (cst, 1)->value);
3524 new_ret = build_constructor (TREE_TYPE (alloc), v);
3526 else
3528 /* The new initial value is just the allocation. */
3529 DECL_INITIAL (new_var) = alloc;
3530 new_ret = fold_convert (TREE_TYPE (alloc), new_var);
3533 gnat_pushdecl (new_var, Empty);
3535 /* Destroy the artificial context and insert the new statements. */
3536 gnat_zaplevel ();
3537 *tp = end_stmt_group ();
3538 current_function_decl = saved_current_function_decl;
3540 /* Chain NEW_VAR immediately after VAR and ignore the latter. */
3541 DECL_CHAIN (new_var) = DECL_CHAIN (var);
3542 DECL_CHAIN (var) = new_var;
3543 DECL_IGNORED_P (var) = 1;
3545 /* Save the new return value and the dereference of NEW_VAR. */
3546 DECL_INITIAL (var)
3547 = build2 (COMPOUND_EXPR, TREE_TYPE (var), new_ret,
3548 build1 (INDIRECT_REF, TREE_TYPE (var), new_var));
3549 /* ??? Kludge to avoid messing up during inlining. */
3550 DECL_CONTEXT (var) = NULL_TREE;
3553 /* And replace all uses of NRVs with the dereference of NEW_VAR. */
3554 else if (is_nrv_p (dp->nrv, t))
3555 *tp = TREE_OPERAND (DECL_INITIAL (t), 1);
3557 /* Avoid walking into the same tree more than once. Unfortunately, we
3558 can't just use walk_tree_without_duplicates because it would only
3559 call us for the first occurrence of NRVs in the function body. */
3560 if (dp->visited->add (*tp))
3561 *walk_subtrees = 0;
3563 return NULL_TREE;
3566 /* Finalize the Named Return Value optimization for FNDECL. The NRV bitmap
3567 contains the candidates for Named Return Value and OTHER is a list of
3568 the other return values. GNAT_RET is a representative return node. */
3570 static void
3571 finalize_nrv (tree fndecl, bitmap nrv, vec<tree, va_gc> *other, Node_Id gnat_ret)
3573 struct cgraph_node *node;
3574 struct nrv_data data;
3575 walk_tree_fn func;
3576 unsigned int i;
3577 tree iter;
3579 /* We shouldn't be applying the optimization to return types that we aren't
3580 allowed to manipulate freely. */
3581 gcc_assert (!TYPE_IS_BY_REFERENCE_P (TREE_TYPE (TREE_TYPE (fndecl))));
3583 /* Prune the candidates that are referenced by other return values. */
3584 data.nrv = nrv;
3585 data.result = NULL_TREE;
3586 data.gnat_ret = Empty;
3587 data.visited = NULL;
3588 FOR_EACH_VEC_SAFE_ELT (other, i, iter)
3589 walk_tree_without_duplicates (&iter, prune_nrv_r, &data);
3590 if (bitmap_empty_p (nrv))
3591 return;
3593 /* Prune also the candidates that are referenced by nested functions. */
3594 node = cgraph_node::get_create (fndecl);
3595 for (node = node->nested; node; node = node->next_nested)
3596 walk_tree_without_duplicates (&DECL_SAVED_TREE (node->decl), prune_nrv_r,
3597 &data);
3598 if (bitmap_empty_p (nrv))
3599 return;
3601 /* Extract a set of NRVs with non-overlapping live ranges. */
3602 if (!prune_nrv_in_block (nrv, DECL_INITIAL (fndecl)))
3603 return;
3605 /* Adjust the relevant RETURN_EXPRs and replace the occurrences of NRVs. */
3606 data.nrv = nrv;
3607 data.result = DECL_RESULT (fndecl);
3608 data.gnat_ret = gnat_ret;
3609 data.visited = new hash_set<tree>;
3610 if (TYPE_RETURN_UNCONSTRAINED_P (TREE_TYPE (fndecl)))
3611 func = finalize_nrv_unc_r;
3612 else
3613 func = finalize_nrv_r;
3614 walk_tree (&DECL_SAVED_TREE (fndecl), func, &data, NULL);
3615 delete data.visited;
3618 /* Return true if RET_VAL can be used as a Named Return Value for the
3619 anonymous return object RET_OBJ. */
3621 static bool
3622 return_value_ok_for_nrv_p (tree ret_obj, tree ret_val)
3624 if (TREE_CODE (ret_val) != VAR_DECL)
3625 return false;
3627 if (TREE_THIS_VOLATILE (ret_val))
3628 return false;
3630 if (DECL_CONTEXT (ret_val) != current_function_decl)
3631 return false;
3633 if (TREE_STATIC (ret_val))
3634 return false;
3636 if (TREE_ADDRESSABLE (ret_val))
3637 return false;
3639 if (ret_obj && DECL_ALIGN (ret_val) > DECL_ALIGN (ret_obj))
3640 return false;
3642 return true;
3645 /* Build a RETURN_EXPR. If RET_VAL is non-null, build a RETURN_EXPR around
3646 the assignment of RET_VAL to RET_OBJ. Otherwise build a bare RETURN_EXPR
3647 around RESULT_OBJ, which may be null in this case. */
3649 static tree
3650 build_return_expr (tree ret_obj, tree ret_val)
3652 tree result_expr;
3654 if (ret_val)
3656 /* The gimplifier explicitly enforces the following invariant:
3658 RETURN_EXPR
3660 INIT_EXPR
3663 RET_OBJ ...
3665 As a consequence, type consistency dictates that we use the type
3666 of the RET_OBJ as the operation type. */
3667 tree operation_type = TREE_TYPE (ret_obj);
3669 /* Convert the right operand to the operation type. Note that this is
3670 the transformation applied in the INIT_EXPR case of build_binary_op,
3671 with the assumption that the type cannot involve a placeholder. */
3672 if (operation_type != TREE_TYPE (ret_val))
3673 ret_val = convert (operation_type, ret_val);
3675 /* We always can use an INIT_EXPR for the return object. */
3676 result_expr = build2 (INIT_EXPR, void_type_node, ret_obj, ret_val);
3678 /* If the function returns an aggregate type, find out whether this is
3679 a candidate for Named Return Value. If so, record it. Otherwise,
3680 if this is an expression of some kind, record it elsewhere. */
3681 if (optimize
3682 && AGGREGATE_TYPE_P (operation_type)
3683 && !TYPE_IS_FAT_POINTER_P (operation_type)
3684 && TYPE_MODE (operation_type) == BLKmode
3685 && aggregate_value_p (operation_type, current_function_decl))
3687 /* Recognize the temporary created for a return value with variable
3688 size in Call_to_gnu. We want to eliminate it if possible. */
3689 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3690 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
3691 && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
3692 == TREE_OPERAND (ret_val, 1))
3693 ret_val = TREE_OPERAND (ret_val, 1);
3695 /* Strip useless conversions around the return value. */
3696 if (gnat_useless_type_conversion (ret_val))
3697 ret_val = TREE_OPERAND (ret_val, 0);
3699 /* Now apply the test to the return value. */
3700 if (return_value_ok_for_nrv_p (ret_obj, ret_val))
3702 if (!f_named_ret_val)
3703 f_named_ret_val = BITMAP_GGC_ALLOC ();
3704 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
3707 /* Note that we need not care about CONSTRUCTORs here, as they are
3708 totally transparent given the read-compose-write semantics of
3709 assignments from CONSTRUCTORs. */
3710 else if (EXPR_P (ret_val))
3711 vec_safe_push (f_other_ret_val, ret_val);
3714 else
3715 result_expr = ret_obj;
3717 return build1 (RETURN_EXPR, void_type_node, result_expr);
3720 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Subprogram_Body. We
3721 don't return anything. */
3723 static void
3724 Subprogram_Body_to_gnu (Node_Id gnat_node)
3726 /* Defining identifier of a parameter to the subprogram. */
3727 Entity_Id gnat_param;
3728 /* The defining identifier for the subprogram body. Note that if a
3729 specification has appeared before for this body, then the identifier
3730 occurring in that specification will also be a defining identifier and all
3731 the calls to this subprogram will point to that specification. */
3732 Entity_Id gnat_subprog_id
3733 = (Present (Corresponding_Spec (gnat_node))
3734 ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
3735 /* The FUNCTION_DECL node corresponding to the subprogram spec. */
3736 tree gnu_subprog_decl;
3737 /* Its RESULT_DECL node. */
3738 tree gnu_result_decl;
3739 /* Its FUNCTION_TYPE node. */
3740 tree gnu_subprog_type;
3741 /* The TYPE_CI_CO_LIST of its FUNCTION_TYPE node, if any. */
3742 tree gnu_cico_list;
3743 /* The entry in the CI_CO_LIST that represents a function return, if any. */
3744 tree gnu_return_var_elmt = NULL_TREE;
3745 tree gnu_result;
3746 location_t locus;
3747 struct language_function *gnu_subprog_language;
3748 vec<parm_attr, va_gc> *cache;
3750 /* If this is a generic object or if it has been eliminated,
3751 ignore it. */
3752 if (Ekind (gnat_subprog_id) == E_Generic_Procedure
3753 || Ekind (gnat_subprog_id) == E_Generic_Function
3754 || Is_Eliminated (gnat_subprog_id))
3755 return;
3757 /* If this subprogram acts as its own spec, define it. Otherwise, just get
3758 the already-elaborated tree node. However, if this subprogram had its
3759 elaboration deferred, we will already have made a tree node for it. So
3760 treat it as not being defined in that case. Such a subprogram cannot
3761 have an address clause or a freeze node, so this test is safe, though it
3762 does disable some otherwise-useful error checking. */
3763 gnu_subprog_decl
3764 = gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE,
3765 Acts_As_Spec (gnat_node)
3766 && !present_gnu_tree (gnat_subprog_id));
3767 gnu_result_decl = DECL_RESULT (gnu_subprog_decl);
3768 gnu_subprog_type = TREE_TYPE (gnu_subprog_decl);
3769 gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
3770 if (gnu_cico_list && TREE_VALUE (gnu_cico_list) == void_type_node)
3771 gnu_return_var_elmt = gnu_cico_list;
3773 /* If the function returns by invisible reference, make it explicit in the
3774 function body. See gnat_to_gnu_entity, E_Subprogram_Type case. */
3775 if (TREE_ADDRESSABLE (gnu_subprog_type))
3777 TREE_TYPE (gnu_result_decl)
3778 = build_reference_type (TREE_TYPE (gnu_result_decl));
3779 relayout_decl (gnu_result_decl);
3782 /* Set the line number in the decl to correspond to that of the body. */
3783 Sloc_to_locus (Sloc (gnat_node), &locus);
3784 DECL_SOURCE_LOCATION (gnu_subprog_decl) = locus;
3786 /* Initialize the information structure for the function. */
3787 allocate_struct_function (gnu_subprog_decl, false);
3788 gnu_subprog_language = ggc_cleared_alloc<language_function> ();
3789 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language = gnu_subprog_language;
3790 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->function_start_locus = locus;
3791 set_cfun (NULL);
3793 begin_subprog_body (gnu_subprog_decl);
3795 /* If there are copy-in/copy-out parameters, we need to ensure that they are
3796 properly copied out by the return statement. We do this by making a new
3797 block and converting any return into a goto to a label at the end of the
3798 block. */
3799 if (gnu_cico_list)
3801 tree gnu_return_var = NULL_TREE;
3803 vec_safe_push (gnu_return_label_stack,
3804 create_artificial_label (input_location));
3806 start_stmt_group ();
3807 gnat_pushlevel ();
3809 /* If this is a function with copy-in/copy-out parameters and which does
3810 not return by invisible reference, we also need a variable for the
3811 return value to be placed. */
3812 if (gnu_return_var_elmt && !TREE_ADDRESSABLE (gnu_subprog_type))
3814 tree gnu_return_type
3815 = TREE_TYPE (TREE_PURPOSE (gnu_return_var_elmt));
3817 gnu_return_var
3818 = create_var_decl (get_identifier ("RETVAL"), NULL_TREE,
3819 gnu_return_type, NULL_TREE,
3820 false, false, false, false, false,
3821 true, false, NULL, gnat_subprog_id);
3822 TREE_VALUE (gnu_return_var_elmt) = gnu_return_var;
3825 vec_safe_push (gnu_return_var_stack, gnu_return_var);
3827 /* See whether there are parameters for which we don't have a GCC tree
3828 yet. These must be Out parameters. Make a VAR_DECL for them and
3829 put it into TYPE_CI_CO_LIST, which must contain an empty entry too.
3830 We can match up the entries because TYPE_CI_CO_LIST is in the order
3831 of the parameters. */
3832 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3833 Present (gnat_param);
3834 gnat_param = Next_Formal_With_Extras (gnat_param))
3835 if (!present_gnu_tree (gnat_param))
3837 tree gnu_cico_entry = gnu_cico_list;
3838 tree gnu_decl;
3840 /* Skip any entries that have been already filled in; they must
3841 correspond to In Out parameters. */
3842 while (gnu_cico_entry && TREE_VALUE (gnu_cico_entry))
3843 gnu_cico_entry = TREE_CHAIN (gnu_cico_entry);
3845 /* Do any needed dereferences for by-ref objects. */
3846 gnu_decl = gnat_to_gnu_entity (gnat_param, NULL_TREE, 1);
3847 gcc_assert (DECL_P (gnu_decl));
3848 if (DECL_BY_REF_P (gnu_decl))
3849 gnu_decl = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_decl);
3851 /* Do any needed references for padded types. */
3852 TREE_VALUE (gnu_cico_entry)
3853 = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_entry)), gnu_decl);
3856 else
3857 vec_safe_push (gnu_return_label_stack, NULL_TREE);
3859 /* Get a tree corresponding to the code for the subprogram. */
3860 start_stmt_group ();
3861 gnat_pushlevel ();
3863 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
3865 /* Generate the code of the subprogram itself. A return statement will be
3866 present and any Out parameters will be handled there. */
3867 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
3868 gnat_poplevel ();
3869 gnu_result = end_stmt_group ();
3871 /* If we populated the parameter attributes cache, we need to make sure that
3872 the cached expressions are evaluated on all the possible paths leading to
3873 their uses. So we force their evaluation on entry of the function. */
3874 cache = gnu_subprog_language->parm_attr_cache;
3875 if (cache)
3877 struct parm_attr_d *pa;
3878 int i;
3880 start_stmt_group ();
3882 FOR_EACH_VEC_ELT (*cache, i, pa)
3884 if (pa->first)
3885 add_stmt_with_node_force (pa->first, gnat_node);
3886 if (pa->last)
3887 add_stmt_with_node_force (pa->last, gnat_node);
3888 if (pa->length)
3889 add_stmt_with_node_force (pa->length, gnat_node);
3892 add_stmt (gnu_result);
3893 gnu_result = end_stmt_group ();
3895 gnu_subprog_language->parm_attr_cache = NULL;
3898 /* If we are dealing with a return from an Ada procedure with parameters
3899 passed by copy-in/copy-out, we need to return a record containing the
3900 final values of these parameters. If the list contains only one entry,
3901 return just that entry though.
3903 For a full description of the copy-in/copy-out parameter mechanism, see
3904 the part of the gnat_to_gnu_entity routine dealing with the translation
3905 of subprograms.
3907 We need to make a block that contains the definition of that label and
3908 the copying of the return value. It first contains the function, then
3909 the label and copy statement. */
3910 if (gnu_cico_list)
3912 const Node_Id gnat_end_label
3913 = End_Label (Handled_Statement_Sequence (gnat_node));
3915 gnu_return_var_stack->pop ();
3917 add_stmt (gnu_result);
3918 add_stmt (build1 (LABEL_EXPR, void_type_node,
3919 gnu_return_label_stack->last ()));
3921 /* If this is a function which returns by invisible reference, the
3922 return value has already been dealt with at the return statements,
3923 so we only need to indirectly copy out the parameters. */
3924 if (TREE_ADDRESSABLE (gnu_subprog_type))
3926 tree gnu_ret_deref
3927 = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result_decl);
3928 tree t;
3930 gcc_assert (TREE_VALUE (gnu_cico_list) == void_type_node);
3932 for (t = TREE_CHAIN (gnu_cico_list); t; t = TREE_CHAIN (t))
3934 tree gnu_field_deref
3935 = build_component_ref (gnu_ret_deref, TREE_PURPOSE (t), true);
3936 gnu_result = build2 (MODIFY_EXPR, void_type_node,
3937 gnu_field_deref, TREE_VALUE (t));
3938 add_stmt_with_node (gnu_result, gnat_end_label);
3942 /* Otherwise, if this is a procedure or a function which does not return
3943 by invisible reference, we can do a direct block-copy out. */
3944 else
3946 tree gnu_retval;
3948 if (list_length (gnu_cico_list) == 1)
3949 gnu_retval = TREE_VALUE (gnu_cico_list);
3950 else
3951 gnu_retval
3952 = build_constructor_from_list (TREE_TYPE (gnu_subprog_type),
3953 gnu_cico_list);
3955 gnu_result = build_return_expr (gnu_result_decl, gnu_retval);
3956 add_stmt_with_node (gnu_result, gnat_end_label);
3959 gnat_poplevel ();
3960 gnu_result = end_stmt_group ();
3963 gnu_return_label_stack->pop ();
3965 /* Attempt setting the end_locus of our GCC body tree, typically a
3966 BIND_EXPR or STATEMENT_LIST, then the end_locus of our GCC subprogram
3967 declaration tree. */
3968 set_end_locus_from_node (gnu_result, gnat_node);
3969 set_end_locus_from_node (gnu_subprog_decl, gnat_node);
3971 /* On SEH targets, install an exception handler around the main entry
3972 point to catch unhandled exceptions. */
3973 if (DECL_NAME (gnu_subprog_decl) == main_identifier_node
3974 && targetm_common.except_unwind_info (&global_options) == UI_SEH)
3976 tree t;
3977 tree etype;
3979 t = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
3980 1, integer_zero_node);
3981 t = build_call_n_expr (unhandled_except_decl, 1, t);
3983 etype = build_unary_op (ADDR_EXPR, NULL_TREE, unhandled_others_decl);
3984 etype = tree_cons (NULL_TREE, etype, NULL_TREE);
3986 t = build2 (CATCH_EXPR, void_type_node, etype, t);
3987 gnu_result = build2 (TRY_CATCH_EXPR, TREE_TYPE (gnu_result),
3988 gnu_result, t);
3991 end_subprog_body (gnu_result);
3993 /* Finally annotate the parameters and disconnect the trees for parameters
3994 that we have turned into variables since they are now unusable. */
3995 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3996 Present (gnat_param);
3997 gnat_param = Next_Formal_With_Extras (gnat_param))
3999 tree gnu_param = get_gnu_tree (gnat_param);
4000 bool is_var_decl = (TREE_CODE (gnu_param) == VAR_DECL);
4002 annotate_object (gnat_param, TREE_TYPE (gnu_param), NULL_TREE,
4003 DECL_BY_REF_P (gnu_param));
4005 if (is_var_decl)
4006 save_gnu_tree (gnat_param, NULL_TREE, false);
4009 /* Disconnect the variable created for the return value. */
4010 if (gnu_return_var_elmt)
4011 TREE_VALUE (gnu_return_var_elmt) = void_type_node;
4013 /* If the function returns an aggregate type and we have candidates for
4014 a Named Return Value, finalize the optimization. */
4015 if (optimize && gnu_subprog_language->named_ret_val)
4017 finalize_nrv (gnu_subprog_decl,
4018 gnu_subprog_language->named_ret_val,
4019 gnu_subprog_language->other_ret_val,
4020 gnu_subprog_language->gnat_ret);
4021 gnu_subprog_language->named_ret_val = NULL;
4022 gnu_subprog_language->other_ret_val = NULL;
4025 /* If this is an inlined external function that has been marked uninlinable,
4026 drop the body and stop there. Otherwise compile the body. */
4027 if (DECL_EXTERNAL (gnu_subprog_decl) && DECL_UNINLINABLE (gnu_subprog_decl))
4028 DECL_SAVED_TREE (gnu_subprog_decl) = NULL_TREE;
4029 else
4030 rest_of_subprog_body_compilation (gnu_subprog_decl);
4033 /* Return true if GNAT_NODE references an Atomic entity. */
4035 static bool
4036 node_is_atomic (Node_Id gnat_node)
4038 Entity_Id gnat_entity;
4040 switch (Nkind (gnat_node))
4042 case N_Identifier:
4043 case N_Expanded_Name:
4044 gnat_entity = Entity (gnat_node);
4045 if (Ekind (gnat_entity) != E_Variable)
4046 break;
4047 return Is_Atomic (gnat_entity) || Is_Atomic (Etype (gnat_entity));
4049 case N_Selected_Component:
4050 gnat_entity = Entity (Selector_Name (gnat_node));
4051 return Is_Atomic (gnat_entity) || Is_Atomic (Etype (gnat_entity));
4053 case N_Indexed_Component:
4054 if (Has_Atomic_Components (Etype (Prefix (gnat_node))))
4055 return true;
4057 /* ... fall through ... */
4059 case N_Explicit_Dereference:
4060 return Is_Atomic (Etype (gnat_node));
4062 default:
4063 break;
4066 return false;
4069 /* Return true if GNAT_NODE references a Volatile_Full_Access entity. */
4071 static bool
4072 node_has_volatile_full_access (Node_Id gnat_node)
4074 Entity_Id gnat_entity;
4076 switch (Nkind (gnat_node))
4078 case N_Identifier:
4079 case N_Expanded_Name:
4080 gnat_entity = Entity (gnat_node);
4081 if (Ekind (gnat_entity) != E_Variable)
4082 break;
4083 return Is_Volatile_Full_Access (gnat_entity)
4084 || Is_Volatile_Full_Access (Etype (gnat_entity));
4086 case N_Selected_Component:
4087 gnat_entity = Entity (Selector_Name (gnat_node));
4088 return Is_Volatile_Full_Access (gnat_entity)
4089 || Is_Volatile_Full_Access (Etype (gnat_entity));
4091 case N_Indexed_Component:
4092 case N_Explicit_Dereference:
4093 return Is_Volatile_Full_Access (Etype (gnat_node));
4095 default:
4096 break;
4099 return false;
4102 /* Strip any type conversion on GNAT_NODE and return the result. */
4104 static Node_Id
4105 gnat_strip_type_conversion (Node_Id gnat_node)
4107 Node_Kind kind = Nkind (gnat_node);
4109 if (kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
4110 gnat_node = Expression (gnat_node);
4112 return gnat_node;
4115 /* Return true if GNAT_NODE requires outer atomic access, i.e. atomic access
4116 of an object of which GNAT_NODE is a component. */
4118 static bool
4119 outer_atomic_access_required_p (Node_Id gnat_node)
4121 gnat_node = gnat_strip_type_conversion (gnat_node);
4123 while (true)
4125 switch (Nkind (gnat_node))
4127 case N_Identifier:
4128 case N_Expanded_Name:
4129 if (No (Renamed_Object (Entity (gnat_node))))
4130 return false;
4131 gnat_node
4132 = gnat_strip_type_conversion (Renamed_Object (Entity (gnat_node)));
4133 break;
4135 case N_Indexed_Component:
4136 case N_Selected_Component:
4137 case N_Slice:
4138 gnat_node = gnat_strip_type_conversion (Prefix (gnat_node));
4139 if (node_has_volatile_full_access (gnat_node))
4140 return true;
4141 break;
4143 default:
4144 return false;
4148 gcc_unreachable ();
4151 /* Return true if GNAT_NODE requires atomic access and set SYNC according to
4152 the associated synchronization setting. */
4154 static bool
4155 atomic_access_required_p (Node_Id gnat_node, bool *sync)
4157 const Node_Id gnat_parent = Parent (gnat_node);
4158 unsigned char attr_id;
4159 bool as_a_whole = true;
4161 /* First, scan the parent to find out cases where the flag is irrelevant. */
4162 switch (Nkind (gnat_parent))
4164 case N_Attribute_Reference:
4165 attr_id = Get_Attribute_Id (Attribute_Name (gnat_parent));
4166 /* Do not mess up machine code insertions. */
4167 if (attr_id == Attr_Asm_Input || attr_id == Attr_Asm_Output)
4168 return false;
4170 /* Nothing to do if we are the prefix of an attribute, since we do not
4171 want an atomic access for things like 'Size. */
4173 /* ... fall through ... */
4175 case N_Reference:
4176 /* The N_Reference node is like an attribute. */
4177 if (Prefix (gnat_parent) == gnat_node)
4178 return false;
4179 break;
4181 case N_Indexed_Component:
4182 case N_Selected_Component:
4183 case N_Slice:
4184 /* If we are the prefix, then the access is only partial. */
4185 if (Prefix (gnat_parent) == gnat_node)
4186 as_a_whole = false;
4187 break;
4189 case N_Object_Renaming_Declaration:
4190 /* Nothing to do for the identifier in an object renaming declaration,
4191 the renaming itself does not need atomic access. */
4192 return false;
4194 default:
4195 break;
4198 /* Then, scan the node to find the atomic object. */
4199 gnat_node = gnat_strip_type_conversion (gnat_node);
4201 /* For Atomic itself, only reads and updates of the object as a whole require
4202 atomic access (RM C.6 (15)). But for Volatile_Full_Access, all reads and
4203 updates require atomic access. */
4204 if (!(as_a_whole && node_is_atomic (gnat_node))
4205 && !node_has_volatile_full_access (gnat_node))
4206 return false;
4208 /* If an outer atomic access will also be required, it cancels this one. */
4209 if (outer_atomic_access_required_p (gnat_node))
4210 return false;
4212 *sync = Atomic_Sync_Required (gnat_node);
4214 return true;
4217 /* Create a temporary variable with PREFIX and TYPE, and return it. */
4219 static tree
4220 create_temporary (const char *prefix, tree type)
4222 tree gnu_temp
4223 = create_var_decl (create_tmp_var_name (prefix), NULL_TREE,
4224 type, NULL_TREE,
4225 false, false, false, false, false,
4226 true, false, NULL, Empty);
4227 return gnu_temp;
4230 /* Create a temporary variable with PREFIX and initialize it with GNU_INIT.
4231 Put the initialization statement into GNU_INIT_STMT and annotate it with
4232 the SLOC of GNAT_NODE. Return the temporary variable. */
4234 static tree
4235 create_init_temporary (const char *prefix, tree gnu_init, tree *gnu_init_stmt,
4236 Node_Id gnat_node)
4238 tree gnu_temp = create_temporary (prefix, TREE_TYPE (gnu_init));
4240 *gnu_init_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_temp, gnu_init);
4241 set_expr_location_from_node (*gnu_init_stmt, gnat_node);
4243 return gnu_temp;
4246 /* Subroutine of gnat_to_gnu to translate gnat_node, either an N_Function_Call
4247 or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
4248 GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
4249 If GNU_TARGET is non-null, this must be a function call on the RHS of a
4250 N_Assignment_Statement and the result is to be placed into that object.
4251 If OUTER_ATOMIC_ACCESS is true, then the assignment to GNU_TARGET must be a
4252 load-modify-store sequence. Otherwise, if ATOMIC_ACCESS is true, then the
4253 assignment to GNU_TARGET must be atomic. If, in addition, ATOMIC_SYNC is
4254 true, then the assignment to GNU_TARGET requires atomic synchronization. */
4256 static tree
4257 Call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target,
4258 bool outer_atomic_access, bool atomic_access, bool atomic_sync)
4260 const bool function_call = (Nkind (gnat_node) == N_Function_Call);
4261 const bool returning_value = (function_call && !gnu_target);
4262 /* The GCC node corresponding to the GNAT subprogram name. This can either
4263 be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
4264 or an indirect reference expression (an INDIRECT_REF node) pointing to a
4265 subprogram. */
4266 tree gnu_subprog = gnat_to_gnu (Name (gnat_node));
4267 /* The FUNCTION_TYPE node giving the GCC type of the subprogram. */
4268 tree gnu_subprog_type = TREE_TYPE (gnu_subprog);
4269 /* The return type of the FUNCTION_TYPE. */
4270 tree gnu_result_type = TREE_TYPE (gnu_subprog_type);
4271 tree gnu_subprog_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_subprog);
4272 vec<tree, va_gc> *gnu_actual_vec = NULL;
4273 tree gnu_name_list = NULL_TREE;
4274 tree gnu_stmt_list = NULL_TREE;
4275 tree gnu_after_list = NULL_TREE;
4276 tree gnu_retval = NULL_TREE;
4277 tree gnu_call, gnu_result;
4278 bool went_into_elab_proc = false;
4279 bool pushed_binding_level = false;
4280 Entity_Id gnat_formal;
4281 Node_Id gnat_actual;
4282 bool sync;
4284 gcc_assert (TREE_CODE (gnu_subprog_type) == FUNCTION_TYPE);
4286 /* If we are calling a stubbed function, raise Program_Error, but Elaborate
4287 all our args first. */
4288 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL && DECL_STUBBED_P (gnu_subprog))
4290 tree call_expr = build_call_raise (PE_Stubbed_Subprogram_Called,
4291 gnat_node, N_Raise_Program_Error);
4293 for (gnat_actual = First_Actual (gnat_node);
4294 Present (gnat_actual);
4295 gnat_actual = Next_Actual (gnat_actual))
4296 add_stmt (gnat_to_gnu (gnat_actual));
4298 if (returning_value)
4300 *gnu_result_type_p = gnu_result_type;
4301 return build1 (NULL_EXPR, gnu_result_type, call_expr);
4304 return call_expr;
4307 /* For a call to a nested function, check the inlining status. */
4308 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL
4309 && decl_function_context (gnu_subprog))
4310 check_inlining_for_nested_subprog (gnu_subprog);
4312 /* The only way we can be making a call via an access type is if Name is an
4313 explicit dereference. In that case, get the list of formal args from the
4314 type the access type is pointing to. Otherwise, get the formals from the
4315 entity being called. */
4316 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
4317 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
4318 else if (Nkind (Name (gnat_node)) == N_Attribute_Reference)
4319 /* Assume here that this must be 'Elab_Body or 'Elab_Spec. */
4320 gnat_formal = Empty;
4321 else
4322 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
4324 /* The lifetime of the temporaries created for the call ends right after the
4325 return value is copied, so we can give them the scope of the elaboration
4326 routine at top level. */
4327 if (!current_function_decl)
4329 current_function_decl = get_elaboration_procedure ();
4330 went_into_elab_proc = true;
4333 /* First, create the temporary for the return value when:
4335 1. There is no target and the function has copy-in/copy-out parameters,
4336 because we need to preserve the return value before copying back the
4337 parameters.
4339 2. There is no target and this is neither an object nor a renaming
4340 declaration, and the return type has variable size, because in
4341 these cases the gimplifier cannot create the temporary.
4343 3. There is a target and it is a slice or an array with fixed size,
4344 and the return type has variable size, because the gimplifier
4345 doesn't handle these cases.
4347 This must be done before we push a binding level around the call, since
4348 we will pop it before copying the return value. */
4349 if (function_call
4350 && ((!gnu_target && TYPE_CI_CO_LIST (gnu_subprog_type))
4351 || (!gnu_target
4352 && Nkind (Parent (gnat_node)) != N_Object_Declaration
4353 && Nkind (Parent (gnat_node)) != N_Object_Renaming_Declaration
4354 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)
4355 || (gnu_target
4356 && (TREE_CODE (gnu_target) == ARRAY_RANGE_REF
4357 || (TREE_CODE (TREE_TYPE (gnu_target)) == ARRAY_TYPE
4358 && TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_target)))
4359 == INTEGER_CST))
4360 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)))
4361 gnu_retval = create_temporary ("R", gnu_result_type);
4363 /* Create the list of the actual parameters as GCC expects it, namely a
4364 chain of TREE_LIST nodes in which the TREE_VALUE field of each node
4365 is an expression and the TREE_PURPOSE field is null. But skip Out
4366 parameters not passed by reference and that need not be copied in. */
4367 for (gnat_actual = First_Actual (gnat_node);
4368 Present (gnat_actual);
4369 gnat_formal = Next_Formal_With_Extras (gnat_formal),
4370 gnat_actual = Next_Actual (gnat_actual))
4372 Entity_Id gnat_formal_type = Etype (gnat_formal);
4373 tree gnu_formal = present_gnu_tree (gnat_formal)
4374 ? get_gnu_tree (gnat_formal) : NULL_TREE;
4375 tree gnu_formal_type = gnat_to_gnu_type (gnat_formal_type);
4376 const bool is_true_formal_parm
4377 = gnu_formal && TREE_CODE (gnu_formal) == PARM_DECL;
4378 const bool is_by_ref_formal_parm
4379 = is_true_formal_parm
4380 && (DECL_BY_REF_P (gnu_formal)
4381 || DECL_BY_COMPONENT_PTR_P (gnu_formal));
4382 /* In the Out or In Out case, we must suppress conversions that yield
4383 an lvalue but can nevertheless cause the creation of a temporary,
4384 because we need the real object in this case, either to pass its
4385 address if it's passed by reference or as target of the back copy
4386 done after the call if it uses the copy-in/copy-out mechanism.
4387 We do it in the In case too, except for an unchecked conversion
4388 to an elementary type or a constrained composite type because it
4389 alone can cause the actual to be misaligned and the addressability
4390 test is applied to the real object. */
4391 const bool suppress_type_conversion
4392 = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
4393 && (Ekind (gnat_formal) != E_In_Parameter
4394 || (Is_Composite_Type (Underlying_Type (gnat_formal_type))
4395 && !Is_Constrained (Underlying_Type (gnat_formal_type)))))
4396 || (Nkind (gnat_actual) == N_Type_Conversion
4397 && Is_Composite_Type (Underlying_Type (gnat_formal_type))));
4398 Node_Id gnat_name = suppress_type_conversion
4399 ? Expression (gnat_actual) : gnat_actual;
4400 tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
4401 tree gnu_actual;
4403 /* If it's possible we may need to use this expression twice, make sure
4404 that any side-effects are handled via SAVE_EXPRs; likewise if we need
4405 to force side-effects before the call. */
4406 if (Ekind (gnat_formal) != E_In_Parameter
4407 && !is_by_ref_formal_parm
4408 && TREE_CODE (gnu_name) != NULL_EXPR)
4410 tree init = NULL_TREE;
4411 gnu_name = gnat_stabilize_reference (gnu_name, true, &init);
4412 if (init)
4413 gnu_name
4414 = build_compound_expr (TREE_TYPE (gnu_name), init, gnu_name);
4417 /* If we are passing a non-addressable parameter by reference, pass the
4418 address of a copy. In the Out or In Out case, set up to copy back
4419 out after the call. */
4420 if (is_by_ref_formal_parm
4421 && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
4422 && !addressable_p (gnu_name, gnu_name_type))
4424 bool in_param = (Ekind (gnat_formal) == E_In_Parameter);
4425 tree gnu_orig = gnu_name, gnu_temp, gnu_stmt;
4427 /* Do not issue warnings for CONSTRUCTORs since this is not a copy
4428 but sort of an instantiation for them. */
4429 if (TREE_CODE (gnu_name) == CONSTRUCTOR)
4432 /* If the type is passed by reference, a copy is not allowed. */
4433 else if (TYPE_IS_BY_REFERENCE_P (gnu_formal_type))
4434 post_error ("misaligned actual cannot be passed by reference",
4435 gnat_actual);
4437 /* For users of Starlet we issue a warning because the interface
4438 apparently assumes that by-ref parameters outlive the procedure
4439 invocation. The code still will not work as intended, but we
4440 cannot do much better since low-level parts of the back-end
4441 would allocate temporaries at will because of the misalignment
4442 if we did not do so here. */
4443 else if (Is_Valued_Procedure (Entity (Name (gnat_node))))
4445 post_error
4446 ("?possible violation of implicit assumption", gnat_actual);
4447 post_error_ne
4448 ("?made by pragma Import_Valued_Procedure on &", gnat_actual,
4449 Entity (Name (gnat_node)));
4450 post_error_ne ("?because of misalignment of &", gnat_actual,
4451 gnat_formal);
4454 /* If the actual type of the object is already the nominal type,
4455 we have nothing to do, except if the size is self-referential
4456 in which case we'll remove the unpadding below. */
4457 if (TREE_TYPE (gnu_name) == gnu_name_type
4458 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_name_type)))
4461 /* Otherwise remove the unpadding from all the objects. */
4462 else if (TREE_CODE (gnu_name) == COMPONENT_REF
4463 && TYPE_IS_PADDING_P
4464 (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))
4465 gnu_orig = gnu_name = TREE_OPERAND (gnu_name, 0);
4467 /* Otherwise convert to the nominal type of the object if needed.
4468 There are several cases in which we need to make the temporary
4469 using this type instead of the actual type of the object when
4470 they are distinct, because the expectations of the callee would
4471 otherwise not be met:
4472 - if it's a justified modular type,
4473 - if the actual type is a smaller form of it,
4474 - if it's a smaller form of the actual type. */
4475 else if ((TREE_CODE (gnu_name_type) == RECORD_TYPE
4476 && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
4477 || smaller_form_type_p (TREE_TYPE (gnu_name),
4478 gnu_name_type)))
4479 || (INTEGRAL_TYPE_P (gnu_name_type)
4480 && smaller_form_type_p (gnu_name_type,
4481 TREE_TYPE (gnu_name))))
4482 gnu_name = convert (gnu_name_type, gnu_name);
4484 /* If this is an In Out or Out parameter and we're returning a value,
4485 we need to create a temporary for the return value because we must
4486 preserve it before copying back at the very end. */
4487 if (!in_param && returning_value && !gnu_retval)
4488 gnu_retval = create_temporary ("R", gnu_result_type);
4490 /* If we haven't pushed a binding level, push a new one. This will
4491 narrow the lifetime of the temporary we are about to make as much
4492 as possible. The drawback is that we'd need to create a temporary
4493 for the return value, if any (see comment before the loop). So do
4494 it only when this temporary was already created just above. */
4495 if (!pushed_binding_level && !(in_param && returning_value))
4497 start_stmt_group ();
4498 gnat_pushlevel ();
4499 pushed_binding_level = true;
4502 /* Create an explicit temporary holding the copy. */
4503 gnu_temp
4504 = create_init_temporary ("A", gnu_name, &gnu_stmt, gnat_actual);
4506 /* But initialize it on the fly like for an implicit temporary as
4507 we aren't necessarily having a statement list. */
4508 gnu_name = build_compound_expr (TREE_TYPE (gnu_name), gnu_stmt,
4509 gnu_temp);
4511 /* Set up to move the copy back to the original if needed. */
4512 if (!in_param)
4514 /* If the original is a COND_EXPR whose first arm isn't meant to
4515 be further used, just deal with the second arm. This is very
4516 likely the conditional expression built for a check. */
4517 if (TREE_CODE (gnu_orig) == COND_EXPR
4518 && TREE_CODE (TREE_OPERAND (gnu_orig, 1)) == COMPOUND_EXPR
4519 && integer_zerop
4520 (TREE_OPERAND (TREE_OPERAND (gnu_orig, 1), 1)))
4521 gnu_orig = TREE_OPERAND (gnu_orig, 2);
4523 gnu_stmt
4524 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_orig, gnu_temp);
4525 set_expr_location_from_node (gnu_stmt, gnat_node);
4527 append_to_statement_list (gnu_stmt, &gnu_after_list);
4531 /* Start from the real object and build the actual. */
4532 gnu_actual = gnu_name;
4534 /* If atomic access is required for an In or In Out actual parameter,
4535 build the atomic load. */
4536 if (is_true_formal_parm
4537 && !is_by_ref_formal_parm
4538 && Ekind (gnat_formal) != E_Out_Parameter
4539 && atomic_access_required_p (gnat_actual, &sync))
4540 gnu_actual = build_atomic_load (gnu_actual, sync);
4542 /* If this was a procedure call, we may not have removed any padding.
4543 So do it here for the part we will use as an input, if any. */
4544 if (Ekind (gnat_formal) != E_Out_Parameter
4545 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4546 gnu_actual
4547 = convert (get_unpadded_type (Etype (gnat_actual)), gnu_actual);
4549 /* Put back the conversion we suppressed above in the computation of the
4550 real object. And even if we didn't suppress any conversion there, we
4551 may have suppressed a conversion to the Etype of the actual earlier,
4552 since the parent is a procedure call, so put it back here. */
4553 if (suppress_type_conversion
4554 && Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4555 gnu_actual
4556 = unchecked_convert (gnat_to_gnu_type (Etype (gnat_actual)),
4557 gnu_actual, No_Truncation (gnat_actual));
4558 else
4559 gnu_actual
4560 = convert (gnat_to_gnu_type (Etype (gnat_actual)), gnu_actual);
4562 /* Make sure that the actual is in range of the formal's type. */
4563 if (Ekind (gnat_formal) != E_Out_Parameter
4564 && Do_Range_Check (gnat_actual))
4565 gnu_actual
4566 = emit_range_check (gnu_actual, gnat_formal_type, gnat_actual);
4568 /* Unless this is an In parameter, we must remove any justified modular
4569 building from GNU_NAME to get an lvalue. */
4570 if (Ekind (gnat_formal) != E_In_Parameter
4571 && TREE_CODE (gnu_name) == CONSTRUCTOR
4572 && TREE_CODE (TREE_TYPE (gnu_name)) == RECORD_TYPE
4573 && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (gnu_name)))
4574 gnu_name
4575 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_name))), gnu_name);
4577 /* First see if the parameter is passed by reference. */
4578 if (is_true_formal_parm && DECL_BY_REF_P (gnu_formal))
4580 if (Ekind (gnat_formal) != E_In_Parameter)
4582 /* In Out or Out parameters passed by reference don't use the
4583 copy-in/copy-out mechanism so the address of the real object
4584 must be passed to the function. */
4585 gnu_actual = gnu_name;
4587 /* If we have a padded type, be sure we've removed padding. */
4588 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4589 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
4590 gnu_actual);
4592 /* If we have the constructed subtype of an aliased object
4593 with an unconstrained nominal subtype, the type of the
4594 actual includes the template, although it is formally
4595 constrained. So we need to convert it back to the real
4596 constructed subtype to retrieve the constrained part
4597 and takes its address. */
4598 if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
4599 && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
4600 && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
4601 && Is_Array_Type (Underlying_Type (Etype (gnat_actual))))
4602 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
4603 gnu_actual);
4606 /* There is no need to convert the actual to the formal's type before
4607 taking its address. The only exception is for unconstrained array
4608 types because of the way we build fat pointers. */
4609 if (TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
4611 /* Put back a view conversion for In Out or Out parameters. */
4612 if (Ekind (gnat_formal) != E_In_Parameter)
4613 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
4614 gnu_actual);
4615 gnu_actual = convert (gnu_formal_type, gnu_actual);
4618 /* The symmetry of the paths to the type of an entity is broken here
4619 since arguments don't know that they will be passed by ref. */
4620 gnu_formal_type = TREE_TYPE (gnu_formal);
4621 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4624 /* Then see if the parameter is an array passed to a foreign convention
4625 subprogram. */
4626 else if (is_true_formal_parm && DECL_BY_COMPONENT_PTR_P (gnu_formal))
4628 gnu_formal_type = TREE_TYPE (gnu_formal);
4629 gnu_actual = maybe_implicit_deref (gnu_actual);
4630 gnu_actual = maybe_unconstrained_array (gnu_actual);
4632 if (TYPE_IS_PADDING_P (gnu_formal_type))
4634 gnu_formal_type = TREE_TYPE (TYPE_FIELDS (gnu_formal_type));
4635 gnu_actual = convert (gnu_formal_type, gnu_actual);
4638 /* Take the address of the object and convert to the proper pointer
4639 type. We'd like to actually compute the address of the beginning
4640 of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
4641 possibility that the ARRAY_REF might return a constant and we'd be
4642 getting the wrong address. Neither approach is exactly correct,
4643 but this is the most likely to work in all cases. */
4644 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4647 /* Otherwise the parameter is passed by copy. */
4648 else
4650 tree gnu_size;
4652 if (Ekind (gnat_formal) != E_In_Parameter)
4653 gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
4655 /* If we didn't create a PARM_DECL for the formal, this means that
4656 it is an Out parameter not passed by reference and that need not
4657 be copied in. In this case, the value of the actual need not be
4658 read. However, we still need to make sure that its side-effects
4659 are evaluated before the call, so we evaluate its address. */
4660 if (!is_true_formal_parm)
4662 if (TREE_SIDE_EFFECTS (gnu_name))
4664 tree addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_name);
4665 append_to_statement_list (addr, &gnu_stmt_list);
4667 continue;
4670 gnu_actual = convert (gnu_formal_type, gnu_actual);
4672 /* If this is 'Null_Parameter, pass a zero even though we are
4673 dereferencing it. */
4674 if (TREE_CODE (gnu_actual) == INDIRECT_REF
4675 && TREE_PRIVATE (gnu_actual)
4676 && (gnu_size = TYPE_SIZE (TREE_TYPE (gnu_actual)))
4677 && TREE_CODE (gnu_size) == INTEGER_CST
4678 && compare_tree_int (gnu_size, BITS_PER_WORD) <= 0)
4679 gnu_actual
4680 = unchecked_convert (DECL_ARG_TYPE (gnu_formal),
4681 convert (gnat_type_for_size
4682 (TREE_INT_CST_LOW (gnu_size), 1),
4683 integer_zero_node),
4684 false);
4685 else
4686 gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
4689 vec_safe_push (gnu_actual_vec, gnu_actual);
4692 gnu_call
4693 = build_call_vec (gnu_result_type, gnu_subprog_addr, gnu_actual_vec);
4694 set_expr_location_from_node (gnu_call, gnat_node);
4696 /* If we have created a temporary for the return value, initialize it. */
4697 if (gnu_retval)
4699 tree gnu_stmt
4700 = build_binary_op (INIT_EXPR, NULL_TREE, gnu_retval, gnu_call);
4701 set_expr_location_from_node (gnu_stmt, gnat_node);
4702 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
4703 gnu_call = gnu_retval;
4706 /* If this is a subprogram with copy-in/copy-out parameters, we need to
4707 unpack the valued returned from the function into the In Out or Out
4708 parameters. We deal with the function return (if this is an Ada
4709 function) below. */
4710 if (TYPE_CI_CO_LIST (gnu_subprog_type))
4712 /* List of FIELD_DECLs associated with the PARM_DECLs of the copy-in/
4713 copy-out parameters. */
4714 tree gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
4715 const int length = list_length (gnu_cico_list);
4717 /* The call sequence must contain one and only one call, even though the
4718 function is pure. Save the result into a temporary if needed. */
4719 if (length > 1)
4721 if (!gnu_retval)
4723 tree gnu_stmt;
4724 /* If we haven't pushed a binding level, push a new one. This
4725 will narrow the lifetime of the temporary we are about to
4726 make as much as possible. */
4727 if (!pushed_binding_level)
4729 start_stmt_group ();
4730 gnat_pushlevel ();
4731 pushed_binding_level = true;
4733 gnu_call
4734 = create_init_temporary ("P", gnu_call, &gnu_stmt, gnat_node);
4735 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
4738 gnu_name_list = nreverse (gnu_name_list);
4741 /* The first entry is for the actual return value if this is a
4742 function, so skip it. */
4743 if (function_call)
4744 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4746 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
4747 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
4748 else
4749 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
4751 for (gnat_actual = First_Actual (gnat_node);
4752 Present (gnat_actual);
4753 gnat_formal = Next_Formal_With_Extras (gnat_formal),
4754 gnat_actual = Next_Actual (gnat_actual))
4755 /* If we are dealing with a copy-in/copy-out parameter, we must
4756 retrieve its value from the record returned in the call. */
4757 if (!(present_gnu_tree (gnat_formal)
4758 && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
4759 && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
4760 || DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))))
4761 && Ekind (gnat_formal) != E_In_Parameter)
4763 /* Get the value to assign to this Out or In Out parameter. It is
4764 either the result of the function if there is only a single such
4765 parameter or the appropriate field from the record returned. */
4766 tree gnu_result
4767 = length == 1
4768 ? gnu_call
4769 : build_component_ref (gnu_call, TREE_PURPOSE (gnu_cico_list),
4770 false);
4772 /* If the actual is a conversion, get the inner expression, which
4773 will be the real destination, and convert the result to the
4774 type of the actual parameter. */
4775 tree gnu_actual
4776 = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
4778 /* If the result is a padded type, remove the padding. */
4779 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
4780 gnu_result
4781 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
4782 gnu_result);
4784 /* If the actual is a type conversion, the real target object is
4785 denoted by the inner Expression and we need to convert the
4786 result to the associated type.
4787 We also need to convert our gnu assignment target to this type
4788 if the corresponding GNU_NAME was constructed from the GNAT
4789 conversion node and not from the inner Expression. */
4790 if (Nkind (gnat_actual) == N_Type_Conversion)
4792 gnu_result
4793 = convert_with_check
4794 (Etype (Expression (gnat_actual)), gnu_result,
4795 Do_Overflow_Check (gnat_actual),
4796 Do_Range_Check (Expression (gnat_actual)),
4797 Float_Truncate (gnat_actual), gnat_actual);
4799 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
4800 gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
4803 /* Unchecked conversions as actuals for Out parameters are not
4804 allowed in user code because they are not variables, but do
4805 occur in front-end expansions. The associated GNU_NAME is
4806 always obtained from the inner expression in such cases. */
4807 else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4808 gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
4809 gnu_result,
4810 No_Truncation (gnat_actual));
4811 else
4813 if (Do_Range_Check (gnat_actual))
4814 gnu_result
4815 = emit_range_check (gnu_result, Etype (gnat_actual),
4816 gnat_actual);
4818 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
4819 && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
4820 gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
4823 /* If an outer atomic access is required for an actual parameter,
4824 build the load-modify-store sequence. */
4825 if (outer_atomic_access_required_p (gnat_actual))
4826 gnu_result
4827 = build_load_modify_store (gnu_actual, gnu_result, gnat_node);
4829 /* Or else, if simple atomic access is required, build the atomic
4830 store. */
4831 else if (atomic_access_required_p (gnat_actual, &sync))
4832 gnu_result = build_atomic_store (gnu_actual, gnu_result, sync);
4834 /* Otherwise build a regular assignment. */
4835 else
4836 gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
4837 gnu_actual, gnu_result);
4839 if (EXPR_P (gnu_result))
4840 set_expr_location_from_node (gnu_result, gnat_node);
4841 append_to_statement_list (gnu_result, &gnu_stmt_list);
4842 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4843 gnu_name_list = TREE_CHAIN (gnu_name_list);
4847 /* If this is a function call, the result is the call expression unless a
4848 target is specified, in which case we copy the result into the target
4849 and return the assignment statement. */
4850 if (function_call)
4852 /* If this is a function with copy-in/copy-out parameters, extract the
4853 return value from it and update the return type. */
4854 if (TYPE_CI_CO_LIST (gnu_subprog_type))
4856 tree gnu_elmt = TYPE_CI_CO_LIST (gnu_subprog_type);
4857 gnu_call
4858 = build_component_ref (gnu_call, TREE_PURPOSE (gnu_elmt), false);
4859 gnu_result_type = TREE_TYPE (gnu_call);
4862 /* If the function returns an unconstrained array or by direct reference,
4863 we have to dereference the pointer. */
4864 if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type)
4865 || TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type))
4866 gnu_call = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_call);
4868 if (gnu_target)
4870 Node_Id gnat_parent = Parent (gnat_node);
4871 enum tree_code op_code;
4873 /* If range check is needed, emit code to generate it. */
4874 if (Do_Range_Check (gnat_node))
4875 gnu_call
4876 = emit_range_check (gnu_call, Etype (Name (gnat_parent)),
4877 gnat_parent);
4879 /* ??? If the return type has variable size, then force the return
4880 slot optimization as we would not be able to create a temporary.
4881 That's what has been done historically. */
4882 if (return_type_with_variable_size_p (gnu_result_type))
4883 op_code = INIT_EXPR;
4884 else
4885 op_code = MODIFY_EXPR;
4887 /* Use the required method to move the result to the target. */
4888 if (outer_atomic_access)
4889 gnu_call
4890 = build_load_modify_store (gnu_target, gnu_call, gnat_node);
4891 else if (atomic_access)
4892 gnu_call = build_atomic_store (gnu_target, gnu_call, atomic_sync);
4893 else
4894 gnu_call
4895 = build_binary_op (op_code, NULL_TREE, gnu_target, gnu_call);
4897 if (EXPR_P (gnu_call))
4898 set_expr_location_from_node (gnu_call, gnat_parent);
4899 append_to_statement_list (gnu_call, &gnu_stmt_list);
4901 else
4902 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
4905 /* Otherwise, if this is a procedure call statement without copy-in/copy-out
4906 parameters, the result is just the call statement. */
4907 else if (!TYPE_CI_CO_LIST (gnu_subprog_type))
4908 append_to_statement_list (gnu_call, &gnu_stmt_list);
4910 /* Finally, add the copy back statements, if any. */
4911 append_to_statement_list (gnu_after_list, &gnu_stmt_list);
4913 if (went_into_elab_proc)
4914 current_function_decl = NULL_TREE;
4916 /* If we have pushed a binding level, pop it and finish up the enclosing
4917 statement group. */
4918 if (pushed_binding_level)
4920 add_stmt (gnu_stmt_list);
4921 gnat_poplevel ();
4922 gnu_result = end_stmt_group ();
4925 /* Otherwise, retrieve the statement list, if any. */
4926 else if (gnu_stmt_list)
4927 gnu_result = gnu_stmt_list;
4929 /* Otherwise, just return the call expression. */
4930 else
4931 return gnu_call;
4933 /* If we nevertheless need a value, make a COMPOUND_EXPR to return it.
4934 But first simplify if we have only one statement in the list. */
4935 if (returning_value)
4937 tree first = expr_first (gnu_result), last = expr_last (gnu_result);
4938 if (first == last)
4939 gnu_result = first;
4940 gnu_result
4941 = build_compound_expr (TREE_TYPE (gnu_call), gnu_result, gnu_call);
4944 return gnu_result;
4947 /* Subroutine of gnat_to_gnu to translate gnat_node, an
4948 N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned. */
4950 static tree
4951 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
4953 tree gnu_jmpsave_decl = NULL_TREE;
4954 tree gnu_jmpbuf_decl = NULL_TREE;
4955 /* If just annotating, ignore all EH and cleanups. */
4956 bool gcc_eh = (!type_annotate_only
4957 && Present (Exception_Handlers (gnat_node))
4958 && Back_End_Exceptions ());
4959 bool fe_sjlj
4960 = (!type_annotate_only && Present (Exception_Handlers (gnat_node))
4961 && Exception_Mechanism == Front_End_SJLJ);
4962 bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
4963 bool binding_for_block = (at_end || gcc_eh || fe_sjlj);
4964 tree gnu_inner_block; /* The statement(s) for the block itself. */
4965 tree gnu_result;
4966 tree gnu_expr;
4967 Node_Id gnat_temp;
4968 /* Node providing the sloc for the cleanup actions. */
4969 Node_Id gnat_cleanup_loc_node = (Present (End_Label (gnat_node)) ?
4970 End_Label (gnat_node) :
4971 gnat_node);
4973 /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes
4974 and we have our own SJLJ mechanism. To call the GCC mechanism, we call
4975 add_cleanup, and when we leave the binding, end_stmt_group will create
4976 the TRY_FINALLY_EXPR.
4978 ??? The region level calls down there have been specifically put in place
4979 for a ZCX context and currently the order in which things are emitted
4980 (region/handlers) is different from the SJLJ case. Instead of putting
4981 other calls with different conditions at other places for the SJLJ case,
4982 it seems cleaner to reorder things for the SJLJ case and generalize the
4983 condition to make it not ZCX specific.
4985 If there are any exceptions or cleanup processing involved, we need an
4986 outer statement group (for Fe_Sjlj) and binding level. */
4987 if (binding_for_block)
4989 start_stmt_group ();
4990 gnat_pushlevel ();
4993 /* If using fe_sjlj, make the variables for the setjmp buffer and save
4994 area for address of previous buffer. Do this first since we need to have
4995 the setjmp buf known for any decls in this block. */
4996 if (fe_sjlj)
4998 gnu_jmpsave_decl
4999 = create_var_decl (get_identifier ("JMPBUF_SAVE"), NULL_TREE,
5000 jmpbuf_ptr_type,
5001 build_call_n_expr (get_jmpbuf_decl, 0),
5002 false, false, false, false, false, true, false,
5003 NULL, gnat_node);
5005 /* The __builtin_setjmp receivers will immediately reinstall it. Now
5006 because of the unstructured form of EH used by fe_sjlj, there
5007 might be forward edges going to __builtin_setjmp receivers on which
5008 it is uninitialized, although they will never be actually taken. */
5009 TREE_NO_WARNING (gnu_jmpsave_decl) = 1;
5010 gnu_jmpbuf_decl
5011 = create_var_decl (get_identifier ("JMP_BUF"), NULL_TREE,
5012 jmpbuf_type,
5013 NULL_TREE,
5014 false, false, false, false, false, true, false,
5015 NULL, gnat_node);
5017 set_block_jmpbuf_decl (gnu_jmpbuf_decl);
5019 /* When we exit this block, restore the saved value. */
5020 add_cleanup (build_call_n_expr (set_jmpbuf_decl, 1, gnu_jmpsave_decl),
5021 gnat_cleanup_loc_node);
5024 /* If we are to call a function when exiting this block, add a cleanup
5025 to the binding level we made above. Note that add_cleanup is FIFO
5026 so we must register this cleanup after the EH cleanup just above. */
5027 if (at_end)
5029 tree proc_decl = gnat_to_gnu (At_End_Proc (gnat_node));
5030 /* When not optimizing, disable inlining of finalizers as this can
5031 create a more complex CFG in the parent function. */
5032 if (!optimize)
5033 DECL_DECLARED_INLINE_P (proc_decl) = 0;
5034 add_cleanup (build_call_n_expr (proc_decl, 0), gnat_cleanup_loc_node);
5037 /* Now build the tree for the declarations and statements inside this block.
5038 If this is SJLJ, set our jmp_buf as the current buffer. */
5039 start_stmt_group ();
5041 if (fe_sjlj)
5043 gnu_expr = build_call_n_expr (set_jmpbuf_decl, 1,
5044 build_unary_op (ADDR_EXPR, NULL_TREE,
5045 gnu_jmpbuf_decl));
5046 set_expr_location_from_node (gnu_expr, gnat_node);
5047 add_stmt (gnu_expr);
5050 if (Present (First_Real_Statement (gnat_node)))
5051 process_decls (Statements (gnat_node), Empty,
5052 First_Real_Statement (gnat_node), true, true);
5054 /* Generate code for each statement in the block. */
5055 for (gnat_temp = (Present (First_Real_Statement (gnat_node))
5056 ? First_Real_Statement (gnat_node)
5057 : First (Statements (gnat_node)));
5058 Present (gnat_temp); gnat_temp = Next (gnat_temp))
5059 add_stmt (gnat_to_gnu (gnat_temp));
5060 gnu_inner_block = end_stmt_group ();
5062 /* Now generate code for the two exception models, if either is relevant for
5063 this block. */
5064 if (fe_sjlj)
5066 tree *gnu_else_ptr = 0;
5067 tree gnu_handler;
5069 /* Make a binding level for the exception handling declarations and code
5070 and set up gnu_except_ptr_stack for the handlers to use. */
5071 start_stmt_group ();
5072 gnat_pushlevel ();
5074 vec_safe_push (gnu_except_ptr_stack,
5075 create_var_decl (get_identifier ("EXCEPT_PTR"), NULL_TREE,
5076 build_pointer_type (except_type_node),
5077 build_call_n_expr (get_excptr_decl, 0),
5078 false, false, false, false, false,
5079 true, false, NULL, gnat_node));
5081 /* Generate code for each handler. The N_Exception_Handler case does the
5082 real work and returns a COND_EXPR for each handler, which we chain
5083 together here. */
5084 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
5085 Present (gnat_temp); gnat_temp = Next_Non_Pragma (gnat_temp))
5087 gnu_expr = gnat_to_gnu (gnat_temp);
5089 /* If this is the first one, set it as the outer one. Otherwise,
5090 point the "else" part of the previous handler to us. Then point
5091 to our "else" part. */
5092 if (!gnu_else_ptr)
5093 add_stmt (gnu_expr);
5094 else
5095 *gnu_else_ptr = gnu_expr;
5097 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
5100 /* If none of the exception handlers did anything, re-raise but do not
5101 defer abortion. */
5102 gnu_expr = build_call_n_expr (raise_nodefer_decl, 1,
5103 gnu_except_ptr_stack->last ());
5104 set_expr_location_from_node
5105 (gnu_expr,
5106 Present (End_Label (gnat_node)) ? End_Label (gnat_node) : gnat_node);
5108 if (gnu_else_ptr)
5109 *gnu_else_ptr = gnu_expr;
5110 else
5111 add_stmt (gnu_expr);
5113 /* End the binding level dedicated to the exception handlers and get the
5114 whole statement group. */
5115 gnu_except_ptr_stack->pop ();
5116 gnat_poplevel ();
5117 gnu_handler = end_stmt_group ();
5119 /* If the setjmp returns 1, we restore our incoming longjmp value and
5120 then check the handlers. */
5121 start_stmt_group ();
5122 add_stmt_with_node (build_call_n_expr (set_jmpbuf_decl, 1,
5123 gnu_jmpsave_decl),
5124 gnat_node);
5125 add_stmt (gnu_handler);
5126 gnu_handler = end_stmt_group ();
5128 /* This block is now "if (setjmp) ... <handlers> else <block>". */
5129 gnu_result = build3 (COND_EXPR, void_type_node,
5130 (build_call_n_expr
5131 (setjmp_decl, 1,
5132 build_unary_op (ADDR_EXPR, NULL_TREE,
5133 gnu_jmpbuf_decl))),
5134 gnu_handler, gnu_inner_block);
5136 else if (gcc_eh)
5138 tree gnu_handlers;
5139 location_t locus;
5141 /* First make a block containing the handlers. */
5142 start_stmt_group ();
5143 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
5144 Present (gnat_temp);
5145 gnat_temp = Next_Non_Pragma (gnat_temp))
5146 add_stmt (gnat_to_gnu (gnat_temp));
5147 gnu_handlers = end_stmt_group ();
5149 /* Now make the TRY_CATCH_EXPR for the block. */
5150 gnu_result = build2 (TRY_CATCH_EXPR, void_type_node,
5151 gnu_inner_block, gnu_handlers);
5152 /* Set a location. We need to find a unique location for the dispatching
5153 code, otherwise we can get coverage or debugging issues. Try with
5154 the location of the end label. */
5155 if (Present (End_Label (gnat_node))
5156 && Sloc_to_locus (Sloc (End_Label (gnat_node)), &locus))
5157 SET_EXPR_LOCATION (gnu_result, locus);
5158 else
5159 /* Clear column information so that the exception handler of an
5160 implicit transient block does not incorrectly inherit the slocs
5161 of a decision, which would otherwise confuse control flow based
5162 coverage analysis tools. */
5163 set_expr_location_from_node (gnu_result, gnat_node, true);
5165 else
5166 gnu_result = gnu_inner_block;
5168 /* Now close our outer block, if we had to make one. */
5169 if (binding_for_block)
5171 add_stmt (gnu_result);
5172 gnat_poplevel ();
5173 gnu_result = end_stmt_group ();
5176 return gnu_result;
5179 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
5180 to a GCC tree, which is returned. This is the variant for front-end sjlj
5181 exception handling. */
5183 static tree
5184 Exception_Handler_to_gnu_fe_sjlj (Node_Id gnat_node)
5186 /* Unless this is "Others" or the special "Non-Ada" exception for Ada, make
5187 an "if" statement to select the proper exceptions. For "Others", exclude
5188 exceptions where Handled_By_Others is nonzero unless the All_Others flag
5189 is set. For "Non-ada", accept an exception if "Lang" is 'V'. */
5190 tree gnu_choice = boolean_false_node;
5191 tree gnu_body = build_stmt_group (Statements (gnat_node), false);
5192 Node_Id gnat_temp;
5194 for (gnat_temp = First (Exception_Choices (gnat_node));
5195 gnat_temp; gnat_temp = Next (gnat_temp))
5197 tree this_choice;
5199 if (Nkind (gnat_temp) == N_Others_Choice)
5201 if (All_Others (gnat_temp))
5202 this_choice = boolean_true_node;
5203 else
5204 this_choice
5205 = build_binary_op
5206 (EQ_EXPR, boolean_type_node,
5207 convert
5208 (integer_type_node,
5209 build_component_ref
5210 (build_unary_op
5211 (INDIRECT_REF, NULL_TREE,
5212 gnu_except_ptr_stack->last ()),
5213 not_handled_by_others_decl,
5214 false)),
5215 integer_zero_node);
5218 else if (Nkind (gnat_temp) == N_Identifier
5219 || Nkind (gnat_temp) == N_Expanded_Name)
5221 Entity_Id gnat_ex_id = Entity (gnat_temp);
5222 tree gnu_expr;
5224 /* Exception may be a renaming. Recover original exception which is
5225 the one elaborated and registered. */
5226 if (Present (Renamed_Object (gnat_ex_id)))
5227 gnat_ex_id = Renamed_Object (gnat_ex_id);
5229 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
5231 this_choice
5232 = build_binary_op
5233 (EQ_EXPR, boolean_type_node,
5234 gnu_except_ptr_stack->last (),
5235 convert (TREE_TYPE (gnu_except_ptr_stack->last ()),
5236 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr)));
5238 else
5239 gcc_unreachable ();
5241 gnu_choice = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
5242 gnu_choice, this_choice);
5245 return build3 (COND_EXPR, void_type_node, gnu_choice, gnu_body, NULL_TREE);
5248 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
5249 to a GCC tree, which is returned. This is the variant for GCC exception
5250 schemes. */
5252 static tree
5253 Exception_Handler_to_gnu_gcc (Node_Id gnat_node)
5255 tree gnu_etypes_list = NULL_TREE;
5256 tree gnu_current_exc_ptr, prev_gnu_incoming_exc_ptr;
5257 Node_Id gnat_temp;
5259 /* We build a TREE_LIST of nodes representing what exception types this
5260 handler can catch, with special cases for others and all others cases.
5262 Each exception type is actually identified by a pointer to the exception
5263 id, or to a dummy object for "others" and "all others". */
5264 for (gnat_temp = First (Exception_Choices (gnat_node));
5265 gnat_temp; gnat_temp = Next (gnat_temp))
5267 tree gnu_expr, gnu_etype;
5269 if (Nkind (gnat_temp) == N_Others_Choice)
5271 gnu_expr = All_Others (gnat_temp) ? all_others_decl : others_decl;
5272 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
5274 else if (Nkind (gnat_temp) == N_Identifier
5275 || Nkind (gnat_temp) == N_Expanded_Name)
5277 Entity_Id gnat_ex_id = Entity (gnat_temp);
5279 /* Exception may be a renaming. Recover original exception which is
5280 the one elaborated and registered. */
5281 if (Present (Renamed_Object (gnat_ex_id)))
5282 gnat_ex_id = Renamed_Object (gnat_ex_id);
5284 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
5285 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
5287 else
5288 gcc_unreachable ();
5290 /* The GCC interface expects NULL to be passed for catch all handlers, so
5291 it would be quite tempting to set gnu_etypes_list to NULL if gnu_etype
5292 is integer_zero_node. It would not work, however, because GCC's
5293 notion of "catch all" is stronger than our notion of "others". Until
5294 we correctly use the cleanup interface as well, doing that would
5295 prevent the "all others" handlers from being seen, because nothing
5296 can be caught beyond a catch all from GCC's point of view. */
5297 gnu_etypes_list = tree_cons (NULL_TREE, gnu_etype, gnu_etypes_list);
5300 start_stmt_group ();
5301 gnat_pushlevel ();
5303 /* Expand a call to the begin_handler hook at the beginning of the handler,
5304 and arrange for a call to the end_handler hook to occur on every possible
5305 exit path.
5307 The hooks expect a pointer to the low level occurrence. This is required
5308 for our stack management scheme because a raise inside the handler pushes
5309 a new occurrence on top of the stack, which means that this top does not
5310 necessarily match the occurrence this handler was dealing with.
5312 __builtin_eh_pointer references the exception occurrence being
5313 propagated. Upon handler entry, this is the exception for which the
5314 handler is triggered. This might not be the case upon handler exit,
5315 however, as we might have a new occurrence propagated by the handler's
5316 body, and the end_handler hook called as a cleanup in this context.
5318 We use a local variable to retrieve the incoming value at handler entry
5319 time, and reuse it to feed the end_handler hook's argument at exit. */
5321 gnu_current_exc_ptr
5322 = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
5323 1, integer_zero_node);
5324 prev_gnu_incoming_exc_ptr = gnu_incoming_exc_ptr;
5325 gnu_incoming_exc_ptr
5326 = create_var_decl (get_identifier ("EXPTR"), NULL_TREE,
5327 ptr_type_node, gnu_current_exc_ptr,
5328 false, false, false, false, false, true, true,
5329 NULL, gnat_node);
5331 add_stmt_with_node (build_call_n_expr (begin_handler_decl, 1,
5332 gnu_incoming_exc_ptr),
5333 gnat_node);
5335 /* Declare and initialize the choice parameter, if present. */
5336 if (Present (Choice_Parameter (gnat_node)))
5338 tree gnu_param
5339 = gnat_to_gnu_entity (Choice_Parameter (gnat_node), NULL_TREE, 1);
5341 add_stmt (build_call_n_expr
5342 (set_exception_parameter_decl, 2,
5343 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_param),
5344 gnu_incoming_exc_ptr));
5347 /* We don't have an End_Label at hand to set the location of the cleanup
5348 actions, so we use that of the exception handler itself instead. */
5349 add_cleanup (build_call_n_expr (end_handler_decl, 1, gnu_incoming_exc_ptr),
5350 gnat_node);
5351 add_stmt_list (Statements (gnat_node));
5352 gnat_poplevel ();
5354 gnu_incoming_exc_ptr = prev_gnu_incoming_exc_ptr;
5356 return
5357 build2 (CATCH_EXPR, void_type_node, gnu_etypes_list, end_stmt_group ());
5360 /* Subroutine of gnat_to_gnu to generate code for an N_Compilation unit. */
5362 static void
5363 Compilation_Unit_to_gnu (Node_Id gnat_node)
5365 const Node_Id gnat_unit = Unit (gnat_node);
5366 const bool body_p = (Nkind (gnat_unit) == N_Package_Body
5367 || Nkind (gnat_unit) == N_Subprogram_Body);
5368 const Entity_Id gnat_unit_entity = Defining_Entity (gnat_unit);
5369 Entity_Id gnat_entity;
5370 Node_Id gnat_pragma;
5371 /* Make the decl for the elaboration procedure. */
5372 tree gnu_elab_proc_decl
5373 = create_subprog_decl
5374 (create_concat_name (gnat_unit_entity, body_p ? "elabb" : "elabs"),
5375 NULL_TREE, void_ftype, NULL_TREE,
5376 is_disabled, false, true, false, false, true, true,
5377 NULL, gnat_unit);
5378 struct elab_info *info;
5380 vec_safe_push (gnu_elab_proc_stack, gnu_elab_proc_decl);
5381 DECL_ELABORATION_PROC_P (gnu_elab_proc_decl) = 1;
5383 /* Initialize the information structure for the function. */
5384 allocate_struct_function (gnu_elab_proc_decl, false);
5385 set_cfun (NULL);
5387 current_function_decl = NULL_TREE;
5389 start_stmt_group ();
5390 gnat_pushlevel ();
5392 /* For a body, first process the spec if there is one. */
5393 if (Nkind (gnat_unit) == N_Package_Body
5394 || (Nkind (gnat_unit) == N_Subprogram_Body && !Acts_As_Spec (gnat_node)))
5395 add_stmt (gnat_to_gnu (Library_Unit (gnat_node)));
5397 if (type_annotate_only && gnat_node == Cunit (Main_Unit))
5399 elaborate_all_entities (gnat_node);
5401 if (Nkind (gnat_unit) == N_Subprogram_Declaration
5402 || Nkind (gnat_unit) == N_Generic_Package_Declaration
5403 || Nkind (gnat_unit) == N_Generic_Subprogram_Declaration)
5404 return;
5407 /* Then process any pragmas and declarations preceding the unit. */
5408 for (gnat_pragma = First (Context_Items (gnat_node));
5409 Present (gnat_pragma);
5410 gnat_pragma = Next (gnat_pragma))
5411 if (Nkind (gnat_pragma) == N_Pragma)
5412 add_stmt (gnat_to_gnu (gnat_pragma));
5413 process_decls (Declarations (Aux_Decls_Node (gnat_node)), Empty, Empty,
5414 true, true);
5416 /* Process the unit itself. */
5417 add_stmt (gnat_to_gnu (gnat_unit));
5419 /* Generate code for all the inlined subprograms. */
5420 for (gnat_entity = First_Inlined_Subprogram (gnat_node);
5421 Present (gnat_entity);
5422 gnat_entity = Next_Inlined_Subprogram (gnat_entity))
5424 Node_Id gnat_body;
5426 /* Without optimization, process only the required subprograms. */
5427 if (!optimize && !Has_Pragma_Inline_Always (gnat_entity))
5428 continue;
5430 gnat_body = Parent (Declaration_Node (gnat_entity));
5431 if (Nkind (gnat_body) != N_Subprogram_Body)
5433 /* ??? This happens when only the spec of a package is provided. */
5434 if (No (Corresponding_Body (gnat_body)))
5435 continue;
5437 gnat_body
5438 = Parent (Declaration_Node (Corresponding_Body (gnat_body)));
5441 /* Define the entity first so we set DECL_EXTERNAL. */
5442 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5443 add_stmt (gnat_to_gnu (gnat_body));
5446 /* Process any pragmas and actions following the unit. */
5447 add_stmt_list (Pragmas_After (Aux_Decls_Node (gnat_node)));
5448 add_stmt_list (Actions (Aux_Decls_Node (gnat_node)));
5449 finalize_from_limited_with ();
5451 /* Save away what we've made so far and finish it up. */
5452 set_current_block_context (gnu_elab_proc_decl);
5453 gnat_poplevel ();
5454 DECL_SAVED_TREE (gnu_elab_proc_decl) = end_stmt_group ();
5455 set_end_locus_from_node (gnu_elab_proc_decl, gnat_unit);
5456 gnu_elab_proc_stack->pop ();
5458 /* Record this potential elaboration procedure for later processing. */
5459 info = ggc_alloc<elab_info> ();
5460 info->next = elab_info_list;
5461 info->elab_proc = gnu_elab_proc_decl;
5462 info->gnat_node = gnat_node;
5463 elab_info_list = info;
5465 /* Force the processing for all nodes that remain in the queue. */
5466 process_deferred_decl_context (true);
5469 /* Mark COND, a boolean expression, as predicating a call to a noreturn
5470 function, i.e. predict that it is very likely false, and return it.
5472 The compiler will automatically predict the last edge leading to a call
5473 to a noreturn function as very unlikely taken. This function makes it
5474 possible to expand the prediction to predecessors in case the condition
5475 is made up of several short-circuit operators. */
5477 static tree
5478 build_noreturn_cond (tree cond)
5480 tree fn = builtin_decl_explicit (BUILT_IN_EXPECT);
5481 tree arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
5482 tree pred_type = TREE_VALUE (arg_types);
5483 tree expected_type = TREE_VALUE (TREE_CHAIN (arg_types));
5485 tree t = build_call_expr (fn, 3,
5486 fold_convert (pred_type, cond),
5487 build_int_cst (expected_type, 0),
5488 build_int_cst (integer_type_node,
5489 PRED_NORETURN));
5491 return build1 (NOP_EXPR, boolean_type_node, t);
5494 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Raise_xxx_Error,
5495 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to where
5496 we should place the result type. LABEL_P is true if there is a label to
5497 branch to for the exception. */
5499 static tree
5500 Raise_Error_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
5502 const Node_Kind kind = Nkind (gnat_node);
5503 const int reason = UI_To_Int (Reason (gnat_node));
5504 const Node_Id gnat_cond = Condition (gnat_node);
5505 const bool with_extra_info
5506 = Exception_Extra_Info
5507 && !No_Exception_Handlers_Set ()
5508 && !get_exception_label (kind);
5509 tree gnu_result = NULL_TREE, gnu_cond = NULL_TREE;
5511 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
5513 switch (reason)
5515 case CE_Access_Check_Failed:
5516 if (with_extra_info)
5517 gnu_result = build_call_raise_column (reason, gnat_node);
5518 break;
5520 case CE_Index_Check_Failed:
5521 case CE_Range_Check_Failed:
5522 case CE_Invalid_Data:
5523 if (Present (gnat_cond) && Nkind (gnat_cond) == N_Op_Not)
5525 Node_Id gnat_range, gnat_index, gnat_type;
5526 tree gnu_index, gnu_low_bound, gnu_high_bound, disp;
5527 bool neg_p;
5528 struct loop_info_d *loop;
5530 switch (Nkind (Right_Opnd (gnat_cond)))
5532 case N_In:
5533 gnat_range = Right_Opnd (Right_Opnd (gnat_cond));
5534 gcc_assert (Nkind (gnat_range) == N_Range);
5535 gnu_low_bound = gnat_to_gnu (Low_Bound (gnat_range));
5536 gnu_high_bound = gnat_to_gnu (High_Bound (gnat_range));
5537 break;
5539 case N_Op_Ge:
5540 gnu_low_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
5541 gnu_high_bound = NULL_TREE;
5542 break;
5544 case N_Op_Le:
5545 gnu_low_bound = NULL_TREE;
5546 gnu_high_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
5547 break;
5549 default:
5550 goto common;
5553 gnat_index = Left_Opnd (Right_Opnd (gnat_cond));
5554 gnat_type = Etype (gnat_index);
5555 gnu_index = gnat_to_gnu (gnat_index);
5557 if (with_extra_info
5558 && gnu_low_bound
5559 && gnu_high_bound
5560 && Known_Esize (gnat_type)
5561 && UI_To_Int (Esize (gnat_type)) <= 32)
5562 gnu_result
5563 = build_call_raise_range (reason, gnat_node, gnu_index,
5564 gnu_low_bound, gnu_high_bound);
5566 /* If optimization is enabled and we are inside a loop, we try to
5567 compute invariant conditions for checks applied to the iteration
5568 variable, i.e. conditions that are independent of the variable
5569 and necessary in order for the checks to fail in the course of
5570 some iteration. If we succeed, we consider an alternative:
5572 1. If loop unswitching is enabled, we prepend these conditions
5573 to the original conditions of the checks. This will make it
5574 possible for the loop unswitching pass to replace the loop
5575 with two loops, one of which has the checks eliminated and
5576 the other has the original checks reinstated, and a prologue
5577 implementing a run-time selection. The former loop will be
5578 for example suitable for vectorization.
5580 2. Otherwise, we instead append the conditions to the original
5581 conditions of the checks. At worse, if the conditions cannot
5582 be evaluated at compile time, they will be evaluated as true
5583 at run time only when the checks have already failed, thus
5584 contributing negatively only to the size of the executable.
5585 But the hope is that these invariant conditions be evaluated
5586 at compile time to false, thus taking away the entire checks
5587 with them. */
5588 if (optimize
5589 && inside_loop_p ()
5590 && (!gnu_low_bound
5591 || (gnu_low_bound = gnat_invariant_expr (gnu_low_bound)))
5592 && (!gnu_high_bound
5593 || (gnu_high_bound = gnat_invariant_expr (gnu_high_bound)))
5594 && (loop = find_loop_for (gnu_index, &disp, &neg_p)))
5596 struct range_check_info_d *rci = ggc_alloc<range_check_info_d> ();
5597 rci->low_bound = gnu_low_bound;
5598 rci->high_bound = gnu_high_bound;
5599 rci->disp = disp;
5600 rci->neg_p = neg_p;
5601 rci->type = get_unpadded_type (gnat_type);
5602 rci->inserted_cond
5603 = build1 (SAVE_EXPR, boolean_type_node, boolean_true_node);
5604 vec_safe_push (loop->checks, rci);
5605 loop->has_checks = true;
5606 gnu_cond = build_noreturn_cond (gnat_to_gnu (gnat_cond));
5607 if (flag_unswitch_loops)
5608 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
5609 boolean_type_node,
5610 rci->inserted_cond,
5611 gnu_cond);
5612 else
5613 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
5614 boolean_type_node,
5615 gnu_cond,
5616 rci->inserted_cond);
5619 /* Or else, if aggressive loop optimizations are enabled, we just
5620 record that there are checks applied to iteration variables. */
5621 else if (optimize
5622 && flag_aggressive_loop_optimizations
5623 && inside_loop_p ()
5624 && (loop = find_loop_for (gnu_index)))
5625 loop->has_checks = true;
5627 break;
5629 default:
5630 break;
5633 common:
5634 if (!gnu_result)
5635 gnu_result = build_call_raise (reason, gnat_node, kind);
5636 set_expr_location_from_node (gnu_result, gnat_node);
5638 /* If the type is VOID, this is a statement, so we need to generate the code
5639 for the call. Handle a condition, if there is one. */
5640 if (VOID_TYPE_P (*gnu_result_type_p))
5642 if (Present (gnat_cond))
5644 if (!gnu_cond)
5645 gnu_cond = gnat_to_gnu (gnat_cond);
5646 gnu_result = build3 (COND_EXPR, void_type_node, gnu_cond, gnu_result,
5647 alloc_stmt_list ());
5650 else
5651 gnu_result = build1 (NULL_EXPR, *gnu_result_type_p, gnu_result);
5653 return gnu_result;
5656 /* Return true if GNAT_NODE is on the LHS of an assignment or an actual
5657 parameter of a call. */
5659 static bool
5660 lhs_or_actual_p (Node_Id gnat_node)
5662 Node_Id gnat_parent = Parent (gnat_node);
5663 Node_Kind kind = Nkind (gnat_parent);
5665 if (kind == N_Assignment_Statement && Name (gnat_parent) == gnat_node)
5666 return true;
5668 if ((kind == N_Procedure_Call_Statement || kind == N_Function_Call)
5669 && Name (gnat_parent) != gnat_node)
5670 return true;
5672 if (kind == N_Parameter_Association)
5673 return true;
5675 return false;
5678 /* Return true if either GNAT_NODE or a view of GNAT_NODE is on the LHS
5679 of an assignment or an actual parameter of a call. */
5681 static bool
5682 present_in_lhs_or_actual_p (Node_Id gnat_node)
5684 Node_Kind kind;
5686 if (lhs_or_actual_p (gnat_node))
5687 return true;
5689 kind = Nkind (Parent (gnat_node));
5691 if ((kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
5692 && lhs_or_actual_p (Parent (gnat_node)))
5693 return true;
5695 return false;
5698 /* Return true if GNAT_NODE, an unchecked type conversion, is a no-op as far
5699 as gigi is concerned. This is used to avoid conversions on the LHS. */
5701 static bool
5702 unchecked_conversion_nop (Node_Id gnat_node)
5704 Entity_Id from_type, to_type;
5706 /* The conversion must be on the LHS of an assignment or an actual parameter
5707 of a call. Otherwise, even if the conversion was essentially a no-op, it
5708 could de facto ensure type consistency and this should be preserved. */
5709 if (!lhs_or_actual_p (gnat_node))
5710 return false;
5712 from_type = Etype (Expression (gnat_node));
5714 /* We're interested in artificial conversions generated by the front-end
5715 to make private types explicit, e.g. in Expand_Assign_Array. */
5716 if (!Is_Private_Type (from_type))
5717 return false;
5719 from_type = Underlying_Type (from_type);
5720 to_type = Etype (gnat_node);
5722 /* The direct conversion to the underlying type is a no-op. */
5723 if (to_type == from_type)
5724 return true;
5726 /* For an array subtype, the conversion to the PAIT is a no-op. */
5727 if (Ekind (from_type) == E_Array_Subtype
5728 && to_type == Packed_Array_Impl_Type (from_type))
5729 return true;
5731 /* For a record subtype, the conversion to the type is a no-op. */
5732 if (Ekind (from_type) == E_Record_Subtype
5733 && to_type == Etype (from_type))
5734 return true;
5736 return false;
5739 /* This function is the driver of the GNAT to GCC tree transformation process.
5740 It is the entry point of the tree transformer. GNAT_NODE is the root of
5741 some GNAT tree. Return the root of the corresponding GCC tree. If this
5742 is an expression, return the GCC equivalent of the expression. If this
5743 is a statement, return the statement or add it to the current statement
5744 group, in which case anything returned is to be interpreted as occurring
5745 after anything added. */
5747 tree
5748 gnat_to_gnu (Node_Id gnat_node)
5750 const Node_Kind kind = Nkind (gnat_node);
5751 bool went_into_elab_proc = false;
5752 tree gnu_result = error_mark_node; /* Default to no value. */
5753 tree gnu_result_type = void_type_node;
5754 tree gnu_expr, gnu_lhs, gnu_rhs;
5755 Node_Id gnat_temp;
5756 bool sync;
5758 /* Save node number for error message and set location information. */
5759 error_gnat_node = gnat_node;
5760 Sloc_to_locus (Sloc (gnat_node), &input_location);
5762 /* If this node is a statement and we are only annotating types, return an
5763 empty statement list. */
5764 if (type_annotate_only && IN (kind, N_Statement_Other_Than_Procedure_Call))
5765 return alloc_stmt_list ();
5767 /* If this node is a non-static subexpression and we are only annotating
5768 types, make this into a NULL_EXPR. */
5769 if (type_annotate_only
5770 && IN (kind, N_Subexpr)
5771 && kind != N_Expanded_Name
5772 && kind != N_Identifier
5773 && !Compile_Time_Known_Value (gnat_node))
5774 return build1 (NULL_EXPR, get_unpadded_type (Etype (gnat_node)),
5775 build_call_raise (CE_Range_Check_Failed, gnat_node,
5776 N_Raise_Constraint_Error));
5778 if ((IN (kind, N_Statement_Other_Than_Procedure_Call)
5779 && kind != N_Null_Statement)
5780 || kind == N_Procedure_Call_Statement
5781 || kind == N_Label
5782 || kind == N_Implicit_Label_Declaration
5783 || kind == N_Handled_Sequence_Of_Statements
5784 || (IN (kind, N_Raise_xxx_Error) && Ekind (Etype (gnat_node)) == E_Void))
5786 tree current_elab_proc = get_elaboration_procedure ();
5788 /* If this is a statement and we are at top level, it must be part of
5789 the elaboration procedure, so mark us as being in that procedure. */
5790 if (!current_function_decl)
5792 current_function_decl = current_elab_proc;
5793 went_into_elab_proc = true;
5796 /* If we are in the elaboration procedure, check if we are violating a
5797 No_Elaboration_Code restriction by having a statement there. Don't
5798 check for a possible No_Elaboration_Code restriction violation on
5799 N_Handled_Sequence_Of_Statements, as we want to signal an error on
5800 every nested real statement instead. This also avoids triggering
5801 spurious errors on dummy (empty) sequences created by the front-end
5802 for package bodies in some cases. */
5803 if (current_function_decl == current_elab_proc
5804 && kind != N_Handled_Sequence_Of_Statements)
5805 Check_Elaboration_Code_Allowed (gnat_node);
5808 switch (kind)
5810 /********************************/
5811 /* Chapter 2: Lexical Elements */
5812 /********************************/
5814 case N_Identifier:
5815 case N_Expanded_Name:
5816 case N_Operator_Symbol:
5817 case N_Defining_Identifier:
5818 case N_Defining_Operator_Symbol:
5819 gnu_result = Identifier_to_gnu (gnat_node, &gnu_result_type);
5821 /* If atomic access is required on the RHS, build the atomic load. */
5822 if (atomic_access_required_p (gnat_node, &sync)
5823 && !present_in_lhs_or_actual_p (gnat_node))
5824 gnu_result = build_atomic_load (gnu_result, sync);
5825 break;
5827 case N_Integer_Literal:
5829 tree gnu_type;
5831 /* Get the type of the result, looking inside any padding and
5832 justified modular types. Then get the value in that type. */
5833 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
5835 if (TREE_CODE (gnu_type) == RECORD_TYPE
5836 && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
5837 gnu_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
5839 gnu_result = UI_To_gnu (Intval (gnat_node), gnu_type);
5841 /* If the result overflows (meaning it doesn't fit in its base type),
5842 abort. We would like to check that the value is within the range
5843 of the subtype, but that causes problems with subtypes whose usage
5844 will raise Constraint_Error and with biased representation, so
5845 we don't. */
5846 gcc_assert (!TREE_OVERFLOW (gnu_result));
5848 break;
5850 case N_Character_Literal:
5851 /* If a Entity is present, it means that this was one of the
5852 literals in a user-defined character type. In that case,
5853 just return the value in the CONST_DECL. Otherwise, use the
5854 character code. In that case, the base type should be an
5855 INTEGER_TYPE, but we won't bother checking for that. */
5856 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5857 if (Present (Entity (gnat_node)))
5858 gnu_result = DECL_INITIAL (get_gnu_tree (Entity (gnat_node)));
5859 else
5860 gnu_result
5861 = build_int_cst_type
5862 (gnu_result_type, UI_To_CC (Char_Literal_Value (gnat_node)));
5863 break;
5865 case N_Real_Literal:
5866 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5868 /* If this is of a fixed-point type, the value we want is the value of
5869 the corresponding integer. */
5870 if (IN (Ekind (Underlying_Type (Etype (gnat_node))), Fixed_Point_Kind))
5872 gnu_result = UI_To_gnu (Corresponding_Integer_Value (gnat_node),
5873 gnu_result_type);
5874 gcc_assert (!TREE_OVERFLOW (gnu_result));
5877 else
5879 Ureal ur_realval = Realval (gnat_node);
5881 /* First convert the value to a machine number if it isn't already.
5882 That will force the base to 2 for non-zero values and simplify
5883 the rest of the logic. */
5884 if (!Is_Machine_Number (gnat_node))
5885 ur_realval
5886 = Machine (Base_Type (Underlying_Type (Etype (gnat_node))),
5887 ur_realval, Round_Even, gnat_node);
5889 if (UR_Is_Zero (ur_realval))
5890 gnu_result = convert (gnu_result_type, integer_zero_node);
5891 else
5893 REAL_VALUE_TYPE tmp;
5895 gnu_result = UI_To_gnu (Numerator (ur_realval), gnu_result_type);
5897 /* The base must be 2 as Machine guarantees this, so we scale
5898 the value, which we know can fit in the mantissa of the type
5899 (hence the use of that type above). */
5900 gcc_assert (Rbase (ur_realval) == 2);
5901 real_ldexp (&tmp, &TREE_REAL_CST (gnu_result),
5902 - UI_To_Int (Denominator (ur_realval)));
5903 gnu_result = build_real (gnu_result_type, tmp);
5906 /* Now see if we need to negate the result. Do it this way to
5907 properly handle -0. */
5908 if (UR_Is_Negative (Realval (gnat_node)))
5909 gnu_result
5910 = build_unary_op (NEGATE_EXPR, get_base_type (gnu_result_type),
5911 gnu_result);
5914 break;
5916 case N_String_Literal:
5917 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5918 if (TYPE_PRECISION (TREE_TYPE (gnu_result_type)) == HOST_BITS_PER_CHAR)
5920 String_Id gnat_string = Strval (gnat_node);
5921 int length = String_Length (gnat_string);
5922 int i;
5923 char *string;
5924 if (length >= ALLOCA_THRESHOLD)
5925 string = XNEWVEC (char, length + 1);
5926 else
5927 string = (char *) alloca (length + 1);
5929 /* Build the string with the characters in the literal. Note
5930 that Ada strings are 1-origin. */
5931 for (i = 0; i < length; i++)
5932 string[i] = Get_String_Char (gnat_string, i + 1);
5934 /* Put a null at the end of the string in case it's in a context
5935 where GCC will want to treat it as a C string. */
5936 string[i] = 0;
5938 gnu_result = build_string (length, string);
5940 /* Strings in GCC don't normally have types, but we want
5941 this to not be converted to the array type. */
5942 TREE_TYPE (gnu_result) = gnu_result_type;
5944 if (length >= ALLOCA_THRESHOLD)
5945 free (string);
5947 else
5949 /* Build a list consisting of each character, then make
5950 the aggregate. */
5951 String_Id gnat_string = Strval (gnat_node);
5952 int length = String_Length (gnat_string);
5953 int i;
5954 tree gnu_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
5955 tree gnu_one_node = convert (TREE_TYPE (gnu_idx), integer_one_node);
5956 vec<constructor_elt, va_gc> *gnu_vec;
5957 vec_alloc (gnu_vec, length);
5959 for (i = 0; i < length; i++)
5961 tree t = build_int_cst (TREE_TYPE (gnu_result_type),
5962 Get_String_Char (gnat_string, i + 1));
5964 CONSTRUCTOR_APPEND_ELT (gnu_vec, gnu_idx, t);
5965 gnu_idx = int_const_binop (PLUS_EXPR, gnu_idx, gnu_one_node);
5968 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
5970 break;
5972 case N_Pragma:
5973 gnu_result = Pragma_to_gnu (gnat_node);
5974 break;
5976 /**************************************/
5977 /* Chapter 3: Declarations and Types */
5978 /**************************************/
5980 case N_Subtype_Declaration:
5981 case N_Full_Type_Declaration:
5982 case N_Incomplete_Type_Declaration:
5983 case N_Private_Type_Declaration:
5984 case N_Private_Extension_Declaration:
5985 case N_Task_Type_Declaration:
5986 process_type (Defining_Entity (gnat_node));
5987 gnu_result = alloc_stmt_list ();
5988 break;
5990 case N_Object_Declaration:
5991 case N_Exception_Declaration:
5992 gnat_temp = Defining_Entity (gnat_node);
5993 gnu_result = alloc_stmt_list ();
5995 /* If we are just annotating types and this object has an unconstrained
5996 or task type, don't elaborate it. */
5997 if (type_annotate_only
5998 && (((Is_Array_Type (Etype (gnat_temp))
5999 || Is_Record_Type (Etype (gnat_temp)))
6000 && !Is_Constrained (Etype (gnat_temp)))
6001 || Is_Concurrent_Type (Etype (gnat_temp))))
6002 break;
6004 if (Present (Expression (gnat_node))
6005 && !(kind == N_Object_Declaration && No_Initialization (gnat_node))
6006 && (!type_annotate_only
6007 || Compile_Time_Known_Value (Expression (gnat_node))))
6009 gnu_expr = gnat_to_gnu (Expression (gnat_node));
6010 if (Do_Range_Check (Expression (gnat_node)))
6011 gnu_expr
6012 = emit_range_check (gnu_expr, Etype (gnat_temp), gnat_node);
6014 if (type_annotate_only && TREE_CODE (gnu_expr) == ERROR_MARK)
6015 gnu_expr = NULL_TREE;
6017 else
6018 gnu_expr = NULL_TREE;
6020 /* If this is a deferred constant with an address clause, we ignore the
6021 full view since the clause is on the partial view and we cannot have
6022 2 different GCC trees for the object. The only bits of the full view
6023 we will use is the initializer, but it will be directly fetched. */
6024 if (Ekind(gnat_temp) == E_Constant
6025 && Present (Address_Clause (gnat_temp))
6026 && Present (Full_View (gnat_temp)))
6027 save_gnu_tree (Full_View (gnat_temp), error_mark_node, true);
6029 /* If this object has its elaboration delayed, we must force evaluation
6030 of GNU_EXPR now and save it for the freeze point. Note that we need
6031 not do anything special at the global level since the lifetime of the
6032 temporary is fully contained within the elaboration routine. */
6033 if (Present (Freeze_Node (gnat_temp)))
6035 if (gnu_expr)
6037 gnu_result = gnat_save_expr (gnu_expr);
6038 save_gnu_tree (gnat_node, gnu_result, true);
6041 else
6042 gnat_to_gnu_entity (gnat_temp, gnu_expr, 1);
6043 break;
6045 case N_Object_Renaming_Declaration:
6046 gnat_temp = Defining_Entity (gnat_node);
6047 gnu_result = alloc_stmt_list ();
6049 /* Don't do anything if this renaming is handled by the front end or if
6050 we are just annotating types and this object has a composite or task
6051 type, don't elaborate it. */
6052 if (!Is_Renaming_Of_Object (gnat_temp)
6053 && ! (type_annotate_only
6054 && (Is_Array_Type (Etype (gnat_temp))
6055 || Is_Record_Type (Etype (gnat_temp))
6056 || Is_Concurrent_Type (Etype (gnat_temp)))))
6058 tree gnu_temp
6059 = gnat_to_gnu_entity (gnat_temp,
6060 gnat_to_gnu (Renamed_Object (gnat_temp)), 1);
6061 /* See case 2 of renaming in gnat_to_gnu_entity. */
6062 if (TREE_SIDE_EFFECTS (gnu_temp))
6063 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_temp);
6065 break;
6067 case N_Exception_Renaming_Declaration:
6068 gnat_temp = Defining_Entity (gnat_node);
6069 gnu_result = alloc_stmt_list ();
6071 /* See the above case for the rationale. */
6072 if (Present (Renamed_Entity (gnat_temp)))
6074 tree gnu_temp
6075 = gnat_to_gnu_entity (gnat_temp,
6076 gnat_to_gnu (Renamed_Entity (gnat_temp)), 1);
6077 if (TREE_SIDE_EFFECTS (gnu_temp))
6078 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_temp);
6080 break;
6082 case N_Subprogram_Renaming_Declaration:
6084 const Node_Id gnat_renaming = Defining_Entity (gnat_node);
6085 const Node_Id gnat_renamed = Renamed_Entity (gnat_renaming);
6087 gnu_result = alloc_stmt_list ();
6089 /* Materializing renamed subprograms will only benefit the debugging
6090 information as they aren't referenced in the generated code. So
6091 skip them when they aren't needed. Avoid doing this if:
6093 - there is a freeze node: in this case the renamed entity is not
6094 elaborated yet,
6095 - the renamed subprogram is intrinsic: it will not be available in
6096 the debugging information (note that both or only one of the
6097 renaming and the renamed subprograms can be intrinsic). */
6098 if (!type_annotate_only
6099 && Needs_Debug_Info (gnat_renaming)
6100 && No (Freeze_Node (gnat_renaming))
6101 && Present (gnat_renamed)
6102 && (Ekind (gnat_renamed) == E_Function
6103 || Ekind (gnat_renamed) == E_Procedure)
6104 && !Is_Intrinsic_Subprogram (gnat_renaming)
6105 && !Is_Intrinsic_Subprogram (gnat_renamed))
6106 gnat_to_gnu_entity (gnat_renaming, gnat_to_gnu (gnat_renamed), 1);
6107 break;
6110 case N_Implicit_Label_Declaration:
6111 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
6112 gnu_result = alloc_stmt_list ();
6113 break;
6115 case N_Number_Declaration:
6116 case N_Package_Renaming_Declaration:
6117 /* These are fully handled in the front end. */
6118 /* ??? For package renamings, find a way to use GENERIC namespaces so
6119 that we get proper debug information for them. */
6120 gnu_result = alloc_stmt_list ();
6121 break;
6123 /*************************************/
6124 /* Chapter 4: Names and Expressions */
6125 /*************************************/
6127 case N_Explicit_Dereference:
6128 gnu_result = gnat_to_gnu (Prefix (gnat_node));
6129 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6130 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
6132 /* If atomic access is required on the RHS, build the atomic load. */
6133 if (atomic_access_required_p (gnat_node, &sync)
6134 && !present_in_lhs_or_actual_p (gnat_node))
6135 gnu_result = build_atomic_load (gnu_result, sync);
6136 break;
6138 case N_Indexed_Component:
6140 tree gnu_array_object = gnat_to_gnu (Prefix (gnat_node));
6141 tree gnu_type;
6142 int ndim;
6143 int i;
6144 Node_Id *gnat_expr_array;
6146 gnu_array_object = maybe_implicit_deref (gnu_array_object);
6148 /* Convert vector inputs to their representative array type, to fit
6149 what the code below expects. */
6150 if (VECTOR_TYPE_P (TREE_TYPE (gnu_array_object)))
6152 if (present_in_lhs_or_actual_p (gnat_node))
6153 gnat_mark_addressable (gnu_array_object);
6154 gnu_array_object = maybe_vector_array (gnu_array_object);
6157 gnu_array_object = maybe_unconstrained_array (gnu_array_object);
6159 /* If we got a padded type, remove it too. */
6160 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_array_object)))
6161 gnu_array_object
6162 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_array_object))),
6163 gnu_array_object);
6165 gnu_result = gnu_array_object;
6167 /* The failure of this assertion will very likely come from a missing
6168 expansion for a packed array access. */
6169 gcc_assert (TREE_CODE (TREE_TYPE (gnu_array_object)) == ARRAY_TYPE);
6171 /* First compute the number of dimensions of the array, then
6172 fill the expression array, the order depending on whether
6173 this is a Convention_Fortran array or not. */
6174 for (ndim = 1, gnu_type = TREE_TYPE (gnu_array_object);
6175 TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
6176 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type));
6177 ndim++, gnu_type = TREE_TYPE (gnu_type))
6180 gnat_expr_array = XALLOCAVEC (Node_Id, ndim);
6182 if (TYPE_CONVENTION_FORTRAN_P (TREE_TYPE (gnu_array_object)))
6183 for (i = ndim - 1, gnat_temp = First (Expressions (gnat_node));
6184 i >= 0;
6185 i--, gnat_temp = Next (gnat_temp))
6186 gnat_expr_array[i] = gnat_temp;
6187 else
6188 for (i = 0, gnat_temp = First (Expressions (gnat_node));
6189 i < ndim;
6190 i++, gnat_temp = Next (gnat_temp))
6191 gnat_expr_array[i] = gnat_temp;
6193 for (i = 0, gnu_type = TREE_TYPE (gnu_array_object);
6194 i < ndim;
6195 i++, gnu_type = TREE_TYPE (gnu_type))
6197 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
6198 gnat_temp = gnat_expr_array[i];
6199 gnu_expr = gnat_to_gnu (gnat_temp);
6200 struct loop_info_d *loop;
6202 if (Do_Range_Check (gnat_temp))
6203 gnu_expr
6204 = emit_index_check
6205 (gnu_array_object, gnu_expr,
6206 TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
6207 TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
6208 gnat_temp);
6210 gnu_result
6211 = build_binary_op (ARRAY_REF, NULL_TREE, gnu_result, gnu_expr);
6213 /* Array accesses are bound-checked so they cannot trap, but this
6214 is valid only if they are not hoisted ahead of the check. We
6215 need to mark them as no-trap to get decent loop optimizations
6216 in the presence of -fnon-call-exceptions, so we do it when we
6217 know that the original expression had no side-effects. */
6218 if (TREE_CODE (gnu_result) == ARRAY_REF
6219 && !(Nkind (gnat_temp) == N_Identifier
6220 && Ekind (Entity (gnat_temp)) == E_Constant))
6221 TREE_THIS_NOTRAP (gnu_result) = 1;
6223 /* If aggressive loop optimizations are enabled, we warn for loops
6224 overrunning a simple array of size 1 not at the end of a record.
6225 This is aimed to catch misuses of the trailing array idiom. */
6226 if (optimize
6227 && flag_aggressive_loop_optimizations
6228 && inside_loop_p ()
6229 && TREE_CODE (TREE_TYPE (gnu_type)) != ARRAY_TYPE
6230 && TREE_CODE (gnu_array_object) != ARRAY_REF
6231 && tree_int_cst_equal (TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_type)),
6232 TYPE_MAX_VALUE (TYPE_DOMAIN (gnu_type)))
6233 && !array_at_struct_end_p (gnu_result)
6234 && (loop = find_loop_for (gnu_expr))
6235 && !loop->artificial
6236 && !loop->has_checks
6237 && tree_int_cst_equal (TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_type)),
6238 loop->low_bound)
6239 && can_be_lower_p (loop->low_bound, loop->high_bound)
6240 && !loop->warned_aggressive_loop_optimizations
6241 && warning (OPT_Waggressive_loop_optimizations,
6242 "out-of-bounds access may be optimized away"))
6244 inform (EXPR_LOCATION (loop->stmt), "containing loop");
6245 loop->warned_aggressive_loop_optimizations = true;
6249 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6251 /* If atomic access is required on the RHS, build the atomic load. */
6252 if (atomic_access_required_p (gnat_node, &sync)
6253 && !present_in_lhs_or_actual_p (gnat_node))
6254 gnu_result = build_atomic_load (gnu_result, sync);
6256 break;
6258 case N_Slice:
6260 Node_Id gnat_range_node = Discrete_Range (gnat_node);
6261 tree gnu_type;
6263 gnu_result = gnat_to_gnu (Prefix (gnat_node));
6264 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6266 /* Do any implicit dereferences of the prefix and do any needed
6267 range check. */
6268 gnu_result = maybe_implicit_deref (gnu_result);
6269 gnu_result = maybe_unconstrained_array (gnu_result);
6270 gnu_type = TREE_TYPE (gnu_result);
6271 if (Do_Range_Check (gnat_range_node))
6273 /* Get the bounds of the slice. */
6274 tree gnu_index_type
6275 = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_result_type));
6276 tree gnu_min_expr = TYPE_MIN_VALUE (gnu_index_type);
6277 tree gnu_max_expr = TYPE_MAX_VALUE (gnu_index_type);
6278 /* Get the permitted bounds. */
6279 tree gnu_base_index_type
6280 = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
6281 tree gnu_base_min_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
6282 (TYPE_MIN_VALUE (gnu_base_index_type), gnu_result);
6283 tree gnu_base_max_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
6284 (TYPE_MAX_VALUE (gnu_base_index_type), gnu_result);
6285 tree gnu_expr_l, gnu_expr_h, gnu_expr_type;
6287 gnu_min_expr = gnat_protect_expr (gnu_min_expr);
6288 gnu_max_expr = gnat_protect_expr (gnu_max_expr);
6290 /* Derive a good type to convert everything to. */
6291 gnu_expr_type = get_base_type (gnu_index_type);
6293 /* Test whether the minimum slice value is too small. */
6294 gnu_expr_l = build_binary_op (LT_EXPR, boolean_type_node,
6295 convert (gnu_expr_type,
6296 gnu_min_expr),
6297 convert (gnu_expr_type,
6298 gnu_base_min_expr));
6300 /* Test whether the maximum slice value is too large. */
6301 gnu_expr_h = build_binary_op (GT_EXPR, boolean_type_node,
6302 convert (gnu_expr_type,
6303 gnu_max_expr),
6304 convert (gnu_expr_type,
6305 gnu_base_max_expr));
6307 /* Build a slice index check that returns the low bound,
6308 assuming the slice is not empty. */
6309 gnu_expr = emit_check
6310 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
6311 gnu_expr_l, gnu_expr_h),
6312 gnu_min_expr, CE_Index_Check_Failed, gnat_node);
6314 /* Build a conditional expression that does the index checks and
6315 returns the low bound if the slice is not empty (max >= min),
6316 and returns the naked low bound otherwise (max < min), unless
6317 it is non-constant and the high bound is; this prevents VRP
6318 from inferring bogus ranges on the unlikely path. */
6319 gnu_expr = fold_build3 (COND_EXPR, gnu_expr_type,
6320 build_binary_op (GE_EXPR, gnu_expr_type,
6321 convert (gnu_expr_type,
6322 gnu_max_expr),
6323 convert (gnu_expr_type,
6324 gnu_min_expr)),
6325 gnu_expr,
6326 TREE_CODE (gnu_min_expr) != INTEGER_CST
6327 && TREE_CODE (gnu_max_expr) == INTEGER_CST
6328 ? gnu_max_expr : gnu_min_expr);
6330 else
6331 /* Simply return the naked low bound. */
6332 gnu_expr = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
6334 /* If this is a slice with non-constant size of an array with constant
6335 size, set the maximum size for the allocation of temporaries. */
6336 if (!TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_result_type))
6337 && TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_type)))
6338 TYPE_ARRAY_MAX_SIZE (gnu_result_type) = TYPE_SIZE_UNIT (gnu_type);
6340 gnu_result = build_binary_op (ARRAY_RANGE_REF, gnu_result_type,
6341 gnu_result, gnu_expr);
6343 break;
6345 case N_Selected_Component:
6347 Entity_Id gnat_prefix = Prefix (gnat_node);
6348 Entity_Id gnat_field = Entity (Selector_Name (gnat_node));
6349 tree gnu_prefix = gnat_to_gnu (gnat_prefix);
6350 tree gnu_field;
6352 gnu_prefix = maybe_implicit_deref (gnu_prefix);
6354 /* For discriminant references in tagged types always substitute the
6355 corresponding discriminant as the actual selected component. */
6356 if (Is_Tagged_Type (Underlying_Type (Etype (gnat_prefix))))
6357 while (Present (Corresponding_Discriminant (gnat_field)))
6358 gnat_field = Corresponding_Discriminant (gnat_field);
6360 /* For discriminant references of untagged types always substitute the
6361 corresponding stored discriminant. */
6362 else if (Present (Corresponding_Discriminant (gnat_field)))
6363 gnat_field = Original_Record_Component (gnat_field);
6365 /* Handle extracting the real or imaginary part of a complex.
6366 The real part is the first field and the imaginary the last. */
6367 if (TREE_CODE (TREE_TYPE (gnu_prefix)) == COMPLEX_TYPE)
6368 gnu_result = build_unary_op (Present (Next_Entity (gnat_field))
6369 ? REALPART_EXPR : IMAGPART_EXPR,
6370 NULL_TREE, gnu_prefix);
6371 else
6373 gnu_field = gnat_to_gnu_field_decl (gnat_field);
6375 gnu_result
6376 = build_component_ref (gnu_prefix, gnu_field,
6377 (Nkind (Parent (gnat_node))
6378 == N_Attribute_Reference)
6379 && lvalue_required_for_attribute_p
6380 (Parent (gnat_node)));
6383 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6385 /* If atomic access is required on the RHS, build the atomic load. */
6386 if (atomic_access_required_p (gnat_node, &sync)
6387 && !present_in_lhs_or_actual_p (gnat_node))
6388 gnu_result = build_atomic_load (gnu_result, sync);
6390 break;
6392 case N_Attribute_Reference:
6394 /* The attribute designator. */
6395 const int attr = Get_Attribute_Id (Attribute_Name (gnat_node));
6397 /* The Elab_Spec and Elab_Body attributes are special in that Prefix
6398 is a unit, not an object with a GCC equivalent. */
6399 if (attr == Attr_Elab_Spec || attr == Attr_Elab_Body)
6400 return
6401 create_subprog_decl (create_concat_name
6402 (Entity (Prefix (gnat_node)),
6403 attr == Attr_Elab_Body ? "elabb" : "elabs"),
6404 NULL_TREE, void_ftype, NULL_TREE, is_disabled,
6405 false, true, true, false, true, true,
6406 NULL, gnat_node);
6408 gnu_result = Attribute_to_gnu (gnat_node, &gnu_result_type, attr);
6410 break;
6412 case N_Reference:
6413 /* Like 'Access as far as we are concerned. */
6414 gnu_result = gnat_to_gnu (Prefix (gnat_node));
6415 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
6416 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6417 break;
6419 case N_Aggregate:
6420 case N_Extension_Aggregate:
6422 tree gnu_aggr_type;
6424 /* ??? It is wrong to evaluate the type now, but there doesn't
6425 seem to be any other practical way of doing it. */
6427 gcc_assert (!Expansion_Delayed (gnat_node));
6429 gnu_aggr_type = gnu_result_type
6430 = get_unpadded_type (Etype (gnat_node));
6432 if (TREE_CODE (gnu_result_type) == RECORD_TYPE
6433 && TYPE_CONTAINS_TEMPLATE_P (gnu_result_type))
6434 gnu_aggr_type
6435 = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_result_type)));
6436 else if (TREE_CODE (gnu_result_type) == VECTOR_TYPE)
6437 gnu_aggr_type = TYPE_REPRESENTATIVE_ARRAY (gnu_result_type);
6439 if (Null_Record_Present (gnat_node))
6440 gnu_result = gnat_build_constructor (gnu_aggr_type,
6441 NULL);
6443 else if (TREE_CODE (gnu_aggr_type) == RECORD_TYPE
6444 || TREE_CODE (gnu_aggr_type) == UNION_TYPE)
6445 gnu_result
6446 = assoc_to_constructor (Etype (gnat_node),
6447 First (Component_Associations (gnat_node)),
6448 gnu_aggr_type);
6449 else if (TREE_CODE (gnu_aggr_type) == ARRAY_TYPE)
6450 gnu_result = pos_to_constructor (First (Expressions (gnat_node)),
6451 gnu_aggr_type,
6452 Component_Type (Etype (gnat_node)));
6453 else if (TREE_CODE (gnu_aggr_type) == COMPLEX_TYPE)
6454 gnu_result
6455 = build_binary_op
6456 (COMPLEX_EXPR, gnu_aggr_type,
6457 gnat_to_gnu (Expression (First
6458 (Component_Associations (gnat_node)))),
6459 gnat_to_gnu (Expression
6460 (Next
6461 (First (Component_Associations (gnat_node))))));
6462 else
6463 gcc_unreachable ();
6465 gnu_result = convert (gnu_result_type, gnu_result);
6467 break;
6469 case N_Null:
6470 if (TARGET_VTABLE_USES_DESCRIPTORS
6471 && Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
6472 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
6473 gnu_result = null_fdesc_node;
6474 else
6475 gnu_result = null_pointer_node;
6476 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6477 break;
6479 case N_Type_Conversion:
6480 case N_Qualified_Expression:
6481 /* Get the operand expression. */
6482 gnu_result = gnat_to_gnu (Expression (gnat_node));
6483 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6485 /* If this is a qualified expression for a tagged type, we mark the type
6486 as used. Because of polymorphism, this might be the only reference to
6487 the tagged type in the program while objects have it as dynamic type.
6488 The debugger needs to see it to display these objects properly. */
6489 if (kind == N_Qualified_Expression && Is_Tagged_Type (Etype (gnat_node)))
6490 used_types_insert (gnu_result_type);
6492 gnu_result
6493 = convert_with_check (Etype (gnat_node), gnu_result,
6494 Do_Overflow_Check (gnat_node),
6495 Do_Range_Check (Expression (gnat_node)),
6496 kind == N_Type_Conversion
6497 && Float_Truncate (gnat_node), gnat_node);
6498 break;
6500 case N_Unchecked_Type_Conversion:
6501 gnu_result = gnat_to_gnu (Expression (gnat_node));
6503 /* Skip further processing if the conversion is deemed a no-op. */
6504 if (unchecked_conversion_nop (gnat_node))
6506 gnu_result_type = TREE_TYPE (gnu_result);
6507 break;
6510 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6512 /* If the result is a pointer type, see if we are improperly
6513 converting to a stricter alignment. */
6514 if (STRICT_ALIGNMENT && POINTER_TYPE_P (gnu_result_type)
6515 && IN (Ekind (Etype (gnat_node)), Access_Kind))
6517 unsigned int align = known_alignment (gnu_result);
6518 tree gnu_obj_type = TREE_TYPE (gnu_result_type);
6519 unsigned int oalign = TYPE_ALIGN (gnu_obj_type);
6521 if (align != 0 && align < oalign && !TYPE_ALIGN_OK (gnu_obj_type))
6522 post_error_ne_tree_2
6523 ("?source alignment (^) '< alignment of & (^)",
6524 gnat_node, Designated_Type (Etype (gnat_node)),
6525 size_int (align / BITS_PER_UNIT), oalign / BITS_PER_UNIT);
6528 /* If we are converting a descriptor to a function pointer, first
6529 build the pointer. */
6530 if (TARGET_VTABLE_USES_DESCRIPTORS
6531 && TREE_TYPE (gnu_result) == fdesc_type_node
6532 && POINTER_TYPE_P (gnu_result_type))
6533 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
6535 gnu_result = unchecked_convert (gnu_result_type, gnu_result,
6536 No_Truncation (gnat_node));
6537 break;
6539 case N_In:
6540 case N_Not_In:
6542 tree gnu_obj = gnat_to_gnu (Left_Opnd (gnat_node));
6543 Node_Id gnat_range = Right_Opnd (gnat_node);
6544 tree gnu_low, gnu_high;
6546 /* GNAT_RANGE is either an N_Range node or an identifier denoting a
6547 subtype. */
6548 if (Nkind (gnat_range) == N_Range)
6550 gnu_low = gnat_to_gnu (Low_Bound (gnat_range));
6551 gnu_high = gnat_to_gnu (High_Bound (gnat_range));
6553 else if (Nkind (gnat_range) == N_Identifier
6554 || Nkind (gnat_range) == N_Expanded_Name)
6556 tree gnu_range_type = get_unpadded_type (Entity (gnat_range));
6557 tree gnu_range_base_type = get_base_type (gnu_range_type);
6559 gnu_low
6560 = convert (gnu_range_base_type, TYPE_MIN_VALUE (gnu_range_type));
6561 gnu_high
6562 = convert (gnu_range_base_type, TYPE_MAX_VALUE (gnu_range_type));
6564 else
6565 gcc_unreachable ();
6567 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6569 /* If LOW and HIGH are identical, perform an equality test. Otherwise,
6570 ensure that GNU_OBJ is evaluated only once and perform a full range
6571 test. */
6572 if (operand_equal_p (gnu_low, gnu_high, 0))
6573 gnu_result
6574 = build_binary_op (EQ_EXPR, gnu_result_type, gnu_obj, gnu_low);
6575 else
6577 tree t1, t2;
6578 gnu_obj = gnat_protect_expr (gnu_obj);
6579 t1 = build_binary_op (GE_EXPR, gnu_result_type, gnu_obj, gnu_low);
6580 if (EXPR_P (t1))
6581 set_expr_location_from_node (t1, gnat_node);
6582 t2 = build_binary_op (LE_EXPR, gnu_result_type, gnu_obj, gnu_high);
6583 if (EXPR_P (t2))
6584 set_expr_location_from_node (t2, gnat_node);
6585 gnu_result
6586 = build_binary_op (TRUTH_ANDIF_EXPR, gnu_result_type, t1, t2);
6589 if (kind == N_Not_In)
6590 gnu_result
6591 = invert_truthvalue_loc (EXPR_LOCATION (gnu_result), gnu_result);
6593 break;
6595 case N_Op_Divide:
6596 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6597 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6598 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6599 gnu_result = build_binary_op (FLOAT_TYPE_P (gnu_result_type)
6600 ? RDIV_EXPR
6601 : (Rounded_Result (gnat_node)
6602 ? ROUND_DIV_EXPR : TRUNC_DIV_EXPR),
6603 gnu_result_type, gnu_lhs, gnu_rhs);
6604 break;
6606 case N_Op_Or: case N_Op_And: case N_Op_Xor:
6607 /* These can either be operations on booleans or on modular types.
6608 Fall through for boolean types since that's the way GNU_CODES is
6609 set up. */
6610 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
6612 enum tree_code code
6613 = (kind == N_Op_Or ? BIT_IOR_EXPR
6614 : kind == N_Op_And ? BIT_AND_EXPR
6615 : BIT_XOR_EXPR);
6617 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6618 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6619 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6620 gnu_result = build_binary_op (code, gnu_result_type,
6621 gnu_lhs, gnu_rhs);
6622 break;
6625 /* ... fall through ... */
6627 case N_Op_Eq: case N_Op_Ne: case N_Op_Lt:
6628 case N_Op_Le: case N_Op_Gt: case N_Op_Ge:
6629 case N_Op_Add: case N_Op_Subtract: case N_Op_Multiply:
6630 case N_Op_Mod: case N_Op_Rem:
6631 case N_Op_Rotate_Left:
6632 case N_Op_Rotate_Right:
6633 case N_Op_Shift_Left:
6634 case N_Op_Shift_Right:
6635 case N_Op_Shift_Right_Arithmetic:
6636 case N_And_Then: case N_Or_Else:
6638 enum tree_code code = gnu_codes[kind];
6639 bool ignore_lhs_overflow = false;
6640 location_t saved_location = input_location;
6641 tree gnu_type;
6643 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6644 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6645 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
6647 /* Pending generic support for efficient vector logical operations in
6648 GCC, convert vectors to their representative array type view and
6649 fallthrough. */
6650 gnu_lhs = maybe_vector_array (gnu_lhs);
6651 gnu_rhs = maybe_vector_array (gnu_rhs);
6653 /* If this is a comparison operator, convert any references to an
6654 unconstrained array value into a reference to the actual array. */
6655 if (TREE_CODE_CLASS (code) == tcc_comparison)
6657 gnu_lhs = maybe_unconstrained_array (gnu_lhs);
6658 gnu_rhs = maybe_unconstrained_array (gnu_rhs);
6661 /* If this is a shift whose count is not guaranteed to be correct,
6662 we need to adjust the shift count. */
6663 if (IN (kind, N_Op_Shift) && !Shift_Count_OK (gnat_node))
6665 tree gnu_count_type = get_base_type (TREE_TYPE (gnu_rhs));
6666 tree gnu_max_shift
6667 = convert (gnu_count_type, TYPE_SIZE (gnu_type));
6669 if (kind == N_Op_Rotate_Left || kind == N_Op_Rotate_Right)
6670 gnu_rhs = build_binary_op (TRUNC_MOD_EXPR, gnu_count_type,
6671 gnu_rhs, gnu_max_shift);
6672 else if (kind == N_Op_Shift_Right_Arithmetic)
6673 gnu_rhs
6674 = build_binary_op
6675 (MIN_EXPR, gnu_count_type,
6676 build_binary_op (MINUS_EXPR,
6677 gnu_count_type,
6678 gnu_max_shift,
6679 convert (gnu_count_type,
6680 integer_one_node)),
6681 gnu_rhs);
6684 /* For right shifts, the type says what kind of shift to do,
6685 so we may need to choose a different type. In this case,
6686 we have to ignore integer overflow lest it propagates all
6687 the way down and causes a CE to be explicitly raised. */
6688 if (kind == N_Op_Shift_Right && !TYPE_UNSIGNED (gnu_type))
6690 gnu_type = gnat_unsigned_type (gnu_type);
6691 ignore_lhs_overflow = true;
6693 else if (kind == N_Op_Shift_Right_Arithmetic
6694 && TYPE_UNSIGNED (gnu_type))
6696 gnu_type = gnat_signed_type (gnu_type);
6697 ignore_lhs_overflow = true;
6700 if (gnu_type != gnu_result_type)
6702 tree gnu_old_lhs = gnu_lhs;
6703 gnu_lhs = convert (gnu_type, gnu_lhs);
6704 if (TREE_CODE (gnu_lhs) == INTEGER_CST && ignore_lhs_overflow)
6705 TREE_OVERFLOW (gnu_lhs) = TREE_OVERFLOW (gnu_old_lhs);
6706 gnu_rhs = convert (gnu_type, gnu_rhs);
6709 /* Instead of expanding overflow checks for addition, subtraction
6710 and multiplication itself, the front end will leave this to
6711 the back end when Backend_Overflow_Checks_On_Target is set.
6712 As the GCC back end itself does not know yet how to properly
6713 do overflow checking, do it here. The goal is to push
6714 the expansions further into the back end over time. */
6715 if (Do_Overflow_Check (gnat_node) && Backend_Overflow_Checks_On_Target
6716 && (kind == N_Op_Add
6717 || kind == N_Op_Subtract
6718 || kind == N_Op_Multiply)
6719 && !TYPE_UNSIGNED (gnu_type)
6720 && !FLOAT_TYPE_P (gnu_type))
6721 gnu_result = build_binary_op_trapv (code, gnu_type,
6722 gnu_lhs, gnu_rhs, gnat_node);
6723 else
6725 /* Some operations, e.g. comparisons of arrays, generate complex
6726 trees that need to be annotated while they are being built. */
6727 input_location = saved_location;
6728 gnu_result = build_binary_op (code, gnu_type, gnu_lhs, gnu_rhs);
6731 /* If this is a logical shift with the shift count not verified,
6732 we must return zero if it is too large. We cannot compensate
6733 above in this case. */
6734 if ((kind == N_Op_Shift_Left || kind == N_Op_Shift_Right)
6735 && !Shift_Count_OK (gnat_node))
6736 gnu_result
6737 = build_cond_expr
6738 (gnu_type,
6739 build_binary_op (GE_EXPR, boolean_type_node,
6740 gnu_rhs,
6741 convert (TREE_TYPE (gnu_rhs),
6742 TYPE_SIZE (gnu_type))),
6743 convert (gnu_type, integer_zero_node),
6744 gnu_result);
6746 break;
6748 case N_If_Expression:
6750 tree gnu_cond = gnat_to_gnu (First (Expressions (gnat_node)));
6751 tree gnu_true = gnat_to_gnu (Next (First (Expressions (gnat_node))));
6752 tree gnu_false
6753 = gnat_to_gnu (Next (Next (First (Expressions (gnat_node)))));
6755 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6756 gnu_result
6757 = build_cond_expr (gnu_result_type, gnu_cond, gnu_true, gnu_false);
6759 break;
6761 case N_Op_Plus:
6762 gnu_result = gnat_to_gnu (Right_Opnd (gnat_node));
6763 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6764 break;
6766 case N_Op_Not:
6767 /* This case can apply to a boolean or a modular type.
6768 Fall through for a boolean operand since GNU_CODES is set
6769 up to handle this. */
6770 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
6772 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
6773 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6774 gnu_result = build_unary_op (BIT_NOT_EXPR, gnu_result_type,
6775 gnu_expr);
6776 break;
6779 /* ... fall through ... */
6781 case N_Op_Minus: case N_Op_Abs:
6782 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
6783 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6785 if (Do_Overflow_Check (gnat_node)
6786 && !TYPE_UNSIGNED (gnu_result_type)
6787 && !FLOAT_TYPE_P (gnu_result_type))
6788 gnu_result
6789 = build_unary_op_trapv (gnu_codes[kind],
6790 gnu_result_type, gnu_expr, gnat_node);
6791 else
6792 gnu_result = build_unary_op (gnu_codes[kind],
6793 gnu_result_type, gnu_expr);
6794 break;
6796 case N_Allocator:
6798 tree gnu_init = 0;
6799 tree gnu_type;
6800 bool ignore_init_type = false;
6802 gnat_temp = Expression (gnat_node);
6804 /* The Expression operand can either be an N_Identifier or
6805 Expanded_Name, which must represent a type, or a
6806 N_Qualified_Expression, which contains both the object type and an
6807 initial value for the object. */
6808 if (Nkind (gnat_temp) == N_Identifier
6809 || Nkind (gnat_temp) == N_Expanded_Name)
6810 gnu_type = gnat_to_gnu_type (Entity (gnat_temp));
6811 else if (Nkind (gnat_temp) == N_Qualified_Expression)
6813 Entity_Id gnat_desig_type
6814 = Designated_Type (Underlying_Type (Etype (gnat_node)));
6816 ignore_init_type = Has_Constrained_Partial_View (gnat_desig_type);
6817 gnu_init = gnat_to_gnu (Expression (gnat_temp));
6819 gnu_init = maybe_unconstrained_array (gnu_init);
6820 if (Do_Range_Check (Expression (gnat_temp)))
6821 gnu_init
6822 = emit_range_check (gnu_init, gnat_desig_type, gnat_temp);
6824 if (Is_Elementary_Type (gnat_desig_type)
6825 || Is_Constrained (gnat_desig_type))
6826 gnu_type = gnat_to_gnu_type (gnat_desig_type);
6827 else
6829 gnu_type = gnat_to_gnu_type (Etype (Expression (gnat_temp)));
6830 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
6831 gnu_type = TREE_TYPE (gnu_init);
6834 /* See the N_Qualified_Expression case for the rationale. */
6835 if (Is_Tagged_Type (gnat_desig_type))
6836 used_types_insert (gnu_type);
6838 gnu_init = convert (gnu_type, gnu_init);
6840 else
6841 gcc_unreachable ();
6843 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6844 return build_allocator (gnu_type, gnu_init, gnu_result_type,
6845 Procedure_To_Call (gnat_node),
6846 Storage_Pool (gnat_node), gnat_node,
6847 ignore_init_type);
6849 break;
6851 /**************************/
6852 /* Chapter 5: Statements */
6853 /**************************/
6855 case N_Label:
6856 gnu_result = build1 (LABEL_EXPR, void_type_node,
6857 gnat_to_gnu (Identifier (gnat_node)));
6858 break;
6860 case N_Null_Statement:
6861 /* When not optimizing, turn null statements from source into gotos to
6862 the next statement that the middle-end knows how to preserve. */
6863 if (!optimize && Comes_From_Source (gnat_node))
6865 tree stmt, label = create_label_decl (NULL_TREE, gnat_node);
6866 DECL_IGNORED_P (label) = 1;
6867 start_stmt_group ();
6868 stmt = build1 (GOTO_EXPR, void_type_node, label);
6869 set_expr_location_from_node (stmt, gnat_node);
6870 add_stmt (stmt);
6871 stmt = build1 (LABEL_EXPR, void_type_node, label);
6872 set_expr_location_from_node (stmt, gnat_node);
6873 add_stmt (stmt);
6874 gnu_result = end_stmt_group ();
6876 else
6877 gnu_result = alloc_stmt_list ();
6878 break;
6880 case N_Assignment_Statement:
6881 /* Get the LHS and RHS of the statement and convert any reference to an
6882 unconstrained array into a reference to the underlying array. */
6883 gnu_lhs = maybe_unconstrained_array (gnat_to_gnu (Name (gnat_node)));
6885 /* If the type has a size that overflows, convert this into raise of
6886 Storage_Error: execution shouldn't have gotten here anyway. */
6887 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))) == INTEGER_CST
6888 && !valid_constant_size_p (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))))
6889 gnu_result = build_call_raise (SE_Object_Too_Large, gnat_node,
6890 N_Raise_Storage_Error);
6891 else if (Nkind (Expression (gnat_node)) == N_Function_Call)
6893 bool outer_atomic_access
6894 = outer_atomic_access_required_p (Name (gnat_node));
6895 bool atomic_access
6896 = !outer_atomic_access
6897 && atomic_access_required_p (Name (gnat_node), &sync);
6898 gnu_result
6899 = Call_to_gnu (Expression (gnat_node), &gnu_result_type, gnu_lhs,
6900 outer_atomic_access, atomic_access, sync);
6902 else
6904 const Node_Id gnat_expr = Expression (gnat_node);
6905 const Entity_Id gnat_type
6906 = Underlying_Type (Etype (Name (gnat_node)));
6907 const bool regular_array_type_p
6908 = (Is_Array_Type (gnat_type) && !Is_Bit_Packed_Array (gnat_type));
6909 const bool use_memset_p
6910 = (regular_array_type_p
6911 && Nkind (gnat_expr) == N_Aggregate
6912 && Is_Others_Aggregate (gnat_expr));
6914 /* If we'll use memset, we need to find the inner expression. */
6915 if (use_memset_p)
6917 Node_Id gnat_inner
6918 = Expression (First (Component_Associations (gnat_expr)));
6919 while (Nkind (gnat_inner) == N_Aggregate
6920 && Is_Others_Aggregate (gnat_inner))
6921 gnat_inner
6922 = Expression (First (Component_Associations (gnat_inner)));
6923 gnu_rhs = gnat_to_gnu (gnat_inner);
6925 else
6926 gnu_rhs = maybe_unconstrained_array (gnat_to_gnu (gnat_expr));
6928 /* If range check is needed, emit code to generate it. */
6929 if (Do_Range_Check (gnat_expr))
6930 gnu_rhs = emit_range_check (gnu_rhs, Etype (Name (gnat_node)),
6931 gnat_node);
6933 /* If an outer atomic access is required on the LHS, build the load-
6934 modify-store sequence. */
6935 if (outer_atomic_access_required_p (Name (gnat_node)))
6936 gnu_result = build_load_modify_store (gnu_lhs, gnu_rhs, gnat_node);
6938 /* Or else, if atomic access is required, build the atomic store. */
6939 else if (atomic_access_required_p (Name (gnat_node), &sync))
6940 gnu_result = build_atomic_store (gnu_lhs, gnu_rhs, sync);
6942 /* Or else, use memset when the conditions are met. */
6943 else if (use_memset_p)
6945 tree value = fold_convert (integer_type_node, gnu_rhs);
6946 tree to = gnu_lhs;
6947 tree type = TREE_TYPE (to);
6948 tree size
6949 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), to);
6950 tree to_ptr = build_fold_addr_expr (to);
6951 tree t = builtin_decl_explicit (BUILT_IN_MEMSET);
6952 if (TREE_CODE (value) == INTEGER_CST)
6954 tree mask
6955 = build_int_cst (integer_type_node,
6956 ((HOST_WIDE_INT) 1 << BITS_PER_UNIT) - 1);
6957 value = int_const_binop (BIT_AND_EXPR, value, mask);
6959 gnu_result = build_call_expr (t, 3, to_ptr, value, size);
6962 /* Otherwise build a regular assignment. */
6963 else
6964 gnu_result
6965 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_lhs, gnu_rhs);
6967 /* If the assignment type is a regular array and the two sides are
6968 not completely disjoint, play safe and use memmove. But don't do
6969 it for a bit-packed array as it might not be byte-aligned. */
6970 if (TREE_CODE (gnu_result) == MODIFY_EXPR
6971 && regular_array_type_p
6972 && !(Forwards_OK (gnat_node) && Backwards_OK (gnat_node)))
6974 tree to = TREE_OPERAND (gnu_result, 0);
6975 tree from = TREE_OPERAND (gnu_result, 1);
6976 tree type = TREE_TYPE (from);
6977 tree size
6978 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), from);
6979 tree to_ptr = build_fold_addr_expr (to);
6980 tree from_ptr = build_fold_addr_expr (from);
6981 tree t = builtin_decl_explicit (BUILT_IN_MEMMOVE);
6982 gnu_result = build_call_expr (t, 3, to_ptr, from_ptr, size);
6985 break;
6987 case N_If_Statement:
6989 tree *gnu_else_ptr; /* Point to put next "else if" or "else". */
6991 /* Make the outer COND_EXPR. Avoid non-determinism. */
6992 gnu_result = build3 (COND_EXPR, void_type_node,
6993 gnat_to_gnu (Condition (gnat_node)),
6994 NULL_TREE, NULL_TREE);
6995 COND_EXPR_THEN (gnu_result)
6996 = build_stmt_group (Then_Statements (gnat_node), false);
6997 TREE_SIDE_EFFECTS (gnu_result) = 1;
6998 gnu_else_ptr = &COND_EXPR_ELSE (gnu_result);
7000 /* Now make a COND_EXPR for each of the "else if" parts. Put each
7001 into the previous "else" part and point to where to put any
7002 outer "else". Also avoid non-determinism. */
7003 if (Present (Elsif_Parts (gnat_node)))
7004 for (gnat_temp = First (Elsif_Parts (gnat_node));
7005 Present (gnat_temp); gnat_temp = Next (gnat_temp))
7007 gnu_expr = build3 (COND_EXPR, void_type_node,
7008 gnat_to_gnu (Condition (gnat_temp)),
7009 NULL_TREE, NULL_TREE);
7010 COND_EXPR_THEN (gnu_expr)
7011 = build_stmt_group (Then_Statements (gnat_temp), false);
7012 TREE_SIDE_EFFECTS (gnu_expr) = 1;
7013 set_expr_location_from_node (gnu_expr, gnat_temp);
7014 *gnu_else_ptr = gnu_expr;
7015 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
7018 *gnu_else_ptr = build_stmt_group (Else_Statements (gnat_node), false);
7020 break;
7022 case N_Case_Statement:
7023 gnu_result = Case_Statement_to_gnu (gnat_node);
7024 break;
7026 case N_Loop_Statement:
7027 gnu_result = Loop_Statement_to_gnu (gnat_node);
7028 break;
7030 case N_Block_Statement:
7031 /* The only way to enter the block is to fall through to it. */
7032 if (stmt_group_may_fallthru ())
7034 start_stmt_group ();
7035 gnat_pushlevel ();
7036 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
7037 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
7038 gnat_poplevel ();
7039 gnu_result = end_stmt_group ();
7041 else
7042 gnu_result = alloc_stmt_list ();
7043 break;
7045 case N_Exit_Statement:
7046 gnu_result
7047 = build2 (EXIT_STMT, void_type_node,
7048 (Present (Condition (gnat_node))
7049 ? gnat_to_gnu (Condition (gnat_node)) : NULL_TREE),
7050 (Present (Name (gnat_node))
7051 ? get_gnu_tree (Entity (Name (gnat_node)))
7052 : LOOP_STMT_LABEL (gnu_loop_stack->last ()->stmt)));
7053 break;
7055 case N_Simple_Return_Statement:
7057 tree gnu_ret_obj, gnu_ret_val;
7059 /* If the subprogram is a function, we must return the expression. */
7060 if (Present (Expression (gnat_node)))
7062 tree gnu_subprog_type = TREE_TYPE (current_function_decl);
7064 /* If this function has copy-in/copy-out parameters parameters and
7065 doesn't return by invisible reference, get the real object for
7066 the return. See Subprogram_Body_to_gnu. */
7067 if (TYPE_CI_CO_LIST (gnu_subprog_type)
7068 && !TREE_ADDRESSABLE (gnu_subprog_type))
7069 gnu_ret_obj = gnu_return_var_stack->last ();
7070 else
7071 gnu_ret_obj = DECL_RESULT (current_function_decl);
7073 /* Get the GCC tree for the expression to be returned. */
7074 gnu_ret_val = gnat_to_gnu (Expression (gnat_node));
7076 /* Do not remove the padding from GNU_RET_VAL if the inner type is
7077 self-referential since we want to allocate the fixed size. */
7078 if (TREE_CODE (gnu_ret_val) == COMPONENT_REF
7079 && type_is_padding_self_referential
7080 (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0))))
7081 gnu_ret_val = TREE_OPERAND (gnu_ret_val, 0);
7083 /* If the function returns by direct reference, return a pointer
7084 to the return value. */
7085 if (TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type)
7086 || By_Ref (gnat_node))
7087 gnu_ret_val = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_ret_val);
7089 /* Otherwise, if it returns an unconstrained array, we have to
7090 allocate a new version of the result and return it. */
7091 else if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type))
7093 gnu_ret_val = maybe_unconstrained_array (gnu_ret_val);
7095 /* And find out whether this is a candidate for Named Return
7096 Value. If so, record it. */
7097 if (!TYPE_CI_CO_LIST (gnu_subprog_type) && optimize)
7099 tree ret_val = gnu_ret_val;
7101 /* Strip useless conversions around the return value. */
7102 if (gnat_useless_type_conversion (ret_val))
7103 ret_val = TREE_OPERAND (ret_val, 0);
7105 /* Strip unpadding around the return value. */
7106 if (TREE_CODE (ret_val) == COMPONENT_REF
7107 && TYPE_IS_PADDING_P
7108 (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
7109 ret_val = TREE_OPERAND (ret_val, 0);
7111 /* Now apply the test to the return value. */
7112 if (return_value_ok_for_nrv_p (NULL_TREE, ret_val))
7114 if (!f_named_ret_val)
7115 f_named_ret_val = BITMAP_GGC_ALLOC ();
7116 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
7117 if (!f_gnat_ret)
7118 f_gnat_ret = gnat_node;
7122 gnu_ret_val = build_allocator (TREE_TYPE (gnu_ret_val),
7123 gnu_ret_val,
7124 TREE_TYPE (gnu_ret_obj),
7125 Procedure_To_Call (gnat_node),
7126 Storage_Pool (gnat_node),
7127 gnat_node, false);
7130 /* Otherwise, if it returns by invisible reference, dereference
7131 the pointer it is passed using the type of the return value
7132 and build the copy operation manually. This ensures that we
7133 don't copy too much data, for example if the return type is
7134 unconstrained with a maximum size. */
7135 else if (TREE_ADDRESSABLE (gnu_subprog_type))
7137 tree gnu_ret_deref
7138 = build_unary_op (INDIRECT_REF, TREE_TYPE (gnu_ret_val),
7139 gnu_ret_obj);
7140 gnu_result = build2 (INIT_EXPR, void_type_node,
7141 gnu_ret_deref, gnu_ret_val);
7142 add_stmt_with_node (gnu_result, gnat_node);
7143 gnu_ret_val = NULL_TREE;
7147 else
7148 gnu_ret_obj = gnu_ret_val = NULL_TREE;
7150 /* If we have a return label defined, convert this into a branch to
7151 that label. The return proper will be handled elsewhere. */
7152 if (gnu_return_label_stack->last ())
7154 if (gnu_ret_val)
7155 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_ret_obj,
7156 gnu_ret_val));
7158 gnu_result = build1 (GOTO_EXPR, void_type_node,
7159 gnu_return_label_stack->last ());
7161 /* When not optimizing, make sure the return is preserved. */
7162 if (!optimize && Comes_From_Source (gnat_node))
7163 DECL_ARTIFICIAL (gnu_return_label_stack->last ()) = 0;
7166 /* Otherwise, build a regular return. */
7167 else
7168 gnu_result = build_return_expr (gnu_ret_obj, gnu_ret_val);
7170 break;
7172 case N_Goto_Statement:
7173 gnu_result
7174 = build1 (GOTO_EXPR, void_type_node, gnat_to_gnu (Name (gnat_node)));
7175 break;
7177 /***************************/
7178 /* Chapter 6: Subprograms */
7179 /***************************/
7181 case N_Subprogram_Declaration:
7182 /* Unless there is a freeze node, declare the subprogram. We consider
7183 this a "definition" even though we're not generating code for
7184 the subprogram because we will be making the corresponding GCC
7185 node here. */
7187 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
7188 gnat_to_gnu_entity (Defining_Entity (Specification (gnat_node)),
7189 NULL_TREE, 1);
7190 gnu_result = alloc_stmt_list ();
7191 break;
7193 case N_Abstract_Subprogram_Declaration:
7194 /* This subprogram doesn't exist for code generation purposes, but we
7195 have to elaborate the types of any parameters and result, unless
7196 they are imported types (nothing to generate in this case).
7198 The parameter list may contain types with freeze nodes, e.g. not null
7199 subtypes, so the subprogram itself may carry a freeze node, in which
7200 case its elaboration must be deferred. */
7202 /* Process the parameter types first. */
7203 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
7204 for (gnat_temp
7205 = First_Formal_With_Extras
7206 (Defining_Entity (Specification (gnat_node)));
7207 Present (gnat_temp);
7208 gnat_temp = Next_Formal_With_Extras (gnat_temp))
7209 if (Is_Itype (Etype (gnat_temp))
7210 && !From_Limited_With (Etype (gnat_temp)))
7211 gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
7213 /* Then the result type, set to Standard_Void_Type for procedures. */
7215 Entity_Id gnat_temp_type
7216 = Etype (Defining_Entity (Specification (gnat_node)));
7218 if (Is_Itype (gnat_temp_type) && !From_Limited_With (gnat_temp_type))
7219 gnat_to_gnu_entity (Etype (gnat_temp_type), NULL_TREE, 0);
7222 gnu_result = alloc_stmt_list ();
7223 break;
7225 case N_Defining_Program_Unit_Name:
7226 /* For a child unit identifier go up a level to get the specification.
7227 We get this when we try to find the spec of a child unit package
7228 that is the compilation unit being compiled. */
7229 gnu_result = gnat_to_gnu (Parent (gnat_node));
7230 break;
7232 case N_Subprogram_Body:
7233 Subprogram_Body_to_gnu (gnat_node);
7234 gnu_result = alloc_stmt_list ();
7235 break;
7237 case N_Function_Call:
7238 case N_Procedure_Call_Statement:
7239 gnu_result = Call_to_gnu (gnat_node, &gnu_result_type, NULL_TREE,
7240 false, false, false);
7241 break;
7243 /************************/
7244 /* Chapter 7: Packages */
7245 /************************/
7247 case N_Package_Declaration:
7248 gnu_result = gnat_to_gnu (Specification (gnat_node));
7249 break;
7251 case N_Package_Specification:
7253 start_stmt_group ();
7254 process_decls (Visible_Declarations (gnat_node),
7255 Private_Declarations (gnat_node), Empty, true, true);
7256 gnu_result = end_stmt_group ();
7257 break;
7259 case N_Package_Body:
7261 /* If this is the body of a generic package - do nothing. */
7262 if (Ekind (Corresponding_Spec (gnat_node)) == E_Generic_Package)
7264 gnu_result = alloc_stmt_list ();
7265 break;
7268 start_stmt_group ();
7269 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
7271 if (Present (Handled_Statement_Sequence (gnat_node)))
7272 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
7274 gnu_result = end_stmt_group ();
7275 break;
7277 /********************************/
7278 /* Chapter 8: Visibility Rules */
7279 /********************************/
7281 case N_Use_Package_Clause:
7282 case N_Use_Type_Clause:
7283 /* Nothing to do here - but these may appear in list of declarations. */
7284 gnu_result = alloc_stmt_list ();
7285 break;
7287 /*********************/
7288 /* Chapter 9: Tasks */
7289 /*********************/
7291 case N_Protected_Type_Declaration:
7292 gnu_result = alloc_stmt_list ();
7293 break;
7295 case N_Single_Task_Declaration:
7296 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
7297 gnu_result = alloc_stmt_list ();
7298 break;
7300 /*********************************************************/
7301 /* Chapter 10: Program Structure and Compilation Issues */
7302 /*********************************************************/
7304 case N_Compilation_Unit:
7305 /* This is not called for the main unit on which gigi is invoked. */
7306 Compilation_Unit_to_gnu (gnat_node);
7307 gnu_result = alloc_stmt_list ();
7308 break;
7310 case N_Subunit:
7311 gnu_result = gnat_to_gnu (Proper_Body (gnat_node));
7312 break;
7314 case N_Entry_Body:
7315 case N_Protected_Body:
7316 case N_Task_Body:
7317 /* These nodes should only be present when annotating types. */
7318 gcc_assert (type_annotate_only);
7319 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
7320 gnu_result = alloc_stmt_list ();
7321 break;
7323 case N_Subprogram_Body_Stub:
7324 case N_Package_Body_Stub:
7325 case N_Protected_Body_Stub:
7326 case N_Task_Body_Stub:
7327 /* Simply process whatever unit is being inserted. */
7328 if (Present (Library_Unit (gnat_node)))
7329 gnu_result = gnat_to_gnu (Unit (Library_Unit (gnat_node)));
7330 else
7332 gcc_assert (type_annotate_only);
7333 gnu_result = alloc_stmt_list ();
7335 break;
7337 /***************************/
7338 /* Chapter 11: Exceptions */
7339 /***************************/
7341 case N_Handled_Sequence_Of_Statements:
7342 /* If there is an At_End procedure attached to this node, and the EH
7343 mechanism is front-end, we must have at least a corresponding At_End
7344 handler, unless the No_Exception_Handlers restriction is set. */
7345 gcc_assert (type_annotate_only
7346 || !Front_End_Exceptions ()
7347 || No (At_End_Proc (gnat_node))
7348 || Present (Exception_Handlers (gnat_node))
7349 || No_Exception_Handlers_Set ());
7351 gnu_result = Handled_Sequence_Of_Statements_to_gnu (gnat_node);
7352 break;
7354 case N_Exception_Handler:
7355 if (Exception_Mechanism == Front_End_SJLJ)
7356 gnu_result = Exception_Handler_to_gnu_fe_sjlj (gnat_node);
7357 else if (Back_End_Exceptions ())
7358 gnu_result = Exception_Handler_to_gnu_gcc (gnat_node);
7359 else
7360 gcc_unreachable ();
7361 break;
7363 case N_Raise_Statement:
7364 /* Only for reraise in back-end exceptions mode. */
7365 gcc_assert (No (Name (gnat_node))
7366 && Back_End_Exceptions ());
7368 start_stmt_group ();
7369 gnat_pushlevel ();
7371 /* Clear the current exception pointer so that the occurrence won't be
7372 deallocated. */
7373 gnu_expr = create_var_decl (get_identifier ("SAVED_EXPTR"), NULL_TREE,
7374 ptr_type_node, gnu_incoming_exc_ptr,
7375 false, false, false, false, false,
7376 true, true, NULL, gnat_node);
7378 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_incoming_exc_ptr,
7379 convert (ptr_type_node, integer_zero_node)));
7380 add_stmt (build_call_n_expr (reraise_zcx_decl, 1, gnu_expr));
7381 gnat_poplevel ();
7382 gnu_result = end_stmt_group ();
7383 break;
7385 case N_Push_Constraint_Error_Label:
7386 push_exception_label_stack (&gnu_constraint_error_label_stack,
7387 Exception_Label (gnat_node));
7388 break;
7390 case N_Push_Storage_Error_Label:
7391 push_exception_label_stack (&gnu_storage_error_label_stack,
7392 Exception_Label (gnat_node));
7393 break;
7395 case N_Push_Program_Error_Label:
7396 push_exception_label_stack (&gnu_program_error_label_stack,
7397 Exception_Label (gnat_node));
7398 break;
7400 case N_Pop_Constraint_Error_Label:
7401 gnu_constraint_error_label_stack->pop ();
7402 break;
7404 case N_Pop_Storage_Error_Label:
7405 gnu_storage_error_label_stack->pop ();
7406 break;
7408 case N_Pop_Program_Error_Label:
7409 gnu_program_error_label_stack->pop ();
7410 break;
7412 /******************************/
7413 /* Chapter 12: Generic Units */
7414 /******************************/
7416 case N_Generic_Function_Renaming_Declaration:
7417 case N_Generic_Package_Renaming_Declaration:
7418 case N_Generic_Procedure_Renaming_Declaration:
7419 case N_Generic_Package_Declaration:
7420 case N_Generic_Subprogram_Declaration:
7421 case N_Package_Instantiation:
7422 case N_Procedure_Instantiation:
7423 case N_Function_Instantiation:
7424 /* These nodes can appear on a declaration list but there is nothing to
7425 to be done with them. */
7426 gnu_result = alloc_stmt_list ();
7427 break;
7429 /**************************************************/
7430 /* Chapter 13: Representation Clauses and */
7431 /* Implementation-Dependent Features */
7432 /**************************************************/
7434 case N_Attribute_Definition_Clause:
7435 gnu_result = alloc_stmt_list ();
7437 /* The only one we need to deal with is 'Address since, for the others,
7438 the front-end puts the information elsewhere. */
7439 if (Get_Attribute_Id (Chars (gnat_node)) != Attr_Address)
7440 break;
7442 /* And we only deal with 'Address if the object has a Freeze node. */
7443 gnat_temp = Entity (Name (gnat_node));
7444 if (No (Freeze_Node (gnat_temp)))
7445 break;
7447 /* Get the value to use as the address and save it as the equivalent
7448 for the object. When it is frozen, gnat_to_gnu_entity will do the
7449 right thing. */
7450 save_gnu_tree (gnat_temp, gnat_to_gnu (Expression (gnat_node)), true);
7451 break;
7453 case N_Enumeration_Representation_Clause:
7454 case N_Record_Representation_Clause:
7455 case N_At_Clause:
7456 /* We do nothing with these. SEM puts the information elsewhere. */
7457 gnu_result = alloc_stmt_list ();
7458 break;
7460 case N_Code_Statement:
7461 if (!type_annotate_only)
7463 tree gnu_template = gnat_to_gnu (Asm_Template (gnat_node));
7464 tree gnu_inputs = NULL_TREE, gnu_outputs = NULL_TREE;
7465 tree gnu_clobbers = NULL_TREE, tail;
7466 bool allows_mem, allows_reg, fake;
7467 int ninputs, noutputs, i;
7468 const char **oconstraints;
7469 const char *constraint;
7470 char *clobber;
7472 /* First retrieve the 3 operand lists built by the front-end. */
7473 Setup_Asm_Outputs (gnat_node);
7474 while (Present (gnat_temp = Asm_Output_Variable ()))
7476 tree gnu_value = gnat_to_gnu (gnat_temp);
7477 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
7478 (Asm_Output_Constraint ()));
7480 gnu_outputs = tree_cons (gnu_constr, gnu_value, gnu_outputs);
7481 Next_Asm_Output ();
7484 Setup_Asm_Inputs (gnat_node);
7485 while (Present (gnat_temp = Asm_Input_Value ()))
7487 tree gnu_value = gnat_to_gnu (gnat_temp);
7488 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
7489 (Asm_Input_Constraint ()));
7491 gnu_inputs = tree_cons (gnu_constr, gnu_value, gnu_inputs);
7492 Next_Asm_Input ();
7495 Clobber_Setup (gnat_node);
7496 while ((clobber = Clobber_Get_Next ()))
7497 gnu_clobbers
7498 = tree_cons (NULL_TREE,
7499 build_string (strlen (clobber) + 1, clobber),
7500 gnu_clobbers);
7502 /* Then perform some standard checking and processing on the
7503 operands. In particular, mark them addressable if needed. */
7504 gnu_outputs = nreverse (gnu_outputs);
7505 noutputs = list_length (gnu_outputs);
7506 gnu_inputs = nreverse (gnu_inputs);
7507 ninputs = list_length (gnu_inputs);
7508 oconstraints = XALLOCAVEC (const char *, noutputs);
7510 for (i = 0, tail = gnu_outputs; tail; ++i, tail = TREE_CHAIN (tail))
7512 tree output = TREE_VALUE (tail);
7513 constraint
7514 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
7515 oconstraints[i] = constraint;
7517 if (parse_output_constraint (&constraint, i, ninputs, noutputs,
7518 &allows_mem, &allows_reg, &fake))
7520 /* If the operand is going to end up in memory,
7521 mark it addressable. Note that we don't test
7522 allows_mem like in the input case below; this
7523 is modelled on the C front-end. */
7524 if (!allows_reg)
7526 output = remove_conversions (output, false);
7527 if (TREE_CODE (output) == CONST_DECL
7528 && DECL_CONST_CORRESPONDING_VAR (output))
7529 output = DECL_CONST_CORRESPONDING_VAR (output);
7530 if (!gnat_mark_addressable (output))
7531 output = error_mark_node;
7534 else
7535 output = error_mark_node;
7537 TREE_VALUE (tail) = output;
7540 for (i = 0, tail = gnu_inputs; tail; ++i, tail = TREE_CHAIN (tail))
7542 tree input = TREE_VALUE (tail);
7543 constraint
7544 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
7546 if (parse_input_constraint (&constraint, i, ninputs, noutputs,
7547 0, oconstraints,
7548 &allows_mem, &allows_reg))
7550 /* If the operand is going to end up in memory,
7551 mark it addressable. */
7552 if (!allows_reg && allows_mem)
7554 input = remove_conversions (input, false);
7555 if (TREE_CODE (input) == CONST_DECL
7556 && DECL_CONST_CORRESPONDING_VAR (input))
7557 input = DECL_CONST_CORRESPONDING_VAR (input);
7558 if (!gnat_mark_addressable (input))
7559 input = error_mark_node;
7562 else
7563 input = error_mark_node;
7565 TREE_VALUE (tail) = input;
7568 gnu_result = build5 (ASM_EXPR, void_type_node,
7569 gnu_template, gnu_outputs,
7570 gnu_inputs, gnu_clobbers, NULL_TREE);
7571 ASM_VOLATILE_P (gnu_result) = Is_Asm_Volatile (gnat_node);
7573 else
7574 gnu_result = alloc_stmt_list ();
7576 break;
7578 /****************/
7579 /* Added Nodes */
7580 /****************/
7582 case N_Expression_With_Actions:
7583 /* This construct doesn't define a scope so we don't push a binding
7584 level around the statement list, but we wrap it in a SAVE_EXPR to
7585 protect it from unsharing. Elaborate the expression as part of the
7586 same statement group as the actions so that the type declaration
7587 gets inserted there as well. This ensures that the type elaboration
7588 code is issued past the actions computing values on which it might
7589 depend. */
7590 start_stmt_group ();
7591 add_stmt_list (Actions (gnat_node));
7592 gnu_expr = gnat_to_gnu (Expression (gnat_node));
7593 gnu_result = end_stmt_group ();
7595 gnu_result = build1 (SAVE_EXPR, void_type_node, gnu_result);
7596 TREE_SIDE_EFFECTS (gnu_result) = 1;
7598 gnu_result
7599 = build_compound_expr (TREE_TYPE (gnu_expr), gnu_result, gnu_expr);
7600 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7601 break;
7603 case N_Freeze_Entity:
7604 start_stmt_group ();
7605 process_freeze_entity (gnat_node);
7606 process_decls (Actions (gnat_node), Empty, Empty, true, true);
7607 gnu_result = end_stmt_group ();
7608 break;
7610 case N_Freeze_Generic_Entity:
7611 gnu_result = alloc_stmt_list ();
7612 break;
7614 case N_Itype_Reference:
7615 if (!present_gnu_tree (Itype (gnat_node)))
7616 process_type (Itype (gnat_node));
7618 gnu_result = alloc_stmt_list ();
7619 break;
7621 case N_Free_Statement:
7622 if (!type_annotate_only)
7624 tree gnu_ptr = gnat_to_gnu (Expression (gnat_node));
7625 tree gnu_ptr_type = TREE_TYPE (gnu_ptr);
7626 tree gnu_obj_type, gnu_actual_obj_type;
7628 /* If this is a thin pointer, we must first dereference it to create
7629 a fat pointer, then go back below to a thin pointer. The reason
7630 for this is that we need to have a fat pointer someplace in order
7631 to properly compute the size. */
7632 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
7633 gnu_ptr = build_unary_op (ADDR_EXPR, NULL_TREE,
7634 build_unary_op (INDIRECT_REF, NULL_TREE,
7635 gnu_ptr));
7637 /* If this is a fat pointer, the object must have been allocated with
7638 the template in front of the array. So pass the template address,
7639 and get the total size; do it by converting to a thin pointer. */
7640 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
7641 gnu_ptr
7642 = convert (build_pointer_type
7643 (TYPE_OBJECT_RECORD_TYPE
7644 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
7645 gnu_ptr);
7647 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
7649 /* If this is a thin pointer, the object must have been allocated with
7650 the template in front of the array. So pass the template address,
7651 and get the total size. */
7652 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
7653 gnu_ptr
7654 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
7655 gnu_ptr,
7656 fold_build1 (NEGATE_EXPR, sizetype,
7657 byte_position
7658 (DECL_CHAIN
7659 TYPE_FIELDS ((gnu_obj_type)))));
7661 /* If we have a special dynamic constrained subtype on the node, use
7662 it to compute the size; otherwise, use the designated subtype. */
7663 if (Present (Actual_Designated_Subtype (gnat_node)))
7665 gnu_actual_obj_type
7666 = gnat_to_gnu_type (Actual_Designated_Subtype (gnat_node));
7668 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
7669 gnu_actual_obj_type
7670 = build_unc_object_type_from_ptr (gnu_ptr_type,
7671 gnu_actual_obj_type,
7672 get_identifier ("DEALLOC"),
7673 false);
7675 else
7676 gnu_actual_obj_type = gnu_obj_type;
7678 gnu_result
7679 = build_call_alloc_dealloc (gnu_ptr,
7680 TYPE_SIZE_UNIT (gnu_actual_obj_type),
7681 gnu_obj_type,
7682 Procedure_To_Call (gnat_node),
7683 Storage_Pool (gnat_node),
7684 gnat_node);
7686 break;
7688 case N_Raise_Constraint_Error:
7689 case N_Raise_Program_Error:
7690 case N_Raise_Storage_Error:
7691 if (type_annotate_only)
7692 gnu_result = alloc_stmt_list ();
7693 else
7694 gnu_result = Raise_Error_to_gnu (gnat_node, &gnu_result_type);
7695 break;
7697 case N_Validate_Unchecked_Conversion:
7698 /* The only validation we currently do on an unchecked conversion is
7699 that of aliasing assumptions. */
7700 if (flag_strict_aliasing)
7701 gnat_validate_uc_list.safe_push (gnat_node);
7702 gnu_result = alloc_stmt_list ();
7703 break;
7705 case N_Function_Specification:
7706 case N_Procedure_Specification:
7707 case N_Op_Concat:
7708 case N_Component_Association:
7709 /* These nodes should only be present when annotating types. */
7710 gcc_assert (type_annotate_only);
7711 gnu_result = alloc_stmt_list ();
7712 break;
7714 default:
7715 /* Other nodes are not supposed to reach here. */
7716 gcc_unreachable ();
7719 /* If we pushed the processing of the elaboration routine, pop it back. */
7720 if (went_into_elab_proc)
7721 current_function_decl = NULL_TREE;
7723 /* When not optimizing, turn boolean rvalues B into B != false tests
7724 so that the code just below can put the location information of the
7725 reference to B on the inequality operator for better debug info. */
7726 if (!optimize
7727 && TREE_CODE (gnu_result) != INTEGER_CST
7728 && (kind == N_Identifier
7729 || kind == N_Expanded_Name
7730 || kind == N_Explicit_Dereference
7731 || kind == N_Function_Call
7732 || kind == N_Indexed_Component
7733 || kind == N_Selected_Component)
7734 && TREE_CODE (get_base_type (gnu_result_type)) == BOOLEAN_TYPE
7735 && !lvalue_required_p (gnat_node, gnu_result_type, false, false, false))
7736 gnu_result = build_binary_op (NE_EXPR, gnu_result_type,
7737 convert (gnu_result_type, gnu_result),
7738 convert (gnu_result_type,
7739 boolean_false_node));
7741 /* Set the location information on the result. Note that we may have
7742 no result if we tried to build a CALL_EXPR node to a procedure with
7743 no side-effects and optimization is enabled. */
7744 if (gnu_result && EXPR_P (gnu_result))
7745 set_gnu_expr_location_from_node (gnu_result, gnat_node);
7747 /* If we're supposed to return something of void_type, it means we have
7748 something we're elaborating for effect, so just return. */
7749 if (TREE_CODE (gnu_result_type) == VOID_TYPE)
7750 return gnu_result;
7752 /* If the result is a constant that overflowed, raise Constraint_Error. */
7753 if (TREE_CODE (gnu_result) == INTEGER_CST && TREE_OVERFLOW (gnu_result))
7755 post_error ("?`Constraint_Error` will be raised at run time", gnat_node);
7756 gnu_result
7757 = build1 (NULL_EXPR, gnu_result_type,
7758 build_call_raise (CE_Overflow_Check_Failed, gnat_node,
7759 N_Raise_Constraint_Error));
7762 /* If the result has side-effects and is of an unconstrained type, make a
7763 SAVE_EXPR so that we can be sure it will only be referenced once. But
7764 this is useless for a call to a function that returns an unconstrained
7765 type with default discriminant, as we cannot compute the size of the
7766 actual returned object. We must do this before any conversions. */
7767 if (TREE_SIDE_EFFECTS (gnu_result)
7768 && !(TREE_CODE (gnu_result) == CALL_EXPR
7769 && type_is_padding_self_referential (TREE_TYPE (gnu_result)))
7770 && (TREE_CODE (gnu_result_type) == UNCONSTRAINED_ARRAY_TYPE
7771 || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))))
7772 gnu_result = gnat_protect_expr (gnu_result);
7774 /* Now convert the result to the result type, unless we are in one of the
7775 following cases:
7777 1. If this is the LHS of an assignment or an actual parameter of a
7778 call, return the result almost unmodified since the RHS will have
7779 to be converted to our type in that case, unless the result type
7780 has a simpler size. Likewise if there is just a no-op unchecked
7781 conversion in-between. Similarly, don't convert integral types
7782 that are the operands of an unchecked conversion since we need
7783 to ignore those conversions (for 'Valid).
7785 2. If we have a label (which doesn't have any well-defined type), a
7786 field or an error, return the result almost unmodified. Similarly,
7787 if the two types are record types with the same name, don't convert.
7788 This will be the case when we are converting from a packable version
7789 of a type to its original type and we need those conversions to be
7790 NOPs in order for assignments into these types to work properly.
7792 3. If the type is void or if we have no result, return error_mark_node
7793 to show we have no result.
7795 4. If this is a call to a function that returns with variable size and
7796 the call is used as the expression in either an object or a renaming
7797 declaration, return the result unmodified because we want to use the
7798 return slot optimization in this case.
7800 5. Finally, if the type of the result is already correct. */
7802 if (Present (Parent (gnat_node))
7803 && (lhs_or_actual_p (gnat_node)
7804 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
7805 && unchecked_conversion_nop (Parent (gnat_node)))
7806 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
7807 && !AGGREGATE_TYPE_P (gnu_result_type)
7808 && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))))
7809 && !(TYPE_SIZE (gnu_result_type)
7810 && TYPE_SIZE (TREE_TYPE (gnu_result))
7811 && (AGGREGATE_TYPE_P (gnu_result_type)
7812 == AGGREGATE_TYPE_P (TREE_TYPE (gnu_result)))
7813 && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) == INTEGER_CST
7814 && (TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_result)))
7815 != INTEGER_CST))
7816 || (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
7817 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))
7818 && (CONTAINS_PLACEHOLDER_P
7819 (TYPE_SIZE (TREE_TYPE (gnu_result))))))
7820 && !(TREE_CODE (gnu_result_type) == RECORD_TYPE
7821 && TYPE_JUSTIFIED_MODULAR_P (gnu_result_type))))
7823 /* Remove padding only if the inner object is of self-referential
7824 size: in that case it must be an object of unconstrained type
7825 with a default discriminant and we want to avoid copying too
7826 much data. */
7827 if (type_is_padding_self_referential (TREE_TYPE (gnu_result)))
7828 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
7829 gnu_result);
7832 else if (TREE_CODE (gnu_result) == LABEL_DECL
7833 || TREE_CODE (gnu_result) == FIELD_DECL
7834 || TREE_CODE (gnu_result) == ERROR_MARK
7835 || (TYPE_NAME (gnu_result_type)
7836 == TYPE_NAME (TREE_TYPE (gnu_result))
7837 && TREE_CODE (gnu_result_type) == RECORD_TYPE
7838 && TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE))
7840 /* Remove any padding. */
7841 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
7842 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
7843 gnu_result);
7846 else if (gnu_result == error_mark_node || gnu_result_type == void_type_node)
7847 gnu_result = error_mark_node;
7849 else if (Present (Parent (gnat_node))
7850 && (Nkind (Parent (gnat_node)) == N_Object_Declaration
7851 || Nkind (Parent (gnat_node)) == N_Object_Renaming_Declaration)
7852 && TREE_CODE (gnu_result) == CALL_EXPR
7853 && return_type_with_variable_size_p (TREE_TYPE (gnu_result)))
7856 else if (TREE_TYPE (gnu_result) != gnu_result_type)
7857 gnu_result = convert (gnu_result_type, gnu_result);
7859 /* We don't need any NOP_EXPR or NON_LVALUE_EXPR on the result. */
7860 while ((TREE_CODE (gnu_result) == NOP_EXPR
7861 || TREE_CODE (gnu_result) == NON_LVALUE_EXPR)
7862 && TREE_TYPE (TREE_OPERAND (gnu_result, 0)) == TREE_TYPE (gnu_result))
7863 gnu_result = TREE_OPERAND (gnu_result, 0);
7865 return gnu_result;
7868 /* Subroutine of above to push the exception label stack. GNU_STACK is
7869 a pointer to the stack to update and GNAT_LABEL, if present, is the
7870 label to push onto the stack. */
7872 static void
7873 push_exception_label_stack (vec<tree, va_gc> **gnu_stack, Entity_Id gnat_label)
7875 tree gnu_label = (Present (gnat_label)
7876 ? gnat_to_gnu_entity (gnat_label, NULL_TREE, 0)
7877 : NULL_TREE);
7879 vec_safe_push (*gnu_stack, gnu_label);
7882 /* Record the current code position in GNAT_NODE. */
7884 static void
7885 record_code_position (Node_Id gnat_node)
7887 tree stmt_stmt = build1 (STMT_STMT, void_type_node, NULL_TREE);
7889 add_stmt_with_node (stmt_stmt, gnat_node);
7890 save_gnu_tree (gnat_node, stmt_stmt, true);
7893 /* Insert the code for GNAT_NODE at the position saved for that node. */
7895 static void
7896 insert_code_for (Node_Id gnat_node)
7898 STMT_STMT_STMT (get_gnu_tree (gnat_node)) = gnat_to_gnu (gnat_node);
7899 save_gnu_tree (gnat_node, NULL_TREE, true);
7902 /* Start a new statement group chained to the previous group. */
7904 void
7905 start_stmt_group (void)
7907 struct stmt_group *group = stmt_group_free_list;
7909 /* First see if we can get one from the free list. */
7910 if (group)
7911 stmt_group_free_list = group->previous;
7912 else
7913 group = ggc_alloc<stmt_group> ();
7915 group->previous = current_stmt_group;
7916 group->stmt_list = group->block = group->cleanups = NULL_TREE;
7917 current_stmt_group = group;
7920 /* Add GNU_STMT to the current statement group. If it is an expression with
7921 no effects, it is ignored. */
7923 void
7924 add_stmt (tree gnu_stmt)
7926 append_to_statement_list (gnu_stmt, &current_stmt_group->stmt_list);
7929 /* Similar, but the statement is always added, regardless of side-effects. */
7931 void
7932 add_stmt_force (tree gnu_stmt)
7934 append_to_statement_list_force (gnu_stmt, &current_stmt_group->stmt_list);
7937 /* Like add_stmt, but set the location of GNU_STMT to that of GNAT_NODE. */
7939 void
7940 add_stmt_with_node (tree gnu_stmt, Node_Id gnat_node)
7942 /* Do not emit a location for renamings that come from generic instantiation,
7943 they are likely to disturb debugging. */
7944 if (Present (gnat_node)
7945 && !renaming_from_generic_instantiation_p (gnat_node))
7946 set_expr_location_from_node (gnu_stmt, gnat_node);
7947 add_stmt (gnu_stmt);
7950 /* Similar, but the statement is always added, regardless of side-effects. */
7952 void
7953 add_stmt_with_node_force (tree gnu_stmt, Node_Id gnat_node)
7955 if (Present (gnat_node))
7956 set_expr_location_from_node (gnu_stmt, gnat_node);
7957 add_stmt_force (gnu_stmt);
7960 /* Add a declaration statement for GNU_DECL to the current statement group.
7961 Get SLOC from Entity_Id. */
7963 void
7964 add_decl_expr (tree gnu_decl, Entity_Id gnat_entity)
7966 tree type = TREE_TYPE (gnu_decl);
7967 tree gnu_stmt, gnu_init, t;
7969 /* If this is a variable that Gigi is to ignore, we may have been given
7970 an ERROR_MARK. So test for it. We also might have been given a
7971 reference for a renaming. So only do something for a decl. Also
7972 ignore a TYPE_DECL for an UNCONSTRAINED_ARRAY_TYPE. */
7973 if (!DECL_P (gnu_decl)
7974 || (TREE_CODE (gnu_decl) == TYPE_DECL
7975 && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE))
7976 return;
7978 gnu_stmt = build1 (DECL_EXPR, void_type_node, gnu_decl);
7980 /* If we are external or global, we don't want to output the DECL_EXPR for
7981 this DECL node since we already have evaluated the expressions in the
7982 sizes and positions as globals and doing it again would be wrong. */
7983 if (DECL_EXTERNAL (gnu_decl) || global_bindings_p ())
7985 /* Mark everything as used to prevent node sharing with subprograms.
7986 Note that walk_tree knows how to deal with TYPE_DECL, but neither
7987 VAR_DECL nor CONST_DECL. This appears to be somewhat arbitrary. */
7988 MARK_VISITED (gnu_stmt);
7989 if (TREE_CODE (gnu_decl) == VAR_DECL
7990 || TREE_CODE (gnu_decl) == CONST_DECL)
7992 MARK_VISITED (DECL_SIZE (gnu_decl));
7993 MARK_VISITED (DECL_SIZE_UNIT (gnu_decl));
7994 MARK_VISITED (DECL_INITIAL (gnu_decl));
7996 /* In any case, we have to deal with our own TYPE_ADA_SIZE field. */
7997 else if (TREE_CODE (gnu_decl) == TYPE_DECL
7998 && RECORD_OR_UNION_TYPE_P (type)
7999 && !TYPE_FAT_POINTER_P (type))
8000 MARK_VISITED (TYPE_ADA_SIZE (type));
8002 else
8003 add_stmt_with_node (gnu_stmt, gnat_entity);
8005 /* If this is a variable and an initializer is attached to it, it must be
8006 valid for the context. Similar to init_const in create_var_decl. */
8007 if (TREE_CODE (gnu_decl) == VAR_DECL
8008 && (gnu_init = DECL_INITIAL (gnu_decl)) != NULL_TREE
8009 && (!gnat_types_compatible_p (type, TREE_TYPE (gnu_init))
8010 || (TREE_STATIC (gnu_decl)
8011 && !initializer_constant_valid_p (gnu_init,
8012 TREE_TYPE (gnu_init)))))
8014 /* If GNU_DECL has a padded type, convert it to the unpadded
8015 type so the assignment is done properly. */
8016 if (TYPE_IS_PADDING_P (type))
8017 t = convert (TREE_TYPE (TYPE_FIELDS (type)), gnu_decl);
8018 else
8019 t = gnu_decl;
8021 gnu_stmt = build_binary_op (INIT_EXPR, NULL_TREE, t, gnu_init);
8023 DECL_INITIAL (gnu_decl) = NULL_TREE;
8024 if (TREE_READONLY (gnu_decl))
8026 TREE_READONLY (gnu_decl) = 0;
8027 DECL_READONLY_ONCE_ELAB (gnu_decl) = 1;
8030 add_stmt_with_node (gnu_stmt, gnat_entity);
8034 /* Callback for walk_tree to mark the visited trees rooted at *TP. */
8036 static tree
8037 mark_visited_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
8039 tree t = *tp;
8041 if (TREE_VISITED (t))
8042 *walk_subtrees = 0;
8044 /* Don't mark a dummy type as visited because we want to mark its sizes
8045 and fields once it's filled in. */
8046 else if (!TYPE_IS_DUMMY_P (t))
8047 TREE_VISITED (t) = 1;
8049 if (TYPE_P (t))
8050 TYPE_SIZES_GIMPLIFIED (t) = 1;
8052 return NULL_TREE;
8055 /* Mark nodes rooted at T with TREE_VISITED and types as having their
8056 sized gimplified. We use this to indicate all variable sizes and
8057 positions in global types may not be shared by any subprogram. */
8059 void
8060 mark_visited (tree t)
8062 walk_tree (&t, mark_visited_r, NULL, NULL);
8065 /* Add GNU_CLEANUP, a cleanup action, to the current code group and
8066 set its location to that of GNAT_NODE if present, but with column info
8067 cleared so that conditional branches generated as part of the cleanup
8068 code do not interfere with coverage analysis tools. */
8070 static void
8071 add_cleanup (tree gnu_cleanup, Node_Id gnat_node)
8073 if (Present (gnat_node))
8074 set_expr_location_from_node (gnu_cleanup, gnat_node, true);
8075 append_to_statement_list (gnu_cleanup, &current_stmt_group->cleanups);
8078 /* Set the BLOCK node corresponding to the current code group to GNU_BLOCK. */
8080 void
8081 set_block_for_group (tree gnu_block)
8083 gcc_assert (!current_stmt_group->block);
8084 current_stmt_group->block = gnu_block;
8087 /* Return code corresponding to the current code group. It is normally
8088 a STATEMENT_LIST, but may also be a BIND_EXPR or TRY_FINALLY_EXPR if
8089 BLOCK or cleanups were set. */
8091 tree
8092 end_stmt_group (void)
8094 struct stmt_group *group = current_stmt_group;
8095 tree gnu_retval = group->stmt_list;
8097 /* If this is a null list, allocate a new STATEMENT_LIST. Then, if there
8098 are cleanups, make a TRY_FINALLY_EXPR. Last, if there is a BLOCK,
8099 make a BIND_EXPR. Note that we nest in that because the cleanup may
8100 reference variables in the block. */
8101 if (gnu_retval == NULL_TREE)
8102 gnu_retval = alloc_stmt_list ();
8104 if (group->cleanups)
8105 gnu_retval = build2 (TRY_FINALLY_EXPR, void_type_node, gnu_retval,
8106 group->cleanups);
8108 if (current_stmt_group->block)
8109 gnu_retval = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (group->block),
8110 gnu_retval, group->block);
8112 /* Remove this group from the stack and add it to the free list. */
8113 current_stmt_group = group->previous;
8114 group->previous = stmt_group_free_list;
8115 stmt_group_free_list = group;
8117 return gnu_retval;
8120 /* Return whether the current statement group may fall through. */
8122 static inline bool
8123 stmt_group_may_fallthru (void)
8125 if (current_stmt_group->stmt_list)
8126 return block_may_fallthru (current_stmt_group->stmt_list);
8127 else
8128 return true;
8131 /* Add a list of statements from GNAT_LIST, a possibly-empty list of
8132 statements.*/
8134 static void
8135 add_stmt_list (List_Id gnat_list)
8137 Node_Id gnat_node;
8139 if (Present (gnat_list))
8140 for (gnat_node = First (gnat_list); Present (gnat_node);
8141 gnat_node = Next (gnat_node))
8142 add_stmt (gnat_to_gnu (gnat_node));
8145 /* Build a tree from GNAT_LIST, a possibly-empty list of statements.
8146 If BINDING_P is true, push and pop a binding level around the list. */
8148 static tree
8149 build_stmt_group (List_Id gnat_list, bool binding_p)
8151 start_stmt_group ();
8153 if (binding_p)
8154 gnat_pushlevel ();
8156 add_stmt_list (gnat_list);
8158 if (binding_p)
8159 gnat_poplevel ();
8161 return end_stmt_group ();
8164 /* Generate GIMPLE in place for the expression at *EXPR_P. */
8167 gnat_gimplify_expr (tree *expr_p, gimple_seq *pre_p,
8168 gimple_seq *post_p ATTRIBUTE_UNUSED)
8170 tree expr = *expr_p;
8171 tree type = TREE_TYPE (expr);
8172 tree op;
8174 if (IS_ADA_STMT (expr))
8175 return gnat_gimplify_stmt (expr_p);
8177 switch (TREE_CODE (expr))
8179 case NULL_EXPR:
8180 /* If this is an aggregate type, build a null pointer of the appropriate
8181 type and dereference it. */
8182 if (AGGREGATE_TYPE_P (type)
8183 || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
8184 *expr_p = build_unary_op (INDIRECT_REF, NULL_TREE,
8185 convert (build_pointer_type (type),
8186 integer_zero_node));
8187 /* Otherwise, just make a VAR_DECL. */
8188 else
8190 *expr_p = create_tmp_var (type, NULL);
8191 TREE_NO_WARNING (*expr_p) = 1;
8194 gimplify_and_add (TREE_OPERAND (expr, 0), pre_p);
8195 return GS_OK;
8197 case UNCONSTRAINED_ARRAY_REF:
8198 /* We should only do this if we are just elaborating for side-effects,
8199 but we can't know that yet. */
8200 *expr_p = TREE_OPERAND (*expr_p, 0);
8201 return GS_OK;
8203 case ADDR_EXPR:
8204 op = TREE_OPERAND (expr, 0);
8206 /* If we are taking the address of a constant CONSTRUCTOR, make sure it
8207 is put into static memory. We know that it's going to be read-only
8208 given the semantics we have and it must be in static memory when the
8209 reference is in an elaboration procedure. */
8210 if (TREE_CODE (op) == CONSTRUCTOR && TREE_CONSTANT (op))
8212 tree addr = build_fold_addr_expr (tree_output_constant_def (op));
8213 *expr_p = fold_convert (type, addr);
8214 return GS_ALL_DONE;
8217 /* Replace atomic loads with their first argument. That's necessary
8218 because the gimplifier would create a temporary otherwise. */
8219 if (TREE_SIDE_EFFECTS (op))
8220 while (handled_component_p (op) || CONVERT_EXPR_P (op))
8222 tree inner = TREE_OPERAND (op, 0);
8223 if (TREE_CODE (inner) == CALL_EXPR && call_is_atomic_load (inner))
8225 tree t = CALL_EXPR_ARG (inner, 0);
8226 if (TREE_CODE (t) == NOP_EXPR)
8227 t = TREE_OPERAND (t, 0);
8228 if (TREE_CODE (t) == ADDR_EXPR)
8229 TREE_OPERAND (op, 0) = TREE_OPERAND (t, 0);
8230 else
8231 TREE_OPERAND (op, 0) = build_fold_indirect_ref (t);
8233 else
8234 op = inner;
8237 return GS_UNHANDLED;
8239 case VIEW_CONVERT_EXPR:
8240 op = TREE_OPERAND (expr, 0);
8242 /* If we are view-converting a CONSTRUCTOR or a call from an aggregate
8243 type to a scalar one, explicitly create the local temporary. That's
8244 required if the type is passed by reference. */
8245 if ((TREE_CODE (op) == CONSTRUCTOR || TREE_CODE (op) == CALL_EXPR)
8246 && AGGREGATE_TYPE_P (TREE_TYPE (op))
8247 && !AGGREGATE_TYPE_P (type))
8249 tree mod, new_var = create_tmp_var_raw (TREE_TYPE (op), "C");
8250 gimple_add_tmp_var (new_var);
8252 mod = build2 (INIT_EXPR, TREE_TYPE (new_var), new_var, op);
8253 gimplify_and_add (mod, pre_p);
8255 TREE_OPERAND (expr, 0) = new_var;
8256 return GS_OK;
8259 return GS_UNHANDLED;
8261 case DECL_EXPR:
8262 op = DECL_EXPR_DECL (expr);
8264 /* The expressions for the RM bounds must be gimplified to ensure that
8265 they are properly elaborated. See gimplify_decl_expr. */
8266 if ((TREE_CODE (op) == TYPE_DECL || TREE_CODE (op) == VAR_DECL)
8267 && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (op)))
8268 switch (TREE_CODE (TREE_TYPE (op)))
8270 case INTEGER_TYPE:
8271 case ENUMERAL_TYPE:
8272 case BOOLEAN_TYPE:
8273 case REAL_TYPE:
8275 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (op)), t, val;
8277 val = TYPE_RM_MIN_VALUE (type);
8278 if (val)
8280 gimplify_one_sizepos (&val, pre_p);
8281 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
8282 SET_TYPE_RM_MIN_VALUE (t, val);
8285 val = TYPE_RM_MAX_VALUE (type);
8286 if (val)
8288 gimplify_one_sizepos (&val, pre_p);
8289 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
8290 SET_TYPE_RM_MAX_VALUE (t, val);
8294 break;
8296 default:
8297 break;
8300 /* ... fall through ... */
8302 default:
8303 return GS_UNHANDLED;
8307 /* Generate GIMPLE in place for the statement at *STMT_P. */
8309 static enum gimplify_status
8310 gnat_gimplify_stmt (tree *stmt_p)
8312 tree stmt = *stmt_p;
8314 switch (TREE_CODE (stmt))
8316 case STMT_STMT:
8317 *stmt_p = STMT_STMT_STMT (stmt);
8318 return GS_OK;
8320 case LOOP_STMT:
8322 tree gnu_start_label = create_artificial_label (input_location);
8323 tree gnu_cond = LOOP_STMT_COND (stmt);
8324 tree gnu_update = LOOP_STMT_UPDATE (stmt);
8325 tree gnu_end_label = LOOP_STMT_LABEL (stmt);
8327 /* Build the condition expression from the test, if any. */
8328 if (gnu_cond)
8330 /* Deal with the optimization hints. */
8331 if (LOOP_STMT_IVDEP (stmt))
8332 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8333 build_int_cst (integer_type_node,
8334 annot_expr_ivdep_kind));
8335 if (LOOP_STMT_NO_VECTOR (stmt))
8336 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8337 build_int_cst (integer_type_node,
8338 annot_expr_no_vector_kind));
8339 if (LOOP_STMT_VECTOR (stmt))
8340 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
8341 build_int_cst (integer_type_node,
8342 annot_expr_vector_kind));
8344 gnu_cond
8345 = build3 (COND_EXPR, void_type_node, gnu_cond, NULL_TREE,
8346 build1 (GOTO_EXPR, void_type_node, gnu_end_label));
8349 /* Set to emit the statements of the loop. */
8350 *stmt_p = NULL_TREE;
8352 /* We first emit the start label and then a conditional jump to the
8353 end label if there's a top condition, then the update if it's at
8354 the top, then the body of the loop, then a conditional jump to
8355 the end label if there's a bottom condition, then the update if
8356 it's at the bottom, and finally a jump to the start label and the
8357 definition of the end label. */
8358 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
8359 gnu_start_label),
8360 stmt_p);
8362 if (gnu_cond && !LOOP_STMT_BOTTOM_COND_P (stmt))
8363 append_to_statement_list (gnu_cond, stmt_p);
8365 if (gnu_update && LOOP_STMT_TOP_UPDATE_P (stmt))
8366 append_to_statement_list (gnu_update, stmt_p);
8368 append_to_statement_list (LOOP_STMT_BODY (stmt), stmt_p);
8370 if (gnu_cond && LOOP_STMT_BOTTOM_COND_P (stmt))
8371 append_to_statement_list (gnu_cond, stmt_p);
8373 if (gnu_update && !LOOP_STMT_TOP_UPDATE_P (stmt))
8374 append_to_statement_list (gnu_update, stmt_p);
8376 tree t = build1 (GOTO_EXPR, void_type_node, gnu_start_label);
8377 SET_EXPR_LOCATION (t, DECL_SOURCE_LOCATION (gnu_end_label));
8378 append_to_statement_list (t, stmt_p);
8380 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
8381 gnu_end_label),
8382 stmt_p);
8383 return GS_OK;
8386 case EXIT_STMT:
8387 /* Build a statement to jump to the corresponding end label, then
8388 see if it needs to be conditional. */
8389 *stmt_p = build1 (GOTO_EXPR, void_type_node, EXIT_STMT_LABEL (stmt));
8390 if (EXIT_STMT_COND (stmt))
8391 *stmt_p = build3 (COND_EXPR, void_type_node,
8392 EXIT_STMT_COND (stmt), *stmt_p, alloc_stmt_list ());
8393 return GS_OK;
8395 default:
8396 gcc_unreachable ();
8400 /* Force a reference to each of the entities in GNAT_PACKAGE recursively.
8402 This routine is exclusively called in type_annotate mode, to compute DDA
8403 information for types in withed units, for ASIS use. */
8405 static void
8406 elaborate_all_entities_for_package (Entity_Id gnat_package)
8408 Entity_Id gnat_entity;
8410 for (gnat_entity = First_Entity (gnat_package);
8411 Present (gnat_entity);
8412 gnat_entity = Next_Entity (gnat_entity))
8414 const Entity_Kind kind = Ekind (gnat_entity);
8416 /* We are interested only in entities visible from the main unit. */
8417 if (!Is_Public (gnat_entity))
8418 continue;
8420 /* Skip stuff internal to the compiler. */
8421 if (Convention (gnat_entity) == Convention_Intrinsic)
8422 continue;
8423 if (kind == E_Operator)
8424 continue;
8425 if (IN (kind, Subprogram_Kind) && Is_Intrinsic_Subprogram (gnat_entity))
8426 continue;
8428 /* Skip named numbers. */
8429 if (IN (kind, Named_Kind))
8430 continue;
8432 /* Skip generic declarations. */
8433 if (IN (kind, Generic_Unit_Kind))
8434 continue;
8436 /* Skip package bodies. */
8437 if (kind == E_Package_Body)
8438 continue;
8440 /* Skip limited views that point back to the main unit. */
8441 if (IN (kind, Incomplete_Kind)
8442 && From_Limited_With (gnat_entity)
8443 && In_Extended_Main_Code_Unit (Non_Limited_View (gnat_entity)))
8444 continue;
8446 /* Skip types that aren't frozen. */
8447 if (IN (kind, Type_Kind) && !Is_Frozen (gnat_entity))
8448 continue;
8450 /* Recurse on real packages that aren't in the main unit. */
8451 if (kind == E_Package)
8453 if (No (Renamed_Entity (gnat_entity))
8454 && !In_Extended_Main_Code_Unit (gnat_entity))
8455 elaborate_all_entities_for_package (gnat_entity);
8457 else
8458 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
8462 /* Force a reference to each of the entities in packages withed by GNAT_NODE.
8463 Operate recursively but check that we aren't elaborating something more
8464 than once.
8466 This routine is exclusively called in type_annotate mode, to compute DDA
8467 information for types in withed units, for ASIS use. */
8469 static void
8470 elaborate_all_entities (Node_Id gnat_node)
8472 Entity_Id gnat_with_clause;
8474 /* Process each unit only once. As we trace the context of all relevant
8475 units transitively, including generic bodies, we may encounter the
8476 same generic unit repeatedly. */
8477 if (!present_gnu_tree (gnat_node))
8478 save_gnu_tree (gnat_node, integer_zero_node, true);
8480 /* Save entities in all context units. A body may have an implicit_with
8481 on its own spec, if the context includes a child unit, so don't save
8482 the spec twice. */
8483 for (gnat_with_clause = First (Context_Items (gnat_node));
8484 Present (gnat_with_clause);
8485 gnat_with_clause = Next (gnat_with_clause))
8486 if (Nkind (gnat_with_clause) == N_With_Clause
8487 && !present_gnu_tree (Library_Unit (gnat_with_clause))
8488 && Library_Unit (gnat_with_clause) != Library_Unit (Cunit (Main_Unit)))
8490 Node_Id gnat_unit = Library_Unit (gnat_with_clause);
8491 Entity_Id gnat_entity = Entity (Name (gnat_with_clause));
8493 elaborate_all_entities (gnat_unit);
8495 if (Ekind (gnat_entity) == E_Package)
8496 elaborate_all_entities_for_package (gnat_entity);
8498 else if (Ekind (gnat_entity) == E_Generic_Package)
8500 Node_Id gnat_body = Corresponding_Body (Unit (gnat_unit));
8502 /* Retrieve compilation unit node of generic body. */
8503 while (Present (gnat_body)
8504 && Nkind (gnat_body) != N_Compilation_Unit)
8505 gnat_body = Parent (gnat_body);
8507 /* If body is available, elaborate its context. */
8508 if (Present (gnat_body))
8509 elaborate_all_entities (gnat_body);
8513 if (Nkind (Unit (gnat_node)) == N_Package_Body)
8514 elaborate_all_entities (Library_Unit (gnat_node));
8517 /* Do the processing of GNAT_NODE, an N_Freeze_Entity. */
8519 static void
8520 process_freeze_entity (Node_Id gnat_node)
8522 const Entity_Id gnat_entity = Entity (gnat_node);
8523 const Entity_Kind kind = Ekind (gnat_entity);
8524 tree gnu_old, gnu_new;
8526 /* If this is a package, we need to generate code for the package. */
8527 if (kind == E_Package)
8529 insert_code_for
8530 (Parent (Corresponding_Body
8531 (Parent (Declaration_Node (gnat_entity)))));
8532 return;
8535 /* Don't do anything for class-wide types as they are always transformed
8536 into their root type. */
8537 if (kind == E_Class_Wide_Type)
8538 return;
8540 /* Check for an old definition. This freeze node might be for an Itype. */
8541 gnu_old
8542 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : NULL_TREE;
8544 /* If this entity has an address representation clause, GNU_OLD is the
8545 address, so discard it here. */
8546 if (Present (Address_Clause (gnat_entity)))
8547 gnu_old = NULL_TREE;
8549 /* Don't do anything for subprograms that may have been elaborated before
8550 their freeze nodes. This can happen, for example, because of an inner
8551 call in an instance body or because of previous compilation of a spec
8552 for inlining purposes. */
8553 if (gnu_old
8554 && ((TREE_CODE (gnu_old) == FUNCTION_DECL
8555 && (kind == E_Function || kind == E_Procedure))
8556 || (TREE_CODE (TREE_TYPE (gnu_old)) == FUNCTION_TYPE
8557 && kind == E_Subprogram_Type)))
8558 return;
8560 /* If we have a non-dummy type old tree, we have nothing to do, except
8561 aborting if this is the public view of a private type whose full view was
8562 not delayed, as this node was never delayed as it should have been. We
8563 let this happen for concurrent types and their Corresponding_Record_Type,
8564 however, because each might legitimately be elaborated before its own
8565 freeze node, e.g. while processing the other. */
8566 if (gnu_old
8567 && !(TREE_CODE (gnu_old) == TYPE_DECL
8568 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old))))
8570 gcc_assert ((IN (kind, Incomplete_Or_Private_Kind)
8571 && Present (Full_View (gnat_entity))
8572 && No (Freeze_Node (Full_View (gnat_entity))))
8573 || Is_Concurrent_Type (gnat_entity)
8574 || (IN (kind, Record_Kind)
8575 && Is_Concurrent_Record_Type (gnat_entity)));
8576 return;
8579 /* Reset the saved tree, if any, and elaborate the object or type for real.
8580 If there is a full view, elaborate it and use the result. And, if this
8581 is the root type of a class-wide type, reuse it for the latter. */
8582 if (gnu_old)
8584 save_gnu_tree (gnat_entity, NULL_TREE, false);
8586 if (IN (kind, Incomplete_Or_Private_Kind)
8587 && Present (Full_View (gnat_entity)))
8589 Entity_Id full_view = Full_View (gnat_entity);
8591 save_gnu_tree (full_view, NULL_TREE, false);
8593 if (IN (Ekind (full_view), Private_Kind)
8594 && Present (Underlying_Full_View (full_view)))
8596 full_view = Underlying_Full_View (full_view);
8597 save_gnu_tree (full_view, NULL_TREE, false);
8601 if (IN (kind, Type_Kind)
8602 && Present (Class_Wide_Type (gnat_entity))
8603 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
8604 save_gnu_tree (Class_Wide_Type (gnat_entity), NULL_TREE, false);
8607 if (IN (kind, Incomplete_Or_Private_Kind)
8608 && Present (Full_View (gnat_entity)))
8610 Entity_Id full_view = Full_View (gnat_entity);
8612 if (IN (Ekind (full_view), Private_Kind)
8613 && Present (Underlying_Full_View (full_view)))
8614 full_view = Underlying_Full_View (full_view);
8616 gnu_new = gnat_to_gnu_entity (full_view, NULL_TREE, 1);
8618 /* Propagate back-annotations from full view to partial view. */
8619 if (Unknown_Alignment (gnat_entity))
8620 Set_Alignment (gnat_entity, Alignment (full_view));
8622 if (Unknown_Esize (gnat_entity))
8623 Set_Esize (gnat_entity, Esize (full_view));
8625 if (Unknown_RM_Size (gnat_entity))
8626 Set_RM_Size (gnat_entity, RM_Size (full_view));
8628 /* The above call may have defined this entity (the simplest example
8629 of this is when we have a private enumeral type since the bounds
8630 will have the public view). */
8631 if (!present_gnu_tree (gnat_entity))
8632 save_gnu_tree (gnat_entity, gnu_new, false);
8634 else
8636 tree gnu_init
8637 = (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration
8638 && present_gnu_tree (Declaration_Node (gnat_entity)))
8639 ? get_gnu_tree (Declaration_Node (gnat_entity)) : NULL_TREE;
8641 gnu_new = gnat_to_gnu_entity (gnat_entity, gnu_init, 1);
8644 if (IN (kind, Type_Kind)
8645 && Present (Class_Wide_Type (gnat_entity))
8646 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
8647 save_gnu_tree (Class_Wide_Type (gnat_entity), gnu_new, false);
8649 /* If we have an old type and we've made pointers to this type, update those
8650 pointers. If this is a Taft amendment type in the main unit, we need to
8651 mark the type as used since other units referencing it don't see the full
8652 declaration and, therefore, cannot mark it as used themselves. */
8653 if (gnu_old)
8655 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
8656 TREE_TYPE (gnu_new));
8657 if (DECL_TAFT_TYPE_P (gnu_old))
8658 used_types_insert (TREE_TYPE (gnu_new));
8662 /* Elaborate decls in the lists GNAT_DECLS and GNAT_DECLS2, if present.
8663 We make two passes, one to elaborate anything other than bodies (but
8664 we declare a function if there was no spec). The second pass
8665 elaborates the bodies.
8667 GNAT_END_LIST gives the element in the list past the end. Normally,
8668 this is Empty, but can be First_Real_Statement for a
8669 Handled_Sequence_Of_Statements.
8671 We make a complete pass through both lists if PASS1P is true, then make
8672 the second pass over both lists if PASS2P is true. The lists usually
8673 correspond to the public and private parts of a package. */
8675 static void
8676 process_decls (List_Id gnat_decls, List_Id gnat_decls2,
8677 Node_Id gnat_end_list, bool pass1p, bool pass2p)
8679 List_Id gnat_decl_array[2];
8680 Node_Id gnat_decl;
8681 int i;
8683 gnat_decl_array[0] = gnat_decls, gnat_decl_array[1] = gnat_decls2;
8685 if (pass1p)
8686 for (i = 0; i <= 1; i++)
8687 if (Present (gnat_decl_array[i]))
8688 for (gnat_decl = First (gnat_decl_array[i]);
8689 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
8691 /* For package specs, we recurse inside the declarations,
8692 thus taking the two pass approach inside the boundary. */
8693 if (Nkind (gnat_decl) == N_Package_Declaration
8694 && (Nkind (Specification (gnat_decl)
8695 == N_Package_Specification)))
8696 process_decls (Visible_Declarations (Specification (gnat_decl)),
8697 Private_Declarations (Specification (gnat_decl)),
8698 Empty, true, false);
8700 /* Similarly for any declarations in the actions of a
8701 freeze node. */
8702 else if (Nkind (gnat_decl) == N_Freeze_Entity)
8704 process_freeze_entity (gnat_decl);
8705 process_decls (Actions (gnat_decl), Empty, Empty, true, false);
8708 /* Package bodies with freeze nodes get their elaboration deferred
8709 until the freeze node, but the code must be placed in the right
8710 place, so record the code position now. */
8711 else if (Nkind (gnat_decl) == N_Package_Body
8712 && Present (Freeze_Node (Corresponding_Spec (gnat_decl))))
8713 record_code_position (gnat_decl);
8715 else if (Nkind (gnat_decl) == N_Package_Body_Stub
8716 && Present (Library_Unit (gnat_decl))
8717 && Present (Freeze_Node
8718 (Corresponding_Spec
8719 (Proper_Body (Unit
8720 (Library_Unit (gnat_decl)))))))
8721 record_code_position
8722 (Proper_Body (Unit (Library_Unit (gnat_decl))));
8724 /* We defer most subprogram bodies to the second pass. */
8725 else if (Nkind (gnat_decl) == N_Subprogram_Body)
8727 if (Acts_As_Spec (gnat_decl))
8729 Node_Id gnat_subprog_id = Defining_Entity (gnat_decl);
8731 if (Ekind (gnat_subprog_id) != E_Generic_Procedure
8732 && Ekind (gnat_subprog_id) != E_Generic_Function)
8733 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
8737 /* For bodies and stubs that act as their own specs, the entity
8738 itself must be elaborated in the first pass, because it may
8739 be used in other declarations. */
8740 else if (Nkind (gnat_decl) == N_Subprogram_Body_Stub)
8742 Node_Id gnat_subprog_id
8743 = Defining_Entity (Specification (gnat_decl));
8745 if (Ekind (gnat_subprog_id) != E_Subprogram_Body
8746 && Ekind (gnat_subprog_id) != E_Generic_Procedure
8747 && Ekind (gnat_subprog_id) != E_Generic_Function)
8748 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
8751 /* Concurrent stubs stand for the corresponding subprogram bodies,
8752 which are deferred like other bodies. */
8753 else if (Nkind (gnat_decl) == N_Task_Body_Stub
8754 || Nkind (gnat_decl) == N_Protected_Body_Stub)
8757 /* Renamed subprograms may not be elaborated yet at this point
8758 since renamings do not trigger freezing. Wait for the second
8759 pass to take care of them. */
8760 else if (Nkind (gnat_decl) == N_Subprogram_Renaming_Declaration)
8763 else
8764 add_stmt (gnat_to_gnu (gnat_decl));
8767 /* Here we elaborate everything we deferred above except for package bodies,
8768 which are elaborated at their freeze nodes. Note that we must also
8769 go inside things (package specs and freeze nodes) the first pass did. */
8770 if (pass2p)
8771 for (i = 0; i <= 1; i++)
8772 if (Present (gnat_decl_array[i]))
8773 for (gnat_decl = First (gnat_decl_array[i]);
8774 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
8776 if (Nkind (gnat_decl) == N_Subprogram_Body
8777 || Nkind (gnat_decl) == N_Subprogram_Body_Stub
8778 || Nkind (gnat_decl) == N_Task_Body_Stub
8779 || Nkind (gnat_decl) == N_Protected_Body_Stub)
8780 add_stmt (gnat_to_gnu (gnat_decl));
8782 else if (Nkind (gnat_decl) == N_Package_Declaration
8783 && (Nkind (Specification (gnat_decl)
8784 == N_Package_Specification)))
8785 process_decls (Visible_Declarations (Specification (gnat_decl)),
8786 Private_Declarations (Specification (gnat_decl)),
8787 Empty, false, true);
8789 else if (Nkind (gnat_decl) == N_Freeze_Entity)
8790 process_decls (Actions (gnat_decl), Empty, Empty, false, true);
8792 else if (Nkind (gnat_decl) == N_Subprogram_Renaming_Declaration)
8793 add_stmt (gnat_to_gnu (gnat_decl));
8797 /* Make a unary operation of kind CODE using build_unary_op, but guard
8798 the operation by an overflow check. CODE can be one of NEGATE_EXPR
8799 or ABS_EXPR. GNU_TYPE is the type desired for the result. Usually
8800 the operation is to be performed in that type. GNAT_NODE is the gnat
8801 node conveying the source location for which the error should be
8802 signaled. */
8804 static tree
8805 build_unary_op_trapv (enum tree_code code, tree gnu_type, tree operand,
8806 Node_Id gnat_node)
8808 gcc_assert (code == NEGATE_EXPR || code == ABS_EXPR);
8810 operand = gnat_protect_expr (operand);
8812 return emit_check (build_binary_op (EQ_EXPR, boolean_type_node,
8813 operand, TYPE_MIN_VALUE (gnu_type)),
8814 build_unary_op (code, gnu_type, operand),
8815 CE_Overflow_Check_Failed, gnat_node);
8818 /* Make a binary operation of kind CODE using build_binary_op, but guard
8819 the operation by an overflow check. CODE can be one of PLUS_EXPR,
8820 MINUS_EXPR or MULT_EXPR. GNU_TYPE is the type desired for the result.
8821 Usually the operation is to be performed in that type. GNAT_NODE is
8822 the GNAT node conveying the source location for which the error should
8823 be signaled. */
8825 static tree
8826 build_binary_op_trapv (enum tree_code code, tree gnu_type, tree left,
8827 tree right, Node_Id gnat_node)
8829 const unsigned int precision = TYPE_PRECISION (gnu_type);
8830 tree lhs = gnat_protect_expr (left);
8831 tree rhs = gnat_protect_expr (right);
8832 tree type_max = TYPE_MAX_VALUE (gnu_type);
8833 tree type_min = TYPE_MIN_VALUE (gnu_type);
8834 tree zero = convert (gnu_type, integer_zero_node);
8835 tree gnu_expr, rhs_lt_zero, tmp1, tmp2;
8836 tree check_pos, check_neg, check;
8838 /* Assert that the precision is a power of 2. */
8839 gcc_assert ((precision & (precision - 1)) == 0);
8841 /* Prefer a constant or known-positive rhs to simplify checks. */
8842 if (!TREE_CONSTANT (rhs)
8843 && commutative_tree_code (code)
8844 && (TREE_CONSTANT (lhs)
8845 || (!tree_expr_nonnegative_p (rhs)
8846 && tree_expr_nonnegative_p (lhs))))
8848 tree tmp = lhs;
8849 lhs = rhs;
8850 rhs = tmp;
8853 gnu_expr = build_binary_op (code, gnu_type, lhs, rhs);
8855 /* If we can fold the expression to a constant, just return it.
8856 The caller will deal with overflow, no need to generate a check. */
8857 if (TREE_CONSTANT (gnu_expr))
8858 return gnu_expr;
8860 rhs_lt_zero = tree_expr_nonnegative_p (rhs)
8861 ? boolean_false_node
8862 : build_binary_op (LT_EXPR, boolean_type_node, rhs, zero);
8864 /* ??? Should use more efficient check for operand_equal_p (lhs, rhs, 0) */
8866 /* Try a few strategies that may be cheaper than the general
8867 code at the end of the function, if the rhs is not known.
8868 The strategies are:
8869 - Call library function for 64-bit multiplication (complex)
8870 - Widen, if input arguments are sufficiently small
8871 - Determine overflow using wrapped result for addition/subtraction. */
8873 if (!TREE_CONSTANT (rhs))
8875 /* Even for add/subtract double size to get another base type. */
8876 const unsigned int needed_precision = precision * 2;
8878 if (code == MULT_EXPR && precision == 64)
8880 tree int_64 = gnat_type_for_size (64, 0);
8882 return convert (gnu_type, build_call_n_expr (mulv64_decl, 2,
8883 convert (int_64, lhs),
8884 convert (int_64, rhs)));
8887 if (needed_precision <= BITS_PER_WORD
8888 || (code == MULT_EXPR && needed_precision <= LONG_LONG_TYPE_SIZE))
8890 tree wide_type = gnat_type_for_size (needed_precision, 0);
8891 tree wide_result = build_binary_op (code, wide_type,
8892 convert (wide_type, lhs),
8893 convert (wide_type, rhs));
8895 check = build_binary_op
8896 (TRUTH_ORIF_EXPR, boolean_type_node,
8897 build_binary_op (LT_EXPR, boolean_type_node, wide_result,
8898 convert (wide_type, type_min)),
8899 build_binary_op (GT_EXPR, boolean_type_node, wide_result,
8900 convert (wide_type, type_max)));
8902 return
8903 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8906 if (code == PLUS_EXPR || code == MINUS_EXPR)
8908 tree unsigned_type = gnat_type_for_size (precision, 1);
8909 tree wrapped_expr
8910 = convert (gnu_type,
8911 build_binary_op (code, unsigned_type,
8912 convert (unsigned_type, lhs),
8913 convert (unsigned_type, rhs)));
8915 /* Overflow when (rhs < 0) ^ (wrapped_expr < lhs)), for addition
8916 or when (rhs < 0) ^ (wrapped_expr > lhs) for subtraction. */
8917 check
8918 = build_binary_op (TRUTH_XOR_EXPR, boolean_type_node, rhs_lt_zero,
8919 build_binary_op (code == PLUS_EXPR
8920 ? LT_EXPR : GT_EXPR,
8921 boolean_type_node,
8922 wrapped_expr, lhs));
8924 return
8925 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8929 switch (code)
8931 case PLUS_EXPR:
8932 /* When rhs >= 0, overflow when lhs > type_max - rhs. */
8933 check_pos = build_binary_op (GT_EXPR, boolean_type_node, lhs,
8934 build_binary_op (MINUS_EXPR, gnu_type,
8935 type_max, rhs)),
8937 /* When rhs < 0, overflow when lhs < type_min - rhs. */
8938 check_neg = build_binary_op (LT_EXPR, boolean_type_node, lhs,
8939 build_binary_op (MINUS_EXPR, gnu_type,
8940 type_min, rhs));
8941 break;
8943 case MINUS_EXPR:
8944 /* When rhs >= 0, overflow when lhs < type_min + rhs. */
8945 check_pos = build_binary_op (LT_EXPR, boolean_type_node, lhs,
8946 build_binary_op (PLUS_EXPR, gnu_type,
8947 type_min, rhs)),
8949 /* When rhs < 0, overflow when lhs > type_max + rhs. */
8950 check_neg = build_binary_op (GT_EXPR, boolean_type_node, lhs,
8951 build_binary_op (PLUS_EXPR, gnu_type,
8952 type_max, rhs));
8953 break;
8955 case MULT_EXPR:
8956 /* The check here is designed to be efficient if the rhs is constant,
8957 but it will work for any rhs by using integer division.
8958 Four different check expressions determine whether X * C overflows,
8959 depending on C.
8960 C == 0 => false
8961 C > 0 => X > type_max / C || X < type_min / C
8962 C == -1 => X == type_min
8963 C < -1 => X > type_min / C || X < type_max / C */
8965 tmp1 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
8966 tmp2 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
8968 check_pos
8969 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
8970 build_binary_op (NE_EXPR, boolean_type_node, zero,
8971 rhs),
8972 build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8973 build_binary_op (GT_EXPR,
8974 boolean_type_node,
8975 lhs, tmp1),
8976 build_binary_op (LT_EXPR,
8977 boolean_type_node,
8978 lhs, tmp2)));
8980 check_neg
8981 = fold_build3 (COND_EXPR, boolean_type_node,
8982 build_binary_op (EQ_EXPR, boolean_type_node, rhs,
8983 build_int_cst (gnu_type, -1)),
8984 build_binary_op (EQ_EXPR, boolean_type_node, lhs,
8985 type_min),
8986 build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8987 build_binary_op (GT_EXPR,
8988 boolean_type_node,
8989 lhs, tmp2),
8990 build_binary_op (LT_EXPR,
8991 boolean_type_node,
8992 lhs, tmp1)));
8993 break;
8995 default:
8996 gcc_unreachable();
8999 check = fold_build3 (COND_EXPR, boolean_type_node, rhs_lt_zero, check_neg,
9000 check_pos);
9002 return emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
9005 /* Emit code for a range check. GNU_EXPR is the expression to be checked,
9006 GNAT_RANGE_TYPE the gnat type or subtype containing the bounds against
9007 which we have to check. GNAT_NODE is the GNAT node conveying the source
9008 location for which the error should be signaled. */
9010 static tree
9011 emit_range_check (tree gnu_expr, Entity_Id gnat_range_type, Node_Id gnat_node)
9013 tree gnu_range_type = get_unpadded_type (gnat_range_type);
9014 tree gnu_compare_type = get_base_type (TREE_TYPE (gnu_expr));
9016 /* If GNU_EXPR has GNAT_RANGE_TYPE as its base type, no check is needed.
9017 This can for example happen when translating 'Val or 'Value. */
9018 if (gnu_compare_type == gnu_range_type)
9019 return gnu_expr;
9021 /* Range checks can only be applied to types with ranges. */
9022 gcc_assert (INTEGRAL_TYPE_P (gnu_range_type)
9023 || SCALAR_FLOAT_TYPE_P (gnu_range_type));
9025 /* If GNU_EXPR has an integral type that is narrower than GNU_RANGE_TYPE,
9026 we can't do anything since we might be truncating the bounds. No
9027 check is needed in this case. */
9028 if (INTEGRAL_TYPE_P (TREE_TYPE (gnu_expr))
9029 && (TYPE_PRECISION (gnu_compare_type)
9030 < TYPE_PRECISION (get_base_type (gnu_range_type))))
9031 return gnu_expr;
9033 /* Checked expressions must be evaluated only once. */
9034 gnu_expr = gnat_protect_expr (gnu_expr);
9036 /* Note that the form of the check is
9037 (not (expr >= lo)) or (not (expr <= hi))
9038 the reason for this slightly convoluted form is that NaNs
9039 are not considered to be in range in the float case. */
9040 return emit_check
9041 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
9042 invert_truthvalue
9043 (build_binary_op (GE_EXPR, boolean_type_node,
9044 convert (gnu_compare_type, gnu_expr),
9045 convert (gnu_compare_type,
9046 TYPE_MIN_VALUE
9047 (gnu_range_type)))),
9048 invert_truthvalue
9049 (build_binary_op (LE_EXPR, boolean_type_node,
9050 convert (gnu_compare_type, gnu_expr),
9051 convert (gnu_compare_type,
9052 TYPE_MAX_VALUE
9053 (gnu_range_type))))),
9054 gnu_expr, CE_Range_Check_Failed, gnat_node);
9057 /* Emit code for an index check. GNU_ARRAY_OBJECT is the array object which
9058 we are about to index, GNU_EXPR is the index expression to be checked,
9059 GNU_LOW and GNU_HIGH are the lower and upper bounds against which GNU_EXPR
9060 has to be checked. Note that for index checking we cannot simply use the
9061 emit_range_check function (although very similar code needs to be generated
9062 in both cases) since for index checking the array type against which we are
9063 checking the indices may be unconstrained and consequently we need to get
9064 the actual index bounds from the array object itself (GNU_ARRAY_OBJECT).
9065 The place where we need to do that is in subprograms having unconstrained
9066 array formal parameters. GNAT_NODE is the GNAT node conveying the source
9067 location for which the error should be signaled. */
9069 static tree
9070 emit_index_check (tree gnu_array_object, tree gnu_expr, tree gnu_low,
9071 tree gnu_high, Node_Id gnat_node)
9073 tree gnu_expr_check;
9075 /* Checked expressions must be evaluated only once. */
9076 gnu_expr = gnat_protect_expr (gnu_expr);
9078 /* Must do this computation in the base type in case the expression's
9079 type is an unsigned subtypes. */
9080 gnu_expr_check = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
9082 /* If GNU_LOW or GNU_HIGH are a PLACEHOLDER_EXPR, qualify them by
9083 the object we are handling. */
9084 gnu_low = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_low, gnu_array_object);
9085 gnu_high = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_high, gnu_array_object);
9087 return emit_check
9088 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
9089 build_binary_op (LT_EXPR, boolean_type_node,
9090 gnu_expr_check,
9091 convert (TREE_TYPE (gnu_expr_check),
9092 gnu_low)),
9093 build_binary_op (GT_EXPR, boolean_type_node,
9094 gnu_expr_check,
9095 convert (TREE_TYPE (gnu_expr_check),
9096 gnu_high))),
9097 gnu_expr, CE_Index_Check_Failed, gnat_node);
9100 /* GNU_COND contains the condition corresponding to an index, overflow or
9101 range check of value GNU_EXPR. Build a COND_EXPR that returns GNU_EXPR
9102 if GNU_COND is false and raises a CONSTRAINT_ERROR if GNU_COND is true.
9103 REASON is the code that says why the exception is raised. GNAT_NODE is
9104 the node conveying the source location for which the error should be
9105 signaled.
9107 We used to propagate TREE_SIDE_EFFECTS from GNU_EXPR to the COND_EXPR,
9108 overwriting the setting inherited from the call statement, on the ground
9109 that the expression need not be evaluated just for the check. However
9110 that's incorrect because, in the GCC type system, its value is presumed
9111 to be valid so its comparison against the type bounds always yields true
9112 and, therefore, could be done without evaluating it; given that it can
9113 be a computation that overflows the bounds, the language may require the
9114 check to fail and thus the expression to be evaluated in this case. */
9116 static tree
9117 emit_check (tree gnu_cond, tree gnu_expr, int reason, Node_Id gnat_node)
9119 tree gnu_call
9120 = build_call_raise (reason, gnat_node, N_Raise_Constraint_Error);
9121 return
9122 fold_build3 (COND_EXPR, TREE_TYPE (gnu_expr), gnu_cond,
9123 build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr), gnu_call,
9124 convert (TREE_TYPE (gnu_expr), integer_zero_node)),
9125 gnu_expr);
9128 /* Return an expression that converts GNU_EXPR to GNAT_TYPE, doing overflow
9129 checks if OVERFLOW_P is true and range checks if RANGE_P is true.
9130 GNAT_TYPE is known to be an integral type. If TRUNCATE_P true, do a
9131 float to integer conversion with truncation; otherwise round.
9132 GNAT_NODE is the GNAT node conveying the source location for which the
9133 error should be signaled. */
9135 static tree
9136 convert_with_check (Entity_Id gnat_type, tree gnu_expr, bool overflowp,
9137 bool rangep, bool truncatep, Node_Id gnat_node)
9139 tree gnu_type = get_unpadded_type (gnat_type);
9140 tree gnu_in_type = TREE_TYPE (gnu_expr);
9141 tree gnu_in_basetype = get_base_type (gnu_in_type);
9142 tree gnu_base_type = get_base_type (gnu_type);
9143 tree gnu_result = gnu_expr;
9145 /* If we are not doing any checks, the output is an integral type and the
9146 input is not a floating-point type, just do the conversion. This is
9147 required for packed array types and is simpler in all cases anyway. */
9148 if (!rangep
9149 && !overflowp
9150 && INTEGRAL_TYPE_P (gnu_base_type)
9151 && !FLOAT_TYPE_P (gnu_in_type))
9152 return convert (gnu_type, gnu_expr);
9154 /* First convert the expression to its base type. This
9155 will never generate code, but makes the tests below much simpler.
9156 But don't do this if converting from an integer type to an unconstrained
9157 array type since then we need to get the bounds from the original
9158 (unpacked) type. */
9159 if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
9160 gnu_result = convert (gnu_in_basetype, gnu_result);
9162 /* If overflow checks are requested, we need to be sure the result will
9163 fit in the output base type. But don't do this if the input
9164 is integer and the output floating-point. */
9165 if (overflowp
9166 && !(FLOAT_TYPE_P (gnu_base_type) && INTEGRAL_TYPE_P (gnu_in_basetype)))
9168 /* Ensure GNU_EXPR only gets evaluated once. */
9169 tree gnu_input = gnat_protect_expr (gnu_result);
9170 tree gnu_cond = boolean_false_node;
9171 tree gnu_in_lb = TYPE_MIN_VALUE (gnu_in_basetype);
9172 tree gnu_in_ub = TYPE_MAX_VALUE (gnu_in_basetype);
9173 tree gnu_out_lb = TYPE_MIN_VALUE (gnu_base_type);
9174 tree gnu_out_ub = TYPE_MAX_VALUE (gnu_base_type);
9176 /* Convert the lower bounds to signed types, so we're sure we're
9177 comparing them properly. Likewise, convert the upper bounds
9178 to unsigned types. */
9179 if (INTEGRAL_TYPE_P (gnu_in_basetype) && TYPE_UNSIGNED (gnu_in_basetype))
9180 gnu_in_lb = convert (gnat_signed_type (gnu_in_basetype), gnu_in_lb);
9182 if (INTEGRAL_TYPE_P (gnu_in_basetype)
9183 && !TYPE_UNSIGNED (gnu_in_basetype))
9184 gnu_in_ub = convert (gnat_unsigned_type (gnu_in_basetype), gnu_in_ub);
9186 if (INTEGRAL_TYPE_P (gnu_base_type) && TYPE_UNSIGNED (gnu_base_type))
9187 gnu_out_lb = convert (gnat_signed_type (gnu_base_type), gnu_out_lb);
9189 if (INTEGRAL_TYPE_P (gnu_base_type) && !TYPE_UNSIGNED (gnu_base_type))
9190 gnu_out_ub = convert (gnat_unsigned_type (gnu_base_type), gnu_out_ub);
9192 /* Check each bound separately and only if the result bound
9193 is tighter than the bound on the input type. Note that all the
9194 types are base types, so the bounds must be constant. Also,
9195 the comparison is done in the base type of the input, which
9196 always has the proper signedness. First check for input
9197 integer (which means output integer), output float (which means
9198 both float), or mixed, in which case we always compare.
9199 Note that we have to do the comparison which would *fail* in the
9200 case of an error since if it's an FP comparison and one of the
9201 values is a NaN or Inf, the comparison will fail. */
9202 if (INTEGRAL_TYPE_P (gnu_in_basetype)
9203 ? tree_int_cst_lt (gnu_in_lb, gnu_out_lb)
9204 : (FLOAT_TYPE_P (gnu_base_type)
9205 ? real_less (&TREE_REAL_CST (gnu_in_lb),
9206 &TREE_REAL_CST (gnu_out_lb))
9207 : 1))
9208 gnu_cond
9209 = invert_truthvalue
9210 (build_binary_op (GE_EXPR, boolean_type_node,
9211 gnu_input, convert (gnu_in_basetype,
9212 gnu_out_lb)));
9214 if (INTEGRAL_TYPE_P (gnu_in_basetype)
9215 ? tree_int_cst_lt (gnu_out_ub, gnu_in_ub)
9216 : (FLOAT_TYPE_P (gnu_base_type)
9217 ? real_less (&TREE_REAL_CST (gnu_out_ub),
9218 &TREE_REAL_CST (gnu_in_lb))
9219 : 1))
9220 gnu_cond
9221 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, gnu_cond,
9222 invert_truthvalue
9223 (build_binary_op (LE_EXPR, boolean_type_node,
9224 gnu_input,
9225 convert (gnu_in_basetype,
9226 gnu_out_ub))));
9228 if (!integer_zerop (gnu_cond))
9229 gnu_result = emit_check (gnu_cond, gnu_input,
9230 CE_Overflow_Check_Failed, gnat_node);
9233 /* Now convert to the result base type. If this is a non-truncating
9234 float-to-integer conversion, round. */
9235 if (INTEGRAL_TYPE_P (gnu_base_type)
9236 && FLOAT_TYPE_P (gnu_in_basetype)
9237 && !truncatep)
9239 REAL_VALUE_TYPE half_minus_pred_half, pred_half;
9240 tree gnu_conv, gnu_zero, gnu_comp, calc_type;
9241 tree gnu_pred_half, gnu_add_pred_half, gnu_subtract_pred_half;
9242 const struct real_format *fmt;
9244 /* The following calculations depend on proper rounding to even
9245 of each arithmetic operation. In order to prevent excess
9246 precision from spoiling this property, use the widest hardware
9247 floating-point type if FP_ARITH_MAY_WIDEN is true. */
9248 calc_type
9249 = fp_arith_may_widen ? longest_float_type_node : gnu_in_basetype;
9251 /* Compute the exact value calc_type'Pred (0.5) at compile time. */
9252 fmt = REAL_MODE_FORMAT (TYPE_MODE (calc_type));
9253 real_2expN (&half_minus_pred_half, -(fmt->p) - 1, TYPE_MODE (calc_type));
9254 real_arithmetic (&pred_half, MINUS_EXPR, &dconsthalf,
9255 &half_minus_pred_half);
9256 gnu_pred_half = build_real (calc_type, pred_half);
9258 /* If the input is strictly negative, subtract this value
9259 and otherwise add it from the input. For 0.5, the result
9260 is exactly between 1.0 and the machine number preceding 1.0
9261 (for calc_type). Since the last bit of 1.0 is even, this 0.5
9262 will round to 1.0, while all other number with an absolute
9263 value less than 0.5 round to 0.0. For larger numbers exactly
9264 halfway between integers, rounding will always be correct as
9265 the true mathematical result will be closer to the higher
9266 integer compared to the lower one. So, this constant works
9267 for all floating-point numbers.
9269 The reason to use the same constant with subtract/add instead
9270 of a positive and negative constant is to allow the comparison
9271 to be scheduled in parallel with retrieval of the constant and
9272 conversion of the input to the calc_type (if necessary). */
9274 gnu_zero = convert (gnu_in_basetype, integer_zero_node);
9275 gnu_result = gnat_protect_expr (gnu_result);
9276 gnu_conv = convert (calc_type, gnu_result);
9277 gnu_comp
9278 = fold_build2 (GE_EXPR, boolean_type_node, gnu_result, gnu_zero);
9279 gnu_add_pred_half
9280 = fold_build2 (PLUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
9281 gnu_subtract_pred_half
9282 = fold_build2 (MINUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
9283 gnu_result = fold_build3 (COND_EXPR, calc_type, gnu_comp,
9284 gnu_add_pred_half, gnu_subtract_pred_half);
9287 if (TREE_CODE (gnu_base_type) == INTEGER_TYPE
9288 && TYPE_HAS_ACTUAL_BOUNDS_P (gnu_base_type)
9289 && TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
9290 gnu_result = unchecked_convert (gnu_base_type, gnu_result, false);
9291 else
9292 gnu_result = convert (gnu_base_type, gnu_result);
9294 /* Finally, do the range check if requested. Note that if the result type
9295 is a modular type, the range check is actually an overflow check. */
9296 if (rangep
9297 || (TREE_CODE (gnu_base_type) == INTEGER_TYPE
9298 && TYPE_MODULAR_P (gnu_base_type) && overflowp))
9299 gnu_result = emit_range_check (gnu_result, gnat_type, gnat_node);
9301 return convert (gnu_type, gnu_result);
9304 /* Return true if GNU_EXPR can be directly addressed. This is the case
9305 unless it is an expression involving computation or if it involves a
9306 reference to a bitfield or to an object not sufficiently aligned for
9307 its type. If GNU_TYPE is non-null, return true only if GNU_EXPR can
9308 be directly addressed as an object of this type.
9310 *** Notes on addressability issues in the Ada compiler ***
9312 This predicate is necessary in order to bridge the gap between Gigi
9313 and the middle-end about addressability of GENERIC trees. A tree
9314 is said to be addressable if it can be directly addressed, i.e. if
9315 its address can be taken, is a multiple of the type's alignment on
9316 strict-alignment architectures and returns the first storage unit
9317 assigned to the object represented by the tree.
9319 In the C family of languages, everything is in practice addressable
9320 at the language level, except for bit-fields. This means that these
9321 compilers will take the address of any tree that doesn't represent
9322 a bit-field reference and expect the result to be the first storage
9323 unit assigned to the object. Even in cases where this will result
9324 in unaligned accesses at run time, nothing is supposed to be done
9325 and the program is considered as erroneous instead (see PR c/18287).
9327 The implicit assumptions made in the middle-end are in keeping with
9328 the C viewpoint described above:
9329 - the address of a bit-field reference is supposed to be never
9330 taken; the compiler (generally) will stop on such a construct,
9331 - any other tree is addressable if it is formally addressable,
9332 i.e. if it is formally allowed to be the operand of ADDR_EXPR.
9334 In Ada, the viewpoint is the opposite one: nothing is addressable
9335 at the language level unless explicitly declared so. This means
9336 that the compiler will both make sure that the trees representing
9337 references to addressable ("aliased" in Ada parlance) objects are
9338 addressable and make no real attempts at ensuring that the trees
9339 representing references to non-addressable objects are addressable.
9341 In the first case, Ada is effectively equivalent to C and handing
9342 down the direct result of applying ADDR_EXPR to these trees to the
9343 middle-end works flawlessly. In the second case, Ada cannot afford
9344 to consider the program as erroneous if the address of trees that
9345 are not addressable is requested for technical reasons, unlike C;
9346 as a consequence, the Ada compiler must arrange for either making
9347 sure that this address is not requested in the middle-end or for
9348 compensating by inserting temporaries if it is requested in Gigi.
9350 The first goal can be achieved because the middle-end should not
9351 request the address of non-addressable trees on its own; the only
9352 exception is for the invocation of low-level block operations like
9353 memcpy, for which the addressability requirements are lower since
9354 the type's alignment can be disregarded. In practice, this means
9355 that Gigi must make sure that such operations cannot be applied to
9356 non-BLKmode bit-fields.
9358 The second goal is achieved by means of the addressable_p predicate,
9359 which computes whether a temporary must be inserted by Gigi when the
9360 address of a tree is requested; if so, the address of the temporary
9361 will be used in lieu of that of the original tree and some glue code
9362 generated to connect everything together. */
9364 static bool
9365 addressable_p (tree gnu_expr, tree gnu_type)
9367 /* For an integral type, the size of the actual type of the object may not
9368 be greater than that of the expected type, otherwise an indirect access
9369 in the latter type wouldn't correctly set all the bits of the object. */
9370 if (gnu_type
9371 && INTEGRAL_TYPE_P (gnu_type)
9372 && smaller_form_type_p (gnu_type, TREE_TYPE (gnu_expr)))
9373 return false;
9375 /* The size of the actual type of the object may not be smaller than that
9376 of the expected type, otherwise an indirect access in the latter type
9377 would be larger than the object. But only record types need to be
9378 considered in practice for this case. */
9379 if (gnu_type
9380 && TREE_CODE (gnu_type) == RECORD_TYPE
9381 && smaller_form_type_p (TREE_TYPE (gnu_expr), gnu_type))
9382 return false;
9384 switch (TREE_CODE (gnu_expr))
9386 case VAR_DECL:
9387 case PARM_DECL:
9388 case FUNCTION_DECL:
9389 case RESULT_DECL:
9390 /* All DECLs are addressable: if they are in a register, we can force
9391 them to memory. */
9392 return true;
9394 case UNCONSTRAINED_ARRAY_REF:
9395 case INDIRECT_REF:
9396 /* Taking the address of a dereference yields the original pointer. */
9397 return true;
9399 case STRING_CST:
9400 case INTEGER_CST:
9401 /* Taking the address yields a pointer to the constant pool. */
9402 return true;
9404 case CONSTRUCTOR:
9405 /* Taking the address of a static constructor yields a pointer to the
9406 tree constant pool. */
9407 return TREE_STATIC (gnu_expr) ? true : false;
9409 case NULL_EXPR:
9410 case SAVE_EXPR:
9411 case CALL_EXPR:
9412 case PLUS_EXPR:
9413 case MINUS_EXPR:
9414 case BIT_IOR_EXPR:
9415 case BIT_XOR_EXPR:
9416 case BIT_AND_EXPR:
9417 case BIT_NOT_EXPR:
9418 /* All rvalues are deemed addressable since taking their address will
9419 force a temporary to be created by the middle-end. */
9420 return true;
9422 case COMPOUND_EXPR:
9423 /* The address of a compound expression is that of its 2nd operand. */
9424 return addressable_p (TREE_OPERAND (gnu_expr, 1), gnu_type);
9426 case COND_EXPR:
9427 /* We accept &COND_EXPR as soon as both operands are addressable and
9428 expect the outcome to be the address of the selected operand. */
9429 return (addressable_p (TREE_OPERAND (gnu_expr, 1), NULL_TREE)
9430 && addressable_p (TREE_OPERAND (gnu_expr, 2), NULL_TREE));
9432 case COMPONENT_REF:
9433 return (((!DECL_BIT_FIELD (TREE_OPERAND (gnu_expr, 1))
9434 /* Even with DECL_BIT_FIELD cleared, we have to ensure that
9435 the field is sufficiently aligned, in case it is subject
9436 to a pragma Component_Alignment. But we don't need to
9437 check the alignment of the containing record, as it is
9438 guaranteed to be not smaller than that of its most
9439 aligned field that is not a bit-field. */
9440 && (!STRICT_ALIGNMENT
9441 || DECL_ALIGN (TREE_OPERAND (gnu_expr, 1))
9442 >= TYPE_ALIGN (TREE_TYPE (gnu_expr))))
9443 /* The field of a padding record is always addressable. */
9444 || TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
9445 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
9447 case ARRAY_REF: case ARRAY_RANGE_REF:
9448 case REALPART_EXPR: case IMAGPART_EXPR:
9449 case NOP_EXPR:
9450 return addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE);
9452 case CONVERT_EXPR:
9453 return (AGGREGATE_TYPE_P (TREE_TYPE (gnu_expr))
9454 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
9456 case VIEW_CONVERT_EXPR:
9458 /* This is addressable if we can avoid a copy. */
9459 tree type = TREE_TYPE (gnu_expr);
9460 tree inner_type = TREE_TYPE (TREE_OPERAND (gnu_expr, 0));
9461 return (((TYPE_MODE (type) == TYPE_MODE (inner_type)
9462 && (!STRICT_ALIGNMENT
9463 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
9464 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT))
9465 || ((TYPE_MODE (type) == BLKmode
9466 || TYPE_MODE (inner_type) == BLKmode)
9467 && (!STRICT_ALIGNMENT
9468 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
9469 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT
9470 || TYPE_ALIGN_OK (type)
9471 || TYPE_ALIGN_OK (inner_type))))
9472 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
9475 default:
9476 return false;
9480 /* Do the processing for the declaration of a GNAT_ENTITY, a type. If
9481 a separate Freeze node exists, delay the bulk of the processing. Otherwise
9482 make a GCC type for GNAT_ENTITY and set up the correspondence. */
9484 void
9485 process_type (Entity_Id gnat_entity)
9487 tree gnu_old
9488 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : 0;
9489 tree gnu_new;
9491 /* If we are to delay elaboration of this type, just do any
9492 elaborations needed for expressions within the declaration and
9493 make a dummy type entry for this node and its Full_View (if
9494 any) in case something points to it. Don't do this if it
9495 has already been done (the only way that can happen is if
9496 the private completion is also delayed). */
9497 if (Present (Freeze_Node (gnat_entity))
9498 || (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
9499 && Present (Full_View (gnat_entity))
9500 && Present (Freeze_Node (Full_View (gnat_entity)))
9501 && !present_gnu_tree (Full_View (gnat_entity))))
9503 elaborate_entity (gnat_entity);
9505 if (!gnu_old)
9507 tree gnu_decl = TYPE_STUB_DECL (make_dummy_type (gnat_entity));
9508 save_gnu_tree (gnat_entity, gnu_decl, false);
9509 if (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
9510 && Present (Full_View (gnat_entity)))
9512 if (Has_Completion_In_Body (gnat_entity))
9513 DECL_TAFT_TYPE_P (gnu_decl) = 1;
9514 save_gnu_tree (Full_View (gnat_entity), gnu_decl, false);
9518 return;
9521 /* If we saved away a dummy type for this node it means that this
9522 made the type that corresponds to the full type of an incomplete
9523 type. Clear that type for now and then update the type in the
9524 pointers. */
9525 if (gnu_old)
9527 gcc_assert (TREE_CODE (gnu_old) == TYPE_DECL
9528 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old)));
9530 save_gnu_tree (gnat_entity, NULL_TREE, false);
9533 /* Now fully elaborate the type. */
9534 gnu_new = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 1);
9535 gcc_assert (TREE_CODE (gnu_new) == TYPE_DECL);
9537 /* If we have an old type and we've made pointers to this type, update those
9538 pointers. If this is a Taft amendment type in the main unit, we need to
9539 mark the type as used since other units referencing it don't see the full
9540 declaration and, therefore, cannot mark it as used themselves. */
9541 if (gnu_old)
9543 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
9544 TREE_TYPE (gnu_new));
9545 if (DECL_TAFT_TYPE_P (gnu_old))
9546 used_types_insert (TREE_TYPE (gnu_new));
9549 /* If this is a record type corresponding to a task or protected type
9550 that is a completion of an incomplete type, perform a similar update
9551 on the type. ??? Including protected types here is a guess. */
9552 if (IN (Ekind (gnat_entity), Record_Kind)
9553 && Is_Concurrent_Record_Type (gnat_entity)
9554 && present_gnu_tree (Corresponding_Concurrent_Type (gnat_entity)))
9556 tree gnu_task_old
9557 = get_gnu_tree (Corresponding_Concurrent_Type (gnat_entity));
9559 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
9560 NULL_TREE, false);
9561 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
9562 gnu_new, false);
9564 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_task_old)),
9565 TREE_TYPE (gnu_new));
9569 /* GNAT_ENTITY is the type of the resulting constructor, GNAT_ASSOC is the
9570 front of the Component_Associations of an N_Aggregate and GNU_TYPE is the
9571 GCC type of the corresponding record type. Return the CONSTRUCTOR. */
9573 static tree
9574 assoc_to_constructor (Entity_Id gnat_entity, Node_Id gnat_assoc, tree gnu_type)
9576 tree gnu_list = NULL_TREE, gnu_result;
9578 /* We test for GNU_FIELD being empty in the case where a variant
9579 was the last thing since we don't take things off GNAT_ASSOC in
9580 that case. We check GNAT_ASSOC in case we have a variant, but it
9581 has no fields. */
9583 for (; Present (gnat_assoc); gnat_assoc = Next (gnat_assoc))
9585 Node_Id gnat_field = First (Choices (gnat_assoc));
9586 tree gnu_field = gnat_to_gnu_field_decl (Entity (gnat_field));
9587 tree gnu_expr = gnat_to_gnu (Expression (gnat_assoc));
9589 /* The expander is supposed to put a single component selector name
9590 in every record component association. */
9591 gcc_assert (No (Next (gnat_field)));
9593 /* Ignore fields that have Corresponding_Discriminants since we'll
9594 be setting that field in the parent. */
9595 if (Present (Corresponding_Discriminant (Entity (gnat_field)))
9596 && Is_Tagged_Type (Scope (Entity (gnat_field))))
9597 continue;
9599 /* Also ignore discriminants of Unchecked_Unions. */
9600 if (Is_Unchecked_Union (gnat_entity)
9601 && Ekind (Entity (gnat_field)) == E_Discriminant)
9602 continue;
9604 /* Before assigning a value in an aggregate make sure range checks
9605 are done if required. Then convert to the type of the field. */
9606 if (Do_Range_Check (Expression (gnat_assoc)))
9607 gnu_expr = emit_range_check (gnu_expr, Etype (gnat_field), Empty);
9609 gnu_expr = convert (TREE_TYPE (gnu_field), gnu_expr);
9611 /* Add the field and expression to the list. */
9612 gnu_list = tree_cons (gnu_field, gnu_expr, gnu_list);
9615 gnu_result = extract_values (gnu_list, gnu_type);
9617 if (flag_checking)
9619 /* Verify that every entry in GNU_LIST was used. */
9620 for (; gnu_list; gnu_list = TREE_CHAIN (gnu_list))
9621 gcc_assert (TREE_ADDRESSABLE (gnu_list));
9624 return gnu_result;
9627 /* Build a possibly nested constructor for array aggregates. GNAT_EXPR is
9628 the first element of an array aggregate. It may itself be an aggregate.
9629 GNU_ARRAY_TYPE is the GCC type corresponding to the array aggregate.
9630 GNAT_COMPONENT_TYPE is the type of the array component; it is needed
9631 for range checking. */
9633 static tree
9634 pos_to_constructor (Node_Id gnat_expr, tree gnu_array_type,
9635 Entity_Id gnat_component_type)
9637 tree gnu_index = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_array_type));
9638 tree gnu_expr;
9639 vec<constructor_elt, va_gc> *gnu_expr_vec = NULL;
9641 for ( ; Present (gnat_expr); gnat_expr = Next (gnat_expr))
9643 /* If the expression is itself an array aggregate then first build the
9644 innermost constructor if it is part of our array (multi-dimensional
9645 case). */
9646 if (Nkind (gnat_expr) == N_Aggregate
9647 && TREE_CODE (TREE_TYPE (gnu_array_type)) == ARRAY_TYPE
9648 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_array_type)))
9649 gnu_expr = pos_to_constructor (First (Expressions (gnat_expr)),
9650 TREE_TYPE (gnu_array_type),
9651 gnat_component_type);
9652 else
9654 gnu_expr = gnat_to_gnu (gnat_expr);
9656 /* Before assigning the element to the array, make sure it is
9657 in range. */
9658 if (Do_Range_Check (gnat_expr))
9659 gnu_expr = emit_range_check (gnu_expr, gnat_component_type, Empty);
9662 CONSTRUCTOR_APPEND_ELT (gnu_expr_vec, gnu_index,
9663 convert (TREE_TYPE (gnu_array_type), gnu_expr));
9665 gnu_index = int_const_binop (PLUS_EXPR, gnu_index,
9666 convert (TREE_TYPE (gnu_index),
9667 integer_one_node));
9670 return gnat_build_constructor (gnu_array_type, gnu_expr_vec);
9673 /* Subroutine of assoc_to_constructor: VALUES is a list of field associations,
9674 some of which are from RECORD_TYPE. Return a CONSTRUCTOR consisting of the
9675 associations that are from RECORD_TYPE. If we see an internal record, make
9676 a recursive call to fill it in as well. */
9678 static tree
9679 extract_values (tree values, tree record_type)
9681 tree field, tem;
9682 vec<constructor_elt, va_gc> *v = NULL;
9684 for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
9686 tree value = 0;
9688 /* _Parent is an internal field, but may have values in the aggregate,
9689 so check for values first. */
9690 if ((tem = purpose_member (field, values)))
9692 value = TREE_VALUE (tem);
9693 TREE_ADDRESSABLE (tem) = 1;
9696 else if (DECL_INTERNAL_P (field))
9698 value = extract_values (values, TREE_TYPE (field));
9699 if (TREE_CODE (value) == CONSTRUCTOR
9700 && vec_safe_is_empty (CONSTRUCTOR_ELTS (value)))
9701 value = 0;
9703 else
9704 /* If we have a record subtype, the names will match, but not the
9705 actual FIELD_DECLs. */
9706 for (tem = values; tem; tem = TREE_CHAIN (tem))
9707 if (DECL_NAME (TREE_PURPOSE (tem)) == DECL_NAME (field))
9709 value = convert (TREE_TYPE (field), TREE_VALUE (tem));
9710 TREE_ADDRESSABLE (tem) = 1;
9713 if (!value)
9714 continue;
9716 CONSTRUCTOR_APPEND_ELT (v, field, value);
9719 return gnat_build_constructor (record_type, v);
9722 /* Process a N_Validate_Unchecked_Conversion node. */
9724 static void
9725 validate_unchecked_conversion (Node_Id gnat_node)
9727 tree gnu_source_type = gnat_to_gnu_type (Source_Type (gnat_node));
9728 tree gnu_target_type = gnat_to_gnu_type (Target_Type (gnat_node));
9730 /* If the target is a pointer type, see if we are either converting from a
9731 non-pointer or from a pointer to a type with a different alias set and
9732 warn if so, unless the pointer has been marked to alias everything. */
9733 if (POINTER_TYPE_P (gnu_target_type)
9734 && !TYPE_REF_CAN_ALIAS_ALL (gnu_target_type))
9736 tree gnu_source_desig_type = POINTER_TYPE_P (gnu_source_type)
9737 ? TREE_TYPE (gnu_source_type)
9738 : NULL_TREE;
9739 tree gnu_target_desig_type = TREE_TYPE (gnu_target_type);
9740 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
9742 if (target_alias_set != 0
9743 && (!POINTER_TYPE_P (gnu_source_type)
9744 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
9745 target_alias_set)))
9747 post_error_ne ("?possible aliasing problem for type&",
9748 gnat_node, Target_Type (gnat_node));
9749 post_error ("\\?use -fno-strict-aliasing switch for references",
9750 gnat_node);
9751 post_error_ne ("\\?or use `pragma No_Strict_Aliasing (&);`",
9752 gnat_node, Target_Type (gnat_node));
9756 /* Likewise if the target is a fat pointer type, but we have no mechanism to
9757 mitigate the problem in this case, so we unconditionally warn. */
9758 else if (TYPE_IS_FAT_POINTER_P (gnu_target_type))
9760 tree gnu_source_desig_type
9761 = TYPE_IS_FAT_POINTER_P (gnu_source_type)
9762 ? TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_source_type)))
9763 : NULL_TREE;
9764 tree gnu_target_desig_type
9765 = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_target_type)));
9766 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
9768 if (target_alias_set != 0
9769 && (!TYPE_IS_FAT_POINTER_P (gnu_source_type)
9770 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
9771 target_alias_set)))
9773 post_error_ne ("?possible aliasing problem for type&",
9774 gnat_node, Target_Type (gnat_node));
9775 post_error ("\\?use -fno-strict-aliasing switch for references",
9776 gnat_node);
9781 /* EXP is to be treated as an array or record. Handle the cases when it is
9782 an access object and perform the required dereferences. */
9784 static tree
9785 maybe_implicit_deref (tree exp)
9787 /* If the type is a pointer, dereference it. */
9788 if (POINTER_TYPE_P (TREE_TYPE (exp))
9789 || TYPE_IS_FAT_POINTER_P (TREE_TYPE (exp)))
9790 exp = build_unary_op (INDIRECT_REF, NULL_TREE, exp);
9792 /* If we got a padded type, remove it too. */
9793 if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
9794 exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
9796 return exp;
9799 /* Convert SLOC into LOCUS. Return true if SLOC corresponds to a source code
9800 location and false if it doesn't. If CLEAR_COLUMN is true, set the column
9801 information to 0. */
9803 bool
9804 Sloc_to_locus (Source_Ptr Sloc, location_t *locus, bool clear_column)
9806 if (Sloc == No_Location)
9807 return false;
9809 if (Sloc <= Standard_Location)
9811 *locus = BUILTINS_LOCATION;
9812 return false;
9815 Source_File_Index file = Get_Source_File_Index (Sloc);
9816 Logical_Line_Number line = Get_Logical_Line_Number (Sloc);
9817 Column_Number column = (clear_column ? 0 : Get_Column_Number (Sloc));
9818 line_map_ordinary *map = LINEMAPS_ORDINARY_MAP_AT (line_table, file - 1);
9820 /* We can have zero if pragma Source_Reference is in effect. */
9821 if (line < 1)
9822 line = 1;
9824 /* Translate the location. */
9825 *locus = linemap_position_for_line_and_column (line_table, map,
9826 line, column);
9828 return true;
9831 /* Similar to set_expr_location, but start with the Sloc of GNAT_NODE and
9832 don't do anything if it doesn't correspond to a source location. And,
9833 if CLEAR_COLUMN is true, set the column information to 0. */
9835 static void
9836 set_expr_location_from_node (tree node, Node_Id gnat_node, bool clear_column)
9838 location_t locus;
9840 if (!Sloc_to_locus (Sloc (gnat_node), &locus, clear_column))
9841 return;
9843 SET_EXPR_LOCATION (node, locus);
9846 /* More elaborate version of set_expr_location_from_node to be used in more
9847 general contexts, for example the result of the translation of a generic
9848 GNAT node. */
9850 static void
9851 set_gnu_expr_location_from_node (tree node, Node_Id gnat_node)
9853 /* Set the location information on the node if it is a real expression.
9854 References can be reused for multiple GNAT nodes and they would get
9855 the location information of their last use. Also make sure not to
9856 overwrite an existing location as it is probably more precise. */
9858 switch (TREE_CODE (node))
9860 CASE_CONVERT:
9861 case NON_LVALUE_EXPR:
9862 case SAVE_EXPR:
9863 break;
9865 case COMPOUND_EXPR:
9866 if (EXPR_P (TREE_OPERAND (node, 1)))
9867 set_gnu_expr_location_from_node (TREE_OPERAND (node, 1), gnat_node);
9869 /* ... fall through ... */
9871 default:
9872 if (!REFERENCE_CLASS_P (node) && !EXPR_HAS_LOCATION (node))
9874 set_expr_location_from_node (node, gnat_node);
9875 set_end_locus_from_node (node, gnat_node);
9877 break;
9881 /* Set the end_locus information for GNU_NODE, if any, from an explicit end
9882 location associated with GNAT_NODE or GNAT_NODE itself, whichever makes
9883 most sense. Return true if a sensible assignment was performed. */
9885 static bool
9886 set_end_locus_from_node (tree gnu_node, Node_Id gnat_node)
9888 Node_Id gnat_end_label;
9889 location_t end_locus;
9891 /* Pick the GNAT node of which we'll take the sloc to assign to the GCC node
9892 end_locus when there is one. We consider only GNAT nodes with a possible
9893 End_Label attached. If the End_Label actually was unassigned, fallback
9894 on the original node. We'd better assign an explicit sloc associated with
9895 the outer construct in any case. */
9897 switch (Nkind (gnat_node))
9899 case N_Package_Body:
9900 case N_Subprogram_Body:
9901 case N_Block_Statement:
9902 gnat_end_label = End_Label (Handled_Statement_Sequence (gnat_node));
9903 break;
9905 case N_Package_Declaration:
9906 gnat_end_label = End_Label (Specification (gnat_node));
9907 break;
9909 default:
9910 return false;
9913 if (Present (gnat_end_label))
9914 gnat_node = gnat_end_label;
9916 /* Some expanded subprograms have neither an End_Label nor a Sloc
9917 attached. Notify that to callers. For a block statement with no
9918 End_Label, clear column information, so that the tree for a
9919 transient block does not receive the sloc of a source condition. */
9920 if (!Sloc_to_locus (Sloc (gnat_node), &end_locus,
9921 No (gnat_end_label)
9922 && (Nkind (gnat_node) == N_Block_Statement)))
9923 return false;
9925 switch (TREE_CODE (gnu_node))
9927 case BIND_EXPR:
9928 BLOCK_SOURCE_END_LOCATION (BIND_EXPR_BLOCK (gnu_node)) = end_locus;
9929 return true;
9931 case FUNCTION_DECL:
9932 DECL_STRUCT_FUNCTION (gnu_node)->function_end_locus = end_locus;
9933 return true;
9935 default:
9936 return false;
9940 /* Return a colon-separated list of encodings contained in encoded Ada
9941 name. */
9943 static const char *
9944 extract_encoding (const char *name)
9946 char *encoding = (char *) ggc_alloc_atomic (strlen (name));
9947 get_encoding (name, encoding);
9948 return encoding;
9951 /* Extract the Ada name from an encoded name. */
9953 static const char *
9954 decode_name (const char *name)
9956 char *decoded = (char *) ggc_alloc_atomic (strlen (name) * 2 + 60);
9957 __gnat_decode (name, decoded, 0);
9958 return decoded;
9961 /* Post an error message. MSG is the error message, properly annotated.
9962 NODE is the node at which to post the error and the node to use for the
9963 '&' substitution. */
9965 void
9966 post_error (const char *msg, Node_Id node)
9968 String_Template temp;
9969 String_Pointer sp;
9971 if (No (node))
9972 return;
9974 temp.Low_Bound = 1;
9975 temp.High_Bound = strlen (msg);
9976 sp.Bounds = &temp;
9977 sp.Array = msg;
9978 Error_Msg_N (sp, node);
9981 /* Similar to post_error, but NODE is the node at which to post the error and
9982 ENT is the node to use for the '&' substitution. */
9984 void
9985 post_error_ne (const char *msg, Node_Id node, Entity_Id ent)
9987 String_Template temp;
9988 String_Pointer sp;
9990 if (No (node))
9991 return;
9993 temp.Low_Bound = 1;
9994 temp.High_Bound = strlen (msg);
9995 sp.Bounds = &temp;
9996 sp.Array = msg;
9997 Error_Msg_NE (sp, node, ent);
10000 /* Similar to post_error_ne, but NUM is the number to use for the '^'. */
10002 void
10003 post_error_ne_num (const char *msg, Node_Id node, Entity_Id ent, int num)
10005 Error_Msg_Uint_1 = UI_From_Int (num);
10006 post_error_ne (msg, node, ent);
10009 /* Similar to post_error_ne, but T is a GCC tree representing the number to
10010 write. If T represents a constant, the text inside curly brackets in
10011 MSG will be output (presumably including a '^'). Otherwise it will not
10012 be output and the text inside square brackets will be output instead. */
10014 void
10015 post_error_ne_tree (const char *msg, Node_Id node, Entity_Id ent, tree t)
10017 char *new_msg = XALLOCAVEC (char, strlen (msg) + 1);
10018 char start_yes, end_yes, start_no, end_no;
10019 const char *p;
10020 char *q;
10022 if (TREE_CODE (t) == INTEGER_CST)
10024 Error_Msg_Uint_1 = UI_From_gnu (t);
10025 start_yes = '{', end_yes = '}', start_no = '[', end_no = ']';
10027 else
10028 start_yes = '[', end_yes = ']', start_no = '{', end_no = '}';
10030 for (p = msg, q = new_msg; *p; p++)
10032 if (*p == start_yes)
10033 for (p++; *p != end_yes; p++)
10034 *q++ = *p;
10035 else if (*p == start_no)
10036 for (p++; *p != end_no; p++)
10038 else
10039 *q++ = *p;
10042 *q = 0;
10044 post_error_ne (new_msg, node, ent);
10047 /* Similar to post_error_ne_tree, but NUM is a second integer to write. */
10049 void
10050 post_error_ne_tree_2 (const char *msg, Node_Id node, Entity_Id ent, tree t,
10051 int num)
10053 Error_Msg_Uint_2 = UI_From_Int (num);
10054 post_error_ne_tree (msg, node, ent, t);
10057 /* Initialize the table that maps GNAT codes to GCC codes for simple
10058 binary and unary operations. */
10060 static void
10061 init_code_table (void)
10063 gnu_codes[N_And_Then] = TRUTH_ANDIF_EXPR;
10064 gnu_codes[N_Or_Else] = TRUTH_ORIF_EXPR;
10066 gnu_codes[N_Op_And] = TRUTH_AND_EXPR;
10067 gnu_codes[N_Op_Or] = TRUTH_OR_EXPR;
10068 gnu_codes[N_Op_Xor] = TRUTH_XOR_EXPR;
10069 gnu_codes[N_Op_Eq] = EQ_EXPR;
10070 gnu_codes[N_Op_Ne] = NE_EXPR;
10071 gnu_codes[N_Op_Lt] = LT_EXPR;
10072 gnu_codes[N_Op_Le] = LE_EXPR;
10073 gnu_codes[N_Op_Gt] = GT_EXPR;
10074 gnu_codes[N_Op_Ge] = GE_EXPR;
10075 gnu_codes[N_Op_Add] = PLUS_EXPR;
10076 gnu_codes[N_Op_Subtract] = MINUS_EXPR;
10077 gnu_codes[N_Op_Multiply] = MULT_EXPR;
10078 gnu_codes[N_Op_Mod] = FLOOR_MOD_EXPR;
10079 gnu_codes[N_Op_Rem] = TRUNC_MOD_EXPR;
10080 gnu_codes[N_Op_Minus] = NEGATE_EXPR;
10081 gnu_codes[N_Op_Abs] = ABS_EXPR;
10082 gnu_codes[N_Op_Not] = TRUTH_NOT_EXPR;
10083 gnu_codes[N_Op_Rotate_Left] = LROTATE_EXPR;
10084 gnu_codes[N_Op_Rotate_Right] = RROTATE_EXPR;
10085 gnu_codes[N_Op_Shift_Left] = LSHIFT_EXPR;
10086 gnu_codes[N_Op_Shift_Right] = RSHIFT_EXPR;
10087 gnu_codes[N_Op_Shift_Right_Arithmetic] = RSHIFT_EXPR;
10090 /* Return a label to branch to for the exception type in KIND or NULL_TREE
10091 if none. */
10093 tree
10094 get_exception_label (char kind)
10096 if (kind == N_Raise_Constraint_Error)
10097 return gnu_constraint_error_label_stack->last ();
10098 else if (kind == N_Raise_Storage_Error)
10099 return gnu_storage_error_label_stack->last ();
10100 else if (kind == N_Raise_Program_Error)
10101 return gnu_program_error_label_stack->last ();
10102 else
10103 return NULL_TREE;
10106 /* Return the decl for the current elaboration procedure. */
10108 tree
10109 get_elaboration_procedure (void)
10111 return gnu_elab_proc_stack->last ();
10114 #include "gt-ada-trans.h"