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

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-stable/] [gcc-4.5.1/] [gcc/] [ada/] [exp_ch5.adb] - Blame information for rev 843

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

Line No. Rev Author Line
1 281 jeremybenn
------------------------------------------------------------------------------
2
--                                                                          --
3
--                         GNAT COMPILER COMPONENTS                         --
4
--                                                                          --
5
--                              E X P _ C H 5                               --
6
--                                                                          --
7
--                                 B o d y                                  --
8
--                                                                          --
9
--          Copyright (C) 1992-2009, Free Software Foundation, Inc.         --
10
--                                                                          --
11
-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12
-- terms of the  GNU General Public License as published  by the Free Soft- --
13
-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14
-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15
-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16
-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17
-- for  more details.  You should have  received  a copy of the GNU General --
18
-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19
-- http://www.gnu.org/licenses for a complete copy of the license.          --
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
with Atree;    use Atree;
27
with Checks;   use Checks;
28
with Debug;    use Debug;
29
with Einfo;    use Einfo;
30
with Elists;   use Elists;
31
with Exp_Atag; use Exp_Atag;
32
with Exp_Aggr; use Exp_Aggr;
33
with Exp_Ch6;  use Exp_Ch6;
34
with Exp_Ch7;  use Exp_Ch7;
35
with Exp_Ch11; use Exp_Ch11;
36
with Exp_Dbug; use Exp_Dbug;
37
with Exp_Pakd; use Exp_Pakd;
38
with Exp_Tss;  use Exp_Tss;
39
with Exp_Util; use Exp_Util;
40
with Namet;    use Namet;
41
with Nlists;   use Nlists;
42
with Nmake;    use Nmake;
43
with Opt;      use Opt;
44
with Restrict; use Restrict;
45
with Rident;   use Rident;
46
with Rtsfind;  use Rtsfind;
47
with Sinfo;    use Sinfo;
48
with Sem;      use Sem;
49
with Sem_Aux;  use Sem_Aux;
50
with Sem_Ch3;  use Sem_Ch3;
51
with Sem_Ch8;  use Sem_Ch8;
52
with Sem_Ch13; use Sem_Ch13;
53
with Sem_Eval; use Sem_Eval;
54
with Sem_Res;  use Sem_Res;
55
with Sem_Util; use Sem_Util;
56
with Snames;   use Snames;
57
with Stand;    use Stand;
58
with Stringt;  use Stringt;
59
with Targparm; use Targparm;
60
with Tbuild;   use Tbuild;
61
with Ttypes;   use Ttypes;
62
with Uintp;    use Uintp;
63
with Validsw;  use Validsw;
64
 
65
package body Exp_Ch5 is
66
 
67
   function Change_Of_Representation (N : Node_Id) return Boolean;
68
   --  Determine if the right hand side of the assignment N is a type
69
   --  conversion which requires a change of representation. Called
70
   --  only for the array and record cases.
71
 
72
   procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
73
   --  N is an assignment which assigns an array value. This routine process
74
   --  the various special cases and checks required for such assignments,
75
   --  including change of representation. Rhs is normally simply the right
76
   --  hand side of the assignment, except that if the right hand side is
77
   --  a type conversion or a qualified expression, then the Rhs is the
78
   --  actual expression inside any such type conversions or qualifications.
79
 
80
   function Expand_Assign_Array_Loop
81
     (N      : Node_Id;
82
      Larray : Entity_Id;
83
      Rarray : Entity_Id;
84
      L_Type : Entity_Id;
85
      R_Type : Entity_Id;
86
      Ndim   : Pos;
87
      Rev    : Boolean) return Node_Id;
88
   --  N is an assignment statement which assigns an array value. This routine
89
   --  expands the assignment into a loop (or nested loops for the case of a
90
   --  multi-dimensional array) to do the assignment component by component.
91
   --  Larray and Rarray are the entities of the actual arrays on the left
92
   --  hand and right hand sides. L_Type and R_Type are the types of these
93
   --  arrays (which may not be the same, due to either sliding, or to a
94
   --  change of representation case). Ndim is the number of dimensions and
95
   --  the parameter Rev indicates if the loops run normally (Rev = False),
96
   --  or reversed (Rev = True). The value returned is the constructed
97
   --  loop statement. Auxiliary declarations are inserted before node N
98
   --  using the standard Insert_Actions mechanism.
99
 
100
   procedure Expand_Assign_Record (N : Node_Id);
101
   --  N is an assignment of a non-tagged record value. This routine handles
102
   --  the case where the assignment must be made component by component,
103
   --  either because the target is not byte aligned, or there is a change
104
   --  of representation, or when we have a tagged type with a representation
105
   --  clause (this last case is required because holes in the tagged type
106
   --  might be filled with components from child types).
107
 
108
   procedure Expand_Non_Function_Return (N : Node_Id);
109
   --  Called by Expand_N_Simple_Return_Statement in case we're returning from
110
   --  a procedure body, entry body, accept statement, or extended return
111
   --  statement.  Note that all non-function returns are simple return
112
   --  statements.
113
 
114
   procedure Expand_Simple_Function_Return (N : Node_Id);
115
   --  Expand simple return from function. In the case where we are returning
116
   --  from a function body this is called by Expand_N_Simple_Return_Statement.
117
 
118
   function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
119
   --  Generate the necessary code for controlled and tagged assignment, that
120
   --  is to say, finalization of the target before, adjustment of the target
121
   --  after and save and restore of the tag and finalization pointers which
122
   --  are not 'part of the value' and must not be changed upon assignment. N
123
   --  is the original Assignment node.
124
 
125
   ------------------------------
126
   -- Change_Of_Representation --
127
   ------------------------------
128
 
129
   function Change_Of_Representation (N : Node_Id) return Boolean is
130
      Rhs : constant Node_Id := Expression (N);
131
   begin
132
      return
133
        Nkind (Rhs) = N_Type_Conversion
134
          and then
135
            not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
136
   end Change_Of_Representation;
137
 
138
   -------------------------
139
   -- Expand_Assign_Array --
140
   -------------------------
141
 
142
   --  There are two issues here. First, do we let Gigi do a block move, or
143
   --  do we expand out into a loop? Second, we need to set the two flags
144
   --  Forwards_OK and Backwards_OK which show whether the block move (or
145
   --  corresponding loops) can be legitimately done in a forwards (low to
146
   --  high) or backwards (high to low) manner.
147
 
148
   procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
149
      Loc : constant Source_Ptr := Sloc (N);
150
 
151
      Lhs : constant Node_Id := Name (N);
152
 
153
      Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
154
      Act_Rhs : Node_Id          := Get_Referenced_Object (Rhs);
155
 
156
      L_Type : constant Entity_Id :=
157
                 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
158
      R_Type : Entity_Id :=
159
                 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
160
 
161
      L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
162
      R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
163
 
164
      Crep : constant Boolean := Change_Of_Representation (N);
165
 
166
      Larray  : Node_Id;
167
      Rarray  : Node_Id;
168
 
169
      Ndim : constant Pos := Number_Dimensions (L_Type);
170
 
171
      Loop_Required : Boolean := False;
172
      --  This switch is set to True if the array move must be done using
173
      --  an explicit front end generated loop.
174
 
175
      procedure Apply_Dereference (Arg : Node_Id);
176
      --  If the argument is an access to an array, and the assignment is
177
      --  converted into a procedure call, apply explicit dereference.
178
 
179
      function Has_Address_Clause (Exp : Node_Id) return Boolean;
180
      --  Test if Exp is a reference to an array whose declaration has
181
      --  an address clause, or it is a slice of such an array.
182
 
183
      function Is_Formal_Array (Exp : Node_Id) return Boolean;
184
      --  Test if Exp is a reference to an array which is either a formal
185
      --  parameter or a slice of a formal parameter. These are the cases
186
      --  where hidden aliasing can occur.
187
 
188
      function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
189
      --  Determine if Exp is a reference to an array variable which is other
190
      --  than an object defined in the current scope, or a slice of such
191
      --  an object. Such objects can be aliased to parameters (unlike local
192
      --  array references).
193
 
194
      -----------------------
195
      -- Apply_Dereference --
196
      -----------------------
197
 
198
      procedure Apply_Dereference (Arg : Node_Id) is
199
         Typ : constant Entity_Id := Etype (Arg);
200
      begin
201
         if Is_Access_Type (Typ) then
202
            Rewrite (Arg, Make_Explicit_Dereference (Loc,
203
              Prefix => Relocate_Node (Arg)));
204
            Analyze_And_Resolve (Arg, Designated_Type (Typ));
205
         end if;
206
      end Apply_Dereference;
207
 
208
      ------------------------
209
      -- Has_Address_Clause --
210
      ------------------------
211
 
212
      function Has_Address_Clause (Exp : Node_Id) return Boolean is
213
      begin
214
         return
215
           (Is_Entity_Name (Exp) and then
216
                              Present (Address_Clause (Entity (Exp))))
217
             or else
218
           (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
219
      end Has_Address_Clause;
220
 
221
      ---------------------
222
      -- Is_Formal_Array --
223
      ---------------------
224
 
225
      function Is_Formal_Array (Exp : Node_Id) return Boolean is
226
      begin
227
         return
228
           (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
229
             or else
230
           (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
231
      end Is_Formal_Array;
232
 
233
      ------------------------
234
      -- Is_Non_Local_Array --
235
      ------------------------
236
 
237
      function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
238
      begin
239
         return (Is_Entity_Name (Exp)
240
                   and then Scope (Entity (Exp)) /= Current_Scope)
241
            or else (Nkind (Exp) = N_Slice
242
                       and then Is_Non_Local_Array (Prefix (Exp)));
243
      end Is_Non_Local_Array;
244
 
245
      --  Determine if Lhs, Rhs are formal arrays or nonlocal arrays
246
 
247
      Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
248
      Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
249
 
250
      Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
251
      Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
252
 
253
   --  Start of processing for Expand_Assign_Array
254
 
255
   begin
256
      --  Deal with length check. Note that the length check is done with
257
      --  respect to the right hand side as given, not a possible underlying
258
      --  renamed object, since this would generate incorrect extra checks.
259
 
260
      Apply_Length_Check (Rhs, L_Type);
261
 
262
      --  We start by assuming that the move can be done in either direction,
263
      --  i.e. that the two sides are completely disjoint.
264
 
265
      Set_Forwards_OK  (N, True);
266
      Set_Backwards_OK (N, True);
267
 
268
      --  Normally it is only the slice case that can lead to overlap, and
269
      --  explicit checks for slices are made below. But there is one case
270
      --  where the slice can be implicit and invisible to us: when we have a
271
      --  one dimensional array, and either both operands are parameters, or
272
      --  one is a parameter (which can be a slice passed by reference) and the
273
      --  other is a non-local variable. In this case the parameter could be a
274
      --  slice that overlaps with the other operand.
275
 
276
      --  However, if the array subtype is a constrained first subtype in the
277
      --  parameter case, then we don't have to worry about overlap, since
278
      --  slice assignments aren't possible (other than for a slice denoting
279
      --  the whole array).
280
 
281
      --  Note: No overlap is possible if there is a change of representation,
282
      --  so we can exclude this case.
283
 
284
      if Ndim = 1
285
        and then not Crep
286
        and then
287
           ((Lhs_Formal and Rhs_Formal)
288
              or else
289
            (Lhs_Formal and Rhs_Non_Local_Var)
290
              or else
291
            (Rhs_Formal and Lhs_Non_Local_Var))
292
        and then
293
           (not Is_Constrained (Etype (Lhs))
294
             or else not Is_First_Subtype (Etype (Lhs)))
295
 
296
         --  In the case of compiling for the Java or .NET Virtual Machine,
297
         --  slices are always passed by making a copy, so we don't have to
298
         --  worry about overlap. We also want to prevent generation of "<"
299
         --  comparisons for array addresses, since that's a meaningless
300
         --  operation on the VM.
301
 
302
        and then VM_Target = No_VM
303
      then
304
         Set_Forwards_OK  (N, False);
305
         Set_Backwards_OK (N, False);
306
 
307
         --  Note: the bit-packed case is not worrisome here, since if we have
308
         --  a slice passed as a parameter, it is always aligned on a byte
309
         --  boundary, and if there are no explicit slices, the assignment
310
         --  can be performed directly.
311
      end if;
312
 
313
      --  If either operand has an address clause clear Backwards_OK and
314
      --  Forwards_OK, since we cannot tell if the operands overlap. We
315
      --  exclude this treatment when Rhs is an aggregate, since we know
316
      --  that overlap can't occur.
317
 
318
      if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
319
        or else Has_Address_Clause (Rhs)
320
      then
321
         Set_Forwards_OK  (N, False);
322
         Set_Backwards_OK (N, False);
323
      end if;
324
 
325
      --  We certainly must use a loop for change of representation and also
326
      --  we use the operand of the conversion on the right hand side as the
327
      --  effective right hand side (the component types must match in this
328
      --  situation).
329
 
330
      if Crep then
331
         Act_Rhs := Get_Referenced_Object (Rhs);
332
         R_Type  := Get_Actual_Subtype (Act_Rhs);
333
         Loop_Required := True;
334
 
335
      --  We require a loop if the left side is possibly bit unaligned
336
 
337
      elsif Possible_Bit_Aligned_Component (Lhs)
338
              or else
339
            Possible_Bit_Aligned_Component (Rhs)
340
      then
341
         Loop_Required := True;
342
 
343
      --  Arrays with controlled components are expanded into a loop to force
344
      --  calls to Adjust at the component level.
345
 
346
      elsif Has_Controlled_Component (L_Type) then
347
         Loop_Required := True;
348
 
349
         --  If object is atomic, we cannot tolerate a loop
350
 
351
      elsif Is_Atomic_Object (Act_Lhs)
352
              or else
353
            Is_Atomic_Object (Act_Rhs)
354
      then
355
         return;
356
 
357
      --  Loop is required if we have atomic components since we have to
358
      --  be sure to do any accesses on an element by element basis.
359
 
360
      elsif Has_Atomic_Components (L_Type)
361
        or else Has_Atomic_Components (R_Type)
362
        or else Is_Atomic (Component_Type (L_Type))
363
        or else Is_Atomic (Component_Type (R_Type))
364
      then
365
         Loop_Required := True;
366
 
367
      --  Case where no slice is involved
368
 
369
      elsif not L_Slice and not R_Slice then
370
 
371
         --  The following code deals with the case of unconstrained bit packed
372
         --  arrays. The problem is that the template for such arrays contains
373
         --  the bounds of the actual source level array, but the copy of an
374
         --  entire array requires the bounds of the underlying array. It would
375
         --  be nice if the back end could take care of this, but right now it
376
         --  does not know how, so if we have such a type, then we expand out
377
         --  into a loop, which is inefficient but works correctly. If we don't
378
         --  do this, we get the wrong length computed for the array to be
379
         --  moved. The two cases we need to worry about are:
380
 
381
         --  Explicit dereference of an unconstrained packed array type as in
382
         --  the following example:
383
 
384
         --    procedure C52 is
385
         --       type BITS is array(INTEGER range <>) of BOOLEAN;
386
         --       pragma PACK(BITS);
387
         --       type A is access BITS;
388
         --       P1,P2 : A;
389
         --    begin
390
         --       P1 := new BITS (1 .. 65_535);
391
         --       P2 := new BITS (1 .. 65_535);
392
         --       P2.ALL := P1.ALL;
393
         --    end C52;
394
 
395
         --  A formal parameter reference with an unconstrained bit array type
396
         --  is the other case we need to worry about (here we assume the same
397
         --  BITS type declared above):
398
 
399
         --    procedure Write_All (File : out BITS; Contents : BITS);
400
         --    begin
401
         --       File.Storage := Contents;
402
         --    end Write_All;
403
 
404
         --  We expand to a loop in either of these two cases
405
 
406
         --  Question for future thought. Another potentially more efficient
407
         --  approach would be to create the actual subtype, and then do an
408
         --  unchecked conversion to this actual subtype ???
409
 
410
         Check_Unconstrained_Bit_Packed_Array : declare
411
 
412
            function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
413
            --  Function to perform required test for the first case, above
414
            --  (dereference of an unconstrained bit packed array).
415
 
416
            -----------------------
417
            -- Is_UBPA_Reference --
418
            -----------------------
419
 
420
            function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
421
               Typ      : constant Entity_Id := Underlying_Type (Etype (Opnd));
422
               P_Type   : Entity_Id;
423
               Des_Type : Entity_Id;
424
 
425
            begin
426
               if Present (Packed_Array_Type (Typ))
427
                 and then Is_Array_Type (Packed_Array_Type (Typ))
428
                 and then not Is_Constrained (Packed_Array_Type (Typ))
429
               then
430
                  return True;
431
 
432
               elsif Nkind (Opnd) = N_Explicit_Dereference then
433
                  P_Type := Underlying_Type (Etype (Prefix (Opnd)));
434
 
435
                  if not Is_Access_Type (P_Type) then
436
                     return False;
437
 
438
                  else
439
                     Des_Type := Designated_Type (P_Type);
440
                     return
441
                       Is_Bit_Packed_Array (Des_Type)
442
                         and then not Is_Constrained (Des_Type);
443
                  end if;
444
 
445
               else
446
                  return False;
447
               end if;
448
            end Is_UBPA_Reference;
449
 
450
         --  Start of processing for Check_Unconstrained_Bit_Packed_Array
451
 
452
         begin
453
            if Is_UBPA_Reference (Lhs)
454
                 or else
455
               Is_UBPA_Reference (Rhs)
456
            then
457
               Loop_Required := True;
458
 
459
            --  Here if we do not have the case of a reference to a bit packed
460
            --  unconstrained array case. In this case gigi can most certainly
461
            --  handle the assignment if a forwards move is allowed.
462
 
463
            --  (could it handle the backwards case also???)
464
 
465
            elsif Forwards_OK (N) then
466
               return;
467
            end if;
468
         end Check_Unconstrained_Bit_Packed_Array;
469
 
470
      --  The back end can always handle the assignment if the right side is a
471
      --  string literal (note that overlap is definitely impossible in this
472
      --  case). If the type is packed, a string literal is always converted
473
      --  into an aggregate, except in the case of a null slice, for which no
474
      --  aggregate can be written. In that case, rewrite the assignment as a
475
      --  null statement, a length check has already been emitted to verify
476
      --  that the range of the left-hand side is empty.
477
 
478
      --  Note that this code is not executed if we have an assignment of a
479
      --  string literal to a non-bit aligned component of a record, a case
480
      --  which cannot be handled by the backend.
481
 
482
      elsif Nkind (Rhs) = N_String_Literal then
483
         if String_Length (Strval (Rhs)) = 0
484
           and then Is_Bit_Packed_Array (L_Type)
485
         then
486
            Rewrite (N, Make_Null_Statement (Loc));
487
            Analyze (N);
488
         end if;
489
 
490
         return;
491
 
492
      --  If either operand is bit packed, then we need a loop, since we can't
493
      --  be sure that the slice is byte aligned. Similarly, if either operand
494
      --  is a possibly unaligned slice, then we need a loop (since the back
495
      --  end cannot handle unaligned slices).
496
 
497
      elsif Is_Bit_Packed_Array (L_Type)
498
        or else Is_Bit_Packed_Array (R_Type)
499
        or else Is_Possibly_Unaligned_Slice (Lhs)
500
        or else Is_Possibly_Unaligned_Slice (Rhs)
501
      then
502
         Loop_Required := True;
503
 
504
      --  If we are not bit-packed, and we have only one slice, then no overlap
505
      --  is possible except in the parameter case, so we can let the back end
506
      --  handle things.
507
 
508
      elsif not (L_Slice and R_Slice) then
509
         if Forwards_OK (N) then
510
            return;
511
         end if;
512
      end if;
513
 
514
      --  If the right-hand side is a string literal, introduce a temporary for
515
      --  it, for use in the generated loop that will follow.
516
 
517
      if Nkind (Rhs) = N_String_Literal then
518
         declare
519
            Temp : constant Entity_Id :=
520
                     Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
521
            Decl : Node_Id;
522
 
523
         begin
524
            Decl :=
525
              Make_Object_Declaration (Loc,
526
                 Defining_Identifier => Temp,
527
                 Object_Definition => New_Occurrence_Of (L_Type, Loc),
528
                 Expression => Relocate_Node (Rhs));
529
 
530
            Insert_Action (N, Decl);
531
            Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
532
            R_Type := Etype (Temp);
533
         end;
534
      end if;
535
 
536
      --  Come here to complete the analysis
537
 
538
      --    Loop_Required: Set to True if we know that a loop is required
539
      --                   regardless of overlap considerations.
540
 
541
      --    Forwards_OK:   Set to False if we already know that a forwards
542
      --                   move is not safe, else set to True.
543
 
544
      --    Backwards_OK:  Set to False if we already know that a backwards
545
      --                   move is not safe, else set to True
546
 
547
      --  Our task at this stage is to complete the overlap analysis, which can
548
      --  result in possibly setting Forwards_OK or Backwards_OK to False, and
549
      --  then generating the final code, either by deciding that it is OK
550
      --  after all to let Gigi handle it, or by generating appropriate code
551
      --  in the front end.
552
 
553
      declare
554
         L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
555
         R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
556
 
557
         Left_Lo  : constant Node_Id := Type_Low_Bound  (L_Index_Typ);
558
         Left_Hi  : constant Node_Id := Type_High_Bound (L_Index_Typ);
559
         Right_Lo : constant Node_Id := Type_Low_Bound  (R_Index_Typ);
560
         Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
561
 
562
         Act_L_Array : Node_Id;
563
         Act_R_Array : Node_Id;
564
 
565
         Cleft_Lo  : Node_Id;
566
         Cright_Lo : Node_Id;
567
         Condition : Node_Id;
568
 
569
         Cresult : Compare_Result;
570
 
571
      begin
572
         --  Get the expressions for the arrays. If we are dealing with a
573
         --  private type, then convert to the underlying type. We can do
574
         --  direct assignments to an array that is a private type, but we
575
         --  cannot assign to elements of the array without this extra
576
         --  unchecked conversion.
577
 
578
         if Nkind (Act_Lhs) = N_Slice then
579
            Larray := Prefix (Act_Lhs);
580
         else
581
            Larray := Act_Lhs;
582
 
583
            if Is_Private_Type (Etype (Larray)) then
584
               Larray :=
585
                 Unchecked_Convert_To
586
                   (Underlying_Type (Etype (Larray)), Larray);
587
            end if;
588
         end if;
589
 
590
         if Nkind (Act_Rhs) = N_Slice then
591
            Rarray := Prefix (Act_Rhs);
592
         else
593
            Rarray := Act_Rhs;
594
 
595
            if Is_Private_Type (Etype (Rarray)) then
596
               Rarray :=
597
                 Unchecked_Convert_To
598
                   (Underlying_Type (Etype (Rarray)), Rarray);
599
            end if;
600
         end if;
601
 
602
         --  If both sides are slices, we must figure out whether it is safe
603
         --  to do the move in one direction or the other. It is always safe
604
         --  if there is a change of representation since obviously two arrays
605
         --  with different representations cannot possibly overlap.
606
 
607
         if (not Crep) and L_Slice and R_Slice then
608
            Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
609
            Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
610
 
611
            --  If both left and right hand arrays are entity names, and refer
612
            --  to different entities, then we know that the move is safe (the
613
            --  two storage areas are completely disjoint).
614
 
615
            if Is_Entity_Name (Act_L_Array)
616
              and then Is_Entity_Name (Act_R_Array)
617
              and then Entity (Act_L_Array) /= Entity (Act_R_Array)
618
            then
619
               null;
620
 
621
            --  Otherwise, we assume the worst, which is that the two arrays
622
            --  are the same array. There is no need to check if we know that
623
            --  is the case, because if we don't know it, we still have to
624
            --  assume it!
625
 
626
            --  Generally if the same array is involved, then we have an
627
            --  overlapping case. We will have to really assume the worst (i.e.
628
            --  set neither of the OK flags) unless we can determine the lower
629
            --  or upper bounds at compile time and compare them.
630
 
631
            else
632
               Cresult :=
633
                 Compile_Time_Compare
634
                   (Left_Lo, Right_Lo, Assume_Valid => True);
635
 
636
               if Cresult = Unknown then
637
                  Cresult :=
638
                    Compile_Time_Compare
639
                      (Left_Hi, Right_Hi, Assume_Valid => True);
640
               end if;
641
 
642
               case Cresult is
643
                  when LT | LE | EQ => Set_Backwards_OK (N, False);
644
                  when GT | GE      => Set_Forwards_OK  (N, False);
645
                  when NE | Unknown => Set_Backwards_OK (N, False);
646
                                       Set_Forwards_OK  (N, False);
647
               end case;
648
            end if;
649
         end if;
650
 
651
         --  If after that analysis Loop_Required is False, meaning that we
652
         --  have not discovered some non-overlap reason for requiring a loop,
653
         --  then the outcome depends on the capabilities of the back end.
654
 
655
         if not Loop_Required then
656
 
657
            --  The GCC back end can deal with all cases of overlap by falling
658
            --  back to memmove if it cannot use a more efficient approach.
659
 
660
            if VM_Target = No_VM and not AAMP_On_Target then
661
               return;
662
 
663
            --  Assume other back ends can handle it if Forwards_OK is set
664
 
665
            elsif Forwards_OK (N) then
666
               return;
667
 
668
            --  If Forwards_OK is not set, the back end will need something
669
            --  like memmove to handle the move. For now, this processing is
670
            --  activated using the .s debug flag (-gnatd.s).
671
 
672
            elsif Debug_Flag_Dot_S then
673
               return;
674
            end if;
675
         end if;
676
 
677
         --  At this stage we have to generate an explicit loop, and we have
678
         --  the following cases:
679
 
680
         --  Forwards_OK = True
681
 
682
         --    Rnn : right_index := right_index'First;
683
         --    for Lnn in left-index loop
684
         --       left (Lnn) := right (Rnn);
685
         --       Rnn := right_index'Succ (Rnn);
686
         --    end loop;
687
 
688
         --    Note: the above code MUST be analyzed with checks off, because
689
         --    otherwise the Succ could overflow. But in any case this is more
690
         --    efficient!
691
 
692
         --  Forwards_OK = False, Backwards_OK = True
693
 
694
         --    Rnn : right_index := right_index'Last;
695
         --    for Lnn in reverse left-index loop
696
         --       left (Lnn) := right (Rnn);
697
         --       Rnn := right_index'Pred (Rnn);
698
         --    end loop;
699
 
700
         --    Note: the above code MUST be analyzed with checks off, because
701
         --    otherwise the Pred could overflow. But in any case this is more
702
         --    efficient!
703
 
704
         --  Forwards_OK = Backwards_OK = False
705
 
706
         --    This only happens if we have the same array on each side. It is
707
         --    possible to create situations using overlays that violate this,
708
         --    but we simply do not promise to get this "right" in this case.
709
 
710
         --    There are two possible subcases. If the No_Implicit_Conditionals
711
         --    restriction is set, then we generate the following code:
712
 
713
         --      declare
714
         --        T : constant <operand-type> := rhs;
715
         --      begin
716
         --        lhs := T;
717
         --      end;
718
 
719
         --    If implicit conditionals are permitted, then we generate:
720
 
721
         --      if Left_Lo <= Right_Lo then
722
         --         <code for Forwards_OK = True above>
723
         --      else
724
         --         <code for Backwards_OK = True above>
725
         --      end if;
726
 
727
         --  In order to detect possible aliasing, we examine the renamed
728
         --  expression when the source or target is a renaming. However,
729
         --  the renaming may be intended to capture an address that may be
730
         --  affected by subsequent code, and therefore we must recover
731
         --  the actual entity for the expansion that follows, not the
732
         --  object it renames. In particular, if source or target designate
733
         --  a portion of a dynamically allocated object, the pointer to it
734
         --  may be reassigned but the renaming preserves the proper location.
735
 
736
         if Is_Entity_Name (Rhs)
737
           and then
738
             Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
739
           and then Nkind (Act_Rhs) = N_Slice
740
         then
741
            Rarray := Rhs;
742
         end if;
743
 
744
         if Is_Entity_Name (Lhs)
745
           and then
746
             Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
747
           and then Nkind (Act_Lhs) = N_Slice
748
         then
749
            Larray := Lhs;
750
         end if;
751
 
752
         --  Cases where either Forwards_OK or Backwards_OK is true
753
 
754
         if Forwards_OK (N) or else Backwards_OK (N) then
755
            if Needs_Finalization (Component_Type (L_Type))
756
              and then Base_Type (L_Type) = Base_Type (R_Type)
757
              and then Ndim = 1
758
              and then not No_Ctrl_Actions (N)
759
            then
760
               declare
761
                  Proc    : constant Entity_Id :=
762
                              TSS (Base_Type (L_Type), TSS_Slice_Assign);
763
                  Actuals : List_Id;
764
 
765
               begin
766
                  Apply_Dereference (Larray);
767
                  Apply_Dereference (Rarray);
768
                  Actuals := New_List (
769
                    Duplicate_Subexpr (Larray,   Name_Req => True),
770
                    Duplicate_Subexpr (Rarray,   Name_Req => True),
771
                    Duplicate_Subexpr (Left_Lo,  Name_Req => True),
772
                    Duplicate_Subexpr (Left_Hi,  Name_Req => True),
773
                    Duplicate_Subexpr (Right_Lo, Name_Req => True),
774
                    Duplicate_Subexpr (Right_Hi, Name_Req => True));
775
 
776
                  Append_To (Actuals,
777
                    New_Occurrence_Of (
778
                      Boolean_Literals (not Forwards_OK (N)), Loc));
779
 
780
                  Rewrite (N,
781
                    Make_Procedure_Call_Statement (Loc,
782
                      Name => New_Reference_To (Proc, Loc),
783
                      Parameter_Associations => Actuals));
784
               end;
785
 
786
            else
787
               Rewrite (N,
788
                 Expand_Assign_Array_Loop
789
                   (N, Larray, Rarray, L_Type, R_Type, Ndim,
790
                    Rev => not Forwards_OK (N)));
791
            end if;
792
 
793
         --  Case of both are false with No_Implicit_Conditionals
794
 
795
         elsif Restriction_Active (No_Implicit_Conditionals) then
796
            declare
797
                  T : constant Entity_Id :=
798
                        Make_Defining_Identifier (Loc, Chars => Name_T);
799
 
800
            begin
801
               Rewrite (N,
802
                 Make_Block_Statement (Loc,
803
                  Declarations => New_List (
804
                    Make_Object_Declaration (Loc,
805
                      Defining_Identifier => T,
806
                      Constant_Present  => True,
807
                      Object_Definition =>
808
                        New_Occurrence_Of (Etype (Rhs), Loc),
809
                      Expression        => Relocate_Node (Rhs))),
810
 
811
                    Handled_Statement_Sequence =>
812
                      Make_Handled_Sequence_Of_Statements (Loc,
813
                        Statements => New_List (
814
                          Make_Assignment_Statement (Loc,
815
                            Name       => Relocate_Node (Lhs),
816
                            Expression => New_Occurrence_Of (T, Loc))))));
817
            end;
818
 
819
         --  Case of both are false with implicit conditionals allowed
820
 
821
         else
822
            --  Before we generate this code, we must ensure that the left and
823
            --  right side array types are defined. They may be itypes, and we
824
            --  cannot let them be defined inside the if, since the first use
825
            --  in the then may not be executed.
826
 
827
            Ensure_Defined (L_Type, N);
828
            Ensure_Defined (R_Type, N);
829
 
830
            --  We normally compare addresses to find out which way round to
831
            --  do the loop, since this is reliable, and handles the cases of
832
            --  parameters, conversions etc. But we can't do that in the bit
833
            --  packed case or the VM case, because addresses don't work there.
834
 
835
            if not Is_Bit_Packed_Array (L_Type) and then VM_Target = No_VM then
836
               Condition :=
837
                 Make_Op_Le (Loc,
838
                   Left_Opnd =>
839
                     Unchecked_Convert_To (RTE (RE_Integer_Address),
840
                       Make_Attribute_Reference (Loc,
841
                         Prefix =>
842
                           Make_Indexed_Component (Loc,
843
                             Prefix =>
844
                               Duplicate_Subexpr_Move_Checks (Larray, True),
845
                             Expressions => New_List (
846
                               Make_Attribute_Reference (Loc,
847
                                 Prefix =>
848
                                   New_Reference_To
849
                                     (L_Index_Typ, Loc),
850
                                 Attribute_Name => Name_First))),
851
                         Attribute_Name => Name_Address)),
852
 
853
                   Right_Opnd =>
854
                     Unchecked_Convert_To (RTE (RE_Integer_Address),
855
                       Make_Attribute_Reference (Loc,
856
                         Prefix =>
857
                           Make_Indexed_Component (Loc,
858
                             Prefix =>
859
                               Duplicate_Subexpr_Move_Checks (Rarray, True),
860
                             Expressions => New_List (
861
                               Make_Attribute_Reference (Loc,
862
                                 Prefix =>
863
                                   New_Reference_To
864
                                     (R_Index_Typ, Loc),
865
                                 Attribute_Name => Name_First))),
866
                         Attribute_Name => Name_Address)));
867
 
868
            --  For the bit packed and VM cases we use the bounds. That's OK,
869
            --  because we don't have to worry about parameters, since they
870
            --  cannot cause overlap. Perhaps we should worry about weird slice
871
            --  conversions ???
872
 
873
            else
874
               --  Copy the bounds
875
 
876
               Cleft_Lo  := New_Copy_Tree (Left_Lo);
877
               Cright_Lo := New_Copy_Tree (Right_Lo);
878
 
879
               --  If the types do not match we add an implicit conversion
880
               --  here to ensure proper match
881
 
882
               if Etype (Left_Lo) /= Etype (Right_Lo) then
883
                  Cright_Lo :=
884
                    Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
885
               end if;
886
 
887
               --  Reset the Analyzed flag, because the bounds of the index
888
               --  type itself may be universal, and must must be reaanalyzed
889
               --  to acquire the proper type for the back end.
890
 
891
               Set_Analyzed (Cleft_Lo, False);
892
               Set_Analyzed (Cright_Lo, False);
893
 
894
               Condition :=
895
                 Make_Op_Le (Loc,
896
                   Left_Opnd  => Cleft_Lo,
897
                   Right_Opnd => Cright_Lo);
898
            end if;
899
 
900
            if Needs_Finalization (Component_Type (L_Type))
901
              and then Base_Type (L_Type) = Base_Type (R_Type)
902
              and then Ndim = 1
903
              and then not No_Ctrl_Actions (N)
904
            then
905
 
906
               --  Call TSS procedure for array assignment, passing the
907
               --  explicit bounds of right and left hand sides.
908
 
909
               declare
910
                  Proc    : constant Entity_Id :=
911
                              TSS (Base_Type (L_Type), TSS_Slice_Assign);
912
                  Actuals : List_Id;
913
 
914
               begin
915
                  Apply_Dereference (Larray);
916
                  Apply_Dereference (Rarray);
917
                  Actuals := New_List (
918
                    Duplicate_Subexpr (Larray,   Name_Req => True),
919
                    Duplicate_Subexpr (Rarray,   Name_Req => True),
920
                    Duplicate_Subexpr (Left_Lo,  Name_Req => True),
921
                    Duplicate_Subexpr (Left_Hi,  Name_Req => True),
922
                    Duplicate_Subexpr (Right_Lo, Name_Req => True),
923
                    Duplicate_Subexpr (Right_Hi, Name_Req => True));
924
 
925
                  Append_To (Actuals,
926
                     Make_Op_Not (Loc,
927
                       Right_Opnd => Condition));
928
 
929
                  Rewrite (N,
930
                    Make_Procedure_Call_Statement (Loc,
931
                      Name => New_Reference_To (Proc, Loc),
932
                      Parameter_Associations => Actuals));
933
               end;
934
 
935
            else
936
               Rewrite (N,
937
                 Make_Implicit_If_Statement (N,
938
                   Condition => Condition,
939
 
940
                   Then_Statements => New_List (
941
                     Expand_Assign_Array_Loop
942
                      (N, Larray, Rarray, L_Type, R_Type, Ndim,
943
                       Rev => False)),
944
 
945
                   Else_Statements => New_List (
946
                     Expand_Assign_Array_Loop
947
                      (N, Larray, Rarray, L_Type, R_Type, Ndim,
948
                       Rev => True))));
949
            end if;
950
         end if;
951
 
952
         Analyze (N, Suppress => All_Checks);
953
      end;
954
 
955
   exception
956
      when RE_Not_Available =>
957
         return;
958
   end Expand_Assign_Array;
959
 
960
   ------------------------------
961
   -- Expand_Assign_Array_Loop --
962
   ------------------------------
963
 
964
   --  The following is an example of the loop generated for the case of a
965
   --  two-dimensional array:
966
 
967
   --    declare
968
   --       R2b : Tm1X1 := 1;
969
   --    begin
970
   --       for L1b in 1 .. 100 loop
971
   --          declare
972
   --             R4b : Tm1X2 := 1;
973
   --          begin
974
   --             for L3b in 1 .. 100 loop
975
   --                vm1 (L1b, L3b) := vm2 (R2b, R4b);
976
   --                R4b := Tm1X2'succ(R4b);
977
   --             end loop;
978
   --          end;
979
   --          R2b := Tm1X1'succ(R2b);
980
   --       end loop;
981
   --    end;
982
 
983
   --  Here Rev is False, and Tm1Xn are the subscript types for the right hand
984
   --  side. The declarations of R2b and R4b are inserted before the original
985
   --  assignment statement.
986
 
987
   function Expand_Assign_Array_Loop
988
     (N      : Node_Id;
989
      Larray : Entity_Id;
990
      Rarray : Entity_Id;
991
      L_Type : Entity_Id;
992
      R_Type : Entity_Id;
993
      Ndim   : Pos;
994
      Rev    : Boolean) return Node_Id
995
   is
996
      Loc  : constant Source_Ptr := Sloc (N);
997
 
998
      Lnn : array (1 .. Ndim) of Entity_Id;
999
      Rnn : array (1 .. Ndim) of Entity_Id;
1000
      --  Entities used as subscripts on left and right sides
1001
 
1002
      L_Index_Type : array (1 .. Ndim) of Entity_Id;
1003
      R_Index_Type : array (1 .. Ndim) of Entity_Id;
1004
      --  Left and right index types
1005
 
1006
      Assign : Node_Id;
1007
 
1008
      F_Or_L : Name_Id;
1009
      S_Or_P : Name_Id;
1010
 
1011
   begin
1012
      if Rev then
1013
         F_Or_L := Name_Last;
1014
         S_Or_P := Name_Pred;
1015
      else
1016
         F_Or_L := Name_First;
1017
         S_Or_P := Name_Succ;
1018
      end if;
1019
 
1020
      --  Setup index types and subscript entities
1021
 
1022
      declare
1023
         L_Index : Node_Id;
1024
         R_Index : Node_Id;
1025
 
1026
      begin
1027
         L_Index := First_Index (L_Type);
1028
         R_Index := First_Index (R_Type);
1029
 
1030
         for J in 1 .. Ndim loop
1031
            Lnn (J) :=
1032
              Make_Defining_Identifier (Loc,
1033
                Chars => New_Internal_Name ('L'));
1034
 
1035
            Rnn (J) :=
1036
              Make_Defining_Identifier (Loc,
1037
                Chars => New_Internal_Name ('R'));
1038
 
1039
            L_Index_Type (J) := Etype (L_Index);
1040
            R_Index_Type (J) := Etype (R_Index);
1041
 
1042
            Next_Index (L_Index);
1043
            Next_Index (R_Index);
1044
         end loop;
1045
      end;
1046
 
1047
      --  Now construct the assignment statement
1048
 
1049
      declare
1050
         ExprL : constant List_Id := New_List;
1051
         ExprR : constant List_Id := New_List;
1052
 
1053
      begin
1054
         for J in 1 .. Ndim loop
1055
            Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1056
            Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1057
         end loop;
1058
 
1059
         Assign :=
1060
           Make_Assignment_Statement (Loc,
1061
             Name =>
1062
               Make_Indexed_Component (Loc,
1063
                 Prefix      => Duplicate_Subexpr (Larray, Name_Req => True),
1064
                 Expressions => ExprL),
1065
             Expression =>
1066
               Make_Indexed_Component (Loc,
1067
                 Prefix      => Duplicate_Subexpr (Rarray, Name_Req => True),
1068
                 Expressions => ExprR));
1069
 
1070
         --  We set assignment OK, since there are some cases, e.g. in object
1071
         --  declarations, where we are actually assigning into a constant.
1072
         --  If there really is an illegality, it was caught long before now,
1073
         --  and was flagged when the original assignment was analyzed.
1074
 
1075
         Set_Assignment_OK (Name (Assign));
1076
 
1077
         --  Propagate the No_Ctrl_Actions flag to individual assignments
1078
 
1079
         Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1080
      end;
1081
 
1082
      --  Now construct the loop from the inside out, with the last subscript
1083
      --  varying most rapidly. Note that Assign is first the raw assignment
1084
      --  statement, and then subsequently the loop that wraps it up.
1085
 
1086
      for J in reverse 1 .. Ndim loop
1087
         Assign :=
1088
           Make_Block_Statement (Loc,
1089
             Declarations => New_List (
1090
              Make_Object_Declaration (Loc,
1091
                Defining_Identifier => Rnn (J),
1092
                Object_Definition =>
1093
                  New_Occurrence_Of (R_Index_Type (J), Loc),
1094
                Expression =>
1095
                  Make_Attribute_Reference (Loc,
1096
                    Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1097
                    Attribute_Name => F_Or_L))),
1098
 
1099
           Handled_Statement_Sequence =>
1100
             Make_Handled_Sequence_Of_Statements (Loc,
1101
               Statements => New_List (
1102
                 Make_Implicit_Loop_Statement (N,
1103
                   Iteration_Scheme =>
1104
                     Make_Iteration_Scheme (Loc,
1105
                       Loop_Parameter_Specification =>
1106
                         Make_Loop_Parameter_Specification (Loc,
1107
                           Defining_Identifier => Lnn (J),
1108
                           Reverse_Present => Rev,
1109
                           Discrete_Subtype_Definition =>
1110
                             New_Reference_To (L_Index_Type (J), Loc))),
1111
 
1112
                   Statements => New_List (
1113
                     Assign,
1114
 
1115
                     Make_Assignment_Statement (Loc,
1116
                       Name => New_Occurrence_Of (Rnn (J), Loc),
1117
                       Expression =>
1118
                         Make_Attribute_Reference (Loc,
1119
                           Prefix =>
1120
                             New_Occurrence_Of (R_Index_Type (J), Loc),
1121
                           Attribute_Name => S_Or_P,
1122
                           Expressions => New_List (
1123
                             New_Occurrence_Of (Rnn (J), Loc)))))))));
1124
      end loop;
1125
 
1126
      return Assign;
1127
   end Expand_Assign_Array_Loop;
1128
 
1129
   --------------------------
1130
   -- Expand_Assign_Record --
1131
   --------------------------
1132
 
1133
   procedure Expand_Assign_Record (N : Node_Id) is
1134
      Lhs   : constant Node_Id    := Name (N);
1135
      Rhs   : Node_Id             := Expression (N);
1136
      L_Typ : constant Entity_Id  := Base_Type (Etype (Lhs));
1137
 
1138
   begin
1139
      --  If change of representation, then extract the real right hand side
1140
      --  from the type conversion, and proceed with component-wise assignment,
1141
      --  since the two types are not the same as far as the back end is
1142
      --  concerned.
1143
 
1144
      if Change_Of_Representation (N) then
1145
         Rhs := Expression (Rhs);
1146
 
1147
      --  If this may be a case of a large bit aligned component, then proceed
1148
      --  with component-wise assignment, to avoid possible clobbering of other
1149
      --  components sharing bits in the first or last byte of the component to
1150
      --  be assigned.
1151
 
1152
      elsif Possible_Bit_Aligned_Component (Lhs)
1153
              or
1154
            Possible_Bit_Aligned_Component (Rhs)
1155
      then
1156
         null;
1157
 
1158
      --  If we have a tagged type that has a complete record representation
1159
      --  clause, we must do we must do component-wise assignments, since child
1160
      --  types may have used gaps for their components, and we might be
1161
      --  dealing with a view conversion.
1162
 
1163
      elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1164
         null;
1165
 
1166
      --  If neither condition met, then nothing special to do, the back end
1167
      --  can handle assignment of the entire component as a single entity.
1168
 
1169
      else
1170
         return;
1171
      end if;
1172
 
1173
      --  At this stage we know that we must do a component wise assignment
1174
 
1175
      declare
1176
         Loc   : constant Source_Ptr := Sloc (N);
1177
         R_Typ : constant Entity_Id  := Base_Type (Etype (Rhs));
1178
         Decl  : constant Node_Id    := Declaration_Node (R_Typ);
1179
         RDef  : Node_Id;
1180
         F     : Entity_Id;
1181
 
1182
         function Find_Component
1183
           (Typ  : Entity_Id;
1184
            Comp : Entity_Id) return Entity_Id;
1185
         --  Find the component with the given name in the underlying record
1186
         --  declaration for Typ. We need to use the actual entity because the
1187
         --  type may be private and resolution by identifier alone would fail.
1188
 
1189
         function Make_Component_List_Assign
1190
           (CL  : Node_Id;
1191
            U_U : Boolean := False) return List_Id;
1192
         --  Returns a sequence of statements to assign the components that
1193
         --  are referenced in the given component list. The flag U_U is
1194
         --  used to force the usage of the inferred value of the variant
1195
         --  part expression as the switch for the generated case statement.
1196
 
1197
         function Make_Field_Assign
1198
           (C : Entity_Id;
1199
            U_U : Boolean := False) return Node_Id;
1200
         --  Given C, the entity for a discriminant or component, build an
1201
         --  assignment for the corresponding field values. The flag U_U
1202
         --  signals the presence of an Unchecked_Union and forces the usage
1203
         --  of the inferred discriminant value of C as the right hand side
1204
         --  of the assignment.
1205
 
1206
         function Make_Field_Assigns (CI : List_Id) return List_Id;
1207
         --  Given CI, a component items list, construct series of statements
1208
         --  for fieldwise assignment of the corresponding components.
1209
 
1210
         --------------------
1211
         -- Find_Component --
1212
         --------------------
1213
 
1214
         function Find_Component
1215
           (Typ  : Entity_Id;
1216
            Comp : Entity_Id) return Entity_Id
1217
         is
1218
            Utyp : constant Entity_Id := Underlying_Type (Typ);
1219
            C    : Entity_Id;
1220
 
1221
         begin
1222
            C := First_Entity (Utyp);
1223
            while Present (C) loop
1224
               if Chars (C) = Chars (Comp) then
1225
                  return C;
1226
               end if;
1227
 
1228
               Next_Entity (C);
1229
            end loop;
1230
 
1231
            raise Program_Error;
1232
         end Find_Component;
1233
 
1234
         --------------------------------
1235
         -- Make_Component_List_Assign --
1236
         --------------------------------
1237
 
1238
         function Make_Component_List_Assign
1239
           (CL  : Node_Id;
1240
            U_U : Boolean := False) return List_Id
1241
         is
1242
            CI : constant List_Id := Component_Items (CL);
1243
            VP : constant Node_Id := Variant_Part (CL);
1244
 
1245
            Alts   : List_Id;
1246
            DC     : Node_Id;
1247
            DCH    : List_Id;
1248
            Expr   : Node_Id;
1249
            Result : List_Id;
1250
            V      : Node_Id;
1251
 
1252
         begin
1253
            Result := Make_Field_Assigns (CI);
1254
 
1255
            if Present (VP) then
1256
               V := First_Non_Pragma (Variants (VP));
1257
               Alts := New_List;
1258
               while Present (V) loop
1259
                  DCH := New_List;
1260
                  DC := First (Discrete_Choices (V));
1261
                  while Present (DC) loop
1262
                     Append_To (DCH, New_Copy_Tree (DC));
1263
                     Next (DC);
1264
                  end loop;
1265
 
1266
                  Append_To (Alts,
1267
                    Make_Case_Statement_Alternative (Loc,
1268
                      Discrete_Choices => DCH,
1269
                      Statements =>
1270
                        Make_Component_List_Assign (Component_List (V))));
1271
                  Next_Non_Pragma (V);
1272
               end loop;
1273
 
1274
               --  If we have an Unchecked_Union, use the value of the inferred
1275
               --  discriminant of the variant part expression as the switch
1276
               --  for the case statement. The case statement may later be
1277
               --  folded.
1278
 
1279
               if U_U then
1280
                  Expr :=
1281
                    New_Copy (Get_Discriminant_Value (
1282
                      Entity (Name (VP)),
1283
                      Etype (Rhs),
1284
                      Discriminant_Constraint (Etype (Rhs))));
1285
               else
1286
                  Expr :=
1287
                    Make_Selected_Component (Loc,
1288
                      Prefix => Duplicate_Subexpr (Rhs),
1289
                      Selector_Name =>
1290
                        Make_Identifier (Loc, Chars (Name (VP))));
1291
               end if;
1292
 
1293
               Append_To (Result,
1294
                 Make_Case_Statement (Loc,
1295
                   Expression => Expr,
1296
                   Alternatives => Alts));
1297
            end if;
1298
 
1299
            return Result;
1300
         end Make_Component_List_Assign;
1301
 
1302
         -----------------------
1303
         -- Make_Field_Assign --
1304
         -----------------------
1305
 
1306
         function Make_Field_Assign
1307
           (C : Entity_Id;
1308
            U_U : Boolean := False) return Node_Id
1309
         is
1310
            A    : Node_Id;
1311
            Expr : Node_Id;
1312
 
1313
         begin
1314
            --  In the case of an Unchecked_Union, use the discriminant
1315
            --  constraint value as on the right hand side of the assignment.
1316
 
1317
            if U_U then
1318
               Expr :=
1319
                 New_Copy (Get_Discriminant_Value (C,
1320
                   Etype (Rhs),
1321
                   Discriminant_Constraint (Etype (Rhs))));
1322
            else
1323
               Expr :=
1324
                 Make_Selected_Component (Loc,
1325
                   Prefix => Duplicate_Subexpr (Rhs),
1326
                   Selector_Name => New_Occurrence_Of (C, Loc));
1327
            end if;
1328
 
1329
            A :=
1330
              Make_Assignment_Statement (Loc,
1331
                Name =>
1332
                  Make_Selected_Component (Loc,
1333
                    Prefix => Duplicate_Subexpr (Lhs),
1334
                    Selector_Name =>
1335
                      New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1336
                Expression => Expr);
1337
 
1338
            --  Set Assignment_OK, so discriminants can be assigned
1339
 
1340
            Set_Assignment_OK (Name (A), True);
1341
 
1342
            if Componentwise_Assignment (N)
1343
              and then Nkind (Name (A)) = N_Selected_Component
1344
              and then Chars (Selector_Name (Name (A))) = Name_uParent
1345
            then
1346
               Set_Componentwise_Assignment (A);
1347
            end if;
1348
 
1349
            return A;
1350
         end Make_Field_Assign;
1351
 
1352
         ------------------------
1353
         -- Make_Field_Assigns --
1354
         ------------------------
1355
 
1356
         function Make_Field_Assigns (CI : List_Id) return List_Id is
1357
            Item   : Node_Id;
1358
            Result : List_Id;
1359
 
1360
         begin
1361
            Item := First (CI);
1362
            Result := New_List;
1363
            while Present (Item) loop
1364
 
1365
               --  Look for components, but exclude _tag field assignment if
1366
               --  the special Componentwise_Assignment flag is set.
1367
 
1368
               if Nkind (Item) = N_Component_Declaration
1369
                 and then not (Is_Tag (Defining_Identifier (Item))
1370
                                and then Componentwise_Assignment (N))
1371
               then
1372
                  Append_To
1373
                    (Result, Make_Field_Assign (Defining_Identifier (Item)));
1374
               end if;
1375
 
1376
               Next (Item);
1377
            end loop;
1378
 
1379
            return Result;
1380
         end Make_Field_Assigns;
1381
 
1382
      --  Start of processing for Expand_Assign_Record
1383
 
1384
      begin
1385
         --  Note that we use the base types for this processing. This results
1386
         --  in some extra work in the constrained case, but the change of
1387
         --  representation case is so unusual that it is not worth the effort.
1388
 
1389
         --  First copy the discriminants. This is done unconditionally. It
1390
         --  is required in the unconstrained left side case, and also in the
1391
         --  case where this assignment was constructed during the expansion
1392
         --  of a type conversion (since initialization of discriminants is
1393
         --  suppressed in this case). It is unnecessary but harmless in
1394
         --  other cases.
1395
 
1396
         if Has_Discriminants (L_Typ) then
1397
            F := First_Discriminant (R_Typ);
1398
            while Present (F) loop
1399
 
1400
               --  If we are expanding the initialization of a derived record
1401
               --  that constrains or renames discriminants of the parent, we
1402
               --  must use the corresponding discriminant in the parent.
1403
 
1404
               declare
1405
                  CF : Entity_Id;
1406
 
1407
               begin
1408
                  if Inside_Init_Proc
1409
                    and then Present (Corresponding_Discriminant (F))
1410
                  then
1411
                     CF := Corresponding_Discriminant (F);
1412
                  else
1413
                     CF := F;
1414
                  end if;
1415
 
1416
                  if Is_Unchecked_Union (Base_Type (R_Typ)) then
1417
                     Insert_Action (N, Make_Field_Assign (CF, True));
1418
                  else
1419
                     Insert_Action (N, Make_Field_Assign (CF));
1420
                  end if;
1421
 
1422
                  Next_Discriminant (F);
1423
               end;
1424
            end loop;
1425
         end if;
1426
 
1427
         --  We know the underlying type is a record, but its current view
1428
         --  may be private. We must retrieve the usable record declaration.
1429
 
1430
         if Nkind_In (Decl, N_Private_Type_Declaration,
1431
                            N_Private_Extension_Declaration)
1432
           and then Present (Full_View (R_Typ))
1433
         then
1434
            RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1435
         else
1436
            RDef := Type_Definition (Decl);
1437
         end if;
1438
 
1439
         if Nkind (RDef) = N_Derived_Type_Definition then
1440
            RDef := Record_Extension_Part (RDef);
1441
         end if;
1442
 
1443
         if Nkind (RDef) = N_Record_Definition
1444
           and then Present (Component_List (RDef))
1445
         then
1446
            if Is_Unchecked_Union (R_Typ) then
1447
               Insert_Actions (N,
1448
                 Make_Component_List_Assign (Component_List (RDef), True));
1449
            else
1450
               Insert_Actions
1451
                 (N, Make_Component_List_Assign (Component_List (RDef)));
1452
            end if;
1453
 
1454
            Rewrite (N, Make_Null_Statement (Loc));
1455
         end if;
1456
      end;
1457
   end Expand_Assign_Record;
1458
 
1459
   -----------------------------------
1460
   -- Expand_N_Assignment_Statement --
1461
   -----------------------------------
1462
 
1463
   --  This procedure implements various cases where an assignment statement
1464
   --  cannot just be passed on to the back end in untransformed state.
1465
 
1466
   procedure Expand_N_Assignment_Statement (N : Node_Id) is
1467
      Loc  : constant Source_Ptr := Sloc (N);
1468
      Lhs  : constant Node_Id    := Name (N);
1469
      Rhs  : constant Node_Id    := Expression (N);
1470
      Typ  : constant Entity_Id  := Underlying_Type (Etype (Lhs));
1471
      Exp  : Node_Id;
1472
 
1473
   begin
1474
      --  Special case to check right away, if the Componentwise_Assignment
1475
      --  flag is set, this is a reanalysis from the expansion of the primitive
1476
      --  assignment procedure for a tagged type, and all we need to do is to
1477
      --  expand to assignment of components, because otherwise, we would get
1478
      --  infinite recursion (since this looks like a tagged assignment which
1479
      --  would normally try to *call* the primitive assignment procedure).
1480
 
1481
      if Componentwise_Assignment (N) then
1482
         Expand_Assign_Record (N);
1483
         return;
1484
      end if;
1485
 
1486
      --  Defend against invalid subscripts on left side if we are in standard
1487
      --  validity checking mode. No need to do this if we are checking all
1488
      --  subscripts.
1489
 
1490
      --  Note that we do this right away, because there are some early return
1491
      --  paths in this procedure, and this is required on all paths.
1492
 
1493
      if Validity_Checks_On
1494
        and then Validity_Check_Default
1495
        and then not Validity_Check_Subscripts
1496
      then
1497
         Check_Valid_Lvalue_Subscripts (Lhs);
1498
      end if;
1499
 
1500
      --  Ada 2005 (AI-327): Handle assignment to priority of protected object
1501
 
1502
      --  Rewrite an assignment to X'Priority into a run-time call
1503
 
1504
      --   For example:         X'Priority := New_Prio_Expr;
1505
      --   ...is expanded into  Set_Ceiling (X._Object, New_Prio_Expr);
1506
 
1507
      --  Note that although X'Priority is notionally an object, it is quite
1508
      --  deliberately not defined as an aliased object in the RM. This means
1509
      --  that it works fine to rewrite it as a call, without having to worry
1510
      --  about complications that would other arise from X'Priority'Access,
1511
      --  which is illegal, because of the lack of aliasing.
1512
 
1513
      if Ada_Version >= Ada_05 then
1514
         declare
1515
            Call           : Node_Id;
1516
            Conctyp        : Entity_Id;
1517
            Ent            : Entity_Id;
1518
            Subprg         : Entity_Id;
1519
            RT_Subprg_Name : Node_Id;
1520
 
1521
         begin
1522
            --  Handle chains of renamings
1523
 
1524
            Ent := Name (N);
1525
            while Nkind (Ent) in N_Has_Entity
1526
              and then Present (Entity (Ent))
1527
              and then Present (Renamed_Object (Entity (Ent)))
1528
            loop
1529
               Ent := Renamed_Object (Entity (Ent));
1530
            end loop;
1531
 
1532
            --  The attribute Priority applied to protected objects has been
1533
            --  previously expanded into a call to the Get_Ceiling run-time
1534
            --  subprogram.
1535
 
1536
            if Nkind (Ent) = N_Function_Call
1537
              and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1538
                          or else
1539
                        Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1540
            then
1541
               --  Look for the enclosing concurrent type
1542
 
1543
               Conctyp := Current_Scope;
1544
               while not Is_Concurrent_Type (Conctyp) loop
1545
                  Conctyp := Scope (Conctyp);
1546
               end loop;
1547
 
1548
               pragma Assert (Is_Protected_Type (Conctyp));
1549
 
1550
               --  Generate the first actual of the call
1551
 
1552
               Subprg := Current_Scope;
1553
               while not Present (Protected_Body_Subprogram (Subprg)) loop
1554
                  Subprg := Scope (Subprg);
1555
               end loop;
1556
 
1557
               --  Select the appropriate run-time call
1558
 
1559
               if Number_Entries (Conctyp) = 0 then
1560
                  RT_Subprg_Name :=
1561
                    New_Reference_To (RTE (RE_Set_Ceiling), Loc);
1562
               else
1563
                  RT_Subprg_Name :=
1564
                    New_Reference_To (RTE (RO_PE_Set_Ceiling), Loc);
1565
               end if;
1566
 
1567
               Call :=
1568
                 Make_Procedure_Call_Statement (Loc,
1569
                   Name => RT_Subprg_Name,
1570
                   Parameter_Associations => New_List (
1571
                     New_Copy_Tree (First (Parameter_Associations (Ent))),
1572
                     Relocate_Node (Expression (N))));
1573
 
1574
               Rewrite (N, Call);
1575
               Analyze (N);
1576
               return;
1577
            end if;
1578
         end;
1579
      end if;
1580
 
1581
      --  First deal with generation of range check if required
1582
 
1583
      if Do_Range_Check (Rhs) then
1584
         Set_Do_Range_Check (Rhs, False);
1585
         Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1586
      end if;
1587
 
1588
      --  Check for a special case where a high level transformation is
1589
      --  required. If we have either of:
1590
 
1591
      --    P.field := rhs;
1592
      --    P (sub) := rhs;
1593
 
1594
      --  where P is a reference to a bit packed array, then we have to unwind
1595
      --  the assignment. The exact meaning of being a reference to a bit
1596
      --  packed array is as follows:
1597
 
1598
      --    An indexed component whose prefix is a bit packed array is a
1599
      --    reference to a bit packed array.
1600
 
1601
      --    An indexed component or selected component whose prefix is a
1602
      --    reference to a bit packed array is itself a reference ot a
1603
      --    bit packed array.
1604
 
1605
      --  The required transformation is
1606
 
1607
      --     Tnn : prefix_type := P;
1608
      --     Tnn.field := rhs;
1609
      --     P := Tnn;
1610
 
1611
      --  or
1612
 
1613
      --     Tnn : prefix_type := P;
1614
      --     Tnn (subscr) := rhs;
1615
      --     P := Tnn;
1616
 
1617
      --  Since P is going to be evaluated more than once, any subscripts
1618
      --  in P must have their evaluation forced.
1619
 
1620
      if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1621
        and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1622
      then
1623
         declare
1624
            BPAR_Expr : constant Node_Id   := Relocate_Node (Prefix (Lhs));
1625
            BPAR_Typ  : constant Entity_Id := Etype (BPAR_Expr);
1626
            Tnn       : constant Entity_Id :=
1627
                          Make_Defining_Identifier (Loc,
1628
                            Chars => New_Internal_Name ('T'));
1629
 
1630
         begin
1631
            --  Insert the post assignment first, because we want to copy the
1632
            --  BPAR_Expr tree before it gets analyzed in the context of the
1633
            --  pre assignment. Note that we do not analyze the post assignment
1634
            --  yet (we cannot till we have completed the analysis of the pre
1635
            --  assignment). As usual, the analysis of this post assignment
1636
            --  will happen on its own when we "run into" it after finishing
1637
            --  the current assignment.
1638
 
1639
            Insert_After (N,
1640
              Make_Assignment_Statement (Loc,
1641
                Name       => New_Copy_Tree (BPAR_Expr),
1642
                Expression => New_Occurrence_Of (Tnn, Loc)));
1643
 
1644
            --  At this stage BPAR_Expr is a reference to a bit packed array
1645
            --  where the reference was not expanded in the original tree,
1646
            --  since it was on the left side of an assignment. But in the
1647
            --  pre-assignment statement (the object definition), BPAR_Expr
1648
            --  will end up on the right hand side, and must be reexpanded. To
1649
            --  achieve this, we reset the analyzed flag of all selected and
1650
            --  indexed components down to the actual indexed component for
1651
            --  the packed array.
1652
 
1653
            Exp := BPAR_Expr;
1654
            loop
1655
               Set_Analyzed (Exp, False);
1656
 
1657
               if Nkind_In
1658
                   (Exp, N_Selected_Component, N_Indexed_Component)
1659
               then
1660
                  Exp := Prefix (Exp);
1661
               else
1662
                  exit;
1663
               end if;
1664
            end loop;
1665
 
1666
            --  Now we can insert and analyze the pre-assignment
1667
 
1668
            --  If the right-hand side requires a transient scope, it has
1669
            --  already been placed on the stack. However, the declaration is
1670
            --  inserted in the tree outside of this scope, and must reflect
1671
            --  the proper scope for its variable. This awkward bit is forced
1672
            --  by the stricter scope discipline imposed by GCC 2.97.
1673
 
1674
            declare
1675
               Uses_Transient_Scope : constant Boolean :=
1676
                                        Scope_Is_Transient
1677
                                          and then N = Node_To_Be_Wrapped;
1678
 
1679
            begin
1680
               if Uses_Transient_Scope then
1681
                  Push_Scope (Scope (Current_Scope));
1682
               end if;
1683
 
1684
               Insert_Before_And_Analyze (N,
1685
                 Make_Object_Declaration (Loc,
1686
                   Defining_Identifier => Tnn,
1687
                   Object_Definition   => New_Occurrence_Of (BPAR_Typ, Loc),
1688
                   Expression          => BPAR_Expr));
1689
 
1690
               if Uses_Transient_Scope then
1691
                  Pop_Scope;
1692
               end if;
1693
            end;
1694
 
1695
            --  Now fix up the original assignment and continue processing
1696
 
1697
            Rewrite (Prefix (Lhs),
1698
              New_Occurrence_Of (Tnn, Loc));
1699
 
1700
            --  We do not need to reanalyze that assignment, and we do not need
1701
            --  to worry about references to the temporary, but we do need to
1702
            --  make sure that the temporary is not marked as a true constant
1703
            --  since we now have a generated assignment to it!
1704
 
1705
            Set_Is_True_Constant (Tnn, False);
1706
         end;
1707
      end if;
1708
 
1709
      --  When we have the appropriate type of aggregate in the expression (it
1710
      --  has been determined during analysis of the aggregate by setting the
1711
      --  delay flag), let's perform in place assignment and thus avoid
1712
      --  creating a temporary.
1713
 
1714
      if Is_Delayed_Aggregate (Rhs) then
1715
         Convert_Aggr_In_Assignment (N);
1716
         Rewrite (N, Make_Null_Statement (Loc));
1717
         Analyze (N);
1718
         return;
1719
      end if;
1720
 
1721
      --  Apply discriminant check if required. If Lhs is an access type to a
1722
      --  designated type with discriminants, we must always check.
1723
 
1724
      if Has_Discriminants (Etype (Lhs)) then
1725
 
1726
         --  Skip discriminant check if change of representation. Will be
1727
         --  done when the change of representation is expanded out.
1728
 
1729
         if not Change_Of_Representation (N) then
1730
            Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1731
         end if;
1732
 
1733
      --  If the type is private without discriminants, and the full type
1734
      --  has discriminants (necessarily with defaults) a check may still be
1735
      --  necessary if the Lhs is aliased. The private determinants must be
1736
      --  visible to build the discriminant constraints.
1737
 
1738
      --  Only an explicit dereference that comes from source indicates
1739
      --  aliasing. Access to formals of protected operations and entries
1740
      --  create dereferences but are not semantic aliasings.
1741
 
1742
      elsif Is_Private_Type (Etype (Lhs))
1743
        and then Has_Discriminants (Typ)
1744
        and then Nkind (Lhs) = N_Explicit_Dereference
1745
        and then Comes_From_Source (Lhs)
1746
      then
1747
         declare
1748
            Lt : constant Entity_Id := Etype (Lhs);
1749
         begin
1750
            Set_Etype (Lhs, Typ);
1751
            Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1752
            Apply_Discriminant_Check (Rhs, Typ, Lhs);
1753
            Set_Etype (Lhs, Lt);
1754
         end;
1755
 
1756
         --  If the Lhs has a private type with unknown discriminants, it
1757
         --  may have a full view with discriminants, but those are nameable
1758
         --  only in the underlying type, so convert the Rhs to it before
1759
         --  potential checking.
1760
 
1761
      elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1762
        and then Has_Discriminants (Typ)
1763
      then
1764
         Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1765
         Apply_Discriminant_Check (Rhs, Typ, Lhs);
1766
 
1767
      --  In the access type case, we need the same discriminant check, and
1768
      --  also range checks if we have an access to constrained array.
1769
 
1770
      elsif Is_Access_Type (Etype (Lhs))
1771
        and then Is_Constrained (Designated_Type (Etype (Lhs)))
1772
      then
1773
         if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1774
 
1775
            --  Skip discriminant check if change of representation. Will be
1776
            --  done when the change of representation is expanded out.
1777
 
1778
            if not Change_Of_Representation (N) then
1779
               Apply_Discriminant_Check (Rhs, Etype (Lhs));
1780
            end if;
1781
 
1782
         elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1783
            Apply_Range_Check (Rhs, Etype (Lhs));
1784
 
1785
            if Is_Constrained (Etype (Lhs)) then
1786
               Apply_Length_Check (Rhs, Etype (Lhs));
1787
            end if;
1788
 
1789
            if Nkind (Rhs) = N_Allocator then
1790
               declare
1791
                  Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1792
                  C_Es       : Check_Result;
1793
 
1794
               begin
1795
                  C_Es :=
1796
                    Get_Range_Checks
1797
                      (Lhs,
1798
                       Target_Typ,
1799
                       Etype (Designated_Type (Etype (Lhs))));
1800
 
1801
                  Insert_Range_Checks
1802
                    (C_Es,
1803
                     N,
1804
                     Target_Typ,
1805
                     Sloc (Lhs),
1806
                     Lhs);
1807
               end;
1808
            end if;
1809
         end if;
1810
 
1811
      --  Apply range check for access type case
1812
 
1813
      elsif Is_Access_Type (Etype (Lhs))
1814
        and then Nkind (Rhs) = N_Allocator
1815
        and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1816
      then
1817
         Analyze_And_Resolve (Expression (Rhs));
1818
         Apply_Range_Check
1819
           (Expression (Rhs), Designated_Type (Etype (Lhs)));
1820
      end if;
1821
 
1822
      --  Ada 2005 (AI-231): Generate the run-time check
1823
 
1824
      if Is_Access_Type (Typ)
1825
        and then Can_Never_Be_Null (Etype (Lhs))
1826
        and then not Can_Never_Be_Null (Etype (Rhs))
1827
      then
1828
         Apply_Constraint_Check (Rhs, Etype (Lhs));
1829
      end if;
1830
 
1831
      --  Case of assignment to a bit packed array element
1832
 
1833
      if Nkind (Lhs) = N_Indexed_Component
1834
        and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1835
      then
1836
         Expand_Bit_Packed_Element_Set (N);
1837
         return;
1838
 
1839
      --  Build-in-place function call case. Note that we're not yet doing
1840
      --  build-in-place for user-written assignment statements (the assignment
1841
      --  here came from an aggregate.)
1842
 
1843
      elsif Ada_Version >= Ada_05
1844
        and then Is_Build_In_Place_Function_Call (Rhs)
1845
      then
1846
         Make_Build_In_Place_Call_In_Assignment (N, Rhs);
1847
 
1848
      elsif Is_Tagged_Type (Typ) and then Is_Value_Type (Etype (Lhs)) then
1849
 
1850
         --  Nothing to do for valuetypes
1851
         --  ??? Set_Scope_Is_Transient (False);
1852
 
1853
         return;
1854
 
1855
      elsif Is_Tagged_Type (Typ)
1856
        or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
1857
      then
1858
         Tagged_Case : declare
1859
            L                   : List_Id := No_List;
1860
            Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
1861
 
1862
         begin
1863
            --  In the controlled case, we ensure that function calls are
1864
            --  evaluated before finalizing the target. In all cases, it makes
1865
            --  the expansion easier if the side-effects are removed first.
1866
 
1867
            Remove_Side_Effects (Lhs);
1868
            Remove_Side_Effects (Rhs);
1869
 
1870
            --  Avoid recursion in the mechanism
1871
 
1872
            Set_Analyzed (N);
1873
 
1874
            --  If dispatching assignment, we need to dispatch to _assign
1875
 
1876
            if Is_Class_Wide_Type (Typ)
1877
 
1878
               --  If the type is tagged, we may as well use the predefined
1879
               --  primitive assignment. This avoids inlining a lot of code
1880
               --  and in the class-wide case, the assignment is replaced by
1881
               --  dispatch call to _assign. Note that this cannot be done when
1882
               --  discriminant checks are locally suppressed (as in extension
1883
               --  aggregate expansions) because otherwise the discriminant
1884
               --  check will be performed within the _assign call. It is also
1885
               --  suppressed for assignments created by the expander that
1886
               --  correspond to initializations, where we do want to copy the
1887
               --  tag (No_Ctrl_Actions flag set True) by the expander and we
1888
               --  do not need to mess with tags ever (Expand_Ctrl_Actions flag
1889
               --  is set True in this case).
1890
 
1891
               or else (Is_Tagged_Type (Typ)
1892
                         and then not Is_Value_Type (Etype (Lhs))
1893
                         and then Chars (Current_Scope) /= Name_uAssign
1894
                         and then Expand_Ctrl_Actions
1895
                         and then not Discriminant_Checks_Suppressed (Empty))
1896
            then
1897
               --  Fetch the primitive op _assign and proper type to call it.
1898
               --  Because of possible conflicts between private and full view,
1899
               --  fetch the proper type directly from the operation profile.
1900
 
1901
               declare
1902
                  Op    : constant Entity_Id :=
1903
                            Find_Prim_Op (Typ, Name_uAssign);
1904
                  F_Typ : Entity_Id := Etype (First_Formal (Op));
1905
 
1906
               begin
1907
                  --  If the assignment is dispatching, make sure to use the
1908
                  --  proper type.
1909
 
1910
                  if Is_Class_Wide_Type (Typ) then
1911
                     F_Typ := Class_Wide_Type (F_Typ);
1912
                  end if;
1913
 
1914
                  L := New_List;
1915
 
1916
                  --  In case of assignment to a class-wide tagged type, before
1917
                  --  the assignment we generate run-time check to ensure that
1918
                  --  the tags of source and target match.
1919
 
1920
                  if Is_Class_Wide_Type (Typ)
1921
                    and then Is_Tagged_Type (Typ)
1922
                    and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
1923
                  then
1924
                     Append_To (L,
1925
                       Make_Raise_Constraint_Error (Loc,
1926
                         Condition =>
1927
                             Make_Op_Ne (Loc,
1928
                               Left_Opnd =>
1929
                                 Make_Selected_Component (Loc,
1930
                                   Prefix        => Duplicate_Subexpr (Lhs),
1931
                                   Selector_Name =>
1932
                                     Make_Identifier (Loc,
1933
                                       Chars => Name_uTag)),
1934
                               Right_Opnd =>
1935
                                 Make_Selected_Component (Loc,
1936
                                   Prefix        => Duplicate_Subexpr (Rhs),
1937
                                   Selector_Name =>
1938
                                     Make_Identifier (Loc,
1939
                                       Chars => Name_uTag))),
1940
                         Reason => CE_Tag_Check_Failed));
1941
                  end if;
1942
 
1943
                  Append_To (L,
1944
                    Make_Procedure_Call_Statement (Loc,
1945
                      Name => New_Reference_To (Op, Loc),
1946
                      Parameter_Associations => New_List (
1947
                        Unchecked_Convert_To (F_Typ,
1948
                          Duplicate_Subexpr (Lhs)),
1949
                        Unchecked_Convert_To (F_Typ,
1950
                          Duplicate_Subexpr (Rhs)))));
1951
               end;
1952
 
1953
            else
1954
               L := Make_Tag_Ctrl_Assignment (N);
1955
 
1956
               --  We can't afford to have destructive Finalization Actions in
1957
               --  the Self assignment case, so if the target and the source
1958
               --  are not obviously different, code is generated to avoid the
1959
               --  self assignment case:
1960
 
1961
               --    if lhs'address /= rhs'address then
1962
               --       <code for controlled and/or tagged assignment>
1963
               --    end if;
1964
 
1965
               --  Skip this if Restriction (No_Finalization) is active
1966
 
1967
               if not Statically_Different (Lhs, Rhs)
1968
                 and then Expand_Ctrl_Actions
1969
                 and then not Restriction_Active (No_Finalization)
1970
               then
1971
                  L := New_List (
1972
                    Make_Implicit_If_Statement (N,
1973
                      Condition =>
1974
                        Make_Op_Ne (Loc,
1975
                          Left_Opnd =>
1976
                            Make_Attribute_Reference (Loc,
1977
                              Prefix         => Duplicate_Subexpr (Lhs),
1978
                              Attribute_Name => Name_Address),
1979
 
1980
                           Right_Opnd =>
1981
                            Make_Attribute_Reference (Loc,
1982
                              Prefix         => Duplicate_Subexpr (Rhs),
1983
                              Attribute_Name => Name_Address)),
1984
 
1985
                      Then_Statements => L));
1986
               end if;
1987
 
1988
               --  We need to set up an exception handler for implementing
1989
               --  7.6.1(18). The remaining adjustments are tackled by the
1990
               --  implementation of adjust for record_controllers (see
1991
               --  s-finimp.adb).
1992
 
1993
               --  This is skipped if we have no finalization
1994
 
1995
               if Expand_Ctrl_Actions
1996
                 and then not Restriction_Active (No_Finalization)
1997
               then
1998
                  L := New_List (
1999
                    Make_Block_Statement (Loc,
2000
                      Handled_Statement_Sequence =>
2001
                        Make_Handled_Sequence_Of_Statements (Loc,
2002
                          Statements => L,
2003
                          Exception_Handlers => New_List (
2004
                            Make_Handler_For_Ctrl_Operation (Loc)))));
2005
               end if;
2006
            end if;
2007
 
2008
            Rewrite (N,
2009
              Make_Block_Statement (Loc,
2010
                Handled_Statement_Sequence =>
2011
                  Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2012
 
2013
            --  If no restrictions on aborts, protect the whole assignment
2014
            --  for controlled objects as per 9.8(11).
2015
 
2016
            if Needs_Finalization (Typ)
2017
              and then Expand_Ctrl_Actions
2018
              and then Abort_Allowed
2019
            then
2020
               declare
2021
                  Blk : constant Entity_Id :=
2022
                          New_Internal_Entity
2023
                            (E_Block, Current_Scope, Sloc (N), 'B');
2024
 
2025
               begin
2026
                  Set_Scope (Blk, Current_Scope);
2027
                  Set_Etype (Blk, Standard_Void_Type);
2028
                  Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2029
 
2030
                  Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2031
                  Set_At_End_Proc (Handled_Statement_Sequence (N),
2032
                    New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
2033
                  Expand_At_End_Handler
2034
                    (Handled_Statement_Sequence (N), Blk);
2035
               end;
2036
            end if;
2037
 
2038
            --  N has been rewritten to a block statement for which it is
2039
            --  known by construction that no checks are necessary: analyze
2040
            --  it with all checks suppressed.
2041
 
2042
            Analyze (N, Suppress => All_Checks);
2043
            return;
2044
         end Tagged_Case;
2045
 
2046
      --  Array types
2047
 
2048
      elsif Is_Array_Type (Typ) then
2049
         declare
2050
            Actual_Rhs : Node_Id := Rhs;
2051
 
2052
         begin
2053
            while Nkind_In (Actual_Rhs, N_Type_Conversion,
2054
                                        N_Qualified_Expression)
2055
            loop
2056
               Actual_Rhs := Expression (Actual_Rhs);
2057
            end loop;
2058
 
2059
            Expand_Assign_Array (N, Actual_Rhs);
2060
            return;
2061
         end;
2062
 
2063
      --  Record types
2064
 
2065
      elsif Is_Record_Type (Typ) then
2066
         Expand_Assign_Record (N);
2067
         return;
2068
 
2069
      --  Scalar types. This is where we perform the processing related to the
2070
      --  requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2071
      --  scalar values.
2072
 
2073
      elsif Is_Scalar_Type (Typ) then
2074
 
2075
         --  Case where right side is known valid
2076
 
2077
         if Expr_Known_Valid (Rhs) then
2078
 
2079
            --  Here the right side is valid, so it is fine. The case to deal
2080
            --  with is when the left side is a local variable reference whose
2081
            --  value is not currently known to be valid. If this is the case,
2082
            --  and the assignment appears in an unconditional context, then
2083
            --  we can mark the left side as now being valid if one of these
2084
            --  conditions holds:
2085
 
2086
            --    The expression of the right side has Do_Range_Check set so
2087
            --    that we know a range check will be performed. Note that it
2088
            --    can be the case that a range check is omitted because we
2089
            --    make the assumption that we can assume validity for operands
2090
            --    appearing in the right side in determining whether a range
2091
            --    check is required
2092
 
2093
            --    The subtype of the right side matches the subtype of the
2094
            --    left side. In this case, even though we have not checked
2095
            --    the range of the right side, we know it is in range of its
2096
            --    subtype if the expression is valid.
2097
 
2098
            if Is_Local_Variable_Reference (Lhs)
2099
              and then not Is_Known_Valid (Entity (Lhs))
2100
              and then In_Unconditional_Context (N)
2101
            then
2102
               if Do_Range_Check (Rhs)
2103
                 or else Etype (Lhs) = Etype (Rhs)
2104
               then
2105
                  Set_Is_Known_Valid (Entity (Lhs), True);
2106
               end if;
2107
            end if;
2108
 
2109
         --  Case where right side may be invalid in the sense of the RM
2110
         --  reference above. The RM does not require that we check for the
2111
         --  validity on an assignment, but it does require that the assignment
2112
         --  of an invalid value not cause erroneous behavior.
2113
 
2114
         --  The general approach in GNAT is to use the Is_Known_Valid flag
2115
         --  to avoid the need for validity checking on assignments. However
2116
         --  in some cases, we have to do validity checking in order to make
2117
         --  sure that the setting of this flag is correct.
2118
 
2119
         else
2120
            --  Validate right side if we are validating copies
2121
 
2122
            if Validity_Checks_On
2123
              and then Validity_Check_Copies
2124
            then
2125
               --  Skip this if left hand side is an array or record component
2126
               --  and elementary component validity checks are suppressed.
2127
 
2128
               if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2129
                 and then not Validity_Check_Components
2130
               then
2131
                  null;
2132
               else
2133
                  Ensure_Valid (Rhs);
2134
               end if;
2135
 
2136
               --  We can propagate this to the left side where appropriate
2137
 
2138
               if Is_Local_Variable_Reference (Lhs)
2139
                 and then not Is_Known_Valid (Entity (Lhs))
2140
                 and then In_Unconditional_Context (N)
2141
               then
2142
                  Set_Is_Known_Valid (Entity (Lhs), True);
2143
               end if;
2144
 
2145
            --  Otherwise check to see what should be done
2146
 
2147
            --  If left side is a local variable, then we just set its flag to
2148
            --  indicate that its value may no longer be valid, since we are
2149
            --  copying a potentially invalid value.
2150
 
2151
            elsif Is_Local_Variable_Reference (Lhs) then
2152
               Set_Is_Known_Valid (Entity (Lhs), False);
2153
 
2154
            --  Check for case of a nonlocal variable on the left side which
2155
            --  is currently known to be valid. In this case, we simply ensure
2156
            --  that the right side is valid. We only play the game of copying
2157
            --  validity status for local variables, since we are doing this
2158
            --  statically, not by tracing the full flow graph.
2159
 
2160
            elsif Is_Entity_Name (Lhs)
2161
              and then Is_Known_Valid (Entity (Lhs))
2162
            then
2163
               --  Note: If Validity_Checking mode is set to none, we ignore
2164
               --  the Ensure_Valid call so don't worry about that case here.
2165
 
2166
               Ensure_Valid (Rhs);
2167
 
2168
            --  In all other cases, we can safely copy an invalid value without
2169
            --  worrying about the status of the left side. Since it is not a
2170
            --  variable reference it will not be considered
2171
            --  as being known to be valid in any case.
2172
 
2173
            else
2174
               null;
2175
            end if;
2176
         end if;
2177
      end if;
2178
 
2179
   exception
2180
      when RE_Not_Available =>
2181
         return;
2182
   end Expand_N_Assignment_Statement;
2183
 
2184
   ------------------------------
2185
   -- Expand_N_Block_Statement --
2186
   ------------------------------
2187
 
2188
   --  Encode entity names defined in block statement
2189
 
2190
   procedure Expand_N_Block_Statement (N : Node_Id) is
2191
   begin
2192
      Qualify_Entity_Names (N);
2193
   end Expand_N_Block_Statement;
2194
 
2195
   -----------------------------
2196
   -- Expand_N_Case_Statement --
2197
   -----------------------------
2198
 
2199
   procedure Expand_N_Case_Statement (N : Node_Id) is
2200
      Loc    : constant Source_Ptr := Sloc (N);
2201
      Expr   : constant Node_Id    := Expression (N);
2202
      Alt    : Node_Id;
2203
      Len    : Nat;
2204
      Cond   : Node_Id;
2205
      Choice : Node_Id;
2206
      Chlist : List_Id;
2207
 
2208
   begin
2209
      --  Check for the situation where we know at compile time which branch
2210
      --  will be taken
2211
 
2212
      if Compile_Time_Known_Value (Expr) then
2213
         Alt := Find_Static_Alternative (N);
2214
 
2215
         --  Move statements from this alternative after the case statement.
2216
         --  They are already analyzed, so will be skipped by the analyzer.
2217
 
2218
         Insert_List_After (N, Statements (Alt));
2219
 
2220
         --  That leaves the case statement as a shell. So now we can kill all
2221
         --  other alternatives in the case statement.
2222
 
2223
         Kill_Dead_Code (Expression (N));
2224
 
2225
         declare
2226
            A : Node_Id;
2227
 
2228
         begin
2229
            --  Loop through case alternatives, skipping pragmas, and skipping
2230
            --  the one alternative that we select (and therefore retain).
2231
 
2232
            A := First (Alternatives (N));
2233
            while Present (A) loop
2234
               if A /= Alt
2235
                 and then Nkind (A) = N_Case_Statement_Alternative
2236
               then
2237
                  Kill_Dead_Code (Statements (A), Warn_On_Deleted_Code);
2238
               end if;
2239
 
2240
               Next (A);
2241
            end loop;
2242
         end;
2243
 
2244
         Rewrite (N, Make_Null_Statement (Loc));
2245
         return;
2246
      end if;
2247
 
2248
      --  Here if the choice is not determined at compile time
2249
 
2250
      declare
2251
         Last_Alt : constant Node_Id := Last (Alternatives (N));
2252
 
2253
         Others_Present : Boolean;
2254
         Others_Node    : Node_Id;
2255
 
2256
         Then_Stms : List_Id;
2257
         Else_Stms : List_Id;
2258
 
2259
      begin
2260
         if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2261
            Others_Present := True;
2262
            Others_Node    := Last_Alt;
2263
         else
2264
            Others_Present := False;
2265
         end if;
2266
 
2267
         --  First step is to worry about possible invalid argument. The RM
2268
         --  requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2269
         --  outside the base range), then Constraint_Error must be raised.
2270
 
2271
         --  Case of validity check required (validity checks are on, the
2272
         --  expression is not known to be valid, and the case statement
2273
         --  comes from source -- no need to validity check internally
2274
         --  generated case statements).
2275
 
2276
         if Validity_Check_Default then
2277
            Ensure_Valid (Expr);
2278
         end if;
2279
 
2280
         --  If there is only a single alternative, just replace it with the
2281
         --  sequence of statements since obviously that is what is going to
2282
         --  be executed in all cases.
2283
 
2284
         Len := List_Length (Alternatives (N));
2285
 
2286
         if Len = 1 then
2287
            --  We still need to evaluate the expression if it has any
2288
            --  side effects.
2289
 
2290
            Remove_Side_Effects (Expression (N));
2291
 
2292
            Insert_List_After (N, Statements (First (Alternatives (N))));
2293
 
2294
            --  That leaves the case statement as a shell. The alternative that
2295
            --  will be executed is reset to a null list. So now we can kill
2296
            --  the entire case statement.
2297
 
2298
            Kill_Dead_Code (Expression (N));
2299
            Rewrite (N, Make_Null_Statement (Loc));
2300
            return;
2301
         end if;
2302
 
2303
         --  An optimization. If there are only two alternatives, and only
2304
         --  a single choice, then rewrite the whole case statement as an
2305
         --  if statement, since this can result in subsequent optimizations.
2306
         --  This helps not only with case statements in the source of a
2307
         --  simple form, but also with generated code (discriminant check
2308
         --  functions in particular)
2309
 
2310
         if Len = 2 then
2311
            Chlist := Discrete_Choices (First (Alternatives (N)));
2312
 
2313
            if List_Length (Chlist) = 1 then
2314
               Choice := First (Chlist);
2315
 
2316
               Then_Stms := Statements (First (Alternatives (N)));
2317
               Else_Stms := Statements (Last  (Alternatives (N)));
2318
 
2319
               --  For TRUE, generate "expression", not expression = true
2320
 
2321
               if Nkind (Choice) = N_Identifier
2322
                 and then Entity (Choice) = Standard_True
2323
               then
2324
                  Cond := Expression (N);
2325
 
2326
               --  For FALSE, generate "expression" and switch then/else
2327
 
2328
               elsif Nkind (Choice) = N_Identifier
2329
                 and then Entity (Choice) = Standard_False
2330
               then
2331
                  Cond := Expression (N);
2332
                  Else_Stms := Statements (First (Alternatives (N)));
2333
                  Then_Stms := Statements (Last  (Alternatives (N)));
2334
 
2335
               --  For a range, generate "expression in range"
2336
 
2337
               elsif Nkind (Choice) = N_Range
2338
                 or else (Nkind (Choice) = N_Attribute_Reference
2339
                           and then Attribute_Name (Choice) = Name_Range)
2340
                 or else (Is_Entity_Name (Choice)
2341
                           and then Is_Type (Entity (Choice)))
2342
                 or else Nkind (Choice) = N_Subtype_Indication
2343
               then
2344
                  Cond :=
2345
                    Make_In (Loc,
2346
                      Left_Opnd  => Expression (N),
2347
                      Right_Opnd => Relocate_Node (Choice));
2348
 
2349
               --  For any other subexpression "expression = value"
2350
 
2351
               else
2352
                  Cond :=
2353
                    Make_Op_Eq (Loc,
2354
                      Left_Opnd  => Expression (N),
2355
                      Right_Opnd => Relocate_Node (Choice));
2356
               end if;
2357
 
2358
               --  Now rewrite the case as an IF
2359
 
2360
               Rewrite (N,
2361
                 Make_If_Statement (Loc,
2362
                   Condition => Cond,
2363
                   Then_Statements => Then_Stms,
2364
                   Else_Statements => Else_Stms));
2365
               Analyze (N);
2366
               return;
2367
            end if;
2368
         end if;
2369
 
2370
         --  If the last alternative is not an Others choice, replace it with
2371
         --  an N_Others_Choice. Note that we do not bother to call Analyze on
2372
         --  the modified case statement, since it's only effect would be to
2373
         --  compute the contents of the Others_Discrete_Choices which is not
2374
         --  needed by the back end anyway.
2375
 
2376
         --  The reason we do this is that the back end always needs some
2377
         --  default for a switch, so if we have not supplied one in the
2378
         --  processing above for validity checking, then we need to supply
2379
         --  one here.
2380
 
2381
         if not Others_Present then
2382
            Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2383
            Set_Others_Discrete_Choices
2384
              (Others_Node, Discrete_Choices (Last_Alt));
2385
            Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2386
         end if;
2387
      end;
2388
   end Expand_N_Case_Statement;
2389
 
2390
   -----------------------------
2391
   -- Expand_N_Exit_Statement --
2392
   -----------------------------
2393
 
2394
   --  The only processing required is to deal with a possible C/Fortran
2395
   --  boolean value used as the condition for the exit statement.
2396
 
2397
   procedure Expand_N_Exit_Statement (N : Node_Id) is
2398
   begin
2399
      Adjust_Condition (Condition (N));
2400
   end Expand_N_Exit_Statement;
2401
 
2402
   ----------------------------------------
2403
   -- Expand_N_Extended_Return_Statement --
2404
   ----------------------------------------
2405
 
2406
   --  If there is a Handled_Statement_Sequence, we rewrite this:
2407
 
2408
   --     return Result : T := <expression> do
2409
   --        <handled_seq_of_stms>
2410
   --     end return;
2411
 
2412
   --  to be:
2413
 
2414
   --     declare
2415
   --        Result : T := <expression>;
2416
   --     begin
2417
   --        <handled_seq_of_stms>
2418
   --        return Result;
2419
   --     end;
2420
 
2421
   --  Otherwise (no Handled_Statement_Sequence), we rewrite this:
2422
 
2423
   --     return Result : T := <expression>;
2424
 
2425
   --  to be:
2426
 
2427
   --     return <expression>;
2428
 
2429
   --  unless it's build-in-place or there's no <expression>, in which case
2430
   --  we generate:
2431
 
2432
   --     declare
2433
   --        Result : T := <expression>;
2434
   --     begin
2435
   --        return Result;
2436
   --     end;
2437
 
2438
   --  Note that this case could have been written by the user as an extended
2439
   --  return statement, or could have been transformed to this from a simple
2440
   --  return statement.
2441
 
2442
   --  That is, we need to have a reified return object if there are statements
2443
   --  (which might refer to it) or if we're doing build-in-place (so we can
2444
   --  set its address to the final resting place or if there is no expression
2445
   --  (in which case default initial values might need to be set).
2446
 
2447
   procedure Expand_N_Extended_Return_Statement (N : Node_Id) is
2448
      Loc : constant Source_Ptr := Sloc (N);
2449
 
2450
      Return_Object_Entity : constant Entity_Id :=
2451
                               First_Entity (Return_Statement_Entity (N));
2452
      Return_Object_Decl   : constant Node_Id :=
2453
                               Parent (Return_Object_Entity);
2454
      Parent_Function      : constant Entity_Id :=
2455
                               Return_Applies_To (Return_Statement_Entity (N));
2456
      Parent_Function_Typ  : constant Entity_Id := Etype (Parent_Function);
2457
      Is_Build_In_Place    : constant Boolean :=
2458
                               Is_Build_In_Place_Function (Parent_Function);
2459
 
2460
      Return_Stm      : Node_Id;
2461
      Statements      : List_Id;
2462
      Handled_Stm_Seq : Node_Id;
2463
      Result          : Node_Id;
2464
      Exp             : Node_Id;
2465
 
2466
      function Has_Controlled_Parts (Typ : Entity_Id) return Boolean;
2467
      --  Determine whether type Typ is controlled or contains a controlled
2468
      --  subcomponent.
2469
 
2470
      function Move_Activation_Chain return Node_Id;
2471
      --  Construct a call to System.Tasking.Stages.Move_Activation_Chain
2472
      --  with parameters:
2473
      --    From         current activation chain
2474
      --    To           activation chain passed in by the caller
2475
      --    New_Master   master passed in by the caller
2476
 
2477
      function Move_Final_List return Node_Id;
2478
      --  Construct call to System.Finalization_Implementation.Move_Final_List
2479
      --  with parameters:
2480
      --
2481
      --    From         finalization list of the return statement
2482
      --    To           finalization list passed in by the caller
2483
 
2484
      --------------------------
2485
      -- Has_Controlled_Parts --
2486
      --------------------------
2487
 
2488
      function Has_Controlled_Parts (Typ : Entity_Id) return Boolean is
2489
      begin
2490
         return
2491
           Is_Controlled (Typ)
2492
             or else Has_Controlled_Component (Typ);
2493
      end Has_Controlled_Parts;
2494
 
2495
      ---------------------------
2496
      -- Move_Activation_Chain --
2497
      ---------------------------
2498
 
2499
      function Move_Activation_Chain return Node_Id is
2500
         Activation_Chain_Formal : constant Entity_Id :=
2501
                                     Build_In_Place_Formal
2502
                                       (Parent_Function, BIP_Activation_Chain);
2503
         To                      : constant Node_Id :=
2504
                                     New_Reference_To
2505
                                       (Activation_Chain_Formal, Loc);
2506
         Master_Formal           : constant Entity_Id :=
2507
                                     Build_In_Place_Formal
2508
                                       (Parent_Function, BIP_Master);
2509
         New_Master              : constant Node_Id :=
2510
                                     New_Reference_To (Master_Formal, Loc);
2511
 
2512
         Chain_Entity : Entity_Id;
2513
         From         : Node_Id;
2514
 
2515
      begin
2516
         Chain_Entity := First_Entity (Return_Statement_Entity (N));
2517
         while Chars (Chain_Entity) /= Name_uChain loop
2518
            Chain_Entity := Next_Entity (Chain_Entity);
2519
         end loop;
2520
 
2521
         From :=
2522
           Make_Attribute_Reference (Loc,
2523
             Prefix         => New_Reference_To (Chain_Entity, Loc),
2524
             Attribute_Name => Name_Unrestricted_Access);
2525
         --  ??? Not clear why "Make_Identifier (Loc, Name_uChain)" doesn't
2526
         --  work, instead of "New_Reference_To (Chain_Entity, Loc)" above.
2527
 
2528
         return
2529
           Make_Procedure_Call_Statement (Loc,
2530
             Name => New_Reference_To (RTE (RE_Move_Activation_Chain), Loc),
2531
             Parameter_Associations => New_List (From, To, New_Master));
2532
      end Move_Activation_Chain;
2533
 
2534
      ---------------------
2535
      -- Move_Final_List --
2536
      ---------------------
2537
 
2538
      function Move_Final_List return Node_Id is
2539
         Flist : constant Entity_Id  :=
2540
                   Finalization_Chain_Entity (Return_Statement_Entity (N));
2541
 
2542
         From : constant Node_Id := New_Reference_To (Flist, Loc);
2543
 
2544
         Caller_Final_List : constant Entity_Id :=
2545
                               Build_In_Place_Formal
2546
                                 (Parent_Function, BIP_Final_List);
2547
 
2548
         To : constant Node_Id := New_Reference_To (Caller_Final_List, Loc);
2549
 
2550
      begin
2551
         --  Catch cases where a finalization chain entity has not been
2552
         --  associated with the return statement entity.
2553
 
2554
         pragma Assert (Present (Flist));
2555
 
2556
         --  Build required call
2557
 
2558
         return
2559
           Make_If_Statement (Loc,
2560
             Condition =>
2561
               Make_Op_Ne (Loc,
2562
                 Left_Opnd  => New_Copy (From),
2563
                 Right_Opnd => New_Node (N_Null, Loc)),
2564
             Then_Statements =>
2565
               New_List (
2566
                 Make_Procedure_Call_Statement (Loc,
2567
                   Name => New_Reference_To (RTE (RE_Move_Final_List), Loc),
2568
                   Parameter_Associations => New_List (From, To))));
2569
      end Move_Final_List;
2570
 
2571
   --  Start of processing for Expand_N_Extended_Return_Statement
2572
 
2573
   begin
2574
      if Nkind (Return_Object_Decl) = N_Object_Declaration then
2575
         Exp := Expression (Return_Object_Decl);
2576
      else
2577
         Exp := Empty;
2578
      end if;
2579
 
2580
      Handled_Stm_Seq := Handled_Statement_Sequence (N);
2581
 
2582
      --  Build a simple_return_statement that returns the return object when
2583
      --  there is a statement sequence, or no expression, or the result will
2584
      --  be built in place. Note however that we currently do this for all
2585
      --  composite cases, even though nonlimited composite results are not yet
2586
      --  built in place (though we plan to do so eventually).
2587
 
2588
      if Present (Handled_Stm_Seq)
2589
        or else Is_Composite_Type (Etype (Parent_Function))
2590
        or else No (Exp)
2591
      then
2592
         if No (Handled_Stm_Seq) then
2593
            Statements := New_List;
2594
 
2595
         --  If the extended return has a handled statement sequence, then wrap
2596
         --  it in a block and use the block as the first statement.
2597
 
2598
         else
2599
            Statements :=
2600
              New_List (Make_Block_Statement (Loc,
2601
                          Declarations => New_List,
2602
                          Handled_Statement_Sequence => Handled_Stm_Seq));
2603
         end if;
2604
 
2605
         --  If control gets past the above Statements, we have successfully
2606
         --  completed the return statement. If the result type has controlled
2607
         --  parts and the return is for a build-in-place function, then we
2608
         --  call Move_Final_List to transfer responsibility for finalization
2609
         --  of the return object to the caller. An alternative would be to
2610
         --  declare a Success flag in the function, initialize it to False,
2611
         --  and set it to True here. Then move the Move_Final_List call into
2612
         --  the cleanup code, and check Success. If Success then make a call
2613
         --  to Move_Final_List else do finalization. Then we can remove the
2614
         --  abort-deferral and the nulling-out of the From parameter from
2615
         --  Move_Final_List. Note that the current method is not quite correct
2616
         --  in the rather obscure case of a select-then-abort statement whose
2617
         --  abortable part contains the return statement.
2618
 
2619
         --  Check the type of the function to determine whether to move the
2620
         --  finalization list. A special case arises when processing a simple
2621
         --  return statement which has been rewritten as an extended return.
2622
         --  In that case check the type of the returned object or the original
2623
         --  expression.
2624
 
2625
         if Is_Build_In_Place
2626
           and then
2627
               (Has_Controlled_Parts (Parent_Function_Typ)
2628
                 or else (Is_Class_Wide_Type (Parent_Function_Typ)
2629
                           and then
2630
                        Has_Controlled_Parts (Root_Type (Parent_Function_Typ)))
2631
                 or else Has_Controlled_Parts (Etype (Return_Object_Entity))
2632
                 or else (Present (Exp)
2633
                           and then Has_Controlled_Parts (Etype (Exp))))
2634
         then
2635
            Append_To (Statements, Move_Final_List);
2636
         end if;
2637
 
2638
         --  Similarly to the above Move_Final_List, if the result type
2639
         --  contains tasks, we call Move_Activation_Chain. Later, the cleanup
2640
         --  code will call Complete_Master, which will terminate any
2641
         --  unactivated tasks belonging to the return statement master. But
2642
         --  Move_Activation_Chain updates their master to be that of the
2643
         --  caller, so they will not be terminated unless the return statement
2644
         --  completes unsuccessfully due to exception, abort, goto, or exit.
2645
         --  As a formality, we test whether the function requires the result
2646
         --  to be built in place, though that's necessarily true for the case
2647
         --  of result types with task parts.
2648
 
2649
         if Is_Build_In_Place and Has_Task (Etype (Parent_Function)) then
2650
            Append_To (Statements, Move_Activation_Chain);
2651
         end if;
2652
 
2653
         --  Build a simple_return_statement that returns the return object
2654
 
2655
         Return_Stm :=
2656
           Make_Simple_Return_Statement (Loc,
2657
             Expression => New_Occurrence_Of (Return_Object_Entity, Loc));
2658
         Append_To (Statements, Return_Stm);
2659
 
2660
         Handled_Stm_Seq :=
2661
           Make_Handled_Sequence_Of_Statements (Loc, Statements);
2662
      end if;
2663
 
2664
      --  Case where we build a block
2665
 
2666
      if Present (Handled_Stm_Seq) then
2667
         Result :=
2668
           Make_Block_Statement (Loc,
2669
             Declarations => Return_Object_Declarations (N),
2670
             Handled_Statement_Sequence => Handled_Stm_Seq);
2671
 
2672
         --  We set the entity of the new block statement to be that of the
2673
         --  return statement. This is necessary so that various fields, such
2674
         --  as Finalization_Chain_Entity carry over from the return statement
2675
         --  to the block. Note that this block is unusual, in that its entity
2676
         --  is an E_Return_Statement rather than an E_Block.
2677
 
2678
         Set_Identifier
2679
           (Result, New_Occurrence_Of (Return_Statement_Entity (N), Loc));
2680
 
2681
         --  If the object decl was already rewritten as a renaming, then
2682
         --  we don't want to do the object allocation and transformation of
2683
         --  of the return object declaration to a renaming. This case occurs
2684
         --  when the return object is initialized by a call to another
2685
         --  build-in-place function, and that function is responsible for the
2686
         --  allocation of the return object.
2687
 
2688
         if Is_Build_In_Place
2689
           and then
2690
             Nkind (Return_Object_Decl) = N_Object_Renaming_Declaration
2691
         then
2692
            pragma Assert (Nkind (Original_Node (Return_Object_Decl)) =
2693
                            N_Object_Declaration
2694
              and then Is_Build_In_Place_Function_Call
2695
                         (Expression (Original_Node (Return_Object_Decl))));
2696
 
2697
            Set_By_Ref (Return_Stm);  -- Return build-in-place results by ref
2698
 
2699
         elsif Is_Build_In_Place then
2700
 
2701
            --  Locate the implicit access parameter associated with the
2702
            --  caller-supplied return object and convert the return
2703
            --  statement's return object declaration to a renaming of a
2704
            --  dereference of the access parameter. If the return object's
2705
            --  declaration includes an expression that has not already been
2706
            --  expanded as separate assignments, then add an assignment
2707
            --  statement to ensure the return object gets initialized.
2708
 
2709
            --  declare
2710
            --     Result : T [:= <expression>];
2711
            --  begin
2712
            --     ...
2713
 
2714
            --  is converted to
2715
 
2716
            --  declare
2717
            --     Result : T renames FuncRA.all;
2718
            --     [Result := <expression;]
2719
            --  begin
2720
            --     ...
2721
 
2722
            declare
2723
               Return_Obj_Id    : constant Entity_Id :=
2724
                                    Defining_Identifier (Return_Object_Decl);
2725
               Return_Obj_Typ   : constant Entity_Id := Etype (Return_Obj_Id);
2726
               Return_Obj_Expr  : constant Node_Id :=
2727
                                    Expression (Return_Object_Decl);
2728
               Result_Subt      : constant Entity_Id :=
2729
                                    Etype (Parent_Function);
2730
               Constr_Result    : constant Boolean :=
2731
                                    Is_Constrained (Result_Subt);
2732
               Obj_Alloc_Formal : Entity_Id;
2733
               Object_Access    : Entity_Id;
2734
               Obj_Acc_Deref    : Node_Id;
2735
               Init_Assignment  : Node_Id := Empty;
2736
 
2737
            begin
2738
               --  Build-in-place results must be returned by reference
2739
 
2740
               Set_By_Ref (Return_Stm);
2741
 
2742
               --  Retrieve the implicit access parameter passed by the caller
2743
 
2744
               Object_Access :=
2745
                 Build_In_Place_Formal (Parent_Function, BIP_Object_Access);
2746
 
2747
               --  If the return object's declaration includes an expression
2748
               --  and the declaration isn't marked as No_Initialization, then
2749
               --  we need to generate an assignment to the object and insert
2750
               --  it after the declaration before rewriting it as a renaming
2751
               --  (otherwise we'll lose the initialization). The case where
2752
               --  the result type is an interface (or class-wide interface)
2753
               --  is also excluded because the context of the function call
2754
               --  must be unconstrained, so the initialization will always
2755
               --  be done as part of an allocator evaluation (storage pool
2756
               --  or secondary stack), never to a constrained target object
2757
               --  passed in by the caller. Besides the assignment being
2758
               --  unneeded in this case, it avoids problems with trying to
2759
               --  generate a dispatching assignment when the return expression
2760
               --  is a nonlimited descendant of a limited interface (the
2761
               --  interface has no assignment operation).
2762
 
2763
               if Present (Return_Obj_Expr)
2764
                 and then not No_Initialization (Return_Object_Decl)
2765
                 and then not Is_Interface (Return_Obj_Typ)
2766
               then
2767
                  Init_Assignment :=
2768
                    Make_Assignment_Statement (Loc,
2769
                      Name       => New_Reference_To (Return_Obj_Id, Loc),
2770
                      Expression => Relocate_Node (Return_Obj_Expr));
2771
                  Set_Etype (Name (Init_Assignment), Etype (Return_Obj_Id));
2772
                  Set_Assignment_OK (Name (Init_Assignment));
2773
                  Set_No_Ctrl_Actions (Init_Assignment);
2774
 
2775
                  Set_Parent (Name (Init_Assignment), Init_Assignment);
2776
                  Set_Parent (Expression (Init_Assignment), Init_Assignment);
2777
 
2778
                  Set_Expression (Return_Object_Decl, Empty);
2779
 
2780
                  if Is_Class_Wide_Type (Etype (Return_Obj_Id))
2781
                    and then not Is_Class_Wide_Type
2782
                                   (Etype (Expression (Init_Assignment)))
2783
                  then
2784
                     Rewrite (Expression (Init_Assignment),
2785
                       Make_Type_Conversion (Loc,
2786
                         Subtype_Mark =>
2787
                           New_Occurrence_Of
2788
                             (Etype (Return_Obj_Id), Loc),
2789
                         Expression =>
2790
                           Relocate_Node (Expression (Init_Assignment))));
2791
                  end if;
2792
 
2793
                  --  In the case of functions where the calling context can
2794
                  --  determine the form of allocation needed, initialization
2795
                  --  is done with each part of the if statement that handles
2796
                  --  the different forms of allocation (this is true for
2797
                  --  unconstrained and tagged result subtypes).
2798
 
2799
                  if Constr_Result
2800
                    and then not Is_Tagged_Type (Underlying_Type (Result_Subt))
2801
                  then
2802
                     Insert_After (Return_Object_Decl, Init_Assignment);
2803
                  end if;
2804
               end if;
2805
 
2806
               --  When the function's subtype is unconstrained, a run-time
2807
               --  test is needed to determine the form of allocation to use
2808
               --  for the return object. The function has an implicit formal
2809
               --  parameter indicating this. If the BIP_Alloc_Form formal has
2810
               --  the value one, then the caller has passed access to an
2811
               --  existing object for use as the return object. If the value
2812
               --  is two, then the return object must be allocated on the
2813
               --  secondary stack. Otherwise, the object must be allocated in
2814
               --  a storage pool (currently only supported for the global
2815
               --  heap, user-defined storage pools TBD ???). We generate an
2816
               --  if statement to test the implicit allocation formal and
2817
               --  initialize a local access value appropriately, creating
2818
               --  allocators in the secondary stack and global heap cases.
2819
               --  The special formal also exists and must be tested when the
2820
               --  function has a tagged result, even when the result subtype
2821
               --  is constrained, because in general such functions can be
2822
               --  called in dispatching contexts and must be handled similarly
2823
               --  to functions with a class-wide result.
2824
 
2825
               if not Constr_Result
2826
                 or else Is_Tagged_Type (Underlying_Type (Result_Subt))
2827
               then
2828
                  Obj_Alloc_Formal :=
2829
                    Build_In_Place_Formal (Parent_Function, BIP_Alloc_Form);
2830
 
2831
                  declare
2832
                     Ref_Type       : Entity_Id;
2833
                     Ptr_Type_Decl  : Node_Id;
2834
                     Alloc_Obj_Id   : Entity_Id;
2835
                     Alloc_Obj_Decl : Node_Id;
2836
                     Alloc_If_Stmt  : Node_Id;
2837
                     SS_Allocator   : Node_Id;
2838
                     Heap_Allocator : Node_Id;
2839
 
2840
                  begin
2841
                     --  Reuse the itype created for the function's implicit
2842
                     --  access formal. This avoids the need to create a new
2843
                     --  access type here, plus it allows assigning the access
2844
                     --  formal directly without applying a conversion.
2845
 
2846
                     --  Ref_Type := Etype (Object_Access);
2847
 
2848
                     --  Create an access type designating the function's
2849
                     --  result subtype.
2850
 
2851
                     Ref_Type :=
2852
                       Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
2853
 
2854
                     Ptr_Type_Decl :=
2855
                       Make_Full_Type_Declaration (Loc,
2856
                         Defining_Identifier => Ref_Type,
2857
                         Type_Definition =>
2858
                           Make_Access_To_Object_Definition (Loc,
2859
                             All_Present => True,
2860
                             Subtype_Indication =>
2861
                               New_Reference_To (Return_Obj_Typ, Loc)));
2862
 
2863
                     Insert_Before (Return_Object_Decl, Ptr_Type_Decl);
2864
 
2865
                     --  Create an access object that will be initialized to an
2866
                     --  access value denoting the return object, either coming
2867
                     --  from an implicit access value passed in by the caller
2868
                     --  or from the result of an allocator.
2869
 
2870
                     Alloc_Obj_Id :=
2871
                       Make_Defining_Identifier (Loc,
2872
                         Chars => New_Internal_Name ('R'));
2873
                     Set_Etype (Alloc_Obj_Id, Ref_Type);
2874
 
2875
                     Alloc_Obj_Decl :=
2876
                       Make_Object_Declaration (Loc,
2877
                         Defining_Identifier => Alloc_Obj_Id,
2878
                         Object_Definition   => New_Reference_To
2879
                                                  (Ref_Type, Loc));
2880
 
2881
                     Insert_Before (Return_Object_Decl, Alloc_Obj_Decl);
2882
 
2883
                     --  Create allocators for both the secondary stack and
2884
                     --  global heap. If there's an initialization expression,
2885
                     --  then create these as initialized allocators.
2886
 
2887
                     if Present (Return_Obj_Expr)
2888
                       and then not No_Initialization (Return_Object_Decl)
2889
                     then
2890
                        --  Always use the type of the expression for the
2891
                        --  qualified expression, rather than the result type.
2892
                        --  In general we cannot always use the result type
2893
                        --  for the allocator, because the expression might be
2894
                        --  of a specific type, such as in the case of an
2895
                        --  aggregate or even a nonlimited object when the
2896
                        --  result type is a limited class-wide interface type.
2897
 
2898
                        Heap_Allocator :=
2899
                          Make_Allocator (Loc,
2900
                            Expression =>
2901
                              Make_Qualified_Expression (Loc,
2902
                                Subtype_Mark =>
2903
                                  New_Reference_To
2904
                                    (Etype (Return_Obj_Expr), Loc),
2905
                                Expression =>
2906
                                  New_Copy_Tree (Return_Obj_Expr)));
2907
 
2908
                     else
2909
                        --  If the function returns a class-wide type we cannot
2910
                        --  use the return type for the allocator. Instead we
2911
                        --  use the type of the expression, which must be an
2912
                        --  aggregate of a definite type.
2913
 
2914
                        if Is_Class_Wide_Type (Return_Obj_Typ) then
2915
                           Heap_Allocator :=
2916
                             Make_Allocator (Loc,
2917
                               Expression =>
2918
                                 New_Reference_To
2919
                                   (Etype (Return_Obj_Expr), Loc));
2920
                        else
2921
                           Heap_Allocator :=
2922
                             Make_Allocator (Loc,
2923
                               Expression =>
2924
                                 New_Reference_To (Return_Obj_Typ, Loc));
2925
                        end if;
2926
 
2927
                        --  If the object requires default initialization then
2928
                        --  that will happen later following the elaboration of
2929
                        --  the object renaming. If we don't turn it off here
2930
                        --  then the object will be default initialized twice.
2931
 
2932
                        Set_No_Initialization (Heap_Allocator);
2933
                     end if;
2934
 
2935
                     --  If the No_Allocators restriction is active, then only
2936
                     --  an allocator for secondary stack allocation is needed.
2937
                     --  It's OK for such allocators to have Comes_From_Source
2938
                     --  set to False, because gigi knows not to flag them as
2939
                     --  being a violation of No_Implicit_Heap_Allocations.
2940
 
2941
                     if Restriction_Active (No_Allocators) then
2942
                        SS_Allocator   := Heap_Allocator;
2943
                        Heap_Allocator := Make_Null (Loc);
2944
 
2945
                     --  Otherwise the heap allocator may be needed, so we make
2946
                     --  another allocator for secondary stack allocation.
2947
 
2948
                     else
2949
                        SS_Allocator := New_Copy_Tree (Heap_Allocator);
2950
 
2951
                        --  The heap allocator is marked Comes_From_Source
2952
                        --  since it corresponds to an explicit user-written
2953
                        --  allocator (that is, it will only be executed on
2954
                        --  behalf of callers that call the function as
2955
                        --  initialization for such an allocator). This
2956
                        --  prevents errors when No_Implicit_Heap_Allocations
2957
                        --  is in force.
2958
 
2959
                        Set_Comes_From_Source (Heap_Allocator, True);
2960
                     end if;
2961
 
2962
                     --  The allocator is returned on the secondary stack. We
2963
                     --  don't do this on VM targets, since the SS is not used.
2964
 
2965
                     if VM_Target = No_VM then
2966
                        Set_Storage_Pool (SS_Allocator, RTE (RE_SS_Pool));
2967
                        Set_Procedure_To_Call
2968
                          (SS_Allocator, RTE (RE_SS_Allocate));
2969
 
2970
                        --  The allocator is returned on the secondary stack,
2971
                        --  so indicate that the function return, as well as
2972
                        --  the block that encloses the allocator, must not
2973
                        --  release it. The flags must be set now because the
2974
                        --  decision to use the secondary stack is done very
2975
                        --  late in the course of expanding the return
2976
                        --  statement, past the point where these flags are
2977
                        --  normally set.
2978
 
2979
                        Set_Sec_Stack_Needed_For_Return (Parent_Function);
2980
                        Set_Sec_Stack_Needed_For_Return
2981
                          (Return_Statement_Entity (N));
2982
                        Set_Uses_Sec_Stack (Parent_Function);
2983
                        Set_Uses_Sec_Stack (Return_Statement_Entity (N));
2984
                     end if;
2985
 
2986
                     --  Create an if statement to test the BIP_Alloc_Form
2987
                     --  formal and initialize the access object to either the
2988
                     --  BIP_Object_Access formal (BIP_Alloc_Form = 0), the
2989
                     --  result of allocating the object in the secondary stack
2990
                     --  (BIP_Alloc_Form = 1), or else an allocator to create
2991
                     --  the return object in the heap (BIP_Alloc_Form = 2).
2992
 
2993
                     --  ??? An unchecked type conversion must be made in the
2994
                     --  case of assigning the access object formal to the
2995
                     --  local access object, because a normal conversion would
2996
                     --  be illegal in some cases (such as converting access-
2997
                     --  to-unconstrained to access-to-constrained), but the
2998
                     --  the unchecked conversion will presumably fail to work
2999
                     --  right in just such cases. It's not clear at all how to
3000
                     --  handle this. ???
3001
 
3002
                     Alloc_If_Stmt :=
3003
                       Make_If_Statement (Loc,
3004
                         Condition       =>
3005
                           Make_Op_Eq (Loc,
3006
                             Left_Opnd =>
3007
                               New_Reference_To (Obj_Alloc_Formal, Loc),
3008
                             Right_Opnd =>
3009
                               Make_Integer_Literal (Loc,
3010
                                 UI_From_Int (BIP_Allocation_Form'Pos
3011
                                                (Caller_Allocation)))),
3012
                         Then_Statements =>
3013
                           New_List (Make_Assignment_Statement (Loc,
3014
                                       Name       =>
3015
                                         New_Reference_To
3016
                                           (Alloc_Obj_Id, Loc),
3017
                                       Expression =>
3018
                                         Make_Unchecked_Type_Conversion (Loc,
3019
                                           Subtype_Mark =>
3020
                                             New_Reference_To (Ref_Type, Loc),
3021
                                           Expression =>
3022
                                             New_Reference_To
3023
                                               (Object_Access, Loc)))),
3024
                         Elsif_Parts     =>
3025
                           New_List (Make_Elsif_Part (Loc,
3026
                                       Condition       =>
3027
                                         Make_Op_Eq (Loc,
3028
                                           Left_Opnd =>
3029
                                             New_Reference_To
3030
                                               (Obj_Alloc_Formal, Loc),
3031
                                           Right_Opnd =>
3032
                                             Make_Integer_Literal (Loc,
3033
                                               UI_From_Int (
3034
                                                 BIP_Allocation_Form'Pos
3035
                                                    (Secondary_Stack)))),
3036
                                       Then_Statements =>
3037
                                          New_List
3038
                                            (Make_Assignment_Statement (Loc,
3039
                                               Name       =>
3040
                                                 New_Reference_To
3041
                                                   (Alloc_Obj_Id, Loc),
3042
                                               Expression =>
3043
                                                 SS_Allocator)))),
3044
                         Else_Statements =>
3045
                           New_List (Make_Assignment_Statement (Loc,
3046
                                        Name       =>
3047
                                          New_Reference_To
3048
                                            (Alloc_Obj_Id, Loc),
3049
                                        Expression =>
3050
                                          Heap_Allocator)));
3051
 
3052
                     --  If a separate initialization assignment was created
3053
                     --  earlier, append that following the assignment of the
3054
                     --  implicit access formal to the access object, to ensure
3055
                     --  that the return object is initialized in that case.
3056
                     --  In this situation, the target of the assignment must
3057
                     --  be rewritten to denote a dereference of the access to
3058
                     --  the return object passed in by the caller.
3059
 
3060
                     if Present (Init_Assignment) then
3061
                        Rewrite (Name (Init_Assignment),
3062
                          Make_Explicit_Dereference (Loc,
3063
                            Prefix => New_Reference_To (Alloc_Obj_Id, Loc)));
3064
                        Set_Etype
3065
                          (Name (Init_Assignment), Etype (Return_Obj_Id));
3066
 
3067
                        Append_To
3068
                          (Then_Statements (Alloc_If_Stmt),
3069
                           Init_Assignment);
3070
                     end if;
3071
 
3072
                     Insert_Before (Return_Object_Decl, Alloc_If_Stmt);
3073
 
3074
                     --  Remember the local access object for use in the
3075
                     --  dereference of the renaming created below.
3076
 
3077
                     Object_Access := Alloc_Obj_Id;
3078
                  end;
3079
               end if;
3080
 
3081
               --  Replace the return object declaration with a renaming of a
3082
               --  dereference of the access value designating the return
3083
               --  object.
3084
 
3085
               Obj_Acc_Deref :=
3086
                 Make_Explicit_Dereference (Loc,
3087
                   Prefix => New_Reference_To (Object_Access, Loc));
3088
 
3089
               Rewrite (Return_Object_Decl,
3090
                 Make_Object_Renaming_Declaration (Loc,
3091
                   Defining_Identifier => Return_Obj_Id,
3092
                   Access_Definition   => Empty,
3093
                   Subtype_Mark        => New_Occurrence_Of
3094
                                            (Return_Obj_Typ, Loc),
3095
                   Name                => Obj_Acc_Deref));
3096
 
3097
               Set_Renamed_Object (Return_Obj_Id, Obj_Acc_Deref);
3098
            end;
3099
         end if;
3100
 
3101
      --  Case where we do not build a block
3102
 
3103
      else
3104
         --  We're about to drop Return_Object_Declarations on the floor, so
3105
         --  we need to insert it, in case it got expanded into useful code.
3106
 
3107
         Insert_List_Before (N, Return_Object_Declarations (N));
3108
 
3109
         --  Build simple_return_statement that returns the expression directly
3110
 
3111
         Return_Stm := Make_Simple_Return_Statement (Loc, Expression => Exp);
3112
 
3113
         Result := Return_Stm;
3114
      end if;
3115
 
3116
      --  Set the flag to prevent infinite recursion
3117
 
3118
      Set_Comes_From_Extended_Return_Statement (Return_Stm);
3119
 
3120
      Rewrite (N, Result);
3121
      Analyze (N);
3122
   end Expand_N_Extended_Return_Statement;
3123
 
3124
   -----------------------------
3125
   -- Expand_N_Goto_Statement --
3126
   -----------------------------
3127
 
3128
   --  Add poll before goto if polling active
3129
 
3130
   procedure Expand_N_Goto_Statement (N : Node_Id) is
3131
   begin
3132
      Generate_Poll_Call (N);
3133
   end Expand_N_Goto_Statement;
3134
 
3135
   ---------------------------
3136
   -- Expand_N_If_Statement --
3137
   ---------------------------
3138
 
3139
   --  First we deal with the case of C and Fortran convention boolean values,
3140
   --  with zero/non-zero semantics.
3141
 
3142
   --  Second, we deal with the obvious rewriting for the cases where the
3143
   --  condition of the IF is known at compile time to be True or False.
3144
 
3145
   --  Third, we remove elsif parts which have non-empty Condition_Actions and
3146
   --  rewrite as independent if statements. For example:
3147
 
3148
   --     if x then xs
3149
   --     elsif y then ys
3150
   --     ...
3151
   --     end if;
3152
 
3153
   --  becomes
3154
   --
3155
   --     if x then xs
3156
   --     else
3157
   --        <<condition actions of y>>
3158
   --        if y then ys
3159
   --        ...
3160
   --        end if;
3161
   --     end if;
3162
 
3163
   --  This rewriting is needed if at least one elsif part has a non-empty
3164
   --  Condition_Actions list. We also do the same processing if there is a
3165
   --  constant condition in an elsif part (in conjunction with the first
3166
   --  processing step mentioned above, for the recursive call made to deal
3167
   --  with the created inner if, this deals with properly optimizing the
3168
   --  cases of constant elsif conditions).
3169
 
3170
   procedure Expand_N_If_Statement (N : Node_Id) is
3171
      Loc    : constant Source_Ptr := Sloc (N);
3172
      Hed    : Node_Id;
3173
      E      : Node_Id;
3174
      New_If : Node_Id;
3175
 
3176
      Warn_If_Deleted : constant Boolean :=
3177
                          Warn_On_Deleted_Code and then Comes_From_Source (N);
3178
      --  Indicates whether we want warnings when we delete branches of the
3179
      --  if statement based on constant condition analysis. We never want
3180
      --  these warnings for expander generated code.
3181
 
3182
   begin
3183
      Adjust_Condition (Condition (N));
3184
 
3185
      --  The following loop deals with constant conditions for the IF. We
3186
      --  need a loop because as we eliminate False conditions, we grab the
3187
      --  first elsif condition and use it as the primary condition.
3188
 
3189
      while Compile_Time_Known_Value (Condition (N)) loop
3190
 
3191
         --  If condition is True, we can simply rewrite the if statement now
3192
         --  by replacing it by the series of then statements.
3193
 
3194
         if Is_True (Expr_Value (Condition (N))) then
3195
 
3196
            --  All the else parts can be killed
3197
 
3198
            Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3199
            Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3200
 
3201
            Hed := Remove_Head (Then_Statements (N));
3202
            Insert_List_After (N, Then_Statements (N));
3203
            Rewrite (N, Hed);
3204
            return;
3205
 
3206
         --  If condition is False, then we can delete the condition and
3207
         --  the Then statements
3208
 
3209
         else
3210
            --  We do not delete the condition if constant condition warnings
3211
            --  are enabled, since otherwise we end up deleting the desired
3212
            --  warning. Of course the backend will get rid of this True/False
3213
            --  test anyway, so nothing is lost here.
3214
 
3215
            if not Constant_Condition_Warnings then
3216
               Kill_Dead_Code (Condition (N));
3217
            end if;
3218
 
3219
            Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3220
 
3221
            --  If there are no elsif statements, then we simply replace the
3222
            --  entire if statement by the sequence of else statements.
3223
 
3224
            if No (Elsif_Parts (N)) then
3225
               if No (Else_Statements (N))
3226
                 or else Is_Empty_List (Else_Statements (N))
3227
               then
3228
                  Rewrite (N,
3229
                    Make_Null_Statement (Sloc (N)));
3230
               else
3231
                  Hed := Remove_Head (Else_Statements (N));
3232
                  Insert_List_After (N, Else_Statements (N));
3233
                  Rewrite (N, Hed);
3234
               end if;
3235
 
3236
               return;
3237
 
3238
            --  If there are elsif statements, the first of them becomes the
3239
            --  if/then section of the rebuilt if statement This is the case
3240
            --  where we loop to reprocess this copied condition.
3241
 
3242
            else
3243
               Hed := Remove_Head (Elsif_Parts (N));
3244
               Insert_Actions      (N, Condition_Actions (Hed));
3245
               Set_Condition       (N, Condition (Hed));
3246
               Set_Then_Statements (N, Then_Statements (Hed));
3247
 
3248
               --  Hed might have been captured as the condition determining
3249
               --  the current value for an entity. Now it is detached from
3250
               --  the tree, so a Current_Value pointer in the condition might
3251
               --  need to be updated.
3252
 
3253
               Set_Current_Value_Condition (N);
3254
 
3255
               if Is_Empty_List (Elsif_Parts (N)) then
3256
                  Set_Elsif_Parts (N, No_List);
3257
               end if;
3258
            end if;
3259
         end if;
3260
      end loop;
3261
 
3262
      --  Loop through elsif parts, dealing with constant conditions and
3263
      --  possible expression actions that are present.
3264
 
3265
      if Present (Elsif_Parts (N)) then
3266
         E := First (Elsif_Parts (N));
3267
         while Present (E) loop
3268
            Adjust_Condition (Condition (E));
3269
 
3270
            --  If there are condition actions, then rewrite the if statement
3271
            --  as indicated above. We also do the same rewrite for a True or
3272
            --  False condition. The further processing of this constant
3273
            --  condition is then done by the recursive call to expand the
3274
            --  newly created if statement
3275
 
3276
            if Present (Condition_Actions (E))
3277
              or else Compile_Time_Known_Value (Condition (E))
3278
            then
3279
               --  Note this is not an implicit if statement, since it is part
3280
               --  of an explicit if statement in the source (or of an implicit
3281
               --  if statement that has already been tested).
3282
 
3283
               New_If :=
3284
                 Make_If_Statement (Sloc (E),
3285
                   Condition       => Condition (E),
3286
                   Then_Statements => Then_Statements (E),
3287
                   Elsif_Parts     => No_List,
3288
                   Else_Statements => Else_Statements (N));
3289
 
3290
               --  Elsif parts for new if come from remaining elsif's of parent
3291
 
3292
               while Present (Next (E)) loop
3293
                  if No (Elsif_Parts (New_If)) then
3294
                     Set_Elsif_Parts (New_If, New_List);
3295
                  end if;
3296
 
3297
                  Append (Remove_Next (E), Elsif_Parts (New_If));
3298
               end loop;
3299
 
3300
               Set_Else_Statements (N, New_List (New_If));
3301
 
3302
               if Present (Condition_Actions (E)) then
3303
                  Insert_List_Before (New_If, Condition_Actions (E));
3304
               end if;
3305
 
3306
               Remove (E);
3307
 
3308
               if Is_Empty_List (Elsif_Parts (N)) then
3309
                  Set_Elsif_Parts (N, No_List);
3310
               end if;
3311
 
3312
               Analyze (New_If);
3313
               return;
3314
 
3315
            --  No special processing for that elsif part, move to next
3316
 
3317
            else
3318
               Next (E);
3319
            end if;
3320
         end loop;
3321
      end if;
3322
 
3323
      --  Some more optimizations applicable if we still have an IF statement
3324
 
3325
      if Nkind (N) /= N_If_Statement then
3326
         return;
3327
      end if;
3328
 
3329
      --  Another optimization, special cases that can be simplified
3330
 
3331
      --     if expression then
3332
      --        return true;
3333
      --     else
3334
      --        return false;
3335
      --     end if;
3336
 
3337
      --  can be changed to:
3338
 
3339
      --     return expression;
3340
 
3341
      --  and
3342
 
3343
      --     if expression then
3344
      --        return false;
3345
      --     else
3346
      --        return true;
3347
      --     end if;
3348
 
3349
      --  can be changed to:
3350
 
3351
      --     return not (expression);
3352
 
3353
      --  Only do these optimizations if we are at least at -O1 level and
3354
      --  do not do them if control flow optimizations are suppressed.
3355
 
3356
      if Optimization_Level > 0
3357
        and then not Opt.Suppress_Control_Flow_Optimizations
3358
      then
3359
         if Nkind (N) = N_If_Statement
3360
           and then No (Elsif_Parts (N))
3361
           and then Present (Else_Statements (N))
3362
           and then List_Length (Then_Statements (N)) = 1
3363
           and then List_Length (Else_Statements (N)) = 1
3364
         then
3365
            declare
3366
               Then_Stm : constant Node_Id := First (Then_Statements (N));
3367
               Else_Stm : constant Node_Id := First (Else_Statements (N));
3368
 
3369
            begin
3370
               if Nkind (Then_Stm) = N_Simple_Return_Statement
3371
                    and then
3372
                  Nkind (Else_Stm) = N_Simple_Return_Statement
3373
               then
3374
                  declare
3375
                     Then_Expr : constant Node_Id := Expression (Then_Stm);
3376
                     Else_Expr : constant Node_Id := Expression (Else_Stm);
3377
 
3378
                  begin
3379
                     if Nkind (Then_Expr) = N_Identifier
3380
                          and then
3381
                        Nkind (Else_Expr) = N_Identifier
3382
                     then
3383
                        if Entity (Then_Expr) = Standard_True
3384
                          and then Entity (Else_Expr) = Standard_False
3385
                        then
3386
                           Rewrite (N,
3387
                             Make_Simple_Return_Statement (Loc,
3388
                               Expression => Relocate_Node (Condition (N))));
3389
                           Analyze (N);
3390
                           return;
3391
 
3392
                        elsif Entity (Then_Expr) = Standard_False
3393
                          and then Entity (Else_Expr) = Standard_True
3394
                        then
3395
                           Rewrite (N,
3396
                             Make_Simple_Return_Statement (Loc,
3397
                               Expression =>
3398
                                 Make_Op_Not (Loc,
3399
                                   Right_Opnd =>
3400
                                     Relocate_Node (Condition (N)))));
3401
                           Analyze (N);
3402
                           return;
3403
                        end if;
3404
                     end if;
3405
                  end;
3406
               end if;
3407
            end;
3408
         end if;
3409
      end if;
3410
   end Expand_N_If_Statement;
3411
 
3412
   -----------------------------
3413
   -- Expand_N_Loop_Statement --
3414
   -----------------------------
3415
 
3416
   --  1. Remove null loop entirely
3417
   --  2. Deal with while condition for C/Fortran boolean
3418
   --  3. Deal with loops with a non-standard enumeration type range
3419
   --  4. Deal with while loops where Condition_Actions is set
3420
   --  5. Insert polling call if required
3421
 
3422
   procedure Expand_N_Loop_Statement (N : Node_Id) is
3423
      Loc  : constant Source_Ptr := Sloc (N);
3424
      Isc  : constant Node_Id    := Iteration_Scheme (N);
3425
 
3426
   begin
3427
      --  Delete null loop
3428
 
3429
      if Is_Null_Loop (N) then
3430
         Rewrite (N, Make_Null_Statement (Loc));
3431
         return;
3432
      end if;
3433
 
3434
      --  Deal with condition for C/Fortran Boolean
3435
 
3436
      if Present (Isc) then
3437
         Adjust_Condition (Condition (Isc));
3438
      end if;
3439
 
3440
      --  Generate polling call
3441
 
3442
      if Is_Non_Empty_List (Statements (N)) then
3443
         Generate_Poll_Call (First (Statements (N)));
3444
      end if;
3445
 
3446
      --  Nothing more to do for plain loop with no iteration scheme
3447
 
3448
      if No (Isc) then
3449
         return;
3450
      end if;
3451
 
3452
      --  Note: we do not have to worry about validity checking of the for loop
3453
      --  range bounds here, since they were frozen with constant declarations
3454
      --  and it is during that process that the validity checking is done.
3455
 
3456
      --  Handle the case where we have a for loop with the range type being an
3457
      --  enumeration type with non-standard representation. In this case we
3458
      --  expand:
3459
 
3460
      --    for x in [reverse] a .. b loop
3461
      --       ...
3462
      --    end loop;
3463
 
3464
      --  to
3465
 
3466
      --    for xP in [reverse] integer
3467
      --                          range etype'Pos (a) .. etype'Pos (b) loop
3468
      --       declare
3469
      --          x : constant etype := Pos_To_Rep (xP);
3470
      --       begin
3471
      --          ...
3472
      --       end;
3473
      --    end loop;
3474
 
3475
      if Present (Loop_Parameter_Specification (Isc)) then
3476
         declare
3477
            LPS     : constant Node_Id   := Loop_Parameter_Specification (Isc);
3478
            Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
3479
            Ltype   : constant Entity_Id := Etype (Loop_Id);
3480
            Btype   : constant Entity_Id := Base_Type (Ltype);
3481
            Expr    : Node_Id;
3482
            New_Id  : Entity_Id;
3483
 
3484
         begin
3485
            if not Is_Enumeration_Type (Btype)
3486
              or else No (Enum_Pos_To_Rep (Btype))
3487
            then
3488
               return;
3489
            end if;
3490
 
3491
            New_Id :=
3492
              Make_Defining_Identifier (Loc,
3493
                Chars => New_External_Name (Chars (Loop_Id), 'P'));
3494
 
3495
            --  If the type has a contiguous representation, successive values
3496
            --  can be generated as offsets from the first literal.
3497
 
3498
            if Has_Contiguous_Rep (Btype) then
3499
               Expr :=
3500
                  Unchecked_Convert_To (Btype,
3501
                    Make_Op_Add (Loc,
3502
                      Left_Opnd =>
3503
                         Make_Integer_Literal (Loc,
3504
                           Enumeration_Rep (First_Literal (Btype))),
3505
                      Right_Opnd => New_Reference_To (New_Id, Loc)));
3506
            else
3507
               --  Use the constructed array Enum_Pos_To_Rep
3508
 
3509
               Expr :=
3510
                 Make_Indexed_Component (Loc,
3511
                   Prefix => New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
3512
                   Expressions => New_List (New_Reference_To (New_Id, Loc)));
3513
            end if;
3514
 
3515
            Rewrite (N,
3516
              Make_Loop_Statement (Loc,
3517
                Identifier => Identifier (N),
3518
 
3519
                Iteration_Scheme =>
3520
                  Make_Iteration_Scheme (Loc,
3521
                    Loop_Parameter_Specification =>
3522
                      Make_Loop_Parameter_Specification (Loc,
3523
                        Defining_Identifier => New_Id,
3524
                        Reverse_Present => Reverse_Present (LPS),
3525
 
3526
                        Discrete_Subtype_Definition =>
3527
                          Make_Subtype_Indication (Loc,
3528
 
3529
                            Subtype_Mark =>
3530
                              New_Reference_To (Standard_Natural, Loc),
3531
 
3532
                            Constraint =>
3533
                              Make_Range_Constraint (Loc,
3534
                                Range_Expression =>
3535
                                  Make_Range (Loc,
3536
 
3537
                                    Low_Bound =>
3538
                                      Make_Attribute_Reference (Loc,
3539
                                        Prefix =>
3540
                                          New_Reference_To (Btype, Loc),
3541
 
3542
                                        Attribute_Name => Name_Pos,
3543
 
3544
                                        Expressions => New_List (
3545
                                          Relocate_Node
3546
                                            (Type_Low_Bound (Ltype)))),
3547
 
3548
                                    High_Bound =>
3549
                                      Make_Attribute_Reference (Loc,
3550
                                        Prefix =>
3551
                                          New_Reference_To (Btype, Loc),
3552
 
3553
                                        Attribute_Name => Name_Pos,
3554
 
3555
                                        Expressions => New_List (
3556
                                          Relocate_Node
3557
                                            (Type_High_Bound (Ltype))))))))),
3558
 
3559
                Statements => New_List (
3560
                  Make_Block_Statement (Loc,
3561
                    Declarations => New_List (
3562
                      Make_Object_Declaration (Loc,
3563
                        Defining_Identifier => Loop_Id,
3564
                        Constant_Present    => True,
3565
                        Object_Definition   => New_Reference_To (Ltype, Loc),
3566
                        Expression          => Expr)),
3567
 
3568
                    Handled_Statement_Sequence =>
3569
                      Make_Handled_Sequence_Of_Statements (Loc,
3570
                        Statements => Statements (N)))),
3571
 
3572
                End_Label => End_Label (N)));
3573
            Analyze (N);
3574
         end;
3575
 
3576
      --  Second case, if we have a while loop with Condition_Actions set, then
3577
      --  we change it into a plain loop:
3578
 
3579
      --    while C loop
3580
      --       ...
3581
      --    end loop;
3582
 
3583
      --  changed to:
3584
 
3585
      --    loop
3586
      --       <<condition actions>>
3587
      --       exit when not C;
3588
      --       ...
3589
      --    end loop
3590
 
3591
      elsif Present (Isc)
3592
        and then Present (Condition_Actions (Isc))
3593
      then
3594
         declare
3595
            ES : Node_Id;
3596
 
3597
         begin
3598
            ES :=
3599
              Make_Exit_Statement (Sloc (Condition (Isc)),
3600
                Condition =>
3601
                  Make_Op_Not (Sloc (Condition (Isc)),
3602
                    Right_Opnd => Condition (Isc)));
3603
 
3604
            Prepend (ES, Statements (N));
3605
            Insert_List_Before (ES, Condition_Actions (Isc));
3606
 
3607
            --  This is not an implicit loop, since it is generated in response
3608
            --  to the loop statement being processed. If this is itself
3609
            --  implicit, the restriction has already been checked. If not,
3610
            --  it is an explicit loop.
3611
 
3612
            Rewrite (N,
3613
              Make_Loop_Statement (Sloc (N),
3614
                Identifier => Identifier (N),
3615
                Statements => Statements (N),
3616
                End_Label  => End_Label  (N)));
3617
 
3618
            Analyze (N);
3619
         end;
3620
      end if;
3621
   end Expand_N_Loop_Statement;
3622
 
3623
   --------------------------------------
3624
   -- Expand_N_Simple_Return_Statement --
3625
   --------------------------------------
3626
 
3627
   procedure Expand_N_Simple_Return_Statement (N : Node_Id) is
3628
   begin
3629
      --  Defend against previous errors (i.e. the return statement calls a
3630
      --  function that is not available in configurable runtime).
3631
 
3632
      if Present (Expression (N))
3633
        and then Nkind (Expression (N)) = N_Empty
3634
      then
3635
         return;
3636
      end if;
3637
 
3638
      --  Distinguish the function and non-function cases:
3639
 
3640
      case Ekind (Return_Applies_To (Return_Statement_Entity (N))) is
3641
 
3642
         when E_Function          |
3643
              E_Generic_Function  =>
3644
            Expand_Simple_Function_Return (N);
3645
 
3646
         when E_Procedure         |
3647
              E_Generic_Procedure |
3648
              E_Entry             |
3649
              E_Entry_Family      |
3650
              E_Return_Statement =>
3651
            Expand_Non_Function_Return (N);
3652
 
3653
         when others =>
3654
            raise Program_Error;
3655
      end case;
3656
 
3657
   exception
3658
      when RE_Not_Available =>
3659
         return;
3660
   end Expand_N_Simple_Return_Statement;
3661
 
3662
   --------------------------------
3663
   -- Expand_Non_Function_Return --
3664
   --------------------------------
3665
 
3666
   procedure Expand_Non_Function_Return (N : Node_Id) is
3667
      pragma Assert (No (Expression (N)));
3668
 
3669
      Loc         : constant Source_Ptr := Sloc (N);
3670
      Scope_Id    : Entity_Id :=
3671
                      Return_Applies_To (Return_Statement_Entity (N));
3672
      Kind        : constant Entity_Kind := Ekind (Scope_Id);
3673
      Call        : Node_Id;
3674
      Acc_Stat    : Node_Id;
3675
      Goto_Stat   : Node_Id;
3676
      Lab_Node    : Node_Id;
3677
 
3678
   begin
3679
      --  Call _Postconditions procedure if procedure with active
3680
      --  postconditions. Here, we use the Postcondition_Proc attribute, which
3681
      --  is needed for implicitly-generated returns. Functions never
3682
      --  have implicitly-generated returns, and there's no room for
3683
      --  Postcondition_Proc in E_Function, so we look up the identifier
3684
      --  Name_uPostconditions for function returns (see
3685
      --  Expand_Simple_Function_Return).
3686
 
3687
      if Ekind (Scope_Id) = E_Procedure
3688
        and then Has_Postconditions (Scope_Id)
3689
      then
3690
         pragma Assert (Present (Postcondition_Proc (Scope_Id)));
3691
         Insert_Action (N,
3692
           Make_Procedure_Call_Statement (Loc,
3693
             Name => New_Reference_To (Postcondition_Proc (Scope_Id), Loc)));
3694
      end if;
3695
 
3696
      --  If it is a return from a procedure do no extra steps
3697
 
3698
      if Kind = E_Procedure or else Kind = E_Generic_Procedure then
3699
         return;
3700
 
3701
      --  If it is a nested return within an extended one, replace it with a
3702
      --  return of the previously declared return object.
3703
 
3704
      elsif Kind = E_Return_Statement then
3705
         Rewrite (N,
3706
           Make_Simple_Return_Statement (Loc,
3707
             Expression =>
3708
               New_Occurrence_Of (First_Entity (Scope_Id), Loc)));
3709
         Set_Comes_From_Extended_Return_Statement (N);
3710
         Set_Return_Statement_Entity (N, Scope_Id);
3711
         Expand_Simple_Function_Return (N);
3712
         return;
3713
      end if;
3714
 
3715
      pragma Assert (Is_Entry (Scope_Id));
3716
 
3717
      --  Look at the enclosing block to see whether the return is from an
3718
      --  accept statement or an entry body.
3719
 
3720
      for J in reverse 0 .. Scope_Stack.Last loop
3721
         Scope_Id := Scope_Stack.Table (J).Entity;
3722
         exit when Is_Concurrent_Type (Scope_Id);
3723
      end loop;
3724
 
3725
      --  If it is a return from accept statement it is expanded as call to
3726
      --  RTS Complete_Rendezvous and a goto to the end of the accept body.
3727
 
3728
      --  (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
3729
      --  Expand_N_Accept_Alternative in exp_ch9.adb)
3730
 
3731
      if Is_Task_Type (Scope_Id) then
3732
 
3733
         Call :=
3734
           Make_Procedure_Call_Statement (Loc,
3735
             Name => New_Reference_To (RTE (RE_Complete_Rendezvous), Loc));
3736
         Insert_Before (N, Call);
3737
         --  why not insert actions here???
3738
         Analyze (Call);
3739
 
3740
         Acc_Stat := Parent (N);
3741
         while Nkind (Acc_Stat) /= N_Accept_Statement loop
3742
            Acc_Stat := Parent (Acc_Stat);
3743
         end loop;
3744
 
3745
         Lab_Node := Last (Statements
3746
           (Handled_Statement_Sequence (Acc_Stat)));
3747
 
3748
         Goto_Stat := Make_Goto_Statement (Loc,
3749
           Name => New_Occurrence_Of
3750
             (Entity (Identifier (Lab_Node)), Loc));
3751
 
3752
         Set_Analyzed (Goto_Stat);
3753
 
3754
         Rewrite (N, Goto_Stat);
3755
         Analyze (N);
3756
 
3757
      --  If it is a return from an entry body, put a Complete_Entry_Body call
3758
      --  in front of the return.
3759
 
3760
      elsif Is_Protected_Type (Scope_Id) then
3761
         Call :=
3762
           Make_Procedure_Call_Statement (Loc,
3763
             Name =>
3764
               New_Reference_To (RTE (RE_Complete_Entry_Body), Loc),
3765
             Parameter_Associations => New_List (
3766
               Make_Attribute_Reference (Loc,
3767
                 Prefix =>
3768
                   New_Reference_To
3769
                     (Find_Protection_Object (Current_Scope), Loc),
3770
                 Attribute_Name =>
3771
                   Name_Unchecked_Access)));
3772
 
3773
         Insert_Before (N, Call);
3774
         Analyze (Call);
3775
      end if;
3776
   end Expand_Non_Function_Return;
3777
 
3778
   -----------------------------------
3779
   -- Expand_Simple_Function_Return --
3780
   -----------------------------------
3781
 
3782
   --  The "simple" comes from the syntax rule simple_return_statement.
3783
   --  The semantics are not at all simple!
3784
 
3785
   procedure Expand_Simple_Function_Return (N : Node_Id) is
3786
      Loc : constant Source_Ptr := Sloc (N);
3787
 
3788
      Scope_Id : constant Entity_Id :=
3789
                   Return_Applies_To (Return_Statement_Entity (N));
3790
      --  The function we are returning from
3791
 
3792
      R_Type : constant Entity_Id := Etype (Scope_Id);
3793
      --  The result type of the function
3794
 
3795
      Utyp : constant Entity_Id := Underlying_Type (R_Type);
3796
 
3797
      Exp : constant Node_Id := Expression (N);
3798
      pragma Assert (Present (Exp));
3799
 
3800
      Exptyp : constant Entity_Id := Etype (Exp);
3801
      --  The type of the expression (not necessarily the same as R_Type)
3802
 
3803
      Subtype_Ind : Node_Id;
3804
      --  If the result type of the function is class-wide and the
3805
      --  expression has a specific type, then we use the expression's
3806
      --  type as the type of the return object. In cases where the
3807
      --  expression is an aggregate that is built in place, this avoids
3808
      --  the need for an expensive conversion of the return object to
3809
      --  the specific type on assignments to the individual components.
3810
 
3811
   begin
3812
      if Is_Class_Wide_Type (R_Type)
3813
        and then not Is_Class_Wide_Type (Etype (Exp))
3814
      then
3815
         Subtype_Ind := New_Occurrence_Of (Etype (Exp), Loc);
3816
      else
3817
         Subtype_Ind := New_Occurrence_Of (R_Type, Loc);
3818
      end if;
3819
 
3820
      --  For the case of a simple return that does not come from an extended
3821
      --  return, in the case of Ada 2005 where we are returning a limited
3822
      --  type, we rewrite "return <expression>;" to be:
3823
 
3824
      --    return _anon_ : <return_subtype> := <expression>
3825
 
3826
      --  The expansion produced by Expand_N_Extended_Return_Statement will
3827
      --  contain simple return statements (for example, a block containing
3828
      --  simple return of the return object), which brings us back here with
3829
      --  Comes_From_Extended_Return_Statement set. The reason for the barrier
3830
      --  checking for a simple return that does not come from an extended
3831
      --  return is to avoid this infinite recursion.
3832
 
3833
      --  The reason for this design is that for Ada 2005 limited returns, we
3834
      --  need to reify the return object, so we can build it "in place", and
3835
      --  we need a block statement to hang finalization and tasking stuff.
3836
 
3837
      --  ??? In order to avoid disruption, we avoid translating to extended
3838
      --  return except in the cases where we really need to (Ada 2005 for
3839
      --  inherently limited). We might prefer to do this translation in all
3840
      --  cases (except perhaps for the case of Ada 95 inherently limited),
3841
      --  in order to fully exercise the Expand_N_Extended_Return_Statement
3842
      --  code. This would also allow us to do the build-in-place optimization
3843
      --  for efficiency even in cases where it is semantically not required.
3844
 
3845
      --  As before, we check the type of the return expression rather than the
3846
      --  return type of the function, because the latter may be a limited
3847
      --  class-wide interface type, which is not a limited type, even though
3848
      --  the type of the expression may be.
3849
 
3850
      if not Comes_From_Extended_Return_Statement (N)
3851
        and then Is_Inherently_Limited_Type (Etype (Expression (N)))
3852
        and then Ada_Version >= Ada_05
3853
        and then not Debug_Flag_Dot_L
3854
      then
3855
         declare
3856
            Return_Object_Entity : constant Entity_Id :=
3857
                                     Make_Defining_Identifier (Loc,
3858
                                       New_Internal_Name ('R'));
3859
            Obj_Decl : constant Node_Id :=
3860
                         Make_Object_Declaration (Loc,
3861
                           Defining_Identifier => Return_Object_Entity,
3862
                           Object_Definition   => Subtype_Ind,
3863
                           Expression          => Exp);
3864
 
3865
            Ext : constant Node_Id := Make_Extended_Return_Statement (Loc,
3866
                    Return_Object_Declarations => New_List (Obj_Decl));
3867
            --  Do not perform this high-level optimization if the result type
3868
            --  is an interface because the "this" pointer must be displaced.
3869
 
3870
         begin
3871
            Rewrite (N, Ext);
3872
            Analyze (N);
3873
            return;
3874
         end;
3875
      end if;
3876
 
3877
      --  Here we have a simple return statement that is part of the expansion
3878
      --  of an extended return statement (either written by the user, or
3879
      --  generated by the above code).
3880
 
3881
      --  Always normalize C/Fortran boolean result. This is not always needed,
3882
      --  but it seems a good idea to minimize the passing around of non-
3883
      --  normalized values, and in any case this handles the processing of
3884
      --  barrier functions for protected types, which turn the condition into
3885
      --  a return statement.
3886
 
3887
      if Is_Boolean_Type (Exptyp)
3888
        and then Nonzero_Is_True (Exptyp)
3889
      then
3890
         Adjust_Condition (Exp);
3891
         Adjust_Result_Type (Exp, Exptyp);
3892
      end if;
3893
 
3894
      --  Do validity check if enabled for returns
3895
 
3896
      if Validity_Checks_On
3897
        and then Validity_Check_Returns
3898
      then
3899
         Ensure_Valid (Exp);
3900
      end if;
3901
 
3902
      --  Check the result expression of a scalar function against the subtype
3903
      --  of the function by inserting a conversion. This conversion must
3904
      --  eventually be performed for other classes of types, but for now it's
3905
      --  only done for scalars.
3906
      --  ???
3907
 
3908
      if Is_Scalar_Type (Exptyp) then
3909
         Rewrite (Exp, Convert_To (R_Type, Exp));
3910
 
3911
         --  The expression is resolved to ensure that the conversion gets
3912
         --  expanded to generate a possible constraint check.
3913
 
3914
         Analyze_And_Resolve (Exp, R_Type);
3915
      end if;
3916
 
3917
      --  Deal with returning variable length objects and controlled types
3918
 
3919
      --  Nothing to do if we are returning by reference, or this is not a
3920
      --  type that requires special processing (indicated by the fact that
3921
      --  it requires a cleanup scope for the secondary stack case).
3922
 
3923
      if Is_Inherently_Limited_Type (Exptyp)
3924
        or else Is_Limited_Interface (Exptyp)
3925
      then
3926
         null;
3927
 
3928
      elsif not Requires_Transient_Scope (R_Type) then
3929
 
3930
         --  Mutable records with no variable length components are not
3931
         --  returned on the sec-stack, so we need to make sure that the
3932
         --  backend will only copy back the size of the actual value, and not
3933
         --  the maximum size. We create an actual subtype for this purpose.
3934
 
3935
         declare
3936
            Ubt  : constant Entity_Id := Underlying_Type (Base_Type (Exptyp));
3937
            Decl : Node_Id;
3938
            Ent  : Entity_Id;
3939
         begin
3940
            if Has_Discriminants (Ubt)
3941
              and then not Is_Constrained (Ubt)
3942
              and then not Has_Unchecked_Union (Ubt)
3943
            then
3944
               Decl := Build_Actual_Subtype (Ubt, Exp);
3945
               Ent := Defining_Identifier (Decl);
3946
               Insert_Action (Exp, Decl);
3947
               Rewrite (Exp, Unchecked_Convert_To (Ent, Exp));
3948
               Analyze_And_Resolve (Exp);
3949
            end if;
3950
         end;
3951
 
3952
      --  Here if secondary stack is used
3953
 
3954
      else
3955
         --  Make sure that no surrounding block will reclaim the secondary
3956
         --  stack on which we are going to put the result. Not only may this
3957
         --  introduce secondary stack leaks but worse, if the reclamation is
3958
         --  done too early, then the result we are returning may get
3959
         --  clobbered.
3960
 
3961
         declare
3962
            S : Entity_Id;
3963
         begin
3964
            S := Current_Scope;
3965
            while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
3966
               Set_Sec_Stack_Needed_For_Return (S, True);
3967
               S := Enclosing_Dynamic_Scope (S);
3968
            end loop;
3969
         end;
3970
 
3971
         --  Optimize the case where the result is a function call. In this
3972
         --  case either the result is already on the secondary stack, or is
3973
         --  already being returned with the stack pointer depressed and no
3974
         --  further processing is required except to set the By_Ref flag to
3975
         --  ensure that gigi does not attempt an extra unnecessary copy.
3976
         --  (actually not just unnecessary but harmfully wrong in the case
3977
         --  of a controlled type, where gigi does not know how to do a copy).
3978
         --  To make up for a gcc 2.8.1 deficiency (???), we perform
3979
         --  the copy for array types if the constrained status of the
3980
         --  target type is different from that of the expression.
3981
 
3982
         if Requires_Transient_Scope (Exptyp)
3983
           and then
3984
              (not Is_Array_Type (Exptyp)
3985
                or else Is_Constrained (Exptyp) = Is_Constrained (R_Type)
3986
                or else CW_Or_Has_Controlled_Part (Utyp))
3987
           and then Nkind (Exp) = N_Function_Call
3988
         then
3989
            Set_By_Ref (N);
3990
 
3991
            --  Remove side effects from the expression now so that other parts
3992
            --  of the expander do not have to reanalyze this node without this
3993
            --  optimization
3994
 
3995
            Rewrite (Exp, Duplicate_Subexpr_No_Checks (Exp));
3996
 
3997
         --  For controlled types, do the allocation on the secondary stack
3998
         --  manually in order to call adjust at the right time:
3999
 
4000
         --    type Anon1 is access R_Type;
4001
         --    for Anon1'Storage_pool use ss_pool;
4002
         --    Anon2 : anon1 := new R_Type'(expr);
4003
         --    return Anon2.all;
4004
 
4005
         --  We do the same for classwide types that are not potentially
4006
         --  controlled (by the virtue of restriction No_Finalization) because
4007
         --  gigi is not able to properly allocate class-wide types.
4008
 
4009
         elsif CW_Or_Has_Controlled_Part (Utyp) then
4010
            declare
4011
               Loc        : constant Source_Ptr := Sloc (N);
4012
               Temp       : constant Entity_Id :=
4013
                              Make_Defining_Identifier (Loc,
4014
                                Chars => New_Internal_Name ('R'));
4015
               Acc_Typ    : constant Entity_Id :=
4016
                              Make_Defining_Identifier (Loc,
4017
                                Chars => New_Internal_Name ('A'));
4018
               Alloc_Node : Node_Id;
4019
 
4020
            begin
4021
               Set_Ekind (Acc_Typ, E_Access_Type);
4022
 
4023
               Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
4024
 
4025
               --  This is an allocator for the secondary stack, and it's fine
4026
               --  to have Comes_From_Source set False on it, as gigi knows not
4027
               --  to flag it as a violation of No_Implicit_Heap_Allocations.
4028
 
4029
               Alloc_Node :=
4030
                 Make_Allocator (Loc,
4031
                   Expression =>
4032
                     Make_Qualified_Expression (Loc,
4033
                       Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
4034
                       Expression => Relocate_Node (Exp)));
4035
 
4036
               --  We do not want discriminant checks on the declaration,
4037
               --  given that it gets its value from the allocator.
4038
 
4039
               Set_No_Initialization (Alloc_Node);
4040
 
4041
               Insert_List_Before_And_Analyze (N, New_List (
4042
                 Make_Full_Type_Declaration (Loc,
4043
                   Defining_Identifier => Acc_Typ,
4044
                   Type_Definition     =>
4045
                     Make_Access_To_Object_Definition (Loc,
4046
                       Subtype_Indication => Subtype_Ind)),
4047
 
4048
                 Make_Object_Declaration (Loc,
4049
                   Defining_Identifier => Temp,
4050
                   Object_Definition   => New_Reference_To (Acc_Typ, Loc),
4051
                   Expression          => Alloc_Node)));
4052
 
4053
               Rewrite (Exp,
4054
                 Make_Explicit_Dereference (Loc,
4055
                 Prefix => New_Reference_To (Temp, Loc)));
4056
 
4057
               Analyze_And_Resolve (Exp, R_Type);
4058
            end;
4059
 
4060
         --  Otherwise use the gigi mechanism to allocate result on the
4061
         --  secondary stack.
4062
 
4063
         else
4064
            Check_Restriction (No_Secondary_Stack, N);
4065
            Set_Storage_Pool (N, RTE (RE_SS_Pool));
4066
 
4067
            --  If we are generating code for the VM do not use
4068
            --  SS_Allocate since everything is heap-allocated anyway.
4069
 
4070
            if VM_Target = No_VM then
4071
               Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
4072
            end if;
4073
         end if;
4074
      end if;
4075
 
4076
      --  Implement the rules of 6.5(8-10), which require a tag check in the
4077
      --  case of a limited tagged return type, and tag reassignment for
4078
      --  nonlimited tagged results. These actions are needed when the return
4079
      --  type is a specific tagged type and the result expression is a
4080
      --  conversion or a formal parameter, because in that case the tag of the
4081
      --  expression might differ from the tag of the specific result type.
4082
 
4083
      if Is_Tagged_Type (Utyp)
4084
        and then not Is_Class_Wide_Type (Utyp)
4085
        and then (Nkind_In (Exp, N_Type_Conversion,
4086
                                 N_Unchecked_Type_Conversion)
4087
                    or else (Is_Entity_Name (Exp)
4088
                               and then Ekind (Entity (Exp)) in Formal_Kind))
4089
      then
4090
         --  When the return type is limited, perform a check that the
4091
         --  tag of the result is the same as the tag of the return type.
4092
 
4093
         if Is_Limited_Type (R_Type) then
4094
            Insert_Action (Exp,
4095
              Make_Raise_Constraint_Error (Loc,
4096
                Condition =>
4097
                  Make_Op_Ne (Loc,
4098
                    Left_Opnd =>
4099
                      Make_Selected_Component (Loc,
4100
                        Prefix => Duplicate_Subexpr (Exp),
4101
                        Selector_Name =>
4102
                          New_Reference_To (First_Tag_Component (Utyp), Loc)),
4103
                    Right_Opnd =>
4104
                      Unchecked_Convert_To (RTE (RE_Tag),
4105
                        New_Reference_To
4106
                          (Node (First_Elmt
4107
                                  (Access_Disp_Table (Base_Type (Utyp)))),
4108
                           Loc))),
4109
                Reason => CE_Tag_Check_Failed));
4110
 
4111
         --  If the result type is a specific nonlimited tagged type, then we
4112
         --  have to ensure that the tag of the result is that of the result
4113
         --  type. This is handled by making a copy of the expression in the
4114
         --  case where it might have a different tag, namely when the
4115
         --  expression is a conversion or a formal parameter. We create a new
4116
         --  object of the result type and initialize it from the expression,
4117
         --  which will implicitly force the tag to be set appropriately.
4118
 
4119
         else
4120
            declare
4121
               Result_Id  : constant Entity_Id :=
4122
                              Make_Defining_Identifier (Loc,
4123
                                Chars => New_Internal_Name ('R'));
4124
               Result_Exp : constant Node_Id :=
4125
                              New_Reference_To (Result_Id, Loc);
4126
               Result_Obj : constant Node_Id :=
4127
                              Make_Object_Declaration (Loc,
4128
                                Defining_Identifier => Result_Id,
4129
                                Object_Definition   =>
4130
                                  New_Reference_To (R_Type, Loc),
4131
                                Constant_Present    => True,
4132
                                Expression          => Relocate_Node (Exp));
4133
 
4134
            begin
4135
               Set_Assignment_OK (Result_Obj);
4136
               Insert_Action (Exp, Result_Obj);
4137
 
4138
               Rewrite (Exp, Result_Exp);
4139
               Analyze_And_Resolve (Exp, R_Type);
4140
            end;
4141
         end if;
4142
 
4143
      --  Ada 2005 (AI-344): If the result type is class-wide, then insert
4144
      --  a check that the level of the return expression's underlying type
4145
      --  is not deeper than the level of the master enclosing the function.
4146
      --  Always generate the check when the type of the return expression
4147
      --  is class-wide, when it's a type conversion, or when it's a formal
4148
      --  parameter. Otherwise, suppress the check in the case where the
4149
      --  return expression has a specific type whose level is known not to
4150
      --  be statically deeper than the function's result type.
4151
 
4152
      --  Note: accessibility check is skipped in the VM case, since there
4153
      --  does not seem to be any practical way to implement this check.
4154
 
4155
      elsif Ada_Version >= Ada_05
4156
        and then Tagged_Type_Expansion
4157
        and then Is_Class_Wide_Type (R_Type)
4158
        and then not Scope_Suppress (Accessibility_Check)
4159
        and then
4160
          (Is_Class_Wide_Type (Etype (Exp))
4161
            or else Nkind_In (Exp, N_Type_Conversion,
4162
                                   N_Unchecked_Type_Conversion)
4163
            or else (Is_Entity_Name (Exp)
4164
                       and then Ekind (Entity (Exp)) in Formal_Kind)
4165
            or else Scope_Depth (Enclosing_Dynamic_Scope (Etype (Exp))) >
4166
                      Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))
4167
      then
4168
         declare
4169
            Tag_Node : Node_Id;
4170
 
4171
         begin
4172
            --  Ada 2005 (AI-251): In class-wide interface objects we displace
4173
            --  "this" to reference the base of the object --- required to get
4174
            --  access to the TSD of the object.
4175
 
4176
            if Is_Class_Wide_Type (Etype (Exp))
4177
              and then Is_Interface (Etype (Exp))
4178
              and then Nkind (Exp) = N_Explicit_Dereference
4179
            then
4180
               Tag_Node :=
4181
                 Make_Explicit_Dereference (Loc,
4182
                   Unchecked_Convert_To (RTE (RE_Tag_Ptr),
4183
                     Make_Function_Call (Loc,
4184
                       Name => New_Reference_To (RTE (RE_Base_Address), Loc),
4185
                       Parameter_Associations => New_List (
4186
                         Unchecked_Convert_To (RTE (RE_Address),
4187
                           Duplicate_Subexpr (Prefix (Exp)))))));
4188
            else
4189
               Tag_Node :=
4190
                 Make_Attribute_Reference (Loc,
4191
                   Prefix => Duplicate_Subexpr (Exp),
4192
                   Attribute_Name => Name_Tag);
4193
            end if;
4194
 
4195
            Insert_Action (Exp,
4196
              Make_Raise_Program_Error (Loc,
4197
                Condition =>
4198
                  Make_Op_Gt (Loc,
4199
                    Left_Opnd =>
4200
                      Build_Get_Access_Level (Loc, Tag_Node),
4201
                    Right_Opnd =>
4202
                      Make_Integer_Literal (Loc,
4203
                        Scope_Depth (Enclosing_Dynamic_Scope (Scope_Id)))),
4204
                Reason => PE_Accessibility_Check_Failed));
4205
         end;
4206
      end if;
4207
 
4208
      --  If we are returning an object that may not be bit-aligned, then
4209
      --  copy the value into a temporary first. This copy may need to expand
4210
      --  to a loop of component operations..
4211
 
4212
      if Is_Possibly_Unaligned_Slice (Exp)
4213
        or else Is_Possibly_Unaligned_Object (Exp)
4214
      then
4215
         declare
4216
            Tnn : constant Entity_Id :=
4217
                    Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
4218
         begin
4219
            Insert_Action (Exp,
4220
              Make_Object_Declaration (Loc,
4221
                Defining_Identifier => Tnn,
4222
                Constant_Present    => True,
4223
                Object_Definition   => New_Occurrence_Of (R_Type, Loc),
4224
                Expression          => Relocate_Node (Exp)),
4225
                Suppress => All_Checks);
4226
            Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4227
         end;
4228
      end if;
4229
 
4230
      --  Generate call to postcondition checks if they are present
4231
 
4232
      if Ekind (Scope_Id) = E_Function
4233
        and then Has_Postconditions (Scope_Id)
4234
      then
4235
         --  We are going to reference the returned value twice in this case,
4236
         --  once in the call to _Postconditions, and once in the actual return
4237
         --  statement, but we can't have side effects happening twice, and in
4238
         --  any case for efficiency we don't want to do the computation twice.
4239
 
4240
         --  If the returned expression is an entity name, we don't need to
4241
         --  worry since it is efficient and safe to reference it twice, that's
4242
         --  also true for literals other than string literals, and for the
4243
         --  case of X.all where X is an entity name.
4244
 
4245
         if Is_Entity_Name (Exp)
4246
           or else Nkind_In (Exp, N_Character_Literal,
4247
                                  N_Integer_Literal,
4248
                                  N_Real_Literal)
4249
           or else (Nkind (Exp) = N_Explicit_Dereference
4250
                      and then Is_Entity_Name (Prefix (Exp)))
4251
         then
4252
            null;
4253
 
4254
         --  Otherwise we are going to need a temporary to capture the value
4255
 
4256
         else
4257
            declare
4258
               Tnn : constant Entity_Id :=
4259
                       Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
4260
 
4261
            begin
4262
               --  For a complex expression of an elementary type, capture
4263
               --  value in the temporary and use it as the reference.
4264
 
4265
               if Is_Elementary_Type (R_Type) then
4266
                  Insert_Action (Exp,
4267
                    Make_Object_Declaration (Loc,
4268
                      Defining_Identifier => Tnn,
4269
                      Constant_Present    => True,
4270
                      Object_Definition   => New_Occurrence_Of (R_Type, Loc),
4271
                      Expression          => Relocate_Node (Exp)),
4272
                    Suppress => All_Checks);
4273
 
4274
                  Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4275
 
4276
               --  If we have something we can rename, generate a renaming of
4277
               --  the object and replace the expression with a reference
4278
 
4279
               elsif Is_Object_Reference (Exp) then
4280
                  Insert_Action (Exp,
4281
                    Make_Object_Renaming_Declaration (Loc,
4282
                      Defining_Identifier => Tnn,
4283
                      Subtype_Mark        => New_Occurrence_Of (R_Type, Loc),
4284
                      Name                => Relocate_Node (Exp)),
4285
                    Suppress => All_Checks);
4286
 
4287
                  Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4288
 
4289
               --  Otherwise we have something like a string literal or an
4290
               --  aggregate. We could copy the value, but that would be
4291
               --  inefficient. Instead we make a reference to the value and
4292
               --  capture this reference with a renaming, the expression is
4293
               --  then replaced by a dereference of this renaming.
4294
 
4295
               else
4296
                  --  For now, copy the value, since the code below does not
4297
                  --  seem to work correctly ???
4298
 
4299
                  Insert_Action (Exp,
4300
                    Make_Object_Declaration (Loc,
4301
                      Defining_Identifier => Tnn,
4302
                      Constant_Present    => True,
4303
                      Object_Definition   => New_Occurrence_Of (R_Type, Loc),
4304
                      Expression          => Relocate_Node (Exp)),
4305
                    Suppress => All_Checks);
4306
 
4307
                  Rewrite (Exp, New_Occurrence_Of (Tnn, Loc));
4308
 
4309
                  --  Insert_Action (Exp,
4310
                  --    Make_Object_Renaming_Declaration (Loc,
4311
                  --      Defining_Identifier => Tnn,
4312
                  --      Access_Definition =>
4313
                  --        Make_Access_Definition (Loc,
4314
                  --          All_Present  => True,
4315
                  --          Subtype_Mark => New_Occurrence_Of (R_Type, Loc)),
4316
                  --      Name =>
4317
                  --        Make_Reference (Loc,
4318
                  --          Prefix => Relocate_Node (Exp))),
4319
                  --    Suppress => All_Checks);
4320
 
4321
                  --  Rewrite (Exp,
4322
                  --    Make_Explicit_Dereference (Loc,
4323
                  --      Prefix => New_Occurrence_Of (Tnn, Loc)));
4324
               end if;
4325
            end;
4326
         end if;
4327
 
4328
         --  Generate call to _postconditions
4329
 
4330
         Insert_Action (Exp,
4331
           Make_Procedure_Call_Statement (Loc,
4332
             Name => Make_Identifier (Loc, Name_uPostconditions),
4333
             Parameter_Associations => New_List (Duplicate_Subexpr (Exp))));
4334
      end if;
4335
 
4336
      --  Ada 2005 (AI-251): If this return statement corresponds with an
4337
      --  simple return statement associated with an extended return statement
4338
      --  and the type of the returned object is an interface then generate an
4339
      --  implicit conversion to force displacement of the "this" pointer.
4340
 
4341
      if Ada_Version >= Ada_05
4342
        and then Comes_From_Extended_Return_Statement (N)
4343
        and then Nkind (Expression (N)) = N_Identifier
4344
        and then Is_Interface (Utyp)
4345
        and then Utyp /= Underlying_Type (Exptyp)
4346
      then
4347
         Rewrite (Exp, Convert_To (Utyp, Relocate_Node (Exp)));
4348
         Analyze_And_Resolve (Exp);
4349
      end if;
4350
   end Expand_Simple_Function_Return;
4351
 
4352
   ------------------------------
4353
   -- Make_Tag_Ctrl_Assignment --
4354
   ------------------------------
4355
 
4356
   function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4357
      Loc : constant Source_Ptr := Sloc (N);
4358
      L   : constant Node_Id    := Name (N);
4359
      T   : constant Entity_Id  := Underlying_Type (Etype (L));
4360
 
4361
      Ctrl_Act : constant Boolean := Needs_Finalization (T)
4362
                                       and then not No_Ctrl_Actions (N);
4363
 
4364
      Component_Assign : constant Boolean :=
4365
                           Is_Fully_Repped_Tagged_Type (T);
4366
 
4367
      Save_Tag : constant Boolean := Is_Tagged_Type (T)
4368
                                       and then not Component_Assign
4369
                                       and then not No_Ctrl_Actions (N)
4370
                                       and then Tagged_Type_Expansion;
4371
      --  Tags are not saved and restored when VM_Target because VM tags are
4372
      --  represented implicitly in objects.
4373
 
4374
      Res      : List_Id;
4375
      Tag_Tmp  : Entity_Id;
4376
 
4377
      Prev_Tmp : Entity_Id;
4378
      Next_Tmp : Entity_Id;
4379
      Ctrl_Ref : Node_Id;
4380
 
4381
   begin
4382
      Res := New_List;
4383
 
4384
      --  Finalize the target of the assignment when controlled
4385
 
4386
      --  We have two exceptions here:
4387
 
4388
      --   1. If we are in an init proc since it is an initialization more
4389
      --      than an assignment.
4390
 
4391
      --   2. If the left-hand side is a temporary that was not initialized
4392
      --      (or the parent part of a temporary since it is the case in
4393
      --      extension aggregates). Such a temporary does not come from
4394
      --      source. We must examine the original node for the prefix, because
4395
      --      it may be a component of an entry formal, in which case it has
4396
      --      been rewritten and does not appear to come from source either.
4397
 
4398
      --  Case of init proc
4399
 
4400
      if not Ctrl_Act then
4401
         null;
4402
 
4403
      --  The left hand side is an uninitialized temporary object
4404
 
4405
      elsif Nkind (L) = N_Type_Conversion
4406
        and then Is_Entity_Name (Expression (L))
4407
        and then Nkind (Parent (Entity (Expression (L)))) =
4408
                                              N_Object_Declaration
4409
        and then No_Initialization (Parent (Entity (Expression (L))))
4410
      then
4411
         null;
4412
 
4413
      else
4414
         Append_List_To (Res,
4415
           Make_Final_Call
4416
             (Ref         => Duplicate_Subexpr_No_Checks (L),
4417
              Typ         => Etype (L),
4418
              With_Detach => New_Reference_To (Standard_False, Loc)));
4419
      end if;
4420
 
4421
      --  Save the Tag in a local variable Tag_Tmp
4422
 
4423
      if Save_Tag then
4424
         Tag_Tmp :=
4425
           Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
4426
 
4427
         Append_To (Res,
4428
           Make_Object_Declaration (Loc,
4429
             Defining_Identifier => Tag_Tmp,
4430
             Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
4431
             Expression =>
4432
               Make_Selected_Component (Loc,
4433
                 Prefix        => Duplicate_Subexpr_No_Checks (L),
4434
                 Selector_Name => New_Reference_To (First_Tag_Component (T),
4435
                                                    Loc))));
4436
 
4437
      --  Otherwise Tag_Tmp not used
4438
 
4439
      else
4440
         Tag_Tmp := Empty;
4441
      end if;
4442
 
4443
      if Ctrl_Act then
4444
         if VM_Target /= No_VM then
4445
 
4446
            --  Cannot assign part of the object in a VM context, so instead
4447
            --  fallback to the previous mechanism, even though it is not
4448
            --  completely correct ???
4449
 
4450
            --  Save the Finalization Pointers in local variables Prev_Tmp and
4451
            --  Next_Tmp. For objects with Has_Controlled_Component set, these
4452
            --  pointers are in the Record_Controller
4453
 
4454
            Ctrl_Ref := Duplicate_Subexpr (L);
4455
 
4456
            if Has_Controlled_Component (T) then
4457
               Ctrl_Ref :=
4458
                 Make_Selected_Component (Loc,
4459
                   Prefix => Ctrl_Ref,
4460
                   Selector_Name =>
4461
                     New_Reference_To (Controller_Component (T), Loc));
4462
            end if;
4463
 
4464
            Prev_Tmp :=
4465
              Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
4466
 
4467
            Append_To (Res,
4468
              Make_Object_Declaration (Loc,
4469
                Defining_Identifier => Prev_Tmp,
4470
 
4471
                Object_Definition =>
4472
                  New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
4473
 
4474
                Expression =>
4475
                  Make_Selected_Component (Loc,
4476
                    Prefix =>
4477
                      Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref),
4478
                    Selector_Name => Make_Identifier (Loc, Name_Prev))));
4479
 
4480
            Next_Tmp :=
4481
              Make_Defining_Identifier (Loc,
4482
                Chars => New_Internal_Name ('C'));
4483
 
4484
            Append_To (Res,
4485
              Make_Object_Declaration (Loc,
4486
                Defining_Identifier => Next_Tmp,
4487
 
4488
                Object_Definition   =>
4489
                  New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
4490
 
4491
                Expression          =>
4492
                  Make_Selected_Component (Loc,
4493
                    Prefix =>
4494
                      Unchecked_Convert_To (RTE (RE_Finalizable),
4495
                        New_Copy_Tree (Ctrl_Ref)),
4496
                    Selector_Name => Make_Identifier (Loc, Name_Next))));
4497
 
4498
            --  Do the Assignment
4499
 
4500
            Append_To (Res, Relocate_Node (N));
4501
 
4502
         else
4503
            --  Regular (non VM) processing for controlled types and types with
4504
            --  controlled components
4505
 
4506
            --  Variables of such types contain pointers used to chain them in
4507
            --  finalization lists, in addition to user data. These pointers
4508
            --  are specific to each object of the type, not to the value being
4509
            --  assigned.
4510
 
4511
            --  Thus they need to be left intact during the assignment. We
4512
            --  achieve this by constructing a Storage_Array subtype, and by
4513
            --  overlaying objects of this type on the source and target of the
4514
            --  assignment. The assignment is then rewritten to assignments of
4515
            --  slices of these arrays, copying the user data, and leaving the
4516
            --  pointers untouched.
4517
 
4518
            Controlled_Actions : declare
4519
               Prev_Ref : Node_Id;
4520
               --  A reference to the Prev component of the record controller
4521
 
4522
               First_After_Root : Node_Id := Empty;
4523
               --  Index of first byte to be copied (used to skip
4524
               --  Root_Controlled in controlled objects).
4525
 
4526
               Last_Before_Hole : Node_Id := Empty;
4527
               --  Index of last byte to be copied before outermost record
4528
               --  controller data.
4529
 
4530
               Hole_Length : Node_Id := Empty;
4531
               --  Length of record controller data (Prev and Next pointers)
4532
 
4533
               First_After_Hole : Node_Id := Empty;
4534
               --  Index of first byte to be copied after outermost record
4535
               --  controller data.
4536
 
4537
               Expr, Source_Size     : Node_Id;
4538
               Source_Actual_Subtype : Entity_Id;
4539
               --  Used for computation of the size of the data to be copied
4540
 
4541
               Range_Type  : Entity_Id;
4542
               Opaque_Type : Entity_Id;
4543
 
4544
               function Build_Slice
4545
                 (Rec : Entity_Id;
4546
                  Lo  : Node_Id;
4547
                  Hi  : Node_Id) return Node_Id;
4548
               --  Build and return a slice of an array of type S overlaid on
4549
               --  object Rec, with bounds specified by Lo and Hi. If either
4550
               --  bound is empty, a default of S'First (respectively S'Last)
4551
               --  is used.
4552
 
4553
               -----------------
4554
               -- Build_Slice --
4555
               -----------------
4556
 
4557
               function Build_Slice
4558
                 (Rec : Node_Id;
4559
                  Lo  : Node_Id;
4560
                  Hi  : Node_Id) return Node_Id
4561
               is
4562
                  Lo_Bound : Node_Id;
4563
                  Hi_Bound : Node_Id;
4564
 
4565
                  Opaque : constant Node_Id :=
4566
                             Unchecked_Convert_To (Opaque_Type,
4567
                               Make_Attribute_Reference (Loc,
4568
                                 Prefix         => Rec,
4569
                                 Attribute_Name => Name_Address));
4570
                  --  Access value designating an opaque storage array of type
4571
                  --  S overlaid on record Rec.
4572
 
4573
               begin
4574
                  --  Compute slice bounds using S'First (1) and S'Last as
4575
                  --  default values when not specified by the caller.
4576
 
4577
                  if No (Lo) then
4578
                     Lo_Bound := Make_Integer_Literal (Loc, 1);
4579
                  else
4580
                     Lo_Bound := Lo;
4581
                  end if;
4582
 
4583
                  if No (Hi) then
4584
                     Hi_Bound := Make_Attribute_Reference (Loc,
4585
                       Prefix => New_Occurrence_Of (Range_Type, Loc),
4586
                       Attribute_Name => Name_Last);
4587
                  else
4588
                     Hi_Bound := Hi;
4589
                  end if;
4590
 
4591
                  return Make_Slice (Loc,
4592
                    Prefix =>
4593
                      Opaque,
4594
                    Discrete_Range => Make_Range (Loc,
4595
                      Lo_Bound, Hi_Bound));
4596
               end Build_Slice;
4597
 
4598
            --  Start of processing for Controlled_Actions
4599
 
4600
            begin
4601
               --  Create a constrained subtype of Storage_Array whose size
4602
               --  corresponds to the value being assigned.
4603
 
4604
               --  subtype G is Storage_Offset range
4605
               --    1 .. (Expr'Size + Storage_Unit - 1) / Storage_Unit
4606
 
4607
               Expr := Duplicate_Subexpr_No_Checks (Expression (N));
4608
 
4609
               if Nkind (Expr) = N_Qualified_Expression then
4610
                  Expr := Expression (Expr);
4611
               end if;
4612
 
4613
               Source_Actual_Subtype := Etype (Expr);
4614
 
4615
               if Has_Discriminants (Source_Actual_Subtype)
4616
                 and then not Is_Constrained (Source_Actual_Subtype)
4617
               then
4618
                  Append_To (Res,
4619
                    Build_Actual_Subtype (Source_Actual_Subtype, Expr));
4620
                  Source_Actual_Subtype := Defining_Identifier (Last (Res));
4621
               end if;
4622
 
4623
               Source_Size :=
4624
                 Make_Op_Add (Loc,
4625
                   Left_Opnd =>
4626
                     Make_Attribute_Reference (Loc,
4627
                       Prefix =>
4628
                         New_Occurrence_Of (Source_Actual_Subtype, Loc),
4629
                     Attribute_Name => Name_Size),
4630
                   Right_Opnd =>
4631
                     Make_Integer_Literal (Loc,
4632
                       Intval => System_Storage_Unit - 1));
4633
 
4634
               Source_Size :=
4635
                 Make_Op_Divide (Loc,
4636
                   Left_Opnd => Source_Size,
4637
                   Right_Opnd =>
4638
                     Make_Integer_Literal (Loc,
4639
                       Intval => System_Storage_Unit));
4640
 
4641
               Range_Type :=
4642
                 Make_Defining_Identifier (Loc,
4643
                   New_Internal_Name ('G'));
4644
 
4645
               Append_To (Res,
4646
                 Make_Subtype_Declaration (Loc,
4647
                   Defining_Identifier => Range_Type,
4648
                   Subtype_Indication =>
4649
                     Make_Subtype_Indication (Loc,
4650
                       Subtype_Mark =>
4651
                         New_Reference_To (RTE (RE_Storage_Offset), Loc),
4652
                       Constraint   => Make_Range_Constraint (Loc,
4653
                         Range_Expression =>
4654
                           Make_Range (Loc,
4655
                             Low_Bound  => Make_Integer_Literal (Loc, 1),
4656
                             High_Bound => Source_Size)))));
4657
 
4658
               --  subtype S is Storage_Array (G)
4659
 
4660
               Append_To (Res,
4661
                 Make_Subtype_Declaration (Loc,
4662
                   Defining_Identifier =>
4663
                     Make_Defining_Identifier (Loc,
4664
                       New_Internal_Name ('S')),
4665
                   Subtype_Indication  =>
4666
                     Make_Subtype_Indication (Loc,
4667
                       Subtype_Mark =>
4668
                         New_Reference_To (RTE (RE_Storage_Array), Loc),
4669
                       Constraint =>
4670
                         Make_Index_Or_Discriminant_Constraint (Loc,
4671
                           Constraints =>
4672
                             New_List (New_Reference_To (Range_Type, Loc))))));
4673
 
4674
               --  type A is access S
4675
 
4676
               Opaque_Type :=
4677
                 Make_Defining_Identifier (Loc,
4678
                   Chars => New_Internal_Name ('A'));
4679
 
4680
               Append_To (Res,
4681
                 Make_Full_Type_Declaration (Loc,
4682
                   Defining_Identifier => Opaque_Type,
4683
                   Type_Definition     =>
4684
                     Make_Access_To_Object_Definition (Loc,
4685
                       Subtype_Indication =>
4686
                         New_Occurrence_Of (
4687
                           Defining_Identifier (Last (Res)), Loc))));
4688
 
4689
               --  Generate appropriate slice assignments
4690
 
4691
               First_After_Root := Make_Integer_Literal (Loc, 1);
4692
 
4693
               --  For controlled object, skip Root_Controlled part
4694
 
4695
               if Is_Controlled (T) then
4696
                  First_After_Root :=
4697
                    Make_Op_Add (Loc,
4698
                      First_After_Root,
4699
                      Make_Op_Divide (Loc,
4700
                        Make_Attribute_Reference (Loc,
4701
                          Prefix =>
4702
                            New_Occurrence_Of (RTE (RE_Root_Controlled), Loc),
4703
                          Attribute_Name => Name_Size),
4704
                        Make_Integer_Literal (Loc, System_Storage_Unit)));
4705
               end if;
4706
 
4707
               --  For the case of a record with controlled components, skip
4708
               --  record controller Prev/Next components. These components
4709
               --  constitute a 'hole' in the middle of the data to be copied.
4710
 
4711
               if Has_Controlled_Component (T) then
4712
                  Prev_Ref :=
4713
                    Make_Selected_Component (Loc,
4714
                      Prefix =>
4715
                        Make_Selected_Component (Loc,
4716
                          Prefix => Duplicate_Subexpr_No_Checks (L),
4717
                          Selector_Name =>
4718
                            New_Reference_To (Controller_Component (T), Loc)),
4719
                      Selector_Name =>  Make_Identifier (Loc, Name_Prev));
4720
 
4721
                  --  Last index before hole: determined by position of the
4722
                  --  _Controller.Prev component.
4723
 
4724
                  Last_Before_Hole :=
4725
                    Make_Defining_Identifier (Loc,
4726
                      New_Internal_Name ('L'));
4727
 
4728
                  Append_To (Res,
4729
                    Make_Object_Declaration (Loc,
4730
                      Defining_Identifier => Last_Before_Hole,
4731
                      Object_Definition   => New_Occurrence_Of (
4732
                        RTE (RE_Storage_Offset), Loc),
4733
                      Constant_Present    => True,
4734
                      Expression          => Make_Op_Add (Loc,
4735
                          Make_Attribute_Reference (Loc,
4736
                            Prefix => Prev_Ref,
4737
                            Attribute_Name => Name_Position),
4738
                          Make_Attribute_Reference (Loc,
4739
                            Prefix => New_Copy_Tree (Prefix (Prev_Ref)),
4740
                            Attribute_Name => Name_Position))));
4741
 
4742
                  --  Hole length: size of the Prev and Next components
4743
 
4744
                  Hole_Length :=
4745
                    Make_Op_Multiply (Loc,
4746
                      Left_Opnd  => Make_Integer_Literal (Loc, Uint_2),
4747
                      Right_Opnd =>
4748
                        Make_Op_Divide (Loc,
4749
                          Left_Opnd =>
4750
                            Make_Attribute_Reference (Loc,
4751
                              Prefix         => New_Copy_Tree (Prev_Ref),
4752
                              Attribute_Name => Name_Size),
4753
                          Right_Opnd =>
4754
                            Make_Integer_Literal (Loc,
4755
                              Intval => System_Storage_Unit)));
4756
 
4757
                  --  First index after hole
4758
 
4759
                  First_After_Hole :=
4760
                    Make_Defining_Identifier (Loc,
4761
                      New_Internal_Name ('F'));
4762
 
4763
                  Append_To (Res,
4764
                    Make_Object_Declaration (Loc,
4765
                      Defining_Identifier => First_After_Hole,
4766
                      Object_Definition   => New_Occurrence_Of (
4767
                        RTE (RE_Storage_Offset), Loc),
4768
                      Constant_Present    => True,
4769
                      Expression          =>
4770
                        Make_Op_Add (Loc,
4771
                          Left_Opnd  =>
4772
                            Make_Op_Add (Loc,
4773
                              Left_Opnd  =>
4774
                                New_Occurrence_Of (Last_Before_Hole, Loc),
4775
                              Right_Opnd => Hole_Length),
4776
                          Right_Opnd => Make_Integer_Literal (Loc, 1))));
4777
 
4778
                  Last_Before_Hole :=
4779
                    New_Occurrence_Of (Last_Before_Hole, Loc);
4780
                  First_After_Hole :=
4781
                    New_Occurrence_Of (First_After_Hole, Loc);
4782
               end if;
4783
 
4784
               --  Assign the first slice (possibly skipping Root_Controlled,
4785
               --  up to the beginning of the record controller if present,
4786
               --  up to the end of the object if not).
4787
 
4788
               Append_To (Res, Make_Assignment_Statement (Loc,
4789
                 Name       => Build_Slice (
4790
                   Rec => Duplicate_Subexpr_No_Checks (L),
4791
                   Lo  => First_After_Root,
4792
                   Hi  => Last_Before_Hole),
4793
 
4794
                 Expression => Build_Slice (
4795
                   Rec => Expression (N),
4796
                   Lo  => First_After_Root,
4797
                   Hi  => New_Copy_Tree (Last_Before_Hole))));
4798
 
4799
               if Present (First_After_Hole) then
4800
 
4801
                  --  If a record controller is present, copy the second slice,
4802
                  --  from right after the _Controller.Next component up to the
4803
                  --  end of the object.
4804
 
4805
                  Append_To (Res, Make_Assignment_Statement (Loc,
4806
                    Name       => Build_Slice (
4807
                      Rec => Duplicate_Subexpr_No_Checks (L),
4808
                      Lo  => First_After_Hole,
4809
                      Hi  => Empty),
4810
                    Expression => Build_Slice (
4811
                      Rec => Duplicate_Subexpr_No_Checks (Expression (N)),
4812
                      Lo  => New_Copy_Tree (First_After_Hole),
4813
                      Hi  => Empty)));
4814
               end if;
4815
            end Controlled_Actions;
4816
         end if;
4817
 
4818
      --  Not controlled case
4819
 
4820
      else
4821
         declare
4822
            Asn : constant Node_Id := Relocate_Node (N);
4823
 
4824
         begin
4825
            --  If this is the case of a tagged type with a full rep clause,
4826
            --  we must expand it into component assignments, so we mark the
4827
            --  node as unanalyzed, to get it reanalyzed, but flag it has
4828
            --  requiring component-wise assignment so we don't get infinite
4829
            --  recursion.
4830
 
4831
            if Component_Assign then
4832
               Set_Analyzed (Asn, False);
4833
               Set_Componentwise_Assignment (Asn, True);
4834
            end if;
4835
 
4836
            Append_To (Res, Asn);
4837
         end;
4838
      end if;
4839
 
4840
      --  Restore the tag
4841
 
4842
      if Save_Tag then
4843
         Append_To (Res,
4844
           Make_Assignment_Statement (Loc,
4845
             Name =>
4846
               Make_Selected_Component (Loc,
4847
                 Prefix        => Duplicate_Subexpr_No_Checks (L),
4848
                 Selector_Name => New_Reference_To (First_Tag_Component (T),
4849
                                                    Loc)),
4850
             Expression => New_Reference_To (Tag_Tmp, Loc)));
4851
      end if;
4852
 
4853
      if Ctrl_Act then
4854
         if VM_Target /= No_VM then
4855
            --  Restore the finalization pointers
4856
 
4857
            Append_To (Res,
4858
              Make_Assignment_Statement (Loc,
4859
                Name =>
4860
                  Make_Selected_Component (Loc,
4861
                    Prefix =>
4862
                      Unchecked_Convert_To (RTE (RE_Finalizable),
4863
                        New_Copy_Tree (Ctrl_Ref)),
4864
                    Selector_Name => Make_Identifier (Loc, Name_Prev)),
4865
                Expression => New_Reference_To (Prev_Tmp, Loc)));
4866
 
4867
            Append_To (Res,
4868
              Make_Assignment_Statement (Loc,
4869
                Name =>
4870
                  Make_Selected_Component (Loc,
4871
                    Prefix =>
4872
                      Unchecked_Convert_To (RTE (RE_Finalizable),
4873
                        New_Copy_Tree (Ctrl_Ref)),
4874
                    Selector_Name => Make_Identifier (Loc, Name_Next)),
4875
                Expression => New_Reference_To (Next_Tmp, Loc)));
4876
         end if;
4877
 
4878
         --  Adjust the target after the assignment when controlled (not in the
4879
         --  init proc since it is an initialization more than an assignment).
4880
 
4881
         Append_List_To (Res,
4882
           Make_Adjust_Call (
4883
             Ref         => Duplicate_Subexpr_Move_Checks (L),
4884
             Typ         => Etype (L),
4885
             Flist_Ref   => New_Reference_To (RTE (RE_Global_Final_List), Loc),
4886
             With_Attach => Make_Integer_Literal (Loc, 0)));
4887
      end if;
4888
 
4889
      return Res;
4890
 
4891
   exception
4892
      --  Could use comment here ???
4893
 
4894
      when RE_Not_Available =>
4895
         return Empty_List;
4896
   end Make_Tag_Ctrl_Assignment;
4897
 
4898
end Exp_Ch5;

powered by: WebSVN 2.1.0

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