OSDN Git Service

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