OSDN Git Service

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