OSDN Git Service

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