OSDN Git Service

2011-08-02 Ed Schonberg <schonberg@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / exp_ch5.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              E X P _ C H 5                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-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 reanalyzed
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). Finally, it is suppressed if the
1947                --  restriction No_Dispatching_Calls is in force because in that
1948                --  case predefined primitives are not generated.
1949
1950                or else (Is_Tagged_Type (Typ)
1951                          and then not Is_Value_Type (Etype (Lhs))
1952                          and then Chars (Current_Scope) /= Name_uAssign
1953                          and then Expand_Ctrl_Actions
1954                          and then not Discriminant_Checks_Suppressed (Empty)
1955                          and then
1956                            not Restriction_Active (No_Dispatching_Calls))
1957             then
1958                --  Fetch the primitive op _assign and proper type to call it.
1959                --  Because of possible conflicts between private and full view,
1960                --  fetch the proper type directly from the operation profile.
1961
1962                declare
1963                   Op    : constant Entity_Id :=
1964                             Find_Prim_Op (Typ, Name_uAssign);
1965                   F_Typ : Entity_Id := Etype (First_Formal (Op));
1966
1967                begin
1968                   --  If the assignment is dispatching, make sure to use the
1969                   --  proper type.
1970
1971                   if Is_Class_Wide_Type (Typ) then
1972                      F_Typ := Class_Wide_Type (F_Typ);
1973                   end if;
1974
1975                   L := New_List;
1976
1977                   --  In case of assignment to a class-wide tagged type, before
1978                   --  the assignment we generate run-time check to ensure that
1979                   --  the tags of source and target match.
1980
1981                   if Is_Class_Wide_Type (Typ)
1982                     and then Is_Tagged_Type (Typ)
1983                     and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
1984                   then
1985                      Append_To (L,
1986                        Make_Raise_Constraint_Error (Loc,
1987                          Condition =>
1988                              Make_Op_Ne (Loc,
1989                                Left_Opnd =>
1990                                  Make_Selected_Component (Loc,
1991                                    Prefix        => Duplicate_Subexpr (Lhs),
1992                                    Selector_Name =>
1993                                      Make_Identifier (Loc, Name_uTag)),
1994                                Right_Opnd =>
1995                                  Make_Selected_Component (Loc,
1996                                    Prefix        => Duplicate_Subexpr (Rhs),
1997                                    Selector_Name =>
1998                                      Make_Identifier (Loc, Name_uTag))),
1999                          Reason => CE_Tag_Check_Failed));
2000                   end if;
2001
2002                   declare
2003                      Left_N  : Node_Id := Duplicate_Subexpr (Lhs);
2004                      Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2005
2006                   begin
2007                      --  In order to dispatch the call to _assign the type of
2008                      --  the actuals must match. Add conversion (if required).
2009
2010                      if Etype (Lhs) /= F_Typ then
2011                         Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2012                      end if;
2013
2014                      if Etype (Rhs) /= F_Typ then
2015                         Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2016                      end if;
2017
2018                      Append_To (L,
2019                        Make_Procedure_Call_Statement (Loc,
2020                          Name => New_Reference_To (Op, Loc),
2021                          Parameter_Associations => New_List (
2022                            Node1 => Left_N,
2023                            Node2 => Right_N)));
2024                   end;
2025                end;
2026
2027             else
2028                L := Make_Tag_Ctrl_Assignment (N);
2029
2030                --  We can't afford to have destructive Finalization Actions in
2031                --  the Self assignment case, so if the target and the source
2032                --  are not obviously different, code is generated to avoid the
2033                --  self assignment case:
2034
2035                --    if lhs'address /= rhs'address then
2036                --       <code for controlled and/or tagged assignment>
2037                --    end if;
2038
2039                --  Skip this if Restriction (No_Finalization) is active
2040
2041                if not Statically_Different (Lhs, Rhs)
2042                  and then Expand_Ctrl_Actions
2043                  and then not Restriction_Active (No_Finalization)
2044                then
2045                   L := New_List (
2046                     Make_Implicit_If_Statement (N,
2047                       Condition =>
2048                         Make_Op_Ne (Loc,
2049                           Left_Opnd =>
2050                             Make_Attribute_Reference (Loc,
2051                               Prefix         => Duplicate_Subexpr (Lhs),
2052                               Attribute_Name => Name_Address),
2053
2054                            Right_Opnd =>
2055                             Make_Attribute_Reference (Loc,
2056                               Prefix         => Duplicate_Subexpr (Rhs),
2057                               Attribute_Name => Name_Address)),
2058
2059                       Then_Statements => L));
2060                end if;
2061
2062                --  We need to set up an exception handler for implementing
2063                --  7.6.1(18). The remaining adjustments are tackled by the
2064                --  implementation of adjust for record_controllers (see
2065                --  s-finimp.adb).
2066
2067                --  This is skipped if we have no finalization
2068
2069                if Expand_Ctrl_Actions
2070                  and then not Restriction_Active (No_Finalization)
2071                then
2072                   L := New_List (
2073                     Make_Block_Statement (Loc,
2074                       Handled_Statement_Sequence =>
2075                         Make_Handled_Sequence_Of_Statements (Loc,
2076                           Statements => L,
2077                           Exception_Handlers => New_List (
2078                             Make_Handler_For_Ctrl_Operation (Loc)))));
2079                end if;
2080             end if;
2081
2082             Rewrite (N,
2083               Make_Block_Statement (Loc,
2084                 Handled_Statement_Sequence =>
2085                   Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2086
2087             --  If no restrictions on aborts, protect the whole assignment
2088             --  for controlled objects as per 9.8(11).
2089
2090             if Needs_Finalization (Typ)
2091               and then Expand_Ctrl_Actions
2092               and then Abort_Allowed
2093             then
2094                declare
2095                   Blk : constant Entity_Id :=
2096                           New_Internal_Entity
2097                             (E_Block, Current_Scope, Sloc (N), 'B');
2098
2099                begin
2100                   Set_Scope (Blk, Current_Scope);
2101                   Set_Etype (Blk, Standard_Void_Type);
2102                   Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2103
2104                   Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2105                   Set_At_End_Proc (Handled_Statement_Sequence (N),
2106                     New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
2107                   Expand_At_End_Handler
2108                     (Handled_Statement_Sequence (N), Blk);
2109                end;
2110             end if;
2111
2112             --  N has been rewritten to a block statement for which it is
2113             --  known by construction that no checks are necessary: analyze
2114             --  it with all checks suppressed.
2115
2116             Analyze (N, Suppress => All_Checks);
2117             return;
2118          end Tagged_Case;
2119
2120       --  Array types
2121
2122       elsif Is_Array_Type (Typ) then
2123          declare
2124             Actual_Rhs : Node_Id := Rhs;
2125
2126          begin
2127             while Nkind_In (Actual_Rhs, N_Type_Conversion,
2128                                         N_Qualified_Expression)
2129             loop
2130                Actual_Rhs := Expression (Actual_Rhs);
2131             end loop;
2132
2133             Expand_Assign_Array (N, Actual_Rhs);
2134             return;
2135          end;
2136
2137       --  Record types
2138
2139       elsif Is_Record_Type (Typ) then
2140          Expand_Assign_Record (N);
2141          return;
2142
2143       --  Scalar types. This is where we perform the processing related to the
2144       --  requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2145       --  scalar values.
2146
2147       elsif Is_Scalar_Type (Typ) then
2148
2149          --  Case where right side is known valid
2150
2151          if Expr_Known_Valid (Rhs) then
2152
2153             --  Here the right side is valid, so it is fine. The case to deal
2154             --  with is when the left side is a local variable reference whose
2155             --  value is not currently known to be valid. If this is the case,
2156             --  and the assignment appears in an unconditional context, then
2157             --  we can mark the left side as now being valid if one of these
2158             --  conditions holds:
2159
2160             --    The expression of the right side has Do_Range_Check set so
2161             --    that we know a range check will be performed. Note that it
2162             --    can be the case that a range check is omitted because we
2163             --    make the assumption that we can assume validity for operands
2164             --    appearing in the right side in determining whether a range
2165             --    check is required
2166
2167             --    The subtype of the right side matches the subtype of the
2168             --    left side. In this case, even though we have not checked
2169             --    the range of the right side, we know it is in range of its
2170             --    subtype if the expression is valid.
2171
2172             if Is_Local_Variable_Reference (Lhs)
2173               and then not Is_Known_Valid (Entity (Lhs))
2174               and then In_Unconditional_Context (N)
2175             then
2176                if Do_Range_Check (Rhs)
2177                  or else Etype (Lhs) = Etype (Rhs)
2178                then
2179                   Set_Is_Known_Valid (Entity (Lhs), True);
2180                end if;
2181             end if;
2182
2183          --  Case where right side may be invalid in the sense of the RM
2184          --  reference above. The RM does not require that we check for the
2185          --  validity on an assignment, but it does require that the assignment
2186          --  of an invalid value not cause erroneous behavior.
2187
2188          --  The general approach in GNAT is to use the Is_Known_Valid flag
2189          --  to avoid the need for validity checking on assignments. However
2190          --  in some cases, we have to do validity checking in order to make
2191          --  sure that the setting of this flag is correct.
2192
2193          else
2194             --  Validate right side if we are validating copies
2195
2196             if Validity_Checks_On
2197               and then Validity_Check_Copies
2198             then
2199                --  Skip this if left hand side is an array or record component
2200                --  and elementary component validity checks are suppressed.
2201
2202                if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2203                  and then not Validity_Check_Components
2204                then
2205                   null;
2206                else
2207                   Ensure_Valid (Rhs);
2208                end if;
2209
2210                --  We can propagate this to the left side where appropriate
2211
2212                if Is_Local_Variable_Reference (Lhs)
2213                  and then not Is_Known_Valid (Entity (Lhs))
2214                  and then In_Unconditional_Context (N)
2215                then
2216                   Set_Is_Known_Valid (Entity (Lhs), True);
2217                end if;
2218
2219             --  Otherwise check to see what should be done
2220
2221             --  If left side is a local variable, then we just set its flag to
2222             --  indicate that its value may no longer be valid, since we are
2223             --  copying a potentially invalid value.
2224
2225             elsif Is_Local_Variable_Reference (Lhs) then
2226                Set_Is_Known_Valid (Entity (Lhs), False);
2227
2228             --  Check for case of a nonlocal variable on the left side which
2229             --  is currently known to be valid. In this case, we simply ensure
2230             --  that the right side is valid. We only play the game of copying
2231             --  validity status for local variables, since we are doing this
2232             --  statically, not by tracing the full flow graph.
2233
2234             elsif Is_Entity_Name (Lhs)
2235               and then Is_Known_Valid (Entity (Lhs))
2236             then
2237                --  Note: If Validity_Checking mode is set to none, we ignore
2238                --  the Ensure_Valid call so don't worry about that case here.
2239
2240                Ensure_Valid (Rhs);
2241
2242             --  In all other cases, we can safely copy an invalid value without
2243             --  worrying about the status of the left side. Since it is not a
2244             --  variable reference it will not be considered
2245             --  as being known to be valid in any case.
2246
2247             else
2248                null;
2249             end if;
2250          end if;
2251       end if;
2252
2253    exception
2254       when RE_Not_Available =>
2255          return;
2256    end Expand_N_Assignment_Statement;
2257
2258    ------------------------------
2259    -- Expand_N_Block_Statement --
2260    ------------------------------
2261
2262    --  Encode entity names defined in block statement
2263
2264    procedure Expand_N_Block_Statement (N : Node_Id) is
2265    begin
2266       Qualify_Entity_Names (N);
2267    end Expand_N_Block_Statement;
2268
2269    -----------------------------
2270    -- Expand_N_Case_Statement --
2271    -----------------------------
2272
2273    procedure Expand_N_Case_Statement (N : Node_Id) is
2274       Loc    : constant Source_Ptr := Sloc (N);
2275       Expr   : constant Node_Id    := Expression (N);
2276       Alt    : Node_Id;
2277       Len    : Nat;
2278       Cond   : Node_Id;
2279       Choice : Node_Id;
2280       Chlist : List_Id;
2281
2282    begin
2283       --  Check for the situation where we know at compile time which branch
2284       --  will be taken
2285
2286       if Compile_Time_Known_Value (Expr) then
2287          Alt := Find_Static_Alternative (N);
2288
2289          --  Move statements from this alternative after the case statement.
2290          --  They are already analyzed, so will be skipped by the analyzer.
2291
2292          Insert_List_After (N, Statements (Alt));
2293
2294          --  That leaves the case statement as a shell. So now we can kill all
2295          --  other alternatives in the case statement.
2296
2297          Kill_Dead_Code (Expression (N));
2298
2299          declare
2300             A : Node_Id;
2301
2302          begin
2303             --  Loop through case alternatives, skipping pragmas, and skipping
2304             --  the one alternative that we select (and therefore retain).
2305
2306             A := First (Alternatives (N));
2307             while Present (A) loop
2308                if A /= Alt
2309                  and then Nkind (A) = N_Case_Statement_Alternative
2310                then
2311                   Kill_Dead_Code (Statements (A), Warn_On_Deleted_Code);
2312                end if;
2313
2314                Next (A);
2315             end loop;
2316          end;
2317
2318          Rewrite (N, Make_Null_Statement (Loc));
2319          return;
2320       end if;
2321
2322       --  Here if the choice is not determined at compile time
2323
2324       declare
2325          Last_Alt : constant Node_Id := Last (Alternatives (N));
2326
2327          Others_Present : Boolean;
2328          Others_Node    : Node_Id;
2329
2330          Then_Stms : List_Id;
2331          Else_Stms : List_Id;
2332
2333       begin
2334          if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2335             Others_Present := True;
2336             Others_Node    := Last_Alt;
2337          else
2338             Others_Present := False;
2339          end if;
2340
2341          --  First step is to worry about possible invalid argument. The RM
2342          --  requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2343          --  outside the base range), then Constraint_Error must be raised.
2344
2345          --  Case of validity check required (validity checks are on, the
2346          --  expression is not known to be valid, and the case statement
2347          --  comes from source -- no need to validity check internally
2348          --  generated case statements).
2349
2350          if Validity_Check_Default then
2351             Ensure_Valid (Expr);
2352          end if;
2353
2354          --  If there is only a single alternative, just replace it with the
2355          --  sequence of statements since obviously that is what is going to
2356          --  be executed in all cases.
2357
2358          Len := List_Length (Alternatives (N));
2359
2360          if Len = 1 then
2361             --  We still need to evaluate the expression if it has any
2362             --  side effects.
2363
2364             Remove_Side_Effects (Expression (N));
2365
2366             Insert_List_After (N, Statements (First (Alternatives (N))));
2367
2368             --  That leaves the case statement as a shell. The alternative that
2369             --  will be executed is reset to a null list. So now we can kill
2370             --  the entire case statement.
2371
2372             Kill_Dead_Code (Expression (N));
2373             Rewrite (N, Make_Null_Statement (Loc));
2374             return;
2375          end if;
2376
2377          --  An optimization. If there are only two alternatives, and only
2378          --  a single choice, then rewrite the whole case statement as an
2379          --  if statement, since this can result in subsequent optimizations.
2380          --  This helps not only with case statements in the source of a
2381          --  simple form, but also with generated code (discriminant check
2382          --  functions in particular)
2383
2384          if Len = 2 then
2385             Chlist := Discrete_Choices (First (Alternatives (N)));
2386
2387             if List_Length (Chlist) = 1 then
2388                Choice := First (Chlist);
2389
2390                Then_Stms := Statements (First (Alternatives (N)));
2391                Else_Stms := Statements (Last  (Alternatives (N)));
2392
2393                --  For TRUE, generate "expression", not expression = true
2394
2395                if Nkind (Choice) = N_Identifier
2396                  and then Entity (Choice) = Standard_True
2397                then
2398                   Cond := Expression (N);
2399
2400                --  For FALSE, generate "expression" and switch then/else
2401
2402                elsif Nkind (Choice) = N_Identifier
2403                  and then Entity (Choice) = Standard_False
2404                then
2405                   Cond := Expression (N);
2406                   Else_Stms := Statements (First (Alternatives (N)));
2407                   Then_Stms := Statements (Last  (Alternatives (N)));
2408
2409                --  For a range, generate "expression in range"
2410
2411                elsif Nkind (Choice) = N_Range
2412                  or else (Nkind (Choice) = N_Attribute_Reference
2413                            and then Attribute_Name (Choice) = Name_Range)
2414                  or else (Is_Entity_Name (Choice)
2415                            and then Is_Type (Entity (Choice)))
2416                  or else Nkind (Choice) = N_Subtype_Indication
2417                then
2418                   Cond :=
2419                     Make_In (Loc,
2420                       Left_Opnd  => Expression (N),
2421                       Right_Opnd => Relocate_Node (Choice));
2422
2423                --  For any other subexpression "expression = value"
2424
2425                else
2426                   Cond :=
2427                     Make_Op_Eq (Loc,
2428                       Left_Opnd  => Expression (N),
2429                       Right_Opnd => Relocate_Node (Choice));
2430                end if;
2431
2432                --  Now rewrite the case as an IF
2433
2434                Rewrite (N,
2435                  Make_If_Statement (Loc,
2436                    Condition => Cond,
2437                    Then_Statements => Then_Stms,
2438                    Else_Statements => Else_Stms));
2439                Analyze (N);
2440                return;
2441             end if;
2442          end if;
2443
2444          --  If the last alternative is not an Others choice, replace it with
2445          --  an N_Others_Choice. Note that we do not bother to call Analyze on
2446          --  the modified case statement, since it's only effect would be to
2447          --  compute the contents of the Others_Discrete_Choices which is not
2448          --  needed by the back end anyway.
2449
2450          --  The reason we do this is that the back end always needs some
2451          --  default for a switch, so if we have not supplied one in the
2452          --  processing above for validity checking, then we need to supply
2453          --  one here.
2454
2455          if not Others_Present then
2456             Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2457             Set_Others_Discrete_Choices
2458               (Others_Node, Discrete_Choices (Last_Alt));
2459             Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2460          end if;
2461       end;
2462    end Expand_N_Case_Statement;
2463
2464    -----------------------------
2465    -- Expand_N_Exit_Statement --
2466    -----------------------------
2467
2468    --  The only processing required is to deal with a possible C/Fortran
2469    --  boolean value used as the condition for the exit statement.
2470
2471    procedure Expand_N_Exit_Statement (N : Node_Id) is
2472    begin
2473       Adjust_Condition (Condition (N));
2474    end Expand_N_Exit_Statement;
2475
2476    -----------------------------
2477    -- Expand_N_Goto_Statement --
2478    -----------------------------
2479
2480    --  Add poll before goto if polling active
2481
2482    procedure Expand_N_Goto_Statement (N : Node_Id) is
2483    begin
2484       Generate_Poll_Call (N);
2485    end Expand_N_Goto_Statement;
2486
2487    ---------------------------
2488    -- Expand_N_If_Statement --
2489    ---------------------------
2490
2491    --  First we deal with the case of C and Fortran convention boolean values,
2492    --  with zero/non-zero semantics.
2493
2494    --  Second, we deal with the obvious rewriting for the cases where the
2495    --  condition of the IF is known at compile time to be True or False.
2496
2497    --  Third, we remove elsif parts which have non-empty Condition_Actions and
2498    --  rewrite as independent if statements. For example:
2499
2500    --     if x then xs
2501    --     elsif y then ys
2502    --     ...
2503    --     end if;
2504
2505    --  becomes
2506    --
2507    --     if x then xs
2508    --     else
2509    --        <<condition actions of y>>
2510    --        if y then ys
2511    --        ...
2512    --        end if;
2513    --     end if;
2514
2515    --  This rewriting is needed if at least one elsif part has a non-empty
2516    --  Condition_Actions list. We also do the same processing if there is a
2517    --  constant condition in an elsif part (in conjunction with the first
2518    --  processing step mentioned above, for the recursive call made to deal
2519    --  with the created inner if, this deals with properly optimizing the
2520    --  cases of constant elsif conditions).
2521
2522    procedure Expand_N_If_Statement (N : Node_Id) is
2523       Loc    : constant Source_Ptr := Sloc (N);
2524       Hed    : Node_Id;
2525       E      : Node_Id;
2526       New_If : Node_Id;
2527
2528       Warn_If_Deleted : constant Boolean :=
2529                           Warn_On_Deleted_Code and then Comes_From_Source (N);
2530       --  Indicates whether we want warnings when we delete branches of the
2531       --  if statement based on constant condition analysis. We never want
2532       --  these warnings for expander generated code.
2533
2534    begin
2535       Adjust_Condition (Condition (N));
2536
2537       --  The following loop deals with constant conditions for the IF. We
2538       --  need a loop because as we eliminate False conditions, we grab the
2539       --  first elsif condition and use it as the primary condition.
2540
2541       while Compile_Time_Known_Value (Condition (N)) loop
2542
2543          --  If condition is True, we can simply rewrite the if statement now
2544          --  by replacing it by the series of then statements.
2545
2546          if Is_True (Expr_Value (Condition (N))) then
2547
2548             --  All the else parts can be killed
2549
2550             Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
2551             Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
2552
2553             Hed := Remove_Head (Then_Statements (N));
2554             Insert_List_After (N, Then_Statements (N));
2555             Rewrite (N, Hed);
2556             return;
2557
2558          --  If condition is False, then we can delete the condition and
2559          --  the Then statements
2560
2561          else
2562             --  We do not delete the condition if constant condition warnings
2563             --  are enabled, since otherwise we end up deleting the desired
2564             --  warning. Of course the backend will get rid of this True/False
2565             --  test anyway, so nothing is lost here.
2566
2567             if not Constant_Condition_Warnings then
2568                Kill_Dead_Code (Condition (N));
2569             end if;
2570
2571             Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
2572
2573             --  If there are no elsif statements, then we simply replace the
2574             --  entire if statement by the sequence of else statements.
2575
2576             if No (Elsif_Parts (N)) then
2577                if No (Else_Statements (N))
2578                  or else Is_Empty_List (Else_Statements (N))
2579                then
2580                   Rewrite (N,
2581                     Make_Null_Statement (Sloc (N)));
2582                else
2583                   Hed := Remove_Head (Else_Statements (N));
2584                   Insert_List_After (N, Else_Statements (N));
2585                   Rewrite (N, Hed);
2586                end if;
2587
2588                return;
2589
2590             --  If there are elsif statements, the first of them becomes the
2591             --  if/then section of the rebuilt if statement This is the case
2592             --  where we loop to reprocess this copied condition.
2593
2594             else
2595                Hed := Remove_Head (Elsif_Parts (N));
2596                Insert_Actions      (N, Condition_Actions (Hed));
2597                Set_Condition       (N, Condition (Hed));
2598                Set_Then_Statements (N, Then_Statements (Hed));
2599
2600                --  Hed might have been captured as the condition determining
2601                --  the current value for an entity. Now it is detached from
2602                --  the tree, so a Current_Value pointer in the condition might
2603                --  need to be updated.
2604
2605                Set_Current_Value_Condition (N);
2606
2607                if Is_Empty_List (Elsif_Parts (N)) then
2608                   Set_Elsif_Parts (N, No_List);
2609                end if;
2610             end if;
2611          end if;
2612       end loop;
2613
2614       --  Loop through elsif parts, dealing with constant conditions and
2615       --  possible expression actions that are present.
2616
2617       if Present (Elsif_Parts (N)) then
2618          E := First (Elsif_Parts (N));
2619          while Present (E) loop
2620             Adjust_Condition (Condition (E));
2621
2622             --  If there are condition actions, then rewrite the if statement
2623             --  as indicated above. We also do the same rewrite for a True or
2624             --  False condition. The further processing of this constant
2625             --  condition is then done by the recursive call to expand the
2626             --  newly created if statement
2627
2628             if Present (Condition_Actions (E))
2629               or else Compile_Time_Known_Value (Condition (E))
2630             then
2631                --  Note this is not an implicit if statement, since it is part
2632                --  of an explicit if statement in the source (or of an implicit
2633                --  if statement that has already been tested).
2634
2635                New_If :=
2636                  Make_If_Statement (Sloc (E),
2637                    Condition       => Condition (E),
2638                    Then_Statements => Then_Statements (E),
2639                    Elsif_Parts     => No_List,
2640                    Else_Statements => Else_Statements (N));
2641
2642                --  Elsif parts for new if come from remaining elsif's of parent
2643
2644                while Present (Next (E)) loop
2645                   if No (Elsif_Parts (New_If)) then
2646                      Set_Elsif_Parts (New_If, New_List);
2647                   end if;
2648
2649                   Append (Remove_Next (E), Elsif_Parts (New_If));
2650                end loop;
2651
2652                Set_Else_Statements (N, New_List (New_If));
2653
2654                if Present (Condition_Actions (E)) then
2655                   Insert_List_Before (New_If, Condition_Actions (E));
2656                end if;
2657
2658                Remove (E);
2659
2660                if Is_Empty_List (Elsif_Parts (N)) then
2661                   Set_Elsif_Parts (N, No_List);
2662                end if;
2663
2664                Analyze (New_If);
2665                return;
2666
2667             --  No special processing for that elsif part, move to next
2668
2669             else
2670                Next (E);
2671             end if;
2672          end loop;
2673       end if;
2674
2675       --  Some more optimizations applicable if we still have an IF statement
2676
2677       if Nkind (N) /= N_If_Statement then
2678          return;
2679       end if;
2680
2681       --  Another optimization, special cases that can be simplified
2682
2683       --     if expression then
2684       --        return true;
2685       --     else
2686       --        return false;
2687       --     end if;
2688
2689       --  can be changed to:
2690
2691       --     return expression;
2692
2693       --  and
2694
2695       --     if expression then
2696       --        return false;
2697       --     else
2698       --        return true;
2699       --     end if;
2700
2701       --  can be changed to:
2702
2703       --     return not (expression);
2704
2705       --  Only do these optimizations if we are at least at -O1 level and
2706       --  do not do them if control flow optimizations are suppressed.
2707
2708       if Optimization_Level > 0
2709         and then not Opt.Suppress_Control_Flow_Optimizations
2710       then
2711          if Nkind (N) = N_If_Statement
2712            and then No (Elsif_Parts (N))
2713            and then Present (Else_Statements (N))
2714            and then List_Length (Then_Statements (N)) = 1
2715            and then List_Length (Else_Statements (N)) = 1
2716          then
2717             declare
2718                Then_Stm : constant Node_Id := First (Then_Statements (N));
2719                Else_Stm : constant Node_Id := First (Else_Statements (N));
2720
2721             begin
2722                if Nkind (Then_Stm) = N_Simple_Return_Statement
2723                     and then
2724                   Nkind (Else_Stm) = N_Simple_Return_Statement
2725                then
2726                   declare
2727                      Then_Expr : constant Node_Id := Expression (Then_Stm);
2728                      Else_Expr : constant Node_Id := Expression (Else_Stm);
2729
2730                   begin
2731                      if Nkind (Then_Expr) = N_Identifier
2732                           and then
2733                         Nkind (Else_Expr) = N_Identifier
2734                      then
2735                         if Entity (Then_Expr) = Standard_True
2736                           and then Entity (Else_Expr) = Standard_False
2737                         then
2738                            Rewrite (N,
2739                              Make_Simple_Return_Statement (Loc,
2740                                Expression => Relocate_Node (Condition (N))));
2741                            Analyze (N);
2742                            return;
2743
2744                         elsif Entity (Then_Expr) = Standard_False
2745                           and then Entity (Else_Expr) = Standard_True
2746                         then
2747                            Rewrite (N,
2748                              Make_Simple_Return_Statement (Loc,
2749                                Expression =>
2750                                  Make_Op_Not (Loc,
2751                                    Right_Opnd =>
2752                                      Relocate_Node (Condition (N)))));
2753                            Analyze (N);
2754                            return;
2755                         end if;
2756                      end if;
2757                   end;
2758                end if;
2759             end;
2760          end if;
2761       end if;
2762    end Expand_N_If_Statement;
2763
2764    --------------------------
2765    -- Expand_Iterator_Loop --
2766    --------------------------
2767
2768    procedure Expand_Iterator_Loop (N : Node_Id) is
2769       Loc        : constant Source_Ptr := Sloc (N);
2770       Isc        : constant Node_Id    := Iteration_Scheme (N);
2771       I_Spec     : constant Node_Id    := Iterator_Specification (Isc);
2772       Id         : constant Entity_Id  := Defining_Identifier (I_Spec);
2773
2774       Container : constant Node_Id := Name (I_Spec);
2775       --  An expression whose type is an array or a predefined container
2776
2777       Typ : constant Entity_Id  := Etype (Container);
2778
2779       Cursor   : Entity_Id;
2780       New_Loop : Node_Id;
2781       Stats    : List_Id;
2782
2783    begin
2784       if Is_Array_Type (Typ) then
2785          if Of_Present (I_Spec) then
2786             Cursor := Make_Temporary (Loc, 'C');
2787
2788             --  for Elem of Arr loop ...
2789
2790             declare
2791                Decl : constant Node_Id :=
2792                         Make_Object_Renaming_Declaration (Loc,
2793                           Defining_Identifier => Id,
2794                           Subtype_Mark        =>
2795                             New_Occurrence_Of (Component_Type (Typ), Loc),
2796                           Name                =>
2797                             Make_Indexed_Component (Loc,
2798                               Prefix      => Relocate_Node (Container),
2799                               Expressions =>
2800                                 New_List (New_Occurrence_Of (Cursor, Loc))));
2801             begin
2802                Stats := Statements (N);
2803                Prepend (Decl, Stats);
2804
2805                New_Loop :=
2806                  Make_Loop_Statement (Loc,
2807                    Iteration_Scheme =>
2808                      Make_Iteration_Scheme (Loc,
2809                        Loop_Parameter_Specification =>
2810                          Make_Loop_Parameter_Specification (Loc,
2811                            Defining_Identifier         => Cursor,
2812                            Discrete_Subtype_Definition =>
2813                               Make_Attribute_Reference (Loc,
2814                                 Prefix         => Relocate_Node (Container),
2815                                 Attribute_Name => Name_Range),
2816                            Reverse_Present => Reverse_Present (I_Spec))),
2817                    Statements       => Stats,
2818                    End_Label        => Empty);
2819             end;
2820
2821          else
2822             --  for Index in Array loop ...
2823
2824             --  The cursor (index into the array) is the source Id
2825
2826             Cursor := Id;
2827             New_Loop :=
2828               Make_Loop_Statement (Loc,
2829                 Iteration_Scheme =>
2830                   Make_Iteration_Scheme (Loc,
2831                     Loop_Parameter_Specification =>
2832                       Make_Loop_Parameter_Specification (Loc,
2833                         Defining_Identifier         => Cursor,
2834                         Discrete_Subtype_Definition =>
2835                            Make_Attribute_Reference (Loc,
2836                              Prefix         => Relocate_Node (Container),
2837                              Attribute_Name => Name_Range),
2838                         Reverse_Present => Reverse_Present (I_Spec))),
2839                 Statements       => Statements (N),
2840                 End_Label        => Empty);
2841          end if;
2842
2843       --  Iterators over containers
2844
2845       else
2846          --  In both cases these require a cursor of the proper type
2847
2848          --    Cursor : P.Cursor_Type := Container.First;
2849          --    while Cursor /= P.No_Element loop
2850
2851          --       Obj : P.Element_Type renames Element (Cursor);
2852          --       --  For the "of" form, the element name renames the element
2853          --       --  designated by the cursor.
2854
2855          --       Statements;
2856          --       P.Next (Cursor);
2857          --    end loop;
2858
2859          --  with the obvious replacements if "reverse" is specified.
2860
2861          declare
2862             Element_Type  : constant Entity_Id := Etype (Id);
2863             Pack          : constant Entity_Id := Scope (Etype (Container));
2864             Name_Init     : Name_Id;
2865             Name_Step     : Name_Id;
2866             Cond          : Node_Id;
2867             Cursor_Decl   : Node_Id;
2868             Renaming_Decl : Node_Id;
2869
2870          begin
2871             Stats := Statements (N);
2872
2873             if Of_Present (I_Spec) then
2874                Cursor := Make_Temporary (Loc, 'C');
2875             else
2876                Cursor := Id;
2877             end if;
2878
2879             if Reverse_Present (I_Spec) then
2880
2881                --  Must verify that the container has a reverse iterator ???
2882
2883                Name_Init := Name_Last;
2884                Name_Step := Name_Previous;
2885
2886             else
2887                Name_Init := Name_First;
2888                Name_Step := Name_Next;
2889             end if;
2890
2891             --  C : Cursor_Type := Container.First;
2892
2893             Cursor_Decl :=
2894               Make_Object_Declaration (Loc,
2895                 Defining_Identifier => Cursor,
2896                 Object_Definition   =>
2897                   Make_Selected_Component (Loc,
2898                     Prefix        => New_Occurrence_Of (Pack, Loc),
2899                     Selector_Name => Make_Identifier (Loc, Name_Cursor)),
2900                 Expression =>
2901                   Make_Selected_Component (Loc,
2902                     Prefix        => Relocate_Node (Container),
2903                     Selector_Name => Make_Identifier (Loc, Name_Init)));
2904
2905             Insert_Action (N, Cursor_Decl);
2906
2907             --  while C /= No_Element loop
2908
2909             Cond := Make_Op_Ne (Loc,
2910                       Left_Opnd  => New_Occurrence_Of (Cursor, Loc),
2911                       Right_Opnd => Make_Selected_Component (Loc,
2912                          Prefix        => New_Occurrence_Of (Pack, Loc),
2913                          Selector_Name =>
2914                            Make_Identifier (Loc, Name_No_Element)));
2915
2916             if Of_Present (I_Spec) then
2917
2918                --  Id : Element_Type renames Pack.Element (Cursor);
2919
2920                Renaming_Decl :=
2921                  Make_Object_Renaming_Declaration (Loc,
2922                    Defining_Identifier => Id,
2923                    Subtype_Mark        =>
2924                      New_Occurrence_Of (Element_Type, Loc),
2925                    Name                =>
2926                      Make_Indexed_Component (Loc,
2927                        Prefix =>
2928                          Make_Selected_Component (Loc,
2929                            Prefix        =>  New_Occurrence_Of (Pack, Loc),
2930                            Selector_Name =>
2931                              Make_Identifier (Loc, Chars => Name_Element)),
2932                        Expressions =>
2933                          New_List (New_Occurrence_Of (Cursor, Loc))));
2934
2935                Prepend (Renaming_Decl, Stats);
2936             end if;
2937
2938             --  For both iterator forms, add call to step operation (Next or
2939             --  Previous) to advance cursor.
2940
2941             Append_To (Stats,
2942               Make_Procedure_Call_Statement (Loc,
2943                 Name =>
2944                   Make_Selected_Component (Loc,
2945                     Prefix        => New_Occurrence_Of (Pack, Loc),
2946                     Selector_Name => Make_Identifier (Loc, Name_Step)),
2947                 Parameter_Associations =>
2948                   New_List (New_Occurrence_Of (Cursor, Loc))));
2949
2950             New_Loop := Make_Loop_Statement (Loc,
2951               Iteration_Scheme =>
2952                 Make_Iteration_Scheme (Loc, Condition => Cond),
2953               Statements       => Stats,
2954               End_Label        => Empty);
2955          end;
2956       end if;
2957
2958       Rewrite (N, New_Loop);
2959       Analyze (N);
2960    end Expand_Iterator_Loop;
2961
2962    -----------------------------
2963    -- Expand_N_Loop_Statement --
2964    -----------------------------
2965
2966    --  1. Remove null loop entirely
2967    --  2. Deal with while condition for C/Fortran boolean
2968    --  3. Deal with loops with a non-standard enumeration type range
2969    --  4. Deal with while loops where Condition_Actions is set
2970    --  5. Deal with loops over predicated subtypes
2971    --  6. Deal with loops with iterators over arrays and containers
2972    --  7. Insert polling call if required
2973
2974    procedure Expand_N_Loop_Statement (N : Node_Id) is
2975       Loc  : constant Source_Ptr := Sloc (N);
2976       Isc  : constant Node_Id    := Iteration_Scheme (N);
2977
2978    begin
2979       --  Delete null loop
2980
2981       if Is_Null_Loop (N) then
2982          Rewrite (N, Make_Null_Statement (Loc));
2983          return;
2984       end if;
2985
2986       --  Deal with condition for C/Fortran Boolean
2987
2988       if Present (Isc) then
2989          Adjust_Condition (Condition (Isc));
2990       end if;
2991
2992       --  Generate polling call
2993
2994       if Is_Non_Empty_List (Statements (N)) then
2995          Generate_Poll_Call (First (Statements (N)));
2996       end if;
2997
2998       --  Nothing more to do for plain loop with no iteration scheme
2999
3000       if No (Isc) then
3001          null;
3002
3003       --  Case of for loop (Loop_Parameter_Specification present)
3004
3005       --  Note: we do not have to worry about validity checking of the for loop
3006       --  range bounds here, since they were frozen with constant declarations
3007       --  and it is during that process that the validity checking is done.
3008
3009       elsif Present (Loop_Parameter_Specification (Isc)) then
3010          declare
3011             LPS     : constant Node_Id   := Loop_Parameter_Specification (Isc);
3012             Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
3013             Ltype   : constant Entity_Id := Etype (Loop_Id);
3014             Btype   : constant Entity_Id := Base_Type (Ltype);
3015             Expr    : Node_Id;
3016             New_Id  : Entity_Id;
3017
3018          begin
3019             --  Deal with loop over predicates
3020
3021             if Is_Discrete_Type (Ltype)
3022               and then Present (Predicate_Function (Ltype))
3023             then
3024                Expand_Predicated_Loop (N);
3025
3026             --  Handle the case where we have a for loop with the range type
3027             --  being an enumeration type with non-standard representation.
3028             --  In this case we expand:
3029
3030             --    for x in [reverse] a .. b loop
3031             --       ...
3032             --    end loop;
3033
3034             --  to
3035
3036             --    for xP in [reverse] integer
3037             --      range etype'Pos (a) .. etype'Pos (b)
3038             --    loop
3039             --       declare
3040             --          x : constant etype := Pos_To_Rep (xP);
3041             --       begin
3042             --          ...
3043             --       end;
3044             --    end loop;
3045
3046             elsif Is_Enumeration_Type (Btype)
3047               and then Present (Enum_Pos_To_Rep (Btype))
3048             then
3049                New_Id :=
3050                  Make_Defining_Identifier (Loc,
3051                    Chars => New_External_Name (Chars (Loop_Id), 'P'));
3052
3053                --  If the type has a contiguous representation, successive
3054                --  values can be generated as offsets from the first literal.
3055
3056                if Has_Contiguous_Rep (Btype) then
3057                   Expr :=
3058                      Unchecked_Convert_To (Btype,
3059                        Make_Op_Add (Loc,
3060                          Left_Opnd =>
3061                             Make_Integer_Literal (Loc,
3062                               Enumeration_Rep (First_Literal (Btype))),
3063                          Right_Opnd => New_Reference_To (New_Id, Loc)));
3064                else
3065                   --  Use the constructed array Enum_Pos_To_Rep
3066
3067                   Expr :=
3068                     Make_Indexed_Component (Loc,
3069                       Prefix      =>
3070                         New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
3071                       Expressions =>
3072                         New_List (New_Reference_To (New_Id, Loc)));
3073                end if;
3074
3075                Rewrite (N,
3076                  Make_Loop_Statement (Loc,
3077                    Identifier => Identifier (N),
3078
3079                    Iteration_Scheme =>
3080                      Make_Iteration_Scheme (Loc,
3081                        Loop_Parameter_Specification =>
3082                          Make_Loop_Parameter_Specification (Loc,
3083                            Defining_Identifier => New_Id,
3084                            Reverse_Present => Reverse_Present (LPS),
3085
3086                            Discrete_Subtype_Definition =>
3087                              Make_Subtype_Indication (Loc,
3088
3089                                Subtype_Mark =>
3090                                  New_Reference_To (Standard_Natural, Loc),
3091
3092                                Constraint =>
3093                                  Make_Range_Constraint (Loc,
3094                                    Range_Expression =>
3095                                      Make_Range (Loc,
3096
3097                                        Low_Bound =>
3098                                          Make_Attribute_Reference (Loc,
3099                                            Prefix =>
3100                                              New_Reference_To (Btype, Loc),
3101
3102                                            Attribute_Name => Name_Pos,
3103
3104                                            Expressions => New_List (
3105                                              Relocate_Node
3106                                                (Type_Low_Bound (Ltype)))),
3107
3108                                        High_Bound =>
3109                                          Make_Attribute_Reference (Loc,
3110                                            Prefix =>
3111                                              New_Reference_To (Btype, Loc),
3112
3113                                            Attribute_Name => Name_Pos,
3114
3115                                            Expressions => New_List (
3116                                              Relocate_Node
3117                                                (Type_High_Bound
3118                                                   (Ltype))))))))),
3119
3120                    Statements => New_List (
3121                      Make_Block_Statement (Loc,
3122                        Declarations => New_List (
3123                          Make_Object_Declaration (Loc,
3124                            Defining_Identifier => Loop_Id,
3125                            Constant_Present    => True,
3126                            Object_Definition   =>
3127                              New_Reference_To (Ltype, Loc),
3128                            Expression          => Expr)),
3129
3130                        Handled_Statement_Sequence =>
3131                          Make_Handled_Sequence_Of_Statements (Loc,
3132                            Statements => Statements (N)))),
3133
3134                    End_Label => End_Label (N)));
3135                Analyze (N);
3136
3137             --  Nothing to do with other cases of for loops
3138
3139             else
3140                null;
3141             end if;
3142          end;
3143
3144       --  Second case, if we have a while loop with Condition_Actions set, then
3145       --  we change it into a plain loop:
3146
3147       --    while C loop
3148       --       ...
3149       --    end loop;
3150
3151       --  changed to:
3152
3153       --    loop
3154       --       <<condition actions>>
3155       --       exit when not C;
3156       --       ...
3157       --    end loop
3158
3159       elsif Present (Isc)
3160         and then Present (Condition_Actions (Isc))
3161       then
3162          declare
3163             ES : Node_Id;
3164
3165          begin
3166             ES :=
3167               Make_Exit_Statement (Sloc (Condition (Isc)),
3168                 Condition =>
3169                   Make_Op_Not (Sloc (Condition (Isc)),
3170                     Right_Opnd => Condition (Isc)));
3171
3172             Prepend (ES, Statements (N));
3173             Insert_List_Before (ES, Condition_Actions (Isc));
3174
3175             --  This is not an implicit loop, since it is generated in response
3176             --  to the loop statement being processed. If this is itself
3177             --  implicit, the restriction has already been checked. If not,
3178             --  it is an explicit loop.
3179
3180             Rewrite (N,
3181               Make_Loop_Statement (Sloc (N),
3182                 Identifier => Identifier (N),
3183                 Statements => Statements (N),
3184                 End_Label  => End_Label  (N)));
3185
3186             Analyze (N);
3187          end;
3188
3189       --  Here to deal with iterator case
3190
3191       elsif Present (Isc)
3192         and then Present (Iterator_Specification (Isc))
3193       then
3194          Expand_Iterator_Loop (N);
3195       end if;
3196    end Expand_N_Loop_Statement;
3197
3198    ----------------------------
3199    -- Expand_Predicated_Loop --
3200    ----------------------------
3201
3202    --  Note: the expander can handle generation of loops over predicated
3203    --  subtypes for both the dynamic and static cases. Depending on what
3204    --  we decide is allowed in Ada 2012 mode and/or extensions allowed
3205    --  mode, the semantic analyzer may disallow one or both forms.
3206
3207    procedure Expand_Predicated_Loop (N : Node_Id) is
3208       Loc     : constant Source_Ptr := Sloc (N);
3209       Isc     : constant Node_Id    := Iteration_Scheme (N);
3210       LPS     : constant Node_Id    := Loop_Parameter_Specification (Isc);
3211       Loop_Id : constant Entity_Id  := Defining_Identifier (LPS);
3212       Ltype   : constant Entity_Id  := Etype (Loop_Id);
3213       Stat    : constant List_Id    := Static_Predicate (Ltype);
3214       Stmts   : constant List_Id    := Statements (N);
3215
3216    begin
3217       --  Case of iteration over non-static predicate, should not be possible
3218       --  since this is not allowed by the semantics and should have been
3219       --  caught during analysis of the loop statement.
3220
3221       if No (Stat) then
3222          raise Program_Error;
3223
3224       --  If the predicate list is empty, that corresponds to a predicate of
3225       --  False, in which case the loop won't run at all, and we rewrite the
3226       --  entire loop as a null statement.
3227
3228       elsif Is_Empty_List (Stat) then
3229          Rewrite (N, Make_Null_Statement (Loc));
3230          Analyze (N);
3231
3232       --  For expansion over a static predicate we generate the following
3233
3234       --     declare
3235       --        J : Ltype := min-val;
3236       --     begin
3237       --        loop
3238       --           body
3239       --           case J is
3240       --              when endpoint => J := startpoint;
3241       --              when endpoint => J := startpoint;
3242       --              ...
3243       --              when max-val  => exit;
3244       --              when others   => J := Lval'Succ (J);
3245       --           end case;
3246       --        end loop;
3247       --     end;
3248
3249       --  To make this a little clearer, let's take a specific example:
3250
3251       --        type Int is range 1 .. 10;
3252       --        subtype L is Int with
3253       --          predicate => L in 3 | 10 | 5 .. 7;
3254       --          ...
3255       --        for L in StaticP loop
3256       --           Put_Line ("static:" & J'Img);
3257       --        end loop;
3258
3259       --  In this case, the loop is transformed into
3260
3261       --     begin
3262       --        J : L := 3;
3263       --        loop
3264       --           body
3265       --           case J is
3266       --              when 3  => J := 5;
3267       --              when 7  => J := 10;
3268       --              when 10 => exit;
3269       --              when others  => J := L'Succ (J);
3270       --           end case;
3271       --        end loop;
3272       --     end;
3273
3274       else
3275          Static_Predicate : declare
3276             S    : Node_Id;
3277             D    : Node_Id;
3278             P    : Node_Id;
3279             Alts : List_Id;
3280             Cstm : Node_Id;
3281
3282             function Lo_Val (N : Node_Id) return Node_Id;
3283             --  Given static expression or static range, returns an identifier
3284             --  whose value is the low bound of the expression value or range.
3285
3286             function Hi_Val (N : Node_Id) return Node_Id;
3287             --  Given static expression or static range, returns an identifier
3288             --  whose value is the high bound of the expression value or range.
3289
3290             ------------
3291             -- Hi_Val --
3292             ------------
3293
3294             function Hi_Val (N : Node_Id) return Node_Id is
3295             begin
3296                if Is_Static_Expression (N) then
3297                   return New_Copy (N);
3298                else
3299                   pragma Assert (Nkind (N) = N_Range);
3300                   return New_Copy (High_Bound (N));
3301                end if;
3302             end Hi_Val;
3303
3304             ------------
3305             -- Lo_Val --
3306             ------------
3307
3308             function Lo_Val (N : Node_Id) return Node_Id is
3309             begin
3310                if Is_Static_Expression (N) then
3311                   return New_Copy (N);
3312                else
3313                   pragma Assert (Nkind (N) = N_Range);
3314                   return New_Copy (Low_Bound (N));
3315                end if;
3316             end Lo_Val;
3317
3318          --  Start of processing for Static_Predicate
3319
3320          begin
3321             --  Convert loop identifier to normal variable and reanalyze it so
3322             --  that this conversion works. We have to use the same defining
3323             --  identifier, since there may be references in the loop body.
3324
3325             Set_Analyzed (Loop_Id, False);
3326             Set_Ekind    (Loop_Id, E_Variable);
3327
3328             --  Loop to create branches of case statement
3329
3330             Alts := New_List;
3331             P := First (Stat);
3332             while Present (P) loop
3333                if No (Next (P)) then
3334                   S := Make_Exit_Statement (Loc);
3335                else
3336                   S :=
3337                     Make_Assignment_Statement (Loc,
3338                       Name       => New_Occurrence_Of (Loop_Id, Loc),
3339                       Expression => Lo_Val (Next (P)));
3340                   Set_Suppress_Assignment_Checks (S);
3341                end if;
3342
3343                Append_To (Alts,
3344                  Make_Case_Statement_Alternative (Loc,
3345                    Statements       => New_List (S),
3346                    Discrete_Choices => New_List (Hi_Val (P))));
3347
3348                Next (P);
3349             end loop;
3350
3351             --  Add others choice
3352
3353             S :=
3354                Make_Assignment_Statement (Loc,
3355                  Name       => New_Occurrence_Of (Loop_Id, Loc),
3356                  Expression =>
3357                    Make_Attribute_Reference (Loc,
3358                      Prefix => New_Occurrence_Of (Ltype, Loc),
3359                      Attribute_Name => Name_Succ,
3360                      Expressions    => New_List (
3361                        New_Occurrence_Of (Loop_Id, Loc))));
3362             Set_Suppress_Assignment_Checks (S);
3363
3364             Append_To (Alts,
3365               Make_Case_Statement_Alternative (Loc,
3366                 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
3367                 Statements       => New_List (S)));
3368
3369             --  Construct case statement and append to body statements
3370
3371             Cstm :=
3372               Make_Case_Statement (Loc,
3373                 Expression   => New_Occurrence_Of (Loop_Id, Loc),
3374                 Alternatives => Alts);
3375             Append_To (Stmts, Cstm);
3376
3377             --  Rewrite the loop
3378
3379             D :=
3380                Make_Object_Declaration (Loc,
3381                  Defining_Identifier => Loop_Id,
3382                  Object_Definition   => New_Occurrence_Of (Ltype, Loc),
3383                  Expression          => Lo_Val (First (Stat)));
3384             Set_Suppress_Assignment_Checks (D);
3385
3386             Rewrite (N,
3387               Make_Block_Statement (Loc,
3388                 Declarations               => New_List (D),
3389                 Handled_Statement_Sequence =>
3390                   Make_Handled_Sequence_Of_Statements (Loc,
3391                     Statements => New_List (
3392                       Make_Loop_Statement (Loc,
3393                         Statements => Stmts,
3394                         End_Label  => Empty)))));
3395
3396             Analyze (N);
3397          end Static_Predicate;
3398       end if;
3399    end Expand_Predicated_Loop;
3400
3401    ------------------------------
3402    -- Make_Tag_Ctrl_Assignment --
3403    ------------------------------
3404
3405    function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
3406       Loc : constant Source_Ptr := Sloc (N);
3407       L   : constant Node_Id    := Name (N);
3408       T   : constant Entity_Id  := Underlying_Type (Etype (L));
3409
3410       Ctrl_Act : constant Boolean := Needs_Finalization (T)
3411                                        and then not No_Ctrl_Actions (N);
3412
3413       Component_Assign : constant Boolean :=
3414                            Is_Fully_Repped_Tagged_Type (T);
3415
3416       Save_Tag : constant Boolean := Is_Tagged_Type (T)
3417                                        and then not Component_Assign
3418                                        and then not No_Ctrl_Actions (N)
3419                                        and then Tagged_Type_Expansion;
3420       --  Tags are not saved and restored when VM_Target because VM tags are
3421       --  represented implicitly in objects.
3422
3423       Res      : List_Id;
3424       Tag_Tmp  : Entity_Id;
3425
3426       Prev_Tmp : Entity_Id;
3427       Next_Tmp : Entity_Id;
3428       Ctrl_Ref : Node_Id;
3429
3430    begin
3431       Res := New_List;
3432
3433       --  Finalize the target of the assignment when controlled
3434
3435       --  We have two exceptions here:
3436
3437       --   1. If we are in an init proc since it is an initialization more
3438       --      than an assignment.
3439
3440       --   2. If the left-hand side is a temporary that was not initialized
3441       --      (or the parent part of a temporary since it is the case in
3442       --      extension aggregates). Such a temporary does not come from
3443       --      source. We must examine the original node for the prefix, because
3444       --      it may be a component of an entry formal, in which case it has
3445       --      been rewritten and does not appear to come from source either.
3446
3447       --  Case of init proc
3448
3449       if not Ctrl_Act then
3450          null;
3451
3452       --  The left hand side is an uninitialized temporary object
3453
3454       elsif Nkind (L) = N_Type_Conversion
3455         and then Is_Entity_Name (Expression (L))
3456         and then Nkind (Parent (Entity (Expression (L)))) =
3457                                               N_Object_Declaration
3458         and then No_Initialization (Parent (Entity (Expression (L))))
3459       then
3460          null;
3461
3462       else
3463          Append_List_To (Res,
3464            Make_Final_Call
3465              (Ref         => Duplicate_Subexpr_No_Checks (L),
3466               Typ         => Etype (L),
3467               With_Detach => New_Reference_To (Standard_False, Loc)));
3468       end if;
3469
3470       --  Save the Tag in a local variable Tag_Tmp
3471
3472       if Save_Tag then
3473          Tag_Tmp := Make_Temporary (Loc, 'A');
3474
3475          Append_To (Res,
3476            Make_Object_Declaration (Loc,
3477              Defining_Identifier => Tag_Tmp,
3478              Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
3479              Expression =>
3480                Make_Selected_Component (Loc,
3481                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3482                  Selector_Name => New_Reference_To (First_Tag_Component (T),
3483                                                     Loc))));
3484
3485       --  Otherwise Tag_Tmp not used
3486
3487       else
3488          Tag_Tmp := Empty;
3489       end if;
3490
3491       if Ctrl_Act then
3492          if VM_Target /= No_VM then
3493
3494             --  Cannot assign part of the object in a VM context, so instead
3495             --  fallback to the previous mechanism, even though it is not
3496             --  completely correct ???
3497
3498             --  Save the Finalization Pointers in local variables Prev_Tmp and
3499             --  Next_Tmp. For objects with Has_Controlled_Component set, these
3500             --  pointers are in the Record_Controller
3501
3502             Ctrl_Ref := Duplicate_Subexpr (L);
3503
3504             if Has_Controlled_Component (T) then
3505                Ctrl_Ref :=
3506                  Make_Selected_Component (Loc,
3507                    Prefix => Ctrl_Ref,
3508                    Selector_Name =>
3509                      New_Reference_To (Controller_Component (T), Loc));
3510             end if;
3511
3512             Prev_Tmp := Make_Temporary (Loc, 'B');
3513
3514             Append_To (Res,
3515               Make_Object_Declaration (Loc,
3516                 Defining_Identifier => Prev_Tmp,
3517
3518                 Object_Definition =>
3519                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3520
3521                 Expression =>
3522                   Make_Selected_Component (Loc,
3523                     Prefix =>
3524                       Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref),
3525                     Selector_Name => Make_Identifier (Loc, Name_Prev))));
3526
3527             Next_Tmp := Make_Temporary (Loc, 'C');
3528
3529             Append_To (Res,
3530               Make_Object_Declaration (Loc,
3531                 Defining_Identifier => Next_Tmp,
3532
3533                 Object_Definition   =>
3534                   New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
3535
3536                 Expression          =>
3537                   Make_Selected_Component (Loc,
3538                     Prefix =>
3539                       Unchecked_Convert_To (RTE (RE_Finalizable),
3540                         New_Copy_Tree (Ctrl_Ref)),
3541                     Selector_Name => Make_Identifier (Loc, Name_Next))));
3542
3543             --  Do the Assignment
3544
3545             Append_To (Res, Relocate_Node (N));
3546
3547          else
3548             --  Regular (non VM) processing for controlled types and types with
3549             --  controlled components
3550
3551             --  Variables of such types contain pointers used to chain them in
3552             --  finalization lists, in addition to user data. These pointers
3553             --  are specific to each object of the type, not to the value being
3554             --  assigned.
3555
3556             --  Thus they need to be left intact during the assignment. We
3557             --  achieve this by constructing a Storage_Array subtype, and by
3558             --  overlaying objects of this type on the source and target of the
3559             --  assignment. The assignment is then rewritten to assignments of
3560             --  slices of these arrays, copying the user data, and leaving the
3561             --  pointers untouched.
3562
3563             Controlled_Actions : declare
3564                Prev_Ref : Node_Id;
3565                --  A reference to the Prev component of the record controller
3566
3567                First_After_Root : Node_Id := Empty;
3568                --  Index of first byte to be copied (used to skip
3569                --  Root_Controlled in controlled objects).
3570
3571                Last_Before_Hole : Node_Id := Empty;
3572                --  Index of last byte to be copied before outermost record
3573                --  controller data.
3574
3575                Hole_Length : Node_Id := Empty;
3576                --  Length of record controller data (Prev and Next pointers)
3577
3578                First_After_Hole : Node_Id := Empty;
3579                --  Index of first byte to be copied after outermost record
3580                --  controller data.
3581
3582                Expr, Source_Size     : Node_Id;
3583                Source_Actual_Subtype : Entity_Id;
3584                --  Used for computation of the size of the data to be copied
3585
3586                Range_Type  : Entity_Id;
3587                Opaque_Type : Entity_Id;
3588
3589                function Build_Slice
3590                  (Rec : Entity_Id;
3591                   Lo  : Node_Id;
3592                   Hi  : Node_Id) return Node_Id;
3593                --  Build and return a slice of an array of type S overlaid on
3594                --  object Rec, with bounds specified by Lo and Hi. If either
3595                --  bound is empty, a default of S'First (respectively S'Last)
3596                --  is used.
3597
3598                -----------------
3599                -- Build_Slice --
3600                -----------------
3601
3602                function Build_Slice
3603                  (Rec : Node_Id;
3604                   Lo  : Node_Id;
3605                   Hi  : Node_Id) return Node_Id
3606                is
3607                   Lo_Bound : Node_Id;
3608                   Hi_Bound : Node_Id;
3609
3610                   Opaque : constant Node_Id :=
3611                              Unchecked_Convert_To (Opaque_Type,
3612                                Make_Attribute_Reference (Loc,
3613                                  Prefix         => Rec,
3614                                  Attribute_Name => Name_Address));
3615                   --  Access value designating an opaque storage array of type
3616                   --  S overlaid on record Rec.
3617
3618                begin
3619                   --  Compute slice bounds using S'First (1) and S'Last as
3620                   --  default values when not specified by the caller.
3621
3622                   if No (Lo) then
3623                      Lo_Bound := Make_Integer_Literal (Loc, 1);
3624                   else
3625                      Lo_Bound := Lo;
3626                   end if;
3627
3628                   if No (Hi) then
3629                      Hi_Bound := Make_Attribute_Reference (Loc,
3630                        Prefix => New_Occurrence_Of (Range_Type, Loc),
3631                        Attribute_Name => Name_Last);
3632                   else
3633                      Hi_Bound := Hi;
3634                   end if;
3635
3636                   return Make_Slice (Loc,
3637                     Prefix =>
3638                       Opaque,
3639                     Discrete_Range => Make_Range (Loc,
3640                       Lo_Bound, Hi_Bound));
3641                end Build_Slice;
3642
3643             --  Start of processing for Controlled_Actions
3644
3645             begin
3646                --  Create a constrained subtype of Storage_Array whose size
3647                --  corresponds to the value being assigned.
3648
3649                --  subtype G is Storage_Offset range
3650                --    1 .. (Expr'Size + Storage_Unit - 1) / Storage_Unit
3651
3652                Expr := Duplicate_Subexpr_No_Checks (Expression (N));
3653
3654                if Nkind (Expr) = N_Qualified_Expression then
3655                   Expr := Expression (Expr);
3656                end if;
3657
3658                Source_Actual_Subtype := Etype (Expr);
3659
3660                if Has_Discriminants (Source_Actual_Subtype)
3661                  and then not Is_Constrained (Source_Actual_Subtype)
3662                then
3663                   Append_To (Res,
3664                     Build_Actual_Subtype (Source_Actual_Subtype, Expr));
3665                   Source_Actual_Subtype := Defining_Identifier (Last (Res));
3666                end if;
3667
3668                Source_Size :=
3669                  Make_Op_Add (Loc,
3670                    Left_Opnd =>
3671                      Make_Attribute_Reference (Loc,
3672                        Prefix =>
3673                          New_Occurrence_Of (Source_Actual_Subtype, Loc),
3674                      Attribute_Name => Name_Size),
3675                    Right_Opnd =>
3676                      Make_Integer_Literal (Loc,
3677                        Intval => System_Storage_Unit - 1));
3678
3679                Source_Size :=
3680                  Make_Op_Divide (Loc,
3681                    Left_Opnd => Source_Size,
3682                    Right_Opnd =>
3683                      Make_Integer_Literal (Loc,
3684                        Intval => System_Storage_Unit));
3685
3686                Range_Type := Make_Temporary (Loc, 'G');
3687
3688                Append_To (Res,
3689                  Make_Subtype_Declaration (Loc,
3690                    Defining_Identifier => Range_Type,
3691                    Subtype_Indication =>
3692                      Make_Subtype_Indication (Loc,
3693                        Subtype_Mark =>
3694                          New_Reference_To (RTE (RE_Storage_Offset), Loc),
3695                        Constraint   => Make_Range_Constraint (Loc,
3696                          Range_Expression =>
3697                            Make_Range (Loc,
3698                              Low_Bound  => Make_Integer_Literal (Loc, 1),
3699                              High_Bound => Source_Size)))));
3700
3701                --  subtype S is Storage_Array (G)
3702
3703                Append_To (Res,
3704                  Make_Subtype_Declaration (Loc,
3705                    Defining_Identifier => Make_Temporary (Loc, 'S'),
3706                    Subtype_Indication  =>
3707                      Make_Subtype_Indication (Loc,
3708                        Subtype_Mark =>
3709                          New_Reference_To (RTE (RE_Storage_Array), Loc),
3710                        Constraint =>
3711                          Make_Index_Or_Discriminant_Constraint (Loc,
3712                            Constraints =>
3713                              New_List (New_Reference_To (Range_Type, Loc))))));
3714
3715                --  type A is access S
3716
3717                Opaque_Type := Make_Temporary (Loc, 'A');
3718
3719                Append_To (Res,
3720                  Make_Full_Type_Declaration (Loc,
3721                    Defining_Identifier => Opaque_Type,
3722                    Type_Definition     =>
3723                      Make_Access_To_Object_Definition (Loc,
3724                        Subtype_Indication =>
3725                          New_Occurrence_Of (
3726                            Defining_Identifier (Last (Res)), Loc))));
3727
3728                --  Generate appropriate slice assignments
3729
3730                First_After_Root := Make_Integer_Literal (Loc, 1);
3731
3732                --  For controlled object, skip Root_Controlled part
3733
3734                if Is_Controlled (T) then
3735                   First_After_Root :=
3736                     Make_Op_Add (Loc,
3737                       First_After_Root,
3738                       Make_Op_Divide (Loc,
3739                         Make_Attribute_Reference (Loc,
3740                           Prefix =>
3741                             New_Occurrence_Of (RTE (RE_Root_Controlled), Loc),
3742                           Attribute_Name => Name_Size),
3743                         Make_Integer_Literal (Loc, System_Storage_Unit)));
3744                end if;
3745
3746                --  For the case of a record with controlled components, skip
3747                --  record controller Prev/Next components. These components
3748                --  constitute a 'hole' in the middle of the data to be copied.
3749
3750                if Has_Controlled_Component (T) then
3751                   Prev_Ref :=
3752                     Make_Selected_Component (Loc,
3753                       Prefix        =>
3754                         Make_Selected_Component (Loc,
3755                           Prefix => Duplicate_Subexpr_No_Checks (L),
3756                           Selector_Name =>
3757                             New_Reference_To (Controller_Component (T), Loc)),
3758                       Selector_Name =>  Make_Identifier (Loc, Name_Prev));
3759
3760                   --  Last index before hole: determined by position of the
3761                   --  _Controller.Prev component.
3762
3763                   Last_Before_Hole := Make_Temporary (Loc, 'L');
3764
3765                   Append_To (Res,
3766                     Make_Object_Declaration (Loc,
3767                       Defining_Identifier => Last_Before_Hole,
3768                       Object_Definition   => New_Occurrence_Of (
3769                         RTE (RE_Storage_Offset), Loc),
3770                       Constant_Present    => True,
3771                       Expression          =>
3772                         Make_Op_Add (Loc,
3773                           Make_Attribute_Reference (Loc,
3774                             Prefix => Prev_Ref,
3775                             Attribute_Name => Name_Position),
3776                           Make_Attribute_Reference (Loc,
3777                             Prefix => New_Copy_Tree (Prefix (Prev_Ref)),
3778                             Attribute_Name => Name_Position))));
3779
3780                   --  Hole length: size of the Prev and Next components
3781
3782                   Hole_Length :=
3783                     Make_Op_Multiply (Loc,
3784                       Left_Opnd  => Make_Integer_Literal (Loc, Uint_2),
3785                       Right_Opnd =>
3786                         Make_Op_Divide (Loc,
3787                           Left_Opnd =>
3788                             Make_Attribute_Reference (Loc,
3789                               Prefix         => New_Copy_Tree (Prev_Ref),
3790                               Attribute_Name => Name_Size),
3791                           Right_Opnd =>
3792                             Make_Integer_Literal (Loc,
3793                               Intval => System_Storage_Unit)));
3794
3795                   --  First index after hole
3796
3797                   First_After_Hole := Make_Temporary (Loc, 'F');
3798
3799                   Append_To (Res,
3800                     Make_Object_Declaration (Loc,
3801                       Defining_Identifier => First_After_Hole,
3802                       Object_Definition   => New_Occurrence_Of (
3803                         RTE (RE_Storage_Offset), Loc),
3804                       Constant_Present    => True,
3805                       Expression          =>
3806                         Make_Op_Add (Loc,
3807                           Left_Opnd  =>
3808                             Make_Op_Add (Loc,
3809                               Left_Opnd  =>
3810                                 New_Occurrence_Of (Last_Before_Hole, Loc),
3811                               Right_Opnd => Hole_Length),
3812                           Right_Opnd => Make_Integer_Literal (Loc, 1))));
3813
3814                   Last_Before_Hole :=
3815                     New_Occurrence_Of (Last_Before_Hole, Loc);
3816                   First_After_Hole :=
3817                     New_Occurrence_Of (First_After_Hole, Loc);
3818                end if;
3819
3820                --  Assign the first slice (possibly skipping Root_Controlled,
3821                --  up to the beginning of the record controller if present,
3822                --  up to the end of the object if not).
3823
3824                Append_To (Res, Make_Assignment_Statement (Loc,
3825                  Name       => Build_Slice (
3826                    Rec => Duplicate_Subexpr_No_Checks (L),
3827                    Lo  => First_After_Root,
3828                    Hi  => Last_Before_Hole),
3829
3830                  Expression => Build_Slice (
3831                    Rec => Expression (N),
3832                    Lo  => First_After_Root,
3833                    Hi  => New_Copy_Tree (Last_Before_Hole))));
3834
3835                if Present (First_After_Hole) then
3836
3837                   --  If a record controller is present, copy the second slice,
3838                   --  from right after the _Controller.Next component up to the
3839                   --  end of the object.
3840
3841                   Append_To (Res, Make_Assignment_Statement (Loc,
3842                     Name       => Build_Slice (
3843                       Rec => Duplicate_Subexpr_No_Checks (L),
3844                       Lo  => First_After_Hole,
3845                       Hi  => Empty),
3846                     Expression => Build_Slice (
3847                       Rec => Duplicate_Subexpr_No_Checks (Expression (N)),
3848                       Lo  => New_Copy_Tree (First_After_Hole),
3849                       Hi  => Empty)));
3850                end if;
3851             end Controlled_Actions;
3852          end if;
3853
3854       --  Not controlled case
3855
3856       else
3857          declare
3858             Asn : constant Node_Id := Relocate_Node (N);
3859
3860          begin
3861             --  If this is the case of a tagged type with a full rep clause,
3862             --  we must expand it into component assignments, so we mark the
3863             --  node as unanalyzed, to get it reanalyzed, but flag it has
3864             --  requiring component-wise assignment so we don't get infinite
3865             --  recursion.
3866
3867             if Component_Assign then
3868                Set_Analyzed (Asn, False);
3869                Set_Componentwise_Assignment (Asn, True);
3870             end if;
3871
3872             Append_To (Res, Asn);
3873          end;
3874       end if;
3875
3876       --  Restore the tag
3877
3878       if Save_Tag then
3879          Append_To (Res,
3880            Make_Assignment_Statement (Loc,
3881              Name =>
3882                Make_Selected_Component (Loc,
3883                  Prefix        => Duplicate_Subexpr_No_Checks (L),
3884                  Selector_Name => New_Reference_To (First_Tag_Component (T),
3885                                                     Loc)),
3886              Expression => New_Reference_To (Tag_Tmp, Loc)));
3887       end if;
3888
3889       if Ctrl_Act then
3890          if VM_Target /= No_VM then
3891             --  Restore the finalization pointers
3892
3893             Append_To (Res,
3894               Make_Assignment_Statement (Loc,
3895                 Name =>
3896                   Make_Selected_Component (Loc,
3897                     Prefix        =>
3898                       Unchecked_Convert_To (RTE (RE_Finalizable),
3899                         New_Copy_Tree (Ctrl_Ref)),
3900                     Selector_Name => Make_Identifier (Loc, Name_Prev)),
3901                 Expression => New_Reference_To (Prev_Tmp, Loc)));
3902
3903             Append_To (Res,
3904               Make_Assignment_Statement (Loc,
3905                 Name =>
3906                   Make_Selected_Component (Loc,
3907                     Prefix        =>
3908                       Unchecked_Convert_To (RTE (RE_Finalizable),
3909                         New_Copy_Tree (Ctrl_Ref)),
3910                     Selector_Name => Make_Identifier (Loc, Name_Next)),
3911                 Expression => New_Reference_To (Next_Tmp, Loc)));
3912          end if;
3913
3914          --  Adjust the target after the assignment when controlled (not in the
3915          --  init proc since it is an initialization more than an assignment).
3916
3917          Append_List_To (Res,
3918            Make_Adjust_Call (
3919              Ref         => Duplicate_Subexpr_Move_Checks (L),
3920              Typ         => Etype (L),
3921              Flist_Ref   => New_Reference_To (RTE (RE_Global_Final_List), Loc),
3922              With_Attach => Make_Integer_Literal (Loc, 0)));
3923       end if;
3924
3925       return Res;
3926
3927    exception
3928       --  Could use comment here ???
3929
3930       when RE_Not_Available =>
3931          return Empty_List;
3932    end Make_Tag_Ctrl_Assignment;
3933
3934 end Exp_Ch5;