OSDN Git Service

2004-01-05 Robert Dewar <dewar@gnat.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-2003, 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,  59 Temple Place - Suite 330,  Boston, --
20 -- MA 02111-1307, 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 Einfo;    use Einfo;
30 with Exp_Aggr; use Exp_Aggr;
31 with Exp_Ch7;  use Exp_Ch7;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Dbug; use Exp_Dbug;
34 with Exp_Pakd; use Exp_Pakd;
35 with Exp_Util; use Exp_Util;
36 with Hostparm; use Hostparm;
37 with Nlists;   use Nlists;
38 with Nmake;    use Nmake;
39 with Opt;      use Opt;
40 with Restrict; use Restrict;
41 with Rtsfind;  use Rtsfind;
42 with Sinfo;    use Sinfo;
43 with Sem;      use Sem;
44 with Sem_Ch8;  use Sem_Ch8;
45 with Sem_Ch13; use Sem_Ch13;
46 with Sem_Eval; use Sem_Eval;
47 with Sem_Res;  use Sem_Res;
48 with Sem_Util; use Sem_Util;
49 with Snames;   use Snames;
50 with Stand;    use Stand;
51 with Stringt;  use Stringt;
52 with Tbuild;   use Tbuild;
53 with Ttypes;   use Ttypes;
54 with Uintp;    use Uintp;
55 with Validsw;  use Validsw;
56
57 package body Exp_Ch5 is
58
59    function Change_Of_Representation (N : Node_Id) return Boolean;
60    --  Determine if the right hand side of the assignment N is a type
61    --  conversion which requires a change of representation. Called
62    --  only for the array and record cases.
63
64    procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
65    --  N is an assignment which assigns an array value. This routine process
66    --  the various special cases and checks required for such assignments,
67    --  including change of representation. Rhs is normally simply the right
68    --  hand side of the assignment, except that if the right hand side is
69    --  a type conversion or a qualified expression, then the Rhs is the
70    --  actual expression inside any such type conversions or qualifications.
71
72    function Expand_Assign_Array_Loop
73      (N      : Node_Id;
74       Larray : Entity_Id;
75       Rarray : Entity_Id;
76       L_Type : Entity_Id;
77       R_Type : Entity_Id;
78       Ndim   : Pos;
79       Rev    : Boolean) return Node_Id;
80    --  N is an assignment statement which assigns an array value. This routine
81    --  expands the assignment into a loop (or nested loops for the case of a
82    --  multi-dimensional array) to do the assignment component by component.
83    --  Larray and Rarray are the entities of the actual arrays on the left
84    --  hand and right hand sides. L_Type and R_Type are the types of these
85    --  arrays (which may not be the same, due to either sliding, or to a
86    --  change of representation case). Ndim is the number of dimensions and
87    --  the parameter Rev indicates if the loops run normally (Rev = False),
88    --  or reversed (Rev = True). The value returned is the constructed
89    --  loop statement. Auxiliary declarations are inserted before node N
90    --  using the standard Insert_Actions mechanism.
91
92    procedure Expand_Assign_Record (N : Node_Id);
93    --  N is an assignment of a non-tagged record value. This routine handles
94    --  the case where the assignment must be made component by component,
95    --  either because the target is not byte aligned, or there is a change
96    --  of representation.
97
98    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
99    --  Generate the necessary code for controlled and Tagged assignment,
100    --  that is to say, finalization of the target before, adjustement of
101    --  the target after and save and restore of the tag and finalization
102    --  pointers which are not 'part of the value' and must not be changed
103    --  upon assignment. N is the original Assignment node.
104
105    function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean;
106    --  This function is used in processing the assignment of a record or
107    --  indexed component. The argument N is either the left hand or right
108    --  hand side of an assignment, and this function determines if there
109    --  is a record component reference where the record may be bit aligned
110    --  in a manner that causes trouble for the back end (see description
111    --  of Sem_Util.Component_May_Be_Bit_Aligned for further details).
112
113    ------------------------------
114    -- Change_Of_Representation --
115    ------------------------------
116
117    function Change_Of_Representation (N : Node_Id) return Boolean is
118       Rhs : constant Node_Id := Expression (N);
119    begin
120       return
121         Nkind (Rhs) = N_Type_Conversion
122           and then
123             not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
124    end Change_Of_Representation;
125
126    -------------------------
127    -- Expand_Assign_Array --
128    -------------------------
129
130    --  There are two issues here. First, do we let Gigi do a block move, or
131    --  do we expand out into a loop? Second, we need to set the two flags
132    --  Forwards_OK and Backwards_OK which show whether the block move (or
133    --  corresponding loops) can be legitimately done in a forwards (low to
134    --  high) or backwards (high to low) manner.
135
136    procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
137       Loc : constant Source_Ptr := Sloc (N);
138
139       Lhs : constant Node_Id := Name (N);
140
141       Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
142       Act_Rhs : Node_Id          := Get_Referenced_Object (Rhs);
143
144       L_Type : constant Entity_Id :=
145                  Underlying_Type (Get_Actual_Subtype (Act_Lhs));
146       R_Type : Entity_Id :=
147                  Underlying_Type (Get_Actual_Subtype (Act_Rhs));
148
149       L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
150       R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
151
152       Crep : constant Boolean := Change_Of_Representation (N);
153
154       Larray  : Node_Id;
155       Rarray  : Node_Id;
156
157       Ndim : constant Pos := Number_Dimensions (L_Type);
158
159       Loop_Required : Boolean := False;
160       --  This switch is set to True if the array move must be done using
161       --  an explicit front end generated loop.
162
163       function Has_Address_Clause (Exp : Node_Id) return Boolean;
164       --  Test if Exp is a reference to an array whose declaration has
165       --  an address clause, or it is a slice of such an array.
166
167       function Is_Formal_Array (Exp : Node_Id) return Boolean;
168       --  Test if Exp is a reference to an array which is either a formal
169       --  parameter or a slice of a formal parameter. These are the cases
170       --  where hidden aliasing can occur.
171
172       function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
173       --  Determine if Exp is a reference to an array variable which is other
174       --  than an object defined in the current scope, or a slice of such
175       --  an object. Such objects can be aliased to parameters (unlike local
176       --  array references).
177
178       function Possible_Unaligned_Slice (Arg : Node_Id) return Boolean;
179       --  Returns True if Arg (either the left or right hand side of the
180       --  assignment) is a slice that could be unaligned wrt the array type.
181       --  This is true if Arg is a component of a packed record, or is
182       --  a record component to which a component clause applies. This
183       --  is a little pessimistic, but the result of an unnecessary
184       --  decision that something is possibly unaligned is only to
185       --  generate a front end loop, which is not so terrible.
186       --  It would really be better if backend handled this ???
187
188       ------------------------
189       -- Has_Address_Clause --
190       ------------------------
191
192       function Has_Address_Clause (Exp : Node_Id) return Boolean is
193       begin
194          return
195            (Is_Entity_Name (Exp) and then
196                               Present (Address_Clause (Entity (Exp))))
197              or else
198            (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
199       end Has_Address_Clause;
200
201       ---------------------
202       -- Is_Formal_Array --
203       ---------------------
204
205       function Is_Formal_Array (Exp : Node_Id) return Boolean is
206       begin
207          return
208            (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
209              or else
210            (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
211       end Is_Formal_Array;
212
213       ------------------------
214       -- Is_Non_Local_Array --
215       ------------------------
216
217       function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
218       begin
219          return (Is_Entity_Name (Exp)
220                    and then Scope (Entity (Exp)) /= Current_Scope)
221             or else (Nkind (Exp) = N_Slice
222                        and then Is_Non_Local_Array (Prefix (Exp)));
223       end Is_Non_Local_Array;
224
225       ------------------------------
226       -- Possible_Unaligned_Slice --
227       ------------------------------
228
229       function Possible_Unaligned_Slice (Arg : Node_Id) return Boolean is
230       begin
231          --  No issue if this is not a slice, or else strict alignment
232          --  is not required in any case.
233
234          if Nkind (Arg) /= N_Slice
235            or else not Target_Strict_Alignment
236          then
237             return False;
238          end if;
239
240          --  No issue if the component type is a byte or byte aligned
241
242          declare
243             Array_Typ : constant Entity_Id := Etype (Arg);
244             Comp_Typ  : constant Entity_Id := Component_Type (Array_Typ);
245             Pref      : constant Node_Id   := Prefix (Arg);
246
247          begin
248             if Known_Alignment (Array_Typ) then
249                if Alignment (Array_Typ) = 1 then
250                   return False;
251                end if;
252
253             elsif Known_Component_Size (Array_Typ) then
254                if Component_Size (Array_Typ) = 1 then
255                   return False;
256                end if;
257
258             elsif Known_Esize (Comp_Typ) then
259                if Esize (Comp_Typ) <= System_Storage_Unit then
260                   return False;
261                end if;
262             end if;
263
264             --  No issue if this is not a selected component
265
266             if Nkind (Pref) /= N_Selected_Component then
267                return False;
268             end if;
269
270             --  Else we test for a possibly unaligned component
271
272             return
273               Is_Packed (Etype (Pref))
274                 or else
275               Present (Component_Clause (Entity (Selector_Name (Pref))));
276          end;
277       end Possible_Unaligned_Slice;
278
279       --  Determine if Lhs, Rhs are formal arrays or nonlocal arrays
280
281       Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
282       Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
283
284       Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
285       Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
286
287    --  Start of processing for Expand_Assign_Array
288
289    begin
290       --  Deal with length check, note that the length check is done with
291       --  respect to the right hand side as given, not a possible underlying
292       --  renamed object, since this would generate incorrect extra checks.
293
294       Apply_Length_Check (Rhs, L_Type);
295
296       --  We start by assuming that the move can be done in either
297       --  direction, i.e. that the two sides are completely disjoint.
298
299       Set_Forwards_OK  (N, True);
300       Set_Backwards_OK (N, True);
301
302       --  Normally it is only the slice case that can lead to overlap,
303       --  and explicit checks for slices are made below. But there is
304       --  one case where the slice can be implicit and invisible to us
305       --  and that is the case where we have a one dimensional array,
306       --  and either both operands are parameters, or one is a parameter
307       --  and the other is a global variable. In this case the parameter
308       --  could be a slice that overlaps with the other parameter.
309
310       --  Check for the case of slices requiring an explicit loop. Normally
311       --  it is only the explicit slice cases that bother us, but in the
312       --  case of one dimensional arrays, parameters can be slices that
313       --  are passed by reference, so we can have aliasing for assignments
314       --  from one parameter to another, or assignments between parameters
315       --  and nonlocal variables. However, if the array subtype is a
316       --  constrained first subtype in the parameter case, then we don't
317       --  have to worry about overlap, since slice assignments aren't
318       --  possible (other than for a slice denoting the whole array).
319
320       --  Note: overlap is never possible if there is a change of
321       --  representation, so we can exclude this case.
322
323       if Ndim = 1
324         and then not Crep
325         and then
326            ((Lhs_Formal and Rhs_Formal)
327               or else
328             (Lhs_Formal and Rhs_Non_Local_Var)
329               or else
330             (Rhs_Formal and Lhs_Non_Local_Var))
331         and then
332            (not Is_Constrained (Etype (Lhs))
333              or else not Is_First_Subtype (Etype (Lhs)))
334
335          --  In the case of compiling for the Java Virtual Machine,
336          --  slices are always passed by making a copy, so we don't
337          --  have to worry about overlap. We also want to prevent
338          --  generation of "<" comparisons for array addresses,
339          --  since that's a meaningless operation on the JVM.
340
341         and then not Java_VM
342       then
343          Set_Forwards_OK  (N, False);
344          Set_Backwards_OK (N, False);
345
346          --  Note: the bit-packed case is not worrisome here, since if
347          --  we have a slice passed as a parameter, it is always aligned
348          --  on a byte boundary, and if there are no explicit slices, the
349          --  assignment can be performed directly.
350       end if;
351
352       --  We certainly must use a loop for change of representation
353       --  and also we use the operand of the conversion on the right
354       --  hand side as the effective right hand side (the component
355       --  types must match in this situation).
356
357       if Crep then
358          Act_Rhs := Get_Referenced_Object (Rhs);
359          R_Type  := Get_Actual_Subtype (Act_Rhs);
360          Loop_Required := True;
361
362       --  We require a loop if the left side is possibly bit unaligned
363
364       elsif Possible_Bit_Aligned_Component (Lhs)
365               or else
366             Possible_Bit_Aligned_Component (Rhs)
367       then
368          Loop_Required := True;
369
370       --  Arrays with controlled components are expanded into a loop
371       --  to force calls to adjust at the component level.
372
373       elsif Has_Controlled_Component (L_Type) then
374          Loop_Required := True;
375
376       --  Case where no slice is involved
377
378       elsif not L_Slice and not R_Slice then
379
380          --  The following code deals with the case of unconstrained bit
381          --  packed arrays. The problem is that the template for such
382          --  arrays contains the bounds of the actual source level array,
383
384          --  But the copy of an entire array requires the bounds of the
385          --  underlying array. It would be nice if the back end could take
386          --  care of this, but right now it does not know how, so if we
387          --  have such a type, then we expand out into a loop, which is
388          --  inefficient but works correctly. If we don't do this, we
389          --  get the wrong length computed for the array to be moved.
390          --  The two cases we need to worry about are:
391
392          --  Explicit deference of an unconstrained packed array type as
393          --  in the following example:
394
395          --    procedure C52 is
396          --       type BITS is array(INTEGER range <>) of BOOLEAN;
397          --       pragma PACK(BITS);
398          --       type A is access BITS;
399          --       P1,P2 : A;
400          --    begin
401          --       P1 := new BITS (1 .. 65_535);
402          --       P2 := new BITS (1 .. 65_535);
403          --       P2.ALL := P1.ALL;
404          --    end C52;
405
406          --  A formal parameter reference with an unconstrained bit
407          --  array type is the other case we need to worry about (here
408          --  we assume the same BITS type declared above:
409
410          --    procedure Write_All (File : out BITS; Contents : in  BITS);
411          --    begin
412          --       File.Storage := Contents;
413          --    end Write_All;
414
415          --  We expand to a loop in either of these two cases.
416
417          --  Question for future thought. Another potentially more efficient
418          --  approach would be to create the actual subtype, and then do an
419          --  unchecked conversion to this actual subtype ???
420
421          Check_Unconstrained_Bit_Packed_Array : declare
422
423             function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
424             --  Function to perform required test for the first case,
425             --  above (dereference of an unconstrained bit packed array)
426
427             -----------------------
428             -- Is_UBPA_Reference --
429             -----------------------
430
431             function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
432                Typ      : constant Entity_Id := Underlying_Type (Etype (Opnd));
433                P_Type   : Entity_Id;
434                Des_Type : Entity_Id;
435
436             begin
437                if Present (Packed_Array_Type (Typ))
438                  and then Is_Array_Type (Packed_Array_Type (Typ))
439                  and then not Is_Constrained (Packed_Array_Type (Typ))
440                then
441                   return True;
442
443                elsif Nkind (Opnd) = N_Explicit_Dereference then
444                   P_Type := Underlying_Type (Etype (Prefix (Opnd)));
445
446                   if not Is_Access_Type (P_Type) then
447                      return False;
448
449                   else
450                      Des_Type := Designated_Type (P_Type);
451                      return
452                        Is_Bit_Packed_Array (Des_Type)
453                          and then not Is_Constrained (Des_Type);
454                   end if;
455
456                else
457                   return False;
458                end if;
459             end Is_UBPA_Reference;
460
461          --  Start of processing for Check_Unconstrained_Bit_Packed_Array
462
463          begin
464             if Is_UBPA_Reference (Lhs)
465                  or else
466                Is_UBPA_Reference (Rhs)
467             then
468                Loop_Required := True;
469
470             --  Here if we do not have the case of a reference to a bit
471             --  packed unconstrained array case. In this case gigi can
472             --  most certainly handle the assignment if a forwards move
473             --  is allowed.
474
475             --  (could it handle the backwards case also???)
476
477             elsif Forwards_OK (N) then
478                return;
479             end if;
480          end Check_Unconstrained_Bit_Packed_Array;
481
482       --  Gigi can always handle the assignment if the right side is a string
483       --  literal (note that overlap is definitely impossible in this case).
484       --  If the type is packed, a string literal is always converted into a
485       --  aggregate, except in the case of a null slice, for which no aggregate
486       --  can be written. In that case, rewrite the assignment as a null
487       --  statement, a length check has already been emitted to verify that
488       --  the range of the left-hand side is empty.
489
490       --  Note that this code is not executed if we had an assignment of
491       --  a string literal to a non-bit aligned component of a record, a
492       --  case which cannot be handled by the backend
493
494       elsif Nkind (Rhs) = N_String_Literal then
495          if String_Length (Strval (Rhs)) = 0
496            and then Is_Bit_Packed_Array (L_Type)
497          then
498             Rewrite (N, Make_Null_Statement (Loc));
499             Analyze (N);
500          end if;
501
502          return;
503
504       --  If either operand is bit packed, then we need a loop, since we
505       --  can't be sure that the slice is byte aligned. Similarly, if either
506       --  operand is a possibly unaligned slice, then we need a loop (since
507       --  gigi cannot handle unaligned slices).
508
509       elsif Is_Bit_Packed_Array (L_Type)
510         or else Is_Bit_Packed_Array (R_Type)
511         or else Possible_Unaligned_Slice (Lhs)
512         or else Possible_Unaligned_Slice (Rhs)
513       then
514          Loop_Required := True;
515
516       --  If we are not bit-packed, and we have only one slice, then no
517       --  overlap is possible except in the parameter case, so we can let
518       --  gigi handle things.
519
520       elsif not (L_Slice and R_Slice) then
521          if Forwards_OK (N) then
522             return;
523          end if;
524       end if;
525
526       --  Come here to compelete the analysis
527
528       --    Loop_Required: Set to True if we know that a loop is required
529       --                   regardless of overlap considerations.
530
531       --    Forwards_OK:   Set to False if we already know that a forwards
532       --                   move is not safe, else set to True.
533
534       --    Backwards_OK:  Set to False if we already know that a backwards
535       --                   move is not safe, else set to True
536
537       --  Our task at this stage is to complete the overlap analysis, which
538       --  can result in possibly setting Forwards_OK or Backwards_OK to
539       --  False, and then generating the final code, either by deciding
540       --  that it is OK after all to let Gigi handle it, or by generating
541       --  appropriate code in the front end.
542
543       declare
544          L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
545          R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
546
547          Left_Lo  : constant Node_Id := Type_Low_Bound  (L_Index_Typ);
548          Left_Hi  : constant Node_Id := Type_High_Bound (L_Index_Typ);
549          Right_Lo : constant Node_Id := Type_Low_Bound  (R_Index_Typ);
550          Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
551
552          Act_L_Array : Node_Id;
553          Act_R_Array : Node_Id;
554
555          Cleft_Lo  : Node_Id;
556          Cright_Lo : Node_Id;
557          Condition : Node_Id;
558
559          Cresult : Compare_Result;
560
561       begin
562          --  Get the expressions for the arrays. If we are dealing with a
563          --  private type, then convert to the underlying type. We can do
564          --  direct assignments to an array that is a private type, but
565          --  we cannot assign to elements of the array without this extra
566          --  unchecked conversion.
567
568          if Nkind (Act_Lhs) = N_Slice then
569             Larray := Prefix (Act_Lhs);
570          else
571             Larray := Act_Lhs;
572
573             if Is_Private_Type (Etype (Larray)) then
574                Larray :=
575                  Unchecked_Convert_To
576                    (Underlying_Type (Etype (Larray)), Larray);
577             end if;
578          end if;
579
580          if Nkind (Act_Rhs) = N_Slice then
581             Rarray := Prefix (Act_Rhs);
582          else
583             Rarray := Act_Rhs;
584
585             if Is_Private_Type (Etype (Rarray)) then
586                Rarray :=
587                  Unchecked_Convert_To
588                    (Underlying_Type (Etype (Rarray)), Rarray);
589             end if;
590          end if;
591
592          --  If both sides are slices, we must figure out whether
593          --  it is safe to do the move in one direction or the other
594          --  It is always safe if there is a change of representation
595          --  since obviously two arrays with different representations
596          --  cannot possibly overlap.
597
598          if (not Crep) and L_Slice and R_Slice then
599             Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
600             Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
601
602             --  If both left and right hand arrays are entity names, and
603             --  refer to different entities, then we know that the move
604             --  is safe (the two storage areas are completely disjoint).
605
606             if Is_Entity_Name (Act_L_Array)
607               and then Is_Entity_Name (Act_R_Array)
608               and then Entity (Act_L_Array) /= Entity (Act_R_Array)
609             then
610                null;
611
612             --  Otherwise, we assume the worst, which is that the two
613             --  arrays are the same array. There is no need to check if
614             --  we know that is the case, because if we don't know it,
615             --  we still have to assume it!
616
617             --  Generally if the same array is involved, then we have
618             --  an overlapping case. We will have to really assume the
619             --  worst (i.e. set neither of the OK flags) unless we can
620             --  determine the lower or upper bounds at compile time and
621             --  compare them.
622
623             else
624                Cresult := Compile_Time_Compare (Left_Lo, Right_Lo);
625
626                if Cresult = Unknown then
627                   Cresult := Compile_Time_Compare (Left_Hi, Right_Hi);
628                end if;
629
630                case Cresult is
631                   when LT | LE | EQ => Set_Backwards_OK (N, False);
632                   when GT | GE      => Set_Forwards_OK  (N, False);
633                   when NE | Unknown => Set_Backwards_OK (N, False);
634                                        Set_Forwards_OK  (N, False);
635                end case;
636             end if;
637          end if;
638
639          --  If after that analysis, Forwards_OK is still True, and
640          --  Loop_Required is False, meaning that we have not discovered
641          --  some non-overlap reason for requiring a loop, then we can
642          --  still let gigi handle it.
643
644          if not Loop_Required then
645             if Forwards_OK (N) then
646                return;
647
648             else
649                null;
650                --  Here is where a memmove would be appropriate ???
651             end if;
652          end if;
653
654          --  At this stage we have to generate an explicit loop, and
655          --  we have the following cases:
656
657          --  Forwards_OK = True
658
659          --    Rnn : right_index := right_index'First;
660          --    for Lnn in left-index loop
661          --       left (Lnn) := right (Rnn);
662          --       Rnn := right_index'Succ (Rnn);
663          --    end loop;
664
665          --    Note: the above code MUST be analyzed with checks off,
666          --    because otherwise the Succ could overflow. But in any
667          --    case this is more efficient!
668
669          --  Forwards_OK = False, Backwards_OK = True
670
671          --    Rnn : right_index := right_index'Last;
672          --    for Lnn in reverse left-index loop
673          --       left (Lnn) := right (Rnn);
674          --       Rnn := right_index'Pred (Rnn);
675          --    end loop;
676
677          --    Note: the above code MUST be analyzed with checks off,
678          --    because otherwise the Pred could overflow. But in any
679          --    case this is more efficient!
680
681          --  Forwards_OK = Backwards_OK = False
682
683          --    This only happens if we have the same array on each side. It is
684          --    possible to create situations using overlays that violate this,
685          --    but we simply do not promise to get this "right" in this case.
686
687          --    There are two possible subcases. If the No_Implicit_Conditionals
688          --    restriction is set, then we generate the following code:
689
690          --      declare
691          --        T : constant <operand-type> := rhs;
692          --      begin
693          --        lhs := T;
694          --      end;
695
696          --    If implicit conditionals are permitted, then we generate:
697
698          --      if Left_Lo <= Right_Lo then
699          --         <code for Forwards_OK = True above>
700          --      else
701          --         <code for Backwards_OK = True above>
702          --      end if;
703
704          --  Cases where either Forwards_OK or Backwards_OK is true
705
706          if Forwards_OK (N) or else Backwards_OK (N) then
707             Rewrite (N,
708               Expand_Assign_Array_Loop
709                 (N, Larray, Rarray, L_Type, R_Type, Ndim,
710                  Rev => not Forwards_OK (N)));
711
712          --  Case of both are false with No_Implicit_Conditionals
713
714          elsif Restrictions (No_Implicit_Conditionals) then
715             declare
716                   T : constant Entity_Id :=
717                         Make_Defining_Identifier (Loc, Chars => Name_T);
718
719             begin
720                Rewrite (N,
721                  Make_Block_Statement (Loc,
722                   Declarations => New_List (
723                     Make_Object_Declaration (Loc,
724                       Defining_Identifier => T,
725                       Constant_Present  => True,
726                       Object_Definition =>
727                         New_Occurrence_Of (Etype (Rhs), Loc),
728                       Expression        => Relocate_Node (Rhs))),
729
730                     Handled_Statement_Sequence =>
731                       Make_Handled_Sequence_Of_Statements (Loc,
732                         Statements => New_List (
733                           Make_Assignment_Statement (Loc,
734                             Name       => Relocate_Node (Lhs),
735                             Expression => New_Occurrence_Of (T, Loc))))));
736             end;
737
738          --  Case of both are false with implicit conditionals allowed
739
740          else
741             --  Before we generate this code, we must ensure that the
742             --  left and right side array types are defined. They may
743             --  be itypes, and we cannot let them be defined inside the
744             --  if, since the first use in the then may not be executed.
745
746             Ensure_Defined (L_Type, N);
747             Ensure_Defined (R_Type, N);
748
749             --  We normally compare addresses to find out which way round
750             --  to do the loop, since this is realiable, and handles the
751             --  cases of parameters, conversions etc. But we can't do that
752             --  in the bit packed case or the Java VM case, because addresses
753             --  don't work there.
754
755             if not Is_Bit_Packed_Array (L_Type) and then not Java_VM then
756                Condition :=
757                  Make_Op_Le (Loc,
758                    Left_Opnd =>
759                      Unchecked_Convert_To (RTE (RE_Integer_Address),
760                        Make_Attribute_Reference (Loc,
761                          Prefix =>
762                            Make_Indexed_Component (Loc,
763                              Prefix =>
764                                Duplicate_Subexpr_Move_Checks (Larray, True),
765                              Expressions => New_List (
766                                Make_Attribute_Reference (Loc,
767                                  Prefix =>
768                                    New_Reference_To
769                                      (L_Index_Typ, Loc),
770                                  Attribute_Name => Name_First))),
771                          Attribute_Name => Name_Address)),
772
773                    Right_Opnd =>
774                      Unchecked_Convert_To (RTE (RE_Integer_Address),
775                        Make_Attribute_Reference (Loc,
776                          Prefix =>
777                            Make_Indexed_Component (Loc,
778                              Prefix =>
779                                Duplicate_Subexpr_Move_Checks (Rarray, True),
780                              Expressions => New_List (
781                                Make_Attribute_Reference (Loc,
782                                  Prefix =>
783                                    New_Reference_To
784                                      (R_Index_Typ, Loc),
785                                  Attribute_Name => Name_First))),
786                          Attribute_Name => Name_Address)));
787
788             --  For the bit packed and Java VM cases we use the bounds.
789             --  That's OK, because we don't have to worry about parameters,
790             --  since they cannot cause overlap. Perhaps we should worry
791             --  about weird slice conversions ???
792
793             else
794                --  Copy the bounds and reset the Analyzed flag, because the
795                --  bounds of the index type itself may be universal, and must
796                --  must be reaanalyzed to acquire the proper type for Gigi.
797
798                Cleft_Lo  := New_Copy_Tree (Left_Lo);
799                Cright_Lo := New_Copy_Tree (Right_Lo);
800                Set_Analyzed (Cleft_Lo, False);
801                Set_Analyzed (Cright_Lo, False);
802
803                Condition :=
804                  Make_Op_Le (Loc,
805                    Left_Opnd  => Cleft_Lo,
806                    Right_Opnd => Cright_Lo);
807             end if;
808
809             Rewrite (N,
810               Make_Implicit_If_Statement (N,
811                 Condition => Condition,
812
813                 Then_Statements => New_List (
814                   Expand_Assign_Array_Loop
815                    (N, Larray, Rarray, L_Type, R_Type, Ndim,
816                     Rev => False)),
817
818                 Else_Statements => New_List (
819                   Expand_Assign_Array_Loop
820                    (N, Larray, Rarray, L_Type, R_Type, Ndim,
821                     Rev => True))));
822          end if;
823
824          Analyze (N, Suppress => All_Checks);
825       end;
826
827    exception
828       when RE_Not_Available =>
829          return;
830    end Expand_Assign_Array;
831
832    ------------------------------
833    -- Expand_Assign_Array_Loop --
834    ------------------------------
835
836    --  The following is an example of the loop generated for the case of
837    --  a two-dimensional array:
838
839    --    declare
840    --       R2b : Tm1X1 := 1;
841    --    begin
842    --       for L1b in 1 .. 100 loop
843    --          declare
844    --             R4b : Tm1X2 := 1;
845    --          begin
846    --             for L3b in 1 .. 100 loop
847    --                vm1 (L1b, L3b) := vm2 (R2b, R4b);
848    --                R4b := Tm1X2'succ(R4b);
849    --             end loop;
850    --          end;
851    --          R2b := Tm1X1'succ(R2b);
852    --       end loop;
853    --    end;
854
855    --  Here Rev is False, and Tm1Xn are the subscript types for the right
856    --  hand side. The declarations of R2b and R4b are inserted before the
857    --  original assignment statement.
858
859    function Expand_Assign_Array_Loop
860      (N      : Node_Id;
861       Larray : Entity_Id;
862       Rarray : Entity_Id;
863       L_Type : Entity_Id;
864       R_Type : Entity_Id;
865       Ndim   : Pos;
866       Rev    : Boolean) return Node_Id
867    is
868       Loc  : constant Source_Ptr := Sloc (N);
869
870       Lnn : array (1 .. Ndim) of Entity_Id;
871       Rnn : array (1 .. Ndim) of Entity_Id;
872       --  Entities used as subscripts on left and right sides
873
874       L_Index_Type : array (1 .. Ndim) of Entity_Id;
875       R_Index_Type : array (1 .. Ndim) of Entity_Id;
876       --  Left and right index types
877
878       Assign : Node_Id;
879
880       F_Or_L : Name_Id;
881       S_Or_P : Name_Id;
882
883    begin
884       if Rev then
885          F_Or_L := Name_Last;
886          S_Or_P := Name_Pred;
887       else
888          F_Or_L := Name_First;
889          S_Or_P := Name_Succ;
890       end if;
891
892       --  Setup index types and subscript entities
893
894       declare
895          L_Index : Node_Id;
896          R_Index : Node_Id;
897
898       begin
899          L_Index := First_Index (L_Type);
900          R_Index := First_Index (R_Type);
901
902          for J in 1 .. Ndim loop
903             Lnn (J) :=
904               Make_Defining_Identifier (Loc,
905                 Chars => New_Internal_Name ('L'));
906
907             Rnn (J) :=
908               Make_Defining_Identifier (Loc,
909                 Chars => New_Internal_Name ('R'));
910
911             L_Index_Type (J) := Etype (L_Index);
912             R_Index_Type (J) := Etype (R_Index);
913
914             Next_Index (L_Index);
915             Next_Index (R_Index);
916          end loop;
917       end;
918
919       --  Now construct the assignment statement
920
921       declare
922          ExprL : constant List_Id := New_List;
923          ExprR : constant List_Id := New_List;
924
925       begin
926          for J in 1 .. Ndim loop
927             Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
928             Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
929          end loop;
930
931          Assign :=
932            Make_Assignment_Statement (Loc,
933              Name =>
934                Make_Indexed_Component (Loc,
935                  Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
936                  Expressions => ExprL),
937              Expression =>
938                Make_Indexed_Component (Loc,
939                  Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
940                  Expressions => ExprR));
941
942          --  Propagate the No_Ctrl_Actions flag to individual assignments
943
944          Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
945       end;
946
947       --  Now construct the loop from the inside out, with the last subscript
948       --  varying most rapidly. Note that Assign is first the raw assignment
949       --  statement, and then subsequently the loop that wraps it up.
950
951       for J in reverse 1 .. Ndim loop
952          Assign :=
953            Make_Block_Statement (Loc,
954              Declarations => New_List (
955               Make_Object_Declaration (Loc,
956                 Defining_Identifier => Rnn (J),
957                 Object_Definition =>
958                   New_Occurrence_Of (R_Index_Type (J), Loc),
959                 Expression =>
960                   Make_Attribute_Reference (Loc,
961                     Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
962                     Attribute_Name => F_Or_L))),
963
964            Handled_Statement_Sequence =>
965              Make_Handled_Sequence_Of_Statements (Loc,
966                Statements => New_List (
967                  Make_Implicit_Loop_Statement (N,
968                    Iteration_Scheme =>
969                      Make_Iteration_Scheme (Loc,
970                        Loop_Parameter_Specification =>
971                          Make_Loop_Parameter_Specification (Loc,
972                            Defining_Identifier => Lnn (J),
973                            Reverse_Present => Rev,
974                            Discrete_Subtype_Definition =>
975                              New_Reference_To (L_Index_Type (J), Loc))),
976
977                    Statements => New_List (
978                      Assign,
979
980                      Make_Assignment_Statement (Loc,
981                        Name => New_Occurrence_Of (Rnn (J), Loc),
982                        Expression =>
983                          Make_Attribute_Reference (Loc,
984                            Prefix =>
985                              New_Occurrence_Of (R_Index_Type (J), Loc),
986                            Attribute_Name => S_Or_P,
987                            Expressions => New_List (
988                              New_Occurrence_Of (Rnn (J), Loc)))))))));
989       end loop;
990
991       return Assign;
992    end Expand_Assign_Array_Loop;
993
994    --------------------------
995    -- Expand_Assign_Record --
996    --------------------------
997
998    --  The only processing required is in the change of representation
999    --  case, where we must expand the assignment to a series of field
1000    --  by field assignments.
1001
1002    procedure Expand_Assign_Record (N : Node_Id) is
1003       Lhs : constant Node_Id := Name (N);
1004       Rhs : Node_Id          := Expression (N);
1005
1006    begin
1007       --  If change of representation, then extract the real right hand
1008       --  side from the type conversion, and proceed with component-wise
1009       --  assignment, since the two types are not the same as far as the
1010       --  back end is concerned.
1011
1012       if Change_Of_Representation (N) then
1013          Rhs := Expression (Rhs);
1014
1015       --  If this may be a case of a large bit aligned component, then
1016       --  proceed with component-wise assignment, to avoid possible
1017       --  clobbering of other components sharing bits in the first or
1018       --  last byte of the component to be assigned.
1019
1020       elsif Possible_Bit_Aligned_Component (Lhs)
1021               or
1022             Possible_Bit_Aligned_Component (Rhs)
1023       then
1024          null;
1025
1026       --  If neither condition met, then nothing special to do, the back end
1027       --  can handle assignment of the entire component as a single entity.
1028
1029       else
1030          return;
1031       end if;
1032
1033       --  At this stage we know that we must do a component wise assignment
1034
1035       declare
1036          Loc   : constant Source_Ptr := Sloc (N);
1037          R_Typ : constant Entity_Id  := Base_Type (Etype (Rhs));
1038          L_Typ : constant Entity_Id  := Base_Type (Etype (Lhs));
1039          Decl  : constant Node_Id    := Declaration_Node (R_Typ);
1040          RDef  : Node_Id;
1041          F     : Entity_Id;
1042
1043          function Find_Component
1044            (Typ  : Entity_Id;
1045             Comp : Entity_Id) return Entity_Id;
1046          --  Find the component with the given name in the underlying record
1047          --  declaration for Typ. We need to use the actual entity because
1048          --  the type may be private and resolution by identifier alone would
1049          --  fail.
1050
1051          function Make_Component_List_Assign (CL : Node_Id) return List_Id;
1052          --  Returns a sequence of statements to assign the components that
1053          --  are referenced in the given component list.
1054
1055          function Make_Field_Assign (C : Entity_Id) return Node_Id;
1056          --  Given C, the entity for a discriminant or component, build
1057          --  an assignment for the corresponding field values.
1058
1059          function Make_Field_Assigns (CI : List_Id) return List_Id;
1060          --  Given CI, a component items list, construct series of statements
1061          --  for fieldwise assignment of the corresponding components.
1062
1063          --------------------
1064          -- Find_Component --
1065          --------------------
1066
1067          function Find_Component
1068            (Typ  : Entity_Id;
1069             Comp : Entity_Id) return Entity_Id
1070          is
1071             Utyp : constant Entity_Id := Underlying_Type (Typ);
1072             C    : Entity_Id;
1073
1074          begin
1075             C := First_Entity (Utyp);
1076
1077             while Present (C) loop
1078                if Chars (C) = Chars (Comp) then
1079                   return C;
1080                end if;
1081                Next_Entity (C);
1082             end loop;
1083
1084             raise Program_Error;
1085          end Find_Component;
1086
1087          --------------------------------
1088          -- Make_Component_List_Assign --
1089          --------------------------------
1090
1091          function Make_Component_List_Assign (CL : Node_Id) return List_Id is
1092             CI : constant List_Id := Component_Items (CL);
1093             VP : constant Node_Id := Variant_Part (CL);
1094
1095             Result : List_Id;
1096             Alts   : List_Id;
1097             V      : Node_Id;
1098             DC     : Node_Id;
1099             DCH    : List_Id;
1100
1101          begin
1102             Result := Make_Field_Assigns (CI);
1103
1104             if Present (VP) then
1105
1106                V := First_Non_Pragma (Variants (VP));
1107                Alts := New_List;
1108                while Present (V) loop
1109
1110                   DCH := New_List;
1111                   DC := First (Discrete_Choices (V));
1112                   while Present (DC) loop
1113                      Append_To (DCH, New_Copy_Tree (DC));
1114                      Next (DC);
1115                   end loop;
1116
1117                   Append_To (Alts,
1118                     Make_Case_Statement_Alternative (Loc,
1119                       Discrete_Choices => DCH,
1120                       Statements =>
1121                         Make_Component_List_Assign (Component_List (V))));
1122                   Next_Non_Pragma (V);
1123                end loop;
1124
1125                Append_To (Result,
1126                  Make_Case_Statement (Loc,
1127                    Expression =>
1128                      Make_Selected_Component (Loc,
1129                        Prefix => Duplicate_Subexpr (Rhs),
1130                        Selector_Name =>
1131                          Make_Identifier (Loc, Chars (Name (VP)))),
1132                    Alternatives => Alts));
1133
1134             end if;
1135
1136             return Result;
1137          end Make_Component_List_Assign;
1138
1139          -----------------------
1140          -- Make_Field_Assign --
1141          -----------------------
1142
1143          function Make_Field_Assign (C : Entity_Id) return Node_Id is
1144             A : Node_Id;
1145
1146          begin
1147             A :=
1148               Make_Assignment_Statement (Loc,
1149                 Name =>
1150                   Make_Selected_Component (Loc,
1151                     Prefix => Duplicate_Subexpr (Lhs),
1152                     Selector_Name =>
1153                       New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1154                 Expression =>
1155                   Make_Selected_Component (Loc,
1156                     Prefix => Duplicate_Subexpr (Rhs),
1157                     Selector_Name => New_Occurrence_Of (C, Loc)));
1158
1159             --  Set Assignment_OK, so discriminants can be assigned
1160
1161             Set_Assignment_OK (Name (A), True);
1162             return A;
1163          end Make_Field_Assign;
1164
1165          ------------------------
1166          -- Make_Field_Assigns --
1167          ------------------------
1168
1169          function Make_Field_Assigns (CI : List_Id) return List_Id is
1170             Item   : Node_Id;
1171             Result : List_Id;
1172
1173          begin
1174             Item := First (CI);
1175             Result := New_List;
1176
1177             while Present (Item) loop
1178                if Nkind (Item) = N_Component_Declaration then
1179                   Append_To
1180                     (Result, Make_Field_Assign (Defining_Identifier (Item)));
1181                end if;
1182
1183                Next (Item);
1184             end loop;
1185
1186             return Result;
1187          end Make_Field_Assigns;
1188
1189       --  Start of processing for Expand_Assign_Record
1190
1191       begin
1192          --  Note that we use the base types for this processing. This results
1193          --  in some extra work in the constrained case, but the change of
1194          --  representation case is so unusual that it is not worth the effort.
1195
1196          --  First copy the discriminants. This is done unconditionally. It
1197          --  is required in the unconstrained left side case, and also in the
1198          --  case where this assignment was constructed during the expansion
1199          --  of a type conversion (since initialization of discriminants is
1200          --  suppressed in this case). It is unnecessary but harmless in
1201          --  other cases.
1202
1203          if Has_Discriminants (L_Typ) then
1204             F := First_Discriminant (R_Typ);
1205             while Present (F) loop
1206                Insert_Action (N, Make_Field_Assign (F));
1207                Next_Discriminant (F);
1208             end loop;
1209          end if;
1210
1211          --  We know the underlying type is a record, but its current view
1212          --  may be private. We must retrieve the usable record declaration.
1213
1214          if Nkind (Decl) = N_Private_Type_Declaration
1215            and then Present (Full_View (R_Typ))
1216          then
1217             RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1218          else
1219             RDef := Type_Definition (Decl);
1220          end if;
1221
1222          if Nkind (RDef) = N_Record_Definition
1223            and then Present (Component_List (RDef))
1224          then
1225             Insert_Actions
1226               (N, Make_Component_List_Assign (Component_List (RDef)));
1227
1228             Rewrite (N, Make_Null_Statement (Loc));
1229          end if;
1230
1231       end;
1232    end Expand_Assign_Record;
1233
1234    -----------------------------------
1235    -- Expand_N_Assignment_Statement --
1236    -----------------------------------
1237
1238    --  For array types, deal with slice assignments and setting the flags
1239    --  to indicate if it can be statically determined which direction the
1240    --  move should go in. Also deal with generating range/length checks.
1241
1242    procedure Expand_N_Assignment_Statement (N : Node_Id) is
1243       Loc  : constant Source_Ptr := Sloc (N);
1244       Lhs  : constant Node_Id    := Name (N);
1245       Rhs  : constant Node_Id    := Expression (N);
1246       Typ  : constant Entity_Id  := Underlying_Type (Etype (Lhs));
1247       Exp  : Node_Id;
1248
1249    begin
1250       --  First deal with generation of range check if required. For now
1251       --  we do this only for discrete types.
1252
1253       if Do_Range_Check (Rhs)
1254         and then Is_Discrete_Type (Typ)
1255       then
1256          Set_Do_Range_Check (Rhs, False);
1257          Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1258       end if;
1259
1260       --  Check for a special case where a high level transformation is
1261       --  required. If we have either of:
1262
1263       --    P.field := rhs;
1264       --    P (sub) := rhs;
1265
1266       --  where P is a reference to a bit packed array, then we have to unwind
1267       --  the assignment. The exact meaning of being a reference to a bit
1268       --  packed array is as follows:
1269
1270       --    An indexed component whose prefix is a bit packed array is a
1271       --     reference to a bit packed array.
1272
1273       --    An indexed component or selected component whose prefix is a
1274       --     reference to a bit packed array is itself a reference ot a
1275       --     bit packed array.
1276
1277       --  The required transformation is
1278
1279       --     Tnn : prefix_type := P;
1280       --     Tnn.field := rhs;
1281       --     P := Tnn;
1282
1283       --  or
1284
1285       --     Tnn : prefix_type := P;
1286       --     Tnn (subscr) := rhs;
1287       --     P := Tnn;
1288
1289       --  Since P is going to be evaluated more than once, any subscripts
1290       --  in P must have their evaluation forced.
1291
1292       if (Nkind (Lhs) = N_Indexed_Component
1293            or else
1294           Nkind (Lhs) = N_Selected_Component)
1295         and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1296       then
1297          declare
1298             BPAR_Expr : constant Node_Id   := Relocate_Node (Prefix (Lhs));
1299             BPAR_Typ  : constant Entity_Id := Etype (BPAR_Expr);
1300             Tnn       : constant Entity_Id :=
1301                           Make_Defining_Identifier (Loc,
1302                             Chars => New_Internal_Name ('T'));
1303
1304          begin
1305             --  Insert the post assignment first, because we want to copy
1306             --  the BPAR_Expr tree before it gets analyzed in the context
1307             --  of the pre assignment. Note that we do not analyze the
1308             --  post assignment yet (we cannot till we have completed the
1309             --  analysis of the pre assignment). As usual, the analysis
1310             --  of this post assignment will happen on its own when we
1311             --  "run into" it after finishing the current assignment.
1312
1313             Insert_After (N,
1314               Make_Assignment_Statement (Loc,
1315                 Name       => New_Copy_Tree (BPAR_Expr),
1316                 Expression => New_Occurrence_Of (Tnn, Loc)));
1317
1318             --  At this stage BPAR_Expr is a reference to a bit packed
1319             --  array where the reference was not expanded in the original
1320             --  tree, since it was on the left side of an assignment. But
1321             --  in the pre-assignment statement (the object definition),
1322             --  BPAR_Expr will end up on the right hand side, and must be
1323             --  reexpanded. To achieve this, we reset the analyzed flag
1324             --  of all selected and indexed components down to the actual
1325             --  indexed component for the packed array.
1326
1327             Exp := BPAR_Expr;
1328             loop
1329                Set_Analyzed (Exp, False);
1330
1331                if Nkind (Exp) = N_Selected_Component
1332                     or else
1333                   Nkind (Exp) = N_Indexed_Component
1334                then
1335                   Exp := Prefix (Exp);
1336                else
1337                   exit;
1338                end if;
1339             end loop;
1340
1341             --  Now we can insert and analyze the pre-assignment.
1342
1343             --  If the right-hand side requires a transient scope, it has
1344             --  already been placed on the stack. However, the declaration is
1345             --  inserted in the tree outside of this scope, and must reflect
1346             --  the proper scope for its variable. This awkward bit is forced
1347             --  by the stricter scope discipline imposed by GCC 2.97.
1348
1349             declare
1350                Uses_Transient_Scope : constant Boolean :=
1351                   Scope_Is_Transient and then N = Node_To_Be_Wrapped;
1352
1353             begin
1354                if Uses_Transient_Scope then
1355                   New_Scope (Scope (Current_Scope));
1356                end if;
1357
1358                Insert_Before_And_Analyze (N,
1359                  Make_Object_Declaration (Loc,
1360                    Defining_Identifier => Tnn,
1361                    Object_Definition   => New_Occurrence_Of (BPAR_Typ, Loc),
1362                    Expression          => BPAR_Expr));
1363
1364                if Uses_Transient_Scope then
1365                   Pop_Scope;
1366                end if;
1367             end;
1368
1369             --  Now fix up the original assignment and continue processing
1370
1371             Rewrite (Prefix (Lhs),
1372               New_Occurrence_Of (Tnn, Loc));
1373
1374             --  We do not need to reanalyze that assignment, and we do not need
1375             --  to worry about references to the temporary, but we do need to
1376             --  make sure that the temporary is not marked as a true constant
1377             --  since we now have a generate assignment to it!
1378
1379             Set_Is_True_Constant (Tnn, False);
1380          end;
1381       end if;
1382
1383       --  When we have the appropriate type of aggregate in the
1384       --  expression (it has been determined during analysis of the
1385       --  aggregate by setting the delay flag), let's perform in place
1386       --  assignment and thus avoid creating a temporay.
1387
1388       if Is_Delayed_Aggregate (Rhs) then
1389          Convert_Aggr_In_Assignment (N);
1390          Rewrite (N, Make_Null_Statement (Loc));
1391          Analyze (N);
1392          return;
1393       end if;
1394
1395       --  Apply discriminant check if required. If Lhs is an access type
1396       --  to a designated type with discriminants, we must always check.
1397
1398       if Has_Discriminants (Etype (Lhs)) then
1399
1400          --  Skip discriminant check if change of representation. Will be
1401          --  done when the change of representation is expanded out.
1402
1403          if not Change_Of_Representation (N) then
1404             Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1405          end if;
1406
1407       --  If the type is private without discriminants, and the full type
1408       --  has discriminants (necessarily with defaults) a check may still be
1409       --  necessary if the Lhs is aliased. The private determinants must be
1410       --  visible to build the discriminant constraints.
1411
1412       --  Only an explicit dereference that comes from source indicates
1413       --  aliasing. Access to formals of protected operations and entries
1414       --  create dereferences but are not semantic aliasings.
1415
1416       elsif Is_Private_Type (Etype (Lhs))
1417         and then  Has_Discriminants (Typ)
1418         and then Nkind (Lhs) = N_Explicit_Dereference
1419         and then Comes_From_Source (Lhs)
1420       then
1421          declare
1422             Lt : constant Entity_Id := Etype (Lhs);
1423          begin
1424             Set_Etype (Lhs, Typ);
1425             Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1426             Apply_Discriminant_Check (Rhs, Typ, Lhs);
1427             Set_Etype (Lhs, Lt);
1428          end;
1429
1430          --  If the Lhs has a private type with unknown discriminants, it
1431          --  may have a full view with discriminants, but those are nameable
1432          --  only in the underlying type, so convert the Rhs to it before
1433          --  potential checking.
1434
1435       elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1436         and then Has_Discriminants (Typ)
1437       then
1438          Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1439          Apply_Discriminant_Check (Rhs, Typ, Lhs);
1440
1441       --  In the access type case, we need the same discriminant check,
1442       --  and also range checks if we have an access to constrained array.
1443
1444       elsif Is_Access_Type (Etype (Lhs))
1445         and then Is_Constrained (Designated_Type (Etype (Lhs)))
1446       then
1447          if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1448
1449             --  Skip discriminant check if change of representation. Will be
1450             --  done when the change of representation is expanded out.
1451
1452             if not Change_Of_Representation (N) then
1453                Apply_Discriminant_Check (Rhs, Etype (Lhs));
1454             end if;
1455
1456          elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1457             Apply_Range_Check (Rhs, Etype (Lhs));
1458
1459             if Is_Constrained (Etype (Lhs)) then
1460                Apply_Length_Check (Rhs, Etype (Lhs));
1461             end if;
1462
1463             if Nkind (Rhs) = N_Allocator then
1464                declare
1465                   Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1466                   C_Es       : Check_Result;
1467
1468                begin
1469                   C_Es :=
1470                     Range_Check
1471                       (Lhs,
1472                        Target_Typ,
1473                        Etype (Designated_Type (Etype (Lhs))));
1474
1475                   Insert_Range_Checks
1476                     (C_Es,
1477                      N,
1478                      Target_Typ,
1479                      Sloc (Lhs),
1480                      Lhs);
1481                end;
1482             end if;
1483          end if;
1484
1485       --  Apply range check for access type case
1486
1487       elsif Is_Access_Type (Etype (Lhs))
1488         and then Nkind (Rhs) = N_Allocator
1489         and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1490       then
1491          Analyze_And_Resolve (Expression (Rhs));
1492          Apply_Range_Check
1493            (Expression (Rhs), Designated_Type (Etype (Lhs)));
1494       end if;
1495
1496       --  If we are assigning an access type and the left side is an
1497       --  entity, then make sure that Is_Known_Non_Null properly
1498       --  reflects the state of the entity after the assignment
1499
1500       if Is_Access_Type (Typ)
1501         and then Is_Entity_Name (Lhs)
1502         and then Known_Non_Null (Rhs)
1503         and then Safe_To_Capture_Value (N, Entity (Lhs))
1504       then
1505          Set_Is_Known_Non_Null (Entity (Lhs), Known_Non_Null (Rhs));
1506       end if;
1507
1508       --  Case of assignment to a bit packed array element
1509
1510       if Nkind (Lhs) = N_Indexed_Component
1511         and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1512       then
1513          Expand_Bit_Packed_Element_Set (N);
1514          return;
1515
1516       --  Case of tagged type assignment
1517
1518       elsif Is_Tagged_Type (Typ)
1519         or else (Controlled_Type (Typ) and then not Is_Array_Type (Typ))
1520       then
1521          Tagged_Case : declare
1522             L                   : List_Id := No_List;
1523             Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
1524
1525          begin
1526             --  In the controlled case, we need to make sure that function
1527             --  calls are evaluated before finalizing the target. In all
1528             --  cases, it makes the expansion easier if the side-effects
1529             --  are removed first.
1530
1531             Remove_Side_Effects (Lhs);
1532             Remove_Side_Effects (Rhs);
1533
1534             --  Avoid recursion in the mechanism
1535
1536             Set_Analyzed (N);
1537
1538             --  If dispatching assignment, we need to dispatch to _assign
1539
1540             if Is_Class_Wide_Type (Typ)
1541
1542             --  If the type is tagged, we may as well use the predefined
1543             --  primitive assignment. This avoids inlining a lot of code
1544             --  and in the class-wide case, the assignment is replaced by
1545             --  a dispatch call to _assign. Note that this cannot be done
1546             --  when discriminant checks are locally suppressed (as in
1547             --  extension aggregate expansions) because otherwise the
1548             --  discriminant check will be performed within the _assign
1549             --  call.
1550
1551             or else (Is_Tagged_Type (Typ)
1552               and then Chars (Current_Scope) /= Name_uAssign
1553               and then Expand_Ctrl_Actions
1554               and then not Discriminant_Checks_Suppressed (Empty))
1555             then
1556                --  Fetch the primitive op _assign and proper type to call
1557                --  it. Because of possible conflits between private and
1558                --  full view the proper type is fetched directly from the
1559                --  operation profile.
1560
1561                declare
1562                   Op    : constant Entity_Id :=
1563                             Find_Prim_Op (Typ, Name_uAssign);
1564                   F_Typ : Entity_Id := Etype (First_Formal (Op));
1565
1566                begin
1567                   --  If the assignment is dispatching, make sure to use the
1568                   --  ??? where is rest of this comment ???
1569
1570                   if Is_Class_Wide_Type (Typ) then
1571                      F_Typ := Class_Wide_Type (F_Typ);
1572                   end if;
1573
1574                   L := New_List (
1575                     Make_Procedure_Call_Statement (Loc,
1576                       Name => New_Reference_To (Op, Loc),
1577                       Parameter_Associations => New_List (
1578                         Unchecked_Convert_To (F_Typ, Duplicate_Subexpr (Lhs)),
1579                         Unchecked_Convert_To (F_Typ,
1580                           Duplicate_Subexpr (Rhs)))));
1581                end;
1582
1583             else
1584                L := Make_Tag_Ctrl_Assignment (N);
1585
1586                --  We can't afford to have destructive Finalization Actions
1587                --  in the Self assignment case, so if the target and the
1588                --  source are not obviously different, code is generated to
1589                --  avoid the self assignment case
1590                --
1591                --    if lhs'address /= rhs'address then
1592                --       <code for controlled and/or tagged assignment>
1593                --    end if;
1594
1595                if not Statically_Different (Lhs, Rhs)
1596                  and then Expand_Ctrl_Actions
1597                then
1598                   L := New_List (
1599                     Make_Implicit_If_Statement (N,
1600                       Condition =>
1601                         Make_Op_Ne (Loc,
1602                           Left_Opnd =>
1603                             Make_Attribute_Reference (Loc,
1604                               Prefix         => Duplicate_Subexpr (Lhs),
1605                               Attribute_Name => Name_Address),
1606
1607                            Right_Opnd =>
1608                             Make_Attribute_Reference (Loc,
1609                               Prefix         => Duplicate_Subexpr (Rhs),
1610                               Attribute_Name => Name_Address)),
1611
1612                       Then_Statements => L));
1613                end if;
1614
1615                --  We need to set up an exception handler for implementing
1616                --  7.6.1 (18). The remaining adjustments are tackled by the
1617                --  implementation of adjust for record_controllers (see
1618                --  s-finimp.adb)
1619
1620                --  This is skipped if we have no finalization
1621
1622                if Expand_Ctrl_Actions
1623                  and then not Restrictions (No_Finalization)
1624                then
1625                   L := New_List (
1626                     Make_Block_Statement (Loc,
1627                       Handled_Statement_Sequence =>
1628                         Make_Handled_Sequence_Of_Statements (Loc,
1629                           Statements => L,
1630                           Exception_Handlers => New_List (
1631                             Make_Exception_Handler (Loc,
1632                               Exception_Choices =>
1633                                 New_List (Make_Others_Choice (Loc)),
1634                               Statements        => New_List (
1635                                 Make_Raise_Program_Error (Loc,
1636                                   Reason =>
1637                                     PE_Finalize_Raised_Exception)
1638                               ))))));
1639                end if;
1640             end if;
1641
1642             Rewrite (N,
1643               Make_Block_Statement (Loc,
1644                 Handled_Statement_Sequence =>
1645                   Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
1646
1647             --  If no restrictions on aborts, protect the whole assignement
1648             --  for controlled objects as per 9.8(11)
1649
1650             if Controlled_Type (Typ)
1651               and then Expand_Ctrl_Actions
1652               and then Abort_Allowed
1653             then
1654                declare
1655                   Blk : constant Entity_Id :=
1656                     New_Internal_Entity (
1657                       E_Block, Current_Scope, Sloc (N), 'B');
1658
1659                begin
1660                   Set_Scope (Blk, Current_Scope);
1661                   Set_Etype (Blk, Standard_Void_Type);
1662                   Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
1663
1664                   Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
1665                   Set_At_End_Proc (Handled_Statement_Sequence (N),
1666                     New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
1667                   Expand_At_End_Handler
1668                     (Handled_Statement_Sequence (N), Blk);
1669                end;
1670             end if;
1671
1672             Analyze (N);
1673             return;
1674          end Tagged_Case;
1675
1676       --  Array types
1677
1678       elsif Is_Array_Type (Typ) then
1679          declare
1680             Actual_Rhs : Node_Id := Rhs;
1681
1682          begin
1683             while Nkind (Actual_Rhs) = N_Type_Conversion
1684               or else
1685                   Nkind (Actual_Rhs) = N_Qualified_Expression
1686             loop
1687                Actual_Rhs := Expression (Actual_Rhs);
1688             end loop;
1689
1690             Expand_Assign_Array (N, Actual_Rhs);
1691             return;
1692          end;
1693
1694       --  Record types
1695
1696       elsif Is_Record_Type (Typ) then
1697          Expand_Assign_Record (N);
1698          return;
1699
1700       --  Scalar types. This is where we perform the processing related
1701       --  to the requirements of (RM 13.9.1(9-11)) concerning the handling
1702       --  of invalid scalar values.
1703
1704       elsif Is_Scalar_Type (Typ) then
1705
1706          --  Case where right side is known valid
1707
1708          if Expr_Known_Valid (Rhs) then
1709
1710             --  Here the right side is valid, so it is fine. The case to
1711             --  deal with is when the left side is a local variable reference
1712             --  whose value is not currently known to be valid. If this is
1713             --  the case, and the assignment appears in an unconditional
1714             --  context, then we can mark the left side as now being valid.
1715
1716             if Is_Local_Variable_Reference (Lhs)
1717               and then not Is_Known_Valid (Entity (Lhs))
1718               and then In_Unconditional_Context (N)
1719             then
1720                Set_Is_Known_Valid (Entity (Lhs), True);
1721             end if;
1722
1723          --  Case where right side may be invalid in the sense of the RM
1724          --  reference above. The RM does not require that we check for
1725          --  the validity on an assignment, but it does require that the
1726          --  assignment of an invalid value not cause erroneous behavior.
1727
1728          --  The general approach in GNAT is to use the Is_Known_Valid flag
1729          --  to avoid the need for validity checking on assignments. However
1730          --  in some cases, we have to do validity checking in order to make
1731          --  sure that the setting of this flag is correct.
1732
1733          else
1734             --  Validate right side if we are validating copies
1735
1736             if Validity_Checks_On
1737                and then Validity_Check_Copies
1738             then
1739                Ensure_Valid (Rhs);
1740
1741                --  We can propagate this to the left side where appropriate
1742
1743                if Is_Local_Variable_Reference (Lhs)
1744                  and then not Is_Known_Valid (Entity (Lhs))
1745                  and then In_Unconditional_Context (N)
1746                then
1747                   Set_Is_Known_Valid (Entity (Lhs), True);
1748                end if;
1749
1750             --  Otherwise check to see what should be done
1751
1752             --  If left side is a local variable, then we just set its
1753             --  flag to indicate that its value may no longer be valid,
1754             --  since we are copying a potentially invalid value.
1755
1756             elsif Is_Local_Variable_Reference (Lhs) then
1757                Set_Is_Known_Valid (Entity (Lhs), False);
1758
1759             --  Check for case of a nonlocal variable on the left side
1760             --  which is currently known to be valid. In this case, we
1761             --  simply ensure that the right side is valid. We only play
1762             --  the game of copying validity status for local variables,
1763             --  since we are doing this statically, not by tracing the
1764             --  full flow graph.
1765
1766             elsif Is_Entity_Name (Lhs)
1767               and then Is_Known_Valid (Entity (Lhs))
1768             then
1769                --  Note that the Ensure_Valid call is ignored if the
1770                --  Validity_Checking mode is set to none so we do not
1771                --  need to worry about that case here.
1772
1773                Ensure_Valid (Rhs);
1774
1775             --  In all other cases, we can safely copy an invalid value
1776             --  without worrying about the status of the left side. Since
1777             --  it is not a variable reference it will not be considered
1778             --  as being known to be valid in any case.
1779
1780             else
1781                null;
1782             end if;
1783          end if;
1784       end if;
1785
1786       --  Defend against invalid subscripts on left side if we are in
1787       --  standard validity checking mode. No need to do this if we
1788       --  are checking all subscripts.
1789
1790       if Validity_Checks_On
1791         and then Validity_Check_Default
1792         and then not Validity_Check_Subscripts
1793       then
1794          Check_Valid_Lvalue_Subscripts (Lhs);
1795       end if;
1796
1797    exception
1798       when RE_Not_Available =>
1799          return;
1800    end Expand_N_Assignment_Statement;
1801
1802    ------------------------------
1803    -- Expand_N_Block_Statement --
1804    ------------------------------
1805
1806    --  Encode entity names defined in block statement
1807
1808    procedure Expand_N_Block_Statement (N : Node_Id) is
1809    begin
1810       Qualify_Entity_Names (N);
1811    end Expand_N_Block_Statement;
1812
1813    -----------------------------
1814    -- Expand_N_Case_Statement --
1815    -----------------------------
1816
1817    procedure Expand_N_Case_Statement (N : Node_Id) is
1818       Loc    : constant Source_Ptr := Sloc (N);
1819       Expr   : constant Node_Id    := Expression (N);
1820       Alt    : Node_Id;
1821       Len    : Nat;
1822       Cond   : Node_Id;
1823       Choice : Node_Id;
1824       Chlist : List_Id;
1825
1826    begin
1827       --  Check for the situation where we know at compile time which
1828       --  branch will be taken
1829
1830       if Compile_Time_Known_Value (Expr) then
1831          Alt := Find_Static_Alternative (N);
1832
1833          --  Move the statements from this alternative after the case
1834          --  statement. They are already analyzed, so will be skipped
1835          --  by the analyzer.
1836
1837          Insert_List_After (N, Statements (Alt));
1838
1839          --  That leaves the case statement as a shell. The alternative
1840          --  that will be executed is reset to a null list. So now we can
1841          --  kill the entire case statement.
1842
1843          Kill_Dead_Code (Expression (N));
1844          Kill_Dead_Code (Alternatives (N));
1845          Rewrite (N, Make_Null_Statement (Loc));
1846          return;
1847       end if;
1848
1849       --  Here if the choice is not determined at compile time
1850
1851       declare
1852          Last_Alt : constant Node_Id := Last (Alternatives (N));
1853
1854          Others_Present : Boolean;
1855          Others_Node    : Node_Id;
1856
1857          Then_Stms : List_Id;
1858          Else_Stms : List_Id;
1859
1860       begin
1861          if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
1862             Others_Present := True;
1863             Others_Node    := Last_Alt;
1864          else
1865             Others_Present := False;
1866          end if;
1867
1868          --  First step is to worry about possible invalid argument. The RM
1869          --  requires (RM 5.4(13)) that if the result is invalid (e.g. it is
1870          --  outside the base range), then Constraint_Error must be raised.
1871
1872          --  Case of validity check required (validity checks are on, the
1873          --  expression is not known to be valid, and the case statement
1874          --  comes from source -- no need to validity check internally
1875          --  generated case statements).
1876
1877          if Validity_Check_Default then
1878             Ensure_Valid (Expr);
1879          end if;
1880
1881          --  If there is only a single alternative, just replace it with
1882          --  the sequence of statements since obviously that is what is
1883          --  going to be executed in all cases.
1884
1885          Len := List_Length (Alternatives (N));
1886
1887          if Len = 1 then
1888             --  We still need to evaluate the expression if it has any
1889             --  side effects.
1890
1891             Remove_Side_Effects (Expression (N));
1892
1893             Insert_List_After (N, Statements (First (Alternatives (N))));
1894
1895             --  That leaves the case statement as a shell. The alternative
1896             --  that will be executed is reset to a null list. So now we can
1897             --  kill the entire case statement.
1898
1899             Kill_Dead_Code (Expression (N));
1900             Rewrite (N, Make_Null_Statement (Loc));
1901             return;
1902          end if;
1903
1904          --  An optimization. If there are only two alternatives, and only
1905          --  a single choice, then rewrite the whole case statement as an
1906          --  if statement, since this can result in susbequent optimizations.
1907          --  This helps not only with case statements in the source of a
1908          --  simple form, but also with generated code (discriminant check
1909          --  functions in particular)
1910
1911          if Len = 2 then
1912             Chlist := Discrete_Choices (First (Alternatives (N)));
1913
1914             if List_Length (Chlist) = 1 then
1915                Choice := First (Chlist);
1916
1917                Then_Stms := Statements (First (Alternatives (N)));
1918                Else_Stms := Statements (Last  (Alternatives (N)));
1919
1920                --  For TRUE, generate "expression", not expression = true
1921
1922                if Nkind (Choice) = N_Identifier
1923                  and then Entity (Choice) = Standard_True
1924                then
1925                   Cond := Expression (N);
1926
1927                --  For FALSE, generate "expression" and switch then/else
1928
1929                elsif Nkind (Choice) = N_Identifier
1930                  and then Entity (Choice) = Standard_False
1931                then
1932                   Cond := Expression (N);
1933                   Else_Stms := Statements (First (Alternatives (N)));
1934                   Then_Stms := Statements (Last  (Alternatives (N)));
1935
1936                --  For a range, generate "expression in range"
1937
1938                elsif Nkind (Choice) = N_Range
1939                  or else (Nkind (Choice) = N_Attribute_Reference
1940                            and then Attribute_Name (Choice) = Name_Range)
1941                  or else (Is_Entity_Name (Choice)
1942                            and then Is_Type (Entity (Choice)))
1943                  or else Nkind (Choice) = N_Subtype_Indication
1944                then
1945                   Cond :=
1946                     Make_In (Loc,
1947                       Left_Opnd  => Expression (N),
1948                       Right_Opnd => Relocate_Node (Choice));
1949
1950                --  For any other subexpression "expression = value"
1951
1952                else
1953                   Cond :=
1954                     Make_Op_Eq (Loc,
1955                       Left_Opnd  => Expression (N),
1956                       Right_Opnd => Relocate_Node (Choice));
1957                end if;
1958
1959                --  Now rewrite the case as an IF
1960
1961                Rewrite (N,
1962                  Make_If_Statement (Loc,
1963                    Condition => Cond,
1964                    Then_Statements => Then_Stms,
1965                    Else_Statements => Else_Stms));
1966                Analyze (N);
1967                return;
1968             end if;
1969          end if;
1970
1971          --  If the last alternative is not an Others choice, replace it
1972          --  with an N_Others_Choice. Note that we do not bother to call
1973          --  Analyze on the modified case statement, since it's only effect
1974          --  would be to compute the contents of the Others_Discrete_Choices
1975          --  which is not needed by the back end anyway.
1976
1977          --  The reason we do this is that the back end always needs some
1978          --  default for a switch, so if we have not supplied one in the
1979          --  processing above for validity checking, then we need to
1980          --  supply one here.
1981
1982          if not Others_Present then
1983             Others_Node := Make_Others_Choice (Sloc (Last_Alt));
1984             Set_Others_Discrete_Choices
1985               (Others_Node, Discrete_Choices (Last_Alt));
1986             Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
1987          end if;
1988       end;
1989    end Expand_N_Case_Statement;
1990
1991    -----------------------------
1992    -- Expand_N_Exit_Statement --
1993    -----------------------------
1994
1995    --  The only processing required is to deal with a possible C/Fortran
1996    --  boolean value used as the condition for the exit statement.
1997
1998    procedure Expand_N_Exit_Statement (N : Node_Id) is
1999    begin
2000       Adjust_Condition (Condition (N));
2001    end Expand_N_Exit_Statement;
2002
2003    -----------------------------
2004    -- Expand_N_Goto_Statement --
2005    -----------------------------
2006
2007    --  Add poll before goto if polling active
2008
2009    procedure Expand_N_Goto_Statement (N : Node_Id) is
2010    begin
2011       Generate_Poll_Call (N);
2012    end Expand_N_Goto_Statement;
2013
2014    ---------------------------
2015    -- Expand_N_If_Statement --
2016    ---------------------------
2017
2018    --  First we deal with the case of C and Fortran convention boolean
2019    --  values, with zero/non-zero semantics.
2020
2021    --  Second, we deal with the obvious rewriting for the cases where the
2022    --  condition of the IF is known at compile time to be True or False.
2023
2024    --  Third, we remove elsif parts which have non-empty Condition_Actions
2025    --  and rewrite as independent if statements. For example:
2026
2027    --     if x then xs
2028    --     elsif y then ys
2029    --     ...
2030    --     end if;
2031
2032    --  becomes
2033    --
2034    --     if x then xs
2035    --     else
2036    --        <<condition actions of y>>
2037    --        if y then ys
2038    --        ...
2039    --        end if;
2040    --     end if;
2041
2042    --  This rewriting is needed if at least one elsif part has a non-empty
2043    --  Condition_Actions list. We also do the same processing if there is
2044    --  a constant condition in an elsif part (in conjunction with the first
2045    --  processing step mentioned above, for the recursive call made to deal
2046    --  with the created inner if, this deals with properly optimizing the
2047    --  cases of constant elsif conditions).
2048
2049    procedure Expand_N_If_Statement (N : Node_Id) is
2050       Loc    : constant Source_Ptr := Sloc (N);
2051       Hed    : Node_Id;
2052       E      : Node_Id;
2053       New_If : Node_Id;
2054
2055    begin
2056       Adjust_Condition (Condition (N));
2057
2058       --  The following loop deals with constant conditions for the IF. We
2059       --  need a loop because as we eliminate False conditions, we grab the
2060       --  first elsif condition and use it as the primary condition.
2061
2062       while Compile_Time_Known_Value (Condition (N)) loop
2063
2064          --  If condition is True, we can simply rewrite the if statement
2065          --  now by replacing it by the series of then statements.
2066
2067          if Is_True (Expr_Value (Condition (N))) then
2068
2069             --  All the else parts can be killed
2070
2071             Kill_Dead_Code (Elsif_Parts (N));
2072             Kill_Dead_Code (Else_Statements (N));
2073
2074             Hed := Remove_Head (Then_Statements (N));
2075             Insert_List_After (N, Then_Statements (N));
2076             Rewrite (N, Hed);
2077             return;
2078
2079          --  If condition is False, then we can delete the condition and
2080          --  the Then statements
2081
2082          else
2083             --  We do not delete the condition if constant condition
2084             --  warnings are enabled, since otherwise we end up deleting
2085             --  the desired warning. Of course the backend will get rid
2086             --  of this True/False test anyway, so nothing is lost here.
2087
2088             if not Constant_Condition_Warnings then
2089                Kill_Dead_Code (Condition (N));
2090             end if;
2091
2092             Kill_Dead_Code (Then_Statements (N));
2093
2094             --  If there are no elsif statements, then we simply replace
2095             --  the entire if statement by the sequence of else statements.
2096
2097             if No (Elsif_Parts (N)) then
2098
2099                if No (Else_Statements (N))
2100                  or else Is_Empty_List (Else_Statements (N))
2101                then
2102                   Rewrite (N,
2103                     Make_Null_Statement (Sloc (N)));
2104
2105                else
2106                   Hed := Remove_Head (Else_Statements (N));
2107                   Insert_List_After (N, Else_Statements (N));
2108                   Rewrite (N, Hed);
2109                end if;
2110
2111                return;
2112
2113             --  If there are elsif statements, the first of them becomes
2114             --  the if/then section of the rebuilt if statement This is
2115             --  the case where we loop to reprocess this copied condition.
2116
2117             else
2118                Hed := Remove_Head (Elsif_Parts (N));
2119                Insert_Actions      (N, Condition_Actions (Hed));
2120                Set_Condition       (N, Condition (Hed));
2121                Set_Then_Statements (N, Then_Statements (Hed));
2122
2123                if Is_Empty_List (Elsif_Parts (N)) then
2124                   Set_Elsif_Parts (N, No_List);
2125                end if;
2126             end if;
2127          end if;
2128       end loop;
2129
2130       --  Loop through elsif parts, dealing with constant conditions and
2131       --  possible expression actions that are present.
2132
2133       if Present (Elsif_Parts (N)) then
2134          E := First (Elsif_Parts (N));
2135          while Present (E) loop
2136             Adjust_Condition (Condition (E));
2137
2138             --  If there are condition actions, then we rewrite the if
2139             --  statement as indicated above. We also do the same rewrite
2140             --  if the condition is True or False. The further processing
2141             --  of this constant condition is then done by the recursive
2142             --  call to expand the newly created if statement
2143
2144             if Present (Condition_Actions (E))
2145               or else Compile_Time_Known_Value (Condition (E))
2146             then
2147                --  Note this is not an implicit if statement, since it is
2148                --  part of an explicit if statement in the source (or of an
2149                --  implicit if statement that has already been tested).
2150
2151                New_If :=
2152                  Make_If_Statement (Sloc (E),
2153                    Condition       => Condition (E),
2154                    Then_Statements => Then_Statements (E),
2155                    Elsif_Parts     => No_List,
2156                    Else_Statements => Else_Statements (N));
2157
2158                --  Elsif parts for new if come from remaining elsif's of parent
2159
2160                while Present (Next (E)) loop
2161                   if No (Elsif_Parts (New_If)) then
2162                      Set_Elsif_Parts (New_If, New_List);
2163                   end if;
2164
2165                   Append (Remove_Next (E), Elsif_Parts (New_If));
2166                end loop;
2167
2168                Set_Else_Statements (N, New_List (New_If));
2169
2170                if Present (Condition_Actions (E)) then
2171                   Insert_List_Before (New_If, Condition_Actions (E));
2172                end if;
2173
2174                Remove (E);
2175
2176                if Is_Empty_List (Elsif_Parts (N)) then
2177                   Set_Elsif_Parts (N, No_List);
2178                end if;
2179
2180                Analyze (New_If);
2181                return;
2182
2183             --  No special processing for that elsif part, move to next
2184
2185             else
2186                Next (E);
2187             end if;
2188          end loop;
2189       end if;
2190
2191       --  Some more optimizations applicable if we still have an IF statement
2192
2193       if Nkind (N) /= N_If_Statement then
2194          return;
2195       end if;
2196
2197       --  Another optimization, special cases that can be simplified
2198
2199       --     if expression then
2200       --        return true;
2201       --     else
2202       --        return false;
2203       --     end if;
2204
2205       --  can be changed to:
2206
2207       --     return expression;
2208
2209       --  and
2210
2211       --     if expression then
2212       --        return false;
2213       --     else
2214       --        return true;
2215       --     end if;
2216
2217       --  can be changed to:
2218
2219       --     return not (expression);
2220
2221       if Nkind (N) = N_If_Statement
2222          and then No (Elsif_Parts (N))
2223          and then Present (Else_Statements (N))
2224          and then List_Length (Then_Statements (N)) = 1
2225          and then List_Length (Else_Statements (N)) = 1
2226       then
2227          declare
2228             Then_Stm : constant Node_Id := First (Then_Statements (N));
2229             Else_Stm : constant Node_Id := First (Else_Statements (N));
2230
2231          begin
2232             if Nkind (Then_Stm) = N_Return_Statement
2233                  and then
2234                Nkind (Else_Stm) = N_Return_Statement
2235             then
2236                declare
2237                   Then_Expr : constant Node_Id := Expression (Then_Stm);
2238                   Else_Expr : constant Node_Id := Expression (Else_Stm);
2239
2240                begin
2241                   if Nkind (Then_Expr) = N_Identifier
2242                        and then
2243                      Nkind (Else_Expr) = N_Identifier
2244                   then
2245                      if Entity (Then_Expr) = Standard_True
2246                        and then Entity (Else_Expr) = Standard_False
2247                      then
2248                         Rewrite (N,
2249                           Make_Return_Statement (Loc,
2250                             Expression => Relocate_Node (Condition (N))));
2251                         Analyze (N);
2252                         return;
2253
2254                      elsif Entity (Then_Expr) = Standard_False
2255                        and then Entity (Else_Expr) = Standard_True
2256                      then
2257                         Rewrite (N,
2258                           Make_Return_Statement (Loc,
2259                             Expression =>
2260                               Make_Op_Not (Loc,
2261                                 Right_Opnd => Relocate_Node (Condition (N)))));
2262                         Analyze (N);
2263                         return;
2264                      end if;
2265                   end if;
2266                end;
2267             end if;
2268          end;
2269       end if;
2270    end Expand_N_If_Statement;
2271
2272    -----------------------------
2273    -- Expand_N_Loop_Statement --
2274    -----------------------------
2275
2276    --  1. Deal with while condition for C/Fortran boolean
2277    --  2. Deal with loops with a non-standard enumeration type range
2278    --  3. Deal with while loops where Condition_Actions is set
2279    --  4. Insert polling call if required
2280
2281    procedure Expand_N_Loop_Statement (N : Node_Id) is
2282       Loc  : constant Source_Ptr := Sloc (N);
2283       Isc  : constant Node_Id    := Iteration_Scheme (N);
2284
2285    begin
2286       if Present (Isc) then
2287          Adjust_Condition (Condition (Isc));
2288       end if;
2289
2290       if Is_Non_Empty_List (Statements (N)) then
2291          Generate_Poll_Call (First (Statements (N)));
2292       end if;
2293
2294       if No (Isc) then
2295          return;
2296       end if;
2297
2298       --  Handle the case where we have a for loop with the range type being
2299       --  an enumeration type with non-standard representation. In this case
2300       --  we expand:
2301
2302       --    for x in [reverse] a .. b loop
2303       --       ...
2304       --    end loop;
2305
2306       --  to
2307
2308       --    for xP in [reverse] integer
2309       --                          range etype'Pos (a) .. etype'Pos (b) loop
2310       --       declare
2311       --          x : constant etype := Pos_To_Rep (xP);
2312       --       begin
2313       --          ...
2314       --       end;
2315       --    end loop;
2316
2317       if Present (Loop_Parameter_Specification (Isc)) then
2318          declare
2319             LPS     : constant Node_Id   := Loop_Parameter_Specification (Isc);
2320             Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
2321             Ltype   : constant Entity_Id := Etype (Loop_Id);
2322             Btype   : constant Entity_Id := Base_Type (Ltype);
2323             Expr    : Node_Id;
2324             New_Id  : Entity_Id;
2325
2326          begin
2327             if not Is_Enumeration_Type (Btype)
2328               or else No (Enum_Pos_To_Rep (Btype))
2329             then
2330                return;
2331             end if;
2332
2333             New_Id :=
2334               Make_Defining_Identifier (Loc,
2335                 Chars => New_External_Name (Chars (Loop_Id), 'P'));
2336
2337             --  If the type has a contiguous representation, successive
2338             --  values can be generated as offsets from the first literal.
2339
2340             if Has_Contiguous_Rep (Btype) then
2341                Expr :=
2342                   Unchecked_Convert_To (Btype,
2343                     Make_Op_Add (Loc,
2344                       Left_Opnd =>
2345                          Make_Integer_Literal (Loc,
2346                            Enumeration_Rep (First_Literal (Btype))),
2347                       Right_Opnd => New_Reference_To (New_Id, Loc)));
2348             else
2349                --  Use the constructed array Enum_Pos_To_Rep.
2350
2351                Expr :=
2352                  Make_Indexed_Component (Loc,
2353                    Prefix => New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
2354                    Expressions => New_List (New_Reference_To (New_Id, Loc)));
2355             end if;
2356
2357             Rewrite (N,
2358               Make_Loop_Statement (Loc,
2359                 Identifier => Identifier (N),
2360
2361                 Iteration_Scheme =>
2362                   Make_Iteration_Scheme (Loc,
2363                     Loop_Parameter_Specification =>
2364                       Make_Loop_Parameter_Specification (Loc,
2365                         Defining_Identifier => New_Id,
2366                         Reverse_Present => Reverse_Present (LPS),
2367
2368                         Discrete_Subtype_Definition =>
2369                           Make_Subtype_Indication (Loc,
2370
2371                             Subtype_Mark =>
2372                               New_Reference_To (Standard_Natural, Loc),
2373
2374                             Constraint =>
2375                               Make_Range_Constraint (Loc,
2376                                 Range_Expression =>
2377                                   Make_Range (Loc,
2378
2379                                     Low_Bound =>
2380                                       Make_Attribute_Reference (Loc,
2381                                         Prefix =>
2382                                           New_Reference_To (Btype, Loc),
2383
2384                                         Attribute_Name => Name_Pos,
2385
2386                                         Expressions => New_List (
2387                                           Relocate_Node
2388                                             (Type_Low_Bound (Ltype)))),
2389
2390                                     High_Bound =>
2391                                       Make_Attribute_Reference (Loc,
2392                                         Prefix =>
2393                                           New_Reference_To (Btype, Loc),
2394
2395                                         Attribute_Name => Name_Pos,
2396
2397                                         Expressions => New_List (
2398                                           Relocate_Node
2399                                             (Type_High_Bound (Ltype))))))))),
2400
2401                 Statements => New_List (
2402                   Make_Block_Statement (Loc,
2403                     Declarations => New_List (
2404                       Make_Object_Declaration (Loc,
2405                         Defining_Identifier => Loop_Id,
2406                         Constant_Present    => True,
2407                         Object_Definition   => New_Reference_To (Ltype, Loc),
2408                         Expression          => Expr)),
2409
2410                     Handled_Statement_Sequence =>
2411                       Make_Handled_Sequence_Of_Statements (Loc,
2412                         Statements => Statements (N)))),
2413
2414                 End_Label => End_Label (N)));
2415             Analyze (N);
2416          end;
2417
2418       --  Second case, if we have a while loop with Condition_Actions set,
2419       --  then we change it into a plain loop:
2420
2421       --    while C loop
2422       --       ...
2423       --    end loop;
2424
2425       --  changed to:
2426
2427       --    loop
2428       --       <<condition actions>>
2429       --       exit when not C;
2430       --       ...
2431       --    end loop
2432
2433       elsif Present (Isc)
2434         and then Present (Condition_Actions (Isc))
2435       then
2436          declare
2437             ES : Node_Id;
2438
2439          begin
2440             ES :=
2441               Make_Exit_Statement (Sloc (Condition (Isc)),
2442                 Condition =>
2443                   Make_Op_Not (Sloc (Condition (Isc)),
2444                     Right_Opnd => Condition (Isc)));
2445
2446             Prepend (ES, Statements (N));
2447             Insert_List_Before (ES, Condition_Actions (Isc));
2448
2449             --  This is not an implicit loop, since it is generated in
2450             --  response to the loop statement being processed. If this
2451             --  is itself implicit, the restriction has already been
2452             --  checked. If not, it is an explicit loop.
2453
2454             Rewrite (N,
2455               Make_Loop_Statement (Sloc (N),
2456                 Identifier => Identifier (N),
2457                 Statements => Statements (N),
2458                 End_Label  => End_Label  (N)));
2459
2460             Analyze (N);
2461          end;
2462       end if;
2463    end Expand_N_Loop_Statement;
2464
2465    -------------------------------
2466    -- Expand_N_Return_Statement --
2467    -------------------------------
2468
2469    procedure Expand_N_Return_Statement (N : Node_Id) is
2470       Loc         : constant Source_Ptr := Sloc (N);
2471       Exp         : constant Node_Id    := Expression (N);
2472       Exptyp      : Entity_Id;
2473       T           : Entity_Id;
2474       Utyp        : Entity_Id;
2475       Scope_Id    : Entity_Id;
2476       Kind        : Entity_Kind;
2477       Call        : Node_Id;
2478       Acc_Stat    : Node_Id;
2479       Goto_Stat   : Node_Id;
2480       Lab_Node    : Node_Id;
2481       Cur_Idx     : Nat;
2482       Return_Type : Entity_Id;
2483       Result_Exp  : Node_Id;
2484       Result_Id   : Entity_Id;
2485       Result_Obj  : Node_Id;
2486
2487    begin
2488       --  Case where returned expression is present
2489
2490       if Present (Exp) then
2491
2492          --  Always normalize C/Fortran boolean result. This is not always
2493          --  necessary, but it seems a good idea to minimize the passing
2494          --  around of non-normalized values, and in any case this handles
2495          --  the processing of barrier functions for protected types, which
2496          --  turn the condition into a return statement.
2497
2498          Exptyp := Etype (Exp);
2499
2500          if Is_Boolean_Type (Exptyp)
2501            and then Nonzero_Is_True (Exptyp)
2502          then
2503             Adjust_Condition (Exp);
2504             Adjust_Result_Type (Exp, Exptyp);
2505          end if;
2506
2507          --  Do validity check if enabled for returns
2508
2509          if Validity_Checks_On
2510            and then Validity_Check_Returns
2511          then
2512             Ensure_Valid (Exp);
2513          end if;
2514       end if;
2515
2516       --  Find relevant enclosing scope from which return is returning
2517
2518       Cur_Idx := Scope_Stack.Last;
2519       loop
2520          Scope_Id := Scope_Stack.Table (Cur_Idx).Entity;
2521
2522          if Ekind (Scope_Id) /= E_Block
2523            and then Ekind (Scope_Id) /= E_Loop
2524          then
2525             exit;
2526
2527          else
2528             Cur_Idx := Cur_Idx - 1;
2529             pragma Assert (Cur_Idx >= 0);
2530          end if;
2531       end loop;
2532
2533       if No (Exp) then
2534          Kind := Ekind (Scope_Id);
2535
2536          --  If it is a return from procedures do no extra steps.
2537
2538          if Kind = E_Procedure or else Kind = E_Generic_Procedure then
2539             return;
2540          end if;
2541
2542          pragma Assert (Is_Entry (Scope_Id));
2543
2544          --  Look at the enclosing block to see whether the return is from
2545          --  an accept statement or an entry body.
2546
2547          for J in reverse 0 .. Cur_Idx loop
2548             Scope_Id := Scope_Stack.Table (J).Entity;
2549             exit when Is_Concurrent_Type (Scope_Id);
2550          end loop;
2551
2552          --  If it is a return from accept statement it should be expanded
2553          --  as a call to RTS Complete_Rendezvous and a goto to the end of
2554          --  the accept body.
2555
2556          --  (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
2557          --   Expand_N_Accept_Alternative in exp_ch9.adb)
2558
2559          if Is_Task_Type (Scope_Id) then
2560
2561             Call := (Make_Procedure_Call_Statement (Loc,
2562                       Name => New_Reference_To
2563                         (RTE (RE_Complete_Rendezvous), Loc)));
2564             Insert_Before (N, Call);
2565             --  why not insert actions here???
2566             Analyze (Call);
2567
2568             Acc_Stat := Parent (N);
2569             while Nkind (Acc_Stat) /= N_Accept_Statement loop
2570                Acc_Stat := Parent (Acc_Stat);
2571             end loop;
2572
2573             Lab_Node := Last (Statements
2574               (Handled_Statement_Sequence (Acc_Stat)));
2575
2576             Goto_Stat := Make_Goto_Statement (Loc,
2577               Name => New_Occurrence_Of
2578                 (Entity (Identifier (Lab_Node)), Loc));
2579
2580             Set_Analyzed (Goto_Stat);
2581
2582             Rewrite (N, Goto_Stat);
2583             Analyze (N);
2584
2585          --  If it is a return from an entry body, put a Complete_Entry_Body
2586          --  call in front of the return.
2587
2588          elsif Is_Protected_Type (Scope_Id) then
2589
2590             Call :=
2591               Make_Procedure_Call_Statement (Loc,
2592                 Name => New_Reference_To
2593                   (RTE (RE_Complete_Entry_Body), Loc),
2594                 Parameter_Associations => New_List
2595                   (Make_Attribute_Reference (Loc,
2596                     Prefix =>
2597                       New_Reference_To
2598                         (Object_Ref
2599                            (Corresponding_Body (Parent (Scope_Id))),
2600                         Loc),
2601                     Attribute_Name => Name_Unchecked_Access)));
2602
2603             Insert_Before (N, Call);
2604             Analyze (Call);
2605
2606          end if;
2607
2608          return;
2609       end if;
2610
2611       T := Etype (Exp);
2612       Return_Type := Etype (Scope_Id);
2613       Utyp := Underlying_Type (Return_Type);
2614
2615       --  Check the result expression of a scalar function against
2616       --  the subtype of the function by inserting a conversion.
2617       --  This conversion must eventually be performed for other
2618       --  classes of types, but for now it's only done for scalars.
2619       --  ???
2620
2621       if Is_Scalar_Type (T) then
2622          Rewrite (Exp, Convert_To (Return_Type, Exp));
2623          Analyze (Exp);
2624       end if;
2625
2626       --  Implement the rules of 6.5(8-10), which require a tag check in
2627       --  the case of a limited tagged return type, and tag reassignment
2628       --  for nonlimited tagged results. These actions are needed when
2629       --  the return type is a specific tagged type and the result
2630       --  expression is a conversion or a formal parameter, because in
2631       --  that case the tag of the expression might differ from the tag
2632       --  of the specific result type.
2633
2634       if Is_Tagged_Type (Utyp)
2635         and then not Is_Class_Wide_Type (Utyp)
2636         and then (Nkind (Exp) = N_Type_Conversion
2637                     or else Nkind (Exp) = N_Unchecked_Type_Conversion
2638                     or else (Is_Entity_Name (Exp)
2639                                and then Ekind (Entity (Exp)) in Formal_Kind))
2640       then
2641          --  When the return type is limited, perform a check that the
2642          --  tag of the result is the same as the tag of the return type.
2643
2644          if Is_Limited_Type (Return_Type) then
2645             Insert_Action (Exp,
2646               Make_Raise_Constraint_Error (Loc,
2647                 Condition =>
2648                   Make_Op_Ne (Loc,
2649                     Left_Opnd =>
2650                       Make_Selected_Component (Loc,
2651                         Prefix => Duplicate_Subexpr (Exp),
2652                         Selector_Name =>
2653                           New_Reference_To (Tag_Component (Utyp), Loc)),
2654                     Right_Opnd =>
2655                       Unchecked_Convert_To (RTE (RE_Tag),
2656                         New_Reference_To
2657                           (Access_Disp_Table (Base_Type (Utyp)), Loc))),
2658                 Reason => CE_Tag_Check_Failed));
2659
2660          --  If the result type is a specific nonlimited tagged type,
2661          --  then we have to ensure that the tag of the result is that
2662          --  of the result type. This is handled by making a copy of the
2663          --  expression in the case where it might have a different tag,
2664          --  namely when the expression is a conversion or a formal
2665          --  parameter. We create a new object of the result type and
2666          --  initialize it from the expression, which will implicitly
2667          --  force the tag to be set appropriately.
2668
2669          else
2670             Result_Id :=
2671               Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
2672             Result_Exp := New_Reference_To (Result_Id, Loc);
2673
2674             Result_Obj :=
2675               Make_Object_Declaration (Loc,
2676                 Defining_Identifier => Result_Id,
2677                 Object_Definition   => New_Reference_To (Return_Type, Loc),
2678                 Constant_Present    => True,
2679                 Expression          => Relocate_Node (Exp));
2680
2681             Set_Assignment_OK (Result_Obj);
2682             Insert_Action (Exp, Result_Obj);
2683
2684             Rewrite (Exp, Result_Exp);
2685             Analyze_And_Resolve (Exp, Return_Type);
2686          end if;
2687       end if;
2688
2689       --  Deal with returning variable length objects and controlled types
2690
2691       --  Nothing to do if we are returning by reference, or this is not
2692       --  a type that requires special processing (indicated by the fact
2693       --  that it requires a cleanup scope for the secondary stack case)
2694
2695       if Is_Return_By_Reference_Type (T)
2696         or else not Requires_Transient_Scope (Return_Type)
2697       then
2698          null;
2699
2700       --  Case of secondary stack not used
2701
2702       elsif Function_Returns_With_DSP (Scope_Id) then
2703
2704          --  Here what we need to do is to always return by reference, since
2705          --  we will return with the stack pointer depressed. We may need to
2706          --  do a copy to a local temporary before doing this return.
2707
2708          No_Secondary_Stack_Case : declare
2709             Local_Copy_Required : Boolean := False;
2710             --  Set to True if a local copy is required
2711
2712             Copy_Ent : Entity_Id;
2713             --  Used for the target entity if a copy is required
2714
2715             Decl : Node_Id;
2716             --  Declaration used to create copy if needed
2717
2718             procedure Test_Copy_Required (Expr : Node_Id);
2719             --  Determines if Expr represents a return value for which a
2720             --  copy is required. More specifically, a copy is not required
2721             --  if Expr represents an object or component of an object that
2722             --  is either in the local subprogram frame, or is constant.
2723             --  If a copy is required, then Local_Copy_Required is set True.
2724
2725             ------------------------
2726             -- Test_Copy_Required --
2727             ------------------------
2728
2729             procedure Test_Copy_Required (Expr : Node_Id) is
2730                Ent : Entity_Id;
2731
2732             begin
2733                --  If component, test prefix (object containing component)
2734
2735                if Nkind (Expr) = N_Indexed_Component
2736                     or else
2737                   Nkind (Expr) = N_Selected_Component
2738                then
2739                   Test_Copy_Required (Prefix (Expr));
2740                   return;
2741
2742                --  See if we have an entity name
2743
2744                elsif Is_Entity_Name (Expr) then
2745                   Ent := Entity (Expr);
2746
2747                   --  Constant entity is always OK, no copy required
2748
2749                   if Ekind (Ent) = E_Constant then
2750                      return;
2751
2752                   --  No copy required for local variable
2753
2754                   elsif Ekind (Ent) = E_Variable
2755                     and then Scope (Ent) = Current_Subprogram
2756                   then
2757                      return;
2758                   end if;
2759                end if;
2760
2761                --  All other cases require a copy
2762
2763                Local_Copy_Required := True;
2764             end Test_Copy_Required;
2765
2766          --  Start of processing for No_Secondary_Stack_Case
2767
2768          begin
2769             --  No copy needed if result is from a function call.
2770             --  In this case the result is already being returned by
2771             --  reference with the stack pointer depressed.
2772
2773             --  To make up for a gcc 2.8.1 deficiency (???), we perform
2774             --  the copy for array types if the constrained status of the
2775             --  target type is different from that of the expression.
2776
2777             if Requires_Transient_Scope (T)
2778               and then
2779                 (not Is_Array_Type (T)
2780                    or else Is_Constrained (T) = Is_Constrained (Return_Type)
2781                    or else Controlled_Type (T))
2782               and then Nkind (Exp) = N_Function_Call
2783             then
2784                Set_By_Ref (N);
2785
2786             --  We always need a local copy for a controlled type, since
2787             --  we are required to finalize the local value before return.
2788             --  The copy will automatically include the required finalize.
2789             --  Moreover, gigi cannot make this copy, since we need special
2790             --  processing to ensure proper behavior for finalization.
2791
2792             --  Note: the reason we are returning with a depressed stack
2793             --  pointer in the controlled case (even if the type involved
2794             --  is constrained) is that we must make a local copy to deal
2795             --  properly with the requirement that the local result be
2796             --  finalized.
2797
2798             elsif Controlled_Type (Utyp) then
2799                Copy_Ent :=
2800                  Make_Defining_Identifier (Loc,
2801                    Chars => New_Internal_Name ('R'));
2802
2803                --  Build declaration to do the copy, and insert it, setting
2804                --  Assignment_OK, because we may be copying a limited type.
2805                --  In addition we set the special flag to inhibit finalize
2806                --  attachment if this is a controlled type (since this attach
2807                --  must be done by the caller, otherwise if we attach it here
2808                --  we will finalize the returned result prematurely).
2809
2810                Decl :=
2811                  Make_Object_Declaration (Loc,
2812                    Defining_Identifier => Copy_Ent,
2813                    Object_Definition   => New_Occurrence_Of (Return_Type, Loc),
2814                    Expression          => Relocate_Node (Exp));
2815
2816                Set_Assignment_OK (Decl);
2817                Set_Delay_Finalize_Attach (Decl);
2818                Insert_Action (N, Decl);
2819
2820                --  Now the actual return uses the copied value
2821
2822                Rewrite (Exp, New_Occurrence_Of (Copy_Ent, Loc));
2823                Analyze_And_Resolve (Exp, Return_Type);
2824
2825                --  Since we have made the copy, gigi does not have to, so
2826                --  we set the By_Ref flag to prevent another copy being made.
2827
2828                Set_By_Ref (N);
2829
2830             --  Non-controlled cases
2831
2832             else
2833                Test_Copy_Required (Exp);
2834
2835                --  If a local copy is required, then gigi will make the
2836                --  copy, otherwise, we can return the result directly,
2837                --  so set By_Ref to suppress the gigi copy.
2838
2839                if not Local_Copy_Required then
2840                   Set_By_Ref (N);
2841                end if;
2842             end if;
2843          end No_Secondary_Stack_Case;
2844
2845       --  Here if secondary stack is used
2846
2847       else
2848          --  Make sure that no surrounding block will reclaim the
2849          --  secondary-stack on which we are going to put the result.
2850          --  Not only may this introduce secondary stack leaks but worse,
2851          --  if the reclamation is done too early, then the result we are
2852          --  returning may get clobbered. See example in 7417-003.
2853
2854          declare
2855             S : Entity_Id := Current_Scope;
2856
2857          begin
2858             while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
2859                Set_Sec_Stack_Needed_For_Return (S, True);
2860                S := Enclosing_Dynamic_Scope (S);
2861             end loop;
2862          end;
2863
2864          --  Optimize the case where the result is a function call. In this
2865          --  case either the result is already on the secondary stack, or is
2866          --  already being returned with the stack pointer depressed and no
2867          --  further processing is required except to set the By_Ref flag to
2868          --  ensure that gigi does not attempt an extra unnecessary copy.
2869          --  (actually not just unnecessary but harmfully wrong in the case
2870          --  of a controlled type, where gigi does not know how to do a copy).
2871          --  To make up for a gcc 2.8.1 deficiency (???), we perform
2872          --  the copy for array types if the constrained status of the
2873          --  target type is different from that of the expression.
2874
2875          if Requires_Transient_Scope (T)
2876            and then
2877               (not Is_Array_Type (T)
2878                 or else Is_Constrained (T) = Is_Constrained (Return_Type)
2879                 or else Controlled_Type (T))
2880            and then Nkind (Exp) = N_Function_Call
2881          then
2882             Set_By_Ref (N);
2883
2884          --  For controlled types, do the allocation on the sec-stack
2885          --  manually in order to call adjust at the right time
2886          --    type Anon1 is access Return_Type;
2887          --    for Anon1'Storage_pool use ss_pool;
2888          --    Anon2 : anon1 := new Return_Type'(expr);
2889          --    return Anon2.all;
2890
2891          elsif Controlled_Type (Utyp) then
2892             declare
2893                Loc        : constant Source_Ptr := Sloc (N);
2894                Temp       : constant Entity_Id :=
2895                               Make_Defining_Identifier (Loc,
2896                                 Chars => New_Internal_Name ('R'));
2897                Acc_Typ    : constant Entity_Id :=
2898                               Make_Defining_Identifier (Loc,
2899                                 Chars => New_Internal_Name ('A'));
2900                Alloc_Node : Node_Id;
2901
2902             begin
2903                Set_Ekind (Acc_Typ, E_Access_Type);
2904
2905                Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
2906
2907                Alloc_Node :=
2908                  Make_Allocator (Loc,
2909                    Expression =>
2910                      Make_Qualified_Expression (Loc,
2911                        Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
2912                        Expression => Relocate_Node (Exp)));
2913
2914                Insert_List_Before_And_Analyze (N, New_List (
2915                  Make_Full_Type_Declaration (Loc,
2916                    Defining_Identifier => Acc_Typ,
2917                    Type_Definition     =>
2918                      Make_Access_To_Object_Definition (Loc,
2919                        Subtype_Indication =>
2920                           New_Reference_To (Return_Type, Loc))),
2921
2922                  Make_Object_Declaration (Loc,
2923                    Defining_Identifier => Temp,
2924                    Object_Definition   => New_Reference_To (Acc_Typ, Loc),
2925                    Expression          => Alloc_Node)));
2926
2927                Rewrite (Exp,
2928                  Make_Explicit_Dereference (Loc,
2929                  Prefix => New_Reference_To (Temp, Loc)));
2930
2931                Analyze_And_Resolve (Exp, Return_Type);
2932             end;
2933
2934          --  Otherwise use the gigi mechanism to allocate result on the
2935          --  secondary stack.
2936
2937          else
2938             Set_Storage_Pool      (N, RTE (RE_SS_Pool));
2939
2940             --  If we are generating code for the Java VM do not use
2941             --  SS_Allocate since everything is heap-allocated anyway.
2942
2943             if not Java_VM then
2944                Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
2945             end if;
2946          end if;
2947       end if;
2948
2949    exception
2950       when RE_Not_Available =>
2951          return;
2952    end Expand_N_Return_Statement;
2953
2954    ------------------------------
2955    -- Make_Tag_Ctrl_Assignment --
2956    ------------------------------
2957
2958    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
2959       Loc : constant Source_Ptr := Sloc (N);
2960       L   : constant Node_Id    := Name (N);
2961       T   : constant Entity_Id  := Underlying_Type (Etype (L));
2962
2963       Ctrl_Act : constant Boolean := Controlled_Type (T)
2964                                        and then not No_Ctrl_Actions (N);
2965
2966       Save_Tag : constant Boolean := Is_Tagged_Type (T)
2967                                        and then not No_Ctrl_Actions (N)
2968                                        and then not Java_VM;
2969       --  Tags are not saved and restored when Java_VM because JVM tags
2970       --  are represented implicitly in objects.
2971
2972       Res       : List_Id;
2973       Tag_Tmp   : Entity_Id;
2974       Prev_Tmp  : Entity_Id;
2975       Next_Tmp  : Entity_Id;
2976       Ctrl_Ref  : Node_Id;
2977       Ctrl_Ref2 : Node_Id   := Empty;
2978       Prev_Tmp2 : Entity_Id := Empty;  -- prevent warning
2979       Next_Tmp2 : Entity_Id := Empty;  -- prevent warning
2980
2981    begin
2982       Res := New_List;
2983
2984       --  Finalize the target of the assignment when controlled.
2985       --  We have two exceptions here:
2986
2987       --   1. If we are in an init proc since it is an initialization
2988       --      more than an assignment
2989
2990       --   2. If the left-hand side is a temporary that was not initialized
2991       --      (or the parent part of a temporary since it is the case in
2992       --      extension aggregates). Such a temporary does not come from
2993       --      source. We must examine the original node for the prefix, because
2994       --      it may be a component of an entry formal, in which case it has
2995       --      been rewritten and does not appear to come from source either.
2996
2997       --  Case of init proc
2998
2999       if not Ctrl_Act then
3000          null;
3001
3002       --  The left hand side is an uninitialized  temporary
3003
3004       elsif Nkind (L) = N_Type_Conversion
3005         and then Is_Entity_Name (Expression (L))
3006         and then No_Initialization (Parent (Entity (Expression (L))))
3007       then
3008          null;
3009       else
3010          Append_List_To (Res,
3011            Make_Final_Call (
3012              Ref         => Duplicate_Subexpr_No_Checks (L),
3013              Typ         => Etype (L),
3014              With_Detach => New_Reference_To (Standard_False, Loc)));
3015       end if;
3016
3017       Next_Tmp := Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
3018
3019       --  Save the Tag in a local variable Tag_Tmp
3020
3021       if Save_Tag then
3022          Tag_Tmp :=
3023            Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
3024
3025          Append_To (Res,
3026            Make_Object_Declaration (Loc,
3027              Defining_Identifier => Tag_Tmp,
3028              Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
3029              Expression =>
3030                Make_Selected_Component (Loc,
3031                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3032                  Selector_Name => New_Reference_To (Tag_Component (T), Loc))));
3033
3034       --  Otherwise Tag_Tmp not used
3035
3036       else
3037          Tag_Tmp := Empty;
3038       end if;
3039
3040       --  Save the Finalization Pointers in local variables Prev_Tmp and
3041       --  Next_Tmp. For objects with Has_Controlled_Component set, these
3042       --  pointers are in the Record_Controller and if it is also
3043       --  Is_Controlled, we need to save the object pointers as well.
3044
3045       if Ctrl_Act then
3046          Ctrl_Ref := Duplicate_Subexpr_No_Checks (L);
3047
3048          if Has_Controlled_Component (T) then
3049             Ctrl_Ref :=
3050               Make_Selected_Component (Loc,
3051                 Prefix => Ctrl_Ref,
3052                 Selector_Name =>
3053                   New_Reference_To (Controller_Component (T), Loc));
3054
3055             if Is_Controlled (T) then
3056                Ctrl_Ref2 := Duplicate_Subexpr_No_Checks (L);
3057             end if;
3058          end if;
3059
3060          Prev_Tmp := Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
3061
3062          Append_To (Res,
3063            Make_Object_Declaration (Loc,
3064              Defining_Identifier => Prev_Tmp,
3065
3066              Object_Definition =>
3067                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3068
3069              Expression =>
3070                Make_Selected_Component (Loc,
3071                  Prefix =>
3072                    Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref),
3073                  Selector_Name => Make_Identifier (Loc, Name_Prev))));
3074
3075          Next_Tmp := Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
3076
3077          Append_To (Res,
3078            Make_Object_Declaration (Loc,
3079              Defining_Identifier => Next_Tmp,
3080
3081              Object_Definition =>
3082                New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3083
3084              Expression =>
3085                Make_Selected_Component (Loc,
3086                  Prefix =>
3087                    Unchecked_Convert_To (RTE (RE_Finalizable),
3088                      New_Copy_Tree (Ctrl_Ref)),
3089                  Selector_Name => Make_Identifier (Loc, Name_Next))));
3090
3091          if Present (Ctrl_Ref2) then
3092             Prev_Tmp2 :=
3093               Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
3094
3095             Append_To (Res,
3096               Make_Object_Declaration (Loc,
3097                 Defining_Identifier => Prev_Tmp2,
3098
3099                 Object_Definition =>
3100                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3101
3102                 Expression =>
3103                   Make_Selected_Component (Loc,
3104                     Prefix =>
3105                       Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref2),
3106                     Selector_Name => Make_Identifier (Loc, Name_Prev))));
3107
3108             Next_Tmp2 :=
3109               Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
3110
3111             Append_To (Res,
3112               Make_Object_Declaration (Loc,
3113                 Defining_Identifier => Next_Tmp2,
3114
3115                 Object_Definition =>
3116                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3117
3118                 Expression =>
3119                   Make_Selected_Component (Loc,
3120                     Prefix =>
3121                       Unchecked_Convert_To (RTE (RE_Finalizable),
3122                         New_Copy_Tree (Ctrl_Ref2)),
3123                     Selector_Name => Make_Identifier (Loc, Name_Next))));
3124          end if;
3125
3126       --  If not controlled type, then Prev_Tmp and Ctrl_Ref unused
3127
3128       else
3129          Prev_Tmp := Empty;
3130          Ctrl_Ref := Empty;
3131       end if;
3132
3133       --  Do the Assignment
3134
3135       Append_To (Res, Relocate_Node (N));
3136
3137       --  Restore the Tag
3138
3139       if Save_Tag then
3140          Append_To (Res,
3141            Make_Assignment_Statement (Loc,
3142              Name =>
3143                Make_Selected_Component (Loc,
3144                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3145                  Selector_Name => New_Reference_To (Tag_Component (T), Loc)),
3146              Expression => New_Reference_To (Tag_Tmp, Loc)));
3147       end if;
3148
3149       --  Restore the finalization pointers
3150
3151       if Ctrl_Act then
3152          Append_To (Res,
3153            Make_Assignment_Statement (Loc,
3154              Name =>
3155                Make_Selected_Component (Loc,
3156                  Prefix =>
3157                    Unchecked_Convert_To (RTE (RE_Finalizable),
3158                      New_Copy_Tree (Ctrl_Ref)),
3159                  Selector_Name => Make_Identifier (Loc, Name_Prev)),
3160              Expression => New_Reference_To (Prev_Tmp, Loc)));
3161
3162          Append_To (Res,
3163            Make_Assignment_Statement (Loc,
3164              Name =>
3165                Make_Selected_Component (Loc,
3166                  Prefix =>
3167                    Unchecked_Convert_To (RTE (RE_Finalizable),
3168                      New_Copy_Tree (Ctrl_Ref)),
3169                  Selector_Name => Make_Identifier (Loc, Name_Next)),
3170              Expression => New_Reference_To (Next_Tmp, Loc)));
3171
3172          if Present (Ctrl_Ref2) then
3173             Append_To (Res,
3174               Make_Assignment_Statement (Loc,
3175                 Name =>
3176                   Make_Selected_Component (Loc,
3177                     Prefix =>
3178                       Unchecked_Convert_To (RTE (RE_Finalizable),
3179                         New_Copy_Tree (Ctrl_Ref2)),
3180                     Selector_Name => Make_Identifier (Loc, Name_Prev)),
3181                 Expression => New_Reference_To (Prev_Tmp2, Loc)));
3182
3183             Append_To (Res,
3184               Make_Assignment_Statement (Loc,
3185                 Name =>
3186                   Make_Selected_Component (Loc,
3187                     Prefix =>
3188                       Unchecked_Convert_To (RTE (RE_Finalizable),
3189                         New_Copy_Tree (Ctrl_Ref2)),
3190                     Selector_Name => Make_Identifier (Loc, Name_Next)),
3191                 Expression => New_Reference_To (Next_Tmp2, Loc)));
3192          end if;
3193       end if;
3194
3195       --  Adjust the target after the assignment when controlled. (not in
3196       --  the init proc since it is an initialization more than an
3197       --  assignment)
3198
3199       if Ctrl_Act then
3200          Append_List_To (Res,
3201            Make_Adjust_Call (
3202              Ref         => Duplicate_Subexpr_Move_Checks (L),
3203              Typ         => Etype (L),
3204              Flist_Ref   => New_Reference_To (RTE (RE_Global_Final_List), Loc),
3205              With_Attach => Make_Integer_Literal (Loc, 0)));
3206       end if;
3207
3208       return Res;
3209
3210    exception
3211       when RE_Not_Available =>
3212          return Empty_List;
3213    end Make_Tag_Ctrl_Assignment;
3214
3215    ------------------------------------
3216    -- Possible_Bit_Aligned_Component --
3217    ------------------------------------
3218
3219    function Possible_Bit_Aligned_Component (N : Node_Id) return Boolean is
3220    begin
3221       case Nkind (N) is
3222
3223          --  Case of indexed component
3224
3225          when N_Indexed_Component =>
3226             declare
3227                P    : constant Node_Id   := Prefix (N);
3228                Ptyp : constant Entity_Id := Etype (P);
3229
3230             begin
3231                --  If we know the component size and it is less than 64, then
3232                --  we are definitely OK. The back end always does assignment
3233                --  of misaligned small objects correctly.
3234
3235                if Known_Static_Component_Size (Ptyp)
3236                  and then Component_Size (Ptyp) <= 64
3237                then
3238                   return False;
3239
3240                --  Otherwise, we need to test the prefix, to see if we are
3241                --  indexing from a possibly unaligned component.
3242
3243                else
3244                   return Possible_Bit_Aligned_Component (P);
3245                end if;
3246             end;
3247
3248          --  Case of selected component
3249
3250          when N_Selected_Component =>
3251             declare
3252                P    : constant Node_Id   := Prefix (N);
3253                Comp : constant Entity_Id := Entity (Selector_Name (N));
3254
3255             begin
3256                --  If there is no component clause, then we are in the clear
3257                --  since the back end will never misalign a large component
3258                --  unless it is forced to do so. In the clear means we need
3259                --  only the recursive test on the prefix.
3260
3261                if Component_May_Be_Bit_Aligned (Comp) then
3262                   return True;
3263                else
3264                   return Possible_Bit_Aligned_Component (P);
3265                end if;
3266             end;
3267
3268          --  If we have neither a record nor array component, it means that
3269          --  we have fallen off the top testing prefixes recursively, and
3270          --  we now have a stand alone object, where we don't have a problem
3271
3272          when others =>
3273             return False;
3274
3275       end case;
3276    end Possible_Bit_Aligned_Component;
3277
3278 end Exp_Ch5;