OSDN Git Service

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