OSDN Git Service

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