1 -----------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2002, Free Software Foundation, Inc. --
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. --
22 -- GNAT was originally developed by the GNAT team at New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc. --
25 ------------------------------------------------------------------------------
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_Util; use Exp_Util;
36 with Hostparm; use Hostparm;
37 with Nlists; use Nlists;
38 with Nmake; use Nmake;
40 with Restrict; use Restrict;
41 with Rtsfind; use Rtsfind;
42 with Sinfo; use Sinfo;
44 with Sem_Ch8; use Sem_Ch8;
45 with Sem_Ch13; use Sem_Ch13;
46 with Sem_Eval; use Sem_Eval;
47 with Sem_Res; use Sem_Res;
48 with Sem_Util; use Sem_Util;
49 with Snames; use Snames;
50 with Stand; use Stand;
51 with Tbuild; use Tbuild;
52 with Ttypes; use Ttypes;
53 with Uintp; use Uintp;
54 with Validsw; use Validsw;
56 package body Exp_Ch5 is
58 function Change_Of_Representation (N : Node_Id) return Boolean;
59 -- Determine if the right hand side of the assignment N is a type
60 -- conversion which requires a change of representation. Called
61 -- only for the array and record cases.
63 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
64 -- N is an assignment which assigns an array value. This routine process
65 -- the various special cases and checks required for such assignments,
66 -- including change of representation. Rhs is normally simply the right
67 -- hand side of the assignment, except that if the right hand side is
68 -- a type conversion or a qualified expression, then the Rhs is the
69 -- actual expression inside any such type conversions or qualifications.
71 function Expand_Assign_Array_Loop
80 -- N is an assignment statement which assigns an array value. This routine
81 -- expands the assignment into a loop (or nested loops for the case of a
82 -- multi-dimensional array) to do the assignment component by component.
83 -- Larray and Rarray are the entities of the actual arrays on the left
84 -- hand and right hand sides. L_Type and R_Type are the types of these
85 -- arrays (which may not be the same, due to either sliding, or to a
86 -- change of representation case). Ndim is the number of dimensions and
87 -- the parameter Rev indicates if the loops run normally (Rev = False),
88 -- or reversed (Rev = True). The value returned is the constructed
89 -- loop statement. Auxiliary declarations are inserted before node N
90 -- using the standard Insert_Actions mechanism.
92 procedure Expand_Assign_Record (N : Node_Id);
93 -- N is an assignment of a non-tagged record value. This routine handles
94 -- the special cases and checks required for such assignments, including
95 -- change of representation.
97 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
98 -- Generate the necessary code for controlled and Tagged assignment,
99 -- that is to say, finalization of the target before, adjustement of
100 -- the target after and save and restore of the tag and finalization
101 -- pointers which are not 'part of the value' and must not be changed
102 -- upon assignment. N is the original Assignment node.
104 ------------------------------
105 -- Change_Of_Representation --
106 ------------------------------
108 function Change_Of_Representation (N : Node_Id) return Boolean is
109 Rhs : constant Node_Id := Expression (N);
113 Nkind (Rhs) = N_Type_Conversion
115 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
116 end Change_Of_Representation;
118 -------------------------
119 -- Expand_Assign_Array --
120 -------------------------
122 -- There are two issues here. First, do we let Gigi do a block move, or
123 -- do we expand out into a loop? Second, we need to set the two flags
124 -- Forwards_OK and Backwards_OK which show whether the block move (or
125 -- corresponding loops) can be legitimately done in a forwards (low to
126 -- high) or backwards (high to low) manner.
128 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
129 Loc : constant Source_Ptr := Sloc (N);
131 Lhs : constant Node_Id := Name (N);
133 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
134 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
136 L_Type : constant Entity_Id :=
137 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
138 R_Type : Entity_Id :=
139 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
141 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
142 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
144 Crep : constant Boolean := Change_Of_Representation (N);
149 Ndim : constant Pos := Number_Dimensions (L_Type);
151 Loop_Required : Boolean := False;
152 -- This switch is set to True if the array move must be done using
153 -- an explicit front end generated loop.
155 function Has_Address_Clause (Exp : Node_Id) return Boolean;
156 -- Test if Exp is a reference to an array whose declaration has
157 -- an address clause, or it is a slice of such an array.
159 function Is_Formal_Array (Exp : Node_Id) return Boolean;
160 -- Test if Exp is a reference to an array which is either a formal
161 -- parameter or a slice of a formal parameter. These are the cases
162 -- where hidden aliasing can occur.
164 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
165 -- Determine if Exp is a reference to an array variable which is other
166 -- than an object defined in the current scope, or a slice of such
167 -- an object. Such objects can be aliased to parameters (unlike local
168 -- array references).
170 function Possible_Unaligned_Slice (Arg : Node_Id) return Boolean;
171 -- Returns True if Arg (either the left or right hand side of the
172 -- assignment) is a slice that could be unaligned wrt the array type.
173 -- This is true if Arg is a component of a packed record, or is
174 -- a record component to which a component clause applies. This
175 -- is a little pessimistic, but the result of an unnecessary
176 -- decision that something is possibly unaligned is only to
177 -- generate a front end loop, which is not so terrible.
178 -- It would really be better if backend handled this ???
180 ------------------------
181 -- Has_Address_Clause --
182 ------------------------
184 function Has_Address_Clause (Exp : Node_Id) return Boolean is
187 (Is_Entity_Name (Exp) and then
188 Present (Address_Clause (Entity (Exp))))
190 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
191 end Has_Address_Clause;
193 ---------------------
194 -- Is_Formal_Array --
195 ---------------------
197 function Is_Formal_Array (Exp : Node_Id) return Boolean is
200 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
202 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
205 ------------------------
206 -- Is_Non_Local_Array --
207 ------------------------
209 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
211 return (Is_Entity_Name (Exp)
212 and then Scope (Entity (Exp)) /= Current_Scope)
213 or else (Nkind (Exp) = N_Slice
214 and then Is_Non_Local_Array (Prefix (Exp)));
215 end Is_Non_Local_Array;
217 ------------------------------
218 -- Possible_Unaligned_Slice --
219 ------------------------------
221 function Possible_Unaligned_Slice (Arg : Node_Id) return Boolean is
223 -- No issue if this is not a slice, or else strict alignment
224 -- is not required in any case.
226 if Nkind (Arg) /= N_Slice
227 or else not Target_Strict_Alignment
232 -- No issue if the component type is a byte or byte aligned
235 Array_Typ : constant Entity_Id := Etype (Arg);
236 Comp_Typ : constant Entity_Id := Component_Type (Array_Typ);
237 Pref : constant Node_Id := Prefix (Arg);
240 if Known_Alignment (Array_Typ) then
241 if Alignment (Array_Typ) = 1 then
245 elsif Known_Component_Size (Array_Typ) then
246 if Component_Size (Array_Typ) = 1 then
250 elsif Known_Esize (Comp_Typ) then
251 if Esize (Comp_Typ) <= System_Storage_Unit then
256 -- No issue if this is not a selected component
258 if Nkind (Pref) /= N_Selected_Component then
262 -- Else we test for a possibly unaligned component
265 Is_Packed (Etype (Pref))
267 Present (Component_Clause (Entity (Selector_Name (Pref))));
269 end Possible_Unaligned_Slice;
271 -- Determine if Lhs, Rhs are formal arrays or non-local arrays
273 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
274 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
276 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
277 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
279 -- Start of processing for Expand_Assign_Array
282 -- Deal with length check, note that the length check is done with
283 -- respect to the right hand side as given, not a possible underlying
284 -- renamed object, since this would generate incorrect extra checks.
286 Apply_Length_Check (Rhs, L_Type);
288 -- We start by assuming that the move can be done in either
289 -- direction, i.e. that the two sides are completely disjoint.
291 Set_Forwards_OK (N, True);
292 Set_Backwards_OK (N, True);
294 -- Normally it is only the slice case that can lead to overlap,
295 -- and explicit checks for slices are made below. But there is
296 -- one case where the slice can be implicit and invisible to us
297 -- and that is the case where we have a one dimensional array,
298 -- and either both operands are parameters, or one is a parameter
299 -- and the other is a global variable. In this case the parameter
300 -- could be a slice that overlaps with the other parameter.
302 -- Check for the case of slices requiring an explicit loop. Normally
303 -- it is only the explicit slice cases that bother us, but in the
304 -- case of one dimensional arrays, parameters can be slices that
305 -- are passed by reference, so we can have aliasing for assignments
306 -- from one parameter to another, or assignments between parameters
307 -- and non-local variables.
309 -- Note: overlap is never possible if there is a change of
310 -- representation, so we can exclude this case
315 ((Lhs_Formal and Rhs_Formal)
317 (Lhs_Formal and Rhs_Non_Local_Var)
319 (Rhs_Formal and Lhs_Non_Local_Var))
321 -- In the case of compiling for the Java Virtual Machine,
322 -- slices are always passed by making a copy, so we don't
323 -- have to worry about overlap. We also want to prevent
324 -- generation of "<" comparisons for array addresses,
325 -- since that's a meaningless operation on the JVM.
329 Set_Forwards_OK (N, False);
330 Set_Backwards_OK (N, False);
332 -- Note: the bit-packed case is not worrisome here, since if
333 -- we have a slice passed as a parameter, it is always aligned
334 -- on a byte boundary, and if there are no explicit slices, the
335 -- assignment can be performed directly.
338 -- We certainly must use a loop for change of representation
339 -- and also we use the operand of the conversion on the right
340 -- hand side as the effective right hand side (the component
341 -- types must match in this situation).
344 Act_Rhs := Get_Referenced_Object (Rhs);
345 R_Type := Get_Actual_Subtype (Act_Rhs);
346 Loop_Required := True;
348 -- Arrays with controlled components are expanded into a loop
349 -- to force calls to adjust at the component level.
351 elsif Has_Controlled_Component (L_Type) then
352 Loop_Required := True;
354 -- Case where no slice is involved
356 elsif not L_Slice and not R_Slice then
358 -- The following code deals with the case of unconstrained bit
359 -- packed arrays. The problem is that the template for such
360 -- arrays contains the bounds of the actual source level array,
362 -- But the copy of an entire array requires the bounds of the
363 -- underlying array. It would be nice if the back end could take
364 -- care of this, but right now it does not know how, so if we
365 -- have such a type, then we expand out into a loop, which is
366 -- inefficient but works correctly. If we don't do this, we
367 -- get the wrong length computed for the array to be moved.
368 -- The two cases we need to worry about are:
370 -- Explicit deference of an unconstrained packed array type as
371 -- in the following example:
374 -- type BITS is array(INTEGER range <>) of BOOLEAN;
375 -- pragma PACK(BITS);
376 -- type A is access BITS;
379 -- P1 := new BITS (1 .. 65_535);
380 -- P2 := new BITS (1 .. 65_535);
384 -- A formal parameter reference with an unconstrained bit
385 -- array type is the other case we need to worry about (here
386 -- we assume the same BITS type declared above:
388 -- procedure Write_All (File : out BITS; Contents : in BITS);
390 -- File.Storage := Contents;
393 -- We expand to a loop in either of these two cases.
395 -- Question for future thought. Another potentially more efficient
396 -- approach would be to create the actual subtype, and then do an
397 -- unchecked conversion to this actual subtype ???
399 Check_Unconstrained_Bit_Packed_Array : declare
401 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
402 -- Function to perform required test for the first case,
403 -- above (dereference of an unconstrained bit packed array)
405 -----------------------
406 -- Is_UBPA_Reference --
407 -----------------------
409 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
410 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
412 Des_Type : Entity_Id;
415 if Present (Packed_Array_Type (Typ))
416 and then Is_Array_Type (Packed_Array_Type (Typ))
417 and then not Is_Constrained (Packed_Array_Type (Typ))
421 elsif Nkind (Opnd) = N_Explicit_Dereference then
422 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
424 if not Is_Access_Type (P_Type) then
428 Des_Type := Designated_Type (P_Type);
430 Is_Bit_Packed_Array (Des_Type)
431 and then not Is_Constrained (Des_Type);
437 end Is_UBPA_Reference;
439 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
442 if Is_UBPA_Reference (Lhs)
444 Is_UBPA_Reference (Rhs)
446 Loop_Required := True;
448 -- Here if we do not have the case of a reference to a bit
449 -- packed unconstrained array case. In this case gigi can
450 -- most certainly handle the assignment if a forwards move
453 -- (could it handle the backwards case also???)
455 elsif Forwards_OK (N) then
458 end Check_Unconstrained_Bit_Packed_Array;
460 -- Gigi can always handle the assignment if the right side is a string
461 -- literal (note that overlap is definitely impossible in this case).
463 elsif Nkind (Rhs) = N_String_Literal then
466 -- If either operand is bit packed, then we need a loop, since we
467 -- can't be sure that the slice is byte aligned. Similarly, if either
468 -- operand is a possibly unaligned slice, then we need a loop (since
469 -- gigi cannot handle unaligned slices).
471 elsif Is_Bit_Packed_Array (L_Type)
472 or else Is_Bit_Packed_Array (R_Type)
473 or else Possible_Unaligned_Slice (Lhs)
474 or else Possible_Unaligned_Slice (Rhs)
476 Loop_Required := True;
478 -- If we are not bit-packed, and we have only one slice, then no
479 -- overlap is possible except in the parameter case, so we can let
480 -- gigi handle things.
482 elsif not (L_Slice and R_Slice) then
483 if Forwards_OK (N) then
488 -- Come here to compelete the analysis
490 -- Loop_Required: Set to True if we know that a loop is required
491 -- regardless of overlap considerations.
493 -- Forwards_OK: Set to False if we already know that a forwards
494 -- move is not safe, else set to True.
496 -- Backwards_OK: Set to False if we already know that a backwards
497 -- move is not safe, else set to True
499 -- Our task at this stage is to complete the overlap analysis, which
500 -- can result in possibly setting Forwards_OK or Backwards_OK to
501 -- False, and then generating the final code, either by deciding
502 -- that it is OK after all to let Gigi handle it, or by generating
503 -- appropriate code in the front end.
506 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
507 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
509 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
510 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
511 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
512 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
514 Act_L_Array : Node_Id;
515 Act_R_Array : Node_Id;
521 Cresult : Compare_Result;
524 -- Get the expressions for the arrays. If we are dealing with a
525 -- private type, then convert to the underlying type. We can do
526 -- direct assignments to an array that is a private type, but
527 -- we cannot assign to elements of the array without this extra
528 -- unchecked conversion.
530 if Nkind (Act_Lhs) = N_Slice then
531 Larray := Prefix (Act_Lhs);
535 if Is_Private_Type (Etype (Larray)) then
538 (Underlying_Type (Etype (Larray)), Larray);
542 if Nkind (Act_Rhs) = N_Slice then
543 Rarray := Prefix (Act_Rhs);
547 if Is_Private_Type (Etype (Rarray)) then
550 (Underlying_Type (Etype (Rarray)), Rarray);
554 -- If both sides are slices, we must figure out whether
555 -- it is safe to do the move in one direction or the other
556 -- It is always safe if there is a change of representation
557 -- since obviously two arrays with different representations
558 -- cannot possibly overlap.
560 if (not Crep) and L_Slice and R_Slice then
561 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
562 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
564 -- If both left and right hand arrays are entity names, and
565 -- refer to different entities, then we know that the move
566 -- is safe (the two storage areas are completely disjoint).
568 if Is_Entity_Name (Act_L_Array)
569 and then Is_Entity_Name (Act_R_Array)
570 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
574 -- Otherwise, we assume the worst, which is that the two
575 -- arrays are the same array. There is no need to check if
576 -- we know that is the case, because if we don't know it,
577 -- we still have to assume it!
579 -- Generally if the same array is involved, then we have
580 -- an overlapping case. We will have to really assume the
581 -- worst (i.e. set neither of the OK flags) unless we can
582 -- determine the lower or upper bounds at compile time and
586 Cresult := Compile_Time_Compare (Left_Lo, Right_Lo);
588 if Cresult = Unknown then
589 Cresult := Compile_Time_Compare (Left_Hi, Right_Hi);
593 when LT | LE | EQ => Set_Backwards_OK (N, False);
594 when GT | GE => Set_Forwards_OK (N, False);
595 when NE | Unknown => Set_Backwards_OK (N, False);
596 Set_Forwards_OK (N, False);
601 -- If after that analysis, Forwards_OK is still True, and
602 -- Loop_Required is False, meaning that we have not discovered
603 -- some non-overlap reason for requiring a loop, then we can
604 -- still let gigi handle it.
606 if not Loop_Required then
607 if Forwards_OK (N) then
612 -- Here is where a memmove would be appropriate ???
616 -- At this stage we have to generate an explicit loop, and
617 -- we have the following cases:
619 -- Forwards_OK = True
621 -- Rnn : right_index := right_index'First;
622 -- for Lnn in left-index loop
623 -- left (Lnn) := right (Rnn);
624 -- Rnn := right_index'Succ (Rnn);
627 -- Note: the above code MUST be analyzed with checks off,
628 -- because otherwise the Succ could overflow. But in any
629 -- case this is more efficient!
631 -- Forwards_OK = False, Backwards_OK = True
633 -- Rnn : right_index := right_index'Last;
634 -- for Lnn in reverse left-index loop
635 -- left (Lnn) := right (Rnn);
636 -- Rnn := right_index'Pred (Rnn);
639 -- Note: the above code MUST be analyzed with checks off,
640 -- because otherwise the Pred could overflow. But in any
641 -- case this is more efficient!
643 -- Forwards_OK = Backwards_OK = False
645 -- This only happens if we have the same array on each side. It is
646 -- possible to create situations using overlays that violate this,
647 -- but we simply do not promise to get this "right" in this case.
649 -- There are two possible subcases. If the No_Implicit_Conditionals
650 -- restriction is set, then we generate the following code:
653 -- T : constant <operand-type> := rhs;
658 -- If implicit conditionals are permitted, then we generate:
660 -- if Left_Lo <= Right_Lo then
661 -- <code for Forwards_OK = True above>
663 -- <code for Backwards_OK = True above>
666 -- Cases where either Forwards_OK or Backwards_OK is true
668 if Forwards_OK (N) or else Backwards_OK (N) then
670 Expand_Assign_Array_Loop
671 (N, Larray, Rarray, L_Type, R_Type, Ndim,
672 Rev => not Forwards_OK (N)));
674 -- Case of both are false with No_Implicit_Conditionals
676 elsif Restrictions (No_Implicit_Conditionals) then
678 T : Entity_Id := Make_Defining_Identifier (Loc,
683 Make_Block_Statement (Loc,
684 Declarations => New_List (
685 Make_Object_Declaration (Loc,
686 Defining_Identifier => T,
687 Constant_Present => True,
689 New_Occurrence_Of (Etype (Rhs), Loc),
690 Expression => Relocate_Node (Rhs))),
692 Handled_Statement_Sequence =>
693 Make_Handled_Sequence_Of_Statements (Loc,
694 Statements => New_List (
695 Make_Assignment_Statement (Loc,
696 Name => Relocate_Node (Lhs),
697 Expression => New_Occurrence_Of (T, Loc))))));
700 -- Case of both are false with implicit conditionals allowed
703 -- Before we generate this code, we must ensure that the
704 -- left and right side array types are defined. They may
705 -- be itypes, and we cannot let them be defined inside the
706 -- if, since the first use in the then may not be executed.
708 Ensure_Defined (L_Type, N);
709 Ensure_Defined (R_Type, N);
711 -- We normally compare addresses to find out which way round
712 -- to do the loop, since this is realiable, and handles the
713 -- cases of parameters, conversions etc. But we can't do that
714 -- in the bit packed case or the Java VM case, because addresses
717 if not Is_Bit_Packed_Array (L_Type) and then not Java_VM then
721 Unchecked_Convert_To (RTE (RE_Integer_Address),
722 Make_Attribute_Reference (Loc,
724 Make_Indexed_Component (Loc,
726 Duplicate_Subexpr (Larray, True),
727 Expressions => New_List (
728 Make_Attribute_Reference (Loc,
732 Attribute_Name => Name_First))),
733 Attribute_Name => Name_Address)),
736 Unchecked_Convert_To (RTE (RE_Integer_Address),
737 Make_Attribute_Reference (Loc,
739 Make_Indexed_Component (Loc,
741 Duplicate_Subexpr (Rarray, True),
742 Expressions => New_List (
743 Make_Attribute_Reference (Loc,
747 Attribute_Name => Name_First))),
748 Attribute_Name => Name_Address)));
750 -- For the bit packed and Java VM cases we use the bounds.
751 -- That's OK, because we don't have to worry about parameters,
752 -- since they cannot cause overlap. Perhaps we should worry
753 -- about weird slice conversions ???
756 -- Copy the bounds and reset the Analyzed flag, because the
757 -- bounds of the index type itself may be universal, and must
758 -- must be reaanalyzed to acquire the proper type for Gigi.
760 Cleft_Lo := New_Copy_Tree (Left_Lo);
761 Cright_Lo := New_Copy_Tree (Right_Lo);
762 Set_Analyzed (Cleft_Lo, False);
763 Set_Analyzed (Cright_Lo, False);
767 Left_Opnd => Cleft_Lo,
768 Right_Opnd => Cright_Lo);
772 Make_Implicit_If_Statement (N,
773 Condition => Condition,
775 Then_Statements => New_List (
776 Expand_Assign_Array_Loop
777 (N, Larray, Rarray, L_Type, R_Type, Ndim,
780 Else_Statements => New_List (
781 Expand_Assign_Array_Loop
782 (N, Larray, Rarray, L_Type, R_Type, Ndim,
786 Analyze (N, Suppress => All_Checks);
788 end Expand_Assign_Array;
790 ------------------------------
791 -- Expand_Assign_Array_Loop --
792 ------------------------------
794 -- The following is an example of the loop generated for the case of
795 -- a two-dimensional array:
800 -- for L1b in 1 .. 100 loop
804 -- for L3b in 1 .. 100 loop
805 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
806 -- R4b := Tm1X2'succ(R4b);
809 -- R2b := Tm1X1'succ(R2b);
813 -- Here Rev is False, and Tm1Xn are the subscript types for the right
814 -- hand side. The declarations of R2b and R4b are inserted before the
815 -- original assignment statement.
817 function Expand_Assign_Array_Loop
827 Loc : constant Source_Ptr := Sloc (N);
829 Lnn : array (1 .. Ndim) of Entity_Id;
830 Rnn : array (1 .. Ndim) of Entity_Id;
831 -- Entities used as subscripts on left and right sides
833 L_Index_Type : array (1 .. Ndim) of Entity_Id;
834 R_Index_Type : array (1 .. Ndim) of Entity_Id;
835 -- Left and right index types
847 F_Or_L := Name_First;
851 -- Setup index types and subscript entities
858 L_Index := First_Index (L_Type);
859 R_Index := First_Index (R_Type);
861 for J in 1 .. Ndim loop
863 Make_Defining_Identifier (Loc,
864 Chars => New_Internal_Name ('L'));
867 Make_Defining_Identifier (Loc,
868 Chars => New_Internal_Name ('R'));
870 L_Index_Type (J) := Etype (L_Index);
871 R_Index_Type (J) := Etype (R_Index);
873 Next_Index (L_Index);
874 Next_Index (R_Index);
878 -- Now construct the assignment statement
881 ExprL : List_Id := New_List;
882 ExprR : List_Id := New_List;
885 for J in 1 .. Ndim loop
886 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
887 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
891 Make_Assignment_Statement (Loc,
893 Make_Indexed_Component (Loc,
894 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
895 Expressions => ExprL),
897 Make_Indexed_Component (Loc,
898 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
899 Expressions => ExprR));
901 -- Propagate the No_Ctrl_Actions flag to individual assignments
903 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
906 -- Now construct the loop from the inside out, with the last subscript
907 -- varying most rapidly. Note that Assign is first the raw assignment
908 -- statement, and then subsequently the loop that wraps it up.
910 for J in reverse 1 .. Ndim loop
912 Make_Block_Statement (Loc,
913 Declarations => New_List (
914 Make_Object_Declaration (Loc,
915 Defining_Identifier => Rnn (J),
917 New_Occurrence_Of (R_Index_Type (J), Loc),
919 Make_Attribute_Reference (Loc,
920 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
921 Attribute_Name => F_Or_L))),
923 Handled_Statement_Sequence =>
924 Make_Handled_Sequence_Of_Statements (Loc,
925 Statements => New_List (
926 Make_Implicit_Loop_Statement (N,
928 Make_Iteration_Scheme (Loc,
929 Loop_Parameter_Specification =>
930 Make_Loop_Parameter_Specification (Loc,
931 Defining_Identifier => Lnn (J),
932 Reverse_Present => Rev,
933 Discrete_Subtype_Definition =>
934 New_Reference_To (L_Index_Type (J), Loc))),
936 Statements => New_List (
939 Make_Assignment_Statement (Loc,
940 Name => New_Occurrence_Of (Rnn (J), Loc),
942 Make_Attribute_Reference (Loc,
944 New_Occurrence_Of (R_Index_Type (J), Loc),
945 Attribute_Name => S_Or_P,
946 Expressions => New_List (
947 New_Occurrence_Of (Rnn (J), Loc)))))))));
951 end Expand_Assign_Array_Loop;
953 --------------------------
954 -- Expand_Assign_Record --
955 --------------------------
957 -- The only processing required is in the change of representation
958 -- case, where we must expand the assignment to a series of field
959 -- by field assignments.
961 procedure Expand_Assign_Record (N : Node_Id) is
963 if not Change_Of_Representation (N) then
967 -- At this stage we know that the right hand side is a conversion
970 Loc : constant Source_Ptr := Sloc (N);
971 Lhs : constant Node_Id := Name (N);
972 Rhs : constant Node_Id := Expression (Expression (N));
973 R_Rec : constant Node_Id := Expression (Expression (N));
974 R_Typ : constant Entity_Id := Base_Type (Etype (R_Rec));
975 L_Typ : constant Entity_Id := Etype (Lhs);
976 Decl : constant Node_Id := Declaration_Node (R_Typ);
980 function Find_Component
984 -- Find the component with the given name in the underlying record
985 -- declaration for Typ. We need to use the actual entity because
986 -- the type may be private and resolution by identifier alone would
989 function Make_Component_List_Assign (CL : Node_Id) return List_Id;
990 -- Returns a sequence of statements to assign the components that
991 -- are referenced in the given component list.
993 function Make_Field_Assign (C : Entity_Id) return Node_Id;
994 -- Given C, the entity for a discriminant or component, build
995 -- an assignment for the corresponding field values.
997 function Make_Field_Assigns (CI : List_Id) return List_Id;
998 -- Given CI, a component items list, construct series of statements
999 -- for fieldwise assignment of the corresponding components.
1001 --------------------
1002 -- Find_Component --
1003 --------------------
1005 function Find_Component
1011 Utyp : constant Entity_Id := Underlying_Type (Typ);
1015 C := First_Entity (Utyp);
1017 while Present (C) loop
1018 if Chars (C) = Chars (Comp) then
1024 raise Program_Error;
1027 --------------------------------
1028 -- Make_Component_List_Assign --
1029 --------------------------------
1031 function Make_Component_List_Assign (CL : Node_Id) return List_Id is
1032 CI : constant List_Id := Component_Items (CL);
1033 VP : constant Node_Id := Variant_Part (CL);
1042 Result := Make_Field_Assigns (CI);
1044 if Present (VP) then
1046 V := First_Non_Pragma (Variants (VP));
1048 while Present (V) loop
1051 DC := First (Discrete_Choices (V));
1052 while Present (DC) loop
1053 Append_To (DCH, New_Copy_Tree (DC));
1058 Make_Case_Statement_Alternative (Loc,
1059 Discrete_Choices => DCH,
1061 Make_Component_List_Assign (Component_List (V))));
1062 Next_Non_Pragma (V);
1066 Make_Case_Statement (Loc,
1068 Make_Selected_Component (Loc,
1069 Prefix => Duplicate_Subexpr (Rhs),
1071 Make_Identifier (Loc, Chars (Name (VP)))),
1072 Alternatives => Alts));
1077 end Make_Component_List_Assign;
1079 -----------------------
1080 -- Make_Field_Assign --
1081 -----------------------
1083 function Make_Field_Assign (C : Entity_Id) return Node_Id is
1088 Make_Assignment_Statement (Loc,
1090 Make_Selected_Component (Loc,
1091 Prefix => Duplicate_Subexpr (Lhs),
1093 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1095 Make_Selected_Component (Loc,
1096 Prefix => Duplicate_Subexpr (Rhs),
1097 Selector_Name => New_Occurrence_Of (C, Loc)));
1099 -- Set Assignment_OK, so discriminants can be assigned
1101 Set_Assignment_OK (Name (A), True);
1103 end Make_Field_Assign;
1105 ------------------------
1106 -- Make_Field_Assigns --
1107 ------------------------
1109 function Make_Field_Assigns (CI : List_Id) return List_Id is
1117 while Present (Item) loop
1118 if Nkind (Item) = N_Component_Declaration then
1120 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1127 end Make_Field_Assigns;
1129 -- Start of processing for Expand_Assign_Record
1132 -- Note that we use the base type for this processing. This results
1133 -- in some extra work in the constrained case, but the change of
1134 -- representation case is so unusual that it is not worth the effort.
1136 -- First copy the discriminants. This is done unconditionally. It
1137 -- is required in the unconstrained left side case, and also in the
1138 -- case where this assignment was constructed during the expansion
1139 -- of a type conversion (since initialization of discriminants is
1140 -- suppressed in this case). It is unnecessary but harmless in
1143 if Has_Discriminants (L_Typ) then
1144 F := First_Discriminant (R_Typ);
1145 while Present (F) loop
1146 Insert_Action (N, Make_Field_Assign (F));
1147 Next_Discriminant (F);
1151 -- We know the underlying type is a record, but its current view
1152 -- may be private. We must retrieve the usable record declaration.
1154 if Nkind (Decl) = N_Private_Type_Declaration
1155 and then Present (Full_View (R_Typ))
1157 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1159 RDef := Type_Definition (Decl);
1162 if Nkind (RDef) = N_Record_Definition
1163 and then Present (Component_List (RDef))
1166 (N, Make_Component_List_Assign (Component_List (RDef)));
1168 Rewrite (N, Make_Null_Statement (Loc));
1172 end Expand_Assign_Record;
1174 -----------------------------------
1175 -- Expand_N_Assignment_Statement --
1176 -----------------------------------
1178 -- For array types, deal with slice assignments and setting the flags
1179 -- to indicate if it can be statically determined which direction the
1180 -- move should go in. Also deal with generating length checks.
1182 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1183 Loc : constant Source_Ptr := Sloc (N);
1184 Lhs : constant Node_Id := Name (N);
1185 Rhs : constant Node_Id := Expression (N);
1186 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1190 -- Check for a special case where a high level transformation is
1191 -- required. If we have either of:
1196 -- where P is a reference to a bit packed array, then we have to unwind
1197 -- the assignment. The exact meaning of being a reference to a bit
1198 -- packed array is as follows:
1200 -- An indexed component whose prefix is a bit packed array is a
1201 -- reference to a bit packed array.
1203 -- An indexed component or selected component whose prefix is a
1204 -- reference to a bit packed array is itself a reference ot a
1205 -- bit packed array.
1207 -- The required transformation is
1209 -- Tnn : prefix_type := P;
1210 -- Tnn.field := rhs;
1215 -- Tnn : prefix_type := P;
1216 -- Tnn (subscr) := rhs;
1219 -- Since P is going to be evaluated more than once, any subscripts
1220 -- in P must have their evaluation forced.
1222 if (Nkind (Lhs) = N_Indexed_Component
1224 Nkind (Lhs) = N_Selected_Component)
1225 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1228 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1229 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1230 Tnn : constant Entity_Id :=
1231 Make_Defining_Identifier (Loc,
1232 Chars => New_Internal_Name ('T'));
1235 -- Insert the post assignment first, because we want to copy
1236 -- the BPAR_Expr tree before it gets analyzed in the context
1237 -- of the pre assignment. Note that we do not analyze the
1238 -- post assignment yet (we cannot till we have completed the
1239 -- analysis of the pre assignment). As usual, the analysis
1240 -- of this post assignment will happen on its own when we
1241 -- "run into" it after finishing the current assignment.
1244 Make_Assignment_Statement (Loc,
1245 Name => New_Copy_Tree (BPAR_Expr),
1246 Expression => New_Occurrence_Of (Tnn, Loc)));
1248 -- At this stage BPAR_Expr is a reference to a bit packed
1249 -- array where the reference was not expanded in the original
1250 -- tree, since it was on the left side of an assignment. But
1251 -- in the pre-assignment statement (the object definition),
1252 -- BPAR_Expr will end up on the right hand side, and must be
1253 -- reexpanded. To achieve this, we reset the analyzed flag
1254 -- of all selected and indexed components down to the actual
1255 -- indexed component for the packed array.
1259 Set_Analyzed (Exp, False);
1261 if Nkind (Exp) = N_Selected_Component
1263 Nkind (Exp) = N_Indexed_Component
1265 Exp := Prefix (Exp);
1271 -- Now we can insert and analyze the pre-assignment.
1273 -- If the right-hand side requires a transient scope, it has
1274 -- already been placed on the stack. However, the declaration is
1275 -- inserted in the tree outside of this scope, and must reflect
1276 -- the proper scope for its variable. This awkward bit is forced
1277 -- by the stricter scope discipline imposed by GCC 2.97.
1280 Uses_Transient_Scope : constant Boolean :=
1281 Scope_Is_Transient and then N = Node_To_Be_Wrapped;
1284 if Uses_Transient_Scope then
1285 New_Scope (Scope (Current_Scope));
1288 Insert_Before_And_Analyze (N,
1289 Make_Object_Declaration (Loc,
1290 Defining_Identifier => Tnn,
1291 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
1292 Expression => BPAR_Expr));
1294 if Uses_Transient_Scope then
1299 -- Now fix up the original assignment and continue processing
1301 Rewrite (Prefix (Lhs),
1302 New_Occurrence_Of (Tnn, Loc));
1306 -- When we have the appropriate type of aggregate in the
1307 -- expression (it has been determined during analysis of the
1308 -- aggregate by setting the delay flag), let's perform in place
1309 -- assignment and thus avoid creating a temporay.
1311 if Is_Delayed_Aggregate (Rhs) then
1312 Convert_Aggr_In_Assignment (N);
1313 Rewrite (N, Make_Null_Statement (Loc));
1318 -- Apply discriminant check if required. If Lhs is an access type
1319 -- to a designated type with discriminants, we must always check.
1321 if Has_Discriminants (Etype (Lhs)) then
1323 -- Skip discriminant check if change of representation. Will be
1324 -- done when the change of representation is expanded out.
1326 if not Change_Of_Representation (N) then
1327 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1330 -- If the type is private without discriminants, and the full type
1331 -- has discriminants (necessarily with defaults) a check may still be
1332 -- necessary if the Lhs is aliased. The private determinants must be
1333 -- visible to build the discriminant constraints.
1335 elsif Is_Private_Type (Etype (Lhs))
1336 and then Has_Discriminants (Typ)
1337 and then Nkind (Lhs) = N_Explicit_Dereference
1340 Lt : constant Entity_Id := Etype (Lhs);
1342 Set_Etype (Lhs, Typ);
1343 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1344 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1345 Set_Etype (Lhs, Lt);
1348 -- If the Lhs has a private type with unknown discriminants, it
1349 -- may have a full view with discriminants, but those are nameable
1350 -- only in the underlying type, so convert the Rhs to it before
1351 -- potential checking.
1353 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1354 and then Has_Discriminants (Typ)
1356 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1357 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1359 -- In the access type case, we need the same discriminant check,
1360 -- and also range checks if we have an access to constrained array.
1362 elsif Is_Access_Type (Etype (Lhs))
1363 and then Is_Constrained (Designated_Type (Etype (Lhs)))
1365 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1367 -- Skip discriminant check if change of representation. Will be
1368 -- done when the change of representation is expanded out.
1370 if not Change_Of_Representation (N) then
1371 Apply_Discriminant_Check (Rhs, Etype (Lhs));
1374 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1375 Apply_Range_Check (Rhs, Etype (Lhs));
1377 if Is_Constrained (Etype (Lhs)) then
1378 Apply_Length_Check (Rhs, Etype (Lhs));
1381 if Nkind (Rhs) = N_Allocator then
1383 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1384 C_Es : Check_Result;
1391 Etype (Designated_Type (Etype (Lhs))));
1403 -- Apply range check for access type case
1405 elsif Is_Access_Type (Etype (Lhs))
1406 and then Nkind (Rhs) = N_Allocator
1407 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1409 Analyze_And_Resolve (Expression (Rhs));
1411 (Expression (Rhs), Designated_Type (Etype (Lhs)));
1414 -- Case of assignment to a bit packed array element
1416 if Nkind (Lhs) = N_Indexed_Component
1417 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1419 Expand_Bit_Packed_Element_Set (N);
1422 -- Case of tagged type assignment
1424 elsif Is_Tagged_Type (Typ)
1425 or else (Controlled_Type (Typ) and then not Is_Array_Type (Typ))
1427 Tagged_Case : declare
1428 L : List_Id := No_List;
1429 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
1432 -- In the controlled case, we need to make sure that function
1433 -- calls are evaluated before finalizing the target. In all
1434 -- cases, it makes the expansion easier if the side-effects
1435 -- are removed first.
1437 Remove_Side_Effects (Lhs);
1438 Remove_Side_Effects (Rhs);
1440 -- Avoid recursion in the mechanism
1444 -- If dispatching assignment, we need to dispatch to _assign
1446 if Is_Class_Wide_Type (Typ)
1448 -- If the type is tagged, we may as well use the predefined
1449 -- primitive assignment. This avoids inlining a lot of code
1450 -- and in the class-wide case, the assignment is replaced by
1451 -- a dispatch call to _assign. Note that this cannot be done
1452 -- when discriminant checks are locally suppressed (as in
1453 -- extension aggregate expansions) because otherwise the
1454 -- discriminant check will be performed within the _assign
1457 or else (Is_Tagged_Type (Typ)
1458 and then Chars (Current_Scope) /= Name_uAssign
1459 and then Expand_Ctrl_Actions
1460 and then not Discriminant_Checks_Suppressed (Empty))
1462 -- Fetch the primitive op _assign and proper type to call
1463 -- it. Because of possible conflits between private and
1464 -- full view the proper type is fetched directly from the
1465 -- operation profile.
1468 Op : constant Entity_Id
1469 := Find_Prim_Op (Typ, Name_uAssign);
1470 F_Typ : Entity_Id := Etype (First_Formal (Op));
1473 -- If the assignment is dispatching, make sure to use the
1474 -- ??? where is rest of this comment ???
1476 if Is_Class_Wide_Type (Typ) then
1477 F_Typ := Class_Wide_Type (F_Typ);
1481 Make_Procedure_Call_Statement (Loc,
1482 Name => New_Reference_To (Op, Loc),
1483 Parameter_Associations => New_List (
1484 Unchecked_Convert_To (F_Typ, Duplicate_Subexpr (Lhs)),
1485 Unchecked_Convert_To (F_Typ,
1486 Duplicate_Subexpr (Rhs)))));
1490 L := Make_Tag_Ctrl_Assignment (N);
1492 -- We can't afford to have destructive Finalization Actions
1493 -- in the Self assignment case, so if the target and the
1494 -- source are not obviously different, code is generated to
1495 -- avoid the self assignment case
1497 -- if lhs'address /= rhs'address then
1498 -- <code for controlled and/or tagged assignment>
1501 if not Statically_Different (Lhs, Rhs)
1502 and then Expand_Ctrl_Actions
1505 Make_Implicit_If_Statement (N,
1509 Make_Attribute_Reference (Loc,
1510 Prefix => Duplicate_Subexpr (Lhs),
1511 Attribute_Name => Name_Address),
1514 Make_Attribute_Reference (Loc,
1515 Prefix => Duplicate_Subexpr (Rhs),
1516 Attribute_Name => Name_Address)),
1518 Then_Statements => L));
1521 -- We need to set up an exception handler for implementing
1522 -- 7.6.1 (18). The remaining adjustments are tackled by the
1523 -- implementation of adjust for record_controllers (see
1526 -- This is skipped in No_Run_Time mode, where we in any
1527 -- case exclude the possibility of finalization going on!
1529 if Expand_Ctrl_Actions and then not No_Run_Time then
1531 Make_Block_Statement (Loc,
1532 Handled_Statement_Sequence =>
1533 Make_Handled_Sequence_Of_Statements (Loc,
1535 Exception_Handlers => New_List (
1536 Make_Exception_Handler (Loc,
1537 Exception_Choices =>
1538 New_List (Make_Others_Choice (Loc)),
1539 Statements => New_List (
1540 Make_Raise_Program_Error (Loc,
1542 PE_Finalize_Raised_Exception)
1548 Make_Block_Statement (Loc,
1549 Handled_Statement_Sequence =>
1550 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
1552 -- If no restrictions on aborts, protect the whole assignement
1553 -- for controlled objects as per 9.8(11)
1555 if Controlled_Type (Typ)
1556 and then Expand_Ctrl_Actions
1557 and then Abort_Allowed
1560 Blk : constant Entity_Id :=
1561 New_Internal_Entity (
1562 E_Block, Current_Scope, Sloc (N), 'B');
1565 Set_Scope (Blk, Current_Scope);
1566 Set_Etype (Blk, Standard_Void_Type);
1567 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
1569 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
1570 Set_At_End_Proc (Handled_Statement_Sequence (N),
1571 New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
1572 Expand_At_End_Handler
1573 (Handled_Statement_Sequence (N), Blk);
1583 elsif Is_Array_Type (Typ) then
1585 Actual_Rhs : Node_Id := Rhs;
1588 while Nkind (Actual_Rhs) = N_Type_Conversion
1590 Nkind (Actual_Rhs) = N_Qualified_Expression
1592 Actual_Rhs := Expression (Actual_Rhs);
1595 Expand_Assign_Array (N, Actual_Rhs);
1601 elsif Is_Record_Type (Typ) then
1602 Expand_Assign_Record (N);
1605 -- Scalar types. This is where we perform the processing related
1606 -- to the requirements of (RM 13.9.1(9-11)) concerning the handling
1607 -- of invalid scalar values.
1609 elsif Is_Scalar_Type (Typ) then
1611 -- Case where right side is known valid
1613 if Expr_Known_Valid (Rhs) then
1615 -- Here the right side is valid, so it is fine. The case to
1616 -- deal with is when the left side is a local variable reference
1617 -- whose value is not currently known to be valid. If this is
1618 -- the case, and the assignment appears in an unconditional
1619 -- context, then we can mark the left side as now being valid.
1621 if Is_Local_Variable_Reference (Lhs)
1622 and then not Is_Known_Valid (Entity (Lhs))
1623 and then In_Unconditional_Context (N)
1625 Set_Is_Known_Valid (Entity (Lhs), True);
1628 -- Case where right side may be invalid in the sense of the RM
1629 -- reference above. The RM does not require that we check for
1630 -- the validity on an assignment, but it does require that the
1631 -- assignment of an invalid value not cause erroneous behavior.
1633 -- The general approach in GNAT is to use the Is_Known_Valid flag
1634 -- to avoid the need for validity checking on assignments. However
1635 -- in some cases, we have to do validity checking in order to make
1636 -- sure that the setting of this flag is correct.
1639 -- Validate right side if we are validating copies
1641 if Validity_Checks_On
1642 and then Validity_Check_Copies
1646 -- We can propagate this to the left side where appropriate
1648 if Is_Local_Variable_Reference (Lhs)
1649 and then not Is_Known_Valid (Entity (Lhs))
1650 and then In_Unconditional_Context (N)
1652 Set_Is_Known_Valid (Entity (Lhs), True);
1655 -- Otherwise check to see what should be done
1657 -- If left side is a local variable, then we just set its
1658 -- flag to indicate that its value may no longer be valid,
1659 -- since we are copying a potentially invalid value.
1661 elsif Is_Local_Variable_Reference (Lhs) then
1662 Set_Is_Known_Valid (Entity (Lhs), False);
1664 -- Check for case of a non-local variable on the left side
1665 -- which is currently known to be valid. In this case, we
1666 -- simply ensure that the right side is valid. We only play
1667 -- the game of copying validity status for local variables,
1668 -- since we are doing this statically, not by tracing the
1671 elsif Is_Entity_Name (Lhs)
1672 and then Is_Known_Valid (Entity (Lhs))
1674 -- Note that the Ensure_Valid call is ignored if the
1675 -- Validity_Checking mode is set to none so we do not
1676 -- need to worry about that case here.
1680 -- In all other cases, we can safely copy an invalid value
1681 -- without worrying about the status of the left side. Since
1682 -- it is not a variable reference it will not be considered
1683 -- as being known to be valid in any case.
1691 -- Defend against invalid subscripts on left side if we are in
1692 -- standard validity checking mode. No need to do this if we
1693 -- are checking all subscripts.
1695 if Validity_Checks_On
1696 and then Validity_Check_Default
1697 and then not Validity_Check_Subscripts
1699 Check_Valid_Lvalue_Subscripts (Lhs);
1701 end Expand_N_Assignment_Statement;
1703 ------------------------------
1704 -- Expand_N_Block_Statement --
1705 ------------------------------
1707 -- Encode entity names defined in block statement
1709 procedure Expand_N_Block_Statement (N : Node_Id) is
1711 Qualify_Entity_Names (N);
1712 end Expand_N_Block_Statement;
1714 -----------------------------
1715 -- Expand_N_Case_Statement --
1716 -----------------------------
1718 procedure Expand_N_Case_Statement (N : Node_Id) is
1719 Loc : constant Source_Ptr := Sloc (N);
1720 Expr : constant Node_Id := Expression (N);
1723 -- Check for the situation where we know at compile time which
1724 -- branch will be taken
1726 if Compile_Time_Known_Value (Expr) then
1728 Val : constant Uint := Expr_Value (Expr);
1733 Alt := First (Alternatives (N));
1735 Choice := First (Discrete_Choices (Alt));
1736 while Present (Choice) loop
1738 -- Others choice, always matches
1740 if Nkind (Choice) = N_Others_Choice then
1743 -- Range, check if value is in the range
1745 elsif Nkind (Choice) = N_Range then
1747 Val >= Expr_Value (Low_Bound (Choice))
1749 Val <= Expr_Value (High_Bound (Choice));
1751 -- Choice is a subtype name. Note that we know it must
1752 -- be a static subtype, since otherwise it would have
1753 -- been diagnosed as illegal.
1755 elsif Is_Entity_Name (Choice)
1756 and then Is_Type (Entity (Choice))
1758 exit when Is_In_Range (Expr, Etype (Choice));
1760 -- Choice is a subtype indication
1762 elsif Nkind (Choice) = N_Subtype_Indication then
1764 C : constant Node_Id := Constraint (Choice);
1765 R : constant Node_Id := Range_Expression (C);
1769 Val >= Expr_Value (Low_Bound (R))
1771 Val <= Expr_Value (High_Bound (R));
1774 -- Choice is a simple expression
1777 exit Search when Val = Expr_Value (Choice);
1784 pragma Assert (Present (Alt));
1787 -- The above loop *must* terminate by finding a match, since
1788 -- we know the case statement is valid, and the value of the
1789 -- expression is known at compile time. When we fall out of
1790 -- the loop, Alt points to the alternative that we know will
1791 -- be selected at run time.
1793 -- Move the statements from this alternative after the case
1794 -- statement. They are already analyzed, so will be skipped
1797 Insert_List_After (N, Statements (Alt));
1799 -- That leaves the case statement as a shell. The alternative
1800 -- that wlil be executed is reset to a null list. So now we can
1801 -- kill the entire case statement.
1803 Kill_Dead_Code (Expression (N));
1804 Kill_Dead_Code (Alternatives (N));
1805 Rewrite (N, Make_Null_Statement (Loc));
1808 -- Here if the choice is not determined at compile time
1810 -- If the last alternative is not an Others choice, replace it with an
1811 -- N_Others_Choice. Note that we do not bother to call Analyze on the
1812 -- modified case statement, since it's only effect would be to compute
1813 -- the contents of the Others_Discrete_Choices node laboriously, and of
1814 -- course we already know the list of choices that corresponds to the
1815 -- others choice (it's the list we are replacing!)
1819 Altnode : constant Node_Id := Last (Alternatives (N));
1820 Others_Node : Node_Id;
1823 if Nkind (First (Discrete_Choices (Altnode)))
1826 Others_Node := Make_Others_Choice (Sloc (Altnode));
1827 Set_Others_Discrete_Choices
1828 (Others_Node, Discrete_Choices (Altnode));
1829 Set_Discrete_Choices (Altnode, New_List (Others_Node));
1832 -- If checks are on, ensure argument is valid (RM 5.4(13)). This
1833 -- is only done for case statements frpm in the source program.
1834 -- We don't just call Ensure_Valid here, because the requirement
1835 -- is more strenous than usual, in that it is required that
1836 -- Constraint_Error be raised.
1838 if Comes_From_Source (N)
1839 and then Validity_Checks_On
1840 and then Validity_Check_Default
1841 and then not Expr_Known_Valid (Expr)
1843 Insert_Valid_Check (Expr);
1847 end Expand_N_Case_Statement;
1849 -----------------------------
1850 -- Expand_N_Exit_Statement --
1851 -----------------------------
1853 -- The only processing required is to deal with a possible C/Fortran
1854 -- boolean value used as the condition for the exit statement.
1856 procedure Expand_N_Exit_Statement (N : Node_Id) is
1858 Adjust_Condition (Condition (N));
1859 end Expand_N_Exit_Statement;
1861 -----------------------------
1862 -- Expand_N_Goto_Statement --
1863 -----------------------------
1865 -- Add poll before goto if polling active
1867 procedure Expand_N_Goto_Statement (N : Node_Id) is
1869 Generate_Poll_Call (N);
1870 end Expand_N_Goto_Statement;
1872 ---------------------------
1873 -- Expand_N_If_Statement --
1874 ---------------------------
1876 -- First we deal with the case of C and Fortran convention boolean
1877 -- values, with zero/non-zero semantics.
1879 -- Second, we deal with the obvious rewriting for the cases where the
1880 -- condition of the IF is known at compile time to be True or False.
1882 -- Third, we remove elsif parts which have non-empty Condition_Actions
1883 -- and rewrite as independent if statements. For example:
1894 -- <<condition actions of y>>
1900 -- This rewriting is needed if at least one elsif part has a non-empty
1901 -- Condition_Actions list. We also do the same processing if there is
1902 -- a constant condition in an elsif part (in conjunction with the first
1903 -- processing step mentioned above, for the recursive call made to deal
1904 -- with the created inner if, this deals with properly optimizing the
1905 -- cases of constant elsif conditions).
1907 procedure Expand_N_If_Statement (N : Node_Id) is
1913 Adjust_Condition (Condition (N));
1915 -- The following loop deals with constant conditions for the IF. We
1916 -- need a loop because as we eliminate False conditions, we grab the
1917 -- first elsif condition and use it as the primary condition.
1919 while Compile_Time_Known_Value (Condition (N)) loop
1921 -- If condition is True, we can simply rewrite the if statement
1922 -- now by replacing it by the series of then statements.
1924 if Is_True (Expr_Value (Condition (N))) then
1926 -- All the else parts can be killed
1928 Kill_Dead_Code (Elsif_Parts (N));
1929 Kill_Dead_Code (Else_Statements (N));
1931 Hed := Remove_Head (Then_Statements (N));
1932 Insert_List_After (N, Then_Statements (N));
1936 -- If condition is False, then we can delete the condition and
1937 -- the Then statements
1940 -- We do not delete the condition if constant condition
1941 -- warnings are enabled, since otherwise we end up deleting
1942 -- the desired warning. Of course the backend will get rid
1943 -- of this True/False test anyway, so nothing is lost here.
1945 if not Constant_Condition_Warnings then
1946 Kill_Dead_Code (Condition (N));
1949 Kill_Dead_Code (Then_Statements (N));
1951 -- If there are no elsif statements, then we simply replace
1952 -- the entire if statement by the sequence of else statements.
1954 if No (Elsif_Parts (N)) then
1956 if No (Else_Statements (N))
1957 or else Is_Empty_List (Else_Statements (N))
1960 Make_Null_Statement (Sloc (N)));
1963 Hed := Remove_Head (Else_Statements (N));
1964 Insert_List_After (N, Else_Statements (N));
1970 -- If there are elsif statements, the first of them becomes
1971 -- the if/then section of the rebuilt if statement This is
1972 -- the case where we loop to reprocess this copied condition.
1975 Hed := Remove_Head (Elsif_Parts (N));
1976 Insert_Actions (N, Condition_Actions (Hed));
1977 Set_Condition (N, Condition (Hed));
1978 Set_Then_Statements (N, Then_Statements (Hed));
1980 if Is_Empty_List (Elsif_Parts (N)) then
1981 Set_Elsif_Parts (N, No_List);
1987 -- Loop through elsif parts, dealing with constant conditions and
1988 -- possible expression actions that are present.
1990 if Present (Elsif_Parts (N)) then
1991 E := First (Elsif_Parts (N));
1992 while Present (E) loop
1993 Adjust_Condition (Condition (E));
1995 -- If there are condition actions, then we rewrite the if
1996 -- statement as indicated above. We also do the same rewrite
1997 -- if the condition is True or False. The further processing
1998 -- of this constant condition is then done by the recursive
1999 -- call to expand the newly created if statement
2001 if Present (Condition_Actions (E))
2002 or else Compile_Time_Known_Value (Condition (E))
2004 -- Note this is not an implicit if statement, since it is
2005 -- part of an explicit if statement in the source (or of an
2006 -- implicit if statement that has already been tested).
2009 Make_If_Statement (Sloc (E),
2010 Condition => Condition (E),
2011 Then_Statements => Then_Statements (E),
2012 Elsif_Parts => No_List,
2013 Else_Statements => Else_Statements (N));
2015 -- Elsif parts for new if come from remaining elsif's of parent
2017 while Present (Next (E)) loop
2018 if No (Elsif_Parts (New_If)) then
2019 Set_Elsif_Parts (New_If, New_List);
2022 Append (Remove_Next (E), Elsif_Parts (New_If));
2025 Set_Else_Statements (N, New_List (New_If));
2027 if Present (Condition_Actions (E)) then
2028 Insert_List_Before (New_If, Condition_Actions (E));
2033 if Is_Empty_List (Elsif_Parts (N)) then
2034 Set_Elsif_Parts (N, No_List);
2040 -- No special processing for that elsif part, move to next
2047 end Expand_N_If_Statement;
2049 -----------------------------
2050 -- Expand_N_Loop_Statement --
2051 -----------------------------
2053 -- 1. Deal with while condition for C/Fortran boolean
2054 -- 2. Deal with loops with a non-standard enumeration type range
2055 -- 3. Deal with while loops where Condition_Actions is set
2056 -- 4. Insert polling call if required
2058 procedure Expand_N_Loop_Statement (N : Node_Id) is
2059 Loc : constant Source_Ptr := Sloc (N);
2060 Isc : constant Node_Id := Iteration_Scheme (N);
2063 if Present (Isc) then
2064 Adjust_Condition (Condition (Isc));
2067 if Is_Non_Empty_List (Statements (N)) then
2068 Generate_Poll_Call (First (Statements (N)));
2075 -- Handle the case where we have a for loop with the range type being
2076 -- an enumeration type with non-standard representation. In this case
2079 -- for x in [reverse] a .. b loop
2085 -- for xP in [reverse] integer
2086 -- range etype'Pos (a) .. etype'Pos (b) loop
2088 -- x : constant etype := Pos_To_Rep (xP);
2094 if Present (Loop_Parameter_Specification (Isc)) then
2096 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
2097 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
2098 Ltype : constant Entity_Id := Etype (Loop_Id);
2099 Btype : constant Entity_Id := Base_Type (Ltype);
2104 if not Is_Enumeration_Type (Btype)
2105 or else No (Enum_Pos_To_Rep (Btype))
2111 Make_Defining_Identifier (Loc,
2112 Chars => New_External_Name (Chars (Loop_Id), 'P'));
2114 Lo := Type_Low_Bound (Ltype);
2115 Hi := Type_High_Bound (Ltype);
2118 Make_Loop_Statement (Loc,
2119 Identifier => Identifier (N),
2122 Make_Iteration_Scheme (Loc,
2123 Loop_Parameter_Specification =>
2124 Make_Loop_Parameter_Specification (Loc,
2125 Defining_Identifier => New_Id,
2126 Reverse_Present => Reverse_Present (LPS),
2128 Discrete_Subtype_Definition =>
2129 Make_Subtype_Indication (Loc,
2132 New_Reference_To (Standard_Natural, Loc),
2135 Make_Range_Constraint (Loc,
2140 Make_Attribute_Reference (Loc,
2142 New_Reference_To (Btype, Loc),
2144 Attribute_Name => Name_Pos,
2146 Expressions => New_List (
2148 (Type_Low_Bound (Ltype)))),
2151 Make_Attribute_Reference (Loc,
2153 New_Reference_To (Btype, Loc),
2155 Attribute_Name => Name_Pos,
2157 Expressions => New_List (
2159 (Type_High_Bound (Ltype))))))))),
2161 Statements => New_List (
2162 Make_Block_Statement (Loc,
2163 Declarations => New_List (
2164 Make_Object_Declaration (Loc,
2165 Defining_Identifier => Loop_Id,
2166 Constant_Present => True,
2167 Object_Definition => New_Reference_To (Ltype, Loc),
2169 Make_Indexed_Component (Loc,
2171 New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
2172 Expressions => New_List (
2173 New_Reference_To (New_Id, Loc))))),
2175 Handled_Statement_Sequence =>
2176 Make_Handled_Sequence_Of_Statements (Loc,
2177 Statements => Statements (N)))),
2179 End_Label => End_Label (N)));
2184 -- Second case, if we have a while loop with Condition_Actions set,
2185 -- then we change it into a plain loop:
2194 -- <<condition actions>>
2200 and then Present (Condition_Actions (Isc))
2207 Make_Exit_Statement (Sloc (Condition (Isc)),
2209 Make_Op_Not (Sloc (Condition (Isc)),
2210 Right_Opnd => Condition (Isc)));
2212 Prepend (ES, Statements (N));
2213 Insert_List_Before (ES, Condition_Actions (Isc));
2215 -- This is not an implicit loop, since it is generated in
2216 -- response to the loop statement being processed. If this
2217 -- is itself implicit, the restriction has already been
2218 -- checked. If not, it is an explicit loop.
2221 Make_Loop_Statement (Sloc (N),
2222 Identifier => Identifier (N),
2223 Statements => Statements (N),
2224 End_Label => End_Label (N)));
2229 end Expand_N_Loop_Statement;
2231 -------------------------------
2232 -- Expand_N_Return_Statement --
2233 -------------------------------
2235 procedure Expand_N_Return_Statement (N : Node_Id) is
2236 Loc : constant Source_Ptr := Sloc (N);
2237 Exp : constant Node_Id := Expression (N);
2241 Scope_Id : Entity_Id;
2245 Goto_Stat : Node_Id;
2248 Return_Type : Entity_Id;
2249 Result_Exp : Node_Id;
2250 Result_Id : Entity_Id;
2251 Result_Obj : Node_Id;
2254 -- Case where returned expression is present
2256 if Present (Exp) then
2258 -- Always normalize C/Fortran boolean result. This is not always
2259 -- necessary, but it seems a good idea to minimize the passing
2260 -- around of non-normalized values, and in any case this handles
2261 -- the processing of barrier functions for protected types, which
2262 -- turn the condition into a return statement.
2264 Exptyp := Etype (Exp);
2266 if Is_Boolean_Type (Exptyp)
2267 and then Nonzero_Is_True (Exptyp)
2269 Adjust_Condition (Exp);
2270 Adjust_Result_Type (Exp, Exptyp);
2273 -- Do validity check if enabled for returns
2275 if Validity_Checks_On
2276 and then Validity_Check_Returns
2282 -- Find relevant enclosing scope from which return is returning
2284 Cur_Idx := Scope_Stack.Last;
2286 Scope_Id := Scope_Stack.Table (Cur_Idx).Entity;
2288 if Ekind (Scope_Id) /= E_Block
2289 and then Ekind (Scope_Id) /= E_Loop
2294 Cur_Idx := Cur_Idx - 1;
2295 pragma Assert (Cur_Idx >= 0);
2300 Kind := Ekind (Scope_Id);
2302 -- If it is a return from procedures do no extra steps.
2304 if Kind = E_Procedure or else Kind = E_Generic_Procedure then
2308 pragma Assert (Is_Entry (Scope_Id));
2310 -- Look at the enclosing block to see whether the return is from
2311 -- an accept statement or an entry body.
2313 for J in reverse 0 .. Cur_Idx loop
2314 Scope_Id := Scope_Stack.Table (J).Entity;
2315 exit when Is_Concurrent_Type (Scope_Id);
2318 -- If it is a return from accept statement it should be expanded
2319 -- as a call to RTS Complete_Rendezvous and a goto to the end of
2322 -- (cf : Expand_N_Accept_Statement, Expand_N_Selective_Accept,
2323 -- Expand_N_Accept_Alternative in exp_ch9.adb)
2325 if Is_Task_Type (Scope_Id) then
2327 Call := (Make_Procedure_Call_Statement (Loc,
2328 Name => New_Reference_To
2329 (RTE (RE_Complete_Rendezvous), Loc)));
2330 Insert_Before (N, Call);
2331 -- why not insert actions here???
2334 Acc_Stat := Parent (N);
2335 while Nkind (Acc_Stat) /= N_Accept_Statement loop
2336 Acc_Stat := Parent (Acc_Stat);
2339 Lab_Node := Last (Statements
2340 (Handled_Statement_Sequence (Acc_Stat)));
2342 Goto_Stat := Make_Goto_Statement (Loc,
2343 Name => New_Occurrence_Of
2344 (Entity (Identifier (Lab_Node)), Loc));
2346 Set_Analyzed (Goto_Stat);
2348 Rewrite (N, Goto_Stat);
2351 -- If it is a return from an entry body, put a Complete_Entry_Body
2352 -- call in front of the return.
2354 elsif Is_Protected_Type (Scope_Id) then
2357 Make_Procedure_Call_Statement (Loc,
2358 Name => New_Reference_To
2359 (RTE (RE_Complete_Entry_Body), Loc),
2360 Parameter_Associations => New_List
2361 (Make_Attribute_Reference (Loc,
2365 (Corresponding_Body (Parent (Scope_Id))),
2367 Attribute_Name => Name_Unchecked_Access)));
2369 Insert_Before (N, Call);
2378 Return_Type := Etype (Scope_Id);
2379 Utyp := Underlying_Type (Return_Type);
2381 -- Check the result expression of a scalar function against
2382 -- the subtype of the function by inserting a conversion.
2383 -- This conversion must eventually be performed for other
2384 -- classes of types, but for now it's only done for scalars.
2387 if Is_Scalar_Type (T) then
2388 Rewrite (Exp, Convert_To (Return_Type, Exp));
2392 -- Implement the rules of 6.5(8-10), which require a tag check in
2393 -- the case of a limited tagged return type, and tag reassignment
2394 -- for nonlimited tagged results. These actions are needed when
2395 -- the return type is a specific tagged type and the result
2396 -- expression is a conversion or a formal parameter, because in
2397 -- that case the tag of the expression might differ from the tag
2398 -- of the specific result type.
2400 if Is_Tagged_Type (Utyp)
2401 and then not Is_Class_Wide_Type (Utyp)
2402 and then (Nkind (Exp) = N_Type_Conversion
2403 or else Nkind (Exp) = N_Unchecked_Type_Conversion
2404 or else (Is_Entity_Name (Exp)
2405 and then Ekind (Entity (Exp)) in Formal_Kind))
2407 -- When the return type is limited, perform a check that the
2408 -- tag of the result is the same as the tag of the return type.
2410 if Is_Limited_Type (Return_Type) then
2412 Make_Raise_Constraint_Error (Loc,
2416 Make_Selected_Component (Loc,
2417 Prefix => Duplicate_Subexpr (Exp),
2419 New_Reference_To (Tag_Component (Utyp), Loc)),
2421 Unchecked_Convert_To (RTE (RE_Tag),
2423 (Access_Disp_Table (Base_Type (Utyp)), Loc))),
2424 Reason => CE_Tag_Check_Failed));
2426 -- If the result type is a specific nonlimited tagged type,
2427 -- then we have to ensure that the tag of the result is that
2428 -- of the result type. This is handled by making a copy of the
2429 -- expression in the case where it might have a different tag,
2430 -- namely when the expression is a conversion or a formal
2431 -- parameter. We create a new object of the result type and
2432 -- initialize it from the expression, which will implicitly
2433 -- force the tag to be set appropriately.
2437 Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
2438 Result_Exp := New_Reference_To (Result_Id, Loc);
2441 Make_Object_Declaration (Loc,
2442 Defining_Identifier => Result_Id,
2443 Object_Definition => New_Reference_To (Return_Type, Loc),
2444 Constant_Present => True,
2445 Expression => Relocate_Node (Exp));
2447 Set_Assignment_OK (Result_Obj);
2448 Insert_Action (Exp, Result_Obj);
2450 Rewrite (Exp, Result_Exp);
2451 Analyze_And_Resolve (Exp, Return_Type);
2455 -- Deal with returning variable length objects and controlled types
2457 -- Nothing to do if we are returning by reference, or this is not
2458 -- a type that requires special processing (indicated by the fact
2459 -- that it requires a cleanup scope for the secondary stack case)
2461 if Is_Return_By_Reference_Type (T)
2462 or else not Requires_Transient_Scope (Return_Type)
2466 -- Case of secondary stack not used
2468 elsif Function_Returns_With_DSP (Scope_Id) then
2470 -- Here what we need to do is to always return by reference, since
2471 -- we will return with the stack pointer depressed. We may need to
2472 -- do a copy to a local temporary before doing this return.
2474 No_Secondary_Stack_Case : declare
2475 Local_Copy_Required : Boolean := False;
2476 -- Set to True if a local copy is required
2478 Copy_Ent : Entity_Id;
2479 -- Used for the target entity if a copy is required
2482 -- Declaration used to create copy if needed
2484 procedure Test_Copy_Required (Expr : Node_Id);
2485 -- Determines if Expr represents a return value for which a
2486 -- copy is required. More specifically, a copy is not required
2487 -- if Expr represents an object or component of an object that
2488 -- is either in the local subprogram frame, or is constant.
2489 -- If a copy is required, then Local_Copy_Required is set True.
2491 ------------------------
2492 -- Test_Copy_Required --
2493 ------------------------
2495 procedure Test_Copy_Required (Expr : Node_Id) is
2499 -- If component, test prefix (object containing component)
2501 if Nkind (Expr) = N_Indexed_Component
2503 Nkind (Expr) = N_Selected_Component
2505 Test_Copy_Required (Prefix (Expr));
2508 -- See if we have an entity name
2510 elsif Is_Entity_Name (Expr) then
2511 Ent := Entity (Expr);
2513 -- Constant entity is always OK, no copy required
2515 if Ekind (Ent) = E_Constant then
2518 -- No copy required for local variable
2520 elsif Ekind (Ent) = E_Variable
2521 and then Scope (Ent) = Current_Subprogram
2527 -- All other cases require a copy
2529 Local_Copy_Required := True;
2530 end Test_Copy_Required;
2532 -- Start of processing for No_Secondary_Stack_Case
2535 -- No copy needed if result is from a function call for the
2536 -- same type with the same constrainedness (is the latter a
2537 -- necessary check, or could gigi produce the bounds ???).
2538 -- In this case the result is already being returned by
2539 -- reference with the stack pointer depressed.
2541 if Requires_Transient_Scope (T)
2542 and then Is_Constrained (T) = Is_Constrained (Return_Type)
2543 and then (Nkind (Exp) = N_Function_Call
2545 Nkind (Original_Node (Exp)) = N_Function_Call)
2549 -- We always need a local copy for a controlled type, since
2550 -- we are required to finalize the local value before return.
2551 -- The copy will automatically include the required finalize.
2552 -- Moreover, gigi cannot make this copy, since we need special
2553 -- processing to ensure proper behavior for finalization.
2555 -- Note: the reason we are returning with a depressed stack
2556 -- pointer in the controlled case (even if the type involved
2557 -- is constrained) is that we must make a local copy to deal
2558 -- properly with the requirement that the local result be
2561 elsif Controlled_Type (Utyp) then
2563 Make_Defining_Identifier (Loc,
2564 Chars => New_Internal_Name ('R'));
2566 -- Build declaration to do the copy, and insert it, setting
2567 -- Assignment_OK, because we may be copying a limited type.
2568 -- In addition we set the special flag to inhibit finalize
2569 -- attachment if this is a controlled type (since this attach
2570 -- must be done by the caller, otherwise if we attach it here
2571 -- we will finalize the returned result prematurely).
2574 Make_Object_Declaration (Loc,
2575 Defining_Identifier => Copy_Ent,
2576 Object_Definition => New_Occurrence_Of (Return_Type, Loc),
2577 Expression => Relocate_Node (Exp));
2579 Set_Assignment_OK (Decl);
2580 Set_Delay_Finalize_Attach (Decl);
2581 Insert_Action (N, Decl);
2583 -- Now the actual return uses the copied value
2585 Rewrite (Exp, New_Occurrence_Of (Copy_Ent, Loc));
2586 Analyze_And_Resolve (Exp, Return_Type);
2588 -- Since we have made the copy, gigi does not have to, so
2589 -- we set the By_Ref flag to prevent another copy being made.
2593 -- Non-controlled cases
2596 Test_Copy_Required (Exp);
2598 -- If a local copy is required, then gigi will make the
2599 -- copy, otherwise, we can return the result directly,
2600 -- so set By_Ref to suppress the gigi copy.
2602 if not Local_Copy_Required then
2606 end No_Secondary_Stack_Case;
2608 -- Here if secondary stack is used
2611 -- Make sure that no surrounding block will reclaim the
2612 -- secondary-stack on which we are going to put the result.
2613 -- Not only may this introduce secondary stack leaks but worse,
2614 -- if the reclamation is done too early, then the result we are
2615 -- returning may get clobbered. See example in 7417-003.
2618 S : Entity_Id := Current_Scope;
2621 while Ekind (S) = E_Block or else Ekind (S) = E_Loop loop
2622 Set_Sec_Stack_Needed_For_Return (S, True);
2623 S := Enclosing_Dynamic_Scope (S);
2627 -- Optimize the case where the result is from a function call for
2628 -- the same type with the same constrainedness (is the latter a
2629 -- necessary check, or could gigi produce the bounds ???). In this
2630 -- case either the result is already on the secondary stack, or is
2631 -- already being returned with the stack pointer depressed and no
2632 -- further processing is required except to set the By_Ref flag to
2633 -- ensure that gigi does not attempt an extra unnecessary copy.
2634 -- (actually not just unnecessary but harmfully wrong in the case
2635 -- of a controlled type, where gigi does not know how to do a copy).
2637 if Requires_Transient_Scope (T)
2638 and then Is_Constrained (T) = Is_Constrained (Return_Type)
2639 and then (Nkind (Exp) = N_Function_Call
2640 or else Nkind (Original_Node (Exp)) = N_Function_Call)
2644 -- For controlled types, do the allocation on the sec-stack
2645 -- manually in order to call adjust at the right time
2646 -- type Anon1 is access Return_Type;
2647 -- for Anon1'Storage_pool use ss_pool;
2648 -- Anon2 : anon1 := new Return_Type'(expr);
2649 -- return Anon2.all;
2651 elsif Controlled_Type (Utyp) then
2653 Loc : constant Source_Ptr := Sloc (N);
2654 Temp : constant Entity_Id :=
2655 Make_Defining_Identifier (Loc,
2656 Chars => New_Internal_Name ('R'));
2657 Acc_Typ : constant Entity_Id :=
2658 Make_Defining_Identifier (Loc,
2659 Chars => New_Internal_Name ('A'));
2660 Alloc_Node : Node_Id;
2663 Set_Ekind (Acc_Typ, E_Access_Type);
2665 Set_Associated_Storage_Pool (Acc_Typ, RTE (RE_SS_Pool));
2668 Make_Allocator (Loc,
2670 Make_Qualified_Expression (Loc,
2671 Subtype_Mark => New_Reference_To (Etype (Exp), Loc),
2672 Expression => Relocate_Node (Exp)));
2674 Insert_List_Before_And_Analyze (N, New_List (
2675 Make_Full_Type_Declaration (Loc,
2676 Defining_Identifier => Acc_Typ,
2678 Make_Access_To_Object_Definition (Loc,
2679 Subtype_Indication =>
2680 New_Reference_To (Return_Type, Loc))),
2682 Make_Object_Declaration (Loc,
2683 Defining_Identifier => Temp,
2684 Object_Definition => New_Reference_To (Acc_Typ, Loc),
2685 Expression => Alloc_Node)));
2688 Make_Explicit_Dereference (Loc,
2689 Prefix => New_Reference_To (Temp, Loc)));
2691 Analyze_And_Resolve (Exp, Return_Type);
2694 -- Otherwise use the gigi mechanism to allocate result on the
2698 Set_Storage_Pool (N, RTE (RE_SS_Pool));
2700 -- If we are generating code for the Java VM do not use
2701 -- SS_Allocate since everything is heap-allocated anyway.
2704 Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
2708 end Expand_N_Return_Statement;
2710 ------------------------------
2711 -- Make_Tag_Ctrl_Assignment --
2712 ------------------------------
2714 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
2715 Loc : constant Source_Ptr := Sloc (N);
2716 L : constant Node_Id := Name (N);
2717 T : constant Entity_Id := Underlying_Type (Etype (L));
2719 Ctrl_Act : constant Boolean := Controlled_Type (T)
2720 and then not No_Ctrl_Actions (N);
2722 Save_Tag : constant Boolean := Is_Tagged_Type (T)
2723 and then not No_Ctrl_Actions (N)
2724 and then not Java_VM;
2725 -- Tags are not saved and restored when Java_VM because JVM tags
2726 -- are represented implicitly in objects.
2729 Tag_Tmp : Entity_Id;
2730 Prev_Tmp : Entity_Id;
2731 Next_Tmp : Entity_Id;
2737 -- Finalize the target of the assignment when controlled.
2738 -- We have two exceptions here:
2740 -- 1. If we are in an init_proc since it is an initialization
2741 -- more than an assignment
2743 -- 2. If the left-hand side is a temporary that was not initialized
2744 -- (or the parent part of a temporary since it is the case in
2745 -- extension aggregates). Such a temporary does not come from
2746 -- source. We must examine the original node for the prefix, because
2747 -- it may be a component of an entry formal, in which case it has
2748 -- been rewritten and does not appear to come from source either.
2752 if not Ctrl_Act then
2755 -- The left hand side is an uninitialized temporary
2757 elsif Nkind (L) = N_Type_Conversion
2758 and then Is_Entity_Name (Expression (L))
2759 and then No_Initialization (Parent (Entity (Expression (L))))
2763 Append_List_To (Res,
2765 Ref => Duplicate_Subexpr (L),
2767 With_Detach => New_Reference_To (Standard_False, Loc)));
2770 Next_Tmp := Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
2772 -- Save the Tag in a local variable Tag_Tmp
2776 Make_Defining_Identifier (Loc, New_Internal_Name ('A'));
2779 Make_Object_Declaration (Loc,
2780 Defining_Identifier => Tag_Tmp,
2781 Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
2783 Make_Selected_Component (Loc,
2784 Prefix => Duplicate_Subexpr (L),
2785 Selector_Name => New_Reference_To (Tag_Component (T), Loc))));
2787 -- Otherwise Tag_Tmp not used
2793 -- Save the Finalization Pointers in local variables Prev_Tmp and
2794 -- Next_Tmp. For objects with Has_Controlled_Component set, these
2795 -- pointers are in the Record_Controller
2798 Ctrl_Ref := Duplicate_Subexpr (L);
2800 if Has_Controlled_Component (T) then
2802 Make_Selected_Component (Loc,
2805 New_Reference_To (Controller_Component (T), Loc));
2808 Prev_Tmp := Make_Defining_Identifier (Loc, New_Internal_Name ('B'));
2811 Make_Object_Declaration (Loc,
2812 Defining_Identifier => Prev_Tmp,
2814 Object_Definition =>
2815 New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
2818 Make_Selected_Component (Loc,
2820 Unchecked_Convert_To (RTE (RE_Finalizable), Ctrl_Ref),
2821 Selector_Name => Make_Identifier (Loc, Name_Prev))));
2823 Next_Tmp := Make_Defining_Identifier (Loc, New_Internal_Name ('C'));
2826 Make_Object_Declaration (Loc,
2827 Defining_Identifier => Next_Tmp,
2829 Object_Definition =>
2830 New_Reference_To (RTE (RE_Finalizable_Ptr), Loc),
2833 Make_Selected_Component (Loc,
2835 Unchecked_Convert_To (RTE (RE_Finalizable),
2836 New_Copy_Tree (Ctrl_Ref)),
2837 Selector_Name => Make_Identifier (Loc, Name_Next))));
2839 -- If not controlled type, then Prev_Tmp and Ctrl_Ref unused
2846 -- Do the Assignment
2848 Append_To (Res, Relocate_Node (N));
2854 Make_Assignment_Statement (Loc,
2856 Make_Selected_Component (Loc,
2857 Prefix => Duplicate_Subexpr (L),
2858 Selector_Name => New_Reference_To (Tag_Component (T), Loc)),
2859 Expression => New_Reference_To (Tag_Tmp, Loc)));
2862 -- Restore the finalization pointers
2866 Make_Assignment_Statement (Loc,
2868 Make_Selected_Component (Loc,
2870 Unchecked_Convert_To (RTE (RE_Finalizable),
2871 New_Copy_Tree (Ctrl_Ref)),
2872 Selector_Name => Make_Identifier (Loc, Name_Prev)),
2873 Expression => New_Reference_To (Prev_Tmp, Loc)));
2876 Make_Assignment_Statement (Loc,
2878 Make_Selected_Component (Loc,
2880 Unchecked_Convert_To (RTE (RE_Finalizable),
2881 New_Copy_Tree (Ctrl_Ref)),
2882 Selector_Name => Make_Identifier (Loc, Name_Next)),
2883 Expression => New_Reference_To (Next_Tmp, Loc)));
2886 -- Adjust the target after the assignment when controlled. (not in
2887 -- the init_proc since it is an initialization more than an
2891 Append_List_To (Res,
2893 Ref => Duplicate_Subexpr (L),
2895 Flist_Ref => New_Reference_To (RTE (RE_Global_Final_List), Loc),
2896 With_Attach => Make_Integer_Literal (Loc, 0)));
2900 end Make_Tag_Ctrl_Assignment;