Merge from trunk @222673.
[official-gcc.git] / gcc / ada / gcc-interface / trans.c
blobbb3dfa9f2e63cc879ff294d89d26b36f8c9a03b5
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 "tm.h"
30 #include "hash-set.h"
31 #include "machmode.h"
32 #include "vec.h"
33 #include "double-int.h"
34 #include "input.h"
35 #include "alias.h"
36 #include "symtab.h"
37 #include "wide-int.h"
38 #include "inchash.h"
39 #include "real.h"
40 #include "tree.h"
41 #include "fold-const.h"
42 #include "stringpool.h"
43 #include "stor-layout.h"
44 #include "stmt.h"
45 #include "varasm.h"
46 #include "flags.h"
47 #include "output.h"
48 #include "libfuncs.h" /* For set_stack_check_libfunc. */
49 #include "tree-iterator.h"
50 #include "gimple-expr.h"
51 #include "gimplify.h"
52 #include "bitmap.h"
53 #include "hash-map.h"
54 #include "is-a.h"
55 #include "plugin-api.h"
56 #include "hard-reg-set.h"
57 #include "input.h"
58 #include "function.h"
59 #include "ipa-ref.h"
60 #include "cgraph.h"
61 #include "diagnostic.h"
62 #include "opts.h"
63 #include "target.h"
64 #include "common/common-target.h"
66 #include "ada.h"
67 #include "adadecode.h"
68 #include "types.h"
69 #include "atree.h"
70 #include "elists.h"
71 #include "namet.h"
72 #include "nlists.h"
73 #include "snames.h"
74 #include "stringt.h"
75 #include "uintp.h"
76 #include "urealp.h"
77 #include "fe.h"
78 #include "sinfo.h"
79 #include "einfo.h"
80 #include "gadaint.h"
81 #include "ada-tree.h"
82 #include "gigi.h"
84 /* We should avoid allocating more than ALLOCA_THRESHOLD bytes via alloca,
85 for fear of running out of stack space. If we need more, we use xmalloc
86 instead. */
87 #define ALLOCA_THRESHOLD 1000
89 /* In configurations where blocks have no end_locus attached, just
90 sink assignments into a dummy global. */
91 #ifndef BLOCK_SOURCE_END_LOCATION
92 static location_t block_end_locus_sink;
93 #define BLOCK_SOURCE_END_LOCATION(BLOCK) block_end_locus_sink
94 #endif
96 /* Pointers to front-end tables accessed through macros. */
97 struct Node *Nodes_Ptr;
98 struct Flags *Flags_Ptr;
99 Node_Id *Next_Node_Ptr;
100 Node_Id *Prev_Node_Ptr;
101 struct Elist_Header *Elists_Ptr;
102 struct Elmt_Item *Elmts_Ptr;
103 struct String_Entry *Strings_Ptr;
104 Char_Code *String_Chars_Ptr;
105 struct List_Header *List_Headers_Ptr;
107 /* Highest number in the front-end node table. */
108 int max_gnat_nodes;
110 /* Current node being treated, in case abort called. */
111 Node_Id error_gnat_node;
113 /* True when gigi is being called on an analyzed but unexpanded
114 tree, and the only purpose of the call is to properly annotate
115 types with representation information. */
116 bool type_annotate_only;
118 /* Current filename without path. */
119 const char *ref_filename;
122 /* List of N_Validate_Unchecked_Conversion nodes in the unit. */
123 static vec<Node_Id> gnat_validate_uc_list;
125 /* When not optimizing, we cache the 'First, 'Last and 'Length attributes
126 of unconstrained array IN parameters to avoid emitting a great deal of
127 redundant instructions to recompute them each time. */
128 struct GTY (()) parm_attr_d {
129 int id; /* GTY doesn't like Entity_Id. */
130 int dim;
131 tree first;
132 tree last;
133 tree length;
136 typedef struct parm_attr_d *parm_attr;
139 struct GTY(()) language_function {
140 vec<parm_attr, va_gc> *parm_attr_cache;
141 bitmap named_ret_val;
142 vec<tree, va_gc> *other_ret_val;
143 int gnat_ret;
146 #define f_parm_attr_cache \
147 DECL_STRUCT_FUNCTION (current_function_decl)->language->parm_attr_cache
149 #define f_named_ret_val \
150 DECL_STRUCT_FUNCTION (current_function_decl)->language->named_ret_val
152 #define f_other_ret_val \
153 DECL_STRUCT_FUNCTION (current_function_decl)->language->other_ret_val
155 #define f_gnat_ret \
156 DECL_STRUCT_FUNCTION (current_function_decl)->language->gnat_ret
158 /* A structure used to gather together information about a statement group.
159 We use this to gather related statements, for example the "then" part
160 of a IF. In the case where it represents a lexical scope, we may also
161 have a BLOCK node corresponding to it and/or cleanups. */
163 struct GTY((chain_next ("%h.previous"))) stmt_group {
164 struct stmt_group *previous; /* Previous code group. */
165 tree stmt_list; /* List of statements for this code group. */
166 tree block; /* BLOCK for this code group, if any. */
167 tree cleanups; /* Cleanups for this code group, if any. */
170 static GTY(()) struct stmt_group *current_stmt_group;
172 /* List of unused struct stmt_group nodes. */
173 static GTY((deletable)) struct stmt_group *stmt_group_free_list;
175 /* A structure used to record information on elaboration procedures
176 we've made and need to process.
178 ??? gnat_node should be Node_Id, but gengtype gets confused. */
180 struct GTY((chain_next ("%h.next"))) elab_info {
181 struct elab_info *next; /* Pointer to next in chain. */
182 tree elab_proc; /* Elaboration procedure. */
183 int gnat_node; /* The N_Compilation_Unit. */
186 static GTY(()) struct elab_info *elab_info_list;
188 /* Stack of exception pointer variables. Each entry is the VAR_DECL
189 that stores the address of the raised exception. Nonzero means we
190 are in an exception handler. Not used in the zero-cost case. */
191 static GTY(()) vec<tree, va_gc> *gnu_except_ptr_stack;
193 /* In ZCX case, current exception pointer. Used to re-raise it. */
194 static GTY(()) tree gnu_incoming_exc_ptr;
196 /* Stack for storing the current elaboration procedure decl. */
197 static GTY(()) vec<tree, va_gc> *gnu_elab_proc_stack;
199 /* Stack of labels to be used as a goto target instead of a return in
200 some functions. See processing for N_Subprogram_Body. */
201 static GTY(()) vec<tree, va_gc> *gnu_return_label_stack;
203 /* Stack of variable for the return value of a function with copy-in/copy-out
204 parameters. See processing for N_Subprogram_Body. */
205 static GTY(()) vec<tree, va_gc> *gnu_return_var_stack;
207 /* Structure used to record information for a range check. */
208 struct GTY(()) range_check_info_d {
209 tree low_bound;
210 tree high_bound;
211 tree type;
212 tree invariant_cond;
215 typedef struct range_check_info_d *range_check_info;
218 /* Structure used to record information for a loop. */
219 struct GTY(()) loop_info_d {
220 tree stmt;
221 tree loop_var;
222 vec<range_check_info, va_gc> *checks;
225 typedef struct loop_info_d *loop_info;
228 /* Stack of loop_info structures associated with LOOP_STMT nodes. */
229 static GTY(()) vec<loop_info, va_gc> *gnu_loop_stack;
231 /* The stacks for N_{Push,Pop}_*_Label. */
232 static GTY(()) vec<tree, va_gc> *gnu_constraint_error_label_stack;
233 static GTY(()) vec<tree, va_gc> *gnu_storage_error_label_stack;
234 static GTY(()) vec<tree, va_gc> *gnu_program_error_label_stack;
236 /* Map GNAT tree codes to GCC tree codes for simple expressions. */
237 static enum tree_code gnu_codes[Number_Node_Kinds];
239 static void init_code_table (void);
240 static void Compilation_Unit_to_gnu (Node_Id);
241 static void record_code_position (Node_Id);
242 static void insert_code_for (Node_Id);
243 static void add_cleanup (tree, Node_Id);
244 static void add_stmt_list (List_Id);
245 static void push_exception_label_stack (vec<tree, va_gc> **, Entity_Id);
246 static tree build_stmt_group (List_Id, bool);
247 static inline bool stmt_group_may_fallthru (void);
248 static enum gimplify_status gnat_gimplify_stmt (tree *);
249 static void elaborate_all_entities (Node_Id);
250 static void process_freeze_entity (Node_Id);
251 static void process_decls (List_Id, List_Id, Node_Id, bool, bool);
252 static tree emit_range_check (tree, Node_Id, Node_Id);
253 static tree emit_index_check (tree, tree, tree, tree, Node_Id);
254 static tree emit_check (tree, tree, int, Node_Id);
255 static tree build_unary_op_trapv (enum tree_code, tree, tree, Node_Id);
256 static tree build_binary_op_trapv (enum tree_code, tree, tree, tree, Node_Id);
257 static tree convert_with_check (Entity_Id, tree, bool, bool, bool, Node_Id);
258 static bool addressable_p (tree, tree);
259 static tree assoc_to_constructor (Entity_Id, Node_Id, tree);
260 static tree extract_values (tree, tree);
261 static tree pos_to_constructor (Node_Id, tree, Entity_Id);
262 static void validate_unchecked_conversion (Node_Id);
263 static tree maybe_implicit_deref (tree);
264 static void set_expr_location_from_node (tree, Node_Id);
265 static void set_expr_location_from_node1 (tree, Node_Id, bool);
266 static bool Sloc_to_locus1 (Source_Ptr, location_t *, bool);
267 static bool set_end_locus_from_node (tree, Node_Id);
268 static void set_gnu_expr_location_from_node (tree, Node_Id);
269 static int lvalue_required_p (Node_Id, tree, bool, bool, bool);
270 static tree build_raise_check (int, enum exception_info_kind);
271 static tree create_init_temporary (const char *, tree, tree *, Node_Id);
273 /* Hooks for debug info back-ends, only supported and used in a restricted set
274 of configurations. */
275 static const char *extract_encoding (const char *) ATTRIBUTE_UNUSED;
276 static const char *decode_name (const char *) ATTRIBUTE_UNUSED;
278 /* This is the main program of the back-end. It sets up all the table
279 structures and then generates code. */
281 void
282 gigi (Node_Id gnat_root,
283 int max_gnat_node,
284 int number_name ATTRIBUTE_UNUSED,
285 struct Node *nodes_ptr,
286 struct Flags *flags_ptr,
287 Node_Id *next_node_ptr,
288 Node_Id *prev_node_ptr,
289 struct Elist_Header *elists_ptr,
290 struct Elmt_Item *elmts_ptr,
291 struct String_Entry *strings_ptr,
292 Char_Code *string_chars_ptr,
293 struct List_Header *list_headers_ptr,
294 Nat number_file,
295 struct File_Info_Type *file_info_ptr,
296 Entity_Id standard_boolean,
297 Entity_Id standard_integer,
298 Entity_Id standard_character,
299 Entity_Id standard_long_long_float,
300 Entity_Id standard_exception_type,
301 Int gigi_operating_mode)
303 Node_Id gnat_iter;
304 Entity_Id gnat_literal;
305 tree t, ftype, int64_type;
306 struct elab_info *info;
307 int i;
309 max_gnat_nodes = max_gnat_node;
311 Nodes_Ptr = nodes_ptr;
312 Flags_Ptr = flags_ptr;
313 Next_Node_Ptr = next_node_ptr;
314 Prev_Node_Ptr = prev_node_ptr;
315 Elists_Ptr = elists_ptr;
316 Elmts_Ptr = elmts_ptr;
317 Strings_Ptr = strings_ptr;
318 String_Chars_Ptr = string_chars_ptr;
319 List_Headers_Ptr = list_headers_ptr;
321 type_annotate_only = (gigi_operating_mode == 1);
323 for (i = 0; i < number_file; i++)
325 /* Use the identifier table to make a permanent copy of the filename as
326 the name table gets reallocated after Gigi returns but before all the
327 debugging information is output. The __gnat_to_canonical_file_spec
328 call translates filenames from pragmas Source_Reference that contain
329 host style syntax not understood by gdb. */
330 const char *filename
331 = IDENTIFIER_POINTER
332 (get_identifier
333 (__gnat_to_canonical_file_spec
334 (Get_Name_String (file_info_ptr[i].File_Name))));
336 /* We rely on the order isomorphism between files and line maps. */
337 gcc_assert ((int) LINEMAPS_ORDINARY_USED (line_table) == i);
339 /* We create the line map for a source file at once, with a fixed number
340 of columns chosen to avoid jumping over the next power of 2. */
341 linemap_add (line_table, LC_ENTER, 0, filename, 1);
342 linemap_line_start (line_table, file_info_ptr[i].Num_Source_Lines, 252);
343 linemap_position_for_column (line_table, 252 - 1);
344 linemap_add (line_table, LC_LEAVE, 0, NULL, 0);
347 gcc_assert (Nkind (gnat_root) == N_Compilation_Unit);
349 /* Declare the name of the compilation unit as the first global
350 name in order to make the middle-end fully deterministic. */
351 t = create_concat_name (Defining_Entity (Unit (gnat_root)), NULL);
352 first_global_object_name = ggc_strdup (IDENTIFIER_POINTER (t));
354 /* Initialize ourselves. */
355 init_code_table ();
356 init_gnat_decl ();
357 init_gnat_utils ();
359 /* If we are just annotating types, give VOID_TYPE zero sizes to avoid
360 errors. */
361 if (type_annotate_only)
363 TYPE_SIZE (void_type_node) = bitsize_zero_node;
364 TYPE_SIZE_UNIT (void_type_node) = size_zero_node;
367 /* Enable GNAT stack checking method if needed */
368 if (!Stack_Check_Probes_On_Target)
369 set_stack_check_libfunc ("_gnat_stack_check");
371 /* Retrieve alignment settings. */
372 double_float_alignment = get_target_double_float_alignment ();
373 double_scalar_alignment = get_target_double_scalar_alignment ();
375 /* Record the builtin types. Define `integer' and `character' first so that
376 dbx will output them first. */
377 record_builtin_type ("integer", integer_type_node, false);
378 record_builtin_type ("character", unsigned_char_type_node, false);
379 record_builtin_type ("boolean", boolean_type_node, false);
380 record_builtin_type ("void", void_type_node, false);
382 /* Save the type we made for integer as the type for Standard.Integer. */
383 save_gnu_tree (Base_Type (standard_integer),
384 TYPE_NAME (integer_type_node),
385 false);
387 /* Likewise for character as the type for Standard.Character. */
388 save_gnu_tree (Base_Type (standard_character),
389 TYPE_NAME (unsigned_char_type_node),
390 false);
392 /* Likewise for boolean as the type for Standard.Boolean. */
393 save_gnu_tree (Base_Type (standard_boolean),
394 TYPE_NAME (boolean_type_node),
395 false);
396 gnat_literal = First_Literal (Base_Type (standard_boolean));
397 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
398 gcc_assert (t == boolean_false_node);
399 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
400 boolean_type_node, t, true, false, false, false,
401 NULL, gnat_literal);
402 DECL_IGNORED_P (t) = 1;
403 save_gnu_tree (gnat_literal, t, false);
404 gnat_literal = Next_Literal (gnat_literal);
405 t = UI_To_gnu (Enumeration_Rep (gnat_literal), boolean_type_node);
406 gcc_assert (t == boolean_true_node);
407 t = create_var_decl (get_entity_name (gnat_literal), NULL_TREE,
408 boolean_type_node, t, true, false, false, false,
409 NULL, gnat_literal);
410 DECL_IGNORED_P (t) = 1;
411 save_gnu_tree (gnat_literal, t, false);
413 void_ftype = build_function_type_list (void_type_node, NULL_TREE);
414 ptr_void_ftype = build_pointer_type (void_ftype);
416 /* Now declare run-time functions. */
417 ftype = build_function_type_list (ptr_void_type_node, sizetype, NULL_TREE);
419 /* malloc is a function declaration tree for a function to allocate
420 memory. */
421 malloc_decl
422 = create_subprog_decl (get_identifier ("__gnat_malloc"), NULL_TREE,
423 ftype, NULL_TREE, is_disabled, true, true, true,
424 NULL, Empty);
425 DECL_IS_MALLOC (malloc_decl) = 1;
427 /* free is a function declaration tree for a function to free memory. */
428 free_decl
429 = create_subprog_decl (get_identifier ("__gnat_free"), NULL_TREE,
430 build_function_type_list (void_type_node,
431 ptr_void_type_node,
432 NULL_TREE),
433 NULL_TREE, is_disabled, true, true, true, NULL,
434 Empty);
436 /* This is used for 64-bit multiplication with overflow checking. */
437 int64_type = gnat_type_for_size (64, 0);
438 mulv64_decl
439 = create_subprog_decl (get_identifier ("__gnat_mulv64"), NULL_TREE,
440 build_function_type_list (int64_type, int64_type,
441 int64_type, NULL_TREE),
442 NULL_TREE, is_disabled, true, true, true, NULL,
443 Empty);
445 /* Name of the _Parent field in tagged record types. */
446 parent_name_id = get_identifier (Get_Name_String (Name_uParent));
448 /* Name of the Exception_Data type defined in System.Standard_Library. */
449 exception_data_name_id
450 = get_identifier ("system__standard_library__exception_data");
452 /* Make the types and functions used for exception processing. */
453 jmpbuf_type
454 = build_array_type (gnat_type_for_mode (Pmode, 0),
455 build_index_type (size_int (5)));
456 record_builtin_type ("JMPBUF_T", jmpbuf_type, true);
457 jmpbuf_ptr_type = build_pointer_type (jmpbuf_type);
459 /* Functions to get and set the jumpbuf pointer for the current thread. */
460 get_jmpbuf_decl
461 = create_subprog_decl
462 (get_identifier ("system__soft_links__get_jmpbuf_address_soft"),
463 NULL_TREE, build_function_type_list (jmpbuf_ptr_type, NULL_TREE),
464 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
465 DECL_IGNORED_P (get_jmpbuf_decl) = 1;
467 set_jmpbuf_decl
468 = create_subprog_decl
469 (get_identifier ("system__soft_links__set_jmpbuf_address_soft"),
470 NULL_TREE, build_function_type_list (void_type_node, jmpbuf_ptr_type,
471 NULL_TREE),
472 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
473 DECL_IGNORED_P (set_jmpbuf_decl) = 1;
475 /* setjmp returns an integer and has one operand, which is a pointer to
476 a jmpbuf. */
477 setjmp_decl
478 = create_subprog_decl
479 (get_identifier ("__builtin_setjmp"), NULL_TREE,
480 build_function_type_list (integer_type_node, jmpbuf_ptr_type,
481 NULL_TREE),
482 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
483 DECL_BUILT_IN_CLASS (setjmp_decl) = BUILT_IN_NORMAL;
484 DECL_FUNCTION_CODE (setjmp_decl) = BUILT_IN_SETJMP;
486 /* update_setjmp_buf updates a setjmp buffer from the current stack pointer
487 address. */
488 update_setjmp_buf_decl
489 = create_subprog_decl
490 (get_identifier ("__builtin_update_setjmp_buf"), NULL_TREE,
491 build_function_type_list (void_type_node, jmpbuf_ptr_type, NULL_TREE),
492 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
493 DECL_BUILT_IN_CLASS (update_setjmp_buf_decl) = BUILT_IN_NORMAL;
494 DECL_FUNCTION_CODE (update_setjmp_buf_decl) = BUILT_IN_UPDATE_SETJMP_BUF;
496 /* Hooks to call when entering/leaving an exception handler. */
497 ftype
498 = build_function_type_list (void_type_node, ptr_void_type_node, NULL_TREE);
500 begin_handler_decl
501 = create_subprog_decl (get_identifier ("__gnat_begin_handler"), NULL_TREE,
502 ftype, NULL_TREE, is_disabled, true, true, true,
503 NULL, Empty);
504 DECL_IGNORED_P (begin_handler_decl) = 1;
506 end_handler_decl
507 = create_subprog_decl (get_identifier ("__gnat_end_handler"), NULL_TREE,
508 ftype, NULL_TREE, is_disabled, true, true, true,
509 NULL, Empty);
510 DECL_IGNORED_P (end_handler_decl) = 1;
512 unhandled_except_decl
513 = create_subprog_decl (get_identifier ("__gnat_unhandled_except_handler"),
514 NULL_TREE,
515 ftype, NULL_TREE, is_disabled, true, true, true,
516 NULL, Empty);
517 DECL_IGNORED_P (unhandled_except_decl) = 1;
519 reraise_zcx_decl
520 = create_subprog_decl (get_identifier ("__gnat_reraise_zcx"), NULL_TREE,
521 ftype, NULL_TREE, is_disabled, true, true, true,
522 NULL, Empty);
523 /* Indicate that these never return. */
524 DECL_IGNORED_P (reraise_zcx_decl) = 1;
525 TREE_THIS_VOLATILE (reraise_zcx_decl) = 1;
526 TREE_SIDE_EFFECTS (reraise_zcx_decl) = 1;
527 TREE_TYPE (reraise_zcx_decl)
528 = build_qualified_type (TREE_TYPE (reraise_zcx_decl), TYPE_QUAL_VOLATILE);
530 /* If in no exception handlers mode, all raise statements are redirected to
531 __gnat_last_chance_handler. No need to redefine raise_nodefer_decl since
532 this procedure will never be called in this mode. */
533 if (No_Exception_Handlers_Set ())
535 tree decl
536 = create_subprog_decl
537 (get_identifier ("__gnat_last_chance_handler"), NULL_TREE,
538 build_function_type_list (void_type_node,
539 build_pointer_type
540 (unsigned_char_type_node),
541 integer_type_node, NULL_TREE),
542 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
543 TREE_THIS_VOLATILE (decl) = 1;
544 TREE_SIDE_EFFECTS (decl) = 1;
545 TREE_TYPE (decl)
546 = build_qualified_type (TREE_TYPE (decl), TYPE_QUAL_VOLATILE);
547 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
548 gnat_raise_decls[i] = decl;
550 else
552 /* Otherwise, make one decl for each exception reason. */
553 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls); i++)
554 gnat_raise_decls[i] = build_raise_check (i, exception_simple);
555 for (i = 0; i < (int) ARRAY_SIZE (gnat_raise_decls_ext); i++)
556 gnat_raise_decls_ext[i]
557 = build_raise_check (i,
558 i == CE_Index_Check_Failed
559 || i == CE_Range_Check_Failed
560 || i == CE_Invalid_Data
561 ? exception_range : exception_column);
564 /* Set the types that GCC and Gigi use from the front end. */
565 except_type_node = gnat_to_gnu_type (Base_Type (standard_exception_type));
567 /* Make other functions used for exception processing. */
568 get_excptr_decl
569 = create_subprog_decl
570 (get_identifier ("system__soft_links__get_gnat_exception"), NULL_TREE,
571 build_function_type_list (build_pointer_type (except_type_node),
572 NULL_TREE),
573 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
574 DECL_IGNORED_P (get_excptr_decl) = 1;
576 set_exception_parameter_decl
577 = create_subprog_decl
578 (get_identifier ("__gnat_set_exception_parameter"), NULL_TREE,
579 build_function_type_list (void_type_node,
580 ptr_void_type_node,
581 ptr_void_type_node,
582 NULL_TREE),
583 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
585 raise_nodefer_decl
586 = create_subprog_decl
587 (get_identifier ("__gnat_raise_nodefer_with_msg"), NULL_TREE,
588 build_function_type_list (void_type_node,
589 build_pointer_type (except_type_node),
590 NULL_TREE),
591 NULL_TREE, is_disabled, true, true, true, NULL, Empty);
593 /* Indicate that it never returns. */
594 TREE_THIS_VOLATILE (raise_nodefer_decl) = 1;
595 TREE_SIDE_EFFECTS (raise_nodefer_decl) = 1;
596 TREE_TYPE (raise_nodefer_decl)
597 = build_qualified_type (TREE_TYPE (raise_nodefer_decl),
598 TYPE_QUAL_VOLATILE);
600 /* Build the special descriptor type and its null node if needed. */
601 if (TARGET_VTABLE_USES_DESCRIPTORS)
603 tree null_node = fold_convert (ptr_void_ftype, null_pointer_node);
604 tree field_list = NULL_TREE;
605 int j;
606 vec<constructor_elt, va_gc> *null_vec = NULL;
607 constructor_elt *elt;
609 fdesc_type_node = make_node (RECORD_TYPE);
610 vec_safe_grow (null_vec, TARGET_VTABLE_USES_DESCRIPTORS);
611 elt = (null_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
613 for (j = 0; j < TARGET_VTABLE_USES_DESCRIPTORS; j++)
615 tree field
616 = create_field_decl (NULL_TREE, ptr_void_ftype, fdesc_type_node,
617 NULL_TREE, NULL_TREE, 0, 1);
618 DECL_CHAIN (field) = field_list;
619 field_list = field;
620 elt->index = field;
621 elt->value = null_node;
622 elt--;
625 finish_record_type (fdesc_type_node, nreverse (field_list), 0, false);
626 record_builtin_type ("descriptor", fdesc_type_node, true);
627 null_fdesc_node = gnat_build_constructor (fdesc_type_node, null_vec);
630 longest_float_type_node
631 = get_unpadded_type (Base_Type (standard_long_long_float));
633 /* Dummy objects to materialize "others" and "all others" in the exception
634 tables. These are exported by a-exexpr-gcc.adb, so see this unit for
635 the types to use. */
636 others_decl
637 = create_var_decl (get_identifier ("OTHERS"),
638 get_identifier ("__gnat_others_value"),
639 unsigned_char_type_node,
640 NULL_TREE, true, false, true, false, NULL, Empty);
642 all_others_decl
643 = create_var_decl (get_identifier ("ALL_OTHERS"),
644 get_identifier ("__gnat_all_others_value"),
645 unsigned_char_type_node,
646 NULL_TREE, true, false, true, false, NULL, Empty);
648 unhandled_others_decl
649 = create_var_decl (get_identifier ("UNHANDLED_OTHERS"),
650 get_identifier ("__gnat_unhandled_others_value"),
651 unsigned_char_type_node,
652 NULL_TREE, true, false, true, false, NULL, Empty);
654 main_identifier_node = get_identifier ("main");
656 /* Install the builtins we might need, either internally or as
657 user available facilities for Intrinsic imports. */
658 gnat_install_builtins ();
660 vec_safe_push (gnu_except_ptr_stack, NULL_TREE);
661 vec_safe_push (gnu_constraint_error_label_stack, NULL_TREE);
662 vec_safe_push (gnu_storage_error_label_stack, NULL_TREE);
663 vec_safe_push (gnu_program_error_label_stack, NULL_TREE);
665 /* Process any Pragma Ident for the main unit. */
666 if (Present (Ident_String (Main_Unit)))
667 targetm.asm_out.output_ident
668 (TREE_STRING_POINTER (gnat_to_gnu (Ident_String (Main_Unit))));
670 /* If we are using the GCC exception mechanism, let GCC know. */
671 if (Exception_Mechanism == Back_End_Exceptions)
672 gnat_init_gcc_eh ();
674 /* Initialize the GCC support for FP operations. */
675 gnat_init_gcc_fp ();
677 /* Force -fno-strict-aliasing if the configuration pragma was seen. */
678 if (No_Strict_Aliasing_CP)
679 flag_strict_aliasing = 0;
681 /* Save the current optimization options again after the above possible
682 global_options changes. */
683 optimization_default_node = build_optimization_node (&global_options);
684 optimization_current_node = optimization_default_node;
686 /* Now translate the compilation unit proper. */
687 Compilation_Unit_to_gnu (gnat_root);
689 /* Then process the N_Validate_Unchecked_Conversion nodes. We do this at
690 the very end to avoid having to second-guess the front-end when we run
691 into dummy nodes during the regular processing. */
692 for (i = 0; gnat_validate_uc_list.iterate (i, &gnat_iter); i++)
693 validate_unchecked_conversion (gnat_iter);
694 gnat_validate_uc_list.release ();
696 /* Finally see if we have any elaboration procedures to deal with. */
697 for (info = elab_info_list; info; info = info->next)
699 tree gnu_body = DECL_SAVED_TREE (info->elab_proc), gnu_stmts;
701 /* We should have a BIND_EXPR but it may not have any statements in it.
702 If it doesn't have any, we have nothing to do except for setting the
703 flag on the GNAT node. Otherwise, process the function as others. */
704 gnu_stmts = gnu_body;
705 if (TREE_CODE (gnu_stmts) == BIND_EXPR)
706 gnu_stmts = BIND_EXPR_BODY (gnu_stmts);
707 if (!gnu_stmts || !STATEMENT_LIST_HEAD (gnu_stmts))
708 Set_Has_No_Elaboration_Code (info->gnat_node, 1);
709 else
711 begin_subprog_body (info->elab_proc);
712 end_subprog_body (gnu_body);
713 rest_of_subprog_body_compilation (info->elab_proc);
717 /* Destroy ourselves. */
718 destroy_gnat_decl ();
719 destroy_gnat_utils ();
721 /* We cannot track the location of errors past this point. */
722 error_gnat_node = Empty;
725 /* Return a subprogram decl corresponding to __gnat_rcheck_xx for the given
726 CHECK if KIND is EXCEPTION_SIMPLE, or else to __gnat_rcheck_xx_ext. */
728 static tree
729 build_raise_check (int check, enum exception_info_kind kind)
731 tree result, ftype;
732 const char pfx[] = "__gnat_rcheck_";
734 strcpy (Name_Buffer, pfx);
735 Name_Len = sizeof (pfx) - 1;
736 Get_RT_Exception_Name (check);
738 if (kind == exception_simple)
740 Name_Buffer[Name_Len] = 0;
741 ftype
742 = build_function_type_list (void_type_node,
743 build_pointer_type
744 (unsigned_char_type_node),
745 integer_type_node, NULL_TREE);
747 else
749 tree t = (kind == exception_column ? NULL_TREE : integer_type_node);
751 strcpy (Name_Buffer + Name_Len, "_ext");
752 Name_Buffer[Name_Len + 4] = 0;
753 ftype
754 = build_function_type_list (void_type_node,
755 build_pointer_type
756 (unsigned_char_type_node),
757 integer_type_node, integer_type_node,
758 t, t, NULL_TREE);
761 result
762 = create_subprog_decl (get_identifier (Name_Buffer),
763 NULL_TREE, ftype, NULL_TREE,
764 is_disabled, true, true, true, NULL, Empty);
766 /* Indicate that it never returns. */
767 TREE_THIS_VOLATILE (result) = 1;
768 TREE_SIDE_EFFECTS (result) = 1;
769 TREE_TYPE (result)
770 = build_qualified_type (TREE_TYPE (result), TYPE_QUAL_VOLATILE);
772 return result;
775 /* Return a positive value if an lvalue is required for GNAT_NODE, which is
776 an N_Attribute_Reference. */
778 static int
779 lvalue_required_for_attribute_p (Node_Id gnat_node)
781 switch (Get_Attribute_Id (Attribute_Name (gnat_node)))
783 case Attr_Pos:
784 case Attr_Val:
785 case Attr_Pred:
786 case Attr_Succ:
787 case Attr_First:
788 case Attr_Last:
789 case Attr_Range_Length:
790 case Attr_Length:
791 case Attr_Object_Size:
792 case Attr_Value_Size:
793 case Attr_Component_Size:
794 case Attr_Descriptor_Size:
795 case Attr_Max_Size_In_Storage_Elements:
796 case Attr_Min:
797 case Attr_Max:
798 case Attr_Null_Parameter:
799 case Attr_Passed_By_Reference:
800 case Attr_Mechanism_Code:
801 case Attr_Machine:
802 case Attr_Model:
803 return 0;
805 case Attr_Address:
806 case Attr_Access:
807 case Attr_Unchecked_Access:
808 case Attr_Unrestricted_Access:
809 case Attr_Code_Address:
810 case Attr_Pool_Address:
811 case Attr_Size:
812 case Attr_Alignment:
813 case Attr_Bit_Position:
814 case Attr_Position:
815 case Attr_First_Bit:
816 case Attr_Last_Bit:
817 case Attr_Bit:
818 case Attr_Asm_Input:
819 case Attr_Asm_Output:
820 default:
821 return 1;
825 /* Return a positive value if an lvalue is required for GNAT_NODE. GNU_TYPE
826 is the type that will be used for GNAT_NODE in the translated GNU tree.
827 CONSTANT indicates whether the underlying object represented by GNAT_NODE
828 is constant in the Ada sense. If it is, ADDRESS_OF_CONSTANT indicates
829 whether its value is the address of a constant and ALIASED whether it is
830 aliased. If it isn't, ADDRESS_OF_CONSTANT and ALIASED are ignored.
832 The function climbs up the GNAT tree starting from the node and returns 1
833 upon encountering a node that effectively requires an lvalue downstream.
834 It returns int instead of bool to facilitate usage in non-purely binary
835 logic contexts. */
837 static int
838 lvalue_required_p (Node_Id gnat_node, tree gnu_type, bool constant,
839 bool address_of_constant, bool aliased)
841 Node_Id gnat_parent = Parent (gnat_node), gnat_temp;
843 switch (Nkind (gnat_parent))
845 case N_Reference:
846 return 1;
848 case N_Attribute_Reference:
849 return lvalue_required_for_attribute_p (gnat_parent);
851 case N_Parameter_Association:
852 case N_Function_Call:
853 case N_Procedure_Call_Statement:
854 /* If the parameter is by reference, an lvalue is required. */
855 return (!constant
856 || must_pass_by_ref (gnu_type)
857 || default_pass_by_ref (gnu_type));
859 case N_Indexed_Component:
860 /* Only the array expression can require an lvalue. */
861 if (Prefix (gnat_parent) != gnat_node)
862 return 0;
864 /* ??? Consider that referencing an indexed component with a
865 non-constant index forces the whole aggregate to memory.
866 Note that N_Integer_Literal is conservative, any static
867 expression in the RM sense could probably be accepted. */
868 for (gnat_temp = First (Expressions (gnat_parent));
869 Present (gnat_temp);
870 gnat_temp = Next (gnat_temp))
871 if (Nkind (gnat_temp) != N_Integer_Literal)
872 return 1;
874 /* ... fall through ... */
876 case N_Slice:
877 /* Only the array expression can require an lvalue. */
878 if (Prefix (gnat_parent) != gnat_node)
879 return 0;
881 aliased |= Has_Aliased_Components (Etype (gnat_node));
882 return lvalue_required_p (gnat_parent, gnu_type, constant,
883 address_of_constant, aliased);
885 case N_Selected_Component:
886 aliased |= Is_Aliased (Entity (Selector_Name (gnat_parent)));
887 return lvalue_required_p (gnat_parent, gnu_type, constant,
888 address_of_constant, aliased);
890 case N_Object_Renaming_Declaration:
891 /* We need to preserve addresses through a renaming. */
892 return 1;
894 case N_Object_Declaration:
895 /* We cannot use a constructor if this is an atomic object because
896 the actual assignment might end up being done component-wise. */
897 return (!constant
898 ||(Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
899 && Is_Atomic (Defining_Entity (gnat_parent)))
900 /* We don't use a constructor if this is a class-wide object
901 because the effective type of the object is the equivalent
902 type of the class-wide subtype and it smashes most of the
903 data into an array of bytes to which we cannot convert. */
904 || Ekind ((Etype (Defining_Entity (gnat_parent))))
905 == E_Class_Wide_Subtype);
907 case N_Assignment_Statement:
908 /* We cannot use a constructor if the LHS is an atomic object because
909 the actual assignment might end up being done component-wise. */
910 return (!constant
911 || Name (gnat_parent) == gnat_node
912 || (Is_Composite_Type (Underlying_Type (Etype (gnat_node)))
913 && Is_Atomic (Entity (Name (gnat_parent)))));
915 case N_Unchecked_Type_Conversion:
916 if (!constant)
917 return 1;
919 /* ... fall through ... */
921 case N_Type_Conversion:
922 case N_Qualified_Expression:
923 /* We must look through all conversions because we may need to bypass
924 an intermediate conversion that is meant to be purely formal. */
925 return lvalue_required_p (gnat_parent,
926 get_unpadded_type (Etype (gnat_parent)),
927 constant, address_of_constant, aliased);
929 case N_Allocator:
930 /* We should only reach here through the N_Qualified_Expression case.
931 Force an lvalue for composite types since a block-copy to the newly
932 allocated area of memory is made. */
933 return Is_Composite_Type (Underlying_Type (Etype (gnat_node)));
935 case N_Explicit_Dereference:
936 /* We look through dereferences for address of constant because we need
937 to handle the special cases listed above. */
938 if (constant && address_of_constant)
939 return lvalue_required_p (gnat_parent,
940 get_unpadded_type (Etype (gnat_parent)),
941 true, false, true);
943 /* ... fall through ... */
945 default:
946 return 0;
949 gcc_unreachable ();
952 /* Return true if T is a constant DECL node that can be safely replaced
953 by its initializer. */
955 static bool
956 constant_decl_with_initializer_p (tree t)
958 if (!TREE_CONSTANT (t) || !DECL_P (t) || !DECL_INITIAL (t))
959 return false;
961 /* Return false for aggregate types that contain a placeholder since
962 their initializers cannot be manipulated easily. */
963 if (AGGREGATE_TYPE_P (TREE_TYPE (t))
964 && !TYPE_IS_FAT_POINTER_P (TREE_TYPE (t))
965 && type_contains_placeholder_p (TREE_TYPE (t)))
966 return false;
968 return true;
971 /* Return an expression equivalent to EXP but where constant DECL nodes
972 have been replaced by their initializer. */
974 static tree
975 fold_constant_decl_in_expr (tree exp)
977 enum tree_code code = TREE_CODE (exp);
978 tree op0;
980 switch (code)
982 case CONST_DECL:
983 case VAR_DECL:
984 if (!constant_decl_with_initializer_p (exp))
985 return exp;
987 return DECL_INITIAL (exp);
989 case BIT_FIELD_REF:
990 case COMPONENT_REF:
991 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
992 if (op0 == TREE_OPERAND (exp, 0))
993 return exp;
995 return fold_build3 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
996 TREE_OPERAND (exp, 2));
998 case ARRAY_REF:
999 case ARRAY_RANGE_REF:
1000 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1001 if (op0 == TREE_OPERAND (exp, 0))
1002 return exp;
1004 return fold (build4 (code, TREE_TYPE (exp), op0, TREE_OPERAND (exp, 1),
1005 TREE_OPERAND (exp, 2), TREE_OPERAND (exp, 3)));
1007 case VIEW_CONVERT_EXPR:
1008 case REALPART_EXPR:
1009 case IMAGPART_EXPR:
1010 op0 = fold_constant_decl_in_expr (TREE_OPERAND (exp, 0));
1011 if (op0 == TREE_OPERAND (exp, 0))
1012 return exp;
1014 return fold_build1 (code, TREE_TYPE (exp), op0);
1016 default:
1017 return exp;
1020 gcc_unreachable ();
1023 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Identifier,
1024 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer
1025 to where we should place the result type. */
1027 static tree
1028 Identifier_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
1030 Node_Id gnat_temp, gnat_temp_type;
1031 tree gnu_result, gnu_result_type;
1033 /* Whether we should require an lvalue for GNAT_NODE. Needed in
1034 specific circumstances only, so evaluated lazily. < 0 means
1035 unknown, > 0 means known true, 0 means known false. */
1036 int require_lvalue = -1;
1038 /* If GNAT_NODE is a constant, whether we should use the initialization
1039 value instead of the constant entity, typically for scalars with an
1040 address clause when the parent doesn't require an lvalue. */
1041 bool use_constant_initializer = false;
1043 /* If the Etype of this node does not equal the Etype of the Entity,
1044 something is wrong with the entity map, probably in generic
1045 instantiation. However, this does not apply to types. Since we sometime
1046 have strange Ekind's, just do this test for objects. Also, if the Etype of
1047 the Entity is private, the Etype of the N_Identifier is allowed to be the
1048 full type and also we consider a packed array type to be the same as the
1049 original type. Similarly, a class-wide type is equivalent to a subtype of
1050 itself. Finally, if the types are Itypes, one may be a copy of the other,
1051 which is also legal. */
1052 gnat_temp = (Nkind (gnat_node) == N_Defining_Identifier
1053 ? gnat_node : Entity (gnat_node));
1054 gnat_temp_type = Etype (gnat_temp);
1056 gcc_assert (Etype (gnat_node) == gnat_temp_type
1057 || (Is_Packed (gnat_temp_type)
1058 && (Etype (gnat_node)
1059 == Packed_Array_Impl_Type (gnat_temp_type)))
1060 || (Is_Class_Wide_Type (Etype (gnat_node)))
1061 || (IN (Ekind (gnat_temp_type), Private_Kind)
1062 && Present (Full_View (gnat_temp_type))
1063 && ((Etype (gnat_node) == Full_View (gnat_temp_type))
1064 || (Is_Packed (Full_View (gnat_temp_type))
1065 && (Etype (gnat_node)
1066 == Packed_Array_Impl_Type
1067 (Full_View (gnat_temp_type))))))
1068 || (Is_Itype (Etype (gnat_node)) && Is_Itype (gnat_temp_type))
1069 || !(Ekind (gnat_temp) == E_Variable
1070 || Ekind (gnat_temp) == E_Component
1071 || Ekind (gnat_temp) == E_Constant
1072 || Ekind (gnat_temp) == E_Loop_Parameter
1073 || IN (Ekind (gnat_temp), Formal_Kind)));
1075 /* If this is a reference to a deferred constant whose partial view is an
1076 unconstrained private type, the proper type is on the full view of the
1077 constant, not on the full view of the type, which may be unconstrained.
1079 This may be a reference to a type, for example in the prefix of the
1080 attribute Position, generated for dispatching code (see Make_DT in
1081 exp_disp,adb). In that case we need the type itself, not is parent,
1082 in particular if it is a derived type */
1083 if (Ekind (gnat_temp) == E_Constant
1084 && Is_Private_Type (gnat_temp_type)
1085 && (Has_Unknown_Discriminants (gnat_temp_type)
1086 || (Present (Full_View (gnat_temp_type))
1087 && Has_Discriminants (Full_View (gnat_temp_type))))
1088 && Present (Full_View (gnat_temp)))
1090 gnat_temp = Full_View (gnat_temp);
1091 gnat_temp_type = Etype (gnat_temp);
1093 else
1095 /* We want to use the Actual_Subtype if it has already been elaborated,
1096 otherwise the Etype. Avoid using Actual_Subtype for packed arrays to
1097 simplify things. */
1098 if ((Ekind (gnat_temp) == E_Constant
1099 || Ekind (gnat_temp) == E_Variable || Is_Formal (gnat_temp))
1100 && !(Is_Array_Type (Etype (gnat_temp))
1101 && Present (Packed_Array_Impl_Type (Etype (gnat_temp))))
1102 && Present (Actual_Subtype (gnat_temp))
1103 && present_gnu_tree (Actual_Subtype (gnat_temp)))
1104 gnat_temp_type = Actual_Subtype (gnat_temp);
1105 else
1106 gnat_temp_type = Etype (gnat_node);
1109 /* Expand the type of this identifier first, in case it is an enumeral
1110 literal, which only get made when the type is expanded. There is no
1111 order-of-elaboration issue here. */
1112 gnu_result_type = get_unpadded_type (gnat_temp_type);
1114 /* If this is a non-imported elementary constant with an address clause,
1115 retrieve the value instead of a pointer to be dereferenced unless
1116 an lvalue is required. This is generally more efficient and actually
1117 required if this is a static expression because it might be used
1118 in a context where a dereference is inappropriate, such as a case
1119 statement alternative or a record discriminant. There is no possible
1120 volatile-ness short-circuit here since Volatile constants must be
1121 imported per C.6. */
1122 if (Ekind (gnat_temp) == E_Constant
1123 && Is_Elementary_Type (gnat_temp_type)
1124 && !Is_Imported (gnat_temp)
1125 && Present (Address_Clause (gnat_temp)))
1127 require_lvalue = lvalue_required_p (gnat_node, gnu_result_type, true,
1128 false, Is_Aliased (gnat_temp));
1129 use_constant_initializer = !require_lvalue;
1132 if (use_constant_initializer)
1134 /* If this is a deferred constant, the initializer is attached to
1135 the full view. */
1136 if (Present (Full_View (gnat_temp)))
1137 gnat_temp = Full_View (gnat_temp);
1139 gnu_result = gnat_to_gnu (Expression (Declaration_Node (gnat_temp)));
1141 else
1142 gnu_result = gnat_to_gnu_entity (gnat_temp, NULL_TREE, 0);
1144 /* Some objects (such as parameters passed by reference, globals of
1145 variable size, and renamed objects) actually represent the address
1146 of the object. In that case, we must do the dereference. Likewise,
1147 deal with parameters to foreign convention subprograms. */
1148 if (DECL_P (gnu_result)
1149 && (DECL_BY_REF_P (gnu_result)
1150 || (TREE_CODE (gnu_result) == PARM_DECL
1151 && DECL_BY_COMPONENT_PTR_P (gnu_result))))
1153 const bool read_only = DECL_POINTS_TO_READONLY_P (gnu_result);
1155 /* If it's a PARM_DECL to foreign convention subprogram, convert it. */
1156 if (TREE_CODE (gnu_result) == PARM_DECL
1157 && DECL_BY_COMPONENT_PTR_P (gnu_result))
1158 gnu_result
1159 = convert (build_pointer_type (gnu_result_type), gnu_result);
1161 /* If it's a CONST_DECL, return the underlying constant like below. */
1162 else if (TREE_CODE (gnu_result) == CONST_DECL
1163 && !(DECL_CONST_ADDRESS_P (gnu_result)
1164 && lvalue_required_p (gnat_node, gnu_result_type, true,
1165 true, false)))
1166 gnu_result = DECL_INITIAL (gnu_result);
1168 /* If it's a renaming pointer and, either the renamed object is constant
1169 or we are at the right binding level, we can reference the renamed
1170 object directly, since it is constant or has been protected against
1171 multiple evaluations. */
1172 if (TREE_CODE (gnu_result) == VAR_DECL
1173 && !DECL_LOOP_PARM_P (gnu_result)
1174 && DECL_RENAMED_OBJECT (gnu_result)
1175 && (TREE_CONSTANT (DECL_RENAMED_OBJECT (gnu_result))
1176 || !DECL_RENAMING_GLOBAL_P (gnu_result)
1177 || global_bindings_p ()))
1178 gnu_result = DECL_RENAMED_OBJECT (gnu_result);
1180 /* Otherwise, do the final dereference. */
1181 else
1183 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
1185 if ((TREE_CODE (gnu_result) == INDIRECT_REF
1186 || TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
1187 && No (Address_Clause (gnat_temp)))
1188 TREE_THIS_NOTRAP (gnu_result) = 1;
1190 if (read_only)
1191 TREE_READONLY (gnu_result) = 1;
1195 /* If we have a constant declaration and its initializer, try to return the
1196 latter to avoid the need to call fold in lots of places and the need for
1197 elaboration code if this identifier is used as an initializer itself. */
1198 if (constant_decl_with_initializer_p (gnu_result))
1200 bool constant_only = (TREE_CODE (gnu_result) == CONST_DECL
1201 && !DECL_CONST_CORRESPONDING_VAR (gnu_result));
1202 bool address_of_constant = (TREE_CODE (gnu_result) == CONST_DECL
1203 && DECL_CONST_ADDRESS_P (gnu_result));
1205 /* If there is a (corresponding) variable or this is the address of a
1206 constant, we only want to return the initializer if an lvalue isn't
1207 required. Evaluate this now if we have not already done so. */
1208 if ((!constant_only || address_of_constant) && require_lvalue < 0)
1209 require_lvalue
1210 = lvalue_required_p (gnat_node, gnu_result_type, true,
1211 address_of_constant, Is_Aliased (gnat_temp));
1213 /* Finally retrieve the initializer if this is deemed valid. */
1214 if ((constant_only && !address_of_constant) || !require_lvalue)
1215 gnu_result = DECL_INITIAL (gnu_result);
1218 /* But for a constant renaming we couldn't do that incrementally for its
1219 definition because of the need to return an lvalue so, if the present
1220 context doesn't itself require an lvalue, we try again here. */
1221 else if (Ekind (gnat_temp) == E_Constant
1222 && Is_Elementary_Type (gnat_temp_type)
1223 && Present (Renamed_Object (gnat_temp)))
1225 if (require_lvalue < 0)
1226 require_lvalue
1227 = lvalue_required_p (gnat_node, gnu_result_type, true, false,
1228 Is_Aliased (gnat_temp));
1229 if (!require_lvalue)
1230 gnu_result = fold_constant_decl_in_expr (gnu_result);
1233 /* The GNAT tree has the type of a function set to its result type, so we
1234 adjust here. Also use the type of the result if the Etype is a subtype
1235 that is nominally unconstrained. Likewise if this is a deferred constant
1236 of a discriminated type whose full view can be elaborated statically, to
1237 avoid problematic conversions to the nominal subtype. But remove any
1238 padding from the resulting type. */
1239 if (TREE_CODE (TREE_TYPE (gnu_result)) == FUNCTION_TYPE
1240 || Is_Constr_Subt_For_UN_Aliased (gnat_temp_type)
1241 || (Ekind (gnat_temp) == E_Constant
1242 && Present (Full_View (gnat_temp))
1243 && Has_Discriminants (gnat_temp_type)
1244 && TREE_CODE (gnu_result) == CONSTRUCTOR))
1246 gnu_result_type = TREE_TYPE (gnu_result);
1247 if (TYPE_IS_PADDING_P (gnu_result_type))
1248 gnu_result_type = TREE_TYPE (TYPE_FIELDS (gnu_result_type));
1251 *gnu_result_type_p = gnu_result_type;
1253 return gnu_result;
1256 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Pragma. Return
1257 any statements we generate. */
1259 static tree
1260 Pragma_to_gnu (Node_Id gnat_node)
1262 tree gnu_result = alloc_stmt_list ();
1263 unsigned char pragma_id;
1264 Node_Id gnat_temp;
1266 /* Do nothing if we are just annotating types and check for (and ignore)
1267 unrecognized pragmas. */
1268 if (type_annotate_only
1269 || !Is_Pragma_Name (Chars (Pragma_Identifier (gnat_node))))
1270 return gnu_result;
1272 pragma_id = Get_Pragma_Id (Chars (Pragma_Identifier (gnat_node)));
1273 switch (pragma_id)
1275 case Pragma_Inspection_Point:
1276 /* Do nothing at top level: all such variables are already viewable. */
1277 if (global_bindings_p ())
1278 break;
1280 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1281 Present (gnat_temp);
1282 gnat_temp = Next (gnat_temp))
1284 Node_Id gnat_expr = Expression (gnat_temp);
1285 tree gnu_expr = gnat_to_gnu (gnat_expr);
1286 int use_address;
1287 machine_mode mode;
1288 tree asm_constraint = NULL_TREE;
1289 #ifdef ASM_COMMENT_START
1290 char *comment;
1291 #endif
1293 if (TREE_CODE (gnu_expr) == UNCONSTRAINED_ARRAY_REF)
1294 gnu_expr = TREE_OPERAND (gnu_expr, 0);
1296 /* Use the value only if it fits into a normal register,
1297 otherwise use the address. */
1298 mode = TYPE_MODE (TREE_TYPE (gnu_expr));
1299 use_address = ((GET_MODE_CLASS (mode) != MODE_INT
1300 && GET_MODE_CLASS (mode) != MODE_PARTIAL_INT)
1301 || GET_MODE_SIZE (mode) > UNITS_PER_WORD);
1303 if (use_address)
1304 gnu_expr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
1306 #ifdef ASM_COMMENT_START
1307 comment = concat (ASM_COMMENT_START,
1308 " inspection point: ",
1309 Get_Name_String (Chars (gnat_expr)),
1310 use_address ? " address" : "",
1311 " is in %0",
1312 NULL);
1313 asm_constraint = build_string (strlen (comment), comment);
1314 free (comment);
1315 #endif
1316 gnu_expr = build5 (ASM_EXPR, void_type_node,
1317 asm_constraint,
1318 NULL_TREE,
1319 tree_cons
1320 (build_tree_list (NULL_TREE,
1321 build_string (1, "g")),
1322 gnu_expr, NULL_TREE),
1323 NULL_TREE, NULL_TREE);
1324 ASM_VOLATILE_P (gnu_expr) = 1;
1325 set_expr_location_from_node (gnu_expr, gnat_node);
1326 append_to_statement_list (gnu_expr, &gnu_result);
1328 break;
1330 case Pragma_Loop_Optimize:
1331 for (gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1332 Present (gnat_temp);
1333 gnat_temp = Next (gnat_temp))
1335 tree gnu_loop_stmt = gnu_loop_stack->last ()->stmt;
1337 switch (Chars (Expression (gnat_temp)))
1339 case Name_Ivdep:
1340 LOOP_STMT_IVDEP (gnu_loop_stmt) = 1;
1341 break;
1343 case Name_No_Unroll:
1344 LOOP_STMT_NO_UNROLL (gnu_loop_stmt) = 1;
1345 break;
1347 case Name_Unroll:
1348 LOOP_STMT_UNROLL (gnu_loop_stmt) = 1;
1349 break;
1351 case Name_No_Vector:
1352 LOOP_STMT_NO_VECTOR (gnu_loop_stmt) = 1;
1353 break;
1355 case Name_Vector:
1356 LOOP_STMT_VECTOR (gnu_loop_stmt) = 1;
1357 break;
1359 default:
1360 gcc_unreachable ();
1363 break;
1365 case Pragma_Optimize:
1366 switch (Chars (Expression
1367 (First (Pragma_Argument_Associations (gnat_node)))))
1369 case Name_Off:
1370 if (optimize)
1371 post_error ("must specify -O0?", gnat_node);
1372 break;
1374 case Name_Space:
1375 if (!optimize_size)
1376 post_error ("must specify -Os?", gnat_node);
1377 break;
1379 case Name_Time:
1380 if (!optimize)
1381 post_error ("insufficient -O value?", gnat_node);
1382 break;
1384 default:
1385 gcc_unreachable ();
1387 break;
1389 case Pragma_Reviewable:
1390 if (write_symbols == NO_DEBUG)
1391 post_error ("must specify -g?", gnat_node);
1392 break;
1394 case Pragma_Warning_As_Error:
1395 case Pragma_Warnings:
1397 Node_Id gnat_expr;
1398 /* Preserve the location of the pragma. */
1399 const location_t location = input_location;
1400 struct cl_option_handlers handlers;
1401 unsigned int option_index;
1402 diagnostic_t kind;
1403 bool imply;
1405 gnat_temp = First (Pragma_Argument_Associations (gnat_node));
1407 /* This is the String form: pragma Warning{s|_As_Error}(String). */
1408 if (Nkind (Expression (gnat_temp)) == N_String_Literal)
1410 switch (pragma_id)
1412 case Pragma_Warning_As_Error:
1413 kind = DK_ERROR;
1414 imply = false;
1415 break;
1417 case Pragma_Warnings:
1418 kind = DK_WARNING;
1419 imply = true;
1420 break;
1422 default:
1423 gcc_unreachable ();
1426 gnat_expr = Expression (gnat_temp);
1429 /* This is the On/Off form: pragma Warnings (On | Off [,String]). */
1430 else if (Nkind (Expression (gnat_temp)) == N_Identifier)
1432 switch (Chars (Expression (gnat_temp)))
1434 case Name_Off:
1435 kind = DK_IGNORED;
1436 break;
1438 case Name_On:
1439 kind = DK_WARNING;
1440 break;
1442 default:
1443 gcc_unreachable ();
1446 /* Deal with optional pattern (but ignore Reason => "..."). */
1447 if (Present (Next (gnat_temp))
1448 && Chars (Next (gnat_temp)) != Name_Reason)
1450 /* pragma Warnings (On | Off, Name) is handled differently. */
1451 if (Nkind (Expression (Next (gnat_temp))) != N_String_Literal)
1452 break;
1454 gnat_expr = Expression (Next (gnat_temp));
1456 else
1457 gnat_expr = Empty;
1459 imply = false;
1462 else
1463 gcc_unreachable ();
1465 /* This is the same implementation as in the C family of compilers. */
1466 if (Present (gnat_expr))
1468 tree gnu_expr = gnat_to_gnu (gnat_expr);
1469 const char *opt_string = TREE_STRING_POINTER (gnu_expr);
1470 const int len = TREE_STRING_LENGTH (gnu_expr);
1471 if (len < 3 || opt_string[0] != '-' || opt_string[1] != 'W')
1472 break;
1473 for (option_index = 0;
1474 option_index < cl_options_count;
1475 option_index++)
1476 if (strcmp (cl_options[option_index].opt_text, opt_string) == 0)
1477 break;
1478 if (option_index == cl_options_count)
1480 post_error ("unknown -W switch", gnat_node);
1481 break;
1484 else
1485 option_index = 0;
1487 set_default_handlers (&handlers);
1488 control_warning_option (option_index, (int) kind, imply, location,
1489 CL_Ada, &handlers, &global_options,
1490 &global_options_set, global_dc);
1492 break;
1494 default:
1495 break;
1498 return gnu_result;
1502 /* Check the inlining status of nested function FNDECL in the current context.
1504 If a non-inline nested function is referenced from an inline external
1505 function, we cannot honor both requests at the same time without cloning
1506 the nested function in the current unit since it is private to its unit.
1507 We could inline it as well but it's probably better to err on the side
1508 of too little inlining.
1510 This must be invoked only on nested functions present in the source code
1511 and not on nested functions generated by the compiler, e.g. finalizers,
1512 because they are not marked inline and we don't want them to block the
1513 inlining of the parent function. */
1515 static void
1516 check_inlining_for_nested_subprog (tree fndecl)
1518 if (!DECL_DECLARED_INLINE_P (fndecl)
1519 && current_function_decl
1520 && DECL_EXTERNAL (current_function_decl)
1521 && DECL_DECLARED_INLINE_P (current_function_decl))
1523 const location_t loc1 = DECL_SOURCE_LOCATION (fndecl);
1524 const location_t loc2 = DECL_SOURCE_LOCATION (current_function_decl);
1526 if (lookup_attribute ("always_inline",
1527 DECL_ATTRIBUTES (current_function_decl)))
1529 error_at (loc1, "subprogram %q+F not marked Inline_Always", fndecl);
1530 error_at (loc2, "parent subprogram cannot be inlined");
1532 else
1534 warning_at (loc1, OPT_Winline, "subprogram %q+F not marked Inline",
1535 fndecl);
1536 warning_at (loc2, OPT_Winline, "parent subprogram cannot be inlined");
1539 DECL_DECLARED_INLINE_P (current_function_decl) = 0;
1540 DECL_UNINLINABLE (current_function_decl) = 1;
1544 /* Return an expression for the length of TYPE, an integral type, computed in
1545 RESULT_TYPE, another integral type.
1547 We used to compute the length as MAX (hb - lb + 1, 0) which could overflow
1548 when lb == TYPE'First. We now compute it as (hb >= lb) ? hb - lb + 1 : 0
1549 which would only overflow in much rarer cases, for extremely large arrays
1550 we expect never to encounter in practice. Besides, the former computation
1551 required the use of potentially constraining signed arithmetics while the
1552 latter does not. Note that the comparison must be done in the original
1553 base index type in order to avoid any overflow during the conversion. */
1555 static tree
1556 get_type_length (tree type, tree result_type)
1558 tree comp_type = get_base_type (result_type);
1559 tree base_type = get_base_type (type);
1560 tree lb = convert (base_type, TYPE_MIN_VALUE (type));
1561 tree hb = convert (base_type, TYPE_MAX_VALUE (type));
1562 tree length
1563 = build_binary_op (PLUS_EXPR, comp_type,
1564 build_binary_op (MINUS_EXPR, comp_type,
1565 convert (comp_type, hb),
1566 convert (comp_type, lb)),
1567 convert (comp_type, integer_one_node));
1568 length
1569 = build_cond_expr (result_type,
1570 build_binary_op (GE_EXPR, boolean_type_node, hb, lb),
1571 convert (result_type, length),
1572 convert (result_type, integer_zero_node));
1573 return length;
1576 /* Subroutine of gnat_to_gnu to translate GNAT_NODE, an N_Attribute node,
1577 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to
1578 where we should place the result type. ATTRIBUTE is the attribute ID. */
1580 static tree
1581 Attribute_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, int attribute)
1583 const Node_Id gnat_prefix = Prefix (gnat_node);
1584 tree gnu_prefix, gnu_type, gnu_expr;
1585 tree gnu_result_type, gnu_result = error_mark_node;
1586 bool prefix_unused = false;
1588 /* ??? If this is an access attribute for a public subprogram to be used in
1589 a dispatch table, do not translate its type as it's useless in this case
1590 and the parameter types might be incomplete types coming from a limited
1591 context in Ada 2012 (AI05-0151). */
1592 if (Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
1593 && Is_Dispatch_Table_Entity (Etype (gnat_node))
1594 && Nkind (gnat_prefix) == N_Identifier
1595 && Is_Subprogram (Entity (gnat_prefix))
1596 && Is_Public (Entity (gnat_prefix))
1597 && !present_gnu_tree (Entity (gnat_prefix)))
1598 gnu_prefix = get_minimal_subprog_decl (Entity (gnat_prefix));
1599 else
1600 gnu_prefix = gnat_to_gnu (gnat_prefix);
1601 gnu_type = TREE_TYPE (gnu_prefix);
1603 /* If the input is a NULL_EXPR, make a new one. */
1604 if (TREE_CODE (gnu_prefix) == NULL_EXPR)
1606 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1607 *gnu_result_type_p = gnu_result_type;
1608 return build1 (NULL_EXPR, gnu_result_type, TREE_OPERAND (gnu_prefix, 0));
1611 switch (attribute)
1613 case Attr_Pos:
1614 case Attr_Val:
1615 /* These are just conversions since representation clauses for
1616 enumeration types are handled in the front-end. */
1618 bool checkp = Do_Range_Check (First (Expressions (gnat_node)));
1619 gnu_result = gnat_to_gnu (First (Expressions (gnat_node)));
1620 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1621 gnu_result = convert_with_check (Etype (gnat_node), gnu_result,
1622 checkp, checkp, true, gnat_node);
1624 break;
1626 case Attr_Pred:
1627 case Attr_Succ:
1628 /* These just add or subtract the constant 1 since representation
1629 clauses for enumeration types are handled in the front-end. */
1630 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
1631 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1633 if (Do_Range_Check (First (Expressions (gnat_node))))
1635 gnu_expr = gnat_protect_expr (gnu_expr);
1636 gnu_expr
1637 = emit_check
1638 (build_binary_op (EQ_EXPR, boolean_type_node,
1639 gnu_expr,
1640 attribute == Attr_Pred
1641 ? TYPE_MIN_VALUE (gnu_result_type)
1642 : TYPE_MAX_VALUE (gnu_result_type)),
1643 gnu_expr, CE_Range_Check_Failed, gnat_node);
1646 gnu_result
1647 = build_binary_op (attribute == Attr_Pred ? MINUS_EXPR : PLUS_EXPR,
1648 gnu_result_type, gnu_expr,
1649 convert (gnu_result_type, integer_one_node));
1650 break;
1652 case Attr_Address:
1653 case Attr_Unrestricted_Access:
1654 /* Conversions don't change addresses but can cause us to miss the
1655 COMPONENT_REF case below, so strip them off. */
1656 gnu_prefix = remove_conversions (gnu_prefix,
1657 !Must_Be_Byte_Aligned (gnat_node));
1659 /* If we are taking 'Address of an unconstrained object, this is the
1660 pointer to the underlying array. */
1661 if (attribute == Attr_Address)
1662 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1664 /* If we are building a static dispatch table, we have to honor
1665 TARGET_VTABLE_USES_DESCRIPTORS if we want to be compatible
1666 with the C++ ABI. We do it in the non-static case as well,
1667 see gnat_to_gnu_entity, case E_Access_Subprogram_Type. */
1668 else if (TARGET_VTABLE_USES_DESCRIPTORS
1669 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
1671 tree gnu_field, t;
1672 /* Descriptors can only be built here for top-level functions. */
1673 bool build_descriptor = (global_bindings_p () != 0);
1674 int i;
1675 vec<constructor_elt, va_gc> *gnu_vec = NULL;
1676 constructor_elt *elt;
1678 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1680 /* If we're not going to build the descriptor, we have to retrieve
1681 the one which will be built by the linker (or by the compiler
1682 later if a static chain is requested). */
1683 if (!build_descriptor)
1685 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_prefix);
1686 gnu_result = fold_convert (build_pointer_type (gnu_result_type),
1687 gnu_result);
1688 gnu_result = build1 (INDIRECT_REF, gnu_result_type, gnu_result);
1691 vec_safe_grow (gnu_vec, TARGET_VTABLE_USES_DESCRIPTORS);
1692 elt = (gnu_vec->address () + TARGET_VTABLE_USES_DESCRIPTORS - 1);
1693 for (gnu_field = TYPE_FIELDS (gnu_result_type), i = 0;
1694 i < TARGET_VTABLE_USES_DESCRIPTORS;
1695 gnu_field = DECL_CHAIN (gnu_field), i++)
1697 if (build_descriptor)
1699 t = build2 (FDESC_EXPR, TREE_TYPE (gnu_field), gnu_prefix,
1700 build_int_cst (NULL_TREE, i));
1701 TREE_CONSTANT (t) = 1;
1703 else
1704 t = build3 (COMPONENT_REF, ptr_void_ftype, gnu_result,
1705 gnu_field, NULL_TREE);
1707 elt->index = gnu_field;
1708 elt->value = t;
1709 elt--;
1712 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
1713 break;
1716 /* ... fall through ... */
1718 case Attr_Access:
1719 case Attr_Unchecked_Access:
1720 case Attr_Code_Address:
1721 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1722 gnu_result
1723 = build_unary_op (((attribute == Attr_Address
1724 || attribute == Attr_Unrestricted_Access)
1725 && !Must_Be_Byte_Aligned (gnat_node))
1726 ? ATTR_ADDR_EXPR : ADDR_EXPR,
1727 gnu_result_type, gnu_prefix);
1729 /* For 'Code_Address, find an inner ADDR_EXPR and mark it so that we
1730 don't try to build a trampoline. */
1731 if (attribute == Attr_Code_Address)
1733 gnu_expr = remove_conversions (gnu_result, false);
1735 if (TREE_CODE (gnu_expr) == ADDR_EXPR)
1736 TREE_NO_TRAMPOLINE (gnu_expr) = TREE_CONSTANT (gnu_expr) = 1;
1739 /* For 'Access, issue an error message if the prefix is a C++ method
1740 since it can use a special calling convention on some platforms,
1741 which cannot be propagated to the access type. */
1742 else if (attribute == Attr_Access
1743 && Nkind (gnat_prefix) == N_Identifier
1744 && is_cplusplus_method (Entity (gnat_prefix)))
1745 post_error ("access to C++ constructor or member function not allowed",
1746 gnat_node);
1748 /* For other address attributes applied to a nested function,
1749 find an inner ADDR_EXPR and annotate it so that we can issue
1750 a useful warning with -Wtrampolines. */
1751 else if (TREE_CODE (TREE_TYPE (gnu_prefix)) == FUNCTION_TYPE)
1753 gnu_expr = remove_conversions (gnu_result, false);
1755 if (TREE_CODE (gnu_expr) == ADDR_EXPR
1756 && decl_function_context (TREE_OPERAND (gnu_expr, 0)))
1758 set_expr_location_from_node (gnu_expr, gnat_node);
1760 /* Also check the inlining status. */
1761 check_inlining_for_nested_subprog (TREE_OPERAND (gnu_expr, 0));
1763 /* Check that we're not violating the No_Implicit_Dynamic_Code
1764 restriction. Be conservative if we don't know anything
1765 about the trampoline strategy for the target. */
1766 Check_Implicit_Dynamic_Code_Allowed (gnat_node);
1769 break;
1771 case Attr_Pool_Address:
1773 tree gnu_ptr = gnu_prefix;
1774 tree gnu_obj_type;
1776 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1778 /* If this is fat pointer, the object must have been allocated with the
1779 template in front of the array. So compute the template address; do
1780 it by converting to a thin pointer. */
1781 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
1782 gnu_ptr
1783 = convert (build_pointer_type
1784 (TYPE_OBJECT_RECORD_TYPE
1785 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
1786 gnu_ptr);
1788 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
1790 /* If this is a thin pointer, the object must have been allocated with
1791 the template in front of the array. So compute the template address
1792 and return it. */
1793 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
1794 gnu_ptr
1795 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
1796 gnu_ptr,
1797 fold_build1 (NEGATE_EXPR, sizetype,
1798 byte_position
1799 (DECL_CHAIN
1800 TYPE_FIELDS ((gnu_obj_type)))));
1802 gnu_result = convert (gnu_result_type, gnu_ptr);
1804 break;
1806 case Attr_Size:
1807 case Attr_Object_Size:
1808 case Attr_Value_Size:
1809 case Attr_Max_Size_In_Storage_Elements:
1810 gnu_expr = gnu_prefix;
1812 /* Remove NOPs and conversions between original and packable version
1813 from GNU_EXPR, and conversions from GNU_PREFIX. We use GNU_EXPR
1814 to see if a COMPONENT_REF was involved. */
1815 while (TREE_CODE (gnu_expr) == NOP_EXPR
1816 || (TREE_CODE (gnu_expr) == VIEW_CONVERT_EXPR
1817 && TREE_CODE (TREE_TYPE (gnu_expr)) == RECORD_TYPE
1818 && TREE_CODE (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))
1819 == RECORD_TYPE
1820 && TYPE_NAME (TREE_TYPE (gnu_expr))
1821 == TYPE_NAME (TREE_TYPE (TREE_OPERAND (gnu_expr, 0)))))
1822 gnu_expr = TREE_OPERAND (gnu_expr, 0);
1824 gnu_prefix = remove_conversions (gnu_prefix, true);
1825 prefix_unused = true;
1826 gnu_type = TREE_TYPE (gnu_prefix);
1828 /* Replace an unconstrained array type with the type of the underlying
1829 array. We can't do this with a call to maybe_unconstrained_array
1830 since we may have a TYPE_DECL. For 'Max_Size_In_Storage_Elements,
1831 use the record type that will be used to allocate the object and its
1832 template. */
1833 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
1835 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
1836 if (attribute != Attr_Max_Size_In_Storage_Elements)
1837 gnu_type = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
1840 /* If we're looking for the size of a field, return the field size. */
1841 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1842 gnu_result = DECL_SIZE (TREE_OPERAND (gnu_prefix, 1));
1844 /* Otherwise, if the prefix is an object, or if we are looking for
1845 'Object_Size or 'Max_Size_In_Storage_Elements, the result is the
1846 GCC size of the type. We make an exception for padded objects,
1847 as we do not take into account alignment promotions for the size.
1848 This is in keeping with the object case of gnat_to_gnu_entity. */
1849 else if ((TREE_CODE (gnu_prefix) != TYPE_DECL
1850 && !(TYPE_IS_PADDING_P (gnu_type)
1851 && TREE_CODE (gnu_expr) == COMPONENT_REF))
1852 || attribute == Attr_Object_Size
1853 || attribute == Attr_Max_Size_In_Storage_Elements)
1855 /* If this is a dereference and we have a special dynamic constrained
1856 subtype on the prefix, use it to compute the size; otherwise, use
1857 the designated subtype. */
1858 if (Nkind (gnat_prefix) == N_Explicit_Dereference)
1860 Node_Id gnat_actual_subtype
1861 = Actual_Designated_Subtype (gnat_prefix);
1862 tree gnu_ptr_type
1863 = TREE_TYPE (gnat_to_gnu (Prefix (gnat_prefix)));
1865 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type)
1866 && Present (gnat_actual_subtype))
1868 tree gnu_actual_obj_type
1869 = gnat_to_gnu_type (gnat_actual_subtype);
1870 gnu_type
1871 = build_unc_object_type_from_ptr (gnu_ptr_type,
1872 gnu_actual_obj_type,
1873 get_identifier ("SIZE"),
1874 false);
1878 gnu_result = TYPE_SIZE (gnu_type);
1881 /* Otherwise, the result is the RM size of the type. */
1882 else
1883 gnu_result = rm_size (gnu_type);
1885 /* Deal with a self-referential size by returning the maximum size for
1886 a type and by qualifying the size with the object otherwise. */
1887 if (CONTAINS_PLACEHOLDER_P (gnu_result))
1889 if (TREE_CODE (gnu_prefix) == TYPE_DECL)
1890 gnu_result = max_size (gnu_result, true);
1891 else
1892 gnu_result = substitute_placeholder_in_expr (gnu_result, gnu_expr);
1895 /* If the type contains a template, subtract its size. */
1896 if (TREE_CODE (gnu_type) == RECORD_TYPE
1897 && TYPE_CONTAINS_TEMPLATE_P (gnu_type))
1898 gnu_result = size_binop (MINUS_EXPR, gnu_result,
1899 DECL_SIZE (TYPE_FIELDS (gnu_type)));
1901 /* For 'Max_Size_In_Storage_Elements, adjust the unit. */
1902 if (attribute == Attr_Max_Size_In_Storage_Elements)
1903 gnu_result = size_binop (CEIL_DIV_EXPR, gnu_result, bitsize_unit_node);
1905 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1906 break;
1908 case Attr_Alignment:
1910 unsigned int align;
1912 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
1913 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
1914 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
1916 gnu_type = TREE_TYPE (gnu_prefix);
1917 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1918 prefix_unused = true;
1920 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
1921 align = DECL_ALIGN (TREE_OPERAND (gnu_prefix, 1)) / BITS_PER_UNIT;
1922 else
1924 Entity_Id gnat_type = Etype (gnat_prefix);
1925 unsigned int double_align;
1926 bool is_capped_double, align_clause;
1928 /* If the default alignment of "double" or larger scalar types is
1929 specifically capped and there is an alignment clause neither
1930 on the type nor on the prefix itself, return the cap. */
1931 if ((double_align = double_float_alignment) > 0)
1932 is_capped_double
1933 = is_double_float_or_array (gnat_type, &align_clause);
1934 else if ((double_align = double_scalar_alignment) > 0)
1935 is_capped_double
1936 = is_double_scalar_or_array (gnat_type, &align_clause);
1937 else
1938 is_capped_double = align_clause = false;
1940 if (is_capped_double
1941 && Nkind (gnat_prefix) == N_Identifier
1942 && Present (Alignment_Clause (Entity (gnat_prefix))))
1943 align_clause = true;
1945 if (is_capped_double && !align_clause)
1946 align = double_align;
1947 else
1948 align = TYPE_ALIGN (gnu_type) / BITS_PER_UNIT;
1951 gnu_result = size_int (align);
1953 break;
1955 case Attr_First:
1956 case Attr_Last:
1957 case Attr_Range_Length:
1958 prefix_unused = true;
1960 if (INTEGRAL_TYPE_P (gnu_type) || TREE_CODE (gnu_type) == REAL_TYPE)
1962 gnu_result_type = get_unpadded_type (Etype (gnat_node));
1964 if (attribute == Attr_First)
1965 gnu_result = TYPE_MIN_VALUE (gnu_type);
1966 else if (attribute == Attr_Last)
1967 gnu_result = TYPE_MAX_VALUE (gnu_type);
1968 else
1969 gnu_result = get_type_length (gnu_type, gnu_result_type);
1970 break;
1973 /* ... fall through ... */
1975 case Attr_Length:
1977 int Dimension = (Present (Expressions (gnat_node))
1978 ? UI_To_Int (Intval (First (Expressions (gnat_node))))
1979 : 1), i;
1980 struct parm_attr_d *pa = NULL;
1981 Entity_Id gnat_param = Empty;
1982 bool unconstrained_ptr_deref = false;
1984 /* Make sure any implicit dereference gets done. */
1985 gnu_prefix = maybe_implicit_deref (gnu_prefix);
1986 gnu_prefix = maybe_unconstrained_array (gnu_prefix);
1988 /* We treat unconstrained array In parameters specially. We also note
1989 whether we are dereferencing a pointer to unconstrained array. */
1990 if (!Is_Constrained (Etype (gnat_prefix)))
1991 switch (Nkind (gnat_prefix))
1993 case N_Identifier:
1994 /* This is the direct case. */
1995 if (Ekind (Entity (gnat_prefix)) == E_In_Parameter)
1996 gnat_param = Entity (gnat_prefix);
1997 break;
1999 case N_Explicit_Dereference:
2000 /* This is the indirect case. Note that we need to be sure that
2001 the access value cannot be null as we'll hoist the load. */
2002 if (Nkind (Prefix (gnat_prefix)) == N_Identifier
2003 && Ekind (Entity (Prefix (gnat_prefix))) == E_In_Parameter)
2005 if (Can_Never_Be_Null (Entity (Prefix (gnat_prefix))))
2006 gnat_param = Entity (Prefix (gnat_prefix));
2008 else
2009 unconstrained_ptr_deref = true;
2010 break;
2012 default:
2013 break;
2016 /* If the prefix is the view conversion of a constrained array to an
2017 unconstrained form, we retrieve the constrained array because we
2018 might not be able to substitute the PLACEHOLDER_EXPR coming from
2019 the conversion. This can occur with the 'Old attribute applied
2020 to a parameter with an unconstrained type, which gets rewritten
2021 into a constrained local variable very late in the game. */
2022 if (TREE_CODE (gnu_prefix) == VIEW_CONVERT_EXPR
2023 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (gnu_prefix)))
2024 && !CONTAINS_PLACEHOLDER_P
2025 (TYPE_SIZE (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0)))))
2026 gnu_type = TREE_TYPE (TREE_OPERAND (gnu_prefix, 0));
2027 else
2028 gnu_type = TREE_TYPE (gnu_prefix);
2030 prefix_unused = true;
2031 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2033 if (TYPE_CONVENTION_FORTRAN_P (gnu_type))
2035 int ndim;
2036 tree gnu_type_temp;
2038 for (ndim = 1, gnu_type_temp = gnu_type;
2039 TREE_CODE (TREE_TYPE (gnu_type_temp)) == ARRAY_TYPE
2040 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type_temp));
2041 ndim++, gnu_type_temp = TREE_TYPE (gnu_type_temp))
2044 Dimension = ndim + 1 - Dimension;
2047 for (i = 1; i < Dimension; i++)
2048 gnu_type = TREE_TYPE (gnu_type);
2050 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2052 /* When not optimizing, look up the slot associated with the parameter
2053 and the dimension in the cache and create a new one on failure.
2054 Don't do this when the actual subtype needs debug info (this happens
2055 with -gnatD): in elaborate_expression_1, we create variables that
2056 hold the bounds, so caching attributes isn't very interesting and
2057 causes dependency issues between these variables and cached
2058 expressions. */
2059 if (!optimize
2060 && Present (gnat_param)
2061 && !(Present (Actual_Subtype (gnat_param))
2062 && Needs_Debug_Info (Actual_Subtype (gnat_param))))
2064 FOR_EACH_VEC_SAFE_ELT (f_parm_attr_cache, i, pa)
2065 if (pa->id == gnat_param && pa->dim == Dimension)
2066 break;
2068 if (!pa)
2070 pa = ggc_cleared_alloc<parm_attr_d> ();
2071 pa->id = gnat_param;
2072 pa->dim = Dimension;
2073 vec_safe_push (f_parm_attr_cache, pa);
2077 /* Return the cached expression or build a new one. */
2078 if (attribute == Attr_First)
2080 if (pa && pa->first)
2082 gnu_result = pa->first;
2083 break;
2086 gnu_result
2087 = TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2090 else if (attribute == Attr_Last)
2092 if (pa && pa->last)
2094 gnu_result = pa->last;
2095 break;
2098 gnu_result
2099 = TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)));
2102 else /* attribute == Attr_Range_Length || attribute == Attr_Length */
2104 if (pa && pa->length)
2106 gnu_result = pa->length;
2107 break;
2110 gnu_result
2111 = get_type_length (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type)),
2112 gnu_result_type);
2115 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2116 handling. Note that these attributes could not have been used on
2117 an unconstrained array type. */
2118 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2120 /* Cache the expression we have just computed. Since we want to do it
2121 at run time, we force the use of a SAVE_EXPR and let the gimplifier
2122 create the temporary in the outermost binding level. We will make
2123 sure in Subprogram_Body_to_gnu that it is evaluated on all possible
2124 paths by forcing its evaluation on entry of the function. */
2125 if (pa)
2127 gnu_result
2128 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2129 switch (attribute)
2131 case Attr_First:
2132 pa->first = gnu_result;
2133 break;
2135 case Attr_Last:
2136 pa->last = gnu_result;
2137 break;
2139 case Attr_Length:
2140 case Attr_Range_Length:
2141 pa->length = gnu_result;
2142 break;
2144 default:
2145 gcc_unreachable ();
2149 /* Otherwise, evaluate it each time it is referenced. */
2150 else
2151 switch (attribute)
2153 case Attr_First:
2154 case Attr_Last:
2155 /* If we are dereferencing a pointer to unconstrained array, we
2156 need to capture the value because the pointed-to bounds may
2157 subsequently be released. */
2158 if (unconstrained_ptr_deref)
2159 gnu_result
2160 = build1 (SAVE_EXPR, TREE_TYPE (gnu_result), gnu_result);
2161 break;
2163 case Attr_Length:
2164 case Attr_Range_Length:
2165 /* Set the source location onto the predicate of the condition
2166 but not if the expression is cached to avoid messing up the
2167 debug info. */
2168 if (TREE_CODE (gnu_result) == COND_EXPR
2169 && EXPR_P (TREE_OPERAND (gnu_result, 0)))
2170 set_expr_location_from_node (TREE_OPERAND (gnu_result, 0),
2171 gnat_node);
2172 break;
2174 default:
2175 gcc_unreachable ();
2178 break;
2181 case Attr_Bit_Position:
2182 case Attr_Position:
2183 case Attr_First_Bit:
2184 case Attr_Last_Bit:
2185 case Attr_Bit:
2187 HOST_WIDE_INT bitsize;
2188 HOST_WIDE_INT bitpos;
2189 tree gnu_offset;
2190 tree gnu_field_bitpos;
2191 tree gnu_field_offset;
2192 tree gnu_inner;
2193 machine_mode mode;
2194 int unsignedp, reversep, volatilep;
2196 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2197 gnu_prefix = remove_conversions (gnu_prefix, true);
2198 prefix_unused = true;
2200 /* We can have 'Bit on any object, but if it isn't a COMPONENT_REF,
2201 the result is 0. Don't allow 'Bit on a bare component, though. */
2202 if (attribute == Attr_Bit
2203 && TREE_CODE (gnu_prefix) != COMPONENT_REF
2204 && TREE_CODE (gnu_prefix) != FIELD_DECL)
2206 gnu_result = integer_zero_node;
2207 break;
2210 else
2211 gcc_assert (TREE_CODE (gnu_prefix) == COMPONENT_REF
2212 || (attribute == Attr_Bit_Position
2213 && TREE_CODE (gnu_prefix) == FIELD_DECL));
2215 get_inner_reference (gnu_prefix, &bitsize, &bitpos, &gnu_offset,
2216 &mode, &unsignedp, &reversep, &volatilep, false);
2218 if (TREE_CODE (gnu_prefix) == COMPONENT_REF)
2220 gnu_field_bitpos = bit_position (TREE_OPERAND (gnu_prefix, 1));
2221 gnu_field_offset = byte_position (TREE_OPERAND (gnu_prefix, 1));
2223 for (gnu_inner = TREE_OPERAND (gnu_prefix, 0);
2224 TREE_CODE (gnu_inner) == COMPONENT_REF
2225 && DECL_INTERNAL_P (TREE_OPERAND (gnu_inner, 1));
2226 gnu_inner = TREE_OPERAND (gnu_inner, 0))
2228 gnu_field_bitpos
2229 = size_binop (PLUS_EXPR, gnu_field_bitpos,
2230 bit_position (TREE_OPERAND (gnu_inner, 1)));
2231 gnu_field_offset
2232 = size_binop (PLUS_EXPR, gnu_field_offset,
2233 byte_position (TREE_OPERAND (gnu_inner, 1)));
2236 else if (TREE_CODE (gnu_prefix) == FIELD_DECL)
2238 gnu_field_bitpos = bit_position (gnu_prefix);
2239 gnu_field_offset = byte_position (gnu_prefix);
2241 else
2243 gnu_field_bitpos = bitsize_zero_node;
2244 gnu_field_offset = size_zero_node;
2247 switch (attribute)
2249 case Attr_Position:
2250 gnu_result = gnu_field_offset;
2251 break;
2253 case Attr_First_Bit:
2254 case Attr_Bit:
2255 gnu_result = size_int (bitpos % BITS_PER_UNIT);
2256 break;
2258 case Attr_Last_Bit:
2259 gnu_result = bitsize_int (bitpos % BITS_PER_UNIT);
2260 gnu_result = size_binop (PLUS_EXPR, gnu_result,
2261 TYPE_SIZE (TREE_TYPE (gnu_prefix)));
2262 /* ??? Avoid a large unsigned result that will overflow when
2263 converted to the signed universal_integer. */
2264 if (integer_zerop (gnu_result))
2265 gnu_result = integer_minus_one_node;
2266 else
2267 gnu_result
2268 = size_binop (MINUS_EXPR, gnu_result, bitsize_one_node);
2269 break;
2271 case Attr_Bit_Position:
2272 gnu_result = gnu_field_bitpos;
2273 break;
2276 /* If this has a PLACEHOLDER_EXPR, qualify it by the object we are
2277 handling. */
2278 gnu_result = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_result, gnu_prefix);
2279 break;
2282 case Attr_Min:
2283 case Attr_Max:
2285 tree gnu_lhs = gnat_to_gnu (First (Expressions (gnat_node)));
2286 tree gnu_rhs = gnat_to_gnu (Next (First (Expressions (gnat_node))));
2288 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2290 /* The result of {MIN,MAX}_EXPR is unspecified if either operand is
2291 a NaN so we implement the semantics of C99 f{min,max} to make it
2292 predictable in this case: if either operand is a NaN, the other
2293 is returned; if both operands are NaN's, a NaN is returned. */
2294 if (SCALAR_FLOAT_TYPE_P (gnu_result_type))
2296 const bool lhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_lhs);
2297 const bool rhs_side_effects_p = TREE_SIDE_EFFECTS (gnu_rhs);
2298 tree t = builtin_decl_explicit (BUILT_IN_ISNAN);
2299 tree lhs_is_nan, rhs_is_nan;
2301 /* If the operands have side-effects, they need to be evaluated
2302 only once in spite of the multiple references in the result. */
2303 if (lhs_side_effects_p)
2304 gnu_lhs = gnat_protect_expr (gnu_lhs);
2305 if (rhs_side_effects_p)
2306 gnu_rhs = gnat_protect_expr (gnu_rhs);
2308 lhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2309 build_call_expr (t, 1, gnu_lhs),
2310 integer_zero_node);
2312 rhs_is_nan = fold_build2 (NE_EXPR, boolean_type_node,
2313 build_call_expr (t, 1, gnu_rhs),
2314 integer_zero_node);
2316 gnu_result = build_binary_op (attribute == Attr_Min
2317 ? MIN_EXPR : MAX_EXPR,
2318 gnu_result_type, gnu_lhs, gnu_rhs);
2319 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2320 rhs_is_nan, gnu_lhs, gnu_result);
2321 gnu_result = fold_build3 (COND_EXPR, gnu_result_type,
2322 lhs_is_nan, gnu_rhs, gnu_result);
2324 /* If the operands have side-effects, they need to be evaluated
2325 before doing the tests above since the place they otherwise
2326 would end up being evaluated at run time could be wrong. */
2327 if (lhs_side_effects_p)
2328 gnu_result
2329 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_lhs, gnu_result);
2331 if (rhs_side_effects_p)
2332 gnu_result
2333 = build2 (COMPOUND_EXPR, gnu_result_type, gnu_rhs, gnu_result);
2335 else
2336 gnu_result = build_binary_op (attribute == Attr_Min
2337 ? MIN_EXPR : MAX_EXPR,
2338 gnu_result_type, gnu_lhs, gnu_rhs);
2340 break;
2342 case Attr_Passed_By_Reference:
2343 gnu_result = size_int (default_pass_by_ref (gnu_type)
2344 || must_pass_by_ref (gnu_type));
2345 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2346 break;
2348 case Attr_Component_Size:
2349 if (TREE_CODE (gnu_prefix) == COMPONENT_REF
2350 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_prefix, 0))))
2351 gnu_prefix = TREE_OPERAND (gnu_prefix, 0);
2353 gnu_prefix = maybe_implicit_deref (gnu_prefix);
2354 gnu_type = TREE_TYPE (gnu_prefix);
2356 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
2357 gnu_type = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_type))));
2359 while (TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
2360 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type)))
2361 gnu_type = TREE_TYPE (gnu_type);
2363 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
2365 /* Note this size cannot be self-referential. */
2366 gnu_result = TYPE_SIZE (TREE_TYPE (gnu_type));
2367 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2368 prefix_unused = true;
2369 break;
2371 case Attr_Descriptor_Size:
2372 gnu_type = TREE_TYPE (gnu_prefix);
2373 gcc_assert (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE);
2375 /* What we want is the offset of the ARRAY field in the record
2376 that the thin pointer designates. */
2377 gnu_type = TYPE_OBJECT_RECORD_TYPE (gnu_type);
2378 gnu_result = bit_position (DECL_CHAIN (TYPE_FIELDS (gnu_type)));
2379 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2380 prefix_unused = true;
2381 break;
2383 case Attr_Null_Parameter:
2384 /* This is just a zero cast to the pointer type for our prefix and
2385 dereferenced. */
2386 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2387 gnu_result
2388 = build_unary_op (INDIRECT_REF, NULL_TREE,
2389 convert (build_pointer_type (gnu_result_type),
2390 integer_zero_node));
2391 TREE_PRIVATE (gnu_result) = 1;
2392 break;
2394 case Attr_Mechanism_Code:
2396 Entity_Id gnat_obj = Entity (gnat_prefix);
2397 int code;
2399 prefix_unused = true;
2400 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2401 if (Present (Expressions (gnat_node)))
2403 int i = UI_To_Int (Intval (First (Expressions (gnat_node))));
2405 for (gnat_obj = First_Formal (gnat_obj); i > 1;
2406 i--, gnat_obj = Next_Formal (gnat_obj))
2410 code = Mechanism (gnat_obj);
2411 if (code == Default)
2412 code = ((present_gnu_tree (gnat_obj)
2413 && (DECL_BY_REF_P (get_gnu_tree (gnat_obj))
2414 || ((TREE_CODE (get_gnu_tree (gnat_obj))
2415 == PARM_DECL)
2416 && (DECL_BY_COMPONENT_PTR_P
2417 (get_gnu_tree (gnat_obj))))))
2418 ? By_Reference : By_Copy);
2419 gnu_result = convert (gnu_result_type, size_int (- code));
2421 break;
2423 case Attr_Model:
2424 /* We treat Model as identical to Machine. This is true for at least
2425 IEEE and some other nice floating-point systems. */
2427 /* ... fall through ... */
2429 case Attr_Machine:
2430 /* The trick is to force the compiler to store the result in memory so
2431 that we do not have extra precision used. But do this only when this
2432 is necessary, i.e. if FP_ARITH_MAY_WIDEN is true and the precision of
2433 the type is lower than that of the longest floating-point type. */
2434 prefix_unused = true;
2435 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2436 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2437 gnu_result = convert (gnu_result_type, gnu_expr);
2439 if (fp_arith_may_widen
2440 && TYPE_PRECISION (gnu_result_type)
2441 < TYPE_PRECISION (longest_float_type_node))
2443 tree rec_type = make_node (RECORD_TYPE);
2444 tree field
2445 = create_field_decl (get_identifier ("OBJ"), gnu_result_type,
2446 rec_type, NULL_TREE, NULL_TREE, 0, 0);
2447 tree rec_val, asm_expr;
2449 finish_record_type (rec_type, field, 0, false);
2451 rec_val = build_constructor_single (rec_type, field, gnu_result);
2452 rec_val = save_expr (rec_val);
2454 asm_expr
2455 = build5 (ASM_EXPR, void_type_node,
2456 build_string (0, ""),
2457 tree_cons (build_tree_list (NULL_TREE,
2458 build_string (2, "=m")),
2459 rec_val, NULL_TREE),
2460 tree_cons (build_tree_list (NULL_TREE,
2461 build_string (1, "m")),
2462 rec_val, NULL_TREE),
2463 NULL_TREE, NULL_TREE);
2464 ASM_VOLATILE_P (asm_expr) = 1;
2466 gnu_result
2467 = build_compound_expr (gnu_result_type, asm_expr,
2468 build_component_ref (rec_val, NULL_TREE,
2469 field, false));
2471 break;
2473 case Attr_Deref:
2474 prefix_unused = true;
2475 gnu_expr = gnat_to_gnu (First (Expressions (gnat_node)));
2476 gnu_result_type = get_unpadded_type (Etype (gnat_node));
2477 /* This can be a random address so build an alias-all pointer type. */
2478 gnu_expr
2479 = convert (build_pointer_type_for_mode (gnu_result_type, ptr_mode,
2480 true),
2481 gnu_expr);
2482 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_expr);
2483 break;
2485 default:
2486 /* This abort means that we have an unimplemented attribute. */
2487 gcc_unreachable ();
2490 /* If this is an attribute where the prefix was unused, force a use of it if
2491 it has a side-effect. But don't do it if the prefix is just an entity
2492 name. However, if an access check is needed, we must do it. See second
2493 example in AARM 11.6(5.e). */
2494 if (prefix_unused
2495 && TREE_SIDE_EFFECTS (gnu_prefix)
2496 && !Is_Entity_Name (gnat_prefix))
2497 gnu_result
2498 = build_compound_expr (TREE_TYPE (gnu_result), gnu_prefix, gnu_result);
2500 *gnu_result_type_p = gnu_result_type;
2501 return gnu_result;
2504 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Case_Statement,
2505 to a GCC tree, which is returned. */
2507 static tree
2508 Case_Statement_to_gnu (Node_Id gnat_node)
2510 tree gnu_result, gnu_expr, gnu_label;
2511 Node_Id gnat_when;
2512 location_t end_locus;
2513 bool may_fallthru = false;
2515 gnu_expr = gnat_to_gnu (Expression (gnat_node));
2516 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2518 /* The range of values in a case statement is determined by the rules in
2519 RM 5.4(7-9). In almost all cases, this range is represented by the Etype
2520 of the expression. One exception arises in the case of a simple name that
2521 is parenthesized. This still has the Etype of the name, but since it is
2522 not a name, para 7 does not apply, and we need to go to the base type.
2523 This is the only case where parenthesization affects the dynamic
2524 semantics (i.e. the range of possible values at run time that is covered
2525 by the others alternative).
2527 Another exception is if the subtype of the expression is non-static. In
2528 that case, we also have to use the base type. */
2529 if (Paren_Count (Expression (gnat_node)) != 0
2530 || !Is_OK_Static_Subtype (Underlying_Type
2531 (Etype (Expression (gnat_node)))))
2532 gnu_expr = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
2534 /* We build a SWITCH_EXPR that contains the code with interspersed
2535 CASE_LABEL_EXPRs for each label. */
2536 if (!Sloc_to_locus (End_Location (gnat_node), &end_locus))
2537 end_locus = input_location;
2538 gnu_label = create_artificial_label (end_locus);
2539 start_stmt_group ();
2541 for (gnat_when = First_Non_Pragma (Alternatives (gnat_node));
2542 Present (gnat_when);
2543 gnat_when = Next_Non_Pragma (gnat_when))
2545 bool choices_added_p = false;
2546 Node_Id gnat_choice;
2548 /* First compile all the different case choices for the current WHEN
2549 alternative. */
2550 for (gnat_choice = First (Discrete_Choices (gnat_when));
2551 Present (gnat_choice);
2552 gnat_choice = Next (gnat_choice))
2554 tree gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2555 tree label = create_artificial_label (input_location);
2557 switch (Nkind (gnat_choice))
2559 case N_Range:
2560 gnu_low = gnat_to_gnu (Low_Bound (gnat_choice));
2561 gnu_high = gnat_to_gnu (High_Bound (gnat_choice));
2562 break;
2564 case N_Subtype_Indication:
2565 gnu_low = gnat_to_gnu (Low_Bound (Range_Expression
2566 (Constraint (gnat_choice))));
2567 gnu_high = gnat_to_gnu (High_Bound (Range_Expression
2568 (Constraint (gnat_choice))));
2569 break;
2571 case N_Identifier:
2572 case N_Expanded_Name:
2573 /* This represents either a subtype range or a static value of
2574 some kind; Ekind says which. */
2575 if (IN (Ekind (Entity (gnat_choice)), Type_Kind))
2577 tree gnu_type = get_unpadded_type (Entity (gnat_choice));
2579 gnu_low = TYPE_MIN_VALUE (gnu_type);
2580 gnu_high = TYPE_MAX_VALUE (gnu_type);
2581 break;
2584 /* ... fall through ... */
2586 case N_Character_Literal:
2587 case N_Integer_Literal:
2588 gnu_low = gnat_to_gnu (gnat_choice);
2589 break;
2591 case N_Others_Choice:
2592 break;
2594 default:
2595 gcc_unreachable ();
2598 /* Everything should be folded into constants at this point. */
2599 gcc_assert (!gnu_low || TREE_CODE (gnu_low) == INTEGER_CST);
2600 gcc_assert (!gnu_high || TREE_CODE (gnu_high) == INTEGER_CST);
2602 add_stmt_with_node (build_case_label (gnu_low, gnu_high, label),
2603 gnat_choice);
2604 choices_added_p = true;
2607 /* This construct doesn't define a scope so we shouldn't push a binding
2608 level around the statement list. Except that we have always done so
2609 historically and this makes it possible to reduce stack usage. As a
2610 compromise, we keep doing it for case statements, for which this has
2611 never been problematic, but not for case expressions in Ada 2012. */
2612 if (choices_added_p)
2614 const bool is_case_expression
2615 = (Nkind (Parent (gnat_node)) == N_Expression_With_Actions);
2616 tree group
2617 = build_stmt_group (Statements (gnat_when), !is_case_expression);
2618 bool group_may_fallthru = block_may_fallthru (group);
2619 add_stmt (group);
2620 if (group_may_fallthru)
2622 tree stmt = build1 (GOTO_EXPR, void_type_node, gnu_label);
2623 SET_EXPR_LOCATION (stmt, end_locus);
2624 add_stmt (stmt);
2625 may_fallthru = true;
2630 /* Now emit a definition of the label the cases branch to, if any. */
2631 if (may_fallthru)
2632 add_stmt (build1 (LABEL_EXPR, void_type_node, gnu_label));
2633 gnu_result = build3 (SWITCH_EXPR, TREE_TYPE (gnu_expr), gnu_expr,
2634 end_stmt_group (), NULL_TREE);
2636 return gnu_result;
2639 /* Find out whether VAR is an iteration variable of an enclosing loop in the
2640 current function. If so, push a range_check_info structure onto the stack
2641 of this enclosing loop and return it. Otherwise, return NULL. */
2643 static struct range_check_info_d *
2644 push_range_check_info (tree var)
2646 struct loop_info_d *iter = NULL;
2647 unsigned int i;
2649 var = remove_conversions (var, false);
2651 if (TREE_CODE (var) != VAR_DECL)
2652 return NULL;
2654 if (decl_function_context (var) != current_function_decl)
2655 return NULL;
2657 gcc_assert (vec_safe_length (gnu_loop_stack) > 0);
2659 for (i = vec_safe_length (gnu_loop_stack) - 1;
2660 vec_safe_iterate (gnu_loop_stack, i, &iter);
2661 i--)
2662 if (var == iter->loop_var)
2663 break;
2665 if (iter)
2667 struct range_check_info_d *rci = ggc_alloc<range_check_info_d> ();
2668 vec_safe_push (iter->checks, rci);
2669 return rci;
2672 return NULL;
2675 /* Return true if VAL (of type TYPE) can equal the minimum value if MAX is
2676 false, or the maximum value if MAX is true, of TYPE. */
2678 static bool
2679 can_equal_min_or_max_val_p (tree val, tree type, bool max)
2681 tree min_or_max_val = (max ? TYPE_MAX_VALUE (type) : TYPE_MIN_VALUE (type));
2683 if (TREE_CODE (min_or_max_val) != INTEGER_CST)
2684 return true;
2686 if (TREE_CODE (val) == NOP_EXPR)
2687 val = (max
2688 ? TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val, 0)))
2689 : TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val, 0))));
2691 if (TREE_CODE (val) != INTEGER_CST)
2692 return true;
2694 if (max)
2695 return tree_int_cst_lt (val, min_or_max_val) == 0;
2696 else
2697 return tree_int_cst_lt (min_or_max_val, val) == 0;
2700 /* Return true if VAL (of type TYPE) can equal the minimum value of TYPE.
2701 If REVERSE is true, minimum value is taken as maximum value. */
2703 static inline bool
2704 can_equal_min_val_p (tree val, tree type, bool reverse)
2706 return can_equal_min_or_max_val_p (val, type, reverse);
2709 /* Return true if VAL (of type TYPE) can equal the maximum value of TYPE.
2710 If REVERSE is true, maximum value is taken as minimum value. */
2712 static inline bool
2713 can_equal_max_val_p (tree val, tree type, bool reverse)
2715 return can_equal_min_or_max_val_p (val, type, !reverse);
2718 /* Return true if VAL1 can be lower than VAL2. */
2720 static bool
2721 can_be_lower_p (tree val1, tree val2)
2723 if (TREE_CODE (val1) == NOP_EXPR)
2724 val1 = TYPE_MIN_VALUE (TREE_TYPE (TREE_OPERAND (val1, 0)));
2726 if (TREE_CODE (val1) != INTEGER_CST)
2727 return true;
2729 if (TREE_CODE (val2) == NOP_EXPR)
2730 val2 = TYPE_MAX_VALUE (TREE_TYPE (TREE_OPERAND (val2, 0)));
2732 if (TREE_CODE (val2) != INTEGER_CST)
2733 return true;
2735 return tree_int_cst_lt (val1, val2);
2738 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Loop_Statement,
2739 to a GCC tree, which is returned. */
2741 static tree
2742 Loop_Statement_to_gnu (Node_Id gnat_node)
2744 const Node_Id gnat_iter_scheme = Iteration_Scheme (gnat_node);
2745 struct loop_info_d *gnu_loop_info = ggc_cleared_alloc<loop_info_d> ();
2746 tree gnu_loop_stmt = build4 (LOOP_STMT, void_type_node, NULL_TREE,
2747 NULL_TREE, NULL_TREE, NULL_TREE);
2748 tree gnu_loop_label = create_artificial_label (input_location);
2749 tree gnu_cond_expr = NULL_TREE, gnu_low = NULL_TREE, gnu_high = NULL_TREE;
2750 tree gnu_result;
2752 /* Push the loop_info structure associated with the LOOP_STMT. */
2753 vec_safe_push (gnu_loop_stack, gnu_loop_info);
2755 /* Set location information for statement and end label. */
2756 set_expr_location_from_node (gnu_loop_stmt, gnat_node);
2757 Sloc_to_locus (Sloc (End_Label (gnat_node)),
2758 &DECL_SOURCE_LOCATION (gnu_loop_label));
2759 LOOP_STMT_LABEL (gnu_loop_stmt) = gnu_loop_label;
2761 /* Save the statement for later reuse. */
2762 gnu_loop_info->stmt = gnu_loop_stmt;
2764 /* Set the condition under which the loop must keep going.
2765 For the case "LOOP .... END LOOP;" the condition is always true. */
2766 if (No (gnat_iter_scheme))
2769 /* For the case "WHILE condition LOOP ..... END LOOP;" it's immediate. */
2770 else if (Present (Condition (gnat_iter_scheme)))
2771 LOOP_STMT_COND (gnu_loop_stmt)
2772 = gnat_to_gnu (Condition (gnat_iter_scheme));
2774 /* Otherwise we have an iteration scheme and the condition is given by the
2775 bounds of the subtype of the iteration variable. */
2776 else
2778 Node_Id gnat_loop_spec = Loop_Parameter_Specification (gnat_iter_scheme);
2779 Entity_Id gnat_loop_var = Defining_Entity (gnat_loop_spec);
2780 Entity_Id gnat_type = Etype (gnat_loop_var);
2781 tree gnu_type = get_unpadded_type (gnat_type);
2782 tree gnu_base_type = get_base_type (gnu_type);
2783 tree gnu_one_node = convert (gnu_base_type, integer_one_node);
2784 tree gnu_loop_var, gnu_loop_iv, gnu_first, gnu_last, gnu_stmt;
2785 enum tree_code update_code, test_code, shift_code;
2786 bool reverse = Reverse_Present (gnat_loop_spec), use_iv = false;
2788 gnu_low = convert (gnu_base_type, TYPE_MIN_VALUE (gnu_type));
2789 gnu_high = convert (gnu_base_type, TYPE_MAX_VALUE (gnu_type));
2791 /* We must disable modulo reduction for the iteration variable, if any,
2792 in order for the loop comparison to be effective. */
2793 if (reverse)
2795 gnu_first = gnu_high;
2796 gnu_last = gnu_low;
2797 update_code = MINUS_NOMOD_EXPR;
2798 test_code = GE_EXPR;
2799 shift_code = PLUS_NOMOD_EXPR;
2801 else
2803 gnu_first = gnu_low;
2804 gnu_last = gnu_high;
2805 update_code = PLUS_NOMOD_EXPR;
2806 test_code = LE_EXPR;
2807 shift_code = MINUS_NOMOD_EXPR;
2810 /* We use two different strategies to translate the loop, depending on
2811 whether optimization is enabled.
2813 If it is, we generate the canonical loop form expected by the loop
2814 optimizer and the loop vectorizer, which is the do-while form:
2816 ENTRY_COND
2817 loop:
2818 TOP_UPDATE
2819 BODY
2820 BOTTOM_COND
2821 GOTO loop
2823 This avoids an implicit dependency on loop header copying and makes
2824 it possible to turn BOTTOM_COND into an inequality test.
2826 If optimization is disabled, loop header copying doesn't come into
2827 play and we try to generate the loop form with the fewer conditional
2828 branches. First, the default form, which is:
2830 loop:
2831 TOP_COND
2832 BODY
2833 BOTTOM_UPDATE
2834 GOTO loop
2836 It should catch most loops with constant ending point. Then, if we
2837 cannot, we try to generate the shifted form:
2839 loop:
2840 TOP_COND
2841 TOP_UPDATE
2842 BODY
2843 GOTO loop
2845 which should catch loops with constant starting point. Otherwise, if
2846 we cannot, we generate the fallback form:
2848 ENTRY_COND
2849 loop:
2850 BODY
2851 BOTTOM_COND
2852 BOTTOM_UPDATE
2853 GOTO loop
2855 which works in all cases. */
2857 if (optimize)
2859 /* We can use the do-while form directly if GNU_FIRST-1 doesn't
2860 overflow. */
2861 if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse))
2864 /* Otherwise, use the do-while form with the help of a special
2865 induction variable in the unsigned version of the base type
2866 or the unsigned version of the size type, whichever is the
2867 largest, in order to have wrap-around arithmetics for it. */
2868 else
2870 if (TYPE_PRECISION (gnu_base_type)
2871 > TYPE_PRECISION (size_type_node))
2872 gnu_base_type
2873 = gnat_type_for_size (TYPE_PRECISION (gnu_base_type), 1);
2874 else
2875 gnu_base_type = size_type_node;
2877 gnu_first = convert (gnu_base_type, gnu_first);
2878 gnu_last = convert (gnu_base_type, gnu_last);
2879 gnu_one_node = convert (gnu_base_type, integer_one_node);
2880 use_iv = true;
2883 gnu_first
2884 = build_binary_op (shift_code, gnu_base_type, gnu_first,
2885 gnu_one_node);
2886 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
2887 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
2889 else
2891 /* We can use the default form if GNU_LAST+1 doesn't overflow. */
2892 if (!can_equal_max_val_p (gnu_last, gnu_base_type, reverse))
2895 /* Otherwise, we can use the shifted form if neither GNU_FIRST-1 nor
2896 GNU_LAST-1 does. */
2897 else if (!can_equal_min_val_p (gnu_first, gnu_base_type, reverse)
2898 && !can_equal_min_val_p (gnu_last, gnu_base_type, reverse))
2900 gnu_first
2901 = build_binary_op (shift_code, gnu_base_type, gnu_first,
2902 gnu_one_node);
2903 gnu_last
2904 = build_binary_op (shift_code, gnu_base_type, gnu_last,
2905 gnu_one_node);
2906 LOOP_STMT_TOP_UPDATE_P (gnu_loop_stmt) = 1;
2909 /* Otherwise, use the fallback form. */
2910 else
2911 LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt) = 1;
2914 /* If we use the BOTTOM_COND, we can turn the test into an inequality
2915 test but we may have to add ENTRY_COND to protect the empty loop. */
2916 if (LOOP_STMT_BOTTOM_COND_P (gnu_loop_stmt))
2918 test_code = NE_EXPR;
2919 if (can_be_lower_p (gnu_high, gnu_low))
2921 gnu_cond_expr
2922 = build3 (COND_EXPR, void_type_node,
2923 build_binary_op (LE_EXPR, boolean_type_node,
2924 gnu_low, gnu_high),
2925 NULL_TREE, alloc_stmt_list ());
2926 set_expr_location_from_node (gnu_cond_expr, gnat_loop_spec);
2930 /* Open a new nesting level that will surround the loop to declare the
2931 iteration variable. */
2932 start_stmt_group ();
2933 gnat_pushlevel ();
2935 /* If we use the special induction variable, create it and set it to
2936 its initial value. Morever, the regular iteration variable cannot
2937 itself be initialized, lest the initial value wrapped around. */
2938 if (use_iv)
2940 gnu_loop_iv
2941 = create_init_temporary ("I", gnu_first, &gnu_stmt, gnat_loop_var);
2942 add_stmt (gnu_stmt);
2943 gnu_first = NULL_TREE;
2945 else
2946 gnu_loop_iv = NULL_TREE;
2948 /* Declare the iteration variable and set it to its initial value. */
2949 gnu_loop_var = gnat_to_gnu_entity (gnat_loop_var, gnu_first, 1);
2950 if (DECL_BY_REF_P (gnu_loop_var))
2951 gnu_loop_var = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_loop_var);
2952 else if (use_iv)
2954 gcc_assert (DECL_LOOP_PARM_P (gnu_loop_var));
2955 SET_DECL_INDUCTION_VAR (gnu_loop_var, gnu_loop_iv);
2957 gnu_loop_info->loop_var = gnu_loop_var;
2959 /* Do all the arithmetics in the base type. */
2960 gnu_loop_var = convert (gnu_base_type, gnu_loop_var);
2962 /* Set either the top or bottom exit condition. */
2963 if (use_iv)
2964 LOOP_STMT_COND (gnu_loop_stmt)
2965 = build_binary_op (test_code, boolean_type_node, gnu_loop_iv,
2966 gnu_last);
2967 else
2968 LOOP_STMT_COND (gnu_loop_stmt)
2969 = build_binary_op (test_code, boolean_type_node, gnu_loop_var,
2970 gnu_last);
2972 /* Set either the top or bottom update statement and give it the source
2973 location of the iteration for better coverage info. */
2974 if (use_iv)
2976 gnu_stmt
2977 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_iv,
2978 build_binary_op (update_code, gnu_base_type,
2979 gnu_loop_iv, gnu_one_node));
2980 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2981 append_to_statement_list (gnu_stmt,
2982 &LOOP_STMT_UPDATE (gnu_loop_stmt));
2983 gnu_stmt
2984 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
2985 gnu_loop_iv);
2986 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2987 append_to_statement_list (gnu_stmt,
2988 &LOOP_STMT_UPDATE (gnu_loop_stmt));
2990 else
2992 gnu_stmt
2993 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_loop_var,
2994 build_binary_op (update_code, gnu_base_type,
2995 gnu_loop_var, gnu_one_node));
2996 set_expr_location_from_node (gnu_stmt, gnat_iter_scheme);
2997 LOOP_STMT_UPDATE (gnu_loop_stmt) = gnu_stmt;
3001 /* If the loop was named, have the name point to this loop. In this case,
3002 the association is not a DECL node, but the end label of the loop. */
3003 if (Present (Identifier (gnat_node)))
3004 save_gnu_tree (Entity (Identifier (gnat_node)), gnu_loop_label, true);
3006 /* Make the loop body into its own block, so any allocated storage will be
3007 released every iteration. This is needed for stack allocation. */
3008 LOOP_STMT_BODY (gnu_loop_stmt)
3009 = build_stmt_group (Statements (gnat_node), true);
3010 TREE_SIDE_EFFECTS (gnu_loop_stmt) = 1;
3012 /* If we have an iteration scheme, then we are in a statement group. Add
3013 the LOOP_STMT to it, finish it and make it the "loop". */
3014 if (Present (gnat_iter_scheme) && No (Condition (gnat_iter_scheme)))
3016 struct range_check_info_d *rci;
3017 unsigned n_checks = vec_safe_length (gnu_loop_info->checks);
3018 unsigned int i;
3020 /* First, if we have computed a small number of invariant conditions for
3021 range checks applied to the iteration variable, then initialize these
3022 conditions in front of the loop. Otherwise, leave them set to true.
3024 ??? The heuristics need to be improved, by taking into account the
3025 following datapoints:
3026 - loop unswitching is disabled for big loops. The cap is the
3027 parameter PARAM_MAX_UNSWITCH_INSNS (50).
3028 - loop unswitching can only be applied a small number of times
3029 to a given loop. The cap is PARAM_MAX_UNSWITCH_LEVEL (3).
3030 - the front-end quickly generates useless or redundant checks
3031 that can be entirely optimized away in the end. */
3032 if (1 <= n_checks && n_checks <= 4)
3033 for (i = 0;
3034 vec_safe_iterate (gnu_loop_info->checks, i, &rci);
3035 i++)
3037 tree low_ok
3038 = rci->low_bound
3039 ? build_binary_op (GE_EXPR, boolean_type_node,
3040 convert (rci->type, gnu_low),
3041 rci->low_bound)
3042 : boolean_true_node;
3044 tree high_ok
3045 = rci->high_bound
3046 ? build_binary_op (LE_EXPR, boolean_type_node,
3047 convert (rci->type, gnu_high),
3048 rci->high_bound)
3049 : boolean_true_node;
3051 tree range_ok
3052 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
3053 low_ok, high_ok);
3055 TREE_OPERAND (rci->invariant_cond, 0)
3056 = build_unary_op (TRUTH_NOT_EXPR, boolean_type_node, range_ok);
3058 add_stmt_with_node_force (rci->invariant_cond, gnat_node);
3061 add_stmt (gnu_loop_stmt);
3062 gnat_poplevel ();
3063 gnu_loop_stmt = end_stmt_group ();
3066 /* If we have an outer COND_EXPR, that's our result and this loop is its
3067 "true" statement. Otherwise, the result is the LOOP_STMT. */
3068 if (gnu_cond_expr)
3070 COND_EXPR_THEN (gnu_cond_expr) = gnu_loop_stmt;
3071 TREE_SIDE_EFFECTS (gnu_cond_expr) = 1;
3072 gnu_result = gnu_cond_expr;
3074 else
3075 gnu_result = gnu_loop_stmt;
3077 gnu_loop_stack->pop ();
3079 return gnu_result;
3082 /* This page implements a form of Named Return Value optimization modelled
3083 on the C++ optimization of the same name. The main difference is that
3084 we disregard any semantical considerations when applying it here, the
3085 counterpart being that we don't try to apply it to semantically loaded
3086 return types, i.e. types with the TYPE_BY_REFERENCE_P flag set.
3088 We consider a function body of the following GENERIC form:
3090 return_type R1;
3091 [...]
3092 RETURN_EXPR [<retval> = ...]
3093 [...]
3094 RETURN_EXPR [<retval> = R1]
3095 [...]
3096 return_type Ri;
3097 [...]
3098 RETURN_EXPR [<retval> = ...]
3099 [...]
3100 RETURN_EXPR [<retval> = Ri]
3101 [...]
3103 and we try to fulfill a simple criterion that would make it possible to
3104 replace one or several Ri variables with the RESULT_DECL of the function.
3106 The first observation is that RETURN_EXPRs that don't directly reference
3107 any of the Ri variables on the RHS of their assignment are transparent wrt
3108 the optimization. This is because the Ri variables aren't addressable so
3109 any transformation applied to them doesn't affect the RHS; moreover, the
3110 assignment writes the full <retval> object so existing values are entirely
3111 discarded.
3113 This property can be extended to some forms of RETURN_EXPRs that reference
3114 the Ri variables, for example CONSTRUCTORs, but isn't true in the general
3115 case, in particular when function calls are involved.
3117 Therefore the algorithm is as follows:
3119 1. Collect the list of candidates for a Named Return Value (Ri variables
3120 on the RHS of assignments of RETURN_EXPRs) as well as the list of the
3121 other expressions on the RHS of such assignments.
3123 2. Prune the members of the first list (candidates) that are referenced
3124 by a member of the second list (expressions).
3126 3. Extract a set of candidates with non-overlapping live ranges from the
3127 first list. These are the Named Return Values.
3129 4. Adjust the relevant RETURN_EXPRs and replace the occurrences of the
3130 Named Return Values in the function with the RESULT_DECL.
3132 If the function returns an unconstrained type, things are a bit different
3133 because the anonymous return object is allocated on the secondary stack
3134 and RESULT_DECL is only a pointer to it. Each return object can be of a
3135 different size and is allocated separately so we need not care about the
3136 aforementioned overlapping issues. Therefore, we don't collect the other
3137 expressions and skip step #2 in the algorithm. */
3139 struct nrv_data
3141 bitmap nrv;
3142 tree result;
3143 Node_Id gnat_ret;
3144 hash_set<tree> *visited;
3147 /* Return true if T is a Named Return Value. */
3149 static inline bool
3150 is_nrv_p (bitmap nrv, tree t)
3152 return TREE_CODE (t) == VAR_DECL && bitmap_bit_p (nrv, DECL_UID (t));
3155 /* Helper function for walk_tree, used by finalize_nrv below. */
3157 static tree
3158 prune_nrv_r (tree *tp, int *walk_subtrees, void *data)
3160 struct nrv_data *dp = (struct nrv_data *)data;
3161 tree t = *tp;
3163 /* No need to walk into types or decls. */
3164 if (IS_TYPE_OR_DECL_P (t))
3165 *walk_subtrees = 0;
3167 if (is_nrv_p (dp->nrv, t))
3168 bitmap_clear_bit (dp->nrv, DECL_UID (t));
3170 return NULL_TREE;
3173 /* Prune Named Return Values in BLOCK and return true if there is still a
3174 Named Return Value in BLOCK or one of its sub-blocks. */
3176 static bool
3177 prune_nrv_in_block (bitmap nrv, tree block)
3179 bool has_nrv = false;
3180 tree t;
3182 /* First recurse on the sub-blocks. */
3183 for (t = BLOCK_SUBBLOCKS (block); t; t = BLOCK_CHAIN (t))
3184 has_nrv |= prune_nrv_in_block (nrv, t);
3186 /* Then make sure to keep at most one NRV per block. */
3187 for (t = BLOCK_VARS (block); t; t = DECL_CHAIN (t))
3188 if (is_nrv_p (nrv, t))
3190 if (has_nrv)
3191 bitmap_clear_bit (nrv, DECL_UID (t));
3192 else
3193 has_nrv = true;
3196 return has_nrv;
3199 /* Helper function for walk_tree, used by finalize_nrv below. */
3201 static tree
3202 finalize_nrv_r (tree *tp, int *walk_subtrees, void *data)
3204 struct nrv_data *dp = (struct nrv_data *)data;
3205 tree t = *tp;
3207 /* No need to walk into types. */
3208 if (TYPE_P (t))
3209 *walk_subtrees = 0;
3211 /* Change RETURN_EXPRs of NRVs to just refer to the RESULT_DECL; this is a
3212 nop, but differs from using NULL_TREE in that it indicates that we care
3213 about the value of the RESULT_DECL. */
3214 else if (TREE_CODE (t) == RETURN_EXPR
3215 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
3217 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1), init_expr;
3219 /* If this is the temporary created for a return value with variable
3220 size in Call_to_gnu, we replace the RHS with the init expression. */
3221 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3222 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
3223 && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
3224 == TREE_OPERAND (ret_val, 1))
3226 init_expr = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
3227 ret_val = TREE_OPERAND (ret_val, 1);
3229 else
3230 init_expr = NULL_TREE;
3232 /* Strip useless conversions around the return value. */
3233 if (gnat_useless_type_conversion (ret_val))
3234 ret_val = TREE_OPERAND (ret_val, 0);
3236 if (is_nrv_p (dp->nrv, ret_val))
3238 if (init_expr)
3239 TREE_OPERAND (TREE_OPERAND (t, 0), 1) = init_expr;
3240 else
3241 TREE_OPERAND (t, 0) = dp->result;
3245 /* Replace the DECL_EXPR of NRVs with an initialization of the RESULT_DECL,
3246 if needed. */
3247 else if (TREE_CODE (t) == DECL_EXPR
3248 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3250 tree var = DECL_EXPR_DECL (t), init;
3252 if (DECL_INITIAL (var))
3254 init = build_binary_op (INIT_EXPR, NULL_TREE, dp->result,
3255 DECL_INITIAL (var));
3256 SET_EXPR_LOCATION (init, EXPR_LOCATION (t));
3257 DECL_INITIAL (var) = NULL_TREE;
3259 else
3260 init = build_empty_stmt (EXPR_LOCATION (t));
3261 *tp = init;
3263 /* Identify the NRV to the RESULT_DECL for debugging purposes. */
3264 SET_DECL_VALUE_EXPR (var, dp->result);
3265 DECL_HAS_VALUE_EXPR_P (var) = 1;
3266 /* ??? Kludge to avoid an assertion failure during inlining. */
3267 DECL_SIZE (var) = bitsize_unit_node;
3268 DECL_SIZE_UNIT (var) = size_one_node;
3271 /* And replace all uses of NRVs with the RESULT_DECL. */
3272 else if (is_nrv_p (dp->nrv, t))
3273 *tp = convert (TREE_TYPE (t), dp->result);
3275 /* Avoid walking into the same tree more than once. Unfortunately, we
3276 can't just use walk_tree_without_duplicates because it would only
3277 call us for the first occurrence of NRVs in the function body. */
3278 if (dp->visited->add (*tp))
3279 *walk_subtrees = 0;
3281 return NULL_TREE;
3284 /* Likewise, but used when the function returns an unconstrained type. */
3286 static tree
3287 finalize_nrv_unc_r (tree *tp, int *walk_subtrees, void *data)
3289 struct nrv_data *dp = (struct nrv_data *)data;
3290 tree t = *tp;
3292 /* No need to walk into types. */
3293 if (TYPE_P (t))
3294 *walk_subtrees = 0;
3296 /* We need to see the DECL_EXPR of NRVs before any other references so we
3297 walk the body of BIND_EXPR before walking its variables. */
3298 else if (TREE_CODE (t) == BIND_EXPR)
3299 walk_tree (&BIND_EXPR_BODY (t), finalize_nrv_unc_r, data, NULL);
3301 /* Change RETURN_EXPRs of NRVs to assign to the RESULT_DECL only the final
3302 return value built by the allocator instead of the whole construct. */
3303 else if (TREE_CODE (t) == RETURN_EXPR
3304 && TREE_CODE (TREE_OPERAND (t, 0)) == INIT_EXPR)
3306 tree ret_val = TREE_OPERAND (TREE_OPERAND (t, 0), 1);
3308 /* This is the construct returned by the allocator. */
3309 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3310 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR)
3312 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (ret_val)))
3313 ret_val
3314 = (*CONSTRUCTOR_ELTS (TREE_OPERAND (TREE_OPERAND (ret_val, 0),
3315 1)))[1].value;
3316 else
3317 ret_val = TREE_OPERAND (TREE_OPERAND (ret_val, 0), 1);
3320 /* Strip useless conversions around the return value. */
3321 if (gnat_useless_type_conversion (ret_val)
3322 || TREE_CODE (ret_val) == VIEW_CONVERT_EXPR)
3323 ret_val = TREE_OPERAND (ret_val, 0);
3325 /* Strip unpadding around the return value. */
3326 if (TREE_CODE (ret_val) == COMPONENT_REF
3327 && TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
3328 ret_val = TREE_OPERAND (ret_val, 0);
3330 /* Assign the new return value to the RESULT_DECL. */
3331 if (is_nrv_p (dp->nrv, ret_val))
3332 TREE_OPERAND (TREE_OPERAND (t, 0), 1)
3333 = TREE_OPERAND (DECL_INITIAL (ret_val), 0);
3336 /* Adjust the DECL_EXPR of NRVs to call the allocator and save the result
3337 into a new variable. */
3338 else if (TREE_CODE (t) == DECL_EXPR
3339 && is_nrv_p (dp->nrv, DECL_EXPR_DECL (t)))
3341 tree saved_current_function_decl = current_function_decl;
3342 tree var = DECL_EXPR_DECL (t);
3343 tree alloc, p_array, new_var, new_ret;
3344 vec<constructor_elt, va_gc> *v;
3345 vec_alloc (v, 2);
3347 /* Create an artificial context to build the allocation. */
3348 current_function_decl = decl_function_context (var);
3349 start_stmt_group ();
3350 gnat_pushlevel ();
3352 /* This will return a COMPOUND_EXPR with the allocation in the first
3353 arm and the final return value in the second arm. */
3354 alloc = build_allocator (TREE_TYPE (var), DECL_INITIAL (var),
3355 TREE_TYPE (dp->result),
3356 Procedure_To_Call (dp->gnat_ret),
3357 Storage_Pool (dp->gnat_ret),
3358 Empty, false);
3360 /* The new variable is built as a reference to the allocated space. */
3361 new_var
3362 = build_decl (DECL_SOURCE_LOCATION (var), VAR_DECL, DECL_NAME (var),
3363 build_reference_type (TREE_TYPE (var)));
3364 DECL_BY_REFERENCE (new_var) = 1;
3366 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (alloc)))
3368 /* The new initial value is a COMPOUND_EXPR with the allocation in
3369 the first arm and the value of P_ARRAY in the second arm. */
3370 DECL_INITIAL (new_var)
3371 = build2 (COMPOUND_EXPR, TREE_TYPE (new_var),
3372 TREE_OPERAND (alloc, 0),
3373 (*CONSTRUCTOR_ELTS (TREE_OPERAND (alloc, 1)))[0].value);
3375 /* Build a modified CONSTRUCTOR that references NEW_VAR. */
3376 p_array = TYPE_FIELDS (TREE_TYPE (alloc));
3377 CONSTRUCTOR_APPEND_ELT (v, p_array,
3378 fold_convert (TREE_TYPE (p_array), new_var));
3379 CONSTRUCTOR_APPEND_ELT (v, DECL_CHAIN (p_array),
3380 (*CONSTRUCTOR_ELTS (
3381 TREE_OPERAND (alloc, 1)))[1].value);
3382 new_ret = build_constructor (TREE_TYPE (alloc), v);
3384 else
3386 /* The new initial value is just the allocation. */
3387 DECL_INITIAL (new_var) = alloc;
3388 new_ret = fold_convert (TREE_TYPE (alloc), new_var);
3391 gnat_pushdecl (new_var, Empty);
3393 /* Destroy the artificial context and insert the new statements. */
3394 gnat_zaplevel ();
3395 *tp = end_stmt_group ();
3396 current_function_decl = saved_current_function_decl;
3398 /* Chain NEW_VAR immediately after VAR and ignore the latter. */
3399 DECL_CHAIN (new_var) = DECL_CHAIN (var);
3400 DECL_CHAIN (var) = new_var;
3401 DECL_IGNORED_P (var) = 1;
3403 /* Save the new return value and the dereference of NEW_VAR. */
3404 DECL_INITIAL (var)
3405 = build2 (COMPOUND_EXPR, TREE_TYPE (var), new_ret,
3406 build1 (INDIRECT_REF, TREE_TYPE (var), new_var));
3407 /* ??? Kludge to avoid messing up during inlining. */
3408 DECL_CONTEXT (var) = NULL_TREE;
3411 /* And replace all uses of NRVs with the dereference of NEW_VAR. */
3412 else if (is_nrv_p (dp->nrv, t))
3413 *tp = TREE_OPERAND (DECL_INITIAL (t), 1);
3415 /* Avoid walking into the same tree more than once. Unfortunately, we
3416 can't just use walk_tree_without_duplicates because it would only
3417 call us for the first occurrence of NRVs in the function body. */
3418 if (dp->visited->add (*tp))
3419 *walk_subtrees = 0;
3421 return NULL_TREE;
3424 /* Finalize the Named Return Value optimization for FNDECL. The NRV bitmap
3425 contains the candidates for Named Return Value and OTHER is a list of
3426 the other return values. GNAT_RET is a representative return node. */
3428 static void
3429 finalize_nrv (tree fndecl, bitmap nrv, vec<tree, va_gc> *other, Node_Id gnat_ret)
3431 struct cgraph_node *node;
3432 struct nrv_data data;
3433 walk_tree_fn func;
3434 unsigned int i;
3435 tree iter;
3437 /* We shouldn't be applying the optimization to return types that we aren't
3438 allowed to manipulate freely. */
3439 gcc_assert (!TYPE_IS_BY_REFERENCE_P (TREE_TYPE (TREE_TYPE (fndecl))));
3441 /* Prune the candidates that are referenced by other return values. */
3442 data.nrv = nrv;
3443 data.result = NULL_TREE;
3444 data.visited = NULL;
3445 for (i = 0; vec_safe_iterate (other, i, &iter); i++)
3446 walk_tree_without_duplicates (&iter, prune_nrv_r, &data);
3447 if (bitmap_empty_p (nrv))
3448 return;
3450 /* Prune also the candidates that are referenced by nested functions. */
3451 node = cgraph_node::get_create (fndecl);
3452 for (node = node->nested; node; node = node->next_nested)
3453 walk_tree_without_duplicates (&DECL_SAVED_TREE (node->decl), prune_nrv_r,
3454 &data);
3455 if (bitmap_empty_p (nrv))
3456 return;
3458 /* Extract a set of NRVs with non-overlapping live ranges. */
3459 if (!prune_nrv_in_block (nrv, DECL_INITIAL (fndecl)))
3460 return;
3462 /* Adjust the relevant RETURN_EXPRs and replace the occurrences of NRVs. */
3463 data.nrv = nrv;
3464 data.result = DECL_RESULT (fndecl);
3465 data.gnat_ret = gnat_ret;
3466 data.visited = new hash_set<tree>;
3467 if (TYPE_RETURN_UNCONSTRAINED_P (TREE_TYPE (fndecl)))
3468 func = finalize_nrv_unc_r;
3469 else
3470 func = finalize_nrv_r;
3471 walk_tree (&DECL_SAVED_TREE (fndecl), func, &data, NULL);
3472 delete data.visited;
3475 /* Return true if RET_VAL can be used as a Named Return Value for the
3476 anonymous return object RET_OBJ. */
3478 static bool
3479 return_value_ok_for_nrv_p (tree ret_obj, tree ret_val)
3481 if (TREE_CODE (ret_val) != VAR_DECL)
3482 return false;
3484 if (TREE_THIS_VOLATILE (ret_val))
3485 return false;
3487 if (DECL_CONTEXT (ret_val) != current_function_decl)
3488 return false;
3490 if (TREE_STATIC (ret_val))
3491 return false;
3493 if (TREE_ADDRESSABLE (ret_val))
3494 return false;
3496 if (ret_obj && DECL_ALIGN (ret_val) > DECL_ALIGN (ret_obj))
3497 return false;
3499 return true;
3502 /* Build a RETURN_EXPR. If RET_VAL is non-null, build a RETURN_EXPR around
3503 the assignment of RET_VAL to RET_OBJ. Otherwise build a bare RETURN_EXPR
3504 around RESULT_OBJ, which may be null in this case. */
3506 static tree
3507 build_return_expr (tree ret_obj, tree ret_val)
3509 tree result_expr;
3511 if (ret_val)
3513 /* The gimplifier explicitly enforces the following invariant:
3515 RETURN_EXPR
3517 INIT_EXPR
3520 RET_OBJ ...
3522 As a consequence, type consistency dictates that we use the type
3523 of the RET_OBJ as the operation type. */
3524 tree operation_type = TREE_TYPE (ret_obj);
3526 /* Convert the right operand to the operation type. Note that this is
3527 the transformation applied in the INIT_EXPR case of build_binary_op,
3528 with the assumption that the type cannot involve a placeholder. */
3529 if (operation_type != TREE_TYPE (ret_val))
3530 ret_val = convert (operation_type, ret_val);
3532 /* We always can use an INIT_EXPR for the return object. */
3533 result_expr = build2 (INIT_EXPR, void_type_node, ret_obj, ret_val);
3535 /* If the function returns an aggregate type, find out whether this is
3536 a candidate for Named Return Value. If so, record it. Otherwise,
3537 if this is an expression of some kind, record it elsewhere. */
3538 if (optimize
3539 && AGGREGATE_TYPE_P (operation_type)
3540 && !TYPE_IS_FAT_POINTER_P (operation_type)
3541 && TYPE_MODE (operation_type) == BLKmode
3542 && aggregate_value_p (operation_type, current_function_decl))
3544 /* Recognize the temporary created for a return value with variable
3545 size in Call_to_gnu. We want to eliminate it if possible. */
3546 if (TREE_CODE (ret_val) == COMPOUND_EXPR
3547 && TREE_CODE (TREE_OPERAND (ret_val, 0)) == INIT_EXPR
3548 && TREE_OPERAND (TREE_OPERAND (ret_val, 0), 0)
3549 == TREE_OPERAND (ret_val, 1))
3550 ret_val = TREE_OPERAND (ret_val, 1);
3552 /* Strip useless conversions around the return value. */
3553 if (gnat_useless_type_conversion (ret_val))
3554 ret_val = TREE_OPERAND (ret_val, 0);
3556 /* Now apply the test to the return value. */
3557 if (return_value_ok_for_nrv_p (ret_obj, ret_val))
3559 if (!f_named_ret_val)
3560 f_named_ret_val = BITMAP_GGC_ALLOC ();
3561 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
3564 /* Note that we need not care about CONSTRUCTORs here, as they are
3565 totally transparent given the read-compose-write semantics of
3566 assignments from CONSTRUCTORs. */
3567 else if (EXPR_P (ret_val))
3568 vec_safe_push (f_other_ret_val, ret_val);
3571 else
3572 result_expr = ret_obj;
3574 return build1 (RETURN_EXPR, void_type_node, result_expr);
3577 /* Subroutine of gnat_to_gnu to process gnat_node, an N_Subprogram_Body. We
3578 don't return anything. */
3580 static void
3581 Subprogram_Body_to_gnu (Node_Id gnat_node)
3583 /* Defining identifier of a parameter to the subprogram. */
3584 Entity_Id gnat_param;
3585 /* The defining identifier for the subprogram body. Note that if a
3586 specification has appeared before for this body, then the identifier
3587 occurring in that specification will also be a defining identifier and all
3588 the calls to this subprogram will point to that specification. */
3589 Entity_Id gnat_subprog_id
3590 = (Present (Corresponding_Spec (gnat_node))
3591 ? Corresponding_Spec (gnat_node) : Defining_Entity (gnat_node));
3592 /* The FUNCTION_DECL node corresponding to the subprogram spec. */
3593 tree gnu_subprog_decl;
3594 /* Its RESULT_DECL node. */
3595 tree gnu_result_decl;
3596 /* Its FUNCTION_TYPE node. */
3597 tree gnu_subprog_type;
3598 /* The TYPE_CI_CO_LIST of its FUNCTION_TYPE node, if any. */
3599 tree gnu_cico_list;
3600 /* The entry in the CI_CO_LIST that represents a function return, if any. */
3601 tree gnu_return_var_elmt = NULL_TREE;
3602 tree gnu_result;
3603 location_t locus;
3604 struct language_function *gnu_subprog_language;
3605 vec<parm_attr, va_gc> *cache;
3607 /* If this is a generic object or if it has been eliminated,
3608 ignore it. */
3609 if (Ekind (gnat_subprog_id) == E_Generic_Procedure
3610 || Ekind (gnat_subprog_id) == E_Generic_Function
3611 || Is_Eliminated (gnat_subprog_id))
3612 return;
3614 /* If this subprogram acts as its own spec, define it. Otherwise, just get
3615 the already-elaborated tree node. However, if this subprogram had its
3616 elaboration deferred, we will already have made a tree node for it. So
3617 treat it as not being defined in that case. Such a subprogram cannot
3618 have an address clause or a freeze node, so this test is safe, though it
3619 does disable some otherwise-useful error checking. */
3620 gnu_subprog_decl
3621 = gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE,
3622 Acts_As_Spec (gnat_node)
3623 && !present_gnu_tree (gnat_subprog_id));
3624 gnu_result_decl = DECL_RESULT (gnu_subprog_decl);
3625 gnu_subprog_type = TREE_TYPE (gnu_subprog_decl);
3626 gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
3627 if (gnu_cico_list && TREE_VALUE (gnu_cico_list) == void_type_node)
3628 gnu_return_var_elmt = gnu_cico_list;
3630 /* If the function returns by invisible reference, make it explicit in the
3631 function body. See gnat_to_gnu_entity, E_Subprogram_Type case. */
3632 if (TREE_ADDRESSABLE (gnu_subprog_type))
3634 TREE_TYPE (gnu_result_decl)
3635 = build_reference_type (TREE_TYPE (gnu_result_decl));
3636 relayout_decl (gnu_result_decl);
3639 /* Set the line number in the decl to correspond to that of the body. */
3640 Sloc_to_locus (Sloc (gnat_node), &locus);
3641 DECL_SOURCE_LOCATION (gnu_subprog_decl) = locus;
3643 /* Initialize the information structure for the function. */
3644 allocate_struct_function (gnu_subprog_decl, false);
3645 gnu_subprog_language = ggc_cleared_alloc<language_function> ();
3646 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->language = gnu_subprog_language;
3647 DECL_STRUCT_FUNCTION (gnu_subprog_decl)->function_start_locus = locus;
3648 set_cfun (NULL);
3650 begin_subprog_body (gnu_subprog_decl);
3652 /* If there are copy-in/copy-out parameters, we need to ensure that they are
3653 properly copied out by the return statement. We do this by making a new
3654 block and converting any return into a goto to a label at the end of the
3655 block. */
3656 if (gnu_cico_list)
3658 tree gnu_return_var = NULL_TREE;
3660 vec_safe_push (gnu_return_label_stack,
3661 create_artificial_label (input_location));
3663 start_stmt_group ();
3664 gnat_pushlevel ();
3666 /* If this is a function with copy-in/copy-out parameters and which does
3667 not return by invisible reference, we also need a variable for the
3668 return value to be placed. */
3669 if (gnu_return_var_elmt && !TREE_ADDRESSABLE (gnu_subprog_type))
3671 tree gnu_return_type
3672 = TREE_TYPE (TREE_PURPOSE (gnu_return_var_elmt));
3674 gnu_return_var
3675 = create_var_decl (get_identifier ("RETVAL"), NULL_TREE,
3676 gnu_return_type, NULL_TREE, false, false,
3677 false, false, NULL, gnat_subprog_id);
3678 TREE_VALUE (gnu_return_var_elmt) = gnu_return_var;
3681 vec_safe_push (gnu_return_var_stack, gnu_return_var);
3683 /* See whether there are parameters for which we don't have a GCC tree
3684 yet. These must be Out parameters. Make a VAR_DECL for them and
3685 put it into TYPE_CI_CO_LIST, which must contain an empty entry too.
3686 We can match up the entries because TYPE_CI_CO_LIST is in the order
3687 of the parameters. */
3688 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3689 Present (gnat_param);
3690 gnat_param = Next_Formal_With_Extras (gnat_param))
3691 if (!present_gnu_tree (gnat_param))
3693 tree gnu_cico_entry = gnu_cico_list;
3694 tree gnu_decl;
3696 /* Skip any entries that have been already filled in; they must
3697 correspond to In Out parameters. */
3698 while (gnu_cico_entry && TREE_VALUE (gnu_cico_entry))
3699 gnu_cico_entry = TREE_CHAIN (gnu_cico_entry);
3701 /* Do any needed dereferences for by-ref objects. */
3702 gnu_decl = gnat_to_gnu_entity (gnat_param, NULL_TREE, 1);
3703 gcc_assert (DECL_P (gnu_decl));
3704 if (DECL_BY_REF_P (gnu_decl))
3705 gnu_decl = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_decl);
3707 /* Do any needed references for padded types. */
3708 TREE_VALUE (gnu_cico_entry)
3709 = convert (TREE_TYPE (TREE_PURPOSE (gnu_cico_entry)), gnu_decl);
3712 else
3713 vec_safe_push (gnu_return_label_stack, NULL_TREE);
3715 /* Get a tree corresponding to the code for the subprogram. */
3716 start_stmt_group ();
3717 gnat_pushlevel ();
3719 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
3721 /* Generate the code of the subprogram itself. A return statement will be
3722 present and any Out parameters will be handled there. */
3723 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
3724 gnat_poplevel ();
3725 gnu_result = end_stmt_group ();
3727 /* If we populated the parameter attributes cache, we need to make sure that
3728 the cached expressions are evaluated on all the possible paths leading to
3729 their uses. So we force their evaluation on entry of the function. */
3730 cache = gnu_subprog_language->parm_attr_cache;
3731 if (cache)
3733 struct parm_attr_d *pa;
3734 int i;
3736 start_stmt_group ();
3738 FOR_EACH_VEC_ELT (*cache, i, pa)
3740 if (pa->first)
3741 add_stmt_with_node_force (pa->first, gnat_node);
3742 if (pa->last)
3743 add_stmt_with_node_force (pa->last, gnat_node);
3744 if (pa->length)
3745 add_stmt_with_node_force (pa->length, gnat_node);
3748 add_stmt (gnu_result);
3749 gnu_result = end_stmt_group ();
3751 gnu_subprog_language->parm_attr_cache = NULL;
3754 /* If we are dealing with a return from an Ada procedure with parameters
3755 passed by copy-in/copy-out, we need to return a record containing the
3756 final values of these parameters. If the list contains only one entry,
3757 return just that entry though.
3759 For a full description of the copy-in/copy-out parameter mechanism, see
3760 the part of the gnat_to_gnu_entity routine dealing with the translation
3761 of subprograms.
3763 We need to make a block that contains the definition of that label and
3764 the copying of the return value. It first contains the function, then
3765 the label and copy statement. */
3766 if (gnu_cico_list)
3768 const Node_Id gnat_end_label
3769 = End_Label (Handled_Statement_Sequence (gnat_node));
3771 gnu_return_var_stack->pop ();
3773 add_stmt (gnu_result);
3774 add_stmt (build1 (LABEL_EXPR, void_type_node,
3775 gnu_return_label_stack->last ()));
3777 /* If this is a function which returns by invisible reference, the
3778 return value has already been dealt with at the return statements,
3779 so we only need to indirectly copy out the parameters. */
3780 if (TREE_ADDRESSABLE (gnu_subprog_type))
3782 tree gnu_ret_deref
3783 = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result_decl);
3784 tree t;
3786 gcc_assert (TREE_VALUE (gnu_cico_list) == void_type_node);
3788 for (t = TREE_CHAIN (gnu_cico_list); t; t = TREE_CHAIN (t))
3790 tree gnu_field_deref
3791 = build_component_ref (gnu_ret_deref, NULL_TREE,
3792 TREE_PURPOSE (t), true);
3793 gnu_result = build2 (MODIFY_EXPR, void_type_node,
3794 gnu_field_deref, TREE_VALUE (t));
3795 add_stmt_with_node (gnu_result, gnat_end_label);
3799 /* Otherwise, if this is a procedure or a function which does not return
3800 by invisible reference, we can do a direct block-copy out. */
3801 else
3803 tree gnu_retval;
3805 if (list_length (gnu_cico_list) == 1)
3806 gnu_retval = TREE_VALUE (gnu_cico_list);
3807 else
3808 gnu_retval
3809 = build_constructor_from_list (TREE_TYPE (gnu_subprog_type),
3810 gnu_cico_list);
3812 gnu_result = build_return_expr (gnu_result_decl, gnu_retval);
3813 add_stmt_with_node (gnu_result, gnat_end_label);
3816 gnat_poplevel ();
3817 gnu_result = end_stmt_group ();
3820 gnu_return_label_stack->pop ();
3822 /* Attempt setting the end_locus of our GCC body tree, typically a
3823 BIND_EXPR or STATEMENT_LIST, then the end_locus of our GCC subprogram
3824 declaration tree. */
3825 set_end_locus_from_node (gnu_result, gnat_node);
3826 set_end_locus_from_node (gnu_subprog_decl, gnat_node);
3828 /* On SEH targets, install an exception handler around the main entry
3829 point to catch unhandled exceptions. */
3830 if (DECL_NAME (gnu_subprog_decl) == main_identifier_node
3831 && targetm_common.except_unwind_info (&global_options) == UI_SEH)
3833 tree t;
3834 tree etype;
3836 t = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
3837 1, integer_zero_node);
3838 t = build_call_n_expr (unhandled_except_decl, 1, t);
3840 etype = build_unary_op (ADDR_EXPR, NULL_TREE, unhandled_others_decl);
3841 etype = tree_cons (NULL_TREE, etype, NULL_TREE);
3843 t = build2 (CATCH_EXPR, void_type_node, etype, t);
3844 gnu_result = build2 (TRY_CATCH_EXPR, TREE_TYPE (gnu_result),
3845 gnu_result, t);
3848 end_subprog_body (gnu_result);
3850 /* Finally annotate the parameters and disconnect the trees for parameters
3851 that we have turned into variables since they are now unusable. */
3852 for (gnat_param = First_Formal_With_Extras (gnat_subprog_id);
3853 Present (gnat_param);
3854 gnat_param = Next_Formal_With_Extras (gnat_param))
3856 tree gnu_param = get_gnu_tree (gnat_param);
3857 bool is_var_decl = (TREE_CODE (gnu_param) == VAR_DECL);
3859 annotate_object (gnat_param, TREE_TYPE (gnu_param), NULL_TREE,
3860 DECL_BY_REF_P (gnu_param));
3862 if (is_var_decl)
3863 save_gnu_tree (gnat_param, NULL_TREE, false);
3866 /* Disconnect the variable created for the return value. */
3867 if (gnu_return_var_elmt)
3868 TREE_VALUE (gnu_return_var_elmt) = void_type_node;
3870 /* If the function returns an aggregate type and we have candidates for
3871 a Named Return Value, finalize the optimization. */
3872 if (optimize && gnu_subprog_language->named_ret_val)
3874 finalize_nrv (gnu_subprog_decl,
3875 gnu_subprog_language->named_ret_val,
3876 gnu_subprog_language->other_ret_val,
3877 gnu_subprog_language->gnat_ret);
3878 gnu_subprog_language->named_ret_val = NULL;
3879 gnu_subprog_language->other_ret_val = NULL;
3882 /* If this is an inlined external function that has been marked uninlinable,
3883 drop the body and stop there. Otherwise compile the body. */
3884 if (DECL_EXTERNAL (gnu_subprog_decl) && DECL_UNINLINABLE (gnu_subprog_decl))
3885 DECL_SAVED_TREE (gnu_subprog_decl) = NULL_TREE;
3886 else
3887 rest_of_subprog_body_compilation (gnu_subprog_decl);
3890 /* Return true if GNAT_NODE requires atomic synchronization. */
3892 static bool
3893 atomic_sync_required_p (Node_Id gnat_node)
3895 const Node_Id gnat_parent = Parent (gnat_node);
3896 Node_Kind kind;
3897 unsigned char attr_id;
3899 /* First, scan the node to find the Atomic_Sync_Required flag. */
3900 kind = Nkind (gnat_node);
3901 if (kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
3903 gnat_node = Expression (gnat_node);
3904 kind = Nkind (gnat_node);
3907 switch (kind)
3909 case N_Expanded_Name:
3910 case N_Explicit_Dereference:
3911 case N_Identifier:
3912 case N_Indexed_Component:
3913 case N_Selected_Component:
3914 if (!Atomic_Sync_Required (gnat_node))
3915 return false;
3916 break;
3918 default:
3919 return false;
3922 /* Then, scan the parent to find out cases where the flag is irrelevant. */
3923 kind = Nkind (gnat_parent);
3924 switch (kind)
3926 case N_Attribute_Reference:
3927 attr_id = Get_Attribute_Id (Attribute_Name (gnat_parent));
3928 /* Do not mess up machine code insertions. */
3929 if (attr_id == Attr_Asm_Input || attr_id == Attr_Asm_Output)
3930 return false;
3931 break;
3933 case N_Object_Renaming_Declaration:
3934 /* Do not generate a function call as a renamed object. */
3935 return false;
3937 default:
3938 break;
3941 return true;
3944 /* Create a temporary variable with PREFIX and TYPE, and return it. */
3946 static tree
3947 create_temporary (const char *prefix, tree type)
3949 tree gnu_temp = create_var_decl (create_tmp_var_name (prefix), NULL_TREE,
3950 type, NULL_TREE, false, false, false, false,
3951 NULL, Empty);
3952 DECL_ARTIFICIAL (gnu_temp) = 1;
3953 DECL_IGNORED_P (gnu_temp) = 1;
3955 return gnu_temp;
3958 /* Create a temporary variable with PREFIX and initialize it with GNU_INIT.
3959 Put the initialization statement into GNU_INIT_STMT and annotate it with
3960 the SLOC of GNAT_NODE. Return the temporary variable. */
3962 static tree
3963 create_init_temporary (const char *prefix, tree gnu_init, tree *gnu_init_stmt,
3964 Node_Id gnat_node)
3966 tree gnu_temp = create_temporary (prefix, TREE_TYPE (gnu_init));
3968 *gnu_init_stmt = build_binary_op (INIT_EXPR, NULL_TREE, gnu_temp, gnu_init);
3969 set_expr_location_from_node (*gnu_init_stmt, gnat_node);
3971 return gnu_temp;
3974 /* Subroutine of gnat_to_gnu to translate gnat_node, either an N_Function_Call
3975 or an N_Procedure_Call_Statement, to a GCC tree, which is returned.
3976 GNU_RESULT_TYPE_P is a pointer to where we should place the result type.
3977 If GNU_TARGET is non-null, this must be a function call on the RHS of a
3978 N_Assignment_Statement and the result is to be placed into that object.
3979 If, in addition, ATOMIC_SYNC is true, then the assignment to GNU_TARGET
3980 requires atomic synchronization. */
3982 static tree
3983 Call_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p, tree gnu_target,
3984 bool atomic_sync)
3986 const bool function_call = (Nkind (gnat_node) == N_Function_Call);
3987 const bool returning_value = (function_call && !gnu_target);
3988 /* The GCC node corresponding to the GNAT subprogram name. This can either
3989 be a FUNCTION_DECL node if we are dealing with a standard subprogram call,
3990 or an indirect reference expression (an INDIRECT_REF node) pointing to a
3991 subprogram. */
3992 tree gnu_subprog = gnat_to_gnu (Name (gnat_node));
3993 /* The FUNCTION_TYPE node giving the GCC type of the subprogram. */
3994 tree gnu_subprog_type = TREE_TYPE (gnu_subprog);
3995 /* The return type of the FUNCTION_TYPE. */
3996 tree gnu_result_type = TREE_TYPE (gnu_subprog_type);
3997 tree gnu_subprog_addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_subprog);
3998 vec<tree, va_gc> *gnu_actual_vec = NULL;
3999 tree gnu_name_list = NULL_TREE;
4000 tree gnu_stmt_list = NULL_TREE;
4001 tree gnu_after_list = NULL_TREE;
4002 tree gnu_retval = NULL_TREE;
4003 tree gnu_call, gnu_result;
4004 bool went_into_elab_proc = false;
4005 bool pushed_binding_level = false;
4006 Entity_Id gnat_formal;
4007 Node_Id gnat_actual;
4009 gcc_assert (TREE_CODE (gnu_subprog_type) == FUNCTION_TYPE);
4011 /* If we are calling a stubbed function, raise Program_Error, but Elaborate
4012 all our args first. */
4013 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL && DECL_STUBBED_P (gnu_subprog))
4015 tree call_expr = build_call_raise (PE_Stubbed_Subprogram_Called,
4016 gnat_node, N_Raise_Program_Error);
4018 for (gnat_actual = First_Actual (gnat_node);
4019 Present (gnat_actual);
4020 gnat_actual = Next_Actual (gnat_actual))
4021 add_stmt (gnat_to_gnu (gnat_actual));
4023 if (returning_value)
4025 *gnu_result_type_p = gnu_result_type;
4026 return build1 (NULL_EXPR, gnu_result_type, call_expr);
4029 return call_expr;
4032 /* For a call to a nested function, check the inlining status. */
4033 if (TREE_CODE (gnu_subprog) == FUNCTION_DECL
4034 && decl_function_context (gnu_subprog))
4035 check_inlining_for_nested_subprog (gnu_subprog);
4037 /* The only way we can be making a call via an access type is if Name is an
4038 explicit dereference. In that case, get the list of formal args from the
4039 type the access type is pointing to. Otherwise, get the formals from the
4040 entity being called. */
4041 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
4042 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
4043 else if (Nkind (Name (gnat_node)) == N_Attribute_Reference)
4044 /* Assume here that this must be 'Elab_Body or 'Elab_Spec. */
4045 gnat_formal = Empty;
4046 else
4047 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
4049 /* The lifetime of the temporaries created for the call ends right after the
4050 return value is copied, so we can give them the scope of the elaboration
4051 routine at top level. */
4052 if (!current_function_decl)
4054 current_function_decl = get_elaboration_procedure ();
4055 went_into_elab_proc = true;
4058 /* First, create the temporary for the return value when:
4060 1. There is no target and the function has copy-in/copy-out parameters,
4061 because we need to preserve the return value before copying back the
4062 parameters.
4064 2. There is no target and this is not an object declaration, and the
4065 return type has variable size, because in these cases the gimplifier
4066 cannot create the temporary.
4068 3. There is a target and it is a slice or an array with fixed size,
4069 and the return type has variable size, because the gimplifier
4070 doesn't handle these cases.
4072 This must be done before we push a binding level around the call, since
4073 we will pop it before copying the return value. */
4074 if (function_call
4075 && ((!gnu_target && TYPE_CI_CO_LIST (gnu_subprog_type))
4076 || (!gnu_target
4077 && Nkind (Parent (gnat_node)) != N_Object_Declaration
4078 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)
4079 || (gnu_target
4080 && (TREE_CODE (gnu_target) == ARRAY_RANGE_REF
4081 || (TREE_CODE (TREE_TYPE (gnu_target)) == ARRAY_TYPE
4082 && TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_target)))
4083 == INTEGER_CST))
4084 && TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST)))
4085 gnu_retval = create_temporary ("R", gnu_result_type);
4087 /* Create the list of the actual parameters as GCC expects it, namely a
4088 chain of TREE_LIST nodes in which the TREE_VALUE field of each node
4089 is an expression and the TREE_PURPOSE field is null. But skip Out
4090 parameters not passed by reference and that need not be copied in. */
4091 for (gnat_actual = First_Actual (gnat_node);
4092 Present (gnat_actual);
4093 gnat_formal = Next_Formal_With_Extras (gnat_formal),
4094 gnat_actual = Next_Actual (gnat_actual))
4096 Entity_Id gnat_formal_type = Etype (gnat_formal);
4097 tree gnu_formal = present_gnu_tree (gnat_formal)
4098 ? get_gnu_tree (gnat_formal) : NULL_TREE;
4099 tree gnu_formal_type = gnat_to_gnu_type (gnat_formal_type);
4100 const bool is_true_formal_parm
4101 = gnu_formal && TREE_CODE (gnu_formal) == PARM_DECL;
4102 const bool is_by_ref_formal_parm
4103 = is_true_formal_parm
4104 && (DECL_BY_REF_P (gnu_formal)
4105 || DECL_BY_COMPONENT_PTR_P (gnu_formal));
4106 /* In the Out or In Out case, we must suppress conversions that yield
4107 an lvalue but can nevertheless cause the creation of a temporary,
4108 because we need the real object in this case, either to pass its
4109 address if it's passed by reference or as target of the back copy
4110 done after the call if it uses the copy-in/copy-out mechanism.
4111 We do it in the In case too, except for an unchecked conversion
4112 to an elementary type or a constrained composite type because it
4113 alone can cause the actual to be misaligned and the addressability
4114 test is applied to the real object. */
4115 const bool suppress_type_conversion
4116 = ((Nkind (gnat_actual) == N_Unchecked_Type_Conversion
4117 && (Ekind (gnat_formal) != E_In_Parameter
4118 || (Is_Composite_Type (Underlying_Type (gnat_formal_type))
4119 && !Is_Constrained (Underlying_Type (gnat_formal_type)))))
4120 || (Nkind (gnat_actual) == N_Type_Conversion
4121 && Is_Composite_Type (Underlying_Type (gnat_formal_type))));
4122 Node_Id gnat_name = suppress_type_conversion
4123 ? Expression (gnat_actual) : gnat_actual;
4124 tree gnu_name = gnat_to_gnu (gnat_name), gnu_name_type;
4125 tree gnu_actual;
4127 /* If it's possible we may need to use this expression twice, make sure
4128 that any side-effects are handled via SAVE_EXPRs; likewise if we need
4129 to force side-effects before the call.
4130 ??? This is more conservative than we need since we don't need to do
4131 this for pass-by-ref with no conversion. */
4132 if (Ekind (gnat_formal) != E_In_Parameter)
4133 gnu_name = gnat_stabilize_reference (gnu_name, true, NULL);
4135 /* If we are passing a non-addressable parameter by reference, pass the
4136 address of a copy. In the Out or In Out case, set up to copy back
4137 out after the call. */
4138 if (is_by_ref_formal_parm
4139 && (gnu_name_type = gnat_to_gnu_type (Etype (gnat_name)))
4140 && !addressable_p (gnu_name, gnu_name_type))
4142 bool in_param = (Ekind (gnat_formal) == E_In_Parameter);
4143 tree gnu_orig = gnu_name, gnu_temp, gnu_stmt;
4145 /* Do not issue warnings for CONSTRUCTORs since this is not a copy
4146 but sort of an instantiation for them. */
4147 if (TREE_CODE (gnu_name) == CONSTRUCTOR)
4150 /* If the type is passed by reference, a copy is not allowed. */
4151 else if (TYPE_IS_BY_REFERENCE_P (gnu_formal_type))
4152 post_error ("misaligned actual cannot be passed by reference",
4153 gnat_actual);
4155 /* For users of Starlet we issue a warning because the interface
4156 apparently assumes that by-ref parameters outlive the procedure
4157 invocation. The code still will not work as intended, but we
4158 cannot do much better since low-level parts of the back-end
4159 would allocate temporaries at will because of the misalignment
4160 if we did not do so here. */
4161 else if (Is_Valued_Procedure (Entity (Name (gnat_node))))
4163 post_error
4164 ("?possible violation of implicit assumption", gnat_actual);
4165 post_error_ne
4166 ("?made by pragma Import_Valued_Procedure on &", gnat_actual,
4167 Entity (Name (gnat_node)));
4168 post_error_ne ("?because of misalignment of &", gnat_actual,
4169 gnat_formal);
4172 /* If the actual type of the object is already the nominal type,
4173 we have nothing to do, except if the size is self-referential
4174 in which case we'll remove the unpadding below. */
4175 if (TREE_TYPE (gnu_name) == gnu_name_type
4176 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_name_type)))
4179 /* Otherwise remove the unpadding from all the objects. */
4180 else if (TREE_CODE (gnu_name) == COMPONENT_REF
4181 && TYPE_IS_PADDING_P
4182 (TREE_TYPE (TREE_OPERAND (gnu_name, 0))))
4183 gnu_orig = gnu_name = TREE_OPERAND (gnu_name, 0);
4185 /* Otherwise convert to the nominal type of the object if needed.
4186 There are several cases in which we need to make the temporary
4187 using this type instead of the actual type of the object when
4188 they are distinct, because the expectations of the callee would
4189 otherwise not be met:
4190 - if it's a justified modular type,
4191 - if the actual type is a smaller form of it,
4192 - if it's a smaller form of the actual type. */
4193 else if ((TREE_CODE (gnu_name_type) == RECORD_TYPE
4194 && (TYPE_JUSTIFIED_MODULAR_P (gnu_name_type)
4195 || smaller_form_type_p (TREE_TYPE (gnu_name),
4196 gnu_name_type)))
4197 || (INTEGRAL_TYPE_P (gnu_name_type)
4198 && smaller_form_type_p (gnu_name_type,
4199 TREE_TYPE (gnu_name))))
4200 gnu_name = convert (gnu_name_type, gnu_name);
4202 /* If this is an In Out or Out parameter and we're returning a value,
4203 we need to create a temporary for the return value because we must
4204 preserve it before copying back at the very end. */
4205 if (!in_param && returning_value && !gnu_retval)
4206 gnu_retval = create_temporary ("R", gnu_result_type);
4208 /* If we haven't pushed a binding level, push a new one. This will
4209 narrow the lifetime of the temporary we are about to make as much
4210 as possible. The drawback is that we'd need to create a temporary
4211 for the return value, if any (see comment before the loop). So do
4212 it only when this temporary was already created just above. */
4213 if (!pushed_binding_level && !(in_param && returning_value))
4215 start_stmt_group ();
4216 gnat_pushlevel ();
4217 pushed_binding_level = true;
4220 /* Create an explicit temporary holding the copy. */
4221 gnu_temp
4222 = create_init_temporary ("A", gnu_name, &gnu_stmt, gnat_actual);
4224 /* But initialize it on the fly like for an implicit temporary as
4225 we aren't necessarily having a statement list. */
4226 gnu_name = build_compound_expr (TREE_TYPE (gnu_name), gnu_stmt,
4227 gnu_temp);
4229 /* Set up to move the copy back to the original if needed. */
4230 if (!in_param)
4232 /* If the original is a COND_EXPR whose first arm isn't meant to
4233 be further used, just deal with the second arm. This is very
4234 likely the conditional expression built for a check. */
4235 if (TREE_CODE (gnu_orig) == COND_EXPR
4236 && TREE_CODE (TREE_OPERAND (gnu_orig, 1)) == COMPOUND_EXPR
4237 && integer_zerop
4238 (TREE_OPERAND (TREE_OPERAND (gnu_orig, 1), 1)))
4239 gnu_orig = TREE_OPERAND (gnu_orig, 2);
4241 gnu_stmt
4242 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_orig, gnu_temp);
4243 set_expr_location_from_node (gnu_stmt, gnat_node);
4245 append_to_statement_list (gnu_stmt, &gnu_after_list);
4249 /* Start from the real object and build the actual. */
4250 gnu_actual = gnu_name;
4252 /* If this is an atomic access of an In or In Out parameter for which
4253 synchronization is required, build the atomic load. */
4254 if (is_true_formal_parm
4255 && !is_by_ref_formal_parm
4256 && Ekind (gnat_formal) != E_Out_Parameter
4257 && atomic_sync_required_p (gnat_actual))
4258 gnu_actual = build_atomic_load (gnu_actual);
4260 /* If this was a procedure call, we may not have removed any padding.
4261 So do it here for the part we will use as an input, if any. */
4262 if (Ekind (gnat_formal) != E_Out_Parameter
4263 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4264 gnu_actual
4265 = convert (get_unpadded_type (Etype (gnat_actual)), gnu_actual);
4267 /* Put back the conversion we suppressed above in the computation of the
4268 real object. And even if we didn't suppress any conversion there, we
4269 may have suppressed a conversion to the Etype of the actual earlier,
4270 since the parent is a procedure call, so put it back here. */
4271 if (suppress_type_conversion
4272 && Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4273 gnu_actual
4274 = unchecked_convert (gnat_to_gnu_type (Etype (gnat_actual)),
4275 gnu_actual, No_Truncation (gnat_actual));
4276 else
4277 gnu_actual
4278 = convert (gnat_to_gnu_type (Etype (gnat_actual)), gnu_actual);
4280 /* Make sure that the actual is in range of the formal's type. */
4281 if (Ekind (gnat_formal) != E_Out_Parameter
4282 && Do_Range_Check (gnat_actual))
4283 gnu_actual
4284 = emit_range_check (gnu_actual, gnat_formal_type, gnat_actual);
4286 /* Unless this is an In parameter, we must remove any justified modular
4287 building from GNU_NAME to get an lvalue. */
4288 if (Ekind (gnat_formal) != E_In_Parameter
4289 && TREE_CODE (gnu_name) == CONSTRUCTOR
4290 && TREE_CODE (TREE_TYPE (gnu_name)) == RECORD_TYPE
4291 && TYPE_JUSTIFIED_MODULAR_P (TREE_TYPE (gnu_name)))
4292 gnu_name
4293 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_name))), gnu_name);
4295 /* First see if the parameter is passed by reference. */
4296 if (is_true_formal_parm && DECL_BY_REF_P (gnu_formal))
4298 if (Ekind (gnat_formal) != E_In_Parameter)
4300 /* In Out or Out parameters passed by reference don't use the
4301 copy-in/copy-out mechanism so the address of the real object
4302 must be passed to the function. */
4303 gnu_actual = gnu_name;
4305 /* If we have a padded type, be sure we've removed padding. */
4306 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_actual)))
4307 gnu_actual = convert (get_unpadded_type (Etype (gnat_actual)),
4308 gnu_actual);
4310 /* If we have the constructed subtype of an aliased object
4311 with an unconstrained nominal subtype, the type of the
4312 actual includes the template, although it is formally
4313 constrained. So we need to convert it back to the real
4314 constructed subtype to retrieve the constrained part
4315 and takes its address. */
4316 if (TREE_CODE (TREE_TYPE (gnu_actual)) == RECORD_TYPE
4317 && TYPE_CONTAINS_TEMPLATE_P (TREE_TYPE (gnu_actual))
4318 && Is_Constr_Subt_For_UN_Aliased (Etype (gnat_actual))
4319 && Is_Array_Type (Underlying_Type (Etype (gnat_actual))))
4320 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
4321 gnu_actual);
4324 /* There is no need to convert the actual to the formal's type before
4325 taking its address. The only exception is for unconstrained array
4326 types because of the way we build fat pointers. */
4327 if (TREE_CODE (gnu_formal_type) == UNCONSTRAINED_ARRAY_TYPE)
4329 /* Put back a view conversion for In Out or Out parameters. */
4330 if (Ekind (gnat_formal) != E_In_Parameter)
4331 gnu_actual = convert (gnat_to_gnu_type (Etype (gnat_actual)),
4332 gnu_actual);
4333 gnu_actual = convert (gnu_formal_type, gnu_actual);
4336 /* The symmetry of the paths to the type of an entity is broken here
4337 since arguments don't know that they will be passed by ref. */
4338 gnu_formal_type = TREE_TYPE (gnu_formal);
4339 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4342 /* Then see if the parameter is an array passed to a foreign convention
4343 subprogram. */
4344 else if (is_true_formal_parm && DECL_BY_COMPONENT_PTR_P (gnu_formal))
4346 gnu_formal_type = TREE_TYPE (gnu_formal);
4347 gnu_actual = maybe_implicit_deref (gnu_actual);
4348 gnu_actual = maybe_unconstrained_array (gnu_actual);
4350 if (TYPE_IS_PADDING_P (gnu_formal_type))
4352 gnu_formal_type = TREE_TYPE (TYPE_FIELDS (gnu_formal_type));
4353 gnu_actual = convert (gnu_formal_type, gnu_actual);
4356 /* Take the address of the object and convert to the proper pointer
4357 type. We'd like to actually compute the address of the beginning
4358 of the array using an ADDR_EXPR of an ARRAY_REF, but there's a
4359 possibility that the ARRAY_REF might return a constant and we'd be
4360 getting the wrong address. Neither approach is exactly correct,
4361 but this is the most likely to work in all cases. */
4362 gnu_actual = build_unary_op (ADDR_EXPR, gnu_formal_type, gnu_actual);
4365 /* Otherwise the parameter is passed by copy. */
4366 else
4368 tree gnu_size;
4370 if (Ekind (gnat_formal) != E_In_Parameter)
4371 gnu_name_list = tree_cons (NULL_TREE, gnu_name, gnu_name_list);
4373 /* If we didn't create a PARM_DECL for the formal, this means that
4374 it is an Out parameter not passed by reference and that need not
4375 be copied in. In this case, the value of the actual need not be
4376 read. However, we still need to make sure that its side-effects
4377 are evaluated before the call, so we evaluate its address. */
4378 if (!is_true_formal_parm)
4380 if (TREE_SIDE_EFFECTS (gnu_name))
4382 tree addr = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_name);
4383 append_to_statement_list (addr, &gnu_stmt_list);
4385 continue;
4388 gnu_actual = convert (gnu_formal_type, gnu_actual);
4390 /* If this is 'Null_Parameter, pass a zero even though we are
4391 dereferencing it. */
4392 if (TREE_CODE (gnu_actual) == INDIRECT_REF
4393 && TREE_PRIVATE (gnu_actual)
4394 && (gnu_size = TYPE_SIZE (TREE_TYPE (gnu_actual)))
4395 && TREE_CODE (gnu_size) == INTEGER_CST
4396 && compare_tree_int (gnu_size, BITS_PER_WORD) <= 0)
4397 gnu_actual
4398 = unchecked_convert (DECL_ARG_TYPE (gnu_formal),
4399 convert (gnat_type_for_size
4400 (TREE_INT_CST_LOW (gnu_size), 1),
4401 integer_zero_node),
4402 false);
4403 else
4404 gnu_actual = convert (DECL_ARG_TYPE (gnu_formal), gnu_actual);
4407 vec_safe_push (gnu_actual_vec, gnu_actual);
4410 gnu_call
4411 = build_call_vec (gnu_result_type, gnu_subprog_addr, gnu_actual_vec);
4412 set_expr_location_from_node (gnu_call, gnat_node);
4414 /* If we have created a temporary for the return value, initialize it. */
4415 if (gnu_retval)
4417 tree gnu_stmt
4418 = build_binary_op (INIT_EXPR, NULL_TREE, gnu_retval, gnu_call);
4419 set_expr_location_from_node (gnu_stmt, gnat_node);
4420 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
4421 gnu_call = gnu_retval;
4424 /* If this is a subprogram with copy-in/copy-out parameters, we need to
4425 unpack the valued returned from the function into the In Out or Out
4426 parameters. We deal with the function return (if this is an Ada
4427 function) below. */
4428 if (TYPE_CI_CO_LIST (gnu_subprog_type))
4430 /* List of FIELD_DECLs associated with the PARM_DECLs of the copy-in/
4431 copy-out parameters. */
4432 tree gnu_cico_list = TYPE_CI_CO_LIST (gnu_subprog_type);
4433 const int length = list_length (gnu_cico_list);
4435 /* The call sequence must contain one and only one call, even though the
4436 function is pure. Save the result into a temporary if needed. */
4437 if (length > 1)
4439 if (!gnu_retval)
4441 tree gnu_stmt;
4442 /* If we haven't pushed a binding level, push a new one. This
4443 will narrow the lifetime of the temporary we are about to
4444 make as much as possible. */
4445 if (!pushed_binding_level)
4447 start_stmt_group ();
4448 gnat_pushlevel ();
4449 pushed_binding_level = true;
4451 gnu_call
4452 = create_init_temporary ("P", gnu_call, &gnu_stmt, gnat_node);
4453 append_to_statement_list (gnu_stmt, &gnu_stmt_list);
4456 gnu_name_list = nreverse (gnu_name_list);
4459 /* The first entry is for the actual return value if this is a
4460 function, so skip it. */
4461 if (function_call)
4462 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4464 if (Nkind (Name (gnat_node)) == N_Explicit_Dereference)
4465 gnat_formal = First_Formal_With_Extras (Etype (Name (gnat_node)));
4466 else
4467 gnat_formal = First_Formal_With_Extras (Entity (Name (gnat_node)));
4469 for (gnat_actual = First_Actual (gnat_node);
4470 Present (gnat_actual);
4471 gnat_formal = Next_Formal_With_Extras (gnat_formal),
4472 gnat_actual = Next_Actual (gnat_actual))
4473 /* If we are dealing with a copy-in/copy-out parameter, we must
4474 retrieve its value from the record returned in the call. */
4475 if (!(present_gnu_tree (gnat_formal)
4476 && TREE_CODE (get_gnu_tree (gnat_formal)) == PARM_DECL
4477 && (DECL_BY_REF_P (get_gnu_tree (gnat_formal))
4478 || DECL_BY_COMPONENT_PTR_P (get_gnu_tree (gnat_formal))))
4479 && Ekind (gnat_formal) != E_In_Parameter)
4481 /* Get the value to assign to this Out or In Out parameter. It is
4482 either the result of the function if there is only a single such
4483 parameter or the appropriate field from the record returned. */
4484 tree gnu_result
4485 = length == 1
4486 ? gnu_call
4487 : build_component_ref (gnu_call, NULL_TREE,
4488 TREE_PURPOSE (gnu_cico_list), false);
4490 /* If the actual is a conversion, get the inner expression, which
4491 will be the real destination, and convert the result to the
4492 type of the actual parameter. */
4493 tree gnu_actual
4494 = maybe_unconstrained_array (TREE_VALUE (gnu_name_list));
4496 /* If the result is a padded type, remove the padding. */
4497 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
4498 gnu_result
4499 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
4500 gnu_result);
4502 /* If the actual is a type conversion, the real target object is
4503 denoted by the inner Expression and we need to convert the
4504 result to the associated type.
4505 We also need to convert our gnu assignment target to this type
4506 if the corresponding GNU_NAME was constructed from the GNAT
4507 conversion node and not from the inner Expression. */
4508 if (Nkind (gnat_actual) == N_Type_Conversion)
4510 gnu_result
4511 = convert_with_check
4512 (Etype (Expression (gnat_actual)), gnu_result,
4513 Do_Overflow_Check (gnat_actual),
4514 Do_Range_Check (Expression (gnat_actual)),
4515 Float_Truncate (gnat_actual), gnat_actual);
4517 if (!Is_Composite_Type (Underlying_Type (Etype (gnat_formal))))
4518 gnu_actual = convert (TREE_TYPE (gnu_result), gnu_actual);
4521 /* Unchecked conversions as actuals for Out parameters are not
4522 allowed in user code because they are not variables, but do
4523 occur in front-end expansions. The associated GNU_NAME is
4524 always obtained from the inner expression in such cases. */
4525 else if (Nkind (gnat_actual) == N_Unchecked_Type_Conversion)
4526 gnu_result = unchecked_convert (TREE_TYPE (gnu_actual),
4527 gnu_result,
4528 No_Truncation (gnat_actual));
4529 else
4531 if (Do_Range_Check (gnat_actual))
4532 gnu_result
4533 = emit_range_check (gnu_result, Etype (gnat_actual),
4534 gnat_actual);
4536 if (!(!TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_actual)))
4537 && TREE_CONSTANT (TYPE_SIZE (TREE_TYPE (gnu_result)))))
4538 gnu_result = convert (TREE_TYPE (gnu_actual), gnu_result);
4541 if (atomic_sync_required_p (gnat_actual))
4542 gnu_result = build_atomic_store (gnu_actual, gnu_result);
4543 else
4544 gnu_result = build_binary_op (MODIFY_EXPR, NULL_TREE,
4545 gnu_actual, gnu_result);
4546 set_expr_location_from_node (gnu_result, gnat_node);
4547 append_to_statement_list (gnu_result, &gnu_stmt_list);
4548 gnu_cico_list = TREE_CHAIN (gnu_cico_list);
4549 gnu_name_list = TREE_CHAIN (gnu_name_list);
4553 /* If this is a function call, the result is the call expression unless a
4554 target is specified, in which case we copy the result into the target
4555 and return the assignment statement. */
4556 if (function_call)
4558 /* If this is a function with copy-in/copy-out parameters, extract the
4559 return value from it and update the return type. */
4560 if (TYPE_CI_CO_LIST (gnu_subprog_type))
4562 tree gnu_elmt = TYPE_CI_CO_LIST (gnu_subprog_type);
4563 gnu_call = build_component_ref (gnu_call, NULL_TREE,
4564 TREE_PURPOSE (gnu_elmt), false);
4565 gnu_result_type = TREE_TYPE (gnu_call);
4568 /* If the function returns an unconstrained array or by direct reference,
4569 we have to dereference the pointer. */
4570 if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type)
4571 || TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type))
4572 gnu_call = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_call);
4574 if (gnu_target)
4576 Node_Id gnat_parent = Parent (gnat_node);
4577 enum tree_code op_code;
4579 /* If range check is needed, emit code to generate it. */
4580 if (Do_Range_Check (gnat_node))
4581 gnu_call
4582 = emit_range_check (gnu_call, Etype (Name (gnat_parent)),
4583 gnat_parent);
4585 /* ??? If the return type has variable size, then force the return
4586 slot optimization as we would not be able to create a temporary.
4587 Likewise if it was unconstrained as we would copy too much data.
4588 That's what has been done historically. */
4589 if (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
4590 || (TYPE_IS_PADDING_P (gnu_result_type)
4591 && CONTAINS_PLACEHOLDER_P
4592 (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS (gnu_result_type))))))
4593 op_code = INIT_EXPR;
4594 else
4595 op_code = MODIFY_EXPR;
4597 if (atomic_sync)
4598 gnu_call = build_atomic_store (gnu_target, gnu_call);
4599 else
4600 gnu_call
4601 = build_binary_op (op_code, NULL_TREE, gnu_target, gnu_call);
4602 set_expr_location_from_node (gnu_call, gnat_parent);
4603 append_to_statement_list (gnu_call, &gnu_stmt_list);
4605 else
4606 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
4609 /* Otherwise, if this is a procedure call statement without copy-in/copy-out
4610 parameters, the result is just the call statement. */
4611 else if (!TYPE_CI_CO_LIST (gnu_subprog_type))
4612 append_to_statement_list (gnu_call, &gnu_stmt_list);
4614 /* Finally, add the copy back statements, if any. */
4615 append_to_statement_list (gnu_after_list, &gnu_stmt_list);
4617 if (went_into_elab_proc)
4618 current_function_decl = NULL_TREE;
4620 /* If we have pushed a binding level, pop it and finish up the enclosing
4621 statement group. */
4622 if (pushed_binding_level)
4624 add_stmt (gnu_stmt_list);
4625 gnat_poplevel ();
4626 gnu_result = end_stmt_group ();
4629 /* Otherwise, retrieve the statement list, if any. */
4630 else if (gnu_stmt_list)
4631 gnu_result = gnu_stmt_list;
4633 /* Otherwise, just return the call expression. */
4634 else
4635 return gnu_call;
4637 /* If we nevertheless need a value, make a COMPOUND_EXPR to return it.
4638 But first simplify if we have only one statement in the list. */
4639 if (returning_value)
4641 tree first = expr_first (gnu_result), last = expr_last (gnu_result);
4642 if (first == last)
4643 gnu_result = first;
4644 gnu_result
4645 = build_compound_expr (TREE_TYPE (gnu_call), gnu_result, gnu_call);
4648 return gnu_result;
4651 /* Subroutine of gnat_to_gnu to translate gnat_node, an
4652 N_Handled_Sequence_Of_Statements, to a GCC tree, which is returned. */
4654 static tree
4655 Handled_Sequence_Of_Statements_to_gnu (Node_Id gnat_node)
4657 tree gnu_jmpsave_decl = NULL_TREE;
4658 tree gnu_jmpbuf_decl = NULL_TREE;
4659 /* If just annotating, ignore all EH and cleanups. */
4660 bool gcc_zcx = (!type_annotate_only
4661 && Present (Exception_Handlers (gnat_node))
4662 && Exception_Mechanism == Back_End_Exceptions);
4663 bool setjmp_longjmp
4664 = (!type_annotate_only && Present (Exception_Handlers (gnat_node))
4665 && Exception_Mechanism == Setjmp_Longjmp);
4666 bool at_end = !type_annotate_only && Present (At_End_Proc (gnat_node));
4667 bool binding_for_block = (at_end || gcc_zcx || setjmp_longjmp);
4668 tree gnu_inner_block; /* The statement(s) for the block itself. */
4669 tree gnu_result;
4670 tree gnu_expr;
4671 Node_Id gnat_temp;
4672 /* Node providing the sloc for the cleanup actions. */
4673 Node_Id gnat_cleanup_loc_node = (Present (End_Label (gnat_node)) ?
4674 End_Label (gnat_node) :
4675 gnat_node);
4677 /* The GCC exception handling mechanism can handle both ZCX and SJLJ schemes
4678 and we have our own SJLJ mechanism. To call the GCC mechanism, we call
4679 add_cleanup, and when we leave the binding, end_stmt_group will create
4680 the TRY_FINALLY_EXPR.
4682 ??? The region level calls down there have been specifically put in place
4683 for a ZCX context and currently the order in which things are emitted
4684 (region/handlers) is different from the SJLJ case. Instead of putting
4685 other calls with different conditions at other places for the SJLJ case,
4686 it seems cleaner to reorder things for the SJLJ case and generalize the
4687 condition to make it not ZCX specific.
4689 If there are any exceptions or cleanup processing involved, we need an
4690 outer statement group (for Setjmp_Longjmp) and binding level. */
4691 if (binding_for_block)
4693 start_stmt_group ();
4694 gnat_pushlevel ();
4697 /* If using setjmp_longjmp, make the variables for the setjmp buffer and save
4698 area for address of previous buffer. Do this first since we need to have
4699 the setjmp buf known for any decls in this block. */
4700 if (setjmp_longjmp)
4702 gnu_jmpsave_decl
4703 = create_var_decl (get_identifier ("JMPBUF_SAVE"), NULL_TREE,
4704 jmpbuf_ptr_type,
4705 build_call_n_expr (get_jmpbuf_decl, 0),
4706 false, false, false, false, NULL, gnat_node);
4707 DECL_ARTIFICIAL (gnu_jmpsave_decl) = 1;
4709 /* The __builtin_setjmp receivers will immediately reinstall it. Now
4710 because of the unstructured form of EH used by setjmp_longjmp, there
4711 might be forward edges going to __builtin_setjmp receivers on which
4712 it is uninitialized, although they will never be actually taken. */
4713 TREE_NO_WARNING (gnu_jmpsave_decl) = 1;
4714 gnu_jmpbuf_decl
4715 = create_var_decl (get_identifier ("JMP_BUF"), NULL_TREE,
4716 jmpbuf_type,
4717 NULL_TREE,
4718 false, false, false, false, NULL, gnat_node);
4719 DECL_ARTIFICIAL (gnu_jmpbuf_decl) = 1;
4721 set_block_jmpbuf_decl (gnu_jmpbuf_decl);
4723 /* When we exit this block, restore the saved value. */
4724 add_cleanup (build_call_n_expr (set_jmpbuf_decl, 1, gnu_jmpsave_decl),
4725 gnat_cleanup_loc_node);
4728 /* If we are to call a function when exiting this block, add a cleanup
4729 to the binding level we made above. Note that add_cleanup is FIFO
4730 so we must register this cleanup after the EH cleanup just above. */
4731 if (at_end)
4732 add_cleanup (build_call_n_expr (gnat_to_gnu (At_End_Proc (gnat_node)), 0),
4733 gnat_cleanup_loc_node);
4735 /* Now build the tree for the declarations and statements inside this block.
4736 If this is SJLJ, set our jmp_buf as the current buffer. */
4737 start_stmt_group ();
4739 if (setjmp_longjmp)
4741 gnu_expr = build_call_n_expr (set_jmpbuf_decl, 1,
4742 build_unary_op (ADDR_EXPR, NULL_TREE,
4743 gnu_jmpbuf_decl));
4744 set_expr_location_from_node (gnu_expr, gnat_node);
4745 add_stmt (gnu_expr);
4748 if (Present (First_Real_Statement (gnat_node)))
4749 process_decls (Statements (gnat_node), Empty,
4750 First_Real_Statement (gnat_node), true, true);
4752 /* Generate code for each statement in the block. */
4753 for (gnat_temp = (Present (First_Real_Statement (gnat_node))
4754 ? First_Real_Statement (gnat_node)
4755 : First (Statements (gnat_node)));
4756 Present (gnat_temp); gnat_temp = Next (gnat_temp))
4757 add_stmt (gnat_to_gnu (gnat_temp));
4758 gnu_inner_block = end_stmt_group ();
4760 /* Now generate code for the two exception models, if either is relevant for
4761 this block. */
4762 if (setjmp_longjmp)
4764 tree *gnu_else_ptr = 0;
4765 tree gnu_handler;
4767 /* Make a binding level for the exception handling declarations and code
4768 and set up gnu_except_ptr_stack for the handlers to use. */
4769 start_stmt_group ();
4770 gnat_pushlevel ();
4772 vec_safe_push (gnu_except_ptr_stack,
4773 create_var_decl (get_identifier ("EXCEPT_PTR"), NULL_TREE,
4774 build_pointer_type (except_type_node),
4775 build_call_n_expr (get_excptr_decl, 0),
4776 false, false, false, false,
4777 NULL, gnat_node));
4779 /* Generate code for each handler. The N_Exception_Handler case does the
4780 real work and returns a COND_EXPR for each handler, which we chain
4781 together here. */
4782 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
4783 Present (gnat_temp); gnat_temp = Next_Non_Pragma (gnat_temp))
4785 gnu_expr = gnat_to_gnu (gnat_temp);
4787 /* If this is the first one, set it as the outer one. Otherwise,
4788 point the "else" part of the previous handler to us. Then point
4789 to our "else" part. */
4790 if (!gnu_else_ptr)
4791 add_stmt (gnu_expr);
4792 else
4793 *gnu_else_ptr = gnu_expr;
4795 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
4798 /* If none of the exception handlers did anything, re-raise but do not
4799 defer abortion. */
4800 gnu_expr = build_call_n_expr (raise_nodefer_decl, 1,
4801 gnu_except_ptr_stack->last ());
4802 set_expr_location_from_node
4803 (gnu_expr,
4804 Present (End_Label (gnat_node)) ? End_Label (gnat_node) : gnat_node);
4806 if (gnu_else_ptr)
4807 *gnu_else_ptr = gnu_expr;
4808 else
4809 add_stmt (gnu_expr);
4811 /* End the binding level dedicated to the exception handlers and get the
4812 whole statement group. */
4813 gnu_except_ptr_stack->pop ();
4814 gnat_poplevel ();
4815 gnu_handler = end_stmt_group ();
4817 /* If the setjmp returns 1, we restore our incoming longjmp value and
4818 then check the handlers. */
4819 start_stmt_group ();
4820 add_stmt_with_node (build_call_n_expr (set_jmpbuf_decl, 1,
4821 gnu_jmpsave_decl),
4822 gnat_node);
4823 add_stmt (gnu_handler);
4824 gnu_handler = end_stmt_group ();
4826 /* This block is now "if (setjmp) ... <handlers> else <block>". */
4827 gnu_result = build3 (COND_EXPR, void_type_node,
4828 (build_call_n_expr
4829 (setjmp_decl, 1,
4830 build_unary_op (ADDR_EXPR, NULL_TREE,
4831 gnu_jmpbuf_decl))),
4832 gnu_handler, gnu_inner_block);
4834 else if (gcc_zcx)
4836 tree gnu_handlers;
4837 location_t locus;
4839 /* First make a block containing the handlers. */
4840 start_stmt_group ();
4841 for (gnat_temp = First_Non_Pragma (Exception_Handlers (gnat_node));
4842 Present (gnat_temp);
4843 gnat_temp = Next_Non_Pragma (gnat_temp))
4844 add_stmt (gnat_to_gnu (gnat_temp));
4845 gnu_handlers = end_stmt_group ();
4847 /* Now make the TRY_CATCH_EXPR for the block. */
4848 gnu_result = build2 (TRY_CATCH_EXPR, void_type_node,
4849 gnu_inner_block, gnu_handlers);
4850 /* Set a location. We need to find a unique location for the dispatching
4851 code, otherwise we can get coverage or debugging issues. Try with
4852 the location of the end label. */
4853 if (Present (End_Label (gnat_node))
4854 && Sloc_to_locus (Sloc (End_Label (gnat_node)), &locus))
4855 SET_EXPR_LOCATION (gnu_result, locus);
4856 else
4857 /* Clear column information so that the exception handler of an
4858 implicit transient block does not incorrectly inherit the slocs
4859 of a decision, which would otherwise confuse control flow based
4860 coverage analysis tools. */
4861 set_expr_location_from_node1 (gnu_result, gnat_node, true);
4863 else
4864 gnu_result = gnu_inner_block;
4866 /* Now close our outer block, if we had to make one. */
4867 if (binding_for_block)
4869 add_stmt (gnu_result);
4870 gnat_poplevel ();
4871 gnu_result = end_stmt_group ();
4874 return gnu_result;
4877 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
4878 to a GCC tree, which is returned. This is the variant for Setjmp_Longjmp
4879 exception handling. */
4881 static tree
4882 Exception_Handler_to_gnu_sjlj (Node_Id gnat_node)
4884 /* Unless this is "Others" or the special "Non-Ada" exception for Ada, make
4885 an "if" statement to select the proper exceptions. For "Others", exclude
4886 exceptions where Handled_By_Others is nonzero unless the All_Others flag
4887 is set. For "Non-ada", accept an exception if "Lang" is 'V'. */
4888 tree gnu_choice = boolean_false_node;
4889 tree gnu_body = build_stmt_group (Statements (gnat_node), false);
4890 Node_Id gnat_temp;
4892 for (gnat_temp = First (Exception_Choices (gnat_node));
4893 gnat_temp; gnat_temp = Next (gnat_temp))
4895 tree this_choice;
4897 if (Nkind (gnat_temp) == N_Others_Choice)
4899 if (All_Others (gnat_temp))
4900 this_choice = boolean_true_node;
4901 else
4902 this_choice
4903 = build_binary_op
4904 (EQ_EXPR, boolean_type_node,
4905 convert
4906 (integer_type_node,
4907 build_component_ref
4908 (build_unary_op
4909 (INDIRECT_REF, NULL_TREE,
4910 gnu_except_ptr_stack->last ()),
4911 get_identifier ("not_handled_by_others"), NULL_TREE,
4912 false)),
4913 integer_zero_node);
4916 else if (Nkind (gnat_temp) == N_Identifier
4917 || Nkind (gnat_temp) == N_Expanded_Name)
4919 Entity_Id gnat_ex_id = Entity (gnat_temp);
4920 tree gnu_expr;
4922 /* Exception may be a renaming. Recover original exception which is
4923 the one elaborated and registered. */
4924 if (Present (Renamed_Object (gnat_ex_id)))
4925 gnat_ex_id = Renamed_Object (gnat_ex_id);
4927 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
4929 this_choice
4930 = build_binary_op
4931 (EQ_EXPR, boolean_type_node,
4932 gnu_except_ptr_stack->last (),
4933 convert (TREE_TYPE (gnu_except_ptr_stack->last ()),
4934 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr)));
4936 else
4937 gcc_unreachable ();
4939 gnu_choice = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
4940 gnu_choice, this_choice);
4943 return build3 (COND_EXPR, void_type_node, gnu_choice, gnu_body, NULL_TREE);
4946 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Exception_Handler,
4947 to a GCC tree, which is returned. This is the variant for ZCX. */
4949 static tree
4950 Exception_Handler_to_gnu_zcx (Node_Id gnat_node)
4952 tree gnu_etypes_list = NULL_TREE;
4953 tree gnu_current_exc_ptr, prev_gnu_incoming_exc_ptr;
4954 Node_Id gnat_temp;
4956 /* We build a TREE_LIST of nodes representing what exception types this
4957 handler can catch, with special cases for others and all others cases.
4959 Each exception type is actually identified by a pointer to the exception
4960 id, or to a dummy object for "others" and "all others". */
4961 for (gnat_temp = First (Exception_Choices (gnat_node));
4962 gnat_temp; gnat_temp = Next (gnat_temp))
4964 tree gnu_expr, gnu_etype;
4966 if (Nkind (gnat_temp) == N_Others_Choice)
4968 gnu_expr = All_Others (gnat_temp) ? all_others_decl : others_decl;
4969 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
4971 else if (Nkind (gnat_temp) == N_Identifier
4972 || Nkind (gnat_temp) == N_Expanded_Name)
4974 Entity_Id gnat_ex_id = Entity (gnat_temp);
4976 /* Exception may be a renaming. Recover original exception which is
4977 the one elaborated and registered. */
4978 if (Present (Renamed_Object (gnat_ex_id)))
4979 gnat_ex_id = Renamed_Object (gnat_ex_id);
4981 gnu_expr = gnat_to_gnu_entity (gnat_ex_id, NULL_TREE, 0);
4982 gnu_etype = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_expr);
4984 else
4985 gcc_unreachable ();
4987 /* The GCC interface expects NULL to be passed for catch all handlers, so
4988 it would be quite tempting to set gnu_etypes_list to NULL if gnu_etype
4989 is integer_zero_node. It would not work, however, because GCC's
4990 notion of "catch all" is stronger than our notion of "others". Until
4991 we correctly use the cleanup interface as well, doing that would
4992 prevent the "all others" handlers from being seen, because nothing
4993 can be caught beyond a catch all from GCC's point of view. */
4994 gnu_etypes_list = tree_cons (NULL_TREE, gnu_etype, gnu_etypes_list);
4997 start_stmt_group ();
4998 gnat_pushlevel ();
5000 /* Expand a call to the begin_handler hook at the beginning of the handler,
5001 and arrange for a call to the end_handler hook to occur on every possible
5002 exit path.
5004 The hooks expect a pointer to the low level occurrence. This is required
5005 for our stack management scheme because a raise inside the handler pushes
5006 a new occurrence on top of the stack, which means that this top does not
5007 necessarily match the occurrence this handler was dealing with.
5009 __builtin_eh_pointer references the exception occurrence being
5010 propagated. Upon handler entry, this is the exception for which the
5011 handler is triggered. This might not be the case upon handler exit,
5012 however, as we might have a new occurrence propagated by the handler's
5013 body, and the end_handler hook called as a cleanup in this context.
5015 We use a local variable to retrieve the incoming value at handler entry
5016 time, and reuse it to feed the end_handler hook's argument at exit. */
5018 gnu_current_exc_ptr
5019 = build_call_expr (builtin_decl_explicit (BUILT_IN_EH_POINTER),
5020 1, integer_zero_node);
5021 prev_gnu_incoming_exc_ptr = gnu_incoming_exc_ptr;
5022 gnu_incoming_exc_ptr = create_var_decl (get_identifier ("EXPTR"), NULL_TREE,
5023 ptr_type_node, gnu_current_exc_ptr,
5024 false, false, false, false,
5025 NULL, gnat_node);
5027 add_stmt_with_node (build_call_n_expr (begin_handler_decl, 1,
5028 gnu_incoming_exc_ptr),
5029 gnat_node);
5031 /* Declare and initialize the choice parameter, if present. */
5032 if (Present (Choice_Parameter (gnat_node)))
5034 tree gnu_param
5035 = gnat_to_gnu_entity (Choice_Parameter (gnat_node), NULL_TREE, 1);
5037 add_stmt (build_call_n_expr
5038 (set_exception_parameter_decl, 2,
5039 build_unary_op (ADDR_EXPR, NULL_TREE, gnu_param),
5040 gnu_incoming_exc_ptr));
5043 /* We don't have an End_Label at hand to set the location of the cleanup
5044 actions, so we use that of the exception handler itself instead. */
5045 add_cleanup (build_call_n_expr (end_handler_decl, 1, gnu_incoming_exc_ptr),
5046 gnat_node);
5047 add_stmt_list (Statements (gnat_node));
5048 gnat_poplevel ();
5050 gnu_incoming_exc_ptr = prev_gnu_incoming_exc_ptr;
5052 return
5053 build2 (CATCH_EXPR, void_type_node, gnu_etypes_list, end_stmt_group ());
5056 /* Subroutine of gnat_to_gnu to generate code for an N_Compilation unit. */
5058 static void
5059 Compilation_Unit_to_gnu (Node_Id gnat_node)
5061 const Node_Id gnat_unit = Unit (gnat_node);
5062 const bool body_p = (Nkind (gnat_unit) == N_Package_Body
5063 || Nkind (gnat_unit) == N_Subprogram_Body);
5064 const Entity_Id gnat_unit_entity = Defining_Entity (gnat_unit);
5065 Entity_Id gnat_entity;
5066 Node_Id gnat_pragma;
5067 /* Make the decl for the elaboration procedure. */
5068 tree gnu_elab_proc_decl
5069 = create_subprog_decl
5070 (create_concat_name (gnat_unit_entity, body_p ? "elabb" : "elabs"),
5071 NULL_TREE, void_ftype, NULL_TREE, is_disabled, true, false, true, NULL,
5072 gnat_unit);
5073 struct elab_info *info;
5075 vec_safe_push (gnu_elab_proc_stack, gnu_elab_proc_decl);
5076 DECL_ELABORATION_PROC_P (gnu_elab_proc_decl) = 1;
5078 /* Initialize the information structure for the function. */
5079 allocate_struct_function (gnu_elab_proc_decl, false);
5080 set_cfun (NULL);
5082 current_function_decl = NULL_TREE;
5084 start_stmt_group ();
5085 gnat_pushlevel ();
5087 /* For a body, first process the spec if there is one. */
5088 if (Nkind (gnat_unit) == N_Package_Body
5089 || (Nkind (gnat_unit) == N_Subprogram_Body && !Acts_As_Spec (gnat_node)))
5090 add_stmt (gnat_to_gnu (Library_Unit (gnat_node)));
5092 if (type_annotate_only && gnat_node == Cunit (Main_Unit))
5094 elaborate_all_entities (gnat_node);
5096 if (Nkind (gnat_unit) == N_Subprogram_Declaration
5097 || Nkind (gnat_unit) == N_Generic_Package_Declaration
5098 || Nkind (gnat_unit) == N_Generic_Subprogram_Declaration)
5099 return;
5102 /* Then process any pragmas and declarations preceding the unit. */
5103 for (gnat_pragma = First (Context_Items (gnat_node));
5104 Present (gnat_pragma);
5105 gnat_pragma = Next (gnat_pragma))
5106 if (Nkind (gnat_pragma) == N_Pragma)
5107 add_stmt (gnat_to_gnu (gnat_pragma));
5108 process_decls (Declarations (Aux_Decls_Node (gnat_node)), Empty, Empty,
5109 true, true);
5111 /* Process the unit itself. */
5112 add_stmt (gnat_to_gnu (gnat_unit));
5114 /* Generate code for all the inlined subprograms. */
5115 for (gnat_entity = First_Inlined_Subprogram (gnat_node);
5116 Present (gnat_entity);
5117 gnat_entity = Next_Inlined_Subprogram (gnat_entity))
5119 Node_Id gnat_body;
5121 /* Without optimization, process only the required subprograms. */
5122 if (!optimize && !Has_Pragma_Inline_Always (gnat_entity))
5123 continue;
5125 gnat_body = Parent (Declaration_Node (gnat_entity));
5126 if (Nkind (gnat_body) != N_Subprogram_Body)
5128 /* ??? This happens when only the spec of a package is provided. */
5129 if (No (Corresponding_Body (gnat_body)))
5130 continue;
5132 gnat_body
5133 = Parent (Declaration_Node (Corresponding_Body (gnat_body)));
5136 /* Define the entity first so we set DECL_EXTERNAL. */
5137 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
5138 add_stmt (gnat_to_gnu (gnat_body));
5141 /* Process any pragmas and actions following the unit. */
5142 add_stmt_list (Pragmas_After (Aux_Decls_Node (gnat_node)));
5143 add_stmt_list (Actions (Aux_Decls_Node (gnat_node)));
5144 finalize_from_limited_with ();
5146 /* Save away what we've made so far and record this potential elaboration
5147 procedure. */
5148 info = ggc_alloc<elab_info> ();
5149 set_current_block_context (gnu_elab_proc_decl);
5150 gnat_poplevel ();
5151 DECL_SAVED_TREE (gnu_elab_proc_decl) = end_stmt_group ();
5153 set_end_locus_from_node (gnu_elab_proc_decl, gnat_unit);
5155 info->next = elab_info_list;
5156 info->elab_proc = gnu_elab_proc_decl;
5157 info->gnat_node = gnat_node;
5158 elab_info_list = info;
5160 /* Generate elaboration code for this unit, if necessary, and say whether
5161 we did or not. */
5162 gnu_elab_proc_stack->pop ();
5164 /* Invalidate the global renaming pointers. This is necessary because
5165 stabilization of the renamed entities may create SAVE_EXPRs which
5166 have been tied to a specific elaboration routine just above. */
5167 invalidate_global_renaming_pointers ();
5169 /* Force the processing for all nodes that remain in the queue. */
5170 process_deferred_decl_context (true);
5173 /* Subroutine of gnat_to_gnu to translate gnat_node, an N_Raise_xxx_Error,
5174 to a GCC tree, which is returned. GNU_RESULT_TYPE_P is a pointer to where
5175 we should place the result type. LABEL_P is true if there is a label to
5176 branch to for the exception. */
5178 static tree
5179 Raise_Error_to_gnu (Node_Id gnat_node, tree *gnu_result_type_p)
5181 const Node_Kind kind = Nkind (gnat_node);
5182 const int reason = UI_To_Int (Reason (gnat_node));
5183 const Node_Id gnat_cond = Condition (gnat_node);
5184 const bool with_extra_info
5185 = Exception_Extra_Info
5186 && !No_Exception_Handlers_Set ()
5187 && !get_exception_label (kind);
5188 tree gnu_result = NULL_TREE, gnu_cond = NULL_TREE;
5190 *gnu_result_type_p = get_unpadded_type (Etype (gnat_node));
5192 switch (reason)
5194 case CE_Access_Check_Failed:
5195 if (with_extra_info)
5196 gnu_result = build_call_raise_column (reason, gnat_node);
5197 break;
5199 case CE_Index_Check_Failed:
5200 case CE_Range_Check_Failed:
5201 case CE_Invalid_Data:
5202 if (Present (gnat_cond) && Nkind (gnat_cond) == N_Op_Not)
5204 Node_Id gnat_range, gnat_index, gnat_type;
5205 tree gnu_index, gnu_low_bound, gnu_high_bound;
5206 struct range_check_info_d *rci;
5208 switch (Nkind (Right_Opnd (gnat_cond)))
5210 case N_In:
5211 gnat_range = Right_Opnd (Right_Opnd (gnat_cond));
5212 gcc_assert (Nkind (gnat_range) == N_Range);
5213 gnu_low_bound = gnat_to_gnu (Low_Bound (gnat_range));
5214 gnu_high_bound = gnat_to_gnu (High_Bound (gnat_range));
5215 break;
5217 case N_Op_Ge:
5218 gnu_low_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
5219 gnu_high_bound = NULL_TREE;
5220 break;
5222 case N_Op_Le:
5223 gnu_low_bound = NULL_TREE;
5224 gnu_high_bound = gnat_to_gnu (Right_Opnd (Right_Opnd (gnat_cond)));
5225 break;
5227 default:
5228 goto common;
5231 gnat_index = Left_Opnd (Right_Opnd (gnat_cond));
5232 gnat_type = Etype (gnat_index);
5233 gnu_index = gnat_to_gnu (gnat_index);
5235 if (with_extra_info
5236 && gnu_low_bound
5237 && gnu_high_bound
5238 && Known_Esize (gnat_type)
5239 && UI_To_Int (Esize (gnat_type)) <= 32)
5240 gnu_result
5241 = build_call_raise_range (reason, gnat_node, gnu_index,
5242 gnu_low_bound, gnu_high_bound);
5244 /* If loop unswitching is enabled, we try to compute invariant
5245 conditions for checks applied to iteration variables, i.e.
5246 conditions that are both independent of the variable and
5247 necessary in order for the check to fail in the course of
5248 some iteration, and prepend them to the original condition
5249 of the checks. This will make it possible later for the
5250 loop unswitching pass to replace the loop with two loops,
5251 one of which has the checks eliminated and the other has
5252 the original checks reinstated, and a run time selection.
5253 The former loop will be suitable for vectorization. */
5254 if (flag_unswitch_loops
5255 && !vec_safe_is_empty (gnu_loop_stack)
5256 && (!gnu_low_bound
5257 || (gnu_low_bound = gnat_invariant_expr (gnu_low_bound)))
5258 && (!gnu_high_bound
5259 || (gnu_high_bound = gnat_invariant_expr (gnu_high_bound)))
5260 && (rci = push_range_check_info (gnu_index)))
5262 rci->low_bound = gnu_low_bound;
5263 rci->high_bound = gnu_high_bound;
5264 rci->type = get_unpadded_type (gnat_type);
5265 rci->invariant_cond = build1 (SAVE_EXPR, boolean_type_node,
5266 boolean_true_node);
5267 gnu_cond = build_binary_op (TRUTH_ANDIF_EXPR,
5268 boolean_type_node,
5269 rci->invariant_cond,
5270 gnat_to_gnu (gnat_cond));
5273 break;
5275 default:
5276 break;
5279 common:
5280 if (!gnu_result)
5281 gnu_result = build_call_raise (reason, gnat_node, kind);
5282 set_expr_location_from_node (gnu_result, gnat_node);
5284 /* If the type is VOID, this is a statement, so we need to generate the code
5285 for the call. Handle a condition, if there is one. */
5286 if (VOID_TYPE_P (*gnu_result_type_p))
5288 if (Present (gnat_cond))
5290 if (!gnu_cond)
5291 gnu_cond = gnat_to_gnu (gnat_cond);
5292 gnu_result = build3 (COND_EXPR, void_type_node, gnu_cond, gnu_result,
5293 alloc_stmt_list ());
5296 else
5297 gnu_result = build1 (NULL_EXPR, *gnu_result_type_p, gnu_result);
5299 return gnu_result;
5302 /* Return true if GNAT_NODE is on the LHS of an assignment or an actual
5303 parameter of a call. */
5305 static bool
5306 lhs_or_actual_p (Node_Id gnat_node)
5308 Node_Id gnat_parent = Parent (gnat_node);
5309 Node_Kind kind = Nkind (gnat_parent);
5311 if (kind == N_Assignment_Statement && Name (gnat_parent) == gnat_node)
5312 return true;
5314 if ((kind == N_Procedure_Call_Statement || kind == N_Function_Call)
5315 && Name (gnat_parent) != gnat_node)
5316 return true;
5318 if (kind == N_Parameter_Association)
5319 return true;
5321 return false;
5324 /* Return true if either GNAT_NODE or a view of GNAT_NODE is on the LHS
5325 of an assignment or an actual parameter of a call. */
5327 static bool
5328 present_in_lhs_or_actual_p (Node_Id gnat_node)
5330 Node_Kind kind;
5332 if (lhs_or_actual_p (gnat_node))
5333 return true;
5335 kind = Nkind (Parent (gnat_node));
5337 if ((kind == N_Type_Conversion || kind == N_Unchecked_Type_Conversion)
5338 && lhs_or_actual_p (Parent (gnat_node)))
5339 return true;
5341 return false;
5344 /* Return true if GNAT_NODE, an unchecked type conversion, is a no-op as far
5345 as gigi is concerned. This is used to avoid conversions on the LHS. */
5347 static bool
5348 unchecked_conversion_nop (Node_Id gnat_node)
5350 Entity_Id from_type, to_type;
5352 /* The conversion must be on the LHS of an assignment or an actual parameter
5353 of a call. Otherwise, even if the conversion was essentially a no-op, it
5354 could de facto ensure type consistency and this should be preserved. */
5355 if (!lhs_or_actual_p (gnat_node))
5356 return false;
5358 from_type = Etype (Expression (gnat_node));
5360 /* We're interested in artificial conversions generated by the front-end
5361 to make private types explicit, e.g. in Expand_Assign_Array. */
5362 if (!Is_Private_Type (from_type))
5363 return false;
5365 from_type = Underlying_Type (from_type);
5366 to_type = Etype (gnat_node);
5368 /* The direct conversion to the underlying type is a no-op. */
5369 if (to_type == from_type)
5370 return true;
5372 /* For an array subtype, the conversion to the PAIT is a no-op. */
5373 if (Ekind (from_type) == E_Array_Subtype
5374 && to_type == Packed_Array_Impl_Type (from_type))
5375 return true;
5377 /* For a record subtype, the conversion to the type is a no-op. */
5378 if (Ekind (from_type) == E_Record_Subtype
5379 && to_type == Etype (from_type))
5380 return true;
5382 return false;
5385 /* This function is the driver of the GNAT to GCC tree transformation process.
5386 It is the entry point of the tree transformer. GNAT_NODE is the root of
5387 some GNAT tree. Return the root of the corresponding GCC tree. If this
5388 is an expression, return the GCC equivalent of the expression. If this
5389 is a statement, return the statement or add it to the current statement
5390 group, in which case anything returned is to be interpreted as occurring
5391 after anything added. */
5393 tree
5394 gnat_to_gnu (Node_Id gnat_node)
5396 const Node_Kind kind = Nkind (gnat_node);
5397 bool went_into_elab_proc = false;
5398 tree gnu_result = error_mark_node; /* Default to no value. */
5399 tree gnu_result_type = void_type_node;
5400 tree gnu_expr, gnu_lhs, gnu_rhs;
5401 Node_Id gnat_temp;
5403 /* Save node number for error message and set location information. */
5404 error_gnat_node = gnat_node;
5405 Sloc_to_locus (Sloc (gnat_node), &input_location);
5407 /* If this node is a statement and we are only annotating types, return an
5408 empty statement list. */
5409 if (type_annotate_only && IN (kind, N_Statement_Other_Than_Procedure_Call))
5410 return alloc_stmt_list ();
5412 /* If this node is a non-static subexpression and we are only annotating
5413 types, make this into a NULL_EXPR. */
5414 if (type_annotate_only
5415 && IN (kind, N_Subexpr)
5416 && kind != N_Identifier
5417 && !Compile_Time_Known_Value (gnat_node))
5418 return build1 (NULL_EXPR, get_unpadded_type (Etype (gnat_node)),
5419 build_call_raise (CE_Range_Check_Failed, gnat_node,
5420 N_Raise_Constraint_Error));
5422 if ((IN (kind, N_Statement_Other_Than_Procedure_Call)
5423 && kind != N_Null_Statement)
5424 || kind == N_Procedure_Call_Statement
5425 || kind == N_Label
5426 || kind == N_Implicit_Label_Declaration
5427 || kind == N_Handled_Sequence_Of_Statements
5428 || (IN (kind, N_Raise_xxx_Error) && Ekind (Etype (gnat_node)) == E_Void))
5430 tree current_elab_proc = get_elaboration_procedure ();
5432 /* If this is a statement and we are at top level, it must be part of
5433 the elaboration procedure, so mark us as being in that procedure. */
5434 if (!current_function_decl)
5436 current_function_decl = current_elab_proc;
5437 went_into_elab_proc = true;
5440 /* If we are in the elaboration procedure, check if we are violating a
5441 No_Elaboration_Code restriction by having a statement there. Don't
5442 check for a possible No_Elaboration_Code restriction violation on
5443 N_Handled_Sequence_Of_Statements, as we want to signal an error on
5444 every nested real statement instead. This also avoids triggering
5445 spurious errors on dummy (empty) sequences created by the front-end
5446 for package bodies in some cases. */
5447 if (current_function_decl == current_elab_proc
5448 && kind != N_Handled_Sequence_Of_Statements)
5449 Check_Elaboration_Code_Allowed (gnat_node);
5452 switch (kind)
5454 /********************************/
5455 /* Chapter 2: Lexical Elements */
5456 /********************************/
5458 case N_Identifier:
5459 case N_Expanded_Name:
5460 case N_Operator_Symbol:
5461 case N_Defining_Identifier:
5462 gnu_result = Identifier_to_gnu (gnat_node, &gnu_result_type);
5464 /* If this is an atomic access on the RHS for which synchronization is
5465 required, build the atomic load. */
5466 if (atomic_sync_required_p (gnat_node)
5467 && !present_in_lhs_or_actual_p (gnat_node))
5468 gnu_result = build_atomic_load (gnu_result);
5469 break;
5471 case N_Integer_Literal:
5473 tree gnu_type;
5475 /* Get the type of the result, looking inside any padding and
5476 justified modular types. Then get the value in that type. */
5477 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
5479 if (TREE_CODE (gnu_type) == RECORD_TYPE
5480 && TYPE_JUSTIFIED_MODULAR_P (gnu_type))
5481 gnu_type = TREE_TYPE (TYPE_FIELDS (gnu_type));
5483 gnu_result = UI_To_gnu (Intval (gnat_node), gnu_type);
5485 /* If the result overflows (meaning it doesn't fit in its base type),
5486 abort. We would like to check that the value is within the range
5487 of the subtype, but that causes problems with subtypes whose usage
5488 will raise Constraint_Error and with biased representation, so
5489 we don't. */
5490 gcc_assert (!TREE_OVERFLOW (gnu_result));
5492 break;
5494 case N_Character_Literal:
5495 /* If a Entity is present, it means that this was one of the
5496 literals in a user-defined character type. In that case,
5497 just return the value in the CONST_DECL. Otherwise, use the
5498 character code. In that case, the base type should be an
5499 INTEGER_TYPE, but we won't bother checking for that. */
5500 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5501 if (Present (Entity (gnat_node)))
5502 gnu_result = DECL_INITIAL (get_gnu_tree (Entity (gnat_node)));
5503 else
5504 gnu_result
5505 = build_int_cst_type
5506 (gnu_result_type, UI_To_CC (Char_Literal_Value (gnat_node)));
5507 break;
5509 case N_Real_Literal:
5510 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5512 /* If this is of a fixed-point type, the value we want is the value of
5513 the corresponding integer. */
5514 if (IN (Ekind (Underlying_Type (Etype (gnat_node))), Fixed_Point_Kind))
5516 gnu_result = UI_To_gnu (Corresponding_Integer_Value (gnat_node),
5517 gnu_result_type);
5518 gcc_assert (!TREE_OVERFLOW (gnu_result));
5521 else
5523 Ureal ur_realval = Realval (gnat_node);
5525 /* First convert the value to a machine number if it isn't already.
5526 That will force the base to 2 for non-zero values and simplify
5527 the rest of the logic. */
5528 if (!Is_Machine_Number (gnat_node))
5529 ur_realval
5530 = Machine (Base_Type (Underlying_Type (Etype (gnat_node))),
5531 ur_realval, Round_Even, gnat_node);
5533 if (UR_Is_Zero (ur_realval))
5534 gnu_result = convert (gnu_result_type, integer_zero_node);
5535 else
5537 REAL_VALUE_TYPE tmp;
5539 gnu_result = UI_To_gnu (Numerator (ur_realval), gnu_result_type);
5541 /* The base must be 2 as Machine guarantees this, so we scale
5542 the value, which we know can fit in the mantissa of the type
5543 (hence the use of that type above). */
5544 gcc_assert (Rbase (ur_realval) == 2);
5545 real_ldexp (&tmp, &TREE_REAL_CST (gnu_result),
5546 - UI_To_Int (Denominator (ur_realval)));
5547 gnu_result = build_real (gnu_result_type, tmp);
5550 /* Now see if we need to negate the result. Do it this way to
5551 properly handle -0. */
5552 if (UR_Is_Negative (Realval (gnat_node)))
5553 gnu_result
5554 = build_unary_op (NEGATE_EXPR, get_base_type (gnu_result_type),
5555 gnu_result);
5558 break;
5560 case N_String_Literal:
5561 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5562 if (TYPE_PRECISION (TREE_TYPE (gnu_result_type)) == HOST_BITS_PER_CHAR)
5564 String_Id gnat_string = Strval (gnat_node);
5565 int length = String_Length (gnat_string);
5566 int i;
5567 char *string;
5568 if (length >= ALLOCA_THRESHOLD)
5569 string = XNEWVEC (char, length + 1);
5570 else
5571 string = (char *) alloca (length + 1);
5573 /* Build the string with the characters in the literal. Note
5574 that Ada strings are 1-origin. */
5575 for (i = 0; i < length; i++)
5576 string[i] = Get_String_Char (gnat_string, i + 1);
5578 /* Put a null at the end of the string in case it's in a context
5579 where GCC will want to treat it as a C string. */
5580 string[i] = 0;
5582 gnu_result = build_string (length, string);
5584 /* Strings in GCC don't normally have types, but we want
5585 this to not be converted to the array type. */
5586 TREE_TYPE (gnu_result) = gnu_result_type;
5588 if (length >= ALLOCA_THRESHOLD)
5589 free (string);
5591 else
5593 /* Build a list consisting of each character, then make
5594 the aggregate. */
5595 String_Id gnat_string = Strval (gnat_node);
5596 int length = String_Length (gnat_string);
5597 int i;
5598 tree gnu_idx = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
5599 tree gnu_one_node = convert (TREE_TYPE (gnu_idx), integer_one_node);
5600 vec<constructor_elt, va_gc> *gnu_vec;
5601 vec_alloc (gnu_vec, length);
5603 for (i = 0; i < length; i++)
5605 tree t = build_int_cst (TREE_TYPE (gnu_result_type),
5606 Get_String_Char (gnat_string, i + 1));
5608 CONSTRUCTOR_APPEND_ELT (gnu_vec, gnu_idx, t);
5609 gnu_idx = int_const_binop (PLUS_EXPR, gnu_idx, gnu_one_node);
5612 gnu_result = gnat_build_constructor (gnu_result_type, gnu_vec);
5614 break;
5616 case N_Pragma:
5617 gnu_result = Pragma_to_gnu (gnat_node);
5618 break;
5620 /**************************************/
5621 /* Chapter 3: Declarations and Types */
5622 /**************************************/
5624 case N_Subtype_Declaration:
5625 case N_Full_Type_Declaration:
5626 case N_Incomplete_Type_Declaration:
5627 case N_Private_Type_Declaration:
5628 case N_Private_Extension_Declaration:
5629 case N_Task_Type_Declaration:
5630 process_type (Defining_Entity (gnat_node));
5631 gnu_result = alloc_stmt_list ();
5632 break;
5634 case N_Object_Declaration:
5635 case N_Exception_Declaration:
5636 gnat_temp = Defining_Entity (gnat_node);
5637 gnu_result = alloc_stmt_list ();
5639 /* If we are just annotating types and this object has an unconstrained
5640 or task type, don't elaborate it. */
5641 if (type_annotate_only
5642 && (((Is_Array_Type (Etype (gnat_temp))
5643 || Is_Record_Type (Etype (gnat_temp)))
5644 && !Is_Constrained (Etype (gnat_temp)))
5645 || Is_Concurrent_Type (Etype (gnat_temp))))
5646 break;
5648 if (Present (Expression (gnat_node))
5649 && !(kind == N_Object_Declaration && No_Initialization (gnat_node))
5650 && (!type_annotate_only
5651 || Compile_Time_Known_Value (Expression (gnat_node))))
5653 gnu_expr = gnat_to_gnu (Expression (gnat_node));
5654 if (Do_Range_Check (Expression (gnat_node)))
5655 gnu_expr
5656 = emit_range_check (gnu_expr, Etype (gnat_temp), gnat_node);
5658 /* If this object has its elaboration delayed, we must force
5659 evaluation of GNU_EXPR right now and save it for when the object
5660 is frozen. */
5661 if (Present (Freeze_Node (gnat_temp)))
5663 if (TREE_CONSTANT (gnu_expr))
5665 else if (global_bindings_p ())
5666 gnu_expr
5667 = create_var_decl (create_concat_name (gnat_temp, "init"),
5668 NULL_TREE, TREE_TYPE (gnu_expr), gnu_expr,
5669 false, false, false, false,
5670 NULL, gnat_temp);
5671 else
5672 gnu_expr = gnat_save_expr (gnu_expr);
5674 save_gnu_tree (gnat_node, gnu_expr, true);
5677 else
5678 gnu_expr = NULL_TREE;
5680 if (type_annotate_only && gnu_expr && TREE_CODE (gnu_expr) == ERROR_MARK)
5681 gnu_expr = NULL_TREE;
5683 /* If this is a deferred constant with an address clause, we ignore the
5684 full view since the clause is on the partial view and we cannot have
5685 2 different GCC trees for the object. The only bits of the full view
5686 we will use is the initializer, but it will be directly fetched. */
5687 if (Ekind(gnat_temp) == E_Constant
5688 && Present (Address_Clause (gnat_temp))
5689 && Present (Full_View (gnat_temp)))
5690 save_gnu_tree (Full_View (gnat_temp), error_mark_node, true);
5692 if (No (Freeze_Node (gnat_temp)))
5693 gnat_to_gnu_entity (gnat_temp, gnu_expr, 1);
5694 break;
5696 case N_Object_Renaming_Declaration:
5697 gnat_temp = Defining_Entity (gnat_node);
5699 /* Don't do anything if this renaming is handled by the front end or if
5700 we are just annotating types and this object has a composite or task
5701 type, don't elaborate it. We return the result in case it has any
5702 SAVE_EXPRs in it that need to be evaluated here. */
5703 if (!Is_Renaming_Of_Object (gnat_temp)
5704 && ! (type_annotate_only
5705 && (Is_Array_Type (Etype (gnat_temp))
5706 || Is_Record_Type (Etype (gnat_temp))
5707 || Is_Concurrent_Type (Etype (gnat_temp)))))
5708 gnu_result
5709 = gnat_to_gnu_entity (gnat_temp,
5710 gnat_to_gnu (Renamed_Object (gnat_temp)), 1);
5711 else
5712 gnu_result = alloc_stmt_list ();
5713 break;
5715 case N_Exception_Renaming_Declaration:
5716 gnat_temp = Defining_Entity (gnat_node);
5717 if (Renamed_Entity (gnat_temp) != Empty)
5718 gnu_result
5719 = gnat_to_gnu_entity (gnat_temp,
5720 gnat_to_gnu (Renamed_Entity (gnat_temp)), 1);
5721 else
5722 gnu_result = alloc_stmt_list ();
5723 break;
5725 case N_Implicit_Label_Declaration:
5726 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
5727 gnu_result = alloc_stmt_list ();
5728 break;
5730 case N_Number_Declaration:
5731 case N_Subprogram_Renaming_Declaration:
5732 case N_Package_Renaming_Declaration:
5733 /* These are fully handled in the front end. */
5734 /* ??? For package renamings, find a way to use GENERIC namespaces so
5735 that we get proper debug information for them. */
5736 gnu_result = alloc_stmt_list ();
5737 break;
5739 /*************************************/
5740 /* Chapter 4: Names and Expressions */
5741 /*************************************/
5743 case N_Explicit_Dereference:
5744 gnu_result = gnat_to_gnu (Prefix (gnat_node));
5745 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5746 gnu_result = build_unary_op (INDIRECT_REF, NULL_TREE, gnu_result);
5748 /* If this is an atomic access on the RHS for which synchronization is
5749 required, build the atomic load. */
5750 if (atomic_sync_required_p (gnat_node)
5751 && !present_in_lhs_or_actual_p (gnat_node))
5752 gnu_result = build_atomic_load (gnu_result);
5753 break;
5755 case N_Indexed_Component:
5757 tree gnu_array_object = gnat_to_gnu (Prefix (gnat_node));
5758 tree gnu_type;
5759 int ndim;
5760 int i;
5761 Node_Id *gnat_expr_array;
5763 gnu_array_object = maybe_implicit_deref (gnu_array_object);
5765 /* Convert vector inputs to their representative array type, to fit
5766 what the code below expects. */
5767 if (VECTOR_TYPE_P (TREE_TYPE (gnu_array_object)))
5769 if (present_in_lhs_or_actual_p (gnat_node))
5770 gnat_mark_addressable (gnu_array_object);
5771 gnu_array_object = maybe_vector_array (gnu_array_object);
5774 gnu_array_object = maybe_unconstrained_array (gnu_array_object);
5776 /* If we got a padded type, remove it too. */
5777 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_array_object)))
5778 gnu_array_object
5779 = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_array_object))),
5780 gnu_array_object);
5782 gnu_result = gnu_array_object;
5784 /* The failure of this assertion will very likely come from a missing
5785 expansion for a packed array access. */
5786 gcc_assert (TREE_CODE (TREE_TYPE (gnu_array_object)) == ARRAY_TYPE);
5788 /* First compute the number of dimensions of the array, then
5789 fill the expression array, the order depending on whether
5790 this is a Convention_Fortran array or not. */
5791 for (ndim = 1, gnu_type = TREE_TYPE (gnu_array_object);
5792 TREE_CODE (TREE_TYPE (gnu_type)) == ARRAY_TYPE
5793 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_type));
5794 ndim++, gnu_type = TREE_TYPE (gnu_type))
5797 gnat_expr_array = XALLOCAVEC (Node_Id, ndim);
5799 if (TYPE_CONVENTION_FORTRAN_P (TREE_TYPE (gnu_array_object)))
5800 for (i = ndim - 1, gnat_temp = First (Expressions (gnat_node));
5801 i >= 0;
5802 i--, gnat_temp = Next (gnat_temp))
5803 gnat_expr_array[i] = gnat_temp;
5804 else
5805 for (i = 0, gnat_temp = First (Expressions (gnat_node));
5806 i < ndim;
5807 i++, gnat_temp = Next (gnat_temp))
5808 gnat_expr_array[i] = gnat_temp;
5810 for (i = 0, gnu_type = TREE_TYPE (gnu_array_object);
5811 i < ndim; i++, gnu_type = TREE_TYPE (gnu_type))
5813 gcc_assert (TREE_CODE (gnu_type) == ARRAY_TYPE);
5814 gnat_temp = gnat_expr_array[i];
5815 gnu_expr = gnat_to_gnu (gnat_temp);
5817 if (Do_Range_Check (gnat_temp))
5818 gnu_expr
5819 = emit_index_check
5820 (gnu_array_object, gnu_expr,
5821 TYPE_MIN_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
5822 TYPE_MAX_VALUE (TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type))),
5823 gnat_temp);
5825 gnu_result
5826 = build_binary_op (ARRAY_REF, NULL_TREE, gnu_result, gnu_expr);
5828 /* Array accesses are bound-checked so they cannot trap, but this
5829 is valid only if they are not hoisted ahead of the check. We
5830 need to mark them as no-trap to get decent loop optimizations
5831 in the presence of -fnon-call-exceptions, so we do it when we
5832 know that the original expression had no side-effects. */
5833 if (TREE_CODE (gnu_result) == ARRAY_REF
5834 && !(Nkind (gnat_temp) == N_Identifier
5835 && Ekind (Entity (gnat_temp)) == E_Constant))
5836 TREE_THIS_NOTRAP (gnu_result) = 1;
5839 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5841 /* If this is an atomic access on the RHS for which synchronization is
5842 required, build the atomic load. */
5843 if (atomic_sync_required_p (gnat_node)
5844 && !present_in_lhs_or_actual_p (gnat_node))
5845 gnu_result = build_atomic_load (gnu_result);
5847 break;
5849 case N_Slice:
5851 Node_Id gnat_range_node = Discrete_Range (gnat_node);
5852 tree gnu_type;
5854 gnu_result = gnat_to_gnu (Prefix (gnat_node));
5855 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5857 /* Do any implicit dereferences of the prefix and do any needed
5858 range check. */
5859 gnu_result = maybe_implicit_deref (gnu_result);
5860 gnu_result = maybe_unconstrained_array (gnu_result);
5861 gnu_type = TREE_TYPE (gnu_result);
5862 if (Do_Range_Check (gnat_range_node))
5864 /* Get the bounds of the slice. */
5865 tree gnu_index_type
5866 = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_result_type));
5867 tree gnu_min_expr = TYPE_MIN_VALUE (gnu_index_type);
5868 tree gnu_max_expr = TYPE_MAX_VALUE (gnu_index_type);
5869 /* Get the permitted bounds. */
5870 tree gnu_base_index_type
5871 = TYPE_INDEX_TYPE (TYPE_DOMAIN (gnu_type));
5872 tree gnu_base_min_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
5873 (TYPE_MIN_VALUE (gnu_base_index_type), gnu_result);
5874 tree gnu_base_max_expr = SUBSTITUTE_PLACEHOLDER_IN_EXPR
5875 (TYPE_MAX_VALUE (gnu_base_index_type), gnu_result);
5876 tree gnu_expr_l, gnu_expr_h, gnu_expr_type;
5878 gnu_min_expr = gnat_protect_expr (gnu_min_expr);
5879 gnu_max_expr = gnat_protect_expr (gnu_max_expr);
5881 /* Derive a good type to convert everything to. */
5882 gnu_expr_type = get_base_type (gnu_index_type);
5884 /* Test whether the minimum slice value is too small. */
5885 gnu_expr_l = build_binary_op (LT_EXPR, boolean_type_node,
5886 convert (gnu_expr_type,
5887 gnu_min_expr),
5888 convert (gnu_expr_type,
5889 gnu_base_min_expr));
5891 /* Test whether the maximum slice value is too large. */
5892 gnu_expr_h = build_binary_op (GT_EXPR, boolean_type_node,
5893 convert (gnu_expr_type,
5894 gnu_max_expr),
5895 convert (gnu_expr_type,
5896 gnu_base_max_expr));
5898 /* Build a slice index check that returns the low bound,
5899 assuming the slice is not empty. */
5900 gnu_expr = emit_check
5901 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
5902 gnu_expr_l, gnu_expr_h),
5903 gnu_min_expr, CE_Index_Check_Failed, gnat_node);
5905 /* Build a conditional expression that does the index checks and
5906 returns the low bound if the slice is not empty (max >= min),
5907 and returns the naked low bound otherwise (max < min), unless
5908 it is non-constant and the high bound is; this prevents VRP
5909 from inferring bogus ranges on the unlikely path. */
5910 gnu_expr = fold_build3 (COND_EXPR, gnu_expr_type,
5911 build_binary_op (GE_EXPR, gnu_expr_type,
5912 convert (gnu_expr_type,
5913 gnu_max_expr),
5914 convert (gnu_expr_type,
5915 gnu_min_expr)),
5916 gnu_expr,
5917 TREE_CODE (gnu_min_expr) != INTEGER_CST
5918 && TREE_CODE (gnu_max_expr) == INTEGER_CST
5919 ? gnu_max_expr : gnu_min_expr);
5921 else
5922 /* Simply return the naked low bound. */
5923 gnu_expr = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_result_type));
5925 /* If this is a slice with non-constant size of an array with constant
5926 size, set the maximum size for the allocation of temporaries. */
5927 if (!TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_result_type))
5928 && TREE_CONSTANT (TYPE_SIZE_UNIT (gnu_type)))
5929 TYPE_ARRAY_MAX_SIZE (gnu_result_type) = TYPE_SIZE_UNIT (gnu_type);
5931 gnu_result = build_binary_op (ARRAY_RANGE_REF, gnu_result_type,
5932 gnu_result, gnu_expr);
5934 break;
5936 case N_Selected_Component:
5938 Entity_Id gnat_prefix = Prefix (gnat_node);
5939 Entity_Id gnat_field = Entity (Selector_Name (gnat_node));
5940 tree gnu_prefix = gnat_to_gnu (gnat_prefix);
5941 tree gnu_field;
5943 gnu_prefix = maybe_implicit_deref (gnu_prefix);
5945 /* For discriminant references in tagged types always substitute the
5946 corresponding discriminant as the actual selected component. */
5947 if (Is_Tagged_Type (Underlying_Type (Etype (gnat_prefix))))
5948 while (Present (Corresponding_Discriminant (gnat_field)))
5949 gnat_field = Corresponding_Discriminant (gnat_field);
5951 /* For discriminant references of untagged types always substitute the
5952 corresponding stored discriminant. */
5953 else if (Present (Corresponding_Discriminant (gnat_field)))
5954 gnat_field = Original_Record_Component (gnat_field);
5956 /* Handle extracting the real or imaginary part of a complex.
5957 The real part is the first field and the imaginary the last. */
5958 if (TREE_CODE (TREE_TYPE (gnu_prefix)) == COMPLEX_TYPE)
5959 gnu_result = build_unary_op (Present (Next_Entity (gnat_field))
5960 ? REALPART_EXPR : IMAGPART_EXPR,
5961 NULL_TREE, gnu_prefix);
5962 else
5964 gnu_field = gnat_to_gnu_field_decl (gnat_field);
5966 /* If there are discriminants, the prefix might be evaluated more
5967 than once, which is a problem if it has side-effects. */
5968 if (Has_Discriminants (Is_Access_Type (Etype (Prefix (gnat_node)))
5969 ? Designated_Type (Etype
5970 (Prefix (gnat_node)))
5971 : Etype (Prefix (gnat_node))))
5972 gnu_prefix = gnat_stabilize_reference (gnu_prefix, false, NULL);
5974 gnu_result
5975 = build_component_ref (gnu_prefix, NULL_TREE, gnu_field,
5976 (Nkind (Parent (gnat_node))
5977 == N_Attribute_Reference)
5978 && lvalue_required_for_attribute_p
5979 (Parent (gnat_node)));
5982 gnu_result_type = get_unpadded_type (Etype (gnat_node));
5984 /* If this is an atomic access on the RHS for which synchronization is
5985 required, build the atomic load. */
5986 if (atomic_sync_required_p (gnat_node)
5987 && !present_in_lhs_or_actual_p (gnat_node))
5988 gnu_result = build_atomic_load (gnu_result);
5990 break;
5992 case N_Attribute_Reference:
5994 /* The attribute designator. */
5995 const int attr = Get_Attribute_Id (Attribute_Name (gnat_node));
5997 /* The Elab_Spec and Elab_Body attributes are special in that Prefix
5998 is a unit, not an object with a GCC equivalent. */
5999 if (attr == Attr_Elab_Spec || attr == Attr_Elab_Body)
6000 return
6001 create_subprog_decl (create_concat_name
6002 (Entity (Prefix (gnat_node)),
6003 attr == Attr_Elab_Body ? "elabb" : "elabs"),
6004 NULL_TREE, void_ftype, NULL_TREE, is_disabled,
6005 true, true, true, NULL, gnat_node);
6007 gnu_result = Attribute_to_gnu (gnat_node, &gnu_result_type, attr);
6009 break;
6011 case N_Reference:
6012 /* Like 'Access as far as we are concerned. */
6013 gnu_result = gnat_to_gnu (Prefix (gnat_node));
6014 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
6015 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6016 break;
6018 case N_Aggregate:
6019 case N_Extension_Aggregate:
6021 tree gnu_aggr_type;
6023 /* ??? It is wrong to evaluate the type now, but there doesn't
6024 seem to be any other practical way of doing it. */
6026 gcc_assert (!Expansion_Delayed (gnat_node));
6028 gnu_aggr_type = gnu_result_type
6029 = get_unpadded_type (Etype (gnat_node));
6031 if (TREE_CODE (gnu_result_type) == RECORD_TYPE
6032 && TYPE_CONTAINS_TEMPLATE_P (gnu_result_type))
6033 gnu_aggr_type
6034 = TREE_TYPE (DECL_CHAIN (TYPE_FIELDS (gnu_result_type)));
6035 else if (TREE_CODE (gnu_result_type) == VECTOR_TYPE)
6036 gnu_aggr_type = TYPE_REPRESENTATIVE_ARRAY (gnu_result_type);
6038 if (Null_Record_Present (gnat_node))
6039 gnu_result = gnat_build_constructor (gnu_aggr_type,
6040 NULL);
6042 else if (TREE_CODE (gnu_aggr_type) == RECORD_TYPE
6043 || TREE_CODE (gnu_aggr_type) == UNION_TYPE)
6044 gnu_result
6045 = assoc_to_constructor (Etype (gnat_node),
6046 First (Component_Associations (gnat_node)),
6047 gnu_aggr_type);
6048 else if (TREE_CODE (gnu_aggr_type) == ARRAY_TYPE)
6049 gnu_result = pos_to_constructor (First (Expressions (gnat_node)),
6050 gnu_aggr_type,
6051 Component_Type (Etype (gnat_node)));
6052 else if (TREE_CODE (gnu_aggr_type) == COMPLEX_TYPE)
6053 gnu_result
6054 = build_binary_op
6055 (COMPLEX_EXPR, gnu_aggr_type,
6056 gnat_to_gnu (Expression (First
6057 (Component_Associations (gnat_node)))),
6058 gnat_to_gnu (Expression
6059 (Next
6060 (First (Component_Associations (gnat_node))))));
6061 else
6062 gcc_unreachable ();
6064 gnu_result = convert (gnu_result_type, gnu_result);
6066 break;
6068 case N_Null:
6069 if (TARGET_VTABLE_USES_DESCRIPTORS
6070 && Ekind (Etype (gnat_node)) == E_Access_Subprogram_Type
6071 && Is_Dispatch_Table_Entity (Etype (gnat_node)))
6072 gnu_result = null_fdesc_node;
6073 else
6074 gnu_result = null_pointer_node;
6075 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6076 break;
6078 case N_Type_Conversion:
6079 case N_Qualified_Expression:
6080 /* Get the operand expression. */
6081 gnu_result = gnat_to_gnu (Expression (gnat_node));
6082 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6084 /* If this is a qualified expression for a tagged type, we mark the type
6085 as used. Because of polymorphism, this might be the only reference to
6086 the tagged type in the program while objects have it as dynamic type.
6087 The debugger needs to see it to display these objects properly. */
6088 if (kind == N_Qualified_Expression && Is_Tagged_Type (Etype (gnat_node)))
6089 used_types_insert (gnu_result_type);
6091 gnu_result
6092 = convert_with_check (Etype (gnat_node), gnu_result,
6093 Do_Overflow_Check (gnat_node),
6094 Do_Range_Check (Expression (gnat_node)),
6095 kind == N_Type_Conversion
6096 && Float_Truncate (gnat_node), gnat_node);
6097 break;
6099 case N_Unchecked_Type_Conversion:
6100 gnu_result = gnat_to_gnu (Expression (gnat_node));
6102 /* Skip further processing if the conversion is deemed a no-op. */
6103 if (unchecked_conversion_nop (gnat_node))
6105 gnu_result_type = TREE_TYPE (gnu_result);
6106 break;
6109 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6111 /* If the result is a pointer type, see if we are improperly
6112 converting to a stricter alignment. */
6113 if (STRICT_ALIGNMENT && POINTER_TYPE_P (gnu_result_type)
6114 && IN (Ekind (Etype (gnat_node)), Access_Kind))
6116 unsigned int align = known_alignment (gnu_result);
6117 tree gnu_obj_type = TREE_TYPE (gnu_result_type);
6118 unsigned int oalign = TYPE_ALIGN (gnu_obj_type);
6120 if (align != 0 && align < oalign && !TYPE_ALIGN_OK (gnu_obj_type))
6121 post_error_ne_tree_2
6122 ("?source alignment (^) '< alignment of & (^)",
6123 gnat_node, Designated_Type (Etype (gnat_node)),
6124 size_int (align / BITS_PER_UNIT), oalign / BITS_PER_UNIT);
6127 /* If we are converting a descriptor to a function pointer, first
6128 build the pointer. */
6129 if (TARGET_VTABLE_USES_DESCRIPTORS
6130 && TREE_TYPE (gnu_result) == fdesc_type_node
6131 && POINTER_TYPE_P (gnu_result_type))
6132 gnu_result = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_result);
6134 gnu_result = unchecked_convert (gnu_result_type, gnu_result,
6135 No_Truncation (gnat_node));
6136 break;
6138 case N_In:
6139 case N_Not_In:
6141 tree gnu_obj = gnat_to_gnu (Left_Opnd (gnat_node));
6142 Node_Id gnat_range = Right_Opnd (gnat_node);
6143 tree gnu_low, gnu_high;
6145 /* GNAT_RANGE is either an N_Range node or an identifier denoting a
6146 subtype. */
6147 if (Nkind (gnat_range) == N_Range)
6149 gnu_low = gnat_to_gnu (Low_Bound (gnat_range));
6150 gnu_high = gnat_to_gnu (High_Bound (gnat_range));
6152 else if (Nkind (gnat_range) == N_Identifier
6153 || Nkind (gnat_range) == N_Expanded_Name)
6155 tree gnu_range_type = get_unpadded_type (Entity (gnat_range));
6156 tree gnu_range_base_type = get_base_type (gnu_range_type);
6158 gnu_low
6159 = convert (gnu_range_base_type, TYPE_MIN_VALUE (gnu_range_type));
6160 gnu_high
6161 = convert (gnu_range_base_type, TYPE_MAX_VALUE (gnu_range_type));
6163 else
6164 gcc_unreachable ();
6166 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6168 /* If LOW and HIGH are identical, perform an equality test. Otherwise,
6169 ensure that GNU_OBJ is evaluated only once and perform a full range
6170 test. */
6171 if (operand_equal_p (gnu_low, gnu_high, 0))
6172 gnu_result
6173 = build_binary_op (EQ_EXPR, gnu_result_type, gnu_obj, gnu_low);
6174 else
6176 tree t1, t2;
6177 gnu_obj = gnat_protect_expr (gnu_obj);
6178 t1 = build_binary_op (GE_EXPR, gnu_result_type, gnu_obj, gnu_low);
6179 if (EXPR_P (t1))
6180 set_expr_location_from_node (t1, gnat_node);
6181 t2 = build_binary_op (LE_EXPR, gnu_result_type, gnu_obj, gnu_high);
6182 if (EXPR_P (t2))
6183 set_expr_location_from_node (t2, gnat_node);
6184 gnu_result
6185 = build_binary_op (TRUTH_ANDIF_EXPR, gnu_result_type, t1, t2);
6188 if (kind == N_Not_In)
6189 gnu_result
6190 = invert_truthvalue_loc (EXPR_LOCATION (gnu_result), gnu_result);
6192 break;
6194 case N_Op_Divide:
6195 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6196 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6197 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6198 gnu_result = build_binary_op (FLOAT_TYPE_P (gnu_result_type)
6199 ? RDIV_EXPR
6200 : (Rounded_Result (gnat_node)
6201 ? ROUND_DIV_EXPR : TRUNC_DIV_EXPR),
6202 gnu_result_type, gnu_lhs, gnu_rhs);
6203 break;
6205 case N_Op_Or: case N_Op_And: case N_Op_Xor:
6206 /* These can either be operations on booleans or on modular types.
6207 Fall through for boolean types since that's the way GNU_CODES is
6208 set up. */
6209 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
6211 enum tree_code code
6212 = (kind == N_Op_Or ? BIT_IOR_EXPR
6213 : kind == N_Op_And ? BIT_AND_EXPR
6214 : BIT_XOR_EXPR);
6216 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6217 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6218 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6219 gnu_result = build_binary_op (code, gnu_result_type,
6220 gnu_lhs, gnu_rhs);
6221 break;
6224 /* ... fall through ... */
6226 case N_Op_Eq: case N_Op_Ne: case N_Op_Lt:
6227 case N_Op_Le: case N_Op_Gt: case N_Op_Ge:
6228 case N_Op_Add: case N_Op_Subtract: case N_Op_Multiply:
6229 case N_Op_Mod: case N_Op_Rem:
6230 case N_Op_Rotate_Left:
6231 case N_Op_Rotate_Right:
6232 case N_Op_Shift_Left:
6233 case N_Op_Shift_Right:
6234 case N_Op_Shift_Right_Arithmetic:
6235 case N_And_Then: case N_Or_Else:
6237 enum tree_code code = gnu_codes[kind];
6238 bool ignore_lhs_overflow = false;
6239 location_t saved_location = input_location;
6240 tree gnu_type;
6242 gnu_lhs = gnat_to_gnu (Left_Opnd (gnat_node));
6243 gnu_rhs = gnat_to_gnu (Right_Opnd (gnat_node));
6244 gnu_type = gnu_result_type = get_unpadded_type (Etype (gnat_node));
6246 /* Pending generic support for efficient vector logical operations in
6247 GCC, convert vectors to their representative array type view and
6248 fallthrough. */
6249 gnu_lhs = maybe_vector_array (gnu_lhs);
6250 gnu_rhs = maybe_vector_array (gnu_rhs);
6252 /* If this is a comparison operator, convert any references to an
6253 unconstrained array value into a reference to the actual array. */
6254 if (TREE_CODE_CLASS (code) == tcc_comparison)
6256 gnu_lhs = maybe_unconstrained_array (gnu_lhs);
6257 gnu_rhs = maybe_unconstrained_array (gnu_rhs);
6260 /* If this is a shift whose count is not guaranteed to be correct,
6261 we need to adjust the shift count. */
6262 if (IN (kind, N_Op_Shift) && !Shift_Count_OK (gnat_node))
6264 tree gnu_count_type = get_base_type (TREE_TYPE (gnu_rhs));
6265 tree gnu_max_shift
6266 = convert (gnu_count_type, TYPE_SIZE (gnu_type));
6268 if (kind == N_Op_Rotate_Left || kind == N_Op_Rotate_Right)
6269 gnu_rhs = build_binary_op (TRUNC_MOD_EXPR, gnu_count_type,
6270 gnu_rhs, gnu_max_shift);
6271 else if (kind == N_Op_Shift_Right_Arithmetic)
6272 gnu_rhs
6273 = build_binary_op
6274 (MIN_EXPR, gnu_count_type,
6275 build_binary_op (MINUS_EXPR,
6276 gnu_count_type,
6277 gnu_max_shift,
6278 convert (gnu_count_type,
6279 integer_one_node)),
6280 gnu_rhs);
6283 /* For right shifts, the type says what kind of shift to do,
6284 so we may need to choose a different type. In this case,
6285 we have to ignore integer overflow lest it propagates all
6286 the way down and causes a CE to be explicitly raised. */
6287 if (kind == N_Op_Shift_Right && !TYPE_UNSIGNED (gnu_type))
6289 gnu_type = gnat_unsigned_type (gnu_type);
6290 ignore_lhs_overflow = true;
6292 else if (kind == N_Op_Shift_Right_Arithmetic
6293 && TYPE_UNSIGNED (gnu_type))
6295 gnu_type = gnat_signed_type (gnu_type);
6296 ignore_lhs_overflow = true;
6299 if (gnu_type != gnu_result_type)
6301 tree gnu_old_lhs = gnu_lhs;
6302 gnu_lhs = convert (gnu_type, gnu_lhs);
6303 if (TREE_CODE (gnu_lhs) == INTEGER_CST && ignore_lhs_overflow)
6304 TREE_OVERFLOW (gnu_lhs) = TREE_OVERFLOW (gnu_old_lhs);
6305 gnu_rhs = convert (gnu_type, gnu_rhs);
6308 /* Instead of expanding overflow checks for addition, subtraction
6309 and multiplication itself, the front end will leave this to
6310 the back end when Backend_Overflow_Checks_On_Target is set.
6311 As the GCC back end itself does not know yet how to properly
6312 do overflow checking, do it here. The goal is to push
6313 the expansions further into the back end over time. */
6314 if (Do_Overflow_Check (gnat_node) && Backend_Overflow_Checks_On_Target
6315 && (kind == N_Op_Add
6316 || kind == N_Op_Subtract
6317 || kind == N_Op_Multiply)
6318 && !TYPE_UNSIGNED (gnu_type)
6319 && !FLOAT_TYPE_P (gnu_type))
6320 gnu_result = build_binary_op_trapv (code, gnu_type,
6321 gnu_lhs, gnu_rhs, gnat_node);
6322 else
6324 /* Some operations, e.g. comparisons of arrays, generate complex
6325 trees that need to be annotated while they are being built. */
6326 input_location = saved_location;
6327 gnu_result = build_binary_op (code, gnu_type, gnu_lhs, gnu_rhs);
6330 /* If this is a logical shift with the shift count not verified,
6331 we must return zero if it is too large. We cannot compensate
6332 above in this case. */
6333 if ((kind == N_Op_Shift_Left || kind == N_Op_Shift_Right)
6334 && !Shift_Count_OK (gnat_node))
6335 gnu_result
6336 = build_cond_expr
6337 (gnu_type,
6338 build_binary_op (GE_EXPR, boolean_type_node,
6339 gnu_rhs,
6340 convert (TREE_TYPE (gnu_rhs),
6341 TYPE_SIZE (gnu_type))),
6342 convert (gnu_type, integer_zero_node),
6343 gnu_result);
6345 break;
6347 case N_If_Expression:
6349 tree gnu_cond = gnat_to_gnu (First (Expressions (gnat_node)));
6350 tree gnu_true = gnat_to_gnu (Next (First (Expressions (gnat_node))));
6351 tree gnu_false
6352 = gnat_to_gnu (Next (Next (First (Expressions (gnat_node)))));
6354 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6355 gnu_result
6356 = build_cond_expr (gnu_result_type, gnu_cond, gnu_true, gnu_false);
6358 break;
6360 case N_Op_Plus:
6361 gnu_result = gnat_to_gnu (Right_Opnd (gnat_node));
6362 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6363 break;
6365 case N_Op_Not:
6366 /* This case can apply to a boolean or a modular type.
6367 Fall through for a boolean operand since GNU_CODES is set
6368 up to handle this. */
6369 if (Is_Modular_Integer_Type (Underlying_Type (Etype (gnat_node))))
6371 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
6372 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6373 gnu_result = build_unary_op (BIT_NOT_EXPR, gnu_result_type,
6374 gnu_expr);
6375 break;
6378 /* ... fall through ... */
6380 case N_Op_Minus: case N_Op_Abs:
6381 gnu_expr = gnat_to_gnu (Right_Opnd (gnat_node));
6382 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6384 if (Do_Overflow_Check (gnat_node)
6385 && !TYPE_UNSIGNED (gnu_result_type)
6386 && !FLOAT_TYPE_P (gnu_result_type))
6387 gnu_result
6388 = build_unary_op_trapv (gnu_codes[kind],
6389 gnu_result_type, gnu_expr, gnat_node);
6390 else
6391 gnu_result = build_unary_op (gnu_codes[kind],
6392 gnu_result_type, gnu_expr);
6393 break;
6395 case N_Allocator:
6397 tree gnu_init = 0;
6398 tree gnu_type;
6399 bool ignore_init_type = false;
6401 gnat_temp = Expression (gnat_node);
6403 /* The Expression operand can either be an N_Identifier or
6404 Expanded_Name, which must represent a type, or a
6405 N_Qualified_Expression, which contains both the object type and an
6406 initial value for the object. */
6407 if (Nkind (gnat_temp) == N_Identifier
6408 || Nkind (gnat_temp) == N_Expanded_Name)
6409 gnu_type = gnat_to_gnu_type (Entity (gnat_temp));
6410 else if (Nkind (gnat_temp) == N_Qualified_Expression)
6412 Entity_Id gnat_desig_type
6413 = Designated_Type (Underlying_Type (Etype (gnat_node)));
6415 ignore_init_type = Has_Constrained_Partial_View (gnat_desig_type);
6416 gnu_init = gnat_to_gnu (Expression (gnat_temp));
6418 gnu_init = maybe_unconstrained_array (gnu_init);
6419 if (Do_Range_Check (Expression (gnat_temp)))
6420 gnu_init
6421 = emit_range_check (gnu_init, gnat_desig_type, gnat_temp);
6423 if (Is_Elementary_Type (gnat_desig_type)
6424 || Is_Constrained (gnat_desig_type))
6425 gnu_type = gnat_to_gnu_type (gnat_desig_type);
6426 else
6428 gnu_type = gnat_to_gnu_type (Etype (Expression (gnat_temp)));
6429 if (TREE_CODE (gnu_type) == UNCONSTRAINED_ARRAY_TYPE)
6430 gnu_type = TREE_TYPE (gnu_init);
6433 /* See the N_Qualified_Expression case for the rationale. */
6434 if (Is_Tagged_Type (gnat_desig_type))
6435 used_types_insert (gnu_type);
6437 gnu_init = convert (gnu_type, gnu_init);
6439 else
6440 gcc_unreachable ();
6442 gnu_result_type = get_unpadded_type (Etype (gnat_node));
6443 return build_allocator (gnu_type, gnu_init, gnu_result_type,
6444 Procedure_To_Call (gnat_node),
6445 Storage_Pool (gnat_node), gnat_node,
6446 ignore_init_type);
6448 break;
6450 /**************************/
6451 /* Chapter 5: Statements */
6452 /**************************/
6454 case N_Label:
6455 gnu_result = build1 (LABEL_EXPR, void_type_node,
6456 gnat_to_gnu (Identifier (gnat_node)));
6457 break;
6459 case N_Null_Statement:
6460 /* When not optimizing, turn null statements from source into gotos to
6461 the next statement that the middle-end knows how to preserve. */
6462 if (!optimize && Comes_From_Source (gnat_node))
6464 tree stmt, label = create_label_decl (NULL_TREE, gnat_node);
6465 DECL_IGNORED_P (label) = 1;
6466 start_stmt_group ();
6467 stmt = build1 (GOTO_EXPR, void_type_node, label);
6468 set_expr_location_from_node (stmt, gnat_node);
6469 add_stmt (stmt);
6470 stmt = build1 (LABEL_EXPR, void_type_node, label);
6471 set_expr_location_from_node (stmt, gnat_node);
6472 add_stmt (stmt);
6473 gnu_result = end_stmt_group ();
6475 else
6476 gnu_result = alloc_stmt_list ();
6477 break;
6479 case N_Assignment_Statement:
6480 /* Get the LHS and RHS of the statement and convert any reference to an
6481 unconstrained array into a reference to the underlying array. */
6482 gnu_lhs = maybe_unconstrained_array (gnat_to_gnu (Name (gnat_node)));
6484 /* If the type has a size that overflows, convert this into raise of
6485 Storage_Error: execution shouldn't have gotten here anyway. */
6486 if (TREE_CODE (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))) == INTEGER_CST
6487 && !valid_constant_size_p (TYPE_SIZE_UNIT (TREE_TYPE (gnu_lhs))))
6488 gnu_result = build_call_raise (SE_Object_Too_Large, gnat_node,
6489 N_Raise_Storage_Error);
6490 else if (Nkind (Expression (gnat_node)) == N_Function_Call)
6491 gnu_result
6492 = Call_to_gnu (Expression (gnat_node), &gnu_result_type, gnu_lhs,
6493 atomic_sync_required_p (Name (gnat_node)));
6494 else
6496 const Node_Id gnat_expr = Expression (gnat_node);
6497 const Entity_Id gnat_type
6498 = Underlying_Type (Etype (Name (gnat_node)));
6499 const bool regular_array_type_p
6500 = (Is_Array_Type (gnat_type) && !Is_Bit_Packed_Array (gnat_type));
6501 const bool use_memset_p
6502 = (regular_array_type_p
6503 && Nkind (gnat_expr) == N_Aggregate
6504 && Is_Others_Aggregate (gnat_expr));
6506 /* If we'll use memset, we need to find the inner expression. */
6507 if (use_memset_p)
6509 Node_Id gnat_inner
6510 = Expression (First (Component_Associations (gnat_expr)));
6511 while (Nkind (gnat_inner) == N_Aggregate
6512 && Is_Others_Aggregate (gnat_inner))
6513 gnat_inner
6514 = Expression (First (Component_Associations (gnat_inner)));
6515 gnu_rhs = gnat_to_gnu (gnat_inner);
6517 else
6518 gnu_rhs = maybe_unconstrained_array (gnat_to_gnu (gnat_expr));
6520 /* If range check is needed, emit code to generate it. */
6521 if (Do_Range_Check (gnat_expr))
6522 gnu_rhs = emit_range_check (gnu_rhs, Etype (Name (gnat_node)),
6523 gnat_node);
6525 /* If atomic synchronization is required, build an atomic store. */
6526 if (atomic_sync_required_p (Name (gnat_node)))
6527 gnu_result = build_atomic_store (gnu_lhs, gnu_rhs);
6529 /* Or else, use memset when the conditions are met. */
6530 else if (use_memset_p)
6532 tree value = fold_convert (integer_type_node, gnu_rhs);
6533 tree to = gnu_lhs;
6534 tree type = TREE_TYPE (to);
6535 tree size
6536 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), to);
6537 tree to_ptr = build_fold_addr_expr (to);
6538 tree t = builtin_decl_explicit (BUILT_IN_MEMSET);
6539 if (TREE_CODE (value) == INTEGER_CST)
6541 tree mask
6542 = build_int_cst (integer_type_node,
6543 ((HOST_WIDE_INT) 1 << BITS_PER_UNIT) - 1);
6544 value = int_const_binop (BIT_AND_EXPR, value, mask);
6546 gnu_result = build_call_expr (t, 3, to_ptr, value, size);
6549 /* Otherwise build a regular assignment. */
6550 else
6551 gnu_result
6552 = build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_lhs, gnu_rhs);
6554 /* If the assignment type is a regular array and the two sides are
6555 not completely disjoint, play safe and use memmove. But don't do
6556 it for a bit-packed array as it might not be byte-aligned. */
6557 if (TREE_CODE (gnu_result) == MODIFY_EXPR
6558 && regular_array_type_p
6559 && !(Forwards_OK (gnat_node) && Backwards_OK (gnat_node)))
6561 tree to = TREE_OPERAND (gnu_result, 0);
6562 tree from = TREE_OPERAND (gnu_result, 1);
6563 tree type = TREE_TYPE (from);
6564 tree size
6565 = SUBSTITUTE_PLACEHOLDER_IN_EXPR (TYPE_SIZE_UNIT (type), from);
6566 tree to_ptr = build_fold_addr_expr (to);
6567 tree from_ptr = build_fold_addr_expr (from);
6568 tree t = builtin_decl_explicit (BUILT_IN_MEMMOVE);
6569 gnu_result = build_call_expr (t, 3, to_ptr, from_ptr, size);
6572 break;
6574 case N_If_Statement:
6576 tree *gnu_else_ptr; /* Point to put next "else if" or "else". */
6578 /* Make the outer COND_EXPR. Avoid non-determinism. */
6579 gnu_result = build3 (COND_EXPR, void_type_node,
6580 gnat_to_gnu (Condition (gnat_node)),
6581 NULL_TREE, NULL_TREE);
6582 COND_EXPR_THEN (gnu_result)
6583 = build_stmt_group (Then_Statements (gnat_node), false);
6584 TREE_SIDE_EFFECTS (gnu_result) = 1;
6585 gnu_else_ptr = &COND_EXPR_ELSE (gnu_result);
6587 /* Now make a COND_EXPR for each of the "else if" parts. Put each
6588 into the previous "else" part and point to where to put any
6589 outer "else". Also avoid non-determinism. */
6590 if (Present (Elsif_Parts (gnat_node)))
6591 for (gnat_temp = First (Elsif_Parts (gnat_node));
6592 Present (gnat_temp); gnat_temp = Next (gnat_temp))
6594 gnu_expr = build3 (COND_EXPR, void_type_node,
6595 gnat_to_gnu (Condition (gnat_temp)),
6596 NULL_TREE, NULL_TREE);
6597 COND_EXPR_THEN (gnu_expr)
6598 = build_stmt_group (Then_Statements (gnat_temp), false);
6599 TREE_SIDE_EFFECTS (gnu_expr) = 1;
6600 set_expr_location_from_node (gnu_expr, gnat_temp);
6601 *gnu_else_ptr = gnu_expr;
6602 gnu_else_ptr = &COND_EXPR_ELSE (gnu_expr);
6605 *gnu_else_ptr = build_stmt_group (Else_Statements (gnat_node), false);
6607 break;
6609 case N_Case_Statement:
6610 gnu_result = Case_Statement_to_gnu (gnat_node);
6611 break;
6613 case N_Loop_Statement:
6614 gnu_result = Loop_Statement_to_gnu (gnat_node);
6615 break;
6617 case N_Block_Statement:
6618 /* The only way to enter the block is to fall through to it. */
6619 if (stmt_group_may_fallthru ())
6621 start_stmt_group ();
6622 gnat_pushlevel ();
6623 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
6624 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
6625 gnat_poplevel ();
6626 gnu_result = end_stmt_group ();
6628 else
6629 gnu_result = alloc_stmt_list ();
6630 break;
6632 case N_Exit_Statement:
6633 gnu_result
6634 = build2 (EXIT_STMT, void_type_node,
6635 (Present (Condition (gnat_node))
6636 ? gnat_to_gnu (Condition (gnat_node)) : NULL_TREE),
6637 (Present (Name (gnat_node))
6638 ? get_gnu_tree (Entity (Name (gnat_node)))
6639 : LOOP_STMT_LABEL (gnu_loop_stack->last ()->stmt)));
6640 break;
6642 case N_Simple_Return_Statement:
6644 tree gnu_ret_obj, gnu_ret_val;
6646 /* If the subprogram is a function, we must return the expression. */
6647 if (Present (Expression (gnat_node)))
6649 tree gnu_subprog_type = TREE_TYPE (current_function_decl);
6651 /* If this function has copy-in/copy-out parameters parameters and
6652 doesn't return by invisible reference, get the real object for
6653 the return. See Subprogram_Body_to_gnu. */
6654 if (TYPE_CI_CO_LIST (gnu_subprog_type)
6655 && !TREE_ADDRESSABLE (gnu_subprog_type))
6656 gnu_ret_obj = gnu_return_var_stack->last ();
6657 else
6658 gnu_ret_obj = DECL_RESULT (current_function_decl);
6660 /* Get the GCC tree for the expression to be returned. */
6661 gnu_ret_val = gnat_to_gnu (Expression (gnat_node));
6663 /* Do not remove the padding from GNU_RET_VAL if the inner type is
6664 self-referential since we want to allocate the fixed size. */
6665 if (TREE_CODE (gnu_ret_val) == COMPONENT_REF
6666 && TYPE_IS_PADDING_P
6667 (TREE_TYPE (TREE_OPERAND (gnu_ret_val, 0)))
6668 && CONTAINS_PLACEHOLDER_P
6669 (TYPE_SIZE (TREE_TYPE (gnu_ret_val))))
6670 gnu_ret_val = TREE_OPERAND (gnu_ret_val, 0);
6672 /* If the function returns by direct reference, return a pointer
6673 to the return value. */
6674 if (TYPE_RETURN_BY_DIRECT_REF_P (gnu_subprog_type)
6675 || By_Ref (gnat_node))
6676 gnu_ret_val = build_unary_op (ADDR_EXPR, NULL_TREE, gnu_ret_val);
6678 /* Otherwise, if it returns an unconstrained array, we have to
6679 allocate a new version of the result and return it. */
6680 else if (TYPE_RETURN_UNCONSTRAINED_P (gnu_subprog_type))
6682 gnu_ret_val = maybe_unconstrained_array (gnu_ret_val);
6684 /* And find out whether this is a candidate for Named Return
6685 Value. If so, record it. */
6686 if (!TYPE_CI_CO_LIST (gnu_subprog_type) && optimize)
6688 tree ret_val = gnu_ret_val;
6690 /* Strip useless conversions around the return value. */
6691 if (gnat_useless_type_conversion (ret_val))
6692 ret_val = TREE_OPERAND (ret_val, 0);
6694 /* Strip unpadding around the return value. */
6695 if (TREE_CODE (ret_val) == COMPONENT_REF
6696 && TYPE_IS_PADDING_P
6697 (TREE_TYPE (TREE_OPERAND (ret_val, 0))))
6698 ret_val = TREE_OPERAND (ret_val, 0);
6700 /* Now apply the test to the return value. */
6701 if (return_value_ok_for_nrv_p (NULL_TREE, ret_val))
6703 if (!f_named_ret_val)
6704 f_named_ret_val = BITMAP_GGC_ALLOC ();
6705 bitmap_set_bit (f_named_ret_val, DECL_UID (ret_val));
6706 if (!f_gnat_ret)
6707 f_gnat_ret = gnat_node;
6711 gnu_ret_val = build_allocator (TREE_TYPE (gnu_ret_val),
6712 gnu_ret_val,
6713 TREE_TYPE (gnu_ret_obj),
6714 Procedure_To_Call (gnat_node),
6715 Storage_Pool (gnat_node),
6716 gnat_node, false);
6719 /* Otherwise, if it returns by invisible reference, dereference
6720 the pointer it is passed using the type of the return value
6721 and build the copy operation manually. This ensures that we
6722 don't copy too much data, for example if the return type is
6723 unconstrained with a maximum size. */
6724 else if (TREE_ADDRESSABLE (gnu_subprog_type))
6726 tree gnu_ret_deref
6727 = build_unary_op (INDIRECT_REF, TREE_TYPE (gnu_ret_val),
6728 gnu_ret_obj);
6729 gnu_result = build2 (MODIFY_EXPR, void_type_node,
6730 gnu_ret_deref, gnu_ret_val);
6731 add_stmt_with_node (gnu_result, gnat_node);
6732 gnu_ret_val = NULL_TREE;
6736 else
6737 gnu_ret_obj = gnu_ret_val = NULL_TREE;
6739 /* If we have a return label defined, convert this into a branch to
6740 that label. The return proper will be handled elsewhere. */
6741 if (gnu_return_label_stack->last ())
6743 if (gnu_ret_val)
6744 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_ret_obj,
6745 gnu_ret_val));
6747 gnu_result = build1 (GOTO_EXPR, void_type_node,
6748 gnu_return_label_stack->last ());
6750 /* When not optimizing, make sure the return is preserved. */
6751 if (!optimize && Comes_From_Source (gnat_node))
6752 DECL_ARTIFICIAL (gnu_return_label_stack->last ()) = 0;
6755 /* Otherwise, build a regular return. */
6756 else
6757 gnu_result = build_return_expr (gnu_ret_obj, gnu_ret_val);
6759 break;
6761 case N_Goto_Statement:
6762 gnu_result
6763 = build1 (GOTO_EXPR, void_type_node, gnat_to_gnu (Name (gnat_node)));
6764 break;
6766 /***************************/
6767 /* Chapter 6: Subprograms */
6768 /***************************/
6770 case N_Subprogram_Declaration:
6771 /* Unless there is a freeze node, declare the subprogram. We consider
6772 this a "definition" even though we're not generating code for
6773 the subprogram because we will be making the corresponding GCC
6774 node here. */
6776 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
6777 gnat_to_gnu_entity (Defining_Entity (Specification (gnat_node)),
6778 NULL_TREE, 1);
6779 gnu_result = alloc_stmt_list ();
6780 break;
6782 case N_Abstract_Subprogram_Declaration:
6783 /* This subprogram doesn't exist for code generation purposes, but we
6784 have to elaborate the types of any parameters and result, unless
6785 they are imported types (nothing to generate in this case).
6787 The parameter list may contain types with freeze nodes, e.g. not null
6788 subtypes, so the subprogram itself may carry a freeze node, in which
6789 case its elaboration must be deferred. */
6791 /* Process the parameter types first. */
6792 if (No (Freeze_Node (Defining_Entity (Specification (gnat_node)))))
6793 for (gnat_temp
6794 = First_Formal_With_Extras
6795 (Defining_Entity (Specification (gnat_node)));
6796 Present (gnat_temp);
6797 gnat_temp = Next_Formal_With_Extras (gnat_temp))
6798 if (Is_Itype (Etype (gnat_temp))
6799 && !From_Limited_With (Etype (gnat_temp)))
6800 gnat_to_gnu_entity (Etype (gnat_temp), NULL_TREE, 0);
6802 /* Then the result type, set to Standard_Void_Type for procedures. */
6804 Entity_Id gnat_temp_type
6805 = Etype (Defining_Entity (Specification (gnat_node)));
6807 if (Is_Itype (gnat_temp_type) && !From_Limited_With (gnat_temp_type))
6808 gnat_to_gnu_entity (Etype (gnat_temp_type), NULL_TREE, 0);
6811 gnu_result = alloc_stmt_list ();
6812 break;
6814 case N_Defining_Program_Unit_Name:
6815 /* For a child unit identifier go up a level to get the specification.
6816 We get this when we try to find the spec of a child unit package
6817 that is the compilation unit being compiled. */
6818 gnu_result = gnat_to_gnu (Parent (gnat_node));
6819 break;
6821 case N_Subprogram_Body:
6822 Subprogram_Body_to_gnu (gnat_node);
6823 gnu_result = alloc_stmt_list ();
6824 break;
6826 case N_Function_Call:
6827 case N_Procedure_Call_Statement:
6828 gnu_result = Call_to_gnu (gnat_node, &gnu_result_type, NULL_TREE, false);
6829 break;
6831 /************************/
6832 /* Chapter 7: Packages */
6833 /************************/
6835 case N_Package_Declaration:
6836 gnu_result = gnat_to_gnu (Specification (gnat_node));
6837 break;
6839 case N_Package_Specification:
6841 start_stmt_group ();
6842 process_decls (Visible_Declarations (gnat_node),
6843 Private_Declarations (gnat_node), Empty, true, true);
6844 gnu_result = end_stmt_group ();
6845 break;
6847 case N_Package_Body:
6849 /* If this is the body of a generic package - do nothing. */
6850 if (Ekind (Corresponding_Spec (gnat_node)) == E_Generic_Package)
6852 gnu_result = alloc_stmt_list ();
6853 break;
6856 start_stmt_group ();
6857 process_decls (Declarations (gnat_node), Empty, Empty, true, true);
6859 if (Present (Handled_Statement_Sequence (gnat_node)))
6860 add_stmt (gnat_to_gnu (Handled_Statement_Sequence (gnat_node)));
6862 gnu_result = end_stmt_group ();
6863 break;
6865 /********************************/
6866 /* Chapter 8: Visibility Rules */
6867 /********************************/
6869 case N_Use_Package_Clause:
6870 case N_Use_Type_Clause:
6871 /* Nothing to do here - but these may appear in list of declarations. */
6872 gnu_result = alloc_stmt_list ();
6873 break;
6875 /*********************/
6876 /* Chapter 9: Tasks */
6877 /*********************/
6879 case N_Protected_Type_Declaration:
6880 gnu_result = alloc_stmt_list ();
6881 break;
6883 case N_Single_Task_Declaration:
6884 gnat_to_gnu_entity (Defining_Entity (gnat_node), NULL_TREE, 1);
6885 gnu_result = alloc_stmt_list ();
6886 break;
6888 /*********************************************************/
6889 /* Chapter 10: Program Structure and Compilation Issues */
6890 /*********************************************************/
6892 case N_Compilation_Unit:
6893 /* This is not called for the main unit on which gigi is invoked. */
6894 Compilation_Unit_to_gnu (gnat_node);
6895 gnu_result = alloc_stmt_list ();
6896 break;
6898 case N_Subprogram_Body_Stub:
6899 case N_Package_Body_Stub:
6900 case N_Protected_Body_Stub:
6901 case N_Task_Body_Stub:
6902 /* Simply process whatever unit is being inserted. */
6903 if (Present (Library_Unit (gnat_node)))
6904 gnu_result = gnat_to_gnu (Unit (Library_Unit (gnat_node)));
6905 else
6907 gcc_assert (type_annotate_only);
6908 gnu_result = alloc_stmt_list ();
6910 break;
6912 case N_Subunit:
6913 gnu_result = gnat_to_gnu (Proper_Body (gnat_node));
6914 break;
6916 /***************************/
6917 /* Chapter 11: Exceptions */
6918 /***************************/
6920 case N_Handled_Sequence_Of_Statements:
6921 /* If there is an At_End procedure attached to this node, and the EH
6922 mechanism is SJLJ, we must have at least a corresponding At_End
6923 handler, unless the No_Exception_Handlers restriction is set. */
6924 gcc_assert (type_annotate_only
6925 || Exception_Mechanism != Setjmp_Longjmp
6926 || No (At_End_Proc (gnat_node))
6927 || Present (Exception_Handlers (gnat_node))
6928 || No_Exception_Handlers_Set ());
6930 gnu_result = Handled_Sequence_Of_Statements_to_gnu (gnat_node);
6931 break;
6933 case N_Exception_Handler:
6934 if (Exception_Mechanism == Setjmp_Longjmp)
6935 gnu_result = Exception_Handler_to_gnu_sjlj (gnat_node);
6936 else if (Exception_Mechanism == Back_End_Exceptions)
6937 gnu_result = Exception_Handler_to_gnu_zcx (gnat_node);
6938 else
6939 gcc_unreachable ();
6940 break;
6942 case N_Raise_Statement:
6943 /* Only for reraise in back-end exceptions mode. */
6944 gcc_assert (No (Name (gnat_node))
6945 && Exception_Mechanism == Back_End_Exceptions);
6947 start_stmt_group ();
6948 gnat_pushlevel ();
6950 /* Clear the current exception pointer so that the occurrence won't be
6951 deallocated. */
6952 gnu_expr = create_var_decl (get_identifier ("SAVED_EXPTR"), NULL_TREE,
6953 ptr_type_node, gnu_incoming_exc_ptr,
6954 false, false, false, false, NULL, gnat_node);
6956 add_stmt (build_binary_op (MODIFY_EXPR, NULL_TREE, gnu_incoming_exc_ptr,
6957 convert (ptr_type_node, integer_zero_node)));
6958 add_stmt (build_call_n_expr (reraise_zcx_decl, 1, gnu_expr));
6959 gnat_poplevel ();
6960 gnu_result = end_stmt_group ();
6961 break;
6963 case N_Push_Constraint_Error_Label:
6964 push_exception_label_stack (&gnu_constraint_error_label_stack,
6965 Exception_Label (gnat_node));
6966 break;
6968 case N_Push_Storage_Error_Label:
6969 push_exception_label_stack (&gnu_storage_error_label_stack,
6970 Exception_Label (gnat_node));
6971 break;
6973 case N_Push_Program_Error_Label:
6974 push_exception_label_stack (&gnu_program_error_label_stack,
6975 Exception_Label (gnat_node));
6976 break;
6978 case N_Pop_Constraint_Error_Label:
6979 gnu_constraint_error_label_stack->pop ();
6980 break;
6982 case N_Pop_Storage_Error_Label:
6983 gnu_storage_error_label_stack->pop ();
6984 break;
6986 case N_Pop_Program_Error_Label:
6987 gnu_program_error_label_stack->pop ();
6988 break;
6990 /******************************/
6991 /* Chapter 12: Generic Units */
6992 /******************************/
6994 case N_Generic_Function_Renaming_Declaration:
6995 case N_Generic_Package_Renaming_Declaration:
6996 case N_Generic_Procedure_Renaming_Declaration:
6997 case N_Generic_Package_Declaration:
6998 case N_Generic_Subprogram_Declaration:
6999 case N_Package_Instantiation:
7000 case N_Procedure_Instantiation:
7001 case N_Function_Instantiation:
7002 /* These nodes can appear on a declaration list but there is nothing to
7003 to be done with them. */
7004 gnu_result = alloc_stmt_list ();
7005 break;
7007 /**************************************************/
7008 /* Chapter 13: Representation Clauses and */
7009 /* Implementation-Dependent Features */
7010 /**************************************************/
7012 case N_Attribute_Definition_Clause:
7013 gnu_result = alloc_stmt_list ();
7015 /* The only one we need to deal with is 'Address since, for the others,
7016 the front-end puts the information elsewhere. */
7017 if (Get_Attribute_Id (Chars (gnat_node)) != Attr_Address)
7018 break;
7020 /* And we only deal with 'Address if the object has a Freeze node. */
7021 gnat_temp = Entity (Name (gnat_node));
7022 if (No (Freeze_Node (gnat_temp)))
7023 break;
7025 /* Get the value to use as the address and save it as the equivalent
7026 for the object. When it is frozen, gnat_to_gnu_entity will do the
7027 right thing. */
7028 save_gnu_tree (gnat_temp, gnat_to_gnu (Expression (gnat_node)), true);
7029 break;
7031 case N_Enumeration_Representation_Clause:
7032 case N_Record_Representation_Clause:
7033 case N_At_Clause:
7034 /* We do nothing with these. SEM puts the information elsewhere. */
7035 gnu_result = alloc_stmt_list ();
7036 break;
7038 case N_Code_Statement:
7039 if (!type_annotate_only)
7041 tree gnu_template = gnat_to_gnu (Asm_Template (gnat_node));
7042 tree gnu_inputs = NULL_TREE, gnu_outputs = NULL_TREE;
7043 tree gnu_clobbers = NULL_TREE, tail;
7044 bool allows_mem, allows_reg, fake;
7045 int ninputs, noutputs, i;
7046 const char **oconstraints;
7047 const char *constraint;
7048 char *clobber;
7050 /* First retrieve the 3 operand lists built by the front-end. */
7051 Setup_Asm_Outputs (gnat_node);
7052 while (Present (gnat_temp = Asm_Output_Variable ()))
7054 tree gnu_value = gnat_to_gnu (gnat_temp);
7055 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
7056 (Asm_Output_Constraint ()));
7058 gnu_outputs = tree_cons (gnu_constr, gnu_value, gnu_outputs);
7059 Next_Asm_Output ();
7062 Setup_Asm_Inputs (gnat_node);
7063 while (Present (gnat_temp = Asm_Input_Value ()))
7065 tree gnu_value = gnat_to_gnu (gnat_temp);
7066 tree gnu_constr = build_tree_list (NULL_TREE, gnat_to_gnu
7067 (Asm_Input_Constraint ()));
7069 gnu_inputs = tree_cons (gnu_constr, gnu_value, gnu_inputs);
7070 Next_Asm_Input ();
7073 Clobber_Setup (gnat_node);
7074 while ((clobber = Clobber_Get_Next ()))
7075 gnu_clobbers
7076 = tree_cons (NULL_TREE,
7077 build_string (strlen (clobber) + 1, clobber),
7078 gnu_clobbers);
7080 /* Then perform some standard checking and processing on the
7081 operands. In particular, mark them addressable if needed. */
7082 gnu_outputs = nreverse (gnu_outputs);
7083 noutputs = list_length (gnu_outputs);
7084 gnu_inputs = nreverse (gnu_inputs);
7085 ninputs = list_length (gnu_inputs);
7086 oconstraints = XALLOCAVEC (const char *, noutputs);
7088 for (i = 0, tail = gnu_outputs; tail; ++i, tail = TREE_CHAIN (tail))
7090 tree output = TREE_VALUE (tail);
7091 constraint
7092 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
7093 oconstraints[i] = constraint;
7095 if (parse_output_constraint (&constraint, i, ninputs, noutputs,
7096 &allows_mem, &allows_reg, &fake))
7098 /* If the operand is going to end up in memory,
7099 mark it addressable. Note that we don't test
7100 allows_mem like in the input case below; this
7101 is modelled on the C front-end. */
7102 if (!allows_reg)
7104 output = remove_conversions (output, false);
7105 if (TREE_CODE (output) == CONST_DECL
7106 && DECL_CONST_CORRESPONDING_VAR (output))
7107 output = DECL_CONST_CORRESPONDING_VAR (output);
7108 if (!gnat_mark_addressable (output))
7109 output = error_mark_node;
7112 else
7113 output = error_mark_node;
7115 TREE_VALUE (tail) = output;
7118 for (i = 0, tail = gnu_inputs; tail; ++i, tail = TREE_CHAIN (tail))
7120 tree input = TREE_VALUE (tail);
7121 constraint
7122 = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (tail)));
7124 if (parse_input_constraint (&constraint, i, ninputs, noutputs,
7125 0, oconstraints,
7126 &allows_mem, &allows_reg))
7128 /* If the operand is going to end up in memory,
7129 mark it addressable. */
7130 if (!allows_reg && allows_mem)
7132 input = remove_conversions (input, false);
7133 if (TREE_CODE (input) == CONST_DECL
7134 && DECL_CONST_CORRESPONDING_VAR (input))
7135 input = DECL_CONST_CORRESPONDING_VAR (input);
7136 if (!gnat_mark_addressable (input))
7137 input = error_mark_node;
7140 else
7141 input = error_mark_node;
7143 TREE_VALUE (tail) = input;
7146 gnu_result = build5 (ASM_EXPR, void_type_node,
7147 gnu_template, gnu_outputs,
7148 gnu_inputs, gnu_clobbers, NULL_TREE);
7149 ASM_VOLATILE_P (gnu_result) = Is_Asm_Volatile (gnat_node);
7151 else
7152 gnu_result = alloc_stmt_list ();
7154 break;
7156 /****************/
7157 /* Added Nodes */
7158 /****************/
7160 case N_Expression_With_Actions:
7161 /* This construct doesn't define a scope so we don't push a binding
7162 level around the statement list, but we wrap it in a SAVE_EXPR to
7163 protect it from unsharing. Elaborate the expression as part of the
7164 same statement group as the actions so that the type declaration
7165 gets inserted there as well. This ensures that the type elaboration
7166 code is issued past the actions computing values on which it might
7167 depend. */
7169 start_stmt_group ();
7170 add_stmt_list (Actions (gnat_node));
7171 gnu_expr = gnat_to_gnu (Expression (gnat_node));
7172 gnu_result = end_stmt_group ();
7174 gnu_result = build1 (SAVE_EXPR, void_type_node, gnu_result);
7175 TREE_SIDE_EFFECTS (gnu_result) = 1;
7177 gnu_result
7178 = build_compound_expr (TREE_TYPE (gnu_expr), gnu_result, gnu_expr);
7179 gnu_result_type = get_unpadded_type (Etype (gnat_node));
7180 break;
7182 case N_Freeze_Entity:
7183 start_stmt_group ();
7184 process_freeze_entity (gnat_node);
7185 process_decls (Actions (gnat_node), Empty, Empty, true, true);
7186 gnu_result = end_stmt_group ();
7187 break;
7189 case N_Freeze_Generic_Entity:
7190 gnu_result = alloc_stmt_list ();
7191 break;
7193 case N_Itype_Reference:
7194 if (!present_gnu_tree (Itype (gnat_node)))
7195 process_type (Itype (gnat_node));
7197 gnu_result = alloc_stmt_list ();
7198 break;
7200 case N_Free_Statement:
7201 if (!type_annotate_only)
7203 tree gnu_ptr = gnat_to_gnu (Expression (gnat_node));
7204 tree gnu_ptr_type = TREE_TYPE (gnu_ptr);
7205 tree gnu_obj_type, gnu_actual_obj_type;
7207 /* If this is a thin pointer, we must first dereference it to create
7208 a fat pointer, then go back below to a thin pointer. The reason
7209 for this is that we need to have a fat pointer someplace in order
7210 to properly compute the size. */
7211 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
7212 gnu_ptr = build_unary_op (ADDR_EXPR, NULL_TREE,
7213 build_unary_op (INDIRECT_REF, NULL_TREE,
7214 gnu_ptr));
7216 /* If this is a fat pointer, the object must have been allocated with
7217 the template in front of the array. So pass the template address,
7218 and get the total size; do it by converting to a thin pointer. */
7219 if (TYPE_IS_FAT_POINTER_P (TREE_TYPE (gnu_ptr)))
7220 gnu_ptr
7221 = convert (build_pointer_type
7222 (TYPE_OBJECT_RECORD_TYPE
7223 (TYPE_UNCONSTRAINED_ARRAY (TREE_TYPE (gnu_ptr)))),
7224 gnu_ptr);
7226 gnu_obj_type = TREE_TYPE (TREE_TYPE (gnu_ptr));
7228 /* If this is a thin pointer, the object must have been allocated with
7229 the template in front of the array. So pass the template address,
7230 and get the total size. */
7231 if (TYPE_IS_THIN_POINTER_P (TREE_TYPE (gnu_ptr)))
7232 gnu_ptr
7233 = build_binary_op (POINTER_PLUS_EXPR, TREE_TYPE (gnu_ptr),
7234 gnu_ptr,
7235 fold_build1 (NEGATE_EXPR, sizetype,
7236 byte_position
7237 (DECL_CHAIN
7238 TYPE_FIELDS ((gnu_obj_type)))));
7240 /* If we have a special dynamic constrained subtype on the node, use
7241 it to compute the size; otherwise, use the designated subtype. */
7242 if (Present (Actual_Designated_Subtype (gnat_node)))
7244 gnu_actual_obj_type
7245 = gnat_to_gnu_type (Actual_Designated_Subtype (gnat_node));
7247 if (TYPE_IS_FAT_OR_THIN_POINTER_P (gnu_ptr_type))
7248 gnu_actual_obj_type
7249 = build_unc_object_type_from_ptr (gnu_ptr_type,
7250 gnu_actual_obj_type,
7251 get_identifier ("DEALLOC"),
7252 false);
7254 else
7255 gnu_actual_obj_type = gnu_obj_type;
7257 gnu_result
7258 = build_call_alloc_dealloc (gnu_ptr,
7259 TYPE_SIZE_UNIT (gnu_actual_obj_type),
7260 gnu_obj_type,
7261 Procedure_To_Call (gnat_node),
7262 Storage_Pool (gnat_node),
7263 gnat_node);
7265 break;
7267 case N_Raise_Constraint_Error:
7268 case N_Raise_Program_Error:
7269 case N_Raise_Storage_Error:
7270 if (type_annotate_only)
7271 gnu_result = alloc_stmt_list ();
7272 else
7273 gnu_result = Raise_Error_to_gnu (gnat_node, &gnu_result_type);
7274 break;
7276 case N_Validate_Unchecked_Conversion:
7277 /* The only validation we currently do on an unchecked conversion is
7278 that of aliasing assumptions. */
7279 if (flag_strict_aliasing)
7280 gnat_validate_uc_list.safe_push (gnat_node);
7281 gnu_result = alloc_stmt_list ();
7282 break;
7284 case N_Function_Specification:
7285 case N_Procedure_Specification:
7286 case N_Op_Concat:
7287 case N_Component_Association:
7288 case N_Protected_Body:
7289 case N_Task_Body:
7290 /* These nodes should only be present when annotating types. */
7291 gcc_assert (type_annotate_only);
7292 gnu_result = alloc_stmt_list ();
7293 break;
7295 default:
7296 /* Other nodes are not supposed to reach here. */
7297 gcc_unreachable ();
7300 /* If we pushed the processing of the elaboration routine, pop it back. */
7301 if (went_into_elab_proc)
7302 current_function_decl = NULL_TREE;
7304 /* When not optimizing, turn boolean rvalues B into B != false tests
7305 so that the code just below can put the location information of the
7306 reference to B on the inequality operator for better debug info. */
7307 if (!optimize
7308 && TREE_CODE (gnu_result) != INTEGER_CST
7309 && (kind == N_Identifier
7310 || kind == N_Expanded_Name
7311 || kind == N_Explicit_Dereference
7312 || kind == N_Function_Call
7313 || kind == N_Indexed_Component
7314 || kind == N_Selected_Component)
7315 && TREE_CODE (get_base_type (gnu_result_type)) == BOOLEAN_TYPE
7316 && !lvalue_required_p (gnat_node, gnu_result_type, false, false, false))
7317 gnu_result = build_binary_op (NE_EXPR, gnu_result_type,
7318 convert (gnu_result_type, gnu_result),
7319 convert (gnu_result_type,
7320 boolean_false_node));
7322 /* Set the location information on the result. Note that we may have
7323 no result if we tried to build a CALL_EXPR node to a procedure with
7324 no side-effects and optimization is enabled. */
7325 if (gnu_result && EXPR_P (gnu_result))
7326 set_gnu_expr_location_from_node (gnu_result, gnat_node);
7328 /* If we're supposed to return something of void_type, it means we have
7329 something we're elaborating for effect, so just return. */
7330 if (TREE_CODE (gnu_result_type) == VOID_TYPE)
7331 return gnu_result;
7333 /* If the result is a constant that overflowed, raise Constraint_Error. */
7334 if (TREE_CODE (gnu_result) == INTEGER_CST && TREE_OVERFLOW (gnu_result))
7336 post_error ("?`Constraint_Error` will be raised at run time", gnat_node);
7337 gnu_result
7338 = build1 (NULL_EXPR, gnu_result_type,
7339 build_call_raise (CE_Overflow_Check_Failed, gnat_node,
7340 N_Raise_Constraint_Error));
7343 /* If the result has side-effects and is of an unconstrained type, make a
7344 SAVE_EXPR so that we can be sure it will only be referenced once. But
7345 this is useless for a call to a function that returns an unconstrained
7346 type with default discriminant, as we cannot compute the size of the
7347 actual returned object. We must do this before any conversions. */
7348 if (TREE_SIDE_EFFECTS (gnu_result)
7349 && !(TREE_CODE (gnu_result) == CALL_EXPR
7350 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
7351 && (TREE_CODE (gnu_result_type) == UNCONSTRAINED_ARRAY_TYPE
7352 || CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))))
7353 gnu_result = gnat_stabilize_reference (gnu_result, false, NULL);
7355 /* Now convert the result to the result type, unless we are in one of the
7356 following cases:
7358 1. If this is the LHS of an assignment or an actual parameter of a
7359 call, return the result almost unmodified since the RHS will have
7360 to be converted to our type in that case, unless the result type
7361 has a simpler size. Likewise if there is just a no-op unchecked
7362 conversion in-between. Similarly, don't convert integral types
7363 that are the operands of an unchecked conversion since we need
7364 to ignore those conversions (for 'Valid).
7366 2. If we have a label (which doesn't have any well-defined type), a
7367 field or an error, return the result almost unmodified. Similarly,
7368 if the two types are record types with the same name, don't convert.
7369 This will be the case when we are converting from a packable version
7370 of a type to its original type and we need those conversions to be
7371 NOPs in order for assignments into these types to work properly.
7373 3. If the type is void or if we have no result, return error_mark_node
7374 to show we have no result.
7376 4. If this a call to a function that returns an unconstrained type with
7377 default discriminant, return the call expression unmodified since we
7378 cannot compute the size of the actual returned object.
7380 5. Finally, if the type of the result is already correct. */
7382 if (Present (Parent (gnat_node))
7383 && (lhs_or_actual_p (gnat_node)
7384 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
7385 && unchecked_conversion_nop (Parent (gnat_node)))
7386 || (Nkind (Parent (gnat_node)) == N_Unchecked_Type_Conversion
7387 && !AGGREGATE_TYPE_P (gnu_result_type)
7388 && !AGGREGATE_TYPE_P (TREE_TYPE (gnu_result))))
7389 && !(TYPE_SIZE (gnu_result_type)
7390 && TYPE_SIZE (TREE_TYPE (gnu_result))
7391 && (AGGREGATE_TYPE_P (gnu_result_type)
7392 == AGGREGATE_TYPE_P (TREE_TYPE (gnu_result)))
7393 && ((TREE_CODE (TYPE_SIZE (gnu_result_type)) == INTEGER_CST
7394 && (TREE_CODE (TYPE_SIZE (TREE_TYPE (gnu_result)))
7395 != INTEGER_CST))
7396 || (TREE_CODE (TYPE_SIZE (gnu_result_type)) != INTEGER_CST
7397 && !CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type))
7398 && (CONTAINS_PLACEHOLDER_P
7399 (TYPE_SIZE (TREE_TYPE (gnu_result))))))
7400 && !(TREE_CODE (gnu_result_type) == RECORD_TYPE
7401 && TYPE_JUSTIFIED_MODULAR_P (gnu_result_type))))
7403 /* Remove padding only if the inner object is of self-referential
7404 size: in that case it must be an object of unconstrained type
7405 with a default discriminant and we want to avoid copying too
7406 much data. */
7407 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result))
7408 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (TREE_TYPE (TYPE_FIELDS
7409 (TREE_TYPE (gnu_result))))))
7410 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
7411 gnu_result);
7414 else if (TREE_CODE (gnu_result) == LABEL_DECL
7415 || TREE_CODE (gnu_result) == FIELD_DECL
7416 || TREE_CODE (gnu_result) == ERROR_MARK
7417 || (TYPE_NAME (gnu_result_type)
7418 == TYPE_NAME (TREE_TYPE (gnu_result))
7419 && TREE_CODE (gnu_result_type) == RECORD_TYPE
7420 && TREE_CODE (TREE_TYPE (gnu_result)) == RECORD_TYPE))
7422 /* Remove any padding. */
7423 if (TYPE_IS_PADDING_P (TREE_TYPE (gnu_result)))
7424 gnu_result = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result))),
7425 gnu_result);
7428 else if (gnu_result == error_mark_node || gnu_result_type == void_type_node)
7429 gnu_result = error_mark_node;
7431 else if (TREE_CODE (gnu_result) == CALL_EXPR
7432 && TYPE_IS_PADDING_P (TREE_TYPE (gnu_result))
7433 && TREE_TYPE (TYPE_FIELDS (TREE_TYPE (gnu_result)))
7434 == gnu_result_type
7435 && CONTAINS_PLACEHOLDER_P (TYPE_SIZE (gnu_result_type)))
7438 else if (TREE_TYPE (gnu_result) != gnu_result_type)
7439 gnu_result = convert (gnu_result_type, gnu_result);
7441 /* We don't need any NOP_EXPR or NON_LVALUE_EXPR on the result. */
7442 while ((TREE_CODE (gnu_result) == NOP_EXPR
7443 || TREE_CODE (gnu_result) == NON_LVALUE_EXPR)
7444 && TREE_TYPE (TREE_OPERAND (gnu_result, 0)) == TREE_TYPE (gnu_result))
7445 gnu_result = TREE_OPERAND (gnu_result, 0);
7447 return gnu_result;
7450 /* Subroutine of above to push the exception label stack. GNU_STACK is
7451 a pointer to the stack to update and GNAT_LABEL, if present, is the
7452 label to push onto the stack. */
7454 static void
7455 push_exception_label_stack (vec<tree, va_gc> **gnu_stack, Entity_Id gnat_label)
7457 tree gnu_label = (Present (gnat_label)
7458 ? gnat_to_gnu_entity (gnat_label, NULL_TREE, 0)
7459 : NULL_TREE);
7461 vec_safe_push (*gnu_stack, gnu_label);
7464 /* Record the current code position in GNAT_NODE. */
7466 static void
7467 record_code_position (Node_Id gnat_node)
7469 tree stmt_stmt = build1 (STMT_STMT, void_type_node, NULL_TREE);
7471 add_stmt_with_node (stmt_stmt, gnat_node);
7472 save_gnu_tree (gnat_node, stmt_stmt, true);
7475 /* Insert the code for GNAT_NODE at the position saved for that node. */
7477 static void
7478 insert_code_for (Node_Id gnat_node)
7480 STMT_STMT_STMT (get_gnu_tree (gnat_node)) = gnat_to_gnu (gnat_node);
7481 save_gnu_tree (gnat_node, NULL_TREE, true);
7484 /* Start a new statement group chained to the previous group. */
7486 void
7487 start_stmt_group (void)
7489 struct stmt_group *group = stmt_group_free_list;
7491 /* First see if we can get one from the free list. */
7492 if (group)
7493 stmt_group_free_list = group->previous;
7494 else
7495 group = ggc_alloc<stmt_group> ();
7497 group->previous = current_stmt_group;
7498 group->stmt_list = group->block = group->cleanups = NULL_TREE;
7499 current_stmt_group = group;
7502 /* Add GNU_STMT to the current statement group. If it is an expression with
7503 no effects, it is ignored. */
7505 void
7506 add_stmt (tree gnu_stmt)
7508 append_to_statement_list (gnu_stmt, &current_stmt_group->stmt_list);
7511 /* Similar, but the statement is always added, regardless of side-effects. */
7513 void
7514 add_stmt_force (tree gnu_stmt)
7516 append_to_statement_list_force (gnu_stmt, &current_stmt_group->stmt_list);
7519 /* Like add_stmt, but set the location of GNU_STMT to that of GNAT_NODE. */
7521 void
7522 add_stmt_with_node (tree gnu_stmt, Node_Id gnat_node)
7524 /* Do not emit a location for renamings that come from generic instantiation,
7525 they are likely to disturb debugging. */
7526 if (Present (gnat_node)
7527 && !renaming_from_generic_instantiation_p (gnat_node))
7528 set_expr_location_from_node (gnu_stmt, gnat_node);
7529 add_stmt (gnu_stmt);
7532 /* Similar, but the statement is always added, regardless of side-effects. */
7534 void
7535 add_stmt_with_node_force (tree gnu_stmt, Node_Id gnat_node)
7537 if (Present (gnat_node))
7538 set_expr_location_from_node (gnu_stmt, gnat_node);
7539 add_stmt_force (gnu_stmt);
7542 /* Add a declaration statement for GNU_DECL to the current statement group.
7543 Get SLOC from Entity_Id. */
7545 void
7546 add_decl_expr (tree gnu_decl, Entity_Id gnat_entity)
7548 tree type = TREE_TYPE (gnu_decl);
7549 tree gnu_stmt, gnu_init, t;
7551 /* If this is a variable that Gigi is to ignore, we may have been given
7552 an ERROR_MARK. So test for it. We also might have been given a
7553 reference for a renaming. So only do something for a decl. Also
7554 ignore a TYPE_DECL for an UNCONSTRAINED_ARRAY_TYPE. */
7555 if (!DECL_P (gnu_decl)
7556 || (TREE_CODE (gnu_decl) == TYPE_DECL
7557 && TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE))
7558 return;
7560 gnu_stmt = build1 (DECL_EXPR, void_type_node, gnu_decl);
7562 /* If we are external or global, we don't want to output the DECL_EXPR for
7563 this DECL node since we already have evaluated the expressions in the
7564 sizes and positions as globals and doing it again would be wrong. */
7565 if (DECL_EXTERNAL (gnu_decl) || global_bindings_p ())
7567 /* Mark everything as used to prevent node sharing with subprograms.
7568 Note that walk_tree knows how to deal with TYPE_DECL, but neither
7569 VAR_DECL nor CONST_DECL. This appears to be somewhat arbitrary. */
7570 MARK_VISITED (gnu_stmt);
7571 if (TREE_CODE (gnu_decl) == VAR_DECL
7572 || TREE_CODE (gnu_decl) == CONST_DECL)
7574 MARK_VISITED (DECL_SIZE (gnu_decl));
7575 MARK_VISITED (DECL_SIZE_UNIT (gnu_decl));
7576 MARK_VISITED (DECL_INITIAL (gnu_decl));
7578 /* In any case, we have to deal with our own TYPE_ADA_SIZE field. */
7579 else if (TREE_CODE (gnu_decl) == TYPE_DECL
7580 && RECORD_OR_UNION_TYPE_P (type)
7581 && !TYPE_FAT_POINTER_P (type))
7582 MARK_VISITED (TYPE_ADA_SIZE (type));
7584 else
7585 add_stmt_with_node (gnu_stmt, gnat_entity);
7587 /* If this is a variable and an initializer is attached to it, it must be
7588 valid for the context. Similar to init_const in create_var_decl_1. */
7589 if (TREE_CODE (gnu_decl) == VAR_DECL
7590 && (gnu_init = DECL_INITIAL (gnu_decl)) != NULL_TREE
7591 && (!gnat_types_compatible_p (type, TREE_TYPE (gnu_init))
7592 || (TREE_STATIC (gnu_decl)
7593 && !initializer_constant_valid_p (gnu_init,
7594 TREE_TYPE (gnu_init)))))
7596 /* If GNU_DECL has a padded type, convert it to the unpadded
7597 type so the assignment is done properly. */
7598 if (TYPE_IS_PADDING_P (type))
7599 t = convert (TREE_TYPE (TYPE_FIELDS (type)), gnu_decl);
7600 else
7601 t = gnu_decl;
7603 gnu_stmt = build_binary_op (INIT_EXPR, NULL_TREE, t, gnu_init);
7605 DECL_INITIAL (gnu_decl) = NULL_TREE;
7606 if (TREE_READONLY (gnu_decl))
7608 TREE_READONLY (gnu_decl) = 0;
7609 DECL_READONLY_ONCE_ELAB (gnu_decl) = 1;
7612 add_stmt_with_node (gnu_stmt, gnat_entity);
7616 /* Callback for walk_tree to mark the visited trees rooted at *TP. */
7618 static tree
7619 mark_visited_r (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
7621 tree t = *tp;
7623 if (TREE_VISITED (t))
7624 *walk_subtrees = 0;
7626 /* Don't mark a dummy type as visited because we want to mark its sizes
7627 and fields once it's filled in. */
7628 else if (!TYPE_IS_DUMMY_P (t))
7629 TREE_VISITED (t) = 1;
7631 if (TYPE_P (t))
7632 TYPE_SIZES_GIMPLIFIED (t) = 1;
7634 return NULL_TREE;
7637 /* Mark nodes rooted at T with TREE_VISITED and types as having their
7638 sized gimplified. We use this to indicate all variable sizes and
7639 positions in global types may not be shared by any subprogram. */
7641 void
7642 mark_visited (tree t)
7644 walk_tree (&t, mark_visited_r, NULL, NULL);
7647 /* Add GNU_CLEANUP, a cleanup action, to the current code group and
7648 set its location to that of GNAT_NODE if present, but with column info
7649 cleared so that conditional branches generated as part of the cleanup
7650 code do not interfere with coverage analysis tools. */
7652 static void
7653 add_cleanup (tree gnu_cleanup, Node_Id gnat_node)
7655 if (Present (gnat_node))
7656 set_expr_location_from_node1 (gnu_cleanup, gnat_node, true);
7657 append_to_statement_list (gnu_cleanup, &current_stmt_group->cleanups);
7660 /* Set the BLOCK node corresponding to the current code group to GNU_BLOCK. */
7662 void
7663 set_block_for_group (tree gnu_block)
7665 gcc_assert (!current_stmt_group->block);
7666 current_stmt_group->block = gnu_block;
7669 /* Return code corresponding to the current code group. It is normally
7670 a STATEMENT_LIST, but may also be a BIND_EXPR or TRY_FINALLY_EXPR if
7671 BLOCK or cleanups were set. */
7673 tree
7674 end_stmt_group (void)
7676 struct stmt_group *group = current_stmt_group;
7677 tree gnu_retval = group->stmt_list;
7679 /* If this is a null list, allocate a new STATEMENT_LIST. Then, if there
7680 are cleanups, make a TRY_FINALLY_EXPR. Last, if there is a BLOCK,
7681 make a BIND_EXPR. Note that we nest in that because the cleanup may
7682 reference variables in the block. */
7683 if (gnu_retval == NULL_TREE)
7684 gnu_retval = alloc_stmt_list ();
7686 if (group->cleanups)
7687 gnu_retval = build2 (TRY_FINALLY_EXPR, void_type_node, gnu_retval,
7688 group->cleanups);
7690 if (current_stmt_group->block)
7691 gnu_retval = build3 (BIND_EXPR, void_type_node, BLOCK_VARS (group->block),
7692 gnu_retval, group->block);
7694 /* Remove this group from the stack and add it to the free list. */
7695 current_stmt_group = group->previous;
7696 group->previous = stmt_group_free_list;
7697 stmt_group_free_list = group;
7699 return gnu_retval;
7702 /* Return whether the current statement group may fall through. */
7704 static inline bool
7705 stmt_group_may_fallthru (void)
7707 if (current_stmt_group->stmt_list)
7708 return block_may_fallthru (current_stmt_group->stmt_list);
7709 else
7710 return true;
7713 /* Add a list of statements from GNAT_LIST, a possibly-empty list of
7714 statements.*/
7716 static void
7717 add_stmt_list (List_Id gnat_list)
7719 Node_Id gnat_node;
7721 if (Present (gnat_list))
7722 for (gnat_node = First (gnat_list); Present (gnat_node);
7723 gnat_node = Next (gnat_node))
7724 add_stmt (gnat_to_gnu (gnat_node));
7727 /* Build a tree from GNAT_LIST, a possibly-empty list of statements.
7728 If BINDING_P is true, push and pop a binding level around the list. */
7730 static tree
7731 build_stmt_group (List_Id gnat_list, bool binding_p)
7733 start_stmt_group ();
7734 if (binding_p)
7735 gnat_pushlevel ();
7737 add_stmt_list (gnat_list);
7738 if (binding_p)
7739 gnat_poplevel ();
7741 return end_stmt_group ();
7744 /* Generate GIMPLE in place for the expression at *EXPR_P. */
7747 gnat_gimplify_expr (tree *expr_p, gimple_seq *pre_p,
7748 gimple_seq *post_p ATTRIBUTE_UNUSED)
7750 tree expr = *expr_p;
7751 tree type = TREE_TYPE (expr);
7752 tree op;
7754 if (IS_ADA_STMT (expr))
7755 return gnat_gimplify_stmt (expr_p);
7757 switch (TREE_CODE (expr))
7759 case NULL_EXPR:
7760 /* If this is an aggregate type, build a null pointer of the appropriate
7761 type and dereference it. */
7762 if (AGGREGATE_TYPE_P (type)
7763 || TREE_CODE (type) == UNCONSTRAINED_ARRAY_TYPE)
7764 *expr_p = build_unary_op (INDIRECT_REF, NULL_TREE,
7765 convert (build_pointer_type (type),
7766 integer_zero_node));
7767 /* Otherwise, just make a VAR_DECL. */
7768 else
7770 *expr_p = create_tmp_var (type, NULL);
7771 TREE_NO_WARNING (*expr_p) = 1;
7774 gimplify_and_add (TREE_OPERAND (expr, 0), pre_p);
7775 return GS_OK;
7777 case UNCONSTRAINED_ARRAY_REF:
7778 /* We should only do this if we are just elaborating for side-effects,
7779 but we can't know that yet. */
7780 *expr_p = TREE_OPERAND (*expr_p, 0);
7781 return GS_OK;
7783 case ADDR_EXPR:
7784 op = TREE_OPERAND (expr, 0);
7786 /* If we are taking the address of a constant CONSTRUCTOR, make sure it
7787 is put into static memory. We know that it's going to be read-only
7788 given the semantics we have and it must be in static memory when the
7789 reference is in an elaboration procedure. */
7790 if (TREE_CODE (op) == CONSTRUCTOR && TREE_CONSTANT (op))
7792 tree addr = build_fold_addr_expr (tree_output_constant_def (op));
7793 *expr_p = fold_convert (type, addr);
7794 return GS_ALL_DONE;
7797 return GS_UNHANDLED;
7799 case VIEW_CONVERT_EXPR:
7800 op = TREE_OPERAND (expr, 0);
7802 /* If we are view-converting a CONSTRUCTOR or a call from an aggregate
7803 type to a scalar one, explicitly create the local temporary. That's
7804 required if the type is passed by reference. */
7805 if ((TREE_CODE (op) == CONSTRUCTOR || TREE_CODE (op) == CALL_EXPR)
7806 && AGGREGATE_TYPE_P (TREE_TYPE (op))
7807 && !AGGREGATE_TYPE_P (type))
7809 tree mod, new_var = create_tmp_var_raw (TREE_TYPE (op), "C");
7810 gimple_add_tmp_var (new_var);
7812 mod = build2 (INIT_EXPR, TREE_TYPE (new_var), new_var, op);
7813 gimplify_and_add (mod, pre_p);
7815 TREE_OPERAND (expr, 0) = new_var;
7816 return GS_OK;
7819 return GS_UNHANDLED;
7821 case DECL_EXPR:
7822 op = DECL_EXPR_DECL (expr);
7824 /* The expressions for the RM bounds must be gimplified to ensure that
7825 they are properly elaborated. See gimplify_decl_expr. */
7826 if ((TREE_CODE (op) == TYPE_DECL || TREE_CODE (op) == VAR_DECL)
7827 && !TYPE_SIZES_GIMPLIFIED (TREE_TYPE (op)))
7828 switch (TREE_CODE (TREE_TYPE (op)))
7830 case INTEGER_TYPE:
7831 case ENUMERAL_TYPE:
7832 case BOOLEAN_TYPE:
7833 case REAL_TYPE:
7835 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (op)), t, val;
7837 val = TYPE_RM_MIN_VALUE (type);
7838 if (val)
7840 gimplify_one_sizepos (&val, pre_p);
7841 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
7842 SET_TYPE_RM_MIN_VALUE (t, val);
7845 val = TYPE_RM_MAX_VALUE (type);
7846 if (val)
7848 gimplify_one_sizepos (&val, pre_p);
7849 for (t = type; t; t = TYPE_NEXT_VARIANT (t))
7850 SET_TYPE_RM_MAX_VALUE (t, val);
7854 break;
7856 default:
7857 break;
7860 /* ... fall through ... */
7862 default:
7863 return GS_UNHANDLED;
7867 /* Generate GIMPLE in place for the statement at *STMT_P. */
7869 static enum gimplify_status
7870 gnat_gimplify_stmt (tree *stmt_p)
7872 tree stmt = *stmt_p;
7874 switch (TREE_CODE (stmt))
7876 case STMT_STMT:
7877 *stmt_p = STMT_STMT_STMT (stmt);
7878 return GS_OK;
7880 case LOOP_STMT:
7882 tree gnu_start_label = create_artificial_label (input_location);
7883 tree gnu_cond = LOOP_STMT_COND (stmt);
7884 tree gnu_update = LOOP_STMT_UPDATE (stmt);
7885 tree gnu_end_label = LOOP_STMT_LABEL (stmt);
7887 /* Build the condition expression from the test, if any. */
7888 if (gnu_cond)
7890 /* Deal with the optimization hints. */
7891 if (LOOP_STMT_IVDEP (stmt))
7892 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
7893 build_int_cst (integer_type_node,
7894 annot_expr_ivdep_kind));
7895 if (LOOP_STMT_NO_VECTOR (stmt))
7896 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
7897 build_int_cst (integer_type_node,
7898 annot_expr_no_vector_kind));
7899 if (LOOP_STMT_VECTOR (stmt))
7900 gnu_cond = build2 (ANNOTATE_EXPR, TREE_TYPE (gnu_cond), gnu_cond,
7901 build_int_cst (integer_type_node,
7902 annot_expr_vector_kind));
7904 gnu_cond
7905 = build3 (COND_EXPR, void_type_node, gnu_cond, NULL_TREE,
7906 build1 (GOTO_EXPR, void_type_node, gnu_end_label));
7909 /* Set to emit the statements of the loop. */
7910 *stmt_p = NULL_TREE;
7912 /* We first emit the start label and then a conditional jump to the
7913 end label if there's a top condition, then the update if it's at
7914 the top, then the body of the loop, then a conditional jump to
7915 the end label if there's a bottom condition, then the update if
7916 it's at the bottom, and finally a jump to the start label and the
7917 definition of the end label. */
7918 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
7919 gnu_start_label),
7920 stmt_p);
7922 if (gnu_cond && !LOOP_STMT_BOTTOM_COND_P (stmt))
7923 append_to_statement_list (gnu_cond, stmt_p);
7925 if (gnu_update && LOOP_STMT_TOP_UPDATE_P (stmt))
7926 append_to_statement_list (gnu_update, stmt_p);
7928 append_to_statement_list (LOOP_STMT_BODY (stmt), stmt_p);
7930 if (gnu_cond && LOOP_STMT_BOTTOM_COND_P (stmt))
7931 append_to_statement_list (gnu_cond, stmt_p);
7933 if (gnu_update && !LOOP_STMT_TOP_UPDATE_P (stmt))
7934 append_to_statement_list (gnu_update, stmt_p);
7936 tree t = build1 (GOTO_EXPR, void_type_node, gnu_start_label);
7937 SET_EXPR_LOCATION (t, DECL_SOURCE_LOCATION (gnu_end_label));
7938 append_to_statement_list (t, stmt_p);
7940 append_to_statement_list (build1 (LABEL_EXPR, void_type_node,
7941 gnu_end_label),
7942 stmt_p);
7943 return GS_OK;
7946 case EXIT_STMT:
7947 /* Build a statement to jump to the corresponding end label, then
7948 see if it needs to be conditional. */
7949 *stmt_p = build1 (GOTO_EXPR, void_type_node, EXIT_STMT_LABEL (stmt));
7950 if (EXIT_STMT_COND (stmt))
7951 *stmt_p = build3 (COND_EXPR, void_type_node,
7952 EXIT_STMT_COND (stmt), *stmt_p, alloc_stmt_list ());
7953 return GS_OK;
7955 default:
7956 gcc_unreachable ();
7960 /* Force references to each of the entities in packages withed by GNAT_NODE.
7961 Operate recursively but check that we aren't elaborating something more
7962 than once.
7964 This routine is exclusively called in type_annotate mode, to compute DDA
7965 information for types in withed units, for ASIS use. */
7967 static void
7968 elaborate_all_entities (Node_Id gnat_node)
7970 Entity_Id gnat_with_clause, gnat_entity;
7972 /* Process each unit only once. As we trace the context of all relevant
7973 units transitively, including generic bodies, we may encounter the
7974 same generic unit repeatedly. */
7975 if (!present_gnu_tree (gnat_node))
7976 save_gnu_tree (gnat_node, integer_zero_node, true);
7978 /* Save entities in all context units. A body may have an implicit_with
7979 on its own spec, if the context includes a child unit, so don't save
7980 the spec twice. */
7981 for (gnat_with_clause = First (Context_Items (gnat_node));
7982 Present (gnat_with_clause);
7983 gnat_with_clause = Next (gnat_with_clause))
7984 if (Nkind (gnat_with_clause) == N_With_Clause
7985 && !present_gnu_tree (Library_Unit (gnat_with_clause))
7986 && Library_Unit (gnat_with_clause) != Library_Unit (Cunit (Main_Unit)))
7988 elaborate_all_entities (Library_Unit (gnat_with_clause));
7990 if (Ekind (Entity (Name (gnat_with_clause))) == E_Package)
7992 for (gnat_entity = First_Entity (Entity (Name (gnat_with_clause)));
7993 Present (gnat_entity);
7994 gnat_entity = Next_Entity (gnat_entity))
7995 if (Is_Public (gnat_entity)
7996 && Convention (gnat_entity) != Convention_Intrinsic
7997 && Ekind (gnat_entity) != E_Package
7998 && Ekind (gnat_entity) != E_Package_Body
7999 && Ekind (gnat_entity) != E_Operator
8000 && !(IN (Ekind (gnat_entity), Type_Kind)
8001 && !Is_Frozen (gnat_entity))
8002 && !((Ekind (gnat_entity) == E_Procedure
8003 || Ekind (gnat_entity) == E_Function)
8004 && Is_Intrinsic_Subprogram (gnat_entity))
8005 && !IN (Ekind (gnat_entity), Named_Kind)
8006 && !IN (Ekind (gnat_entity), Generic_Unit_Kind))
8007 gnat_to_gnu_entity (gnat_entity, NULL_TREE, 0);
8009 else if (Ekind (Entity (Name (gnat_with_clause))) == E_Generic_Package)
8011 Node_Id gnat_body
8012 = Corresponding_Body (Unit (Library_Unit (gnat_with_clause)));
8014 /* Retrieve compilation unit node of generic body. */
8015 while (Present (gnat_body)
8016 && Nkind (gnat_body) != N_Compilation_Unit)
8017 gnat_body = Parent (gnat_body);
8019 /* If body is available, elaborate its context. */
8020 if (Present (gnat_body))
8021 elaborate_all_entities (gnat_body);
8025 if (Nkind (Unit (gnat_node)) == N_Package_Body)
8026 elaborate_all_entities (Library_Unit (gnat_node));
8029 /* Do the processing of GNAT_NODE, an N_Freeze_Entity. */
8031 static void
8032 process_freeze_entity (Node_Id gnat_node)
8034 const Entity_Id gnat_entity = Entity (gnat_node);
8035 const Entity_Kind kind = Ekind (gnat_entity);
8036 tree gnu_old, gnu_new;
8038 /* If this is a package, we need to generate code for the package. */
8039 if (kind == E_Package)
8041 insert_code_for
8042 (Parent (Corresponding_Body
8043 (Parent (Declaration_Node (gnat_entity)))));
8044 return;
8047 /* Don't do anything for class-wide types as they are always transformed
8048 into their root type. */
8049 if (kind == E_Class_Wide_Type)
8050 return;
8052 /* Check for an old definition. This freeze node might be for an Itype. */
8053 gnu_old
8054 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : NULL_TREE;
8056 /* If this entity has an address representation clause, GNU_OLD is the
8057 address, so discard it here. */
8058 if (Present (Address_Clause (gnat_entity)))
8059 gnu_old = NULL_TREE;
8061 /* Don't do anything for subprograms that may have been elaborated before
8062 their freeze nodes. This can happen, for example, because of an inner
8063 call in an instance body or because of previous compilation of a spec
8064 for inlining purposes. */
8065 if (gnu_old
8066 && ((TREE_CODE (gnu_old) == FUNCTION_DECL
8067 && (kind == E_Function || kind == E_Procedure))
8068 || (TREE_CODE (TREE_TYPE (gnu_old)) == FUNCTION_TYPE
8069 && kind == E_Subprogram_Type)))
8070 return;
8072 /* If we have a non-dummy type old tree, we have nothing to do, except
8073 aborting if this is the public view of a private type whose full view was
8074 not delayed, as this node was never delayed as it should have been. We
8075 let this happen for concurrent types and their Corresponding_Record_Type,
8076 however, because each might legitimately be elaborated before its own
8077 freeze node, e.g. while processing the other. */
8078 if (gnu_old
8079 && !(TREE_CODE (gnu_old) == TYPE_DECL
8080 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old))))
8082 gcc_assert ((IN (kind, Incomplete_Or_Private_Kind)
8083 && Present (Full_View (gnat_entity))
8084 && No (Freeze_Node (Full_View (gnat_entity))))
8085 || Is_Concurrent_Type (gnat_entity)
8086 || (IN (kind, Record_Kind)
8087 && Is_Concurrent_Record_Type (gnat_entity)));
8088 return;
8091 /* Reset the saved tree, if any, and elaborate the object or type for real.
8092 If there is a full view, elaborate it and use the result. And, if this
8093 is the root type of a class-wide type, reuse it for the latter. */
8094 if (gnu_old)
8096 save_gnu_tree (gnat_entity, NULL_TREE, false);
8098 if (IN (kind, Incomplete_Or_Private_Kind)
8099 && Present (Full_View (gnat_entity)))
8101 Entity_Id full_view = Full_View (gnat_entity);
8103 save_gnu_tree (full_view, NULL_TREE, false);
8105 if (IN (Ekind (full_view), Private_Kind)
8106 && Present (Underlying_Full_View (full_view)))
8108 full_view = Underlying_Full_View (full_view);
8109 save_gnu_tree (full_view, NULL_TREE, false);
8113 if (IN (kind, Type_Kind)
8114 && Present (Class_Wide_Type (gnat_entity))
8115 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
8116 save_gnu_tree (Class_Wide_Type (gnat_entity), NULL_TREE, false);
8119 if (IN (kind, Incomplete_Or_Private_Kind)
8120 && Present (Full_View (gnat_entity)))
8122 Entity_Id full_view = Full_View (gnat_entity);
8124 if (IN (Ekind (full_view), Private_Kind)
8125 && Present (Underlying_Full_View (full_view)))
8126 full_view = Underlying_Full_View (full_view);
8128 gnu_new = gnat_to_gnu_entity (full_view, NULL_TREE, 1);
8130 /* Propagate back-annotations from full view to partial view. */
8131 if (Unknown_Alignment (gnat_entity))
8132 Set_Alignment (gnat_entity, Alignment (full_view));
8134 if (Unknown_Esize (gnat_entity))
8135 Set_Esize (gnat_entity, Esize (full_view));
8137 if (Unknown_RM_Size (gnat_entity))
8138 Set_RM_Size (gnat_entity, RM_Size (full_view));
8140 /* The above call may have defined this entity (the simplest example
8141 of this is when we have a private enumeral type since the bounds
8142 will have the public view). */
8143 if (!present_gnu_tree (gnat_entity))
8144 save_gnu_tree (gnat_entity, gnu_new, false);
8146 else
8148 tree gnu_init
8149 = (Nkind (Declaration_Node (gnat_entity)) == N_Object_Declaration
8150 && present_gnu_tree (Declaration_Node (gnat_entity)))
8151 ? get_gnu_tree (Declaration_Node (gnat_entity)) : NULL_TREE;
8153 gnu_new = gnat_to_gnu_entity (gnat_entity, gnu_init, 1);
8156 if (IN (kind, Type_Kind)
8157 && Present (Class_Wide_Type (gnat_entity))
8158 && Root_Type (Class_Wide_Type (gnat_entity)) == gnat_entity)
8159 save_gnu_tree (Class_Wide_Type (gnat_entity), gnu_new, false);
8161 /* If we have an old type and we've made pointers to this type, update those
8162 pointers. If this is a Taft amendment type in the main unit, we need to
8163 mark the type as used since other units referencing it don't see the full
8164 declaration and, therefore, cannot mark it as used themselves. */
8165 if (gnu_old)
8167 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
8168 TREE_TYPE (gnu_new));
8169 if (DECL_TAFT_TYPE_P (gnu_old))
8170 used_types_insert (TREE_TYPE (gnu_new));
8174 /* Elaborate decls in the lists GNAT_DECLS and GNAT_DECLS2, if present.
8175 We make two passes, one to elaborate anything other than bodies (but
8176 we declare a function if there was no spec). The second pass
8177 elaborates the bodies.
8179 GNAT_END_LIST gives the element in the list past the end. Normally,
8180 this is Empty, but can be First_Real_Statement for a
8181 Handled_Sequence_Of_Statements.
8183 We make a complete pass through both lists if PASS1P is true, then make
8184 the second pass over both lists if PASS2P is true. The lists usually
8185 correspond to the public and private parts of a package. */
8187 static void
8188 process_decls (List_Id gnat_decls, List_Id gnat_decls2,
8189 Node_Id gnat_end_list, bool pass1p, bool pass2p)
8191 List_Id gnat_decl_array[2];
8192 Node_Id gnat_decl;
8193 int i;
8195 gnat_decl_array[0] = gnat_decls, gnat_decl_array[1] = gnat_decls2;
8197 if (pass1p)
8198 for (i = 0; i <= 1; i++)
8199 if (Present (gnat_decl_array[i]))
8200 for (gnat_decl = First (gnat_decl_array[i]);
8201 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
8203 /* For package specs, we recurse inside the declarations,
8204 thus taking the two pass approach inside the boundary. */
8205 if (Nkind (gnat_decl) == N_Package_Declaration
8206 && (Nkind (Specification (gnat_decl)
8207 == N_Package_Specification)))
8208 process_decls (Visible_Declarations (Specification (gnat_decl)),
8209 Private_Declarations (Specification (gnat_decl)),
8210 Empty, true, false);
8212 /* Similarly for any declarations in the actions of a
8213 freeze node. */
8214 else if (Nkind (gnat_decl) == N_Freeze_Entity)
8216 process_freeze_entity (gnat_decl);
8217 process_decls (Actions (gnat_decl), Empty, Empty, true, false);
8220 /* Package bodies with freeze nodes get their elaboration deferred
8221 until the freeze node, but the code must be placed in the right
8222 place, so record the code position now. */
8223 else if (Nkind (gnat_decl) == N_Package_Body
8224 && Present (Freeze_Node (Corresponding_Spec (gnat_decl))))
8225 record_code_position (gnat_decl);
8227 else if (Nkind (gnat_decl) == N_Package_Body_Stub
8228 && Present (Library_Unit (gnat_decl))
8229 && Present (Freeze_Node
8230 (Corresponding_Spec
8231 (Proper_Body (Unit
8232 (Library_Unit (gnat_decl)))))))
8233 record_code_position
8234 (Proper_Body (Unit (Library_Unit (gnat_decl))));
8236 /* We defer most subprogram bodies to the second pass. */
8237 else if (Nkind (gnat_decl) == N_Subprogram_Body)
8239 if (Acts_As_Spec (gnat_decl))
8241 Node_Id gnat_subprog_id = Defining_Entity (gnat_decl);
8243 if (Ekind (gnat_subprog_id) != E_Generic_Procedure
8244 && Ekind (gnat_subprog_id) != E_Generic_Function)
8245 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
8249 /* For bodies and stubs that act as their own specs, the entity
8250 itself must be elaborated in the first pass, because it may
8251 be used in other declarations. */
8252 else if (Nkind (gnat_decl) == N_Subprogram_Body_Stub)
8254 Node_Id gnat_subprog_id
8255 = Defining_Entity (Specification (gnat_decl));
8257 if (Ekind (gnat_subprog_id) != E_Subprogram_Body
8258 && Ekind (gnat_subprog_id) != E_Generic_Procedure
8259 && Ekind (gnat_subprog_id) != E_Generic_Function)
8260 gnat_to_gnu_entity (gnat_subprog_id, NULL_TREE, 1);
8263 /* Concurrent stubs stand for the corresponding subprogram bodies,
8264 which are deferred like other bodies. */
8265 else if (Nkind (gnat_decl) == N_Task_Body_Stub
8266 || Nkind (gnat_decl) == N_Protected_Body_Stub)
8269 else
8270 add_stmt (gnat_to_gnu (gnat_decl));
8273 /* Here we elaborate everything we deferred above except for package bodies,
8274 which are elaborated at their freeze nodes. Note that we must also
8275 go inside things (package specs and freeze nodes) the first pass did. */
8276 if (pass2p)
8277 for (i = 0; i <= 1; i++)
8278 if (Present (gnat_decl_array[i]))
8279 for (gnat_decl = First (gnat_decl_array[i]);
8280 gnat_decl != gnat_end_list; gnat_decl = Next (gnat_decl))
8282 if (Nkind (gnat_decl) == N_Subprogram_Body
8283 || Nkind (gnat_decl) == N_Subprogram_Body_Stub
8284 || Nkind (gnat_decl) == N_Task_Body_Stub
8285 || Nkind (gnat_decl) == N_Protected_Body_Stub)
8286 add_stmt (gnat_to_gnu (gnat_decl));
8288 else if (Nkind (gnat_decl) == N_Package_Declaration
8289 && (Nkind (Specification (gnat_decl)
8290 == N_Package_Specification)))
8291 process_decls (Visible_Declarations (Specification (gnat_decl)),
8292 Private_Declarations (Specification (gnat_decl)),
8293 Empty, false, true);
8295 else if (Nkind (gnat_decl) == N_Freeze_Entity)
8296 process_decls (Actions (gnat_decl), Empty, Empty, false, true);
8300 /* Make a unary operation of kind CODE using build_unary_op, but guard
8301 the operation by an overflow check. CODE can be one of NEGATE_EXPR
8302 or ABS_EXPR. GNU_TYPE is the type desired for the result. Usually
8303 the operation is to be performed in that type. GNAT_NODE is the gnat
8304 node conveying the source location for which the error should be
8305 signaled. */
8307 static tree
8308 build_unary_op_trapv (enum tree_code code, tree gnu_type, tree operand,
8309 Node_Id gnat_node)
8311 gcc_assert (code == NEGATE_EXPR || code == ABS_EXPR);
8313 operand = gnat_protect_expr (operand);
8315 return emit_check (build_binary_op (EQ_EXPR, boolean_type_node,
8316 operand, TYPE_MIN_VALUE (gnu_type)),
8317 build_unary_op (code, gnu_type, operand),
8318 CE_Overflow_Check_Failed, gnat_node);
8321 /* Make a binary operation of kind CODE using build_binary_op, but guard
8322 the operation by an overflow check. CODE can be one of PLUS_EXPR,
8323 MINUS_EXPR or MULT_EXPR. GNU_TYPE is the type desired for the result.
8324 Usually the operation is to be performed in that type. GNAT_NODE is
8325 the GNAT node conveying the source location for which the error should
8326 be signaled. */
8328 static tree
8329 build_binary_op_trapv (enum tree_code code, tree gnu_type, tree left,
8330 tree right, Node_Id gnat_node)
8332 const unsigned int precision = TYPE_PRECISION (gnu_type);
8333 tree lhs = gnat_protect_expr (left);
8334 tree rhs = gnat_protect_expr (right);
8335 tree type_max = TYPE_MAX_VALUE (gnu_type);
8336 tree type_min = TYPE_MIN_VALUE (gnu_type);
8337 tree zero = convert (gnu_type, integer_zero_node);
8338 tree gnu_expr, rhs_lt_zero, tmp1, tmp2;
8339 tree check_pos, check_neg, check;
8341 /* Assert that the precision is a power of 2. */
8342 gcc_assert ((precision & (precision - 1)) == 0);
8344 /* Prefer a constant or known-positive rhs to simplify checks. */
8345 if (!TREE_CONSTANT (rhs)
8346 && commutative_tree_code (code)
8347 && (TREE_CONSTANT (lhs)
8348 || (!tree_expr_nonnegative_p (rhs)
8349 && tree_expr_nonnegative_p (lhs))))
8351 tree tmp = lhs;
8352 lhs = rhs;
8353 rhs = tmp;
8356 gnu_expr = build_binary_op (code, gnu_type, lhs, rhs);
8358 /* If we can fold the expression to a constant, just return it.
8359 The caller will deal with overflow, no need to generate a check. */
8360 if (TREE_CONSTANT (gnu_expr))
8361 return gnu_expr;
8363 rhs_lt_zero = tree_expr_nonnegative_p (rhs)
8364 ? boolean_false_node
8365 : build_binary_op (LT_EXPR, boolean_type_node, rhs, zero);
8367 /* ??? Should use more efficient check for operand_equal_p (lhs, rhs, 0) */
8369 /* Try a few strategies that may be cheaper than the general
8370 code at the end of the function, if the rhs is not known.
8371 The strategies are:
8372 - Call library function for 64-bit multiplication (complex)
8373 - Widen, if input arguments are sufficiently small
8374 - Determine overflow using wrapped result for addition/subtraction. */
8376 if (!TREE_CONSTANT (rhs))
8378 /* Even for add/subtract double size to get another base type. */
8379 const unsigned int needed_precision = precision * 2;
8381 if (code == MULT_EXPR && precision == 64)
8383 tree int_64 = gnat_type_for_size (64, 0);
8385 return convert (gnu_type, build_call_n_expr (mulv64_decl, 2,
8386 convert (int_64, lhs),
8387 convert (int_64, rhs)));
8390 if (needed_precision <= BITS_PER_WORD
8391 || (code == MULT_EXPR && needed_precision <= LONG_LONG_TYPE_SIZE))
8393 tree wide_type = gnat_type_for_size (needed_precision, 0);
8394 tree wide_result = build_binary_op (code, wide_type,
8395 convert (wide_type, lhs),
8396 convert (wide_type, rhs));
8398 check = build_binary_op
8399 (TRUTH_ORIF_EXPR, boolean_type_node,
8400 build_binary_op (LT_EXPR, boolean_type_node, wide_result,
8401 convert (wide_type, type_min)),
8402 build_binary_op (GT_EXPR, boolean_type_node, wide_result,
8403 convert (wide_type, type_max)));
8405 return
8406 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8409 if (code == PLUS_EXPR || code == MINUS_EXPR)
8411 tree unsigned_type = gnat_type_for_size (precision, 1);
8412 tree wrapped_expr
8413 = convert (gnu_type,
8414 build_binary_op (code, unsigned_type,
8415 convert (unsigned_type, lhs),
8416 convert (unsigned_type, rhs)));
8418 /* Overflow when (rhs < 0) ^ (wrapped_expr < lhs)), for addition
8419 or when (rhs < 0) ^ (wrapped_expr > lhs) for subtraction. */
8420 check
8421 = build_binary_op (TRUTH_XOR_EXPR, boolean_type_node, rhs_lt_zero,
8422 build_binary_op (code == PLUS_EXPR
8423 ? LT_EXPR : GT_EXPR,
8424 boolean_type_node,
8425 wrapped_expr, lhs));
8427 return
8428 emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8432 switch (code)
8434 case PLUS_EXPR:
8435 /* When rhs >= 0, overflow when lhs > type_max - rhs. */
8436 check_pos = build_binary_op (GT_EXPR, boolean_type_node, lhs,
8437 build_binary_op (MINUS_EXPR, gnu_type,
8438 type_max, rhs)),
8440 /* When rhs < 0, overflow when lhs < type_min - rhs. */
8441 check_neg = build_binary_op (LT_EXPR, boolean_type_node, lhs,
8442 build_binary_op (MINUS_EXPR, gnu_type,
8443 type_min, rhs));
8444 break;
8446 case MINUS_EXPR:
8447 /* When rhs >= 0, overflow when lhs < type_min + rhs. */
8448 check_pos = build_binary_op (LT_EXPR, boolean_type_node, lhs,
8449 build_binary_op (PLUS_EXPR, gnu_type,
8450 type_min, rhs)),
8452 /* When rhs < 0, overflow when lhs > type_max + rhs. */
8453 check_neg = build_binary_op (GT_EXPR, boolean_type_node, lhs,
8454 build_binary_op (PLUS_EXPR, gnu_type,
8455 type_max, rhs));
8456 break;
8458 case MULT_EXPR:
8459 /* The check here is designed to be efficient if the rhs is constant,
8460 but it will work for any rhs by using integer division.
8461 Four different check expressions determine whether X * C overflows,
8462 depending on C.
8463 C == 0 => false
8464 C > 0 => X > type_max / C || X < type_min / C
8465 C == -1 => X == type_min
8466 C < -1 => X > type_min / C || X < type_max / C */
8468 tmp1 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_max, rhs);
8469 tmp2 = build_binary_op (TRUNC_DIV_EXPR, gnu_type, type_min, rhs);
8471 check_pos
8472 = build_binary_op (TRUTH_ANDIF_EXPR, boolean_type_node,
8473 build_binary_op (NE_EXPR, boolean_type_node, zero,
8474 rhs),
8475 build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8476 build_binary_op (GT_EXPR,
8477 boolean_type_node,
8478 lhs, tmp1),
8479 build_binary_op (LT_EXPR,
8480 boolean_type_node,
8481 lhs, tmp2)));
8483 check_neg
8484 = fold_build3 (COND_EXPR, boolean_type_node,
8485 build_binary_op (EQ_EXPR, boolean_type_node, rhs,
8486 build_int_cst (gnu_type, -1)),
8487 build_binary_op (EQ_EXPR, boolean_type_node, lhs,
8488 type_min),
8489 build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8490 build_binary_op (GT_EXPR,
8491 boolean_type_node,
8492 lhs, tmp2),
8493 build_binary_op (LT_EXPR,
8494 boolean_type_node,
8495 lhs, tmp1)));
8496 break;
8498 default:
8499 gcc_unreachable();
8502 check = fold_build3 (COND_EXPR, boolean_type_node, rhs_lt_zero, check_neg,
8503 check_pos);
8505 return emit_check (check, gnu_expr, CE_Overflow_Check_Failed, gnat_node);
8508 /* Emit code for a range check. GNU_EXPR is the expression to be checked,
8509 GNAT_RANGE_TYPE the gnat type or subtype containing the bounds against
8510 which we have to check. GNAT_NODE is the GNAT node conveying the source
8511 location for which the error should be signaled. */
8513 static tree
8514 emit_range_check (tree gnu_expr, Entity_Id gnat_range_type, Node_Id gnat_node)
8516 tree gnu_range_type = get_unpadded_type (gnat_range_type);
8517 tree gnu_compare_type = get_base_type (TREE_TYPE (gnu_expr));
8519 /* If GNU_EXPR has GNAT_RANGE_TYPE as its base type, no check is needed.
8520 This can for example happen when translating 'Val or 'Value. */
8521 if (gnu_compare_type == gnu_range_type)
8522 return gnu_expr;
8524 /* Range checks can only be applied to types with ranges. */
8525 gcc_assert (INTEGRAL_TYPE_P (gnu_range_type)
8526 || SCALAR_FLOAT_TYPE_P (gnu_range_type));
8528 /* If GNU_EXPR has an integral type that is narrower than GNU_RANGE_TYPE,
8529 we can't do anything since we might be truncating the bounds. No
8530 check is needed in this case. */
8531 if (INTEGRAL_TYPE_P (TREE_TYPE (gnu_expr))
8532 && (TYPE_PRECISION (gnu_compare_type)
8533 < TYPE_PRECISION (get_base_type (gnu_range_type))))
8534 return gnu_expr;
8536 /* Checked expressions must be evaluated only once. */
8537 gnu_expr = gnat_protect_expr (gnu_expr);
8539 /* Note that the form of the check is
8540 (not (expr >= lo)) or (not (expr <= hi))
8541 the reason for this slightly convoluted form is that NaNs
8542 are not considered to be in range in the float case. */
8543 return emit_check
8544 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8545 invert_truthvalue
8546 (build_binary_op (GE_EXPR, boolean_type_node,
8547 convert (gnu_compare_type, gnu_expr),
8548 convert (gnu_compare_type,
8549 TYPE_MIN_VALUE
8550 (gnu_range_type)))),
8551 invert_truthvalue
8552 (build_binary_op (LE_EXPR, boolean_type_node,
8553 convert (gnu_compare_type, gnu_expr),
8554 convert (gnu_compare_type,
8555 TYPE_MAX_VALUE
8556 (gnu_range_type))))),
8557 gnu_expr, CE_Range_Check_Failed, gnat_node);
8560 /* Emit code for an index check. GNU_ARRAY_OBJECT is the array object which
8561 we are about to index, GNU_EXPR is the index expression to be checked,
8562 GNU_LOW and GNU_HIGH are the lower and upper bounds against which GNU_EXPR
8563 has to be checked. Note that for index checking we cannot simply use the
8564 emit_range_check function (although very similar code needs to be generated
8565 in both cases) since for index checking the array type against which we are
8566 checking the indices may be unconstrained and consequently we need to get
8567 the actual index bounds from the array object itself (GNU_ARRAY_OBJECT).
8568 The place where we need to do that is in subprograms having unconstrained
8569 array formal parameters. GNAT_NODE is the GNAT node conveying the source
8570 location for which the error should be signaled. */
8572 static tree
8573 emit_index_check (tree gnu_array_object, tree gnu_expr, tree gnu_low,
8574 tree gnu_high, Node_Id gnat_node)
8576 tree gnu_expr_check;
8578 /* Checked expressions must be evaluated only once. */
8579 gnu_expr = gnat_protect_expr (gnu_expr);
8581 /* Must do this computation in the base type in case the expression's
8582 type is an unsigned subtypes. */
8583 gnu_expr_check = convert (get_base_type (TREE_TYPE (gnu_expr)), gnu_expr);
8585 /* If GNU_LOW or GNU_HIGH are a PLACEHOLDER_EXPR, qualify them by
8586 the object we are handling. */
8587 gnu_low = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_low, gnu_array_object);
8588 gnu_high = SUBSTITUTE_PLACEHOLDER_IN_EXPR (gnu_high, gnu_array_object);
8590 return emit_check
8591 (build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node,
8592 build_binary_op (LT_EXPR, boolean_type_node,
8593 gnu_expr_check,
8594 convert (TREE_TYPE (gnu_expr_check),
8595 gnu_low)),
8596 build_binary_op (GT_EXPR, boolean_type_node,
8597 gnu_expr_check,
8598 convert (TREE_TYPE (gnu_expr_check),
8599 gnu_high))),
8600 gnu_expr, CE_Index_Check_Failed, gnat_node);
8603 /* GNU_COND contains the condition corresponding to an access, discriminant or
8604 range check of value GNU_EXPR. Build a COND_EXPR that returns GNU_EXPR if
8605 GNU_COND is false and raises a CONSTRAINT_ERROR if GNU_COND is true.
8606 REASON is the code that says why the exception was raised. GNAT_NODE is
8607 the GNAT node conveying the source location for which the error should be
8608 signaled. */
8610 static tree
8611 emit_check (tree gnu_cond, tree gnu_expr, int reason, Node_Id gnat_node)
8613 tree gnu_call
8614 = build_call_raise (reason, gnat_node, N_Raise_Constraint_Error);
8615 tree gnu_result
8616 = fold_build3 (COND_EXPR, TREE_TYPE (gnu_expr), gnu_cond,
8617 build2 (COMPOUND_EXPR, TREE_TYPE (gnu_expr), gnu_call,
8618 convert (TREE_TYPE (gnu_expr), integer_zero_node)),
8619 gnu_expr);
8621 /* GNU_RESULT has side effects if and only if GNU_EXPR has:
8622 we don't need to evaluate it just for the check. */
8623 TREE_SIDE_EFFECTS (gnu_result) = TREE_SIDE_EFFECTS (gnu_expr);
8625 return gnu_result;
8628 /* Return an expression that converts GNU_EXPR to GNAT_TYPE, doing overflow
8629 checks if OVERFLOW_P is true and range checks if RANGE_P is true.
8630 GNAT_TYPE is known to be an integral type. If TRUNCATE_P true, do a
8631 float to integer conversion with truncation; otherwise round.
8632 GNAT_NODE is the GNAT node conveying the source location for which the
8633 error should be signaled. */
8635 static tree
8636 convert_with_check (Entity_Id gnat_type, tree gnu_expr, bool overflowp,
8637 bool rangep, bool truncatep, Node_Id gnat_node)
8639 tree gnu_type = get_unpadded_type (gnat_type);
8640 tree gnu_in_type = TREE_TYPE (gnu_expr);
8641 tree gnu_in_basetype = get_base_type (gnu_in_type);
8642 tree gnu_base_type = get_base_type (gnu_type);
8643 tree gnu_result = gnu_expr;
8645 /* If we are not doing any checks, the output is an integral type and the
8646 input is not a floating-point type, just do the conversion. This is
8647 required for packed array types and is simpler in all cases anyway. */
8648 if (!rangep
8649 && !overflowp
8650 && INTEGRAL_TYPE_P (gnu_base_type)
8651 && !FLOAT_TYPE_P (gnu_in_type))
8652 return convert (gnu_type, gnu_expr);
8654 /* First convert the expression to its base type. This
8655 will never generate code, but makes the tests below much simpler.
8656 But don't do this if converting from an integer type to an unconstrained
8657 array type since then we need to get the bounds from the original
8658 (unpacked) type. */
8659 if (TREE_CODE (gnu_type) != UNCONSTRAINED_ARRAY_TYPE)
8660 gnu_result = convert (gnu_in_basetype, gnu_result);
8662 /* If overflow checks are requested, we need to be sure the result will
8663 fit in the output base type. But don't do this if the input
8664 is integer and the output floating-point. */
8665 if (overflowp
8666 && !(FLOAT_TYPE_P (gnu_base_type) && INTEGRAL_TYPE_P (gnu_in_basetype)))
8668 /* Ensure GNU_EXPR only gets evaluated once. */
8669 tree gnu_input = gnat_protect_expr (gnu_result);
8670 tree gnu_cond = boolean_false_node;
8671 tree gnu_in_lb = TYPE_MIN_VALUE (gnu_in_basetype);
8672 tree gnu_in_ub = TYPE_MAX_VALUE (gnu_in_basetype);
8673 tree gnu_out_lb = TYPE_MIN_VALUE (gnu_base_type);
8674 tree gnu_out_ub = TYPE_MAX_VALUE (gnu_base_type);
8676 /* Convert the lower bounds to signed types, so we're sure we're
8677 comparing them properly. Likewise, convert the upper bounds
8678 to unsigned types. */
8679 if (INTEGRAL_TYPE_P (gnu_in_basetype) && TYPE_UNSIGNED (gnu_in_basetype))
8680 gnu_in_lb = convert (gnat_signed_type (gnu_in_basetype), gnu_in_lb);
8682 if (INTEGRAL_TYPE_P (gnu_in_basetype)
8683 && !TYPE_UNSIGNED (gnu_in_basetype))
8684 gnu_in_ub = convert (gnat_unsigned_type (gnu_in_basetype), gnu_in_ub);
8686 if (INTEGRAL_TYPE_P (gnu_base_type) && TYPE_UNSIGNED (gnu_base_type))
8687 gnu_out_lb = convert (gnat_signed_type (gnu_base_type), gnu_out_lb);
8689 if (INTEGRAL_TYPE_P (gnu_base_type) && !TYPE_UNSIGNED (gnu_base_type))
8690 gnu_out_ub = convert (gnat_unsigned_type (gnu_base_type), gnu_out_ub);
8692 /* Check each bound separately and only if the result bound
8693 is tighter than the bound on the input type. Note that all the
8694 types are base types, so the bounds must be constant. Also,
8695 the comparison is done in the base type of the input, which
8696 always has the proper signedness. First check for input
8697 integer (which means output integer), output float (which means
8698 both float), or mixed, in which case we always compare.
8699 Note that we have to do the comparison which would *fail* in the
8700 case of an error since if it's an FP comparison and one of the
8701 values is a NaN or Inf, the comparison will fail. */
8702 if (INTEGRAL_TYPE_P (gnu_in_basetype)
8703 ? tree_int_cst_lt (gnu_in_lb, gnu_out_lb)
8704 : (FLOAT_TYPE_P (gnu_base_type)
8705 ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_in_lb),
8706 TREE_REAL_CST (gnu_out_lb))
8707 : 1))
8708 gnu_cond
8709 = invert_truthvalue
8710 (build_binary_op (GE_EXPR, boolean_type_node,
8711 gnu_input, convert (gnu_in_basetype,
8712 gnu_out_lb)));
8714 if (INTEGRAL_TYPE_P (gnu_in_basetype)
8715 ? tree_int_cst_lt (gnu_out_ub, gnu_in_ub)
8716 : (FLOAT_TYPE_P (gnu_base_type)
8717 ? REAL_VALUES_LESS (TREE_REAL_CST (gnu_out_ub),
8718 TREE_REAL_CST (gnu_in_lb))
8719 : 1))
8720 gnu_cond
8721 = build_binary_op (TRUTH_ORIF_EXPR, boolean_type_node, gnu_cond,
8722 invert_truthvalue
8723 (build_binary_op (LE_EXPR, boolean_type_node,
8724 gnu_input,
8725 convert (gnu_in_basetype,
8726 gnu_out_ub))));
8728 if (!integer_zerop (gnu_cond))
8729 gnu_result = emit_check (gnu_cond, gnu_input,
8730 CE_Overflow_Check_Failed, gnat_node);
8733 /* Now convert to the result base type. If this is a non-truncating
8734 float-to-integer conversion, round. */
8735 if (INTEGRAL_TYPE_P (gnu_base_type)
8736 && FLOAT_TYPE_P (gnu_in_basetype)
8737 && !truncatep)
8739 REAL_VALUE_TYPE half_minus_pred_half, pred_half;
8740 tree gnu_conv, gnu_zero, gnu_comp, calc_type;
8741 tree gnu_pred_half, gnu_add_pred_half, gnu_subtract_pred_half;
8742 const struct real_format *fmt;
8744 /* The following calculations depend on proper rounding to even
8745 of each arithmetic operation. In order to prevent excess
8746 precision from spoiling this property, use the widest hardware
8747 floating-point type if FP_ARITH_MAY_WIDEN is true. */
8748 calc_type
8749 = fp_arith_may_widen ? longest_float_type_node : gnu_in_basetype;
8751 /* Compute the exact value calc_type'Pred (0.5) at compile time. */
8752 fmt = REAL_MODE_FORMAT (TYPE_MODE (calc_type));
8753 real_2expN (&half_minus_pred_half, -(fmt->p) - 1, TYPE_MODE (calc_type));
8754 REAL_ARITHMETIC (pred_half, MINUS_EXPR, dconsthalf,
8755 half_minus_pred_half);
8756 gnu_pred_half = build_real (calc_type, pred_half);
8758 /* If the input is strictly negative, subtract this value
8759 and otherwise add it from the input. For 0.5, the result
8760 is exactly between 1.0 and the machine number preceding 1.0
8761 (for calc_type). Since the last bit of 1.0 is even, this 0.5
8762 will round to 1.0, while all other number with an absolute
8763 value less than 0.5 round to 0.0. For larger numbers exactly
8764 halfway between integers, rounding will always be correct as
8765 the true mathematical result will be closer to the higher
8766 integer compared to the lower one. So, this constant works
8767 for all floating-point numbers.
8769 The reason to use the same constant with subtract/add instead
8770 of a positive and negative constant is to allow the comparison
8771 to be scheduled in parallel with retrieval of the constant and
8772 conversion of the input to the calc_type (if necessary). */
8774 gnu_zero = convert (gnu_in_basetype, integer_zero_node);
8775 gnu_result = gnat_protect_expr (gnu_result);
8776 gnu_conv = convert (calc_type, gnu_result);
8777 gnu_comp
8778 = fold_build2 (GE_EXPR, boolean_type_node, gnu_result, gnu_zero);
8779 gnu_add_pred_half
8780 = fold_build2 (PLUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
8781 gnu_subtract_pred_half
8782 = fold_build2 (MINUS_EXPR, calc_type, gnu_conv, gnu_pred_half);
8783 gnu_result = fold_build3 (COND_EXPR, calc_type, gnu_comp,
8784 gnu_add_pred_half, gnu_subtract_pred_half);
8787 if (TREE_CODE (gnu_base_type) == INTEGER_TYPE
8788 && TYPE_HAS_ACTUAL_BOUNDS_P (gnu_base_type)
8789 && TREE_CODE (gnu_result) == UNCONSTRAINED_ARRAY_REF)
8790 gnu_result = unchecked_convert (gnu_base_type, gnu_result, false);
8791 else
8792 gnu_result = convert (gnu_base_type, gnu_result);
8794 /* Finally, do the range check if requested. Note that if the result type
8795 is a modular type, the range check is actually an overflow check. */
8796 if (rangep
8797 || (TREE_CODE (gnu_base_type) == INTEGER_TYPE
8798 && TYPE_MODULAR_P (gnu_base_type) && overflowp))
8799 gnu_result = emit_range_check (gnu_result, gnat_type, gnat_node);
8801 return convert (gnu_type, gnu_result);
8804 /* Return true if GNU_EXPR can be directly addressed. This is the case
8805 unless it is an expression involving computation or if it involves a
8806 reference to a bitfield or to an object not sufficiently aligned for
8807 its type. If GNU_TYPE is non-null, return true only if GNU_EXPR can
8808 be directly addressed as an object of this type.
8810 *** Notes on addressability issues in the Ada compiler ***
8812 This predicate is necessary in order to bridge the gap between Gigi
8813 and the middle-end about addressability of GENERIC trees. A tree
8814 is said to be addressable if it can be directly addressed, i.e. if
8815 its address can be taken, is a multiple of the type's alignment on
8816 strict-alignment architectures and returns the first storage unit
8817 assigned to the object represented by the tree.
8819 In the C family of languages, everything is in practice addressable
8820 at the language level, except for bit-fields. This means that these
8821 compilers will take the address of any tree that doesn't represent
8822 a bit-field reference and expect the result to be the first storage
8823 unit assigned to the object. Even in cases where this will result
8824 in unaligned accesses at run time, nothing is supposed to be done
8825 and the program is considered as erroneous instead (see PR c/18287).
8827 The implicit assumptions made in the middle-end are in keeping with
8828 the C viewpoint described above:
8829 - the address of a bit-field reference is supposed to be never
8830 taken; the compiler (generally) will stop on such a construct,
8831 - any other tree is addressable if it is formally addressable,
8832 i.e. if it is formally allowed to be the operand of ADDR_EXPR.
8834 In Ada, the viewpoint is the opposite one: nothing is addressable
8835 at the language level unless explicitly declared so. This means
8836 that the compiler will both make sure that the trees representing
8837 references to addressable ("aliased" in Ada parlance) objects are
8838 addressable and make no real attempts at ensuring that the trees
8839 representing references to non-addressable objects are addressable.
8841 In the first case, Ada is effectively equivalent to C and handing
8842 down the direct result of applying ADDR_EXPR to these trees to the
8843 middle-end works flawlessly. In the second case, Ada cannot afford
8844 to consider the program as erroneous if the address of trees that
8845 are not addressable is requested for technical reasons, unlike C;
8846 as a consequence, the Ada compiler must arrange for either making
8847 sure that this address is not requested in the middle-end or for
8848 compensating by inserting temporaries if it is requested in Gigi.
8850 The first goal can be achieved because the middle-end should not
8851 request the address of non-addressable trees on its own; the only
8852 exception is for the invocation of low-level block operations like
8853 memcpy, for which the addressability requirements are lower since
8854 the type's alignment can be disregarded. In practice, this means
8855 that Gigi must make sure that such operations cannot be applied to
8856 non-BLKmode bit-fields.
8858 The second goal is achieved by means of the addressable_p predicate,
8859 which computes whether a temporary must be inserted by Gigi when the
8860 address of a tree is requested; if so, the address of the temporary
8861 will be used in lieu of that of the original tree and some glue code
8862 generated to connect everything together. */
8864 static bool
8865 addressable_p (tree gnu_expr, tree gnu_type)
8867 /* For an integral type, the size of the actual type of the object may not
8868 be greater than that of the expected type, otherwise an indirect access
8869 in the latter type wouldn't correctly set all the bits of the object. */
8870 if (gnu_type
8871 && INTEGRAL_TYPE_P (gnu_type)
8872 && smaller_form_type_p (gnu_type, TREE_TYPE (gnu_expr)))
8873 return false;
8875 /* The size of the actual type of the object may not be smaller than that
8876 of the expected type, otherwise an indirect access in the latter type
8877 would be larger than the object. But only record types need to be
8878 considered in practice for this case. */
8879 if (gnu_type
8880 && TREE_CODE (gnu_type) == RECORD_TYPE
8881 && smaller_form_type_p (TREE_TYPE (gnu_expr), gnu_type))
8882 return false;
8884 switch (TREE_CODE (gnu_expr))
8886 case VAR_DECL:
8887 case PARM_DECL:
8888 case FUNCTION_DECL:
8889 case RESULT_DECL:
8890 /* All DECLs are addressable: if they are in a register, we can force
8891 them to memory. */
8892 return true;
8894 case UNCONSTRAINED_ARRAY_REF:
8895 case INDIRECT_REF:
8896 /* Taking the address of a dereference yields the original pointer. */
8897 return true;
8899 case STRING_CST:
8900 case INTEGER_CST:
8901 /* Taking the address yields a pointer to the constant pool. */
8902 return true;
8904 case CONSTRUCTOR:
8905 /* Taking the address of a static constructor yields a pointer to the
8906 tree constant pool. */
8907 return TREE_STATIC (gnu_expr) ? true : false;
8909 case NULL_EXPR:
8910 case SAVE_EXPR:
8911 case CALL_EXPR:
8912 case PLUS_EXPR:
8913 case MINUS_EXPR:
8914 case BIT_IOR_EXPR:
8915 case BIT_XOR_EXPR:
8916 case BIT_AND_EXPR:
8917 case BIT_NOT_EXPR:
8918 /* All rvalues are deemed addressable since taking their address will
8919 force a temporary to be created by the middle-end. */
8920 return true;
8922 case COMPOUND_EXPR:
8923 /* The address of a compound expression is that of its 2nd operand. */
8924 return addressable_p (TREE_OPERAND (gnu_expr, 1), gnu_type);
8926 case COND_EXPR:
8927 /* We accept &COND_EXPR as soon as both operands are addressable and
8928 expect the outcome to be the address of the selected operand. */
8929 return (addressable_p (TREE_OPERAND (gnu_expr, 1), NULL_TREE)
8930 && addressable_p (TREE_OPERAND (gnu_expr, 2), NULL_TREE));
8932 case COMPONENT_REF:
8933 return (((!DECL_BIT_FIELD (TREE_OPERAND (gnu_expr, 1))
8934 /* Even with DECL_BIT_FIELD cleared, we have to ensure that
8935 the field is sufficiently aligned, in case it is subject
8936 to a pragma Component_Alignment. But we don't need to
8937 check the alignment of the containing record, as it is
8938 guaranteed to be not smaller than that of its most
8939 aligned field that is not a bit-field. */
8940 && (!STRICT_ALIGNMENT
8941 || DECL_ALIGN (TREE_OPERAND (gnu_expr, 1))
8942 >= TYPE_ALIGN (TREE_TYPE (gnu_expr))))
8943 /* The field of a padding record is always addressable. */
8944 || TYPE_IS_PADDING_P (TREE_TYPE (TREE_OPERAND (gnu_expr, 0))))
8945 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8947 case ARRAY_REF: case ARRAY_RANGE_REF:
8948 case REALPART_EXPR: case IMAGPART_EXPR:
8949 case NOP_EXPR:
8950 return addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE);
8952 case CONVERT_EXPR:
8953 return (AGGREGATE_TYPE_P (TREE_TYPE (gnu_expr))
8954 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8956 case VIEW_CONVERT_EXPR:
8958 /* This is addressable if we can avoid a copy. */
8959 tree type = TREE_TYPE (gnu_expr);
8960 tree inner_type = TREE_TYPE (TREE_OPERAND (gnu_expr, 0));
8961 return (((TYPE_MODE (type) == TYPE_MODE (inner_type)
8962 && (!STRICT_ALIGNMENT
8963 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
8964 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT))
8965 || ((TYPE_MODE (type) == BLKmode
8966 || TYPE_MODE (inner_type) == BLKmode)
8967 && (!STRICT_ALIGNMENT
8968 || TYPE_ALIGN (type) <= TYPE_ALIGN (inner_type)
8969 || TYPE_ALIGN (inner_type) >= BIGGEST_ALIGNMENT
8970 || TYPE_ALIGN_OK (type)
8971 || TYPE_ALIGN_OK (inner_type))))
8972 && addressable_p (TREE_OPERAND (gnu_expr, 0), NULL_TREE));
8975 default:
8976 return false;
8980 /* Do the processing for the declaration of a GNAT_ENTITY, a type. If
8981 a separate Freeze node exists, delay the bulk of the processing. Otherwise
8982 make a GCC type for GNAT_ENTITY and set up the correspondence. */
8984 void
8985 process_type (Entity_Id gnat_entity)
8987 tree gnu_old
8988 = present_gnu_tree (gnat_entity) ? get_gnu_tree (gnat_entity) : 0;
8989 tree gnu_new;
8991 /* If we are to delay elaboration of this type, just do any
8992 elaborations needed for expressions within the declaration and
8993 make a dummy type entry for this node and its Full_View (if
8994 any) in case something points to it. Don't do this if it
8995 has already been done (the only way that can happen is if
8996 the private completion is also delayed). */
8997 if (Present (Freeze_Node (gnat_entity))
8998 || (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
8999 && Present (Full_View (gnat_entity))
9000 && Present (Freeze_Node (Full_View (gnat_entity)))
9001 && !present_gnu_tree (Full_View (gnat_entity))))
9003 elaborate_entity (gnat_entity);
9005 if (!gnu_old)
9007 tree gnu_decl = TYPE_STUB_DECL (make_dummy_type (gnat_entity));
9008 save_gnu_tree (gnat_entity, gnu_decl, false);
9009 if (IN (Ekind (gnat_entity), Incomplete_Or_Private_Kind)
9010 && Present (Full_View (gnat_entity)))
9012 if (Has_Completion_In_Body (gnat_entity))
9013 DECL_TAFT_TYPE_P (gnu_decl) = 1;
9014 save_gnu_tree (Full_View (gnat_entity), gnu_decl, false);
9018 return;
9021 /* If we saved away a dummy type for this node it means that this
9022 made the type that corresponds to the full type of an incomplete
9023 type. Clear that type for now and then update the type in the
9024 pointers. */
9025 if (gnu_old)
9027 gcc_assert (TREE_CODE (gnu_old) == TYPE_DECL
9028 && TYPE_IS_DUMMY_P (TREE_TYPE (gnu_old)));
9030 save_gnu_tree (gnat_entity, NULL_TREE, false);
9033 /* Now fully elaborate the type. */
9034 gnu_new = gnat_to_gnu_entity (gnat_entity, NULL_TREE, 1);
9035 gcc_assert (TREE_CODE (gnu_new) == TYPE_DECL);
9037 /* If we have an old type and we've made pointers to this type, update those
9038 pointers. If this is a Taft amendment type in the main unit, we need to
9039 mark the type as used since other units referencing it don't see the full
9040 declaration and, therefore, cannot mark it as used themselves. */
9041 if (gnu_old)
9043 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_old)),
9044 TREE_TYPE (gnu_new));
9045 if (DECL_TAFT_TYPE_P (gnu_old))
9046 used_types_insert (TREE_TYPE (gnu_new));
9049 /* If this is a record type corresponding to a task or protected type
9050 that is a completion of an incomplete type, perform a similar update
9051 on the type. ??? Including protected types here is a guess. */
9052 if (IN (Ekind (gnat_entity), Record_Kind)
9053 && Is_Concurrent_Record_Type (gnat_entity)
9054 && present_gnu_tree (Corresponding_Concurrent_Type (gnat_entity)))
9056 tree gnu_task_old
9057 = get_gnu_tree (Corresponding_Concurrent_Type (gnat_entity));
9059 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
9060 NULL_TREE, false);
9061 save_gnu_tree (Corresponding_Concurrent_Type (gnat_entity),
9062 gnu_new, false);
9064 update_pointer_to (TYPE_MAIN_VARIANT (TREE_TYPE (gnu_task_old)),
9065 TREE_TYPE (gnu_new));
9069 /* GNAT_ENTITY is the type of the resulting constructor, GNAT_ASSOC is the
9070 front of the Component_Associations of an N_Aggregate and GNU_TYPE is the
9071 GCC type of the corresponding record type. Return the CONSTRUCTOR. */
9073 static tree
9074 assoc_to_constructor (Entity_Id gnat_entity, Node_Id gnat_assoc, tree gnu_type)
9076 tree gnu_list = NULL_TREE, gnu_result;
9078 /* We test for GNU_FIELD being empty in the case where a variant
9079 was the last thing since we don't take things off GNAT_ASSOC in
9080 that case. We check GNAT_ASSOC in case we have a variant, but it
9081 has no fields. */
9083 for (; Present (gnat_assoc); gnat_assoc = Next (gnat_assoc))
9085 Node_Id gnat_field = First (Choices (gnat_assoc));
9086 tree gnu_field = gnat_to_gnu_field_decl (Entity (gnat_field));
9087 tree gnu_expr = gnat_to_gnu (Expression (gnat_assoc));
9089 /* The expander is supposed to put a single component selector name
9090 in every record component association. */
9091 gcc_assert (No (Next (gnat_field)));
9093 /* Ignore fields that have Corresponding_Discriminants since we'll
9094 be setting that field in the parent. */
9095 if (Present (Corresponding_Discriminant (Entity (gnat_field)))
9096 && Is_Tagged_Type (Scope (Entity (gnat_field))))
9097 continue;
9099 /* Also ignore discriminants of Unchecked_Unions. */
9100 if (Is_Unchecked_Union (gnat_entity)
9101 && Ekind (Entity (gnat_field)) == E_Discriminant)
9102 continue;
9104 /* Before assigning a value in an aggregate make sure range checks
9105 are done if required. Then convert to the type of the field. */
9106 if (Do_Range_Check (Expression (gnat_assoc)))
9107 gnu_expr = emit_range_check (gnu_expr, Etype (gnat_field), Empty);
9109 gnu_expr = convert (TREE_TYPE (gnu_field), gnu_expr);
9111 /* Add the field and expression to the list. */
9112 gnu_list = tree_cons (gnu_field, gnu_expr, gnu_list);
9115 gnu_result = extract_values (gnu_list, gnu_type);
9117 #ifdef ENABLE_CHECKING
9118 /* Verify that every entry in GNU_LIST was used. */
9119 for (; gnu_list; gnu_list = TREE_CHAIN (gnu_list))
9120 gcc_assert (TREE_ADDRESSABLE (gnu_list));
9121 #endif
9123 return gnu_result;
9126 /* Build a possibly nested constructor for array aggregates. GNAT_EXPR is
9127 the first element of an array aggregate. It may itself be an aggregate.
9128 GNU_ARRAY_TYPE is the GCC type corresponding to the array aggregate.
9129 GNAT_COMPONENT_TYPE is the type of the array component; it is needed
9130 for range checking. */
9132 static tree
9133 pos_to_constructor (Node_Id gnat_expr, tree gnu_array_type,
9134 Entity_Id gnat_component_type)
9136 tree gnu_index = TYPE_MIN_VALUE (TYPE_DOMAIN (gnu_array_type));
9137 tree gnu_expr;
9138 vec<constructor_elt, va_gc> *gnu_expr_vec = NULL;
9140 for ( ; Present (gnat_expr); gnat_expr = Next (gnat_expr))
9142 /* If the expression is itself an array aggregate then first build the
9143 innermost constructor if it is part of our array (multi-dimensional
9144 case). */
9145 if (Nkind (gnat_expr) == N_Aggregate
9146 && TREE_CODE (TREE_TYPE (gnu_array_type)) == ARRAY_TYPE
9147 && TYPE_MULTI_ARRAY_P (TREE_TYPE (gnu_array_type)))
9148 gnu_expr = pos_to_constructor (First (Expressions (gnat_expr)),
9149 TREE_TYPE (gnu_array_type),
9150 gnat_component_type);
9151 else
9153 gnu_expr = gnat_to_gnu (gnat_expr);
9155 /* Before assigning the element to the array, make sure it is
9156 in range. */
9157 if (Do_Range_Check (gnat_expr))
9158 gnu_expr = emit_range_check (gnu_expr, gnat_component_type, Empty);
9161 CONSTRUCTOR_APPEND_ELT (gnu_expr_vec, gnu_index,
9162 convert (TREE_TYPE (gnu_array_type), gnu_expr));
9164 gnu_index = int_const_binop (PLUS_EXPR, gnu_index,
9165 convert (TREE_TYPE (gnu_index),
9166 integer_one_node));
9169 return gnat_build_constructor (gnu_array_type, gnu_expr_vec);
9172 /* Subroutine of assoc_to_constructor: VALUES is a list of field associations,
9173 some of which are from RECORD_TYPE. Return a CONSTRUCTOR consisting
9174 of the associations that are from RECORD_TYPE. If we see an internal
9175 record, make a recursive call to fill it in as well. */
9177 static tree
9178 extract_values (tree values, tree record_type)
9180 tree field, tem;
9181 vec<constructor_elt, va_gc> *v = NULL;
9183 for (field = TYPE_FIELDS (record_type); field; field = DECL_CHAIN (field))
9185 tree value = 0;
9187 /* _Parent is an internal field, but may have values in the aggregate,
9188 so check for values first. */
9189 if ((tem = purpose_member (field, values)))
9191 value = TREE_VALUE (tem);
9192 TREE_ADDRESSABLE (tem) = 1;
9195 else if (DECL_INTERNAL_P (field))
9197 value = extract_values (values, TREE_TYPE (field));
9198 if (TREE_CODE (value) == CONSTRUCTOR
9199 && vec_safe_is_empty (CONSTRUCTOR_ELTS (value)))
9200 value = 0;
9202 else
9203 /* If we have a record subtype, the names will match, but not the
9204 actual FIELD_DECLs. */
9205 for (tem = values; tem; tem = TREE_CHAIN (tem))
9206 if (DECL_NAME (TREE_PURPOSE (tem)) == DECL_NAME (field))
9208 value = convert (TREE_TYPE (field), TREE_VALUE (tem));
9209 TREE_ADDRESSABLE (tem) = 1;
9212 if (!value)
9213 continue;
9215 CONSTRUCTOR_APPEND_ELT (v, field, value);
9218 return gnat_build_constructor (record_type, v);
9221 /* Process a N_Validate_Unchecked_Conversion node. */
9223 static void
9224 validate_unchecked_conversion (Node_Id gnat_node)
9226 tree gnu_source_type = gnat_to_gnu_type (Source_Type (gnat_node));
9227 tree gnu_target_type = gnat_to_gnu_type (Target_Type (gnat_node));
9229 /* If the target is a pointer type, see if we are either converting from a
9230 non-pointer or from a pointer to a type with a different alias set and
9231 warn if so, unless the pointer has been marked to alias everything. */
9232 if (POINTER_TYPE_P (gnu_target_type)
9233 && !TYPE_REF_CAN_ALIAS_ALL (gnu_target_type))
9235 tree gnu_source_desig_type = POINTER_TYPE_P (gnu_source_type)
9236 ? TREE_TYPE (gnu_source_type)
9237 : NULL_TREE;
9238 tree gnu_target_desig_type = TREE_TYPE (gnu_target_type);
9239 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
9241 if (target_alias_set != 0
9242 && (!POINTER_TYPE_P (gnu_source_type)
9243 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
9244 target_alias_set)))
9246 post_error_ne ("?possible aliasing problem for type&",
9247 gnat_node, Target_Type (gnat_node));
9248 post_error ("\\?use -fno-strict-aliasing switch for references",
9249 gnat_node);
9250 post_error_ne ("\\?or use `pragma No_Strict_Aliasing (&);`",
9251 gnat_node, Target_Type (gnat_node));
9255 /* Likewise if the target is a fat pointer type, but we have no mechanism to
9256 mitigate the problem in this case, so we unconditionally warn. */
9257 else if (TYPE_IS_FAT_POINTER_P (gnu_target_type))
9259 tree gnu_source_desig_type
9260 = TYPE_IS_FAT_POINTER_P (gnu_source_type)
9261 ? TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_source_type)))
9262 : NULL_TREE;
9263 tree gnu_target_desig_type
9264 = TREE_TYPE (TREE_TYPE (TYPE_FIELDS (gnu_target_type)));
9265 alias_set_type target_alias_set = get_alias_set (gnu_target_desig_type);
9267 if (target_alias_set != 0
9268 && (!TYPE_IS_FAT_POINTER_P (gnu_source_type)
9269 || !alias_sets_conflict_p (get_alias_set (gnu_source_desig_type),
9270 target_alias_set)))
9272 post_error_ne ("?possible aliasing problem for type&",
9273 gnat_node, Target_Type (gnat_node));
9274 post_error ("\\?use -fno-strict-aliasing switch for references",
9275 gnat_node);
9280 /* EXP is to be treated as an array or record. Handle the cases when it is
9281 an access object and perform the required dereferences. */
9283 static tree
9284 maybe_implicit_deref (tree exp)
9286 /* If the type is a pointer, dereference it. */
9287 if (POINTER_TYPE_P (TREE_TYPE (exp))
9288 || TYPE_IS_FAT_POINTER_P (TREE_TYPE (exp)))
9289 exp = build_unary_op (INDIRECT_REF, NULL_TREE, exp);
9291 /* If we got a padded type, remove it too. */
9292 if (TYPE_IS_PADDING_P (TREE_TYPE (exp)))
9293 exp = convert (TREE_TYPE (TYPE_FIELDS (TREE_TYPE (exp))), exp);
9295 return exp;
9298 /* Convert SLOC into LOCUS. Return true if SLOC corresponds to a source code
9299 location and false if it doesn't. In the former case, set the Gigi global
9300 variable REF_FILENAME to the simple debug file name as given by sinput.
9301 If clear_column is true, set column information to 0. */
9303 static bool
9304 Sloc_to_locus1 (Source_Ptr Sloc, location_t *locus, bool clear_column)
9306 if (Sloc == No_Location)
9307 return false;
9309 if (Sloc <= Standard_Location)
9311 *locus = BUILTINS_LOCATION;
9312 return false;
9314 else
9316 Source_File_Index file = Get_Source_File_Index (Sloc);
9317 Logical_Line_Number line = Get_Logical_Line_Number (Sloc);
9318 Column_Number column = (clear_column ? 0 : Get_Column_Number (Sloc));
9319 struct line_map *map = LINEMAPS_ORDINARY_MAP_AT (line_table, file - 1);
9321 /* We can have zero if pragma Source_Reference is in effect. */
9322 if (line < 1)
9323 line = 1;
9325 /* Translate the location. */
9326 *locus = linemap_position_for_line_and_column (map, line, column);
9329 ref_filename
9330 = IDENTIFIER_POINTER
9331 (get_identifier
9332 (Get_Name_String (Debug_Source_Name (Get_Source_File_Index (Sloc)))));;
9334 return true;
9337 /* Similar to the above, not clearing the column information. */
9339 bool
9340 Sloc_to_locus (Source_Ptr Sloc, location_t *locus)
9342 return Sloc_to_locus1 (Sloc, locus, false);
9345 /* Similar to set_expr_location, but start with the Sloc of GNAT_NODE and
9346 don't do anything if it doesn't correspond to a source location. */
9348 static void
9349 set_expr_location_from_node1 (tree node, Node_Id gnat_node, bool clear_column)
9351 location_t locus;
9353 if (!Sloc_to_locus1 (Sloc (gnat_node), &locus, clear_column))
9354 return;
9356 SET_EXPR_LOCATION (node, locus);
9359 /* Similar to the above, not clearing the column information. */
9361 static void
9362 set_expr_location_from_node (tree node, Node_Id gnat_node)
9364 set_expr_location_from_node1 (node, gnat_node, false);
9367 /* More elaborate version of set_expr_location_from_node to be used in more
9368 general contexts, for example the result of the translation of a generic
9369 GNAT node. */
9371 static void
9372 set_gnu_expr_location_from_node (tree node, Node_Id gnat_node)
9374 /* Set the location information on the node if it is a real expression.
9375 References can be reused for multiple GNAT nodes and they would get
9376 the location information of their last use. Also make sure not to
9377 overwrite an existing location as it is probably more precise. */
9379 switch (TREE_CODE (node))
9381 CASE_CONVERT:
9382 case NON_LVALUE_EXPR:
9383 case SAVE_EXPR:
9384 break;
9386 case COMPOUND_EXPR:
9387 if (EXPR_P (TREE_OPERAND (node, 1)))
9388 set_gnu_expr_location_from_node (TREE_OPERAND (node, 1), gnat_node);
9390 /* ... fall through ... */
9392 default:
9393 if (!REFERENCE_CLASS_P (node) && !EXPR_HAS_LOCATION (node))
9395 set_expr_location_from_node (node, gnat_node);
9396 set_end_locus_from_node (node, gnat_node);
9398 break;
9402 /* Return a colon-separated list of encodings contained in encoded Ada
9403 name. */
9405 static const char *
9406 extract_encoding (const char *name)
9408 char *encoding = (char *) ggc_alloc_atomic (strlen (name));
9409 get_encoding (name, encoding);
9410 return encoding;
9413 /* Extract the Ada name from an encoded name. */
9415 static const char *
9416 decode_name (const char *name)
9418 char *decoded = (char *) ggc_alloc_atomic (strlen (name) * 2 + 60);
9419 __gnat_decode (name, decoded, 0);
9420 return decoded;
9423 /* Post an error message. MSG is the error message, properly annotated.
9424 NODE is the node at which to post the error and the node to use for the
9425 '&' substitution. */
9427 void
9428 post_error (const char *msg, Node_Id node)
9430 String_Template temp;
9431 String_Pointer sp;
9433 if (No (node))
9434 return;
9436 temp.Low_Bound = 1;
9437 temp.High_Bound = strlen (msg);
9438 sp.Bounds = &temp;
9439 sp.Array = msg;
9440 Error_Msg_N (sp, node);
9443 /* Similar to post_error, but NODE is the node at which to post the error and
9444 ENT is the node to use for the '&' substitution. */
9446 void
9447 post_error_ne (const char *msg, Node_Id node, Entity_Id ent)
9449 String_Template temp;
9450 String_Pointer sp;
9452 if (No (node))
9453 return;
9455 temp.Low_Bound = 1;
9456 temp.High_Bound = strlen (msg);
9457 sp.Bounds = &temp;
9458 sp.Array = msg;
9459 Error_Msg_NE (sp, node, ent);
9462 /* Similar to post_error_ne, but NUM is the number to use for the '^'. */
9464 void
9465 post_error_ne_num (const char *msg, Node_Id node, Entity_Id ent, int num)
9467 Error_Msg_Uint_1 = UI_From_Int (num);
9468 post_error_ne (msg, node, ent);
9471 /* Set the end_locus information for GNU_NODE, if any, from an explicit end
9472 location associated with GNAT_NODE or GNAT_NODE itself, whichever makes
9473 most sense. Return true if a sensible assignment was performed. */
9475 static bool
9476 set_end_locus_from_node (tree gnu_node, Node_Id gnat_node)
9478 Node_Id gnat_end_label = Empty;
9479 location_t end_locus;
9481 /* Pick the GNAT node of which we'll take the sloc to assign to the GCC node
9482 end_locus when there is one. We consider only GNAT nodes with a possible
9483 End_Label attached. If the End_Label actually was unassigned, fallback
9484 on the original node. We'd better assign an explicit sloc associated with
9485 the outer construct in any case. */
9487 switch (Nkind (gnat_node))
9489 case N_Package_Body:
9490 case N_Subprogram_Body:
9491 case N_Block_Statement:
9492 gnat_end_label = End_Label (Handled_Statement_Sequence (gnat_node));
9493 break;
9495 case N_Package_Declaration:
9496 gnat_end_label = End_Label (Specification (gnat_node));
9497 break;
9499 default:
9500 return false;
9503 gnat_node = Present (gnat_end_label) ? gnat_end_label : gnat_node;
9505 /* Some expanded subprograms have neither an End_Label nor a Sloc
9506 attached. Notify that to callers. For a block statement with no
9507 End_Label, clear column information, so that the tree for a
9508 transient block does not receive the sloc of a source condition. */
9510 if (!Sloc_to_locus1 (Sloc (gnat_node), &end_locus,
9511 No (gnat_end_label) &&
9512 (Nkind (gnat_node) == N_Block_Statement)))
9513 return false;
9515 switch (TREE_CODE (gnu_node))
9517 case BIND_EXPR:
9518 BLOCK_SOURCE_END_LOCATION (BIND_EXPR_BLOCK (gnu_node)) = end_locus;
9519 return true;
9521 case FUNCTION_DECL:
9522 DECL_STRUCT_FUNCTION (gnu_node)->function_end_locus = end_locus;
9523 return true;
9525 default:
9526 return false;
9530 /* Similar to post_error_ne, but T is a GCC tree representing the number to
9531 write. If T represents a constant, the text inside curly brackets in
9532 MSG will be output (presumably including a '^'). Otherwise it will not
9533 be output and the text inside square brackets will be output instead. */
9535 void
9536 post_error_ne_tree (const char *msg, Node_Id node, Entity_Id ent, tree t)
9538 char *new_msg = XALLOCAVEC (char, strlen (msg) + 1);
9539 char start_yes, end_yes, start_no, end_no;
9540 const char *p;
9541 char *q;
9543 if (TREE_CODE (t) == INTEGER_CST)
9545 Error_Msg_Uint_1 = UI_From_gnu (t);
9546 start_yes = '{', end_yes = '}', start_no = '[', end_no = ']';
9548 else
9549 start_yes = '[', end_yes = ']', start_no = '{', end_no = '}';
9551 for (p = msg, q = new_msg; *p; p++)
9553 if (*p == start_yes)
9554 for (p++; *p != end_yes; p++)
9555 *q++ = *p;
9556 else if (*p == start_no)
9557 for (p++; *p != end_no; p++)
9559 else
9560 *q++ = *p;
9563 *q = 0;
9565 post_error_ne (new_msg, node, ent);
9568 /* Similar to post_error_ne_tree, but NUM is a second integer to write. */
9570 void
9571 post_error_ne_tree_2 (const char *msg, Node_Id node, Entity_Id ent, tree t,
9572 int num)
9574 Error_Msg_Uint_2 = UI_From_Int (num);
9575 post_error_ne_tree (msg, node, ent, t);
9578 /* Initialize the table that maps GNAT codes to GCC codes for simple
9579 binary and unary operations. */
9581 static void
9582 init_code_table (void)
9584 gnu_codes[N_And_Then] = TRUTH_ANDIF_EXPR;
9585 gnu_codes[N_Or_Else] = TRUTH_ORIF_EXPR;
9587 gnu_codes[N_Op_And] = TRUTH_AND_EXPR;
9588 gnu_codes[N_Op_Or] = TRUTH_OR_EXPR;
9589 gnu_codes[N_Op_Xor] = TRUTH_XOR_EXPR;
9590 gnu_codes[N_Op_Eq] = EQ_EXPR;
9591 gnu_codes[N_Op_Ne] = NE_EXPR;
9592 gnu_codes[N_Op_Lt] = LT_EXPR;
9593 gnu_codes[N_Op_Le] = LE_EXPR;
9594 gnu_codes[N_Op_Gt] = GT_EXPR;
9595 gnu_codes[N_Op_Ge] = GE_EXPR;
9596 gnu_codes[N_Op_Add] = PLUS_EXPR;
9597 gnu_codes[N_Op_Subtract] = MINUS_EXPR;
9598 gnu_codes[N_Op_Multiply] = MULT_EXPR;
9599 gnu_codes[N_Op_Mod] = FLOOR_MOD_EXPR;
9600 gnu_codes[N_Op_Rem] = TRUNC_MOD_EXPR;
9601 gnu_codes[N_Op_Minus] = NEGATE_EXPR;
9602 gnu_codes[N_Op_Abs] = ABS_EXPR;
9603 gnu_codes[N_Op_Not] = TRUTH_NOT_EXPR;
9604 gnu_codes[N_Op_Rotate_Left] = LROTATE_EXPR;
9605 gnu_codes[N_Op_Rotate_Right] = RROTATE_EXPR;
9606 gnu_codes[N_Op_Shift_Left] = LSHIFT_EXPR;
9607 gnu_codes[N_Op_Shift_Right] = RSHIFT_EXPR;
9608 gnu_codes[N_Op_Shift_Right_Arithmetic] = RSHIFT_EXPR;
9611 /* Return a label to branch to for the exception type in KIND or NULL_TREE
9612 if none. */
9614 tree
9615 get_exception_label (char kind)
9617 if (kind == N_Raise_Constraint_Error)
9618 return gnu_constraint_error_label_stack->last ();
9619 else if (kind == N_Raise_Storage_Error)
9620 return gnu_storage_error_label_stack->last ();
9621 else if (kind == N_Raise_Program_Error)
9622 return gnu_program_error_label_stack->last ();
9623 else
9624 return NULL_TREE;
9627 /* Return the decl for the current elaboration procedure. */
9629 tree
9630 get_elaboration_procedure (void)
9632 return gnu_elab_proc_stack->last ();
9635 #include "gt-ada-trans.h"