OSDN Git Service

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