OSDN Git Service

Fix PR c++/42260 and ensure PR c++/45383 is fixed
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch5.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 5                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2010, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Einfo;    use Einfo;
30 with Exp_Aggr; use Exp_Aggr;
31 with Exp_Ch6;  use Exp_Ch6;
32 with Exp_Ch7;  use Exp_Ch7;
33 with Exp_Ch11; use Exp_Ch11;
34 with Exp_Dbug; use Exp_Dbug;
35 with Exp_Pakd; use Exp_Pakd;
36 with Exp_Tss;  use Exp_Tss;
37 with Exp_Util; use Exp_Util;
38 with Namet;    use Namet;
39 with Nlists;   use Nlists;
40 with Nmake;    use Nmake;
41 with Opt;      use Opt;
42 with Restrict; use Restrict;
43 with Rident;   use Rident;
44 with Rtsfind;  use Rtsfind;
45 with Sinfo;    use Sinfo;
46 with Sem;      use Sem;
47 with Sem_Aux;  use Sem_Aux;
48 with Sem_Ch3;  use Sem_Ch3;
49 with Sem_Ch8;  use Sem_Ch8;
50 with Sem_Ch13; use Sem_Ch13;
51 with Sem_Eval; use Sem_Eval;
52 with Sem_Res;  use Sem_Res;
53 with Sem_Util; use Sem_Util;
54 with Snames;   use Snames;
55 with Stand;    use Stand;
56 with Stringt;  use Stringt;
57 with Targparm; use Targparm;
58 with Tbuild;   use Tbuild;
59 with Ttypes;   use Ttypes;
60 with Uintp;    use Uintp;
61 with Validsw;  use Validsw;
62
63 package body Exp_Ch5 is
64
65    function Change_Of_Representation (N : Node_Id) return Boolean;
66    --  Determine if the right hand side of the assignment N is a type
67    --  conversion which requires a change of representation. Called
68    --  only for the array and record cases.
69
70    procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
71    --  N is an assignment which assigns an array value. This routine process
72    --  the various special cases and checks required for such assignments,
73    --  including change of representation. Rhs is normally simply the right
74    --  hand side of the assignment, except that if the right hand side is
75    --  a type conversion or a qualified expression, then the Rhs is the
76    --  actual expression inside any such type conversions or qualifications.
77
78    function Expand_Assign_Array_Loop
79      (N      : Node_Id;
80       Larray : Entity_Id;
81       Rarray : Entity_Id;
82       L_Type : Entity_Id;
83       R_Type : Entity_Id;
84       Ndim   : Pos;
85       Rev    : Boolean) return Node_Id;
86    --  N is an assignment statement which assigns an array value. This routine
87    --  expands the assignment into a loop (or nested loops for the case of a
88    --  multi-dimensional array) to do the assignment component by component.
89    --  Larray and Rarray are the entities of the actual arrays on the left
90    --  hand and right hand sides. L_Type and R_Type are the types of these
91    --  arrays (which may not be the same, due to either sliding, or to a
92    --  change of representation case). Ndim is the number of dimensions and
93    --  the parameter Rev indicates if the loops run normally (Rev = False),
94    --  or reversed (Rev = True). The value returned is the constructed
95    --  loop statement. Auxiliary declarations are inserted before node N
96    --  using the standard Insert_Actions mechanism.
97
98    procedure Expand_Assign_Record (N : Node_Id);
99    --  N is an assignment of a non-tagged record value. This routine handles
100    --  the case where the assignment must be made component by component,
101    --  either because the target is not byte aligned, or there is a change
102    --  of representation, or when we have a tagged type with a representation
103    --  clause (this last case is required because holes in the tagged type
104    --  might be filled with components from child types).
105
106    procedure Expand_Iterator_Loop (N : Node_Id);
107    --  Expand loop over arrays and containers that uses the form "for X of C"
108    --  with an optional subtype mark, or "for Y in C".
109
110    procedure Expand_Predicated_Loop (N : Node_Id);
111    --  Expand for loop over predicated subtype
112
113    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
114    --  Generate the necessary code for controlled and tagged assignment, that
115    --  is to say, finalization of the target before, adjustment of the target
116    --  after and save and restore of the tag and finalization pointers which
117    --  are not 'part of the value' and must not be changed upon assignment. N
118    --  is the original Assignment node.
119
120    ------------------------------
121    -- Change_Of_Representation --
122    ------------------------------
123
124    function Change_Of_Representation (N : Node_Id) return Boolean is
125       Rhs : constant Node_Id := Expression (N);
126    begin
127       return
128         Nkind (Rhs) = N_Type_Conversion
129           and then
130             not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
131    end Change_Of_Representation;
132
133    -------------------------
134    -- Expand_Assign_Array --
135    -------------------------
136
137    --  There are two issues here. First, do we let Gigi do a block move, or
138    --  do we expand out into a loop? Second, we need to set the two flags
139    --  Forwards_OK and Backwards_OK which show whether the block move (or
140    --  corresponding loops) can be legitimately done in a forwards (low to
141    --  high) or backwards (high to low) manner.
142
143    procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
144       Loc : constant Source_Ptr := Sloc (N);
145
146       Lhs : constant Node_Id := Name (N);
147
148       Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
149       Act_Rhs : Node_Id          := Get_Referenced_Object (Rhs);
150
151       L_Type : constant Entity_Id :=
152                  Underlying_Type (Get_Actual_Subtype (Act_Lhs));
153       R_Type : Entity_Id :=
154                  Underlying_Type (Get_Actual_Subtype (Act_Rhs));
155
156       L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
157       R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
158
159       Crep : constant Boolean := Change_Of_Representation (N);
160
161       Larray  : Node_Id;
162       Rarray  : Node_Id;
163
164       Ndim : constant Pos := Number_Dimensions (L_Type);
165
166       Loop_Required : Boolean := False;
167       --  This switch is set to True if the array move must be done using
168       --  an explicit front end generated loop.
169
170       procedure Apply_Dereference (Arg : Node_Id);
171       --  If the argument is an access to an array, and the assignment is
172       --  converted into a procedure call, apply explicit dereference.
173
174       function Has_Address_Clause (Exp : Node_Id) return Boolean;
175       --  Test if Exp is a reference to an array whose declaration has
176       --  an address clause, or it is a slice of such an array.
177
178       function Is_Formal_Array (Exp : Node_Id) return Boolean;
179       --  Test if Exp is a reference to an array which is either a formal
180       --  parameter or a slice of a formal parameter. These are the cases
181       --  where hidden aliasing can occur.
182
183       function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
184       --  Determine if Exp is a reference to an array variable which is other
185       --  than an object defined in the current scope, or a slice of such
186       --  an object. Such objects can be aliased to parameters (unlike local
187       --  array references).
188
189       -----------------------
190       -- Apply_Dereference --
191       -----------------------
192
193       procedure Apply_Dereference (Arg : Node_Id) is
194          Typ : constant Entity_Id := Etype (Arg);
195       begin
196          if Is_Access_Type (Typ) then
197             Rewrite (Arg, Make_Explicit_Dereference (Loc,
198               Prefix => Relocate_Node (Arg)));
199             Analyze_And_Resolve (Arg, Designated_Type (Typ));
200          end if;
201       end Apply_Dereference;
202
203       ------------------------
204       -- Has_Address_Clause --
205       ------------------------
206
207       function Has_Address_Clause (Exp : Node_Id) return Boolean is
208       begin
209          return
210            (Is_Entity_Name (Exp) and then
211                               Present (Address_Clause (Entity (Exp))))
212              or else
213            (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
214       end Has_Address_Clause;
215
216       ---------------------
217       -- Is_Formal_Array --
218       ---------------------
219
220       function Is_Formal_Array (Exp : Node_Id) return Boolean is
221       begin
222          return
223            (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
224              or else
225            (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
226       end Is_Formal_Array;
227
228       ------------------------
229       -- Is_Non_Local_Array --
230       ------------------------
231
232       function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
233       begin
234          return (Is_Entity_Name (Exp)
235                    and then Scope (Entity (Exp)) /= Current_Scope)
236             or else (Nkind (Exp) = N_Slice
237                        and then Is_Non_Local_Array (Prefix (Exp)));
238       end Is_Non_Local_Array;
239
240       --  Determine if Lhs, Rhs are formal arrays or nonlocal arrays
241
242       Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
243       Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
244
245       Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
246       Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
247
248    --  Start of processing for Expand_Assign_Array
249
250    begin
251       --  Deal with length check. Note that the length check is done with
252       --  respect to the right hand side as given, not a possible underlying
253       --  renamed object, since this would generate incorrect extra checks.
254
255       Apply_Length_Check (Rhs, L_Type);
256
257       --  We start by assuming that the move can be done in either direction,
258       --  i.e. that the two sides are completely disjoint.
259
260       Set_Forwards_OK  (N, True);
261       Set_Backwards_OK (N, True);
262
263       --  Normally it is only the slice case that can lead to overlap, and
264       --  explicit checks for slices are made below. But there is one case
265       --  where the slice can be implicit and invisible to us: when we have a
266       --  one dimensional array, and either both operands are parameters, or
267       --  one is a parameter (which can be a slice passed by reference) and the
268       --  other is a non-local variable. In this case the parameter could be a
269       --  slice that overlaps with the other operand.
270
271       --  However, if the array subtype is a constrained first subtype in the
272       --  parameter case, then we don't have to worry about overlap, since
273       --  slice assignments aren't possible (other than for a slice denoting
274       --  the whole array).
275
276       --  Note: No overlap is possible if there is a change of representation,
277       --  so we can exclude this case.
278
279       if Ndim = 1
280         and then not Crep
281         and then
282            ((Lhs_Formal and Rhs_Formal)
283               or else
284             (Lhs_Formal and Rhs_Non_Local_Var)
285               or else
286             (Rhs_Formal and Lhs_Non_Local_Var))
287         and then
288            (not Is_Constrained (Etype (Lhs))
289              or else not Is_First_Subtype (Etype (Lhs)))
290
291          --  In the case of compiling for the Java or .NET Virtual Machine,
292          --  slices are always passed by making a copy, so we don't have to
293          --  worry about overlap. We also want to prevent generation of "<"
294          --  comparisons for array addresses, since that's a meaningless
295          --  operation on the VM.
296
297         and then VM_Target = No_VM
298       then
299          Set_Forwards_OK  (N, False);
300          Set_Backwards_OK (N, False);
301
302          --  Note: the bit-packed case is not worrisome here, since if we have
303          --  a slice passed as a parameter, it is always aligned on a byte
304          --  boundary, and if there are no explicit slices, the assignment
305          --  can be performed directly.
306       end if;
307
308       --  If either operand has an address clause clear Backwards_OK and
309       --  Forwards_OK, since we cannot tell if the operands overlap. We
310       --  exclude this treatment when Rhs is an aggregate, since we know
311       --  that overlap can't occur.
312
313       if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
314         or else Has_Address_Clause (Rhs)
315       then
316          Set_Forwards_OK  (N, False);
317          Set_Backwards_OK (N, False);
318       end if;
319
320       --  We certainly must use a loop for change of representation and also
321       --  we use the operand of the conversion on the right hand side as the
322       --  effective right hand side (the component types must match in this
323       --  situation).
324
325       if Crep then
326          Act_Rhs := Get_Referenced_Object (Rhs);
327          R_Type  := Get_Actual_Subtype (Act_Rhs);
328          Loop_Required := True;
329
330       --  We require a loop if the left side is possibly bit unaligned
331
332       elsif Possible_Bit_Aligned_Component (Lhs)
333               or else
334             Possible_Bit_Aligned_Component (Rhs)
335       then
336          Loop_Required := True;
337
338       --  Arrays with controlled components are expanded into a loop to force
339       --  calls to Adjust at the component level.
340
341       elsif Has_Controlled_Component (L_Type) then
342          Loop_Required := True;
343
344          --  If object is atomic, we cannot tolerate a loop
345
346       elsif Is_Atomic_Object (Act_Lhs)
347               or else
348             Is_Atomic_Object (Act_Rhs)
349       then
350          return;
351
352       --  Loop is required if we have atomic components since we have to
353       --  be sure to do any accesses on an element by element basis.
354
355       elsif Has_Atomic_Components (L_Type)
356         or else Has_Atomic_Components (R_Type)
357         or else Is_Atomic (Component_Type (L_Type))
358         or else Is_Atomic (Component_Type (R_Type))
359       then
360          Loop_Required := True;
361
362       --  Case where no slice is involved
363
364       elsif not L_Slice and not R_Slice then
365
366          --  The following code deals with the case of unconstrained bit packed
367          --  arrays. The problem is that the template for such arrays contains
368          --  the bounds of the actual source level array, but the copy of an
369          --  entire array requires the bounds of the underlying array. It would
370          --  be nice if the back end could take care of this, but right now it
371          --  does not know how, so if we have such a type, then we expand out
372          --  into a loop, which is inefficient but works correctly. If we don't
373          --  do this, we get the wrong length computed for the array to be
374          --  moved. The two cases we need to worry about are:
375
376          --  Explicit dereference of an unconstrained packed array type as in
377          --  the following example:
378
379          --    procedure C52 is
380          --       type BITS is array(INTEGER range <>) of BOOLEAN;
381          --       pragma PACK(BITS);
382          --       type A is access BITS;
383          --       P1,P2 : A;
384          --    begin
385          --       P1 := new BITS (1 .. 65_535);
386          --       P2 := new BITS (1 .. 65_535);
387          --       P2.ALL := P1.ALL;
388          --    end C52;
389
390          --  A formal parameter reference with an unconstrained bit array type
391          --  is the other case we need to worry about (here we assume the same
392          --  BITS type declared above):
393
394          --    procedure Write_All (File : out BITS; Contents : BITS);
395          --    begin
396          --       File.Storage := Contents;
397          --    end Write_All;
398
399          --  We expand to a loop in either of these two cases
400
401          --  Question for future thought. Another potentially more efficient
402          --  approach would be to create the actual subtype, and then do an
403          --  unchecked conversion to this actual subtype ???
404
405          Check_Unconstrained_Bit_Packed_Array : declare
406
407             function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
408             --  Function to perform required test for the first case, above
409             --  (dereference of an unconstrained bit packed array).
410
411             -----------------------
412             -- Is_UBPA_Reference --
413             -----------------------
414
415             function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
416                Typ      : constant Entity_Id := Underlying_Type (Etype (Opnd));
417                P_Type   : Entity_Id;
418                Des_Type : Entity_Id;
419
420             begin
421                if Present (Packed_Array_Type (Typ))
422                  and then Is_Array_Type (Packed_Array_Type (Typ))
423                  and then not Is_Constrained (Packed_Array_Type (Typ))
424                then
425                   return True;
426
427                elsif Nkind (Opnd) = N_Explicit_Dereference then
428                   P_Type := Underlying_Type (Etype (Prefix (Opnd)));
429
430                   if not Is_Access_Type (P_Type) then
431                      return False;
432
433                   else
434                      Des_Type := Designated_Type (P_Type);
435                      return
436                        Is_Bit_Packed_Array (Des_Type)
437                          and then not Is_Constrained (Des_Type);
438                   end if;
439
440                else
441                   return False;
442                end if;
443             end Is_UBPA_Reference;
444
445          --  Start of processing for Check_Unconstrained_Bit_Packed_Array
446
447          begin
448             if Is_UBPA_Reference (Lhs)
449                  or else
450                Is_UBPA_Reference (Rhs)
451             then
452                Loop_Required := True;
453
454             --  Here if we do not have the case of a reference to a bit packed
455             --  unconstrained array case. In this case gigi can most certainly
456             --  handle the assignment if a forwards move is allowed.
457
458             --  (could it handle the backwards case also???)
459
460             elsif Forwards_OK (N) then
461                return;
462             end if;
463          end Check_Unconstrained_Bit_Packed_Array;
464
465       --  The back end can always handle the assignment if the right side is a
466       --  string literal (note that overlap is definitely impossible in this
467       --  case). If the type is packed, a string literal is always converted
468       --  into an aggregate, except in the case of a null slice, for which no
469       --  aggregate can be written. In that case, rewrite the assignment as a
470       --  null statement, a length check has already been emitted to verify
471       --  that the range of the left-hand side is empty.
472
473       --  Note that this code is not executed if we have an assignment of a
474       --  string literal to a non-bit aligned component of a record, a case
475       --  which cannot be handled by the backend.
476
477       elsif Nkind (Rhs) = N_String_Literal then
478          if String_Length (Strval (Rhs)) = 0
479            and then Is_Bit_Packed_Array (L_Type)
480          then
481             Rewrite (N, Make_Null_Statement (Loc));
482             Analyze (N);
483          end if;
484
485          return;
486
487       --  If either operand is bit packed, then we need a loop, since we can't
488       --  be sure that the slice is byte aligned. Similarly, if either operand
489       --  is a possibly unaligned slice, then we need a loop (since the back
490       --  end cannot handle unaligned slices).
491
492       elsif Is_Bit_Packed_Array (L_Type)
493         or else Is_Bit_Packed_Array (R_Type)
494         or else Is_Possibly_Unaligned_Slice (Lhs)
495         or else Is_Possibly_Unaligned_Slice (Rhs)
496       then
497          Loop_Required := True;
498
499       --  If we are not bit-packed, and we have only one slice, then no overlap
500       --  is possible except in the parameter case, so we can let the back end
501       --  handle things.
502
503       elsif not (L_Slice and R_Slice) then
504          if Forwards_OK (N) then
505             return;
506          end if;
507       end if;
508
509       --  If the right-hand side is a string literal, introduce a temporary for
510       --  it, for use in the generated loop that will follow.
511
512       if Nkind (Rhs) = N_String_Literal then
513          declare
514             Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
515             Decl : Node_Id;
516
517          begin
518             Decl :=
519               Make_Object_Declaration (Loc,
520                  Defining_Identifier => Temp,
521                  Object_Definition => New_Occurrence_Of (L_Type, Loc),
522                  Expression => Relocate_Node (Rhs));
523
524             Insert_Action (N, Decl);
525             Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
526             R_Type := Etype (Temp);
527          end;
528       end if;
529
530       --  Come here to complete the analysis
531
532       --    Loop_Required: Set to True if we know that a loop is required
533       --                   regardless of overlap considerations.
534
535       --    Forwards_OK:   Set to False if we already know that a forwards
536       --                   move is not safe, else set to True.
537
538       --    Backwards_OK:  Set to False if we already know that a backwards
539       --                   move is not safe, else set to True
540
541       --  Our task at this stage is to complete the overlap analysis, which can
542       --  result in possibly setting Forwards_OK or Backwards_OK to False, and
543       --  then generating the final code, either by deciding that it is OK
544       --  after all to let Gigi handle it, or by generating appropriate code
545       --  in the front end.
546
547       declare
548          L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
549          R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
550
551          Left_Lo  : constant Node_Id := Type_Low_Bound  (L_Index_Typ);
552          Left_Hi  : constant Node_Id := Type_High_Bound (L_Index_Typ);
553          Right_Lo : constant Node_Id := Type_Low_Bound  (R_Index_Typ);
554          Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
555
556          Act_L_Array : Node_Id;
557          Act_R_Array : Node_Id;
558
559          Cleft_Lo  : Node_Id;
560          Cright_Lo : Node_Id;
561          Condition : Node_Id;
562
563          Cresult : Compare_Result;
564
565       begin
566          --  Get the expressions for the arrays. If we are dealing with a
567          --  private type, then convert to the underlying type. We can do
568          --  direct assignments to an array that is a private type, but we
569          --  cannot assign to elements of the array without this extra
570          --  unchecked conversion.
571
572          --  Note: We propagate Parent to the conversion nodes to generate
573          --  a well-formed subtree.
574
575          if Nkind (Act_Lhs) = N_Slice then
576             Larray := Prefix (Act_Lhs);
577          else
578             Larray := Act_Lhs;
579
580             if Is_Private_Type (Etype (Larray)) then
581                declare
582                   Par : constant Node_Id := Parent (Larray);
583                begin
584                   Larray :=
585                     Unchecked_Convert_To
586                       (Underlying_Type (Etype (Larray)), Larray);
587                   Set_Parent (Larray, Par);
588                end;
589             end if;
590          end if;
591
592          if Nkind (Act_Rhs) = N_Slice then
593             Rarray := Prefix (Act_Rhs);
594          else
595             Rarray := Act_Rhs;
596
597             if Is_Private_Type (Etype (Rarray)) then
598                declare
599                   Par : constant Node_Id := Parent (Rarray);
600                begin
601                   Rarray :=
602                     Unchecked_Convert_To
603                       (Underlying_Type (Etype (Rarray)), Rarray);
604                   Set_Parent (Rarray, Par);
605                end;
606             end if;
607          end if;
608
609          --  If both sides are slices, we must figure out whether it is safe
610          --  to do the move in one direction or the other. It is always safe
611          --  if there is a change of representation since obviously two arrays
612          --  with different representations cannot possibly overlap.
613
614          if (not Crep) and L_Slice and R_Slice then
615             Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
616             Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
617
618             --  If both left and right hand arrays are entity names, and refer
619             --  to different entities, then we know that the move is safe (the
620             --  two storage areas are completely disjoint).
621
622             if Is_Entity_Name (Act_L_Array)
623               and then Is_Entity_Name (Act_R_Array)
624               and then Entity (Act_L_Array) /= Entity (Act_R_Array)
625             then
626                null;
627
628             --  Otherwise, we assume the worst, which is that the two arrays
629             --  are the same array. There is no need to check if we know that
630             --  is the case, because if we don't know it, we still have to
631             --  assume it!
632
633             --  Generally if the same array is involved, then we have an
634             --  overlapping case. We will have to really assume the worst (i.e.
635             --  set neither of the OK flags) unless we can determine the lower
636             --  or upper bounds at compile time and compare them.
637
638             else
639                Cresult :=
640                  Compile_Time_Compare
641                    (Left_Lo, Right_Lo, Assume_Valid => True);
642
643                if Cresult = Unknown then
644                   Cresult :=
645                     Compile_Time_Compare
646                       (Left_Hi, Right_Hi, Assume_Valid => True);
647                end if;
648
649                case Cresult is
650                   when LT | LE | EQ => Set_Backwards_OK (N, False);
651                   when GT | GE      => Set_Forwards_OK  (N, False);
652                   when NE | Unknown => Set_Backwards_OK (N, False);
653                                        Set_Forwards_OK  (N, False);
654                end case;
655             end if;
656          end if;
657
658          --  If after that analysis Loop_Required is False, meaning that we
659          --  have not discovered some non-overlap reason for requiring a loop,
660          --  then the outcome depends on the capabilities of the back end.
661
662          if not Loop_Required then
663
664             --  The GCC back end can deal with all cases of overlap by falling
665             --  back to memmove if it cannot use a more efficient approach.
666
667             if VM_Target = No_VM and not AAMP_On_Target then
668                return;
669
670             --  Assume other back ends can handle it if Forwards_OK is set
671
672             elsif Forwards_OK (N) then
673                return;
674
675             --  If Forwards_OK is not set, the back end will need something
676             --  like memmove to handle the move. For now, this processing is
677             --  activated using the .s debug flag (-gnatd.s).
678
679             elsif Debug_Flag_Dot_S then
680                return;
681             end if;
682          end if;
683
684          --  At this stage we have to generate an explicit loop, and we have
685          --  the following cases:
686
687          --  Forwards_OK = True
688
689          --    Rnn : right_index := right_index'First;
690          --    for Lnn in left-index loop
691          --       left (Lnn) := right (Rnn);
692          --       Rnn := right_index'Succ (Rnn);
693          --    end loop;
694
695          --    Note: the above code MUST be analyzed with checks off, because
696          --    otherwise the Succ could overflow. But in any case this is more
697          --    efficient!
698
699          --  Forwards_OK = False, Backwards_OK = True
700
701          --    Rnn : right_index := right_index'Last;
702          --    for Lnn in reverse left-index loop
703          --       left (Lnn) := right (Rnn);
704          --       Rnn := right_index'Pred (Rnn);
705          --    end loop;
706
707          --    Note: the above code MUST be analyzed with checks off, because
708          --    otherwise the Pred could overflow. But in any case this is more
709          --    efficient!
710
711          --  Forwards_OK = Backwards_OK = False
712
713          --    This only happens if we have the same array on each side. It is
714          --    possible to create situations using overlays that violate this,
715          --    but we simply do not promise to get this "right" in this case.
716
717          --    There are two possible subcases. If the No_Implicit_Conditionals
718          --    restriction is set, then we generate the following code:
719
720          --      declare
721          --        T : constant <operand-type> := rhs;
722          --      begin
723          --        lhs := T;
724          --      end;
725
726          --    If implicit conditionals are permitted, then we generate:
727
728          --      if Left_Lo <= Right_Lo then
729          --         <code for Forwards_OK = True above>
730          --      else
731          --         <code for Backwards_OK = True above>
732          --      end if;
733
734          --  In order to detect possible aliasing, we examine the renamed
735          --  expression when the source or target is a renaming. However,
736          --  the renaming may be intended to capture an address that may be
737          --  affected by subsequent code, and therefore we must recover
738          --  the actual entity for the expansion that follows, not the
739          --  object it renames. In particular, if source or target designate
740          --  a portion of a dynamically allocated object, the pointer to it
741          --  may be reassigned but the renaming preserves the proper location.
742
743          if Is_Entity_Name (Rhs)
744            and then
745              Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
746            and then Nkind (Act_Rhs) = N_Slice
747          then
748             Rarray := Rhs;
749          end if;
750
751          if Is_Entity_Name (Lhs)
752            and then
753              Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
754            and then Nkind (Act_Lhs) = N_Slice
755          then
756             Larray := Lhs;
757          end if;
758
759          --  Cases where either Forwards_OK or Backwards_OK is true
760
761          if Forwards_OK (N) or else Backwards_OK (N) then
762             if Needs_Finalization (Component_Type (L_Type))
763               and then Base_Type (L_Type) = Base_Type (R_Type)
764               and then Ndim = 1
765               and then not No_Ctrl_Actions (N)
766             then
767                declare
768                   Proc    : constant Entity_Id :=
769                               TSS (Base_Type (L_Type), TSS_Slice_Assign);
770                   Actuals : List_Id;
771
772                begin
773                   Apply_Dereference (Larray);
774                   Apply_Dereference (Rarray);
775                   Actuals := New_List (
776                     Duplicate_Subexpr (Larray,   Name_Req => True),
777                     Duplicate_Subexpr (Rarray,   Name_Req => True),
778                     Duplicate_Subexpr (Left_Lo,  Name_Req => True),
779                     Duplicate_Subexpr (Left_Hi,  Name_Req => True),
780                     Duplicate_Subexpr (Right_Lo, Name_Req => True),
781                     Duplicate_Subexpr (Right_Hi, Name_Req => True));
782
783                   Append_To (Actuals,
784                     New_Occurrence_Of (
785                       Boolean_Literals (not Forwards_OK (N)), Loc));
786
787                   Rewrite (N,
788                     Make_Procedure_Call_Statement (Loc,
789                       Name => New_Reference_To (Proc, Loc),
790                       Parameter_Associations => Actuals));
791                end;
792
793             else
794                Rewrite (N,
795                  Expand_Assign_Array_Loop
796                    (N, Larray, Rarray, L_Type, R_Type, Ndim,
797                     Rev => not Forwards_OK (N)));
798             end if;
799
800          --  Case of both are false with No_Implicit_Conditionals
801
802          elsif Restriction_Active (No_Implicit_Conditionals) then
803             declare
804                   T : constant Entity_Id :=
805                         Make_Defining_Identifier (Loc, Chars => Name_T);
806
807             begin
808                Rewrite (N,
809                  Make_Block_Statement (Loc,
810                   Declarations => New_List (
811                     Make_Object_Declaration (Loc,
812                       Defining_Identifier => T,
813                       Constant_Present  => True,
814                       Object_Definition =>
815                         New_Occurrence_Of (Etype (Rhs), Loc),
816                       Expression        => Relocate_Node (Rhs))),
817
818                     Handled_Statement_Sequence =>
819                       Make_Handled_Sequence_Of_Statements (Loc,
820                         Statements => New_List (
821                           Make_Assignment_Statement (Loc,
822                             Name       => Relocate_Node (Lhs),
823                             Expression => New_Occurrence_Of (T, Loc))))));
824             end;
825
826          --  Case of both are false with implicit conditionals allowed
827
828          else
829             --  Before we generate this code, we must ensure that the left and
830             --  right side array types are defined. They may be itypes, and we
831             --  cannot let them be defined inside the if, since the first use
832             --  in the then may not be executed.
833
834             Ensure_Defined (L_Type, N);
835             Ensure_Defined (R_Type, N);
836
837             --  We normally compare addresses to find out which way round to
838             --  do the loop, since this is reliable, and handles the cases of
839             --  parameters, conversions etc. But we can't do that in the bit
840             --  packed case or the VM case, because addresses don't work there.
841
842             if not Is_Bit_Packed_Array (L_Type) and then VM_Target = No_VM then
843                Condition :=
844                  Make_Op_Le (Loc,
845                    Left_Opnd =>
846                      Unchecked_Convert_To (RTE (RE_Integer_Address),
847                        Make_Attribute_Reference (Loc,
848                          Prefix =>
849                            Make_Indexed_Component (Loc,
850                              Prefix =>
851                                Duplicate_Subexpr_Move_Checks (Larray, True),
852                              Expressions => New_List (
853                                Make_Attribute_Reference (Loc,
854                                  Prefix =>
855                                    New_Reference_To
856                                      (L_Index_Typ, Loc),
857                                  Attribute_Name => Name_First))),
858                          Attribute_Name => Name_Address)),
859
860                    Right_Opnd =>
861                      Unchecked_Convert_To (RTE (RE_Integer_Address),
862                        Make_Attribute_Reference (Loc,
863                          Prefix =>
864                            Make_Indexed_Component (Loc,
865                              Prefix =>
866                                Duplicate_Subexpr_Move_Checks (Rarray, True),
867                              Expressions => New_List (
868                                Make_Attribute_Reference (Loc,
869                                  Prefix =>
870                                    New_Reference_To
871                                      (R_Index_Typ, Loc),
872                                  Attribute_Name => Name_First))),
873                          Attribute_Name => Name_Address)));
874
875             --  For the bit packed and VM cases we use the bounds. That's OK,
876             --  because we don't have to worry about parameters, since they
877             --  cannot cause overlap. Perhaps we should worry about weird slice
878             --  conversions ???
879
880             else
881                --  Copy the bounds
882
883                Cleft_Lo  := New_Copy_Tree (Left_Lo);
884                Cright_Lo := New_Copy_Tree (Right_Lo);
885
886                --  If the types do not match we add an implicit conversion
887                --  here to ensure proper match
888
889                if Etype (Left_Lo) /= Etype (Right_Lo) then
890                   Cright_Lo :=
891                     Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
892                end if;
893
894                --  Reset the Analyzed flag, because the bounds of the index
895                --  type itself may be universal, and must must be reaanalyzed
896                --  to acquire the proper type for the back end.
897
898                Set_Analyzed (Cleft_Lo, False);
899                Set_Analyzed (Cright_Lo, False);
900
901                Condition :=
902                  Make_Op_Le (Loc,
903                    Left_Opnd  => Cleft_Lo,
904                    Right_Opnd => Cright_Lo);
905             end if;
906
907             if Needs_Finalization (Component_Type (L_Type))
908               and then Base_Type (L_Type) = Base_Type (R_Type)
909               and then Ndim = 1
910               and then not No_Ctrl_Actions (N)
911             then
912
913                --  Call TSS procedure for array assignment, passing the
914                --  explicit bounds of right and left hand sides.
915
916                declare
917                   Proc    : constant Entity_Id :=
918                               TSS (Base_Type (L_Type), TSS_Slice_Assign);
919                   Actuals : List_Id;
920
921                begin
922                   Apply_Dereference (Larray);
923                   Apply_Dereference (Rarray);
924                   Actuals := New_List (
925                     Duplicate_Subexpr (Larray,   Name_Req => True),
926                     Duplicate_Subexpr (Rarray,   Name_Req => True),
927                     Duplicate_Subexpr (Left_Lo,  Name_Req => True),
928                     Duplicate_Subexpr (Left_Hi,  Name_Req => True),
929                     Duplicate_Subexpr (Right_Lo, Name_Req => True),
930                     Duplicate_Subexpr (Right_Hi, Name_Req => True));
931
932                   Append_To (Actuals,
933                      Make_Op_Not (Loc,
934                        Right_Opnd => Condition));
935
936                   Rewrite (N,
937                     Make_Procedure_Call_Statement (Loc,
938                       Name => New_Reference_To (Proc, Loc),
939                       Parameter_Associations => Actuals));
940                end;
941
942             else
943                Rewrite (N,
944                  Make_Implicit_If_Statement (N,
945                    Condition => Condition,
946
947                    Then_Statements => New_List (
948                      Expand_Assign_Array_Loop
949                       (N, Larray, Rarray, L_Type, R_Type, Ndim,
950                        Rev => False)),
951
952                    Else_Statements => New_List (
953                      Expand_Assign_Array_Loop
954                       (N, Larray, Rarray, L_Type, R_Type, Ndim,
955                        Rev => True))));
956             end if;
957          end if;
958
959          Analyze (N, Suppress => All_Checks);
960       end;
961
962    exception
963       when RE_Not_Available =>
964          return;
965    end Expand_Assign_Array;
966
967    ------------------------------
968    -- Expand_Assign_Array_Loop --
969    ------------------------------
970
971    --  The following is an example of the loop generated for the case of a
972    --  two-dimensional array:
973
974    --    declare
975    --       R2b : Tm1X1 := 1;
976    --    begin
977    --       for L1b in 1 .. 100 loop
978    --          declare
979    --             R4b : Tm1X2 := 1;
980    --          begin
981    --             for L3b in 1 .. 100 loop
982    --                vm1 (L1b, L3b) := vm2 (R2b, R4b);
983    --                R4b := Tm1X2'succ(R4b);
984    --             end loop;
985    --          end;
986    --          R2b := Tm1X1'succ(R2b);
987    --       end loop;
988    --    end;
989
990    --  Here Rev is False, and Tm1Xn are the subscript types for the right hand
991    --  side. The declarations of R2b and R4b are inserted before the original
992    --  assignment statement.
993
994    function Expand_Assign_Array_Loop
995      (N      : Node_Id;
996       Larray : Entity_Id;
997       Rarray : Entity_Id;
998       L_Type : Entity_Id;
999       R_Type : Entity_Id;
1000       Ndim   : Pos;
1001       Rev    : Boolean) return Node_Id
1002    is
1003       Loc  : constant Source_Ptr := Sloc (N);
1004
1005       Lnn : array (1 .. Ndim) of Entity_Id;
1006       Rnn : array (1 .. Ndim) of Entity_Id;
1007       --  Entities used as subscripts on left and right sides
1008
1009       L_Index_Type : array (1 .. Ndim) of Entity_Id;
1010       R_Index_Type : array (1 .. Ndim) of Entity_Id;
1011       --  Left and right index types
1012
1013       Assign : Node_Id;
1014
1015       F_Or_L : Name_Id;
1016       S_Or_P : Name_Id;
1017
1018       function Build_Step (J : Nat) return Node_Id;
1019       --  The increment step for the index of the right-hand side is written
1020       --  as an attribute reference (Succ or Pred). This function returns
1021       --  the corresponding node, which is placed at the end of the loop body.
1022
1023       ----------------
1024       -- Build_Step --
1025       ----------------
1026
1027       function Build_Step (J : Nat) return Node_Id is
1028          Step : Node_Id;
1029          Lim  : Name_Id;
1030
1031       begin
1032          if Rev then
1033             Lim := Name_First;
1034          else
1035             Lim := Name_Last;
1036          end if;
1037
1038          Step :=
1039             Make_Assignment_Statement (Loc,
1040                Name => New_Occurrence_Of (Rnn (J), Loc),
1041                Expression =>
1042                  Make_Attribute_Reference (Loc,
1043                    Prefix =>
1044                      New_Occurrence_Of (R_Index_Type (J), Loc),
1045                    Attribute_Name => S_Or_P,
1046                    Expressions => New_List (
1047                      New_Occurrence_Of (Rnn (J), Loc))));
1048
1049       --  Note that on the last iteration of the loop, the index is increased
1050       --  (or decreased) past the corresponding bound. This is consistent with
1051       --  the C semantics of the back-end, where such an off-by-one value on a
1052       --  dead index variable is OK. However, in CodePeer mode this leads to
1053       --  spurious warnings, and thus we place a guard around the attribute
1054       --  reference. For obvious reasons we only do this for CodePeer.
1055
1056          if CodePeer_Mode then
1057             Step :=
1058               Make_If_Statement (Loc,
1059                  Condition =>
1060                     Make_Op_Ne (Loc,
1061                        Left_Opnd  => New_Occurrence_Of (Lnn (J), Loc),
1062                        Right_Opnd =>
1063                          Make_Attribute_Reference (Loc,
1064                            Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1065                            Attribute_Name => Lim)),
1066                  Then_Statements => New_List (Step));
1067          end if;
1068
1069          return Step;
1070       end Build_Step;
1071
1072    --  Start of processing for Expand_Assign_Array_Loop
1073
1074    begin
1075       if Rev then
1076          F_Or_L := Name_Last;
1077          S_Or_P := Name_Pred;
1078       else
1079          F_Or_L := Name_First;
1080          S_Or_P := Name_Succ;
1081       end if;
1082
1083       --  Setup index types and subscript entities
1084
1085       declare
1086          L_Index : Node_Id;
1087          R_Index : Node_Id;
1088
1089       begin
1090          L_Index := First_Index (L_Type);
1091          R_Index := First_Index (R_Type);
1092
1093          for J in 1 .. Ndim loop
1094             Lnn (J) := Make_Temporary (Loc, 'L');
1095             Rnn (J) := Make_Temporary (Loc, 'R');
1096
1097             L_Index_Type (J) := Etype (L_Index);
1098             R_Index_Type (J) := Etype (R_Index);
1099
1100             Next_Index (L_Index);
1101             Next_Index (R_Index);
1102          end loop;
1103       end;
1104
1105       --  Now construct the assignment statement
1106
1107       declare
1108          ExprL : constant List_Id := New_List;
1109          ExprR : constant List_Id := New_List;
1110
1111       begin
1112          for J in 1 .. Ndim loop
1113             Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1114             Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1115          end loop;
1116
1117          Assign :=
1118            Make_Assignment_Statement (Loc,
1119              Name =>
1120                Make_Indexed_Component (Loc,
1121                  Prefix      => Duplicate_Subexpr (Larray, Name_Req => True),
1122                  Expressions => ExprL),
1123              Expression =>
1124                Make_Indexed_Component (Loc,
1125                  Prefix      => Duplicate_Subexpr (Rarray, Name_Req => True),
1126                  Expressions => ExprR));
1127
1128          --  We set assignment OK, since there are some cases, e.g. in object
1129          --  declarations, where we are actually assigning into a constant.
1130          --  If there really is an illegality, it was caught long before now,
1131          --  and was flagged when the original assignment was analyzed.
1132
1133          Set_Assignment_OK (Name (Assign));
1134
1135          --  Propagate the No_Ctrl_Actions flag to individual assignments
1136
1137          Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1138       end;
1139
1140       --  Now construct the loop from the inside out, with the last subscript
1141       --  varying most rapidly. Note that Assign is first the raw assignment
1142       --  statement, and then subsequently the loop that wraps it up.
1143
1144       for J in reverse 1 .. Ndim loop
1145          Assign :=
1146            Make_Block_Statement (Loc,
1147              Declarations => New_List (
1148               Make_Object_Declaration (Loc,
1149                 Defining_Identifier => Rnn (J),
1150                 Object_Definition =>
1151                   New_Occurrence_Of (R_Index_Type (J), Loc),
1152                 Expression =>
1153                   Make_Attribute_Reference (Loc,
1154                     Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1155                     Attribute_Name => F_Or_L))),
1156
1157            Handled_Statement_Sequence =>
1158              Make_Handled_Sequence_Of_Statements (Loc,
1159                Statements => New_List (
1160                  Make_Implicit_Loop_Statement (N,
1161                    Iteration_Scheme =>
1162                      Make_Iteration_Scheme (Loc,
1163                        Loop_Parameter_Specification =>
1164                          Make_Loop_Parameter_Specification (Loc,
1165                            Defining_Identifier => Lnn (J),
1166                            Reverse_Present => Rev,
1167                            Discrete_Subtype_Definition =>
1168                              New_Reference_To (L_Index_Type (J), Loc))),
1169
1170                    Statements => New_List (Assign, Build_Step (J))))));
1171       end loop;
1172
1173       return Assign;
1174    end Expand_Assign_Array_Loop;
1175
1176    --------------------------
1177    -- Expand_Assign_Record --
1178    --------------------------
1179
1180    procedure Expand_Assign_Record (N : Node_Id) is
1181       Lhs   : constant Node_Id    := Name (N);
1182       Rhs   : Node_Id             := Expression (N);
1183       L_Typ : constant Entity_Id  := Base_Type (Etype (Lhs));
1184
1185    begin
1186       --  If change of representation, then extract the real right hand side
1187       --  from the type conversion, and proceed with component-wise assignment,
1188       --  since the two types are not the same as far as the back end is
1189       --  concerned.
1190
1191       if Change_Of_Representation (N) then
1192          Rhs := Expression (Rhs);
1193
1194       --  If this may be a case of a large bit aligned component, then proceed
1195       --  with component-wise assignment, to avoid possible clobbering of other
1196       --  components sharing bits in the first or last byte of the component to
1197       --  be assigned.
1198
1199       elsif Possible_Bit_Aligned_Component (Lhs)
1200               or
1201             Possible_Bit_Aligned_Component (Rhs)
1202       then
1203          null;
1204
1205       --  If we have a tagged type that has a complete record representation
1206       --  clause, we must do we must do component-wise assignments, since child
1207       --  types may have used gaps for their components, and we might be
1208       --  dealing with a view conversion.
1209
1210       elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1211          null;
1212
1213       --  If neither condition met, then nothing special to do, the back end
1214       --  can handle assignment of the entire component as a single entity.
1215
1216       else
1217          return;
1218       end if;
1219
1220       --  At this stage we know that we must do a component wise assignment
1221
1222       declare
1223          Loc   : constant Source_Ptr := Sloc (N);
1224          R_Typ : constant Entity_Id  := Base_Type (Etype (Rhs));
1225          Decl  : constant Node_Id    := Declaration_Node (R_Typ);
1226          RDef  : Node_Id;
1227          F     : Entity_Id;
1228
1229          function Find_Component
1230            (Typ  : Entity_Id;
1231             Comp : Entity_Id) return Entity_Id;
1232          --  Find the component with the given name in the underlying record
1233          --  declaration for Typ. We need to use the actual entity because the
1234          --  type may be private and resolution by identifier alone would fail.
1235
1236          function Make_Component_List_Assign
1237            (CL  : Node_Id;
1238             U_U : Boolean := False) return List_Id;
1239          --  Returns a sequence of statements to assign the components that
1240          --  are referenced in the given component list. The flag U_U is
1241          --  used to force the usage of the inferred value of the variant
1242          --  part expression as the switch for the generated case statement.
1243
1244          function Make_Field_Assign
1245            (C   : Entity_Id;
1246             U_U : Boolean := False) return Node_Id;
1247          --  Given C, the entity for a discriminant or component, build an
1248          --  assignment for the corresponding field values. The flag U_U
1249          --  signals the presence of an Unchecked_Union and forces the usage
1250          --  of the inferred discriminant value of C as the right hand side
1251          --  of the assignment.
1252
1253          function Make_Field_Assigns (CI : List_Id) return List_Id;
1254          --  Given CI, a component items list, construct series of statements
1255          --  for fieldwise assignment of the corresponding components.
1256
1257          --------------------
1258          -- Find_Component --
1259          --------------------
1260
1261          function Find_Component
1262            (Typ  : Entity_Id;
1263             Comp : Entity_Id) return Entity_Id
1264          is
1265             Utyp : constant Entity_Id := Underlying_Type (Typ);
1266             C    : Entity_Id;
1267
1268          begin
1269             C := First_Entity (Utyp);
1270             while Present (C) loop
1271                if Chars (C) = Chars (Comp) then
1272                   return C;
1273                end if;
1274
1275                Next_Entity (C);
1276             end loop;
1277
1278             raise Program_Error;
1279          end Find_Component;
1280
1281          --------------------------------
1282          -- Make_Component_List_Assign --
1283          --------------------------------
1284
1285          function Make_Component_List_Assign
1286            (CL  : Node_Id;
1287             U_U : Boolean := False) return List_Id
1288          is
1289             CI : constant List_Id := Component_Items (CL);
1290             VP : constant Node_Id := Variant_Part (CL);
1291
1292             Alts   : List_Id;
1293             DC     : Node_Id;
1294             DCH    : List_Id;
1295             Expr   : Node_Id;
1296             Result : List_Id;
1297             V      : Node_Id;
1298
1299          begin
1300             Result := Make_Field_Assigns (CI);
1301
1302             if Present (VP) then
1303                V := First_Non_Pragma (Variants (VP));
1304                Alts := New_List;
1305                while Present (V) loop
1306                   DCH := New_List;
1307                   DC := First (Discrete_Choices (V));
1308                   while Present (DC) loop
1309                      Append_To (DCH, New_Copy_Tree (DC));
1310                      Next (DC);
1311                   end loop;
1312
1313                   Append_To (Alts,
1314                     Make_Case_Statement_Alternative (Loc,
1315                       Discrete_Choices => DCH,
1316                       Statements =>
1317                         Make_Component_List_Assign (Component_List (V))));
1318                   Next_Non_Pragma (V);
1319                end loop;
1320
1321                --  If we have an Unchecked_Union, use the value of the inferred
1322                --  discriminant of the variant part expression as the switch
1323                --  for the case statement. The case statement may later be
1324                --  folded.
1325
1326                if U_U then
1327                   Expr :=
1328                     New_Copy (Get_Discriminant_Value (
1329                       Entity (Name (VP)),
1330                       Etype (Rhs),
1331                       Discriminant_Constraint (Etype (Rhs))));
1332                else
1333                   Expr :=
1334                     Make_Selected_Component (Loc,
1335                       Prefix        => Duplicate_Subexpr (Rhs),
1336                       Selector_Name =>
1337                         Make_Identifier (Loc, Chars (Name (VP))));
1338                end if;
1339
1340                Append_To (Result,
1341                  Make_Case_Statement (Loc,
1342                    Expression => Expr,
1343                    Alternatives => Alts));
1344             end if;
1345
1346             return Result;
1347          end Make_Component_List_Assign;
1348
1349          -----------------------
1350          -- Make_Field_Assign --
1351          -----------------------
1352
1353          function Make_Field_Assign
1354            (C   : Entity_Id;
1355             U_U : Boolean := False) return Node_Id
1356          is
1357             A    : Node_Id;
1358             Expr : Node_Id;
1359
1360          begin
1361             --  In the case of an Unchecked_Union, use the discriminant
1362             --  constraint value as on the right hand side of the assignment.
1363
1364             if U_U then
1365                Expr :=
1366                  New_Copy (Get_Discriminant_Value (C,
1367                    Etype (Rhs),
1368                    Discriminant_Constraint (Etype (Rhs))));
1369             else
1370                Expr :=
1371                  Make_Selected_Component (Loc,
1372                    Prefix        => Duplicate_Subexpr (Rhs),
1373                    Selector_Name => New_Occurrence_Of (C, Loc));
1374             end if;
1375
1376             A :=
1377               Make_Assignment_Statement (Loc,
1378                 Name =>
1379                   Make_Selected_Component (Loc,
1380                     Prefix        => Duplicate_Subexpr (Lhs),
1381                     Selector_Name =>
1382                       New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1383                 Expression => Expr);
1384
1385             --  Set Assignment_OK, so discriminants can be assigned
1386
1387             Set_Assignment_OK (Name (A), True);
1388
1389             if Componentwise_Assignment (N)
1390               and then Nkind (Name (A)) = N_Selected_Component
1391               and then Chars (Selector_Name (Name (A))) = Name_uParent
1392             then
1393                Set_Componentwise_Assignment (A);
1394             end if;
1395
1396             return A;
1397          end Make_Field_Assign;
1398
1399          ------------------------
1400          -- Make_Field_Assigns --
1401          ------------------------
1402
1403          function Make_Field_Assigns (CI : List_Id) return List_Id is
1404             Item   : Node_Id;
1405             Result : List_Id;
1406
1407          begin
1408             Item := First (CI);
1409             Result := New_List;
1410
1411             while Present (Item) loop
1412
1413                --  Look for components, but exclude _tag field assignment if
1414                --  the special Componentwise_Assignment flag is set.
1415
1416                if Nkind (Item) = N_Component_Declaration
1417                  and then not (Is_Tag (Defining_Identifier (Item))
1418                                  and then Componentwise_Assignment (N))
1419                then
1420                   Append_To
1421                     (Result, Make_Field_Assign (Defining_Identifier (Item)));
1422                end if;
1423
1424                Next (Item);
1425             end loop;
1426
1427             return Result;
1428          end Make_Field_Assigns;
1429
1430       --  Start of processing for Expand_Assign_Record
1431
1432       begin
1433          --  Note that we use the base types for this processing. This results
1434          --  in some extra work in the constrained case, but the change of
1435          --  representation case is so unusual that it is not worth the effort.
1436
1437          --  First copy the discriminants. This is done unconditionally. It
1438          --  is required in the unconstrained left side case, and also in the
1439          --  case where this assignment was constructed during the expansion
1440          --  of a type conversion (since initialization of discriminants is
1441          --  suppressed in this case). It is unnecessary but harmless in
1442          --  other cases.
1443
1444          if Has_Discriminants (L_Typ) then
1445             F := First_Discriminant (R_Typ);
1446             while Present (F) loop
1447
1448                --  If we are expanding the initialization of a derived record
1449                --  that constrains or renames discriminants of the parent, we
1450                --  must use the corresponding discriminant in the parent.
1451
1452                declare
1453                   CF : Entity_Id;
1454
1455                begin
1456                   if Inside_Init_Proc
1457                     and then Present (Corresponding_Discriminant (F))
1458                   then
1459                      CF := Corresponding_Discriminant (F);
1460                   else
1461                      CF := F;
1462                   end if;
1463
1464                   if Is_Unchecked_Union (Base_Type (R_Typ)) then
1465                      Insert_Action (N, Make_Field_Assign (CF, True));
1466                   else
1467                      Insert_Action (N, Make_Field_Assign (CF));
1468                   end if;
1469
1470                   Next_Discriminant (F);
1471                end;
1472             end loop;
1473          end if;
1474
1475          --  We know the underlying type is a record, but its current view
1476          --  may be private. We must retrieve the usable record declaration.
1477
1478          if Nkind_In (Decl, N_Private_Type_Declaration,
1479                             N_Private_Extension_Declaration)
1480            and then Present (Full_View (R_Typ))
1481          then
1482             RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1483          else
1484             RDef := Type_Definition (Decl);
1485          end if;
1486
1487          if Nkind (RDef) = N_Derived_Type_Definition then
1488             RDef := Record_Extension_Part (RDef);
1489          end if;
1490
1491          if Nkind (RDef) = N_Record_Definition
1492            and then Present (Component_List (RDef))
1493          then
1494             if Is_Unchecked_Union (R_Typ) then
1495                Insert_Actions (N,
1496                  Make_Component_List_Assign (Component_List (RDef), True));
1497             else
1498                Insert_Actions
1499                  (N, Make_Component_List_Assign (Component_List (RDef)));
1500             end if;
1501
1502             Rewrite (N, Make_Null_Statement (Loc));
1503          end if;
1504       end;
1505    end Expand_Assign_Record;
1506
1507    -----------------------------------
1508    -- Expand_N_Assignment_Statement --
1509    -----------------------------------
1510
1511    --  This procedure implements various cases where an assignment statement
1512    --  cannot just be passed on to the back end in untransformed state.
1513
1514    procedure Expand_N_Assignment_Statement (N : Node_Id) is
1515       Loc  : constant Source_Ptr := Sloc (N);
1516       Lhs  : constant Node_Id    := Name (N);
1517       Rhs  : constant Node_Id    := Expression (N);
1518       Typ  : constant Entity_Id  := Underlying_Type (Etype (Lhs));
1519       Exp  : Node_Id;
1520
1521    begin
1522       --  Special case to check right away, if the Componentwise_Assignment
1523       --  flag is set, this is a reanalysis from the expansion of the primitive
1524       --  assignment procedure for a tagged type, and all we need to do is to
1525       --  expand to assignment of components, because otherwise, we would get
1526       --  infinite recursion (since this looks like a tagged assignment which
1527       --  would normally try to *call* the primitive assignment procedure).
1528
1529       if Componentwise_Assignment (N) then
1530          Expand_Assign_Record (N);
1531          return;
1532       end if;
1533
1534       --  Defend against invalid subscripts on left side if we are in standard
1535       --  validity checking mode. No need to do this if we are checking all
1536       --  subscripts.
1537
1538       --  Note that we do this right away, because there are some early return
1539       --  paths in this procedure, and this is required on all paths.
1540
1541       if Validity_Checks_On
1542         and then Validity_Check_Default
1543         and then not Validity_Check_Subscripts
1544       then
1545          Check_Valid_Lvalue_Subscripts (Lhs);
1546       end if;
1547
1548       --  Ada 2005 (AI-327): Handle assignment to priority of protected object
1549
1550       --  Rewrite an assignment to X'Priority into a run-time call
1551
1552       --   For example:         X'Priority := New_Prio_Expr;
1553       --   ...is expanded into  Set_Ceiling (X._Object, New_Prio_Expr);
1554
1555       --  Note that although X'Priority is notionally an object, it is quite
1556       --  deliberately not defined as an aliased object in the RM. This means
1557       --  that it works fine to rewrite it as a call, without having to worry
1558       --  about complications that would other arise from X'Priority'Access,
1559       --  which is illegal, because of the lack of aliasing.
1560
1561       if Ada_Version >= Ada_2005 then
1562          declare
1563             Call           : Node_Id;
1564             Conctyp        : Entity_Id;
1565             Ent            : Entity_Id;
1566             Subprg         : Entity_Id;
1567             RT_Subprg_Name : Node_Id;
1568
1569          begin
1570             --  Handle chains of renamings
1571
1572             Ent := Name (N);
1573             while Nkind (Ent) in N_Has_Entity
1574               and then Present (Entity (Ent))
1575               and then Present (Renamed_Object (Entity (Ent)))
1576             loop
1577                Ent := Renamed_Object (Entity (Ent));
1578             end loop;
1579
1580             --  The attribute Priority applied to protected objects has been
1581             --  previously expanded into a call to the Get_Ceiling run-time
1582             --  subprogram.
1583
1584             if Nkind (Ent) = N_Function_Call
1585               and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1586                           or else
1587                         Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1588             then
1589                --  Look for the enclosing concurrent type
1590
1591                Conctyp := Current_Scope;
1592                while not Is_Concurrent_Type (Conctyp) loop
1593                   Conctyp := Scope (Conctyp);
1594                end loop;
1595
1596                pragma Assert (Is_Protected_Type (Conctyp));
1597
1598                --  Generate the first actual of the call
1599
1600                Subprg := Current_Scope;
1601                while not Present (Protected_Body_Subprogram (Subprg)) loop
1602                   Subprg := Scope (Subprg);
1603                end loop;
1604
1605                --  Select the appropriate run-time call
1606
1607                if Number_Entries (Conctyp) = 0 then
1608                   RT_Subprg_Name :=
1609                     New_Reference_To (RTE (RE_Set_Ceiling), Loc);
1610                else
1611                   RT_Subprg_Name :=
1612                     New_Reference_To (RTE (RO_PE_Set_Ceiling), Loc);
1613                end if;
1614
1615                Call :=
1616                  Make_Procedure_Call_Statement (Loc,
1617                    Name => RT_Subprg_Name,
1618                    Parameter_Associations => New_List (
1619                      New_Copy_Tree (First (Parameter_Associations (Ent))),
1620                      Relocate_Node (Expression (N))));
1621
1622                Rewrite (N, Call);
1623                Analyze (N);
1624                return;
1625             end if;
1626          end;
1627       end if;
1628
1629       --  Deal with assignment checks unless suppressed
1630
1631       if not Suppress_Assignment_Checks (N) then
1632
1633          --  First deal with generation of range check if required
1634
1635          if Do_Range_Check (Rhs) then
1636             Set_Do_Range_Check (Rhs, False);
1637             Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1638          end if;
1639
1640          --  Then generate predicate check if required
1641
1642          Apply_Predicate_Check (Rhs, Typ);
1643       end if;
1644
1645       --  Check for a special case where a high level transformation is
1646       --  required. If we have either of:
1647
1648       --    P.field := rhs;
1649       --    P (sub) := rhs;
1650
1651       --  where P is a reference to a bit packed array, then we have to unwind
1652       --  the assignment. The exact meaning of being a reference to a bit
1653       --  packed array is as follows:
1654
1655       --    An indexed component whose prefix is a bit packed array is a
1656       --    reference to a bit packed array.
1657
1658       --    An indexed component or selected component whose prefix is a
1659       --    reference to a bit packed array is itself a reference ot a
1660       --    bit packed array.
1661
1662       --  The required transformation is
1663
1664       --     Tnn : prefix_type := P;
1665       --     Tnn.field := rhs;
1666       --     P := Tnn;
1667
1668       --  or
1669
1670       --     Tnn : prefix_type := P;
1671       --     Tnn (subscr) := rhs;
1672       --     P := Tnn;
1673
1674       --  Since P is going to be evaluated more than once, any subscripts
1675       --  in P must have their evaluation forced.
1676
1677       if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1678         and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1679       then
1680          declare
1681             BPAR_Expr : constant Node_Id   := Relocate_Node (Prefix (Lhs));
1682             BPAR_Typ  : constant Entity_Id := Etype (BPAR_Expr);
1683             Tnn       : constant Entity_Id :=
1684                           Make_Temporary (Loc, 'T', BPAR_Expr);
1685
1686          begin
1687             --  Insert the post assignment first, because we want to copy the
1688             --  BPAR_Expr tree before it gets analyzed in the context of the
1689             --  pre assignment. Note that we do not analyze the post assignment
1690             --  yet (we cannot till we have completed the analysis of the pre
1691             --  assignment). As usual, the analysis of this post assignment
1692             --  will happen on its own when we "run into" it after finishing
1693             --  the current assignment.
1694
1695             Insert_After (N,
1696               Make_Assignment_Statement (Loc,
1697                 Name       => New_Copy_Tree (BPAR_Expr),
1698                 Expression => New_Occurrence_Of (Tnn, Loc)));
1699
1700             --  At this stage BPAR_Expr is a reference to a bit packed array
1701             --  where the reference was not expanded in the original tree,
1702             --  since it was on the left side of an assignment. But in the
1703             --  pre-assignment statement (the object definition), BPAR_Expr
1704             --  will end up on the right hand side, and must be reexpanded. To
1705             --  achieve this, we reset the analyzed flag of all selected and
1706             --  indexed components down to the actual indexed component for
1707             --  the packed array.
1708
1709             Exp := BPAR_Expr;
1710             loop
1711                Set_Analyzed (Exp, False);
1712
1713                if Nkind_In
1714                    (Exp, N_Selected_Component, N_Indexed_Component)
1715                then
1716                   Exp := Prefix (Exp);
1717                else
1718                   exit;
1719                end if;
1720             end loop;
1721
1722             --  Now we can insert and analyze the pre-assignment
1723
1724             --  If the right-hand side requires a transient scope, it has
1725             --  already been placed on the stack. However, the declaration is
1726             --  inserted in the tree outside of this scope, and must reflect
1727             --  the proper scope for its variable. This awkward bit is forced
1728             --  by the stricter scope discipline imposed by GCC 2.97.
1729
1730             declare
1731                Uses_Transient_Scope : constant Boolean :=
1732                                         Scope_Is_Transient
1733                                           and then N = Node_To_Be_Wrapped;
1734
1735             begin
1736                if Uses_Transient_Scope then
1737                   Push_Scope (Scope (Current_Scope));
1738                end if;
1739
1740                Insert_Before_And_Analyze (N,
1741                  Make_Object_Declaration (Loc,
1742                    Defining_Identifier => Tnn,
1743                    Object_Definition   => New_Occurrence_Of (BPAR_Typ, Loc),
1744                    Expression          => BPAR_Expr));
1745
1746                if Uses_Transient_Scope then
1747                   Pop_Scope;
1748                end if;
1749             end;
1750
1751             --  Now fix up the original assignment and continue processing
1752
1753             Rewrite (Prefix (Lhs),
1754               New_Occurrence_Of (Tnn, Loc));
1755
1756             --  We do not need to reanalyze that assignment, and we do not need
1757             --  to worry about references to the temporary, but we do need to
1758             --  make sure that the temporary is not marked as a true constant
1759             --  since we now have a generated assignment to it!
1760
1761             Set_Is_True_Constant (Tnn, False);
1762          end;
1763       end if;
1764
1765       --  When we have the appropriate type of aggregate in the expression (it
1766       --  has been determined during analysis of the aggregate by setting the
1767       --  delay flag), let's perform in place assignment and thus avoid
1768       --  creating a temporary.
1769
1770       if Is_Delayed_Aggregate (Rhs) then
1771          Convert_Aggr_In_Assignment (N);
1772          Rewrite (N, Make_Null_Statement (Loc));
1773          Analyze (N);
1774          return;
1775       end if;
1776
1777       --  Apply discriminant check if required. If Lhs is an access type to a
1778       --  designated type with discriminants, we must always check.
1779
1780       if Has_Discriminants (Etype (Lhs)) then
1781
1782          --  Skip discriminant check if change of representation. Will be
1783          --  done when the change of representation is expanded out.
1784
1785          if not Change_Of_Representation (N) then
1786             Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1787          end if;
1788
1789       --  If the type is private without discriminants, and the full type
1790       --  has discriminants (necessarily with defaults) a check may still be
1791       --  necessary if the Lhs is aliased. The private determinants must be
1792       --  visible to build the discriminant constraints.
1793       --  What is a "determinant"???
1794
1795       --  Only an explicit dereference that comes from source indicates
1796       --  aliasing. Access to formals of protected operations and entries
1797       --  create dereferences but are not semantic aliasings.
1798
1799       elsif Is_Private_Type (Etype (Lhs))
1800         and then Has_Discriminants (Typ)
1801         and then Nkind (Lhs) = N_Explicit_Dereference
1802         and then Comes_From_Source (Lhs)
1803       then
1804          declare
1805             Lt : constant Entity_Id := Etype (Lhs);
1806          begin
1807             Set_Etype (Lhs, Typ);
1808             Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1809             Apply_Discriminant_Check (Rhs, Typ, Lhs);
1810             Set_Etype (Lhs, Lt);
1811          end;
1812
1813          --  If the Lhs has a private type with unknown discriminants, it
1814          --  may have a full view with discriminants, but those are nameable
1815          --  only in the underlying type, so convert the Rhs to it before
1816          --  potential checking.
1817
1818       elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1819         and then Has_Discriminants (Typ)
1820       then
1821          Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1822          Apply_Discriminant_Check (Rhs, Typ, Lhs);
1823
1824       --  In the access type case, we need the same discriminant check, and
1825       --  also range checks if we have an access to constrained array.
1826
1827       elsif Is_Access_Type (Etype (Lhs))
1828         and then Is_Constrained (Designated_Type (Etype (Lhs)))
1829       then
1830          if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1831
1832             --  Skip discriminant check if change of representation. Will be
1833             --  done when the change of representation is expanded out.
1834
1835             if not Change_Of_Representation (N) then
1836                Apply_Discriminant_Check (Rhs, Etype (Lhs));
1837             end if;
1838
1839          elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1840             Apply_Range_Check (Rhs, Etype (Lhs));
1841
1842             if Is_Constrained (Etype (Lhs)) then
1843                Apply_Length_Check (Rhs, Etype (Lhs));
1844             end if;
1845
1846             if Nkind (Rhs) = N_Allocator then
1847                declare
1848                   Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1849                   C_Es       : Check_Result;
1850
1851                begin
1852                   C_Es :=
1853                     Get_Range_Checks
1854                       (Lhs,
1855                        Target_Typ,
1856                        Etype (Designated_Type (Etype (Lhs))));
1857
1858                   Insert_Range_Checks
1859                     (C_Es,
1860                      N,
1861                      Target_Typ,
1862                      Sloc (Lhs),
1863                      Lhs);
1864                end;
1865             end if;
1866          end if;
1867
1868       --  Apply range check for access type case
1869
1870       elsif Is_Access_Type (Etype (Lhs))
1871         and then Nkind (Rhs) = N_Allocator
1872         and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1873       then
1874          Analyze_And_Resolve (Expression (Rhs));
1875          Apply_Range_Check
1876            (Expression (Rhs), Designated_Type (Etype (Lhs)));
1877       end if;
1878
1879       --  Ada 2005 (AI-231): Generate the run-time check
1880
1881       if Is_Access_Type (Typ)
1882         and then Can_Never_Be_Null (Etype (Lhs))
1883         and then not Can_Never_Be_Null (Etype (Rhs))
1884       then
1885          Apply_Constraint_Check (Rhs, Etype (Lhs));
1886       end if;
1887
1888       --  Case of assignment to a bit packed array element
1889
1890       if Nkind (Lhs) = N_Indexed_Component
1891         and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1892       then
1893          Expand_Bit_Packed_Element_Set (N);
1894          return;
1895
1896       --  Build-in-place function call case. Note that we're not yet doing
1897       --  build-in-place for user-written assignment statements (the assignment
1898       --  here came from an aggregate.)
1899
1900       elsif Ada_Version >= Ada_2005
1901         and then Is_Build_In_Place_Function_Call (Rhs)
1902       then
1903          Make_Build_In_Place_Call_In_Assignment (N, Rhs);
1904
1905       elsif Is_Tagged_Type (Typ) and then Is_Value_Type (Etype (Lhs)) then
1906
1907          --  Nothing to do for valuetypes
1908          --  ??? Set_Scope_Is_Transient (False);
1909
1910          return;
1911
1912       elsif Is_Tagged_Type (Typ)
1913         or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
1914       then
1915          Tagged_Case : declare
1916             L                   : List_Id := No_List;
1917             Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
1918
1919          begin
1920             --  In the controlled case, we ensure that function calls are
1921             --  evaluated before finalizing the target. In all cases, it makes
1922             --  the expansion easier if the side-effects are removed first.
1923
1924             Remove_Side_Effects (Lhs);
1925             Remove_Side_Effects (Rhs);
1926
1927             --  Avoid recursion in the mechanism
1928
1929             Set_Analyzed (N);
1930
1931             --  If dispatching assignment, we need to dispatch to _assign
1932
1933             if Is_Class_Wide_Type (Typ)
1934
1935                --  If the type is tagged, we may as well use the predefined
1936                --  primitive assignment. This avoids inlining a lot of code
1937                --  and in the class-wide case, the assignment is replaced by
1938                --  dispatch call to _assign. Note that this cannot be done when
1939                --  discriminant checks are locally suppressed (as in extension
1940                --  aggregate expansions) because otherwise the discriminant
1941                --  check will be performed within the _assign call. It is also
1942                --  suppressed for assignments created by the expander that
1943                --  correspond to initializations, where we do want to copy the
1944                --  tag (No_Ctrl_Actions flag set True) by the expander and we
1945                --  do not need to mess with tags ever (Expand_Ctrl_Actions flag
1946                --  is set True in this case).
1947
1948                or else (Is_Tagged_Type (Typ)
1949                          and then not Is_Value_Type (Etype (Lhs))
1950                          and then Chars (Current_Scope) /= Name_uAssign
1951                          and then Expand_Ctrl_Actions
1952                          and then not Discriminant_Checks_Suppressed (Empty))
1953             then
1954                --  Fetch the primitive op _assign and proper type to call it.
1955                --  Because of possible conflicts between private and full view,
1956                --  fetch the proper type directly from the operation profile.
1957
1958                declare
1959                   Op    : constant Entity_Id :=
1960                             Find_Prim_Op (Typ, Name_uAssign);
1961                   F_Typ : Entity_Id := Etype (First_Formal (Op));
1962
1963                begin
1964                   --  If the assignment is dispatching, make sure to use the
1965                   --  proper type.
1966
1967                   if Is_Class_Wide_Type (Typ) then
1968                      F_Typ := Class_Wide_Type (F_Typ);
1969                   end if;
1970
1971                   L := New_List;
1972
1973                   --  In case of assignment to a class-wide tagged type, before
1974                   --  the assignment we generate run-time check to ensure that
1975                   --  the tags of source and target match.
1976
1977                   if Is_Class_Wide_Type (Typ)
1978                     and then Is_Tagged_Type (Typ)
1979                     and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
1980                   then
1981                      Append_To (L,
1982                        Make_Raise_Constraint_Error (Loc,
1983                          Condition =>
1984                              Make_Op_Ne (Loc,
1985                                Left_Opnd =>
1986                                  Make_Selected_Component (Loc,
1987                                    Prefix        => Duplicate_Subexpr (Lhs),
1988                                    Selector_Name =>
1989                                      Make_Identifier (Loc, Name_uTag)),
1990                                Right_Opnd =>
1991                                  Make_Selected_Component (Loc,
1992                                    Prefix        => Duplicate_Subexpr (Rhs),
1993                                    Selector_Name =>
1994                                      Make_Identifier (Loc, Name_uTag))),
1995                          Reason => CE_Tag_Check_Failed));
1996                   end if;
1997
1998                   declare
1999                      Left_N  : Node_Id := Duplicate_Subexpr (Lhs);
2000                      Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2001
2002                   begin
2003                      --  In order to dispatch the call to _assign the type of
2004                      --  the actuals must match. Add conversion (if required).
2005
2006                      if Etype (Lhs) /= F_Typ then
2007                         Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2008                      end if;
2009
2010                      if Etype (Rhs) /= F_Typ then
2011                         Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2012                      end if;
2013
2014                      Append_To (L,
2015                        Make_Procedure_Call_Statement (Loc,
2016                          Name => New_Reference_To (Op, Loc),
2017                          Parameter_Associations => New_List (
2018                            Node1 => Left_N,
2019                            Node2 => Right_N)));
2020                   end;
2021                end;
2022
2023             else
2024                L := Make_Tag_Ctrl_Assignment (N);
2025
2026                --  We can't afford to have destructive Finalization Actions in
2027                --  the Self assignment case, so if the target and the source
2028                --  are not obviously different, code is generated to avoid the
2029                --  self assignment case:
2030
2031                --    if lhs'address /= rhs'address then
2032                --       <code for controlled and/or tagged assignment>
2033                --    end if;
2034
2035                --  Skip this if Restriction (No_Finalization) is active
2036
2037                if not Statically_Different (Lhs, Rhs)
2038                  and then Expand_Ctrl_Actions
2039                  and then not Restriction_Active (No_Finalization)
2040                then
2041                   L := New_List (
2042                     Make_Implicit_If_Statement (N,
2043                       Condition =>
2044                         Make_Op_Ne (Loc,
2045                           Left_Opnd =>
2046                             Make_Attribute_Reference (Loc,
2047                               Prefix         => Duplicate_Subexpr (Lhs),
2048                               Attribute_Name => Name_Address),
2049
2050                            Right_Opnd =>
2051                             Make_Attribute_Reference (Loc,
2052                               Prefix         => Duplicate_Subexpr (Rhs),
2053                               Attribute_Name => Name_Address)),
2054
2055                       Then_Statements => L));
2056                end if;
2057
2058                --  We need to set up an exception handler for implementing
2059                --  7.6.1(18). The remaining adjustments are tackled by the
2060                --  implementation of adjust for record_controllers (see
2061                --  s-finimp.adb).
2062
2063                --  This is skipped if we have no finalization
2064
2065                if Expand_Ctrl_Actions
2066                  and then not Restriction_Active (No_Finalization)
2067                then
2068                   L := New_List (
2069                     Make_Block_Statement (Loc,
2070                       Handled_Statement_Sequence =>
2071                         Make_Handled_Sequence_Of_Statements (Loc,
2072                           Statements => L,
2073                           Exception_Handlers => New_List (
2074                             Make_Handler_For_Ctrl_Operation (Loc)))));
2075                end if;
2076             end if;
2077
2078             Rewrite (N,
2079               Make_Block_Statement (Loc,
2080                 Handled_Statement_Sequence =>
2081                   Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2082
2083             --  If no restrictions on aborts, protect the whole assignment
2084             --  for controlled objects as per 9.8(11).
2085
2086             if Needs_Finalization (Typ)
2087               and then Expand_Ctrl_Actions
2088               and then Abort_Allowed
2089             then
2090                declare
2091                   Blk : constant Entity_Id :=
2092                           New_Internal_Entity
2093                             (E_Block, Current_Scope, Sloc (N), 'B');
2094
2095                begin
2096                   Set_Scope (Blk, Current_Scope);
2097                   Set_Etype (Blk, Standard_Void_Type);
2098                   Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2099
2100                   Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2101                   Set_At_End_Proc (Handled_Statement_Sequence (N),
2102                     New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
2103                   Expand_At_End_Handler
2104                     (Handled_Statement_Sequence (N), Blk);
2105                end;
2106             end if;
2107
2108             --  N has been rewritten to a block statement for which it is
2109             --  known by construction that no checks are necessary: analyze
2110             --  it with all checks suppressed.
2111
2112             Analyze (N, Suppress => All_Checks);
2113             return;
2114          end Tagged_Case;
2115
2116       --  Array types
2117
2118       elsif Is_Array_Type (Typ) then
2119          declare
2120             Actual_Rhs : Node_Id := Rhs;
2121
2122          begin
2123             while Nkind_In (Actual_Rhs, N_Type_Conversion,
2124                                         N_Qualified_Expression)
2125             loop
2126                Actual_Rhs := Expression (Actual_Rhs);
2127             end loop;
2128
2129             Expand_Assign_Array (N, Actual_Rhs);
2130             return;
2131          end;
2132
2133       --  Record types
2134
2135       elsif Is_Record_Type (Typ) then
2136          Expand_Assign_Record (N);
2137          return;
2138
2139       --  Scalar types. This is where we perform the processing related to the
2140       --  requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2141       --  scalar values.
2142
2143       elsif Is_Scalar_Type (Typ) then
2144
2145          --  Case where right side is known valid
2146
2147          if Expr_Known_Valid (Rhs) then
2148
2149             --  Here the right side is valid, so it is fine. The case to deal
2150             --  with is when the left side is a local variable reference whose
2151             --  value is not currently known to be valid. If this is the case,
2152             --  and the assignment appears in an unconditional context, then
2153             --  we can mark the left side as now being valid if one of these
2154             --  conditions holds:
2155
2156             --    The expression of the right side has Do_Range_Check set so
2157             --    that we know a range check will be performed. Note that it
2158             --    can be the case that a range check is omitted because we
2159             --    make the assumption that we can assume validity for operands
2160             --    appearing in the right side in determining whether a range
2161             --    check is required
2162
2163             --    The subtype of the right side matches the subtype of the
2164             --    left side. In this case, even though we have not checked
2165             --    the range of the right side, we know it is in range of its
2166             --    subtype if the expression is valid.
2167
2168             if Is_Local_Variable_Reference (Lhs)
2169               and then not Is_Known_Valid (Entity (Lhs))
2170               and then In_Unconditional_Context (N)
2171             then
2172                if Do_Range_Check (Rhs)
2173                  or else Etype (Lhs) = Etype (Rhs)
2174                then
2175                   Set_Is_Known_Valid (Entity (Lhs), True);
2176                end if;
2177             end if;
2178
2179          --  Case where right side may be invalid in the sense of the RM
2180          --  reference above. The RM does not require that we check for the
2181          --  validity on an assignment, but it does require that the assignment
2182          --  of an invalid value not cause erroneous behavior.
2183
2184          --  The general approach in GNAT is to use the Is_Known_Valid flag
2185          --  to avoid the need for validity checking on assignments. However
2186          --  in some cases, we have to do validity checking in order to make
2187          --  sure that the setting of this flag is correct.
2188
2189          else
2190             --  Validate right side if we are validating copies
2191
2192             if Validity_Checks_On
2193               and then Validity_Check_Copies
2194             then
2195                --  Skip this if left hand side is an array or record component
2196                --  and elementary component validity checks are suppressed.
2197
2198                if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2199                  and then not Validity_Check_Components
2200                then
2201                   null;
2202                else
2203                   Ensure_Valid (Rhs);
2204                end if;
2205
2206                --  We can propagate this to the left side where appropriate
2207
2208                if Is_Local_Variable_Reference (Lhs)
2209                  and then not Is_Known_Valid (Entity (Lhs))
2210                  and then In_Unconditional_Context (N)
2211                then
2212                   Set_Is_Known_Valid (Entity (Lhs), True);
2213                end if;
2214
2215             --  Otherwise check to see what should be done
2216
2217             --  If left side is a local variable, then we just set its flag to
2218             --  indicate that its value may no longer be valid, since we are
2219             --  copying a potentially invalid value.
2220
2221             elsif Is_Local_Variable_Reference (Lhs) then
2222                Set_Is_Known_Valid (Entity (Lhs), False);
2223
2224             --  Check for case of a nonlocal variable on the left side which
2225             --  is currently known to be valid. In this case, we simply ensure
2226             --  that the right side is valid. We only play the game of copying
2227             --  validity status for local variables, since we are doing this
2228             --  statically, not by tracing the full flow graph.
2229
2230             elsif Is_Entity_Name (Lhs)
2231               and then Is_Known_Valid (Entity (Lhs))
2232             then
2233                --  Note: If Validity_Checking mode is set to none, we ignore
2234                --  the Ensure_Valid call so don't worry about that case here.
2235
2236                Ensure_Valid (Rhs);
2237
2238             --  In all other cases, we can safely copy an invalid value without
2239             --  worrying about the status of the left side. Since it is not a
2240             --  variable reference it will not be considered
2241             --  as being known to be valid in any case.
2242
2243             else
2244                null;
2245             end if;
2246          end if;
2247       end if;
2248
2249    exception
2250       when RE_Not_Available =>
2251          return;
2252    end Expand_N_Assignment_Statement;
2253
2254    ------------------------------
2255    -- Expand_N_Block_Statement --
2256    ------------------------------
2257
2258    --  Encode entity names defined in block statement
2259
2260    procedure Expand_N_Block_Statement (N : Node_Id) is
2261    begin
2262       Qualify_Entity_Names (N);
2263    end Expand_N_Block_Statement;
2264
2265    -----------------------------
2266    -- Expand_N_Case_Statement --
2267    -----------------------------
2268
2269    procedure Expand_N_Case_Statement (N : Node_Id) is
2270       Loc    : constant Source_Ptr := Sloc (N);
2271       Expr   : constant Node_Id    := Expression (N);
2272       Alt    : Node_Id;
2273       Len    : Nat;
2274       Cond   : Node_Id;
2275       Choice : Node_Id;
2276       Chlist : List_Id;
2277
2278    begin
2279       --  Check for the situation where we know at compile time which branch
2280       --  will be taken
2281
2282       if Compile_Time_Known_Value (Expr) then
2283          Alt := Find_Static_Alternative (N);
2284
2285          --  Move statements from this alternative after the case statement.
2286          --  They are already analyzed, so will be skipped by the analyzer.
2287
2288          Insert_List_After (N, Statements (Alt));
2289
2290          --  That leaves the case statement as a shell. So now we can kill all
2291          --  other alternatives in the case statement.
2292
2293          Kill_Dead_Code (Expression (N));
2294
2295          declare
2296             A : Node_Id;
2297
2298          begin
2299             --  Loop through case alternatives, skipping pragmas, and skipping
2300             --  the one alternative that we select (and therefore retain).
2301
2302             A := First (Alternatives (N));
2303             while Present (A) loop
2304                if A /= Alt
2305                  and then Nkind (A) = N_Case_Statement_Alternative
2306                then
2307                   Kill_Dead_Code (Statements (A), Warn_On_Deleted_Code);
2308                end if;
2309
2310                Next (A);
2311             end loop;
2312          end;
2313
2314          Rewrite (N, Make_Null_Statement (Loc));
2315          return;
2316       end if;
2317
2318       --  Here if the choice is not determined at compile time
2319
2320       declare
2321          Last_Alt : constant Node_Id := Last (Alternatives (N));
2322
2323          Others_Present : Boolean;
2324          Others_Node    : Node_Id;
2325
2326          Then_Stms : List_Id;
2327          Else_Stms : List_Id;
2328
2329       begin
2330          if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2331             Others_Present := True;
2332             Others_Node    := Last_Alt;
2333          else
2334             Others_Present := False;
2335          end if;
2336
2337          --  First step is to worry about possible invalid argument. The RM
2338          --  requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2339          --  outside the base range), then Constraint_Error must be raised.
2340
2341          --  Case of validity check required (validity checks are on, the
2342          --  expression is not known to be valid, and the case statement
2343          --  comes from source -- no need to validity check internally
2344          --  generated case statements).
2345
2346          if Validity_Check_Default then
2347             Ensure_Valid (Expr);
2348          end if;
2349
2350          --  If there is only a single alternative, just replace it with the
2351          --  sequence of statements since obviously that is what is going to
2352          --  be executed in all cases.
2353
2354          Len := List_Length (Alternatives (N));
2355
2356          if Len = 1 then
2357             --  We still need to evaluate the expression if it has any
2358             --  side effects.
2359
2360             Remove_Side_Effects (Expression (N));
2361
2362             Insert_List_After (N, Statements (First (Alternatives (N))));
2363
2364             --  That leaves the case statement as a shell. The alternative that
2365             --  will be executed is reset to a null list. So now we can kill
2366             --  the entire case statement.
2367
2368             Kill_Dead_Code (Expression (N));
2369             Rewrite (N, Make_Null_Statement (Loc));
2370             return;
2371          end if;
2372
2373          --  An optimization. If there are only two alternatives, and only
2374          --  a single choice, then rewrite the whole case statement as an
2375          --  if statement, since this can result in subsequent optimizations.
2376          --  This helps not only with case statements in the source of a
2377          --  simple form, but also with generated code (discriminant check
2378          --  functions in particular)
2379
2380          if Len = 2 then
2381             Chlist := Discrete_Choices (First (Alternatives (N)));
2382
2383             if List_Length (Chlist) = 1 then
2384                Choice := First (Chlist);
2385
2386                Then_Stms := Statements (First (Alternatives (N)));
2387                Else_Stms := Statements (Last  (Alternatives (N)));
2388
2389                --  For TRUE, generate "expression", not expression = true
2390
2391                if Nkind (Choice) = N_Identifier
2392                  and then Entity (Choice) = Standard_True
2393                then
2394                   Cond := Expression (N);
2395
2396                --  For FALSE, generate "expression" and switch then/else
2397
2398                elsif Nkind (Choice) = N_Identifier
2399                  and then Entity (Choice) = Standard_False
2400                then
2401                   Cond := Expression (N);
2402                   Else_Stms := Statements (First (Alternatives (N)));
2403                   Then_Stms := Statements (Last  (Alternatives (N)));
2404
2405                --  For a range, generate "expression in range"
2406
2407                elsif Nkind (Choice) = N_Range
2408                  or else (Nkind (Choice) = N_Attribute_Reference
2409                            and then Attribute_Name (Choice) = Name_Range)
2410                  or else (Is_Entity_Name (Choice)
2411                            and then Is_Type (Entity (Choice)))
2412                  or else Nkind (Choice) = N_Subtype_Indication
2413                then
2414                   Cond :=
2415                     Make_In (Loc,
2416                       Left_Opnd  => Expression (N),
2417                       Right_Opnd => Relocate_Node (Choice));
2418
2419                --  For any other subexpression "expression = value"
2420
2421                else
2422                   Cond :=
2423                     Make_Op_Eq (Loc,
2424                       Left_Opnd  => Expression (N),
2425                       Right_Opnd => Relocate_Node (Choice));
2426                end if;
2427
2428                --  Now rewrite the case as an IF
2429
2430                Rewrite (N,
2431                  Make_If_Statement (Loc,
2432                    Condition => Cond,
2433                    Then_Statements => Then_Stms,
2434                    Else_Statements => Else_Stms));
2435                Analyze (N);
2436                return;
2437             end if;
2438          end if;
2439
2440          --  If the last alternative is not an Others choice, replace it with
2441          --  an N_Others_Choice. Note that we do not bother to call Analyze on
2442          --  the modified case statement, since it's only effect would be to
2443          --  compute the contents of the Others_Discrete_Choices which is not
2444          --  needed by the back end anyway.
2445
2446          --  The reason we do this is that the back end always needs some
2447          --  default for a switch, so if we have not supplied one in the
2448          --  processing above for validity checking, then we need to supply
2449          --  one here.
2450
2451          if not Others_Present then
2452             Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2453             Set_Others_Discrete_Choices
2454               (Others_Node, Discrete_Choices (Last_Alt));
2455             Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2456          end if;
2457       end;
2458    end Expand_N_Case_Statement;
2459
2460    -----------------------------
2461    -- Expand_N_Exit_Statement --
2462    -----------------------------
2463
2464    --  The only processing required is to deal with a possible C/Fortran
2465    --  boolean value used as the condition for the exit statement.
2466
2467    procedure Expand_N_Exit_Statement (N : Node_Id) is
2468    begin
2469       Adjust_Condition (Condition (N));
2470    end Expand_N_Exit_Statement;
2471
2472    -----------------------------
2473    -- Expand_N_Goto_Statement --
2474    -----------------------------
2475
2476    --  Add poll before goto if polling active
2477
2478    procedure Expand_N_Goto_Statement (N : Node_Id) is
2479    begin
2480       Generate_Poll_Call (N);
2481    end Expand_N_Goto_Statement;
2482
2483    ---------------------------
2484    -- Expand_N_If_Statement --
2485    ---------------------------
2486
2487    --  First we deal with the case of C and Fortran convention boolean values,
2488    --  with zero/non-zero semantics.
2489
2490    --  Second, we deal with the obvious rewriting for the cases where the
2491    --  condition of the IF is known at compile time to be True or False.
2492
2493    --  Third, we remove elsif parts which have non-empty Condition_Actions and
2494    --  rewrite as independent if statements. For example:
2495
2496    --     if x then xs
2497    --     elsif y then ys
2498    --     ...
2499    --     end if;
2500
2501    --  becomes
2502    --
2503    --     if x then xs
2504    --     else
2505    --        <<condition actions of y>>
2506    --        if y then ys
2507    --        ...
2508    --        end if;
2509    --     end if;
2510
2511    --  This rewriting is needed if at least one elsif part has a non-empty
2512    --  Condition_Actions list. We also do the same processing if there is a
2513    --  constant condition in an elsif part (in conjunction with the first
2514    --  processing step mentioned above, for the recursive call made to deal
2515    --  with the created inner if, this deals with properly optimizing the
2516    --  cases of constant elsif conditions).
2517
2518    procedure Expand_N_If_Statement (N : Node_Id) is
2519       Loc    : constant Source_Ptr := Sloc (N);
2520       Hed    : Node_Id;
2521       E      : Node_Id;
2522       New_If : Node_Id;
2523
2524       Warn_If_Deleted : constant Boolean :=
2525                           Warn_On_Deleted_Code and then Comes_From_Source (N);
2526       --  Indicates whether we want warnings when we delete branches of the
2527       --  if statement based on constant condition analysis. We never want
2528       --  these warnings for expander generated code.
2529
2530    begin
2531       Adjust_Condition (Condition (N));
2532
2533       --  The following loop deals with constant conditions for the IF. We
2534       --  need a loop because as we eliminate False conditions, we grab the
2535       --  first elsif condition and use it as the primary condition.
2536
2537       while Compile_Time_Known_Value (Condition (N)) loop
2538
2539          --  If condition is True, we can simply rewrite the if statement now
2540          --  by replacing it by the series of then statements.
2541
2542          if Is_True (Expr_Value (Condition (N))) then
2543
2544             --  All the else parts can be killed
2545
2546             Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
2547             Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
2548
2549             Hed := Remove_Head (Then_Statements (N));
2550             Insert_List_After (N, Then_Statements (N));
2551             Rewrite (N, Hed);
2552             return;
2553
2554          --  If condition is False, then we can delete the condition and
2555          --  the Then statements
2556
2557          else
2558             --  We do not delete the condition if constant condition warnings
2559             --  are enabled, since otherwise we end up deleting the desired
2560             --  warning. Of course the backend will get rid of this True/False
2561             --  test anyway, so nothing is lost here.
2562
2563             if not Constant_Condition_Warnings then
2564                Kill_Dead_Code (Condition (N));
2565             end if;
2566
2567             Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
2568
2569             --  If there are no elsif statements, then we simply replace the
2570             --  entire if statement by the sequence of else statements.
2571
2572             if No (Elsif_Parts (N)) then
2573                if No (Else_Statements (N))
2574                  or else Is_Empty_List (Else_Statements (N))
2575                then
2576                   Rewrite (N,
2577                     Make_Null_Statement (Sloc (N)));
2578                else
2579                   Hed := Remove_Head (Else_Statements (N));
2580                   Insert_List_After (N, Else_Statements (N));
2581                   Rewrite (N, Hed);
2582                end if;
2583
2584                return;
2585
2586             --  If there are elsif statements, the first of them becomes the
2587             --  if/then section of the rebuilt if statement This is the case
2588             --  where we loop to reprocess this copied condition.
2589
2590             else
2591                Hed := Remove_Head (Elsif_Parts (N));
2592                Insert_Actions      (N, Condition_Actions (Hed));
2593                Set_Condition       (N, Condition (Hed));
2594                Set_Then_Statements (N, Then_Statements (Hed));
2595
2596                --  Hed might have been captured as the condition determining
2597                --  the current value for an entity. Now it is detached from
2598                --  the tree, so a Current_Value pointer in the condition might
2599                --  need to be updated.
2600
2601                Set_Current_Value_Condition (N);
2602
2603                if Is_Empty_List (Elsif_Parts (N)) then
2604                   Set_Elsif_Parts (N, No_List);
2605                end if;
2606             end if;
2607          end if;
2608       end loop;
2609
2610       --  Loop through elsif parts, dealing with constant conditions and
2611       --  possible expression actions that are present.
2612
2613       if Present (Elsif_Parts (N)) then
2614          E := First (Elsif_Parts (N));
2615          while Present (E) loop
2616             Adjust_Condition (Condition (E));
2617
2618             --  If there are condition actions, then rewrite the if statement
2619             --  as indicated above. We also do the same rewrite for a True or
2620             --  False condition. The further processing of this constant
2621             --  condition is then done by the recursive call to expand the
2622             --  newly created if statement
2623
2624             if Present (Condition_Actions (E))
2625               or else Compile_Time_Known_Value (Condition (E))
2626             then
2627                --  Note this is not an implicit if statement, since it is part
2628                --  of an explicit if statement in the source (or of an implicit
2629                --  if statement that has already been tested).
2630
2631                New_If :=
2632                  Make_If_Statement (Sloc (E),
2633                    Condition       => Condition (E),
2634                    Then_Statements => Then_Statements (E),
2635                    Elsif_Parts     => No_List,
2636                    Else_Statements => Else_Statements (N));
2637
2638                --  Elsif parts for new if come from remaining elsif's of parent
2639
2640                while Present (Next (E)) loop
2641                   if No (Elsif_Parts (New_If)) then
2642                      Set_Elsif_Parts (New_If, New_List);
2643                   end if;
2644
2645                   Append (Remove_Next (E), Elsif_Parts (New_If));
2646                end loop;
2647
2648                Set_Else_Statements (N, New_List (New_If));
2649
2650                if Present (Condition_Actions (E)) then
2651                   Insert_List_Before (New_If, Condition_Actions (E));
2652                end if;
2653
2654                Remove (E);
2655
2656                if Is_Empty_List (Elsif_Parts (N)) then
2657                   Set_Elsif_Parts (N, No_List);
2658                end if;
2659
2660                Analyze (New_If);
2661                return;
2662
2663             --  No special processing for that elsif part, move to next
2664
2665             else
2666                Next (E);
2667             end if;
2668          end loop;
2669       end if;
2670
2671       --  Some more optimizations applicable if we still have an IF statement
2672
2673       if Nkind (N) /= N_If_Statement then
2674          return;
2675       end if;
2676
2677       --  Another optimization, special cases that can be simplified
2678
2679       --     if expression then
2680       --        return true;
2681       --     else
2682       --        return false;
2683       --     end if;
2684
2685       --  can be changed to:
2686
2687       --     return expression;
2688
2689       --  and
2690
2691       --     if expression then
2692       --        return false;
2693       --     else
2694       --        return true;
2695       --     end if;
2696
2697       --  can be changed to:
2698
2699       --     return not (expression);
2700
2701       --  Only do these optimizations if we are at least at -O1 level and
2702       --  do not do them if control flow optimizations are suppressed.
2703
2704       if Optimization_Level > 0
2705         and then not Opt.Suppress_Control_Flow_Optimizations
2706       then
2707          if Nkind (N) = N_If_Statement
2708            and then No (Elsif_Parts (N))
2709            and then Present (Else_Statements (N))
2710            and then List_Length (Then_Statements (N)) = 1
2711            and then List_Length (Else_Statements (N)) = 1
2712          then
2713             declare
2714                Then_Stm : constant Node_Id := First (Then_Statements (N));
2715                Else_Stm : constant Node_Id := First (Else_Statements (N));
2716
2717             begin
2718                if Nkind (Then_Stm) = N_Simple_Return_Statement
2719                     and then
2720                   Nkind (Else_Stm) = N_Simple_Return_Statement
2721                then
2722                   declare
2723                      Then_Expr : constant Node_Id := Expression (Then_Stm);
2724                      Else_Expr : constant Node_Id := Expression (Else_Stm);
2725
2726                   begin
2727                      if Nkind (Then_Expr) = N_Identifier
2728                           and then
2729                         Nkind (Else_Expr) = N_Identifier
2730                      then
2731                         if Entity (Then_Expr) = Standard_True
2732                           and then Entity (Else_Expr) = Standard_False
2733                         then
2734                            Rewrite (N,
2735                              Make_Simple_Return_Statement (Loc,
2736                                Expression => Relocate_Node (Condition (N))));
2737                            Analyze (N);
2738                            return;
2739
2740                         elsif Entity (Then_Expr) = Standard_False
2741                           and then Entity (Else_Expr) = Standard_True
2742                         then
2743                            Rewrite (N,
2744                              Make_Simple_Return_Statement (Loc,
2745                                Expression =>
2746                                  Make_Op_Not (Loc,
2747                                    Right_Opnd =>
2748                                      Relocate_Node (Condition (N)))));
2749                            Analyze (N);
2750                            return;
2751                         end if;
2752                      end if;
2753                   end;
2754                end if;
2755             end;
2756          end if;
2757       end if;
2758    end Expand_N_If_Statement;
2759
2760    --------------------------
2761    -- Expand_Iterator_Loop --
2762    --------------------------
2763
2764    procedure Expand_Iterator_Loop (N : Node_Id) is
2765       Loc        : constant Source_Ptr := Sloc (N);
2766       Isc        : constant Node_Id    := Iteration_Scheme (N);
2767       I_Spec     : constant Node_Id    := Iterator_Specification (Isc);
2768       Id         : constant Entity_Id  := Defining_Identifier (I_Spec);
2769       Container  : constant Entity_Id  :=  Entity (Name (I_Spec));
2770       Typ        : constant Entity_Id  := Etype (Container);
2771
2772       Cursor   : Entity_Id;
2773       New_Loop : Node_Id;
2774       Stats    : List_Id;
2775
2776    begin
2777       if Is_Array_Type (Typ) then
2778          if Of_Present (I_Spec) then
2779             Cursor := Make_Temporary (Loc, 'C');
2780
2781             --  for Elem of Arr loop ...
2782
2783             declare
2784                Decl : constant Node_Id :=
2785                         Make_Object_Renaming_Declaration (Loc,
2786                           Defining_Identifier => Id,
2787                           Subtype_Mark        =>
2788                             New_Occurrence_Of (Component_Type (Typ), Loc),
2789                           Name                =>
2790                             Make_Indexed_Component (Loc,
2791                               Prefix      =>
2792                                 New_Occurrence_Of (Container, Loc),
2793                               Expressions =>
2794                                 New_List (New_Occurrence_Of (Cursor, Loc))));
2795             begin
2796                Stats := Statements (N);
2797                Prepend (Decl, Stats);
2798
2799                New_Loop :=
2800                  Make_Loop_Statement (Loc,
2801                    Iteration_Scheme =>
2802                      Make_Iteration_Scheme (Loc,
2803                        Loop_Parameter_Specification =>
2804                          Make_Loop_Parameter_Specification (Loc,
2805                            Defining_Identifier         => Cursor,
2806                            Discrete_Subtype_Definition =>
2807                               Make_Attribute_Reference (Loc,
2808                                 Prefix         =>
2809                                   New_Occurrence_Of (Container, Loc),
2810                                 Attribute_Name => Name_Range),
2811                            Reverse_Present => Reverse_Present (I_Spec))),
2812                    Statements       => Stats,
2813                    End_Label        => Empty);
2814             end;
2815
2816          else
2817             --  for Index in Array loop ...
2818
2819             --  The cursor (index into the array) is the source Id
2820
2821             Cursor := Id;
2822             New_Loop :=
2823               Make_Loop_Statement (Loc,
2824                 Iteration_Scheme =>
2825                   Make_Iteration_Scheme (Loc,
2826                     Loop_Parameter_Specification =>
2827                       Make_Loop_Parameter_Specification (Loc,
2828                         Defining_Identifier         => Cursor,
2829                         Discrete_Subtype_Definition =>
2830                            Make_Attribute_Reference (Loc,
2831                              Prefix         =>
2832                                New_Occurrence_Of (Container, Loc),
2833                              Attribute_Name => Name_Range),
2834                         Reverse_Present => Reverse_Present (I_Spec))),
2835                 Statements       => Statements (N),
2836                 End_Label        => Empty);
2837          end if;
2838
2839       --  Iterators over containers
2840
2841       else
2842          --  In both cases these require a cursor of the proper type
2843
2844          --    Cursor : P.Cursor_Type := Container.First;
2845          --    while Cursor /= P.No_Element loop
2846
2847          --       Obj : P.Element_Type renames Element (Cursor);
2848          --       --  For the "of" form, the element name renames the element
2849          --       --  designated by the cursor.
2850
2851          --       Statements;
2852          --       P.Next (Cursor);
2853          --    end loop;
2854
2855          --  with the obvious replacements if "reverse" is specified.
2856
2857          declare
2858             Element_Type  : constant Entity_Id := Etype (Id);
2859             Pack          : constant Entity_Id := Scope (Etype (Container));
2860             Name_Init     : Name_Id;
2861             Name_Step     : Name_Id;
2862             Cond          : Node_Id;
2863             Cursor_Decl   : Node_Id;
2864             Renaming_Decl : Node_Id;
2865
2866          begin
2867             Stats := Statements (N);
2868
2869             if Of_Present (I_Spec) then
2870                Cursor := Make_Temporary (Loc, 'C');
2871             else
2872                Cursor := Id;
2873             end if;
2874
2875             if Reverse_Present (I_Spec) then
2876
2877                --  Must verify that the container has a reverse iterator ???
2878
2879                Name_Init := Name_Last;
2880                Name_Step := Name_Previous;
2881
2882             else
2883                Name_Init := Name_First;
2884                Name_Step := Name_Next;
2885             end if;
2886
2887             --  C : Cursor_Type := Container.First;
2888
2889             Cursor_Decl :=
2890               Make_Object_Declaration (Loc,
2891                 Defining_Identifier => Cursor,
2892                 Object_Definition   =>
2893                   Make_Selected_Component (Loc,
2894                     Prefix        => New_Occurrence_Of (Pack, Loc),
2895                     Selector_Name => Make_Identifier (Loc, Name_Cursor)),
2896                 Expression =>
2897                   Make_Selected_Component (Loc,
2898                     Prefix        => New_Occurrence_Of (Container, Loc),
2899                     Selector_Name => Make_Identifier (Loc, Name_Init)));
2900
2901             Insert_Action (N, Cursor_Decl);
2902
2903             --  while C /= No_Element loop
2904
2905             Cond := Make_Op_Ne (Loc,
2906                       Left_Opnd  => New_Occurrence_Of (Cursor, Loc),
2907                       Right_Opnd => Make_Selected_Component (Loc,
2908                          Prefix        => New_Occurrence_Of (Pack, Loc),
2909                          Selector_Name =>
2910                            Make_Identifier (Loc, Name_No_Element)));
2911
2912             if Of_Present (I_Spec) then
2913
2914                --  Id : Element_Type renames Pack.Element (Cursor);
2915
2916                Renaming_Decl :=
2917                  Make_Object_Renaming_Declaration (Loc,
2918                    Defining_Identifier => Id,
2919                    Subtype_Mark        =>
2920                      New_Occurrence_Of (Element_Type, Loc),
2921                    Name                =>
2922                      Make_Indexed_Component (Loc,
2923                        Prefix =>
2924                          Make_Selected_Component (Loc,
2925                            Prefix        =>  New_Occurrence_Of (Pack, Loc),
2926                            Selector_Name =>
2927                              Make_Identifier (Loc, Chars => Name_Element)),
2928                        Expressions =>
2929                          New_List (New_Occurrence_Of (Cursor, Loc))));
2930
2931                Prepend (Renaming_Decl, Stats);
2932             end if;
2933
2934             --  For both iterator forms, add call to step operation (Next or
2935             --  Previous) to advance cursor.
2936
2937             Append_To (Stats,
2938               Make_Procedure_Call_Statement (Loc,
2939                 Name =>
2940                   Make_Selected_Component (Loc,
2941                     Prefix        => New_Occurrence_Of (Pack, Loc),
2942                     Selector_Name => Make_Identifier (Loc, Name_Step)),
2943                 Parameter_Associations =>
2944                   New_List (New_Occurrence_Of (Cursor, Loc))));
2945
2946             New_Loop := Make_Loop_Statement (Loc,
2947               Iteration_Scheme =>
2948                 Make_Iteration_Scheme (Loc, Condition => Cond),
2949               Statements       => Stats,
2950               End_Label        => Empty);
2951          end;
2952       end if;
2953
2954       --  Set_Analyzed (I_Spec);
2955       --  Why is this commented out???
2956
2957       Rewrite (N, New_Loop);
2958       Analyze (N);
2959    end Expand_Iterator_Loop;
2960
2961    -----------------------------
2962    -- Expand_N_Loop_Statement --
2963    -----------------------------
2964
2965    --  1. Remove null loop entirely
2966    --  2. Deal with while condition for C/Fortran boolean
2967    --  3. Deal with loops with a non-standard enumeration type range
2968    --  4. Deal with while loops where Condition_Actions is set
2969    --  5. Deal with loops over predicated subtypes
2970    --  6. Deal with loops with iterators over arrays and containers
2971    --  7. Insert polling call if required
2972
2973    procedure Expand_N_Loop_Statement (N : Node_Id) is
2974       Loc  : constant Source_Ptr := Sloc (N);
2975       Isc  : constant Node_Id    := Iteration_Scheme (N);
2976
2977    begin
2978       --  Delete null loop
2979
2980       if Is_Null_Loop (N) then
2981          Rewrite (N, Make_Null_Statement (Loc));
2982          return;
2983       end if;
2984
2985       --  Deal with condition for C/Fortran Boolean
2986
2987       if Present (Isc) then
2988          Adjust_Condition (Condition (Isc));
2989       end if;
2990
2991       --  Generate polling call
2992
2993       if Is_Non_Empty_List (Statements (N)) then
2994          Generate_Poll_Call (First (Statements (N)));
2995       end if;
2996
2997       --  Nothing more to do for plain loop with no iteration scheme
2998
2999       if No (Isc) then
3000          null;
3001
3002       --  Case of for loop (Loop_Parameter_Specification present)
3003
3004       --  Note: we do not have to worry about validity checking of the for loop
3005       --  range bounds here, since they were frozen with constant declarations
3006       --  and it is during that process that the validity checking is done.
3007
3008       elsif Present (Loop_Parameter_Specification (Isc)) then
3009          declare
3010             LPS     : constant Node_Id   := Loop_Parameter_Specification (Isc);
3011             Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
3012             Ltype   : constant Entity_Id := Etype (Loop_Id);
3013             Btype   : constant Entity_Id := Base_Type (Ltype);
3014             Expr    : Node_Id;
3015             New_Id  : Entity_Id;
3016
3017          begin
3018             --  Deal with loop over predicates
3019
3020             if Is_Discrete_Type (Ltype)
3021               and then Present (Predicate_Function (Ltype))
3022             then
3023                Expand_Predicated_Loop (N);
3024
3025             --  Handle the case where we have a for loop with the range type
3026             --  being an enumeration type with non-standard representation.
3027             --  In this case we expand:
3028
3029             --    for x in [reverse] a .. b loop
3030             --       ...
3031             --    end loop;
3032
3033             --  to
3034
3035             --    for xP in [reverse] integer
3036             --      range etype'Pos (a) .. etype'Pos (b)
3037             --    loop
3038             --       declare
3039             --          x : constant etype := Pos_To_Rep (xP);
3040             --       begin
3041             --          ...
3042             --       end;
3043             --    end loop;
3044
3045             elsif Is_Enumeration_Type (Btype)
3046               and then Present (Enum_Pos_To_Rep (Btype))
3047             then
3048                New_Id :=
3049                  Make_Defining_Identifier (Loc,
3050                    Chars => New_External_Name (Chars (Loop_Id), 'P'));
3051
3052                --  If the type has a contiguous representation, successive
3053                --  values can be generated as offsets from the first literal.
3054
3055                if Has_Contiguous_Rep (Btype) then
3056                   Expr :=
3057                      Unchecked_Convert_To (Btype,
3058                        Make_Op_Add (Loc,
3059                          Left_Opnd =>
3060                             Make_Integer_Literal (Loc,
3061                               Enumeration_Rep (First_Literal (Btype))),
3062                          Right_Opnd => New_Reference_To (New_Id, Loc)));
3063                else
3064                   --  Use the constructed array Enum_Pos_To_Rep
3065
3066                   Expr :=
3067                     Make_Indexed_Component (Loc,
3068                       Prefix      =>
3069                         New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
3070                       Expressions =>
3071                         New_List (New_Reference_To (New_Id, Loc)));
3072                end if;
3073
3074                Rewrite (N,
3075                  Make_Loop_Statement (Loc,
3076                    Identifier => Identifier (N),
3077
3078                    Iteration_Scheme =>
3079                      Make_Iteration_Scheme (Loc,
3080                        Loop_Parameter_Specification =>
3081                          Make_Loop_Parameter_Specification (Loc,
3082                            Defining_Identifier => New_Id,
3083                            Reverse_Present => Reverse_Present (LPS),
3084
3085                            Discrete_Subtype_Definition =>
3086                              Make_Subtype_Indication (Loc,
3087
3088                                Subtype_Mark =>
3089                                  New_Reference_To (Standard_Natural, Loc),
3090
3091                                Constraint =>
3092                                  Make_Range_Constraint (Loc,
3093                                    Range_Expression =>
3094                                      Make_Range (Loc,
3095
3096                                        Low_Bound =>
3097                                          Make_Attribute_Reference (Loc,
3098                                            Prefix =>
3099                                              New_Reference_To (Btype, Loc),
3100
3101                                            Attribute_Name => Name_Pos,
3102
3103                                            Expressions => New_List (
3104                                              Relocate_Node
3105                                                (Type_Low_Bound (Ltype)))),
3106
3107                                        High_Bound =>
3108                                          Make_Attribute_Reference (Loc,
3109                                            Prefix =>
3110                                              New_Reference_To (Btype, Loc),
3111
3112                                            Attribute_Name => Name_Pos,
3113
3114                                            Expressions => New_List (
3115                                              Relocate_Node
3116                                                (Type_High_Bound
3117                                                   (Ltype))))))))),
3118
3119                    Statements => New_List (
3120                      Make_Block_Statement (Loc,
3121                        Declarations => New_List (
3122                          Make_Object_Declaration (Loc,
3123                            Defining_Identifier => Loop_Id,
3124                            Constant_Present    => True,
3125                            Object_Definition   =>
3126                              New_Reference_To (Ltype, Loc),
3127                            Expression          => Expr)),
3128
3129                        Handled_Statement_Sequence =>
3130                          Make_Handled_Sequence_Of_Statements (Loc,
3131                            Statements => Statements (N)))),
3132
3133                    End_Label => End_Label (N)));
3134                Analyze (N);
3135
3136             --  Nothing to do with other cases of for loops
3137
3138             else
3139                null;
3140             end if;
3141          end;
3142
3143       --  Second case, if we have a while loop with Condition_Actions set, then
3144       --  we change it into a plain loop:
3145
3146       --    while C loop
3147       --       ...
3148       --    end loop;
3149
3150       --  changed to:
3151
3152       --    loop
3153       --       <<condition actions>>
3154       --       exit when not C;
3155       --       ...
3156       --    end loop
3157
3158       elsif Present (Isc)
3159         and then Present (Condition_Actions (Isc))
3160       then
3161          declare
3162             ES : Node_Id;
3163
3164          begin
3165             ES :=
3166               Make_Exit_Statement (Sloc (Condition (Isc)),
3167                 Condition =>
3168                   Make_Op_Not (Sloc (Condition (Isc)),
3169                     Right_Opnd => Condition (Isc)));
3170
3171             Prepend (ES, Statements (N));
3172             Insert_List_Before (ES, Condition_Actions (Isc));
3173
3174             --  This is not an implicit loop, since it is generated in response
3175             --  to the loop statement being processed. If this is itself
3176             --  implicit, the restriction has already been checked. If not,
3177             --  it is an explicit loop.
3178
3179             Rewrite (N,
3180               Make_Loop_Statement (Sloc (N),
3181                 Identifier => Identifier (N),
3182                 Statements => Statements (N),
3183                 End_Label  => End_Label  (N)));
3184
3185             Analyze (N);
3186          end;
3187
3188       --  Here to deal with iterator case
3189
3190       elsif Present (Isc)
3191         and then Present (Iterator_Specification (Isc))
3192       then
3193          Expand_Iterator_Loop (N);
3194       end if;
3195    end Expand_N_Loop_Statement;
3196
3197    ----------------------------
3198    -- Expand_Predicated_Loop --
3199    ----------------------------
3200
3201    --  Note: the expander can handle generation of loops over predicated
3202    --  subtypes for both the dynamic and static cases. Depending on what
3203    --  we decide is allowed in Ada 2012 mode and/or extentions allowed
3204    --  mode, the semantic analyzer may disallow one or both forms.
3205
3206    procedure Expand_Predicated_Loop (N : Node_Id) is
3207       Loc     : constant Source_Ptr := Sloc (N);
3208       Isc     : constant Node_Id    := Iteration_Scheme (N);
3209       LPS     : constant Node_Id    := Loop_Parameter_Specification (Isc);
3210       Loop_Id : constant Entity_Id  := Defining_Identifier (LPS);
3211       Ltype   : constant Entity_Id  := Etype (Loop_Id);
3212       Stat    : constant List_Id    := Static_Predicate (Ltype);
3213       Stmts   : constant List_Id    := Statements (N);
3214
3215    begin
3216       --  Case of iteration over non-static predicate, should not be possible
3217       --  since this is not allowed by the semantics and should have been
3218       --  caught during analysis of the loop statement.
3219
3220       if No (Stat) then
3221          raise Program_Error;
3222
3223       --  If the predicate list is empty, that corresponds to a predicate of
3224       --  False, in which case the loop won't run at all, and we rewrite the
3225       --  entire loop as a null statement.
3226
3227       elsif Is_Empty_List (Stat) then
3228          Rewrite (N, Make_Null_Statement (Loc));
3229          Analyze (N);
3230
3231       --  For expansion over a static predicate we generate the following
3232
3233       --     declare
3234       --        J : Ltype := min-val;
3235       --     begin
3236       --        loop
3237       --           body
3238       --           case J is
3239       --              when endpoint => J := startpoint;
3240       --              when endpoint => J := startpoint;
3241       --              ...
3242       --              when max-val  => exit;
3243       --              when others   => J := Lval'Succ (J);
3244       --           end case;
3245       --        end loop;
3246       --     end;
3247
3248       --  To make this a little clearer, let's take a specific example:
3249
3250       --        type Int is range 1 .. 10;
3251       --        subtype L is Int with
3252       --          predicate => L in 3 | 10 | 5 .. 7;
3253       --          ...
3254       --        for L in StaticP loop
3255       --           Put_Line ("static:" & J'Img);
3256       --        end loop;
3257
3258       --  In this case, the loop is transformed into
3259
3260       --     begin
3261       --        J : L := 3;
3262       --        loop
3263       --           body
3264       --           case J is
3265       --              when 3  => J := 5;
3266       --              when 7  => J := 10;
3267       --              when 10 => exit;
3268       --              when others  => J := L'Succ (J);
3269       --           end case;
3270       --        end loop;
3271       --     end;
3272
3273       else
3274          Static_Predicate : declare
3275             S    : Node_Id;
3276             D    : Node_Id;
3277             P    : Node_Id;
3278             Alts : List_Id;
3279             Cstm : Node_Id;
3280
3281             function Lo_Val (N : Node_Id) return Node_Id;
3282             --  Given static expression or static range, returns an identifier
3283             --  whose value is the low bound of the expression value or range.
3284
3285             function Hi_Val (N : Node_Id) return Node_Id;
3286             --  Given static expression or static range, returns an identifier
3287             --  whose value is the high bound of the expression value or range.
3288
3289             ------------
3290             -- Hi_Val --
3291             ------------
3292
3293             function Hi_Val (N : Node_Id) return Node_Id is
3294             begin
3295                if Is_Static_Expression (N) then
3296                   return New_Copy (N);
3297                else
3298                   pragma Assert (Nkind (N) = N_Range);
3299                   return New_Copy (High_Bound (N));
3300                end if;
3301             end Hi_Val;
3302
3303             ------------
3304             -- Lo_Val --
3305             ------------
3306
3307             function Lo_Val (N : Node_Id) return Node_Id is
3308             begin
3309                if Is_Static_Expression (N) then
3310                   return New_Copy (N);
3311                else
3312                   pragma Assert (Nkind (N) = N_Range);
3313                   return New_Copy (Low_Bound (N));
3314                end if;
3315             end Lo_Val;
3316
3317          --  Start of processing for Static_Predicate
3318
3319          begin
3320             --  Convert loop identifier to normal variable and reanalyze it so
3321             --  that this conversion works. We have to use the same defining
3322             --  identifier, since there may be references in the loop body.
3323
3324             Set_Analyzed (Loop_Id, False);
3325             Set_Ekind    (Loop_Id, E_Variable);
3326
3327             --  Loop to create branches of case statement
3328
3329             Alts := New_List;
3330             P := First (Stat);
3331             while Present (P) loop
3332                if No (Next (P)) then
3333                   S := Make_Exit_Statement (Loc);
3334                else
3335                   S :=
3336                     Make_Assignment_Statement (Loc,
3337                       Name       => New_Occurrence_Of (Loop_Id, Loc),
3338                       Expression => Lo_Val (Next (P)));
3339                   Set_Suppress_Assignment_Checks (S);
3340                end if;
3341
3342                Append_To (Alts,
3343                  Make_Case_Statement_Alternative (Loc,
3344                    Statements       => New_List (S),
3345                    Discrete_Choices => New_List (Hi_Val (P))));
3346
3347                Next (P);
3348             end loop;
3349
3350             --  Add others choice
3351
3352             S :=
3353                Make_Assignment_Statement (Loc,
3354                  Name       => New_Occurrence_Of (Loop_Id, Loc),
3355                  Expression =>
3356                    Make_Attribute_Reference (Loc,
3357                      Prefix => New_Occurrence_Of (Ltype, Loc),
3358                      Attribute_Name => Name_Succ,
3359                      Expressions    => New_List (
3360                        New_Occurrence_Of (Loop_Id, Loc))));
3361             Set_Suppress_Assignment_Checks (S);
3362
3363             Append_To (Alts,
3364               Make_Case_Statement_Alternative (Loc,
3365                 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
3366                 Statements       => New_List (S)));
3367
3368             --  Construct case statement and append to body statements
3369
3370             Cstm :=
3371               Make_Case_Statement (Loc,
3372                 Expression   => New_Occurrence_Of (Loop_Id, Loc),
3373                 Alternatives => Alts);
3374             Append_To (Stmts, Cstm);
3375
3376             --  Rewrite the loop
3377
3378             D :=
3379                Make_Object_Declaration (Loc,
3380                  Defining_Identifier => Loop_Id,
3381                  Object_Definition   => New_Occurrence_Of (Ltype, Loc),
3382                  Expression          => Lo_Val (First (Stat)));
3383             Set_Suppress_Assignment_Checks (D);
3384
3385             Rewrite (N,
3386               Make_Block_Statement (Loc,
3387                 Declarations               => New_List (D),
3388                 Handled_Statement_Sequence =>
3389                   Make_Handled_Sequence_Of_Statements (Loc,
3390                     Statements => New_List (
3391                       Make_Loop_Statement (Loc,
3392                         Statements => Stmts,
3393                         End_Label  => Empty)))));
3394
3395             Analyze (N);
3396          end Static_Predicate;
3397       end if;
3398    end Expand_Predicated_Loop;
3399
3400    ------------------------------
3401    -- Make_Tag_Ctrl_Assignment --
3402    ------------------------------
3403
3404    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
3405       Loc : constant Source_Ptr := Sloc (N);
3406       L   : constant Node_Id    := Name (N);
3407       T   : constant Entity_Id  := Underlying_Type (Etype (L));
3408
3409       Ctrl_Act : constant Boolean := Needs_Finalization (T)
3410                                        and then not No_Ctrl_Actions (N);
3411
3412       Component_Assign : constant Boolean :=
3413                            Is_Fully_Repped_Tagged_Type (T);
3414
3415       Save_Tag : constant Boolean := Is_Tagged_Type (T)
3416                                        and then not Component_Assign
3417                                        and then not No_Ctrl_Actions (N)
3418                                        and then Tagged_Type_Expansion;
3419       --  Tags are not saved and restored when VM_Target because VM tags are
3420       --  represented implicitly in objects.
3421
3422       Res      : List_Id;
3423       Tag_Tmp  : Entity_Id;
3424
3425       Prev_Tmp : Entity_Id;
3426       Next_Tmp : Entity_Id;
3427       Ctrl_Ref : Node_Id;
3428
3429    begin
3430       Res := New_List;
3431
3432       --  Finalize the target of the assignment when controlled
3433
3434       --  We have two exceptions here:
3435
3436       --   1. If we are in an init proc since it is an initialization more
3437       --      than an assignment.
3438
3439       --   2. If the left-hand side is a temporary that was not initialized
3440       --      (or the parent part of a temporary since it is the case in
3441       --      extension aggregates). Such a temporary does not come from
3442       --      source. We must examine the original node for the prefix, because
3443       --      it may be a component of an entry formal, in which case it has
3444       --      been rewritten and does not appear to come from source either.
3445
3446       --  Case of init proc
3447
3448       if not Ctrl_Act then
3449          null;
3450
3451       --  The left hand side is an uninitialized temporary object
3452
3453       elsif Nkind (L) = N_Type_Conversion
3454         and then Is_Entity_Name (Expression (L))
3455         and then Nkind (Parent (Entity (Expression (L)))) =
3456                                               N_Object_Declaration
3457         and then No_Initialization (Parent (Entity (Expression (L))))
3458       then
3459          null;
3460
3461       else
3462          Append_List_To (Res,
3463            Make_Final_Call
3464              (Ref         => Duplicate_Subexpr_No_Checks (L),
3465               Typ         => Etype (L),
3466               With_Detach => New_Reference_To (Standard_False, Loc)));
3467       end if;
3468
3469       --  Save the Tag in a local variable Tag_Tmp
3470
3471       if Save_Tag then
3472          Tag_Tmp := Make_Temporary (Loc, 'A');
3473
3474          Append_To (Res,
3475            Make_Object_Declaration (Loc,
3476              Defining_Identifier => Tag_Tmp,
3477              Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
3478              Expression =>
3479                Make_Selected_Component (Loc,
3480                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3481                  Selector_Name => New_Reference_To (First_Tag_Component (T),
3482                                                     Loc))));
3483
3484       --  Otherwise Tag_Tmp not used
3485
3486       else
3487          Tag_Tmp := Empty;
3488       end if;
3489
3490       if Ctrl_Act then
3491          if VM_Target /= No_VM then
3492
3493             --  Cannot assign part of the object in a VM context, so instead
3494             --  fallback to the previous mechanism, even though it is not
3495             --  completely correct ???
3496
3497             --  Save the Finalization Pointers in local variables Prev_Tmp and
3498             --  Next_Tmp. For objects with Has_Controlled_Component set, these
3499             --  pointers are in the Record_Controller
3500
3501             Ctrl_Ref := Duplicate_Subexpr (L);
3502
3503             if Has_Controlled_Component (T) then
3504                Ctrl_Ref :=
3505                  Make_Selected_Component (Loc,
3506                    Prefix => Ctrl_Ref,
3507                    Selector_Name =>
3508                      New_Reference_To (Controller_Component (T), Loc));
3509             end if;
3510
3511             Prev_Tmp := Make_Temporary (Loc, 'B');
3512
3513             Append_To (Res,
3514               Make_Object_Declaration (Loc,
3515                 Defining_Identifier => Prev_Tmp,
3516
3517                 Object_Definition =>
3518                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3519
3520                 Expression =>
3521                   Make_Selected_Component (Loc,
3522                     Prefix =>
3523                       Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref),
3524                     Selector_Name => Make_Identifier (Loc, Name_Prev))));
3525
3526             Next_Tmp := Make_Temporary (Loc, 'C');
3527
3528             Append_To (Res,
3529               Make_Object_Declaration (Loc,
3530                 Defining_Identifier => Next_Tmp,
3531
3532                 Object_Definition   =>
3533                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3534
3535                 Expression          =>
3536                   Make_Selected_Component (Loc,
3537                     Prefix =>
3538                       Unchecked_Convert_To (RTE (RE_Finalizable),
3539                         New_Copy_Tree (Ctrl_Ref)),
3540                     Selector_Name => Make_Identifier (Loc, Name_Next))));
3541
3542             --  Do the Assignment
3543
3544             Append_To (Res, Relocate_Node (N));
3545
3546          else
3547             --  Regular (non VM) processing for controlled types and types with
3548             --  controlled components
3549
3550             --  Variables of such types contain pointers used to chain them in
3551             --  finalization lists, in addition to user data. These pointers
3552             --  are specific to each object of the type, not to the value being
3553             --  assigned.
3554
3555             --  Thus they need to be left intact during the assignment. We
3556             --  achieve this by constructing a Storage_Array subtype, and by
3557             --  overlaying objects of this type on the source and target of the
3558             --  assignment. The assignment is then rewritten to assignments of
3559             --  slices of these arrays, copying the user data, and leaving the
3560             --  pointers untouched.
3561
3562             Controlled_Actions : declare
3563                Prev_Ref : Node_Id;
3564                --  A reference to the Prev component of the record controller
3565
3566                First_After_Root : Node_Id := Empty;
3567                --  Index of first byte to be copied (used to skip
3568                --  Root_Controlled in controlled objects).
3569
3570                Last_Before_Hole : Node_Id := Empty;
3571                --  Index of last byte to be copied before outermost record
3572                --  controller data.
3573
3574                Hole_Length : Node_Id := Empty;
3575                --  Length of record controller data (Prev and Next pointers)
3576
3577                First_After_Hole : Node_Id := Empty;
3578                --  Index of first byte to be copied after outermost record
3579                --  controller data.
3580
3581                Expr, Source_Size     : Node_Id;
3582                Source_Actual_Subtype : Entity_Id;
3583                --  Used for computation of the size of the data to be copied
3584
3585                Range_Type  : Entity_Id;
3586                Opaque_Type : Entity_Id;
3587
3588                function Build_Slice
3589                  (Rec : Entity_Id;
3590                   Lo  : Node_Id;
3591                   Hi  : Node_Id) return Node_Id;
3592                --  Build and return a slice of an array of type S overlaid on
3593                --  object Rec, with bounds specified by Lo and Hi. If either
3594                --  bound is empty, a default of S'First (respectively S'Last)
3595                --  is used.
3596
3597                -----------------
3598                -- Build_Slice --
3599                -----------------
3600
3601                function Build_Slice
3602                  (Rec : Node_Id;
3603                   Lo  : Node_Id;
3604                   Hi  : Node_Id) return Node_Id
3605                is
3606                   Lo_Bound : Node_Id;
3607                   Hi_Bound : Node_Id;
3608
3609                   Opaque : constant Node_Id :=
3610                              Unchecked_Convert_To (Opaque_Type,
3611                                Make_Attribute_Reference (Loc,
3612                                  Prefix         => Rec,
3613                                  Attribute_Name => Name_Address));
3614                   --  Access value designating an opaque storage array of type
3615                   --  S overlaid on record Rec.
3616
3617                begin
3618                   --  Compute slice bounds using S'First (1) and S'Last as
3619                   --  default values when not specified by the caller.
3620
3621                   if No (Lo) then
3622                      Lo_Bound := Make_Integer_Literal (Loc, 1);
3623                   else
3624                      Lo_Bound := Lo;
3625                   end if;
3626
3627                   if No (Hi) then
3628                      Hi_Bound := Make_Attribute_Reference (Loc,
3629                        Prefix => New_Occurrence_Of (Range_Type, Loc),
3630                        Attribute_Name => Name_Last);
3631                   else
3632                      Hi_Bound := Hi;
3633                   end if;
3634
3635                   return Make_Slice (Loc,
3636                     Prefix =>
3637                       Opaque,
3638                     Discrete_Range => Make_Range (Loc,
3639                       Lo_Bound, Hi_Bound));
3640                end Build_Slice;
3641
3642             --  Start of processing for Controlled_Actions
3643
3644             begin
3645                --  Create a constrained subtype of Storage_Array whose size
3646                --  corresponds to the value being assigned.
3647
3648                --  subtype G is Storage_Offset range
3649                --    1 .. (Expr'Size + Storage_Unit - 1) / Storage_Unit
3650
3651                Expr := Duplicate_Subexpr_No_Checks (Expression (N));
3652
3653                if Nkind (Expr) = N_Qualified_Expression then
3654                   Expr := Expression (Expr);
3655                end if;
3656
3657                Source_Actual_Subtype := Etype (Expr);
3658
3659                if Has_Discriminants (Source_Actual_Subtype)
3660                  and then not Is_Constrained (Source_Actual_Subtype)
3661                then
3662                   Append_To (Res,
3663                     Build_Actual_Subtype (Source_Actual_Subtype, Expr));
3664                   Source_Actual_Subtype := Defining_Identifier (Last (Res));
3665                end if;
3666
3667                Source_Size :=
3668                  Make_Op_Add (Loc,
3669                    Left_Opnd =>
3670                      Make_Attribute_Reference (Loc,
3671                        Prefix =>
3672                          New_Occurrence_Of (Source_Actual_Subtype, Loc),
3673                      Attribute_Name => Name_Size),
3674                    Right_Opnd =>
3675                      Make_Integer_Literal (Loc,
3676                        Intval => System_Storage_Unit - 1));
3677
3678                Source_Size :=
3679                  Make_Op_Divide (Loc,
3680                    Left_Opnd => Source_Size,
3681                    Right_Opnd =>
3682                      Make_Integer_Literal (Loc,
3683                        Intval => System_Storage_Unit));
3684
3685                Range_Type := Make_Temporary (Loc, 'G');
3686
3687                Append_To (Res,
3688                  Make_Subtype_Declaration (Loc,
3689                    Defining_Identifier => Range_Type,
3690                    Subtype_Indication =>
3691                      Make_Subtype_Indication (Loc,
3692                        Subtype_Mark =>
3693                          New_Reference_To (RTE (RE_Storage_Offset), Loc),
3694                        Constraint   => Make_Range_Constraint (Loc,
3695                          Range_Expression =>
3696                            Make_Range (Loc,
3697                              Low_Bound  => Make_Integer_Literal (Loc, 1),
3698                              High_Bound => Source_Size)))));
3699
3700                --  subtype S is Storage_Array (G)
3701
3702                Append_To (Res,
3703                  Make_Subtype_Declaration (Loc,
3704                    Defining_Identifier => Make_Temporary (Loc, 'S'),
3705                    Subtype_Indication  =>
3706                      Make_Subtype_Indication (Loc,
3707                        Subtype_Mark =>
3708                          New_Reference_To (RTE (RE_Storage_Array), Loc),
3709                        Constraint =>
3710                          Make_Index_Or_Discriminant_Constraint (Loc,
3711                            Constraints =>
3712                              New_List (New_Reference_To (Range_Type, Loc))))));
3713
3714                --  type A is access S
3715
3716                Opaque_Type := Make_Temporary (Loc, 'A');
3717
3718                Append_To (Res,
3719                  Make_Full_Type_Declaration (Loc,
3720                    Defining_Identifier => Opaque_Type,
3721                    Type_Definition     =>
3722                      Make_Access_To_Object_Definition (Loc,
3723                        Subtype_Indication =>
3724                          New_Occurrence_Of (
3725                            Defining_Identifier (Last (Res)), Loc))));
3726
3727                --  Generate appropriate slice assignments
3728
3729                First_After_Root := Make_Integer_Literal (Loc, 1);
3730
3731                --  For controlled object, skip Root_Controlled part
3732
3733                if Is_Controlled (T) then
3734                   First_After_Root :=
3735                     Make_Op_Add (Loc,
3736                       First_After_Root,
3737                       Make_Op_Divide (Loc,
3738                         Make_Attribute_Reference (Loc,
3739                           Prefix =>
3740                             New_Occurrence_Of (RTE (RE_Root_Controlled), Loc),
3741                           Attribute_Name => Name_Size),
3742                         Make_Integer_Literal (Loc, System_Storage_Unit)));
3743                end if;
3744
3745                --  For the case of a record with controlled components, skip
3746                --  record controller Prev/Next components. These components
3747                --  constitute a 'hole' in the middle of the data to be copied.
3748
3749                if Has_Controlled_Component (T) then
3750                   Prev_Ref :=
3751                     Make_Selected_Component (Loc,
3752                       Prefix        =>
3753                         Make_Selected_Component (Loc,
3754                           Prefix => Duplicate_Subexpr_No_Checks (L),
3755                           Selector_Name =>
3756                             New_Reference_To (Controller_Component (T), Loc)),
3757                       Selector_Name =>  Make_Identifier (Loc, Name_Prev));
3758
3759                   --  Last index before hole: determined by position of the
3760                   --  _Controller.Prev component.
3761
3762                   Last_Before_Hole := Make_Temporary (Loc, 'L');
3763
3764                   Append_To (Res,
3765                     Make_Object_Declaration (Loc,
3766                       Defining_Identifier => Last_Before_Hole,
3767                       Object_Definition   => New_Occurrence_Of (
3768                         RTE (RE_Storage_Offset), Loc),
3769                       Constant_Present    => True,
3770                       Expression          =>
3771                         Make_Op_Add (Loc,
3772                           Make_Attribute_Reference (Loc,
3773                             Prefix => Prev_Ref,
3774                             Attribute_Name => Name_Position),
3775                           Make_Attribute_Reference (Loc,
3776                             Prefix => New_Copy_Tree (Prefix (Prev_Ref)),
3777                             Attribute_Name => Name_Position))));
3778
3779                   --  Hole length: size of the Prev and Next components
3780
3781                   Hole_Length :=
3782                     Make_Op_Multiply (Loc,
3783                       Left_Opnd  => Make_Integer_Literal (Loc, Uint_2),
3784                       Right_Opnd =>
3785                         Make_Op_Divide (Loc,
3786                           Left_Opnd =>
3787                             Make_Attribute_Reference (Loc,
3788                               Prefix         => New_Copy_Tree (Prev_Ref),
3789                               Attribute_Name => Name_Size),
3790                           Right_Opnd =>
3791                             Make_Integer_Literal (Loc,
3792                               Intval => System_Storage_Unit)));
3793
3794                   --  First index after hole
3795
3796                   First_After_Hole := Make_Temporary (Loc, 'F');
3797
3798                   Append_To (Res,
3799                     Make_Object_Declaration (Loc,
3800                       Defining_Identifier => First_After_Hole,
3801                       Object_Definition   => New_Occurrence_Of (
3802                         RTE (RE_Storage_Offset), Loc),
3803                       Constant_Present    => True,
3804                       Expression          =>
3805                         Make_Op_Add (Loc,
3806                           Left_Opnd  =>
3807                             Make_Op_Add (Loc,
3808                               Left_Opnd  =>
3809                                 New_Occurrence_Of (Last_Before_Hole, Loc),
3810                               Right_Opnd => Hole_Length),
3811                           Right_Opnd => Make_Integer_Literal (Loc, 1))));
3812
3813                   Last_Before_Hole :=
3814                     New_Occurrence_Of (Last_Before_Hole, Loc);
3815                   First_After_Hole :=
3816                     New_Occurrence_Of (First_After_Hole, Loc);
3817                end if;
3818
3819                --  Assign the first slice (possibly skipping Root_Controlled,
3820                --  up to the beginning of the record controller if present,
3821                --  up to the end of the object if not).
3822
3823                Append_To (Res, Make_Assignment_Statement (Loc,
3824                  Name       => Build_Slice (
3825                    Rec => Duplicate_Subexpr_No_Checks (L),
3826                    Lo  => First_After_Root,
3827                    Hi  => Last_Before_Hole),
3828
3829                  Expression => Build_Slice (
3830                    Rec => Expression (N),
3831                    Lo  => First_After_Root,
3832                    Hi  => New_Copy_Tree (Last_Before_Hole))));
3833
3834                if Present (First_After_Hole) then
3835
3836                   --  If a record controller is present, copy the second slice,
3837                   --  from right after the _Controller.Next component up to the
3838                   --  end of the object.
3839
3840                   Append_To (Res, Make_Assignment_Statement (Loc,
3841                     Name       => Build_Slice (
3842                       Rec => Duplicate_Subexpr_No_Checks (L),
3843                       Lo  => First_After_Hole,
3844                       Hi  => Empty),
3845                     Expression => Build_Slice (
3846                       Rec => Duplicate_Subexpr_No_Checks (Expression (N)),
3847                       Lo  => New_Copy_Tree (First_After_Hole),
3848                       Hi  => Empty)));
3849                end if;
3850             end Controlled_Actions;
3851          end if;
3852
3853       --  Not controlled case
3854
3855       else
3856          declare
3857             Asn : constant Node_Id := Relocate_Node (N);
3858
3859          begin
3860             --  If this is the case of a tagged type with a full rep clause,
3861             --  we must expand it into component assignments, so we mark the
3862             --  node as unanalyzed, to get it reanalyzed, but flag it has
3863             --  requiring component-wise assignment so we don't get infinite
3864             --  recursion.
3865
3866             if Component_Assign then
3867                Set_Analyzed (Asn, False);
3868                Set_Componentwise_Assignment (Asn, True);
3869             end if;
3870
3871             Append_To (Res, Asn);
3872          end;
3873       end if;
3874
3875       --  Restore the tag
3876
3877       if Save_Tag then
3878          Append_To (Res,
3879            Make_Assignment_Statement (Loc,
3880              Name =>
3881                Make_Selected_Component (Loc,
3882                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3883                  Selector_Name => New_Reference_To (First_Tag_Component (T),
3884                                                     Loc)),
3885              Expression => New_Reference_To (Tag_Tmp, Loc)));
3886       end if;
3887
3888       if Ctrl_Act then
3889          if VM_Target /= No_VM then
3890             --  Restore the finalization pointers
3891
3892             Append_To (Res,
3893               Make_Assignment_Statement (Loc,
3894                 Name =>
3895                   Make_Selected_Component (Loc,
3896                     Prefix        =>
3897                       Unchecked_Convert_To (RTE (RE_Finalizable),
3898                         New_Copy_Tree (Ctrl_Ref)),
3899                     Selector_Name => Make_Identifier (Loc, Name_Prev)),
3900                 Expression => New_Reference_To (Prev_Tmp, Loc)));
3901
3902             Append_To (Res,
3903               Make_Assignment_Statement (Loc,
3904                 Name =>
3905                   Make_Selected_Component (Loc,
3906                     Prefix        =>
3907                       Unchecked_Convert_To (RTE (RE_Finalizable),
3908                         New_Copy_Tree (Ctrl_Ref)),
3909                     Selector_Name => Make_Identifier (Loc, Name_Next)),
3910                 Expression => New_Reference_To (Next_Tmp, Loc)));
3911          end if;
3912
3913          --  Adjust the target after the assignment when controlled (not in the
3914          --  init proc since it is an initialization more than an assignment).
3915
3916          Append_List_To (Res,
3917            Make_Adjust_Call (
3918              Ref         => Duplicate_Subexpr_Move_Checks (L),
3919              Typ         => Etype (L),
3920              Flist_Ref   => New_Reference_To (RTE (RE_Global_Final_List), Loc),
3921              With_Attach => Make_Integer_Literal (Loc, 0)));
3922       end if;
3923
3924       return Res;
3925
3926    exception
3927       --  Could use comment here ???
3928
3929       when RE_Not_Available =>
3930          return Empty_List;
3931    end Make_Tag_Ctrl_Assignment;
3932
3933 end Exp_Ch5;