OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [gcc/] [ada/] [gcc-interface/] [trans.c] - Blame information for rev 801

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.