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