OSDN Git Service

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