OSDN Git Service

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