OSDN Git Service

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