OSDN Git Service

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