Implement -mmemcpy-strategy= and -mmemset-strategy= options
[official-gcc.git] / gcc / ada / exp_ch5.adb
blob95e649a13e9214fba8ff613eec4b678a331bae48
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-2013, 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 3, 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 COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
26 with Aspects; use Aspects;
27 with Atree; use Atree;
28 with Checks; use Checks;
29 with Debug; use Debug;
30 with Einfo; use Einfo;
31 with Errout; use Errout;
32 with Exp_Aggr; use Exp_Aggr;
33 with Exp_Ch6; use Exp_Ch6;
34 with Exp_Ch7; use Exp_Ch7;
35 with Exp_Ch11; use Exp_Ch11;
36 with Exp_Dbug; use Exp_Dbug;
37 with Exp_Pakd; use Exp_Pakd;
38 with Exp_Tss; use Exp_Tss;
39 with Exp_Util; use Exp_Util;
40 with Namet; use Namet;
41 with Nlists; use Nlists;
42 with Nmake; use Nmake;
43 with Opt; use Opt;
44 with Restrict; use Restrict;
45 with Rident; use Rident;
46 with Rtsfind; use Rtsfind;
47 with Sinfo; use Sinfo;
48 with Sem; use Sem;
49 with Sem_Aux; use Sem_Aux;
50 with Sem_Ch3; use Sem_Ch3;
51 with Sem_Ch8; use Sem_Ch8;
52 with Sem_Ch13; use Sem_Ch13;
53 with Sem_Eval; use Sem_Eval;
54 with Sem_Res; use Sem_Res;
55 with Sem_Util; use Sem_Util;
56 with Snames; use Snames;
57 with Stand; use Stand;
58 with Stringt; use Stringt;
59 with Targparm; use Targparm;
60 with Tbuild; use Tbuild;
61 with Validsw; use Validsw;
63 package body Exp_Ch5 is
65 function Change_Of_Representation (N : Node_Id) return Boolean;
66 -- Determine if the right hand side of assignment N is a type conversion
67 -- which requires a change of representation. Called only for the array
68 -- and record cases.
70 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
71 -- N is an assignment which assigns an array value. This routine process
72 -- the various special cases and checks required for such assignments,
73 -- including change of representation. Rhs is normally simply the right
74 -- hand side of the assignment, except that if the right hand side is a
75 -- type conversion or a qualified expression, then the RHS is the actual
76 -- expression inside any such type conversions or qualifications.
78 function Expand_Assign_Array_Loop
79 (N : Node_Id;
80 Larray : Entity_Id;
81 Rarray : Entity_Id;
82 L_Type : Entity_Id;
83 R_Type : Entity_Id;
84 Ndim : Pos;
85 Rev : Boolean) return Node_Id;
86 -- N is an assignment statement which assigns an array value. This routine
87 -- expands the assignment into a loop (or nested loops for the case of a
88 -- multi-dimensional array) to do the assignment component by component.
89 -- Larray and Rarray are the entities of the actual arrays on the left
90 -- hand and right hand sides. L_Type and R_Type are the types of these
91 -- arrays (which may not be the same, due to either sliding, or to a
92 -- change of representation case). Ndim is the number of dimensions and
93 -- the parameter Rev indicates if the loops run normally (Rev = False),
94 -- or reversed (Rev = True). The value returned is the constructed
95 -- loop statement. Auxiliary declarations are inserted before node N
96 -- using the standard Insert_Actions mechanism.
98 procedure Expand_Assign_Record (N : Node_Id);
99 -- N is an assignment of a non-tagged record value. This routine handles
100 -- the case where the assignment must be made component by component,
101 -- either because the target is not byte aligned, or there is a change
102 -- of representation, or when we have a tagged type with a representation
103 -- clause (this last case is required because holes in the tagged type
104 -- might be filled with components from child types).
106 procedure Expand_Iterator_Loop (N : Node_Id);
107 -- Expand loop over arrays and containers that uses the form "for X of C"
108 -- with an optional subtype mark, or "for Y in C".
110 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id);
111 -- Expand loop over arrays that uses the form "for X of C"
113 procedure Expand_Predicated_Loop (N : Node_Id);
114 -- Expand for loop over predicated subtype
116 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
117 -- Generate the necessary code for controlled and tagged assignment, that
118 -- is to say, finalization of the target before, adjustment of the target
119 -- after and save and restore of the tag and finalization pointers which
120 -- are not 'part of the value' and must not be changed upon assignment. N
121 -- is the original Assignment node.
123 ------------------------------
124 -- Change_Of_Representation --
125 ------------------------------
127 function Change_Of_Representation (N : Node_Id) return Boolean is
128 Rhs : constant Node_Id := Expression (N);
129 begin
130 return
131 Nkind (Rhs) = N_Type_Conversion
132 and then
133 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
134 end Change_Of_Representation;
136 -------------------------
137 -- Expand_Assign_Array --
138 -------------------------
140 -- There are two issues here. First, do we let Gigi do a block move, or
141 -- do we expand out into a loop? Second, we need to set the two flags
142 -- Forwards_OK and Backwards_OK which show whether the block move (or
143 -- corresponding loops) can be legitimately done in a forwards (low to
144 -- high) or backwards (high to low) manner.
146 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
147 Loc : constant Source_Ptr := Sloc (N);
149 Lhs : constant Node_Id := Name (N);
151 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
152 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
154 L_Type : constant Entity_Id :=
155 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
156 R_Type : Entity_Id :=
157 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
159 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
160 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
162 Crep : constant Boolean := Change_Of_Representation (N);
164 Larray : Node_Id;
165 Rarray : Node_Id;
167 Ndim : constant Pos := Number_Dimensions (L_Type);
169 Loop_Required : Boolean := False;
170 -- This switch is set to True if the array move must be done using
171 -- an explicit front end generated loop.
173 procedure Apply_Dereference (Arg : Node_Id);
174 -- If the argument is an access to an array, and the assignment is
175 -- converted into a procedure call, apply explicit dereference.
177 function Has_Address_Clause (Exp : Node_Id) return Boolean;
178 -- Test if Exp is a reference to an array whose declaration has
179 -- an address clause, or it is a slice of such an array.
181 function Is_Formal_Array (Exp : Node_Id) return Boolean;
182 -- Test if Exp is a reference to an array which is either a formal
183 -- parameter or a slice of a formal parameter. These are the cases
184 -- where hidden aliasing can occur.
186 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
187 -- Determine if Exp is a reference to an array variable which is other
188 -- than an object defined in the current scope, or a slice of such
189 -- an object. Such objects can be aliased to parameters (unlike local
190 -- array references).
192 -----------------------
193 -- Apply_Dereference --
194 -----------------------
196 procedure Apply_Dereference (Arg : Node_Id) is
197 Typ : constant Entity_Id := Etype (Arg);
198 begin
199 if Is_Access_Type (Typ) then
200 Rewrite (Arg, Make_Explicit_Dereference (Loc,
201 Prefix => Relocate_Node (Arg)));
202 Analyze_And_Resolve (Arg, Designated_Type (Typ));
203 end if;
204 end Apply_Dereference;
206 ------------------------
207 -- Has_Address_Clause --
208 ------------------------
210 function Has_Address_Clause (Exp : Node_Id) return Boolean is
211 begin
212 return
213 (Is_Entity_Name (Exp) and then
214 Present (Address_Clause (Entity (Exp))))
215 or else
216 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
217 end Has_Address_Clause;
219 ---------------------
220 -- Is_Formal_Array --
221 ---------------------
223 function Is_Formal_Array (Exp : Node_Id) return Boolean is
224 begin
225 return
226 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
227 or else
228 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
229 end Is_Formal_Array;
231 ------------------------
232 -- Is_Non_Local_Array --
233 ------------------------
235 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
236 begin
237 return (Is_Entity_Name (Exp)
238 and then Scope (Entity (Exp)) /= Current_Scope)
239 or else (Nkind (Exp) = N_Slice
240 and then Is_Non_Local_Array (Prefix (Exp)));
241 end Is_Non_Local_Array;
243 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
245 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
246 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
248 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
249 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
251 -- Start of processing for Expand_Assign_Array
253 begin
254 -- Deal with length check. Note that the length check is done with
255 -- respect to the right hand side as given, not a possible underlying
256 -- renamed object, since this would generate incorrect extra checks.
258 Apply_Length_Check (Rhs, L_Type);
260 -- We start by assuming that the move can be done in either direction,
261 -- i.e. that the two sides are completely disjoint.
263 Set_Forwards_OK (N, True);
264 Set_Backwards_OK (N, True);
266 -- Normally it is only the slice case that can lead to overlap, and
267 -- explicit checks for slices are made below. But there is one case
268 -- where the slice can be implicit and invisible to us: when we have a
269 -- one dimensional array, and either both operands are parameters, or
270 -- one is a parameter (which can be a slice passed by reference) and the
271 -- other is a non-local variable. In this case the parameter could be a
272 -- slice that overlaps with the other operand.
274 -- However, if the array subtype is a constrained first subtype in the
275 -- parameter case, then we don't have to worry about overlap, since
276 -- slice assignments aren't possible (other than for a slice denoting
277 -- the whole array).
279 -- Note: No overlap is possible if there is a change of representation,
280 -- so we can exclude this case.
282 if Ndim = 1
283 and then not Crep
284 and then
285 ((Lhs_Formal and Rhs_Formal)
286 or else
287 (Lhs_Formal and Rhs_Non_Local_Var)
288 or else
289 (Rhs_Formal and Lhs_Non_Local_Var))
290 and then
291 (not Is_Constrained (Etype (Lhs))
292 or else not Is_First_Subtype (Etype (Lhs)))
294 -- In the case of compiling for the Java or .NET Virtual Machine,
295 -- slices are always passed by making a copy, so we don't have to
296 -- worry about overlap. We also want to prevent generation of "<"
297 -- comparisons for array addresses, since that's a meaningless
298 -- operation on the VM.
300 and then VM_Target = No_VM
301 then
302 Set_Forwards_OK (N, False);
303 Set_Backwards_OK (N, False);
305 -- Note: the bit-packed case is not worrisome here, since if we have
306 -- a slice passed as a parameter, it is always aligned on a byte
307 -- boundary, and if there are no explicit slices, the assignment
308 -- can be performed directly.
309 end if;
311 -- If either operand has an address clause clear Backwards_OK and
312 -- Forwards_OK, since we cannot tell if the operands overlap. We
313 -- exclude this treatment when Rhs is an aggregate, since we know
314 -- that overlap can't occur.
316 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
317 or else Has_Address_Clause (Rhs)
318 then
319 Set_Forwards_OK (N, False);
320 Set_Backwards_OK (N, False);
321 end if;
323 -- We certainly must use a loop for change of representation and also
324 -- we use the operand of the conversion on the right hand side as the
325 -- effective right hand side (the component types must match in this
326 -- situation).
328 if Crep then
329 Act_Rhs := Get_Referenced_Object (Rhs);
330 R_Type := Get_Actual_Subtype (Act_Rhs);
331 Loop_Required := True;
333 -- We require a loop if the left side is possibly bit unaligned
335 elsif Possible_Bit_Aligned_Component (Lhs)
336 or else
337 Possible_Bit_Aligned_Component (Rhs)
338 then
339 Loop_Required := True;
341 -- Arrays with controlled components are expanded into a loop to force
342 -- calls to Adjust at the component level.
344 elsif Has_Controlled_Component (L_Type) then
345 Loop_Required := True;
347 -- If object is atomic, we cannot tolerate a loop
349 elsif Is_Atomic_Object (Act_Lhs)
350 or else
351 Is_Atomic_Object (Act_Rhs)
352 then
353 return;
355 -- Loop is required if we have atomic components since we have to
356 -- be sure to do any accesses on an element by element basis.
358 elsif Has_Atomic_Components (L_Type)
359 or else Has_Atomic_Components (R_Type)
360 or else Is_Atomic (Component_Type (L_Type))
361 or else Is_Atomic (Component_Type (R_Type))
362 then
363 Loop_Required := True;
365 -- Case where no slice is involved
367 elsif not L_Slice and not R_Slice then
369 -- The following code deals with the case of unconstrained bit packed
370 -- arrays. The problem is that the template for such arrays contains
371 -- the bounds of the actual source level array, but the copy of an
372 -- entire array requires the bounds of the underlying array. It would
373 -- be nice if the back end could take care of this, but right now it
374 -- does not know how, so if we have such a type, then we expand out
375 -- into a loop, which is inefficient but works correctly. If we don't
376 -- do this, we get the wrong length computed for the array to be
377 -- moved. The two cases we need to worry about are:
379 -- Explicit dereference of an unconstrained packed array type as in
380 -- the following example:
382 -- procedure C52 is
383 -- type BITS is array(INTEGER range <>) of BOOLEAN;
384 -- pragma PACK(BITS);
385 -- type A is access BITS;
386 -- P1,P2 : A;
387 -- begin
388 -- P1 := new BITS (1 .. 65_535);
389 -- P2 := new BITS (1 .. 65_535);
390 -- P2.ALL := P1.ALL;
391 -- end C52;
393 -- A formal parameter reference with an unconstrained bit array type
394 -- is the other case we need to worry about (here we assume the same
395 -- BITS type declared above):
397 -- procedure Write_All (File : out BITS; Contents : BITS);
398 -- begin
399 -- File.Storage := Contents;
400 -- end Write_All;
402 -- We expand to a loop in either of these two cases
404 -- Question for future thought. Another potentially more efficient
405 -- approach would be to create the actual subtype, and then do an
406 -- unchecked conversion to this actual subtype ???
408 Check_Unconstrained_Bit_Packed_Array : declare
410 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
411 -- Function to perform required test for the first case, above
412 -- (dereference of an unconstrained bit packed array).
414 -----------------------
415 -- Is_UBPA_Reference --
416 -----------------------
418 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
419 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
420 P_Type : Entity_Id;
421 Des_Type : Entity_Id;
423 begin
424 if Present (Packed_Array_Type (Typ))
425 and then Is_Array_Type (Packed_Array_Type (Typ))
426 and then not Is_Constrained (Packed_Array_Type (Typ))
427 then
428 return True;
430 elsif Nkind (Opnd) = N_Explicit_Dereference then
431 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
433 if not Is_Access_Type (P_Type) then
434 return False;
436 else
437 Des_Type := Designated_Type (P_Type);
438 return
439 Is_Bit_Packed_Array (Des_Type)
440 and then not Is_Constrained (Des_Type);
441 end if;
443 else
444 return False;
445 end if;
446 end Is_UBPA_Reference;
448 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
450 begin
451 if Is_UBPA_Reference (Lhs)
452 or else
453 Is_UBPA_Reference (Rhs)
454 then
455 Loop_Required := True;
457 -- Here if we do not have the case of a reference to a bit packed
458 -- unconstrained array case. In this case gigi can most certainly
459 -- handle the assignment if a forwards move is allowed.
461 -- (could it handle the backwards case also???)
463 elsif Forwards_OK (N) then
464 return;
465 end if;
466 end Check_Unconstrained_Bit_Packed_Array;
468 -- The back end can always handle the assignment if the right side is a
469 -- string literal (note that overlap is definitely impossible in this
470 -- case). If the type is packed, a string literal is always converted
471 -- into an aggregate, except in the case of a null slice, for which no
472 -- aggregate can be written. In that case, rewrite the assignment as a
473 -- null statement, a length check has already been emitted to verify
474 -- that the range of the left-hand side is empty.
476 -- Note that this code is not executed if we have an assignment of a
477 -- string literal to a non-bit aligned component of a record, a case
478 -- which cannot be handled by the backend.
480 elsif Nkind (Rhs) = N_String_Literal then
481 if String_Length (Strval (Rhs)) = 0
482 and then Is_Bit_Packed_Array (L_Type)
483 then
484 Rewrite (N, Make_Null_Statement (Loc));
485 Analyze (N);
486 end if;
488 return;
490 -- If either operand is bit packed, then we need a loop, since we can't
491 -- be sure that the slice is byte aligned. Similarly, if either operand
492 -- is a possibly unaligned slice, then we need a loop (since the back
493 -- end cannot handle unaligned slices).
495 elsif Is_Bit_Packed_Array (L_Type)
496 or else Is_Bit_Packed_Array (R_Type)
497 or else Is_Possibly_Unaligned_Slice (Lhs)
498 or else Is_Possibly_Unaligned_Slice (Rhs)
499 then
500 Loop_Required := True;
502 -- If we are not bit-packed, and we have only one slice, then no overlap
503 -- is possible except in the parameter case, so we can let the back end
504 -- handle things.
506 elsif not (L_Slice and R_Slice) then
507 if Forwards_OK (N) then
508 return;
509 end if;
510 end if;
512 -- If the right-hand side is a string literal, introduce a temporary for
513 -- it, for use in the generated loop that will follow.
515 if Nkind (Rhs) = N_String_Literal then
516 declare
517 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
518 Decl : Node_Id;
520 begin
521 Decl :=
522 Make_Object_Declaration (Loc,
523 Defining_Identifier => Temp,
524 Object_Definition => New_Occurrence_Of (L_Type, Loc),
525 Expression => Relocate_Node (Rhs));
527 Insert_Action (N, Decl);
528 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
529 R_Type := Etype (Temp);
530 end;
531 end if;
533 -- Come here to complete the analysis
535 -- Loop_Required: Set to True if we know that a loop is required
536 -- regardless of overlap considerations.
538 -- Forwards_OK: Set to False if we already know that a forwards
539 -- move is not safe, else set to True.
541 -- Backwards_OK: Set to False if we already know that a backwards
542 -- move is not safe, else set to True
544 -- Our task at this stage is to complete the overlap analysis, which can
545 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
546 -- then generating the final code, either by deciding that it is OK
547 -- after all to let Gigi handle it, or by generating appropriate code
548 -- in the front end.
550 declare
551 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
552 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
554 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
555 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
556 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
557 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
559 Act_L_Array : Node_Id;
560 Act_R_Array : Node_Id;
562 Cleft_Lo : Node_Id;
563 Cright_Lo : Node_Id;
564 Condition : Node_Id;
566 Cresult : Compare_Result;
568 begin
569 -- Get the expressions for the arrays. If we are dealing with a
570 -- private type, then convert to the underlying type. We can do
571 -- direct assignments to an array that is a private type, but we
572 -- cannot assign to elements of the array without this extra
573 -- unchecked conversion.
575 -- Note: We propagate Parent to the conversion nodes to generate
576 -- a well-formed subtree.
578 if Nkind (Act_Lhs) = N_Slice then
579 Larray := Prefix (Act_Lhs);
580 else
581 Larray := Act_Lhs;
583 if Is_Private_Type (Etype (Larray)) then
584 declare
585 Par : constant Node_Id := Parent (Larray);
586 begin
587 Larray :=
588 Unchecked_Convert_To
589 (Underlying_Type (Etype (Larray)), Larray);
590 Set_Parent (Larray, Par);
591 end;
592 end if;
593 end if;
595 if Nkind (Act_Rhs) = N_Slice then
596 Rarray := Prefix (Act_Rhs);
597 else
598 Rarray := Act_Rhs;
600 if Is_Private_Type (Etype (Rarray)) then
601 declare
602 Par : constant Node_Id := Parent (Rarray);
603 begin
604 Rarray :=
605 Unchecked_Convert_To
606 (Underlying_Type (Etype (Rarray)), Rarray);
607 Set_Parent (Rarray, Par);
608 end;
609 end if;
610 end if;
612 -- If both sides are slices, we must figure out whether it is safe
613 -- to do the move in one direction or the other. It is always safe
614 -- if there is a change of representation since obviously two arrays
615 -- with different representations cannot possibly overlap.
617 if (not Crep) and L_Slice and R_Slice then
618 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
619 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
621 -- If both left and right hand arrays are entity names, and refer
622 -- to different entities, then we know that the move is safe (the
623 -- two storage areas are completely disjoint).
625 if Is_Entity_Name (Act_L_Array)
626 and then Is_Entity_Name (Act_R_Array)
627 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
628 then
629 null;
631 -- Otherwise, we assume the worst, which is that the two arrays
632 -- are the same array. There is no need to check if we know that
633 -- is the case, because if we don't know it, we still have to
634 -- assume it!
636 -- Generally if the same array is involved, then we have an
637 -- overlapping case. We will have to really assume the worst (i.e.
638 -- set neither of the OK flags) unless we can determine the lower
639 -- or upper bounds at compile time and compare them.
641 else
642 Cresult :=
643 Compile_Time_Compare
644 (Left_Lo, Right_Lo, Assume_Valid => True);
646 if Cresult = Unknown then
647 Cresult :=
648 Compile_Time_Compare
649 (Left_Hi, Right_Hi, Assume_Valid => True);
650 end if;
652 case Cresult is
653 when LT | LE | EQ => Set_Backwards_OK (N, False);
654 when GT | GE => Set_Forwards_OK (N, False);
655 when NE | Unknown => Set_Backwards_OK (N, False);
656 Set_Forwards_OK (N, False);
657 end case;
658 end if;
659 end if;
661 -- If after that analysis Loop_Required is False, meaning that we
662 -- have not discovered some non-overlap reason for requiring a loop,
663 -- then the outcome depends on the capabilities of the back end.
665 if not Loop_Required then
667 -- The GCC back end can deal with all cases of overlap by falling
668 -- back to memmove if it cannot use a more efficient approach.
670 if VM_Target = No_VM and not AAMP_On_Target then
671 return;
673 -- Assume other back ends can handle it if Forwards_OK is set
675 elsif Forwards_OK (N) then
676 return;
678 -- If Forwards_OK is not set, the back end will need something
679 -- like memmove to handle the move. For now, this processing is
680 -- activated using the .s debug flag (-gnatd.s).
682 elsif Debug_Flag_Dot_S then
683 return;
684 end if;
685 end if;
687 -- At this stage we have to generate an explicit loop, and we have
688 -- the following cases:
690 -- Forwards_OK = True
692 -- Rnn : right_index := right_index'First;
693 -- for Lnn in left-index loop
694 -- left (Lnn) := right (Rnn);
695 -- Rnn := right_index'Succ (Rnn);
696 -- end loop;
698 -- Note: the above code MUST be analyzed with checks off, because
699 -- otherwise the Succ could overflow. But in any case this is more
700 -- efficient!
702 -- Forwards_OK = False, Backwards_OK = True
704 -- Rnn : right_index := right_index'Last;
705 -- for Lnn in reverse left-index loop
706 -- left (Lnn) := right (Rnn);
707 -- Rnn := right_index'Pred (Rnn);
708 -- end loop;
710 -- Note: the above code MUST be analyzed with checks off, because
711 -- otherwise the Pred could overflow. But in any case this is more
712 -- efficient!
714 -- Forwards_OK = Backwards_OK = False
716 -- This only happens if we have the same array on each side. It is
717 -- possible to create situations using overlays that violate this,
718 -- but we simply do not promise to get this "right" in this case.
720 -- There are two possible subcases. If the No_Implicit_Conditionals
721 -- restriction is set, then we generate the following code:
723 -- declare
724 -- T : constant <operand-type> := rhs;
725 -- begin
726 -- lhs := T;
727 -- end;
729 -- If implicit conditionals are permitted, then we generate:
731 -- if Left_Lo <= Right_Lo then
732 -- <code for Forwards_OK = True above>
733 -- else
734 -- <code for Backwards_OK = True above>
735 -- end if;
737 -- In order to detect possible aliasing, we examine the renamed
738 -- expression when the source or target is a renaming. However,
739 -- the renaming may be intended to capture an address that may be
740 -- affected by subsequent code, and therefore we must recover
741 -- the actual entity for the expansion that follows, not the
742 -- object it renames. In particular, if source or target designate
743 -- a portion of a dynamically allocated object, the pointer to it
744 -- may be reassigned but the renaming preserves the proper location.
746 if Is_Entity_Name (Rhs)
747 and then
748 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
749 and then Nkind (Act_Rhs) = N_Slice
750 then
751 Rarray := Rhs;
752 end if;
754 if Is_Entity_Name (Lhs)
755 and then
756 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
757 and then Nkind (Act_Lhs) = N_Slice
758 then
759 Larray := Lhs;
760 end if;
762 -- Cases where either Forwards_OK or Backwards_OK is true
764 if Forwards_OK (N) or else Backwards_OK (N) then
765 if Needs_Finalization (Component_Type (L_Type))
766 and then Base_Type (L_Type) = Base_Type (R_Type)
767 and then Ndim = 1
768 and then not No_Ctrl_Actions (N)
769 then
770 declare
771 Proc : constant Entity_Id :=
772 TSS (Base_Type (L_Type), TSS_Slice_Assign);
773 Actuals : List_Id;
775 begin
776 Apply_Dereference (Larray);
777 Apply_Dereference (Rarray);
778 Actuals := New_List (
779 Duplicate_Subexpr (Larray, Name_Req => True),
780 Duplicate_Subexpr (Rarray, Name_Req => True),
781 Duplicate_Subexpr (Left_Lo, Name_Req => True),
782 Duplicate_Subexpr (Left_Hi, Name_Req => True),
783 Duplicate_Subexpr (Right_Lo, Name_Req => True),
784 Duplicate_Subexpr (Right_Hi, Name_Req => True));
786 Append_To (Actuals,
787 New_Occurrence_Of (
788 Boolean_Literals (not Forwards_OK (N)), Loc));
790 Rewrite (N,
791 Make_Procedure_Call_Statement (Loc,
792 Name => New_Reference_To (Proc, Loc),
793 Parameter_Associations => Actuals));
794 end;
796 else
797 Rewrite (N,
798 Expand_Assign_Array_Loop
799 (N, Larray, Rarray, L_Type, R_Type, Ndim,
800 Rev => not Forwards_OK (N)));
801 end if;
803 -- Case of both are false with No_Implicit_Conditionals
805 elsif Restriction_Active (No_Implicit_Conditionals) then
806 declare
807 T : constant Entity_Id :=
808 Make_Defining_Identifier (Loc, Chars => Name_T);
810 begin
811 Rewrite (N,
812 Make_Block_Statement (Loc,
813 Declarations => New_List (
814 Make_Object_Declaration (Loc,
815 Defining_Identifier => T,
816 Constant_Present => True,
817 Object_Definition =>
818 New_Occurrence_Of (Etype (Rhs), Loc),
819 Expression => Relocate_Node (Rhs))),
821 Handled_Statement_Sequence =>
822 Make_Handled_Sequence_Of_Statements (Loc,
823 Statements => New_List (
824 Make_Assignment_Statement (Loc,
825 Name => Relocate_Node (Lhs),
826 Expression => New_Occurrence_Of (T, Loc))))));
827 end;
829 -- Case of both are false with implicit conditionals allowed
831 else
832 -- Before we generate this code, we must ensure that the left and
833 -- right side array types are defined. They may be itypes, and we
834 -- cannot let them be defined inside the if, since the first use
835 -- in the then may not be executed.
837 Ensure_Defined (L_Type, N);
838 Ensure_Defined (R_Type, N);
840 -- We normally compare addresses to find out which way round to
841 -- do the loop, since this is reliable, and handles the cases of
842 -- parameters, conversions etc. But we can't do that in the bit
843 -- packed case or the VM case, because addresses don't work there.
845 if not Is_Bit_Packed_Array (L_Type) and then VM_Target = No_VM then
846 Condition :=
847 Make_Op_Le (Loc,
848 Left_Opnd =>
849 Unchecked_Convert_To (RTE (RE_Integer_Address),
850 Make_Attribute_Reference (Loc,
851 Prefix =>
852 Make_Indexed_Component (Loc,
853 Prefix =>
854 Duplicate_Subexpr_Move_Checks (Larray, True),
855 Expressions => New_List (
856 Make_Attribute_Reference (Loc,
857 Prefix =>
858 New_Reference_To
859 (L_Index_Typ, Loc),
860 Attribute_Name => Name_First))),
861 Attribute_Name => Name_Address)),
863 Right_Opnd =>
864 Unchecked_Convert_To (RTE (RE_Integer_Address),
865 Make_Attribute_Reference (Loc,
866 Prefix =>
867 Make_Indexed_Component (Loc,
868 Prefix =>
869 Duplicate_Subexpr_Move_Checks (Rarray, True),
870 Expressions => New_List (
871 Make_Attribute_Reference (Loc,
872 Prefix =>
873 New_Reference_To
874 (R_Index_Typ, Loc),
875 Attribute_Name => Name_First))),
876 Attribute_Name => Name_Address)));
878 -- For the bit packed and VM cases we use the bounds. That's OK,
879 -- because we don't have to worry about parameters, since they
880 -- cannot cause overlap. Perhaps we should worry about weird slice
881 -- conversions ???
883 else
884 -- Copy the bounds
886 Cleft_Lo := New_Copy_Tree (Left_Lo);
887 Cright_Lo := New_Copy_Tree (Right_Lo);
889 -- If the types do not match we add an implicit conversion
890 -- here to ensure proper match
892 if Etype (Left_Lo) /= Etype (Right_Lo) then
893 Cright_Lo :=
894 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
895 end if;
897 -- Reset the Analyzed flag, because the bounds of the index
898 -- type itself may be universal, and must must be reanalyzed
899 -- to acquire the proper type for the back end.
901 Set_Analyzed (Cleft_Lo, False);
902 Set_Analyzed (Cright_Lo, False);
904 Condition :=
905 Make_Op_Le (Loc,
906 Left_Opnd => Cleft_Lo,
907 Right_Opnd => Cright_Lo);
908 end if;
910 if Needs_Finalization (Component_Type (L_Type))
911 and then Base_Type (L_Type) = Base_Type (R_Type)
912 and then Ndim = 1
913 and then not No_Ctrl_Actions (N)
914 then
916 -- Call TSS procedure for array assignment, passing the
917 -- explicit bounds of right and left hand sides.
919 declare
920 Proc : constant Entity_Id :=
921 TSS (Base_Type (L_Type), TSS_Slice_Assign);
922 Actuals : List_Id;
924 begin
925 Apply_Dereference (Larray);
926 Apply_Dereference (Rarray);
927 Actuals := New_List (
928 Duplicate_Subexpr (Larray, Name_Req => True),
929 Duplicate_Subexpr (Rarray, Name_Req => True),
930 Duplicate_Subexpr (Left_Lo, Name_Req => True),
931 Duplicate_Subexpr (Left_Hi, Name_Req => True),
932 Duplicate_Subexpr (Right_Lo, Name_Req => True),
933 Duplicate_Subexpr (Right_Hi, Name_Req => True));
935 Append_To (Actuals,
936 Make_Op_Not (Loc,
937 Right_Opnd => Condition));
939 Rewrite (N,
940 Make_Procedure_Call_Statement (Loc,
941 Name => New_Reference_To (Proc, Loc),
942 Parameter_Associations => Actuals));
943 end;
945 else
946 Rewrite (N,
947 Make_Implicit_If_Statement (N,
948 Condition => Condition,
950 Then_Statements => New_List (
951 Expand_Assign_Array_Loop
952 (N, Larray, Rarray, L_Type, R_Type, Ndim,
953 Rev => False)),
955 Else_Statements => New_List (
956 Expand_Assign_Array_Loop
957 (N, Larray, Rarray, L_Type, R_Type, Ndim,
958 Rev => True))));
959 end if;
960 end if;
962 Analyze (N, Suppress => All_Checks);
963 end;
965 exception
966 when RE_Not_Available =>
967 return;
968 end Expand_Assign_Array;
970 ------------------------------
971 -- Expand_Assign_Array_Loop --
972 ------------------------------
974 -- The following is an example of the loop generated for the case of a
975 -- two-dimensional array:
977 -- declare
978 -- R2b : Tm1X1 := 1;
979 -- begin
980 -- for L1b in 1 .. 100 loop
981 -- declare
982 -- R4b : Tm1X2 := 1;
983 -- begin
984 -- for L3b in 1 .. 100 loop
985 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
986 -- R4b := Tm1X2'succ(R4b);
987 -- end loop;
988 -- end;
989 -- R2b := Tm1X1'succ(R2b);
990 -- end loop;
991 -- end;
993 -- Here Rev is False, and Tm1Xn are the subscript types for the right hand
994 -- side. The declarations of R2b and R4b are inserted before the original
995 -- assignment statement.
997 function Expand_Assign_Array_Loop
998 (N : Node_Id;
999 Larray : Entity_Id;
1000 Rarray : Entity_Id;
1001 L_Type : Entity_Id;
1002 R_Type : Entity_Id;
1003 Ndim : Pos;
1004 Rev : Boolean) return Node_Id
1006 Loc : constant Source_Ptr := Sloc (N);
1008 Lnn : array (1 .. Ndim) of Entity_Id;
1009 Rnn : array (1 .. Ndim) of Entity_Id;
1010 -- Entities used as subscripts on left and right sides
1012 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1013 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1014 -- Left and right index types
1016 Assign : Node_Id;
1018 F_Or_L : Name_Id;
1019 S_Or_P : Name_Id;
1021 function Build_Step (J : Nat) return Node_Id;
1022 -- The increment step for the index of the right-hand side is written
1023 -- as an attribute reference (Succ or Pred). This function returns
1024 -- the corresponding node, which is placed at the end of the loop body.
1026 ----------------
1027 -- Build_Step --
1028 ----------------
1030 function Build_Step (J : Nat) return Node_Id is
1031 Step : Node_Id;
1032 Lim : Name_Id;
1034 begin
1035 if Rev then
1036 Lim := Name_First;
1037 else
1038 Lim := Name_Last;
1039 end if;
1041 Step :=
1042 Make_Assignment_Statement (Loc,
1043 Name => New_Occurrence_Of (Rnn (J), Loc),
1044 Expression =>
1045 Make_Attribute_Reference (Loc,
1046 Prefix =>
1047 New_Occurrence_Of (R_Index_Type (J), Loc),
1048 Attribute_Name => S_Or_P,
1049 Expressions => New_List (
1050 New_Occurrence_Of (Rnn (J), Loc))));
1052 -- Note that on the last iteration of the loop, the index is increased
1053 -- (or decreased) past the corresponding bound. This is consistent with
1054 -- the C semantics of the back-end, where such an off-by-one value on a
1055 -- dead index variable is OK. However, in CodePeer mode this leads to
1056 -- spurious warnings, and thus we place a guard around the attribute
1057 -- reference. For obvious reasons we only do this for CodePeer.
1059 if CodePeer_Mode then
1060 Step :=
1061 Make_If_Statement (Loc,
1062 Condition =>
1063 Make_Op_Ne (Loc,
1064 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1065 Right_Opnd =>
1066 Make_Attribute_Reference (Loc,
1067 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1068 Attribute_Name => Lim)),
1069 Then_Statements => New_List (Step));
1070 end if;
1072 return Step;
1073 end Build_Step;
1075 -- Start of processing for Expand_Assign_Array_Loop
1077 begin
1078 if Rev then
1079 F_Or_L := Name_Last;
1080 S_Or_P := Name_Pred;
1081 else
1082 F_Or_L := Name_First;
1083 S_Or_P := Name_Succ;
1084 end if;
1086 -- Setup index types and subscript entities
1088 declare
1089 L_Index : Node_Id;
1090 R_Index : Node_Id;
1092 begin
1093 L_Index := First_Index (L_Type);
1094 R_Index := First_Index (R_Type);
1096 for J in 1 .. Ndim loop
1097 Lnn (J) := Make_Temporary (Loc, 'L');
1098 Rnn (J) := Make_Temporary (Loc, 'R');
1100 L_Index_Type (J) := Etype (L_Index);
1101 R_Index_Type (J) := Etype (R_Index);
1103 Next_Index (L_Index);
1104 Next_Index (R_Index);
1105 end loop;
1106 end;
1108 -- Now construct the assignment statement
1110 declare
1111 ExprL : constant List_Id := New_List;
1112 ExprR : constant List_Id := New_List;
1114 begin
1115 for J in 1 .. Ndim loop
1116 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1117 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1118 end loop;
1120 Assign :=
1121 Make_Assignment_Statement (Loc,
1122 Name =>
1123 Make_Indexed_Component (Loc,
1124 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1125 Expressions => ExprL),
1126 Expression =>
1127 Make_Indexed_Component (Loc,
1128 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1129 Expressions => ExprR));
1131 -- We set assignment OK, since there are some cases, e.g. in object
1132 -- declarations, where we are actually assigning into a constant.
1133 -- If there really is an illegality, it was caught long before now,
1134 -- and was flagged when the original assignment was analyzed.
1136 Set_Assignment_OK (Name (Assign));
1138 -- Propagate the No_Ctrl_Actions flag to individual assignments
1140 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1141 end;
1143 -- Now construct the loop from the inside out, with the last subscript
1144 -- varying most rapidly. Note that Assign is first the raw assignment
1145 -- statement, and then subsequently the loop that wraps it up.
1147 for J in reverse 1 .. Ndim loop
1148 Assign :=
1149 Make_Block_Statement (Loc,
1150 Declarations => New_List (
1151 Make_Object_Declaration (Loc,
1152 Defining_Identifier => Rnn (J),
1153 Object_Definition =>
1154 New_Occurrence_Of (R_Index_Type (J), Loc),
1155 Expression =>
1156 Make_Attribute_Reference (Loc,
1157 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1158 Attribute_Name => F_Or_L))),
1160 Handled_Statement_Sequence =>
1161 Make_Handled_Sequence_Of_Statements (Loc,
1162 Statements => New_List (
1163 Make_Implicit_Loop_Statement (N,
1164 Iteration_Scheme =>
1165 Make_Iteration_Scheme (Loc,
1166 Loop_Parameter_Specification =>
1167 Make_Loop_Parameter_Specification (Loc,
1168 Defining_Identifier => Lnn (J),
1169 Reverse_Present => Rev,
1170 Discrete_Subtype_Definition =>
1171 New_Reference_To (L_Index_Type (J), Loc))),
1173 Statements => New_List (Assign, Build_Step (J))))));
1174 end loop;
1176 return Assign;
1177 end Expand_Assign_Array_Loop;
1179 --------------------------
1180 -- Expand_Assign_Record --
1181 --------------------------
1183 procedure Expand_Assign_Record (N : Node_Id) is
1184 Lhs : constant Node_Id := Name (N);
1185 Rhs : Node_Id := Expression (N);
1186 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1188 begin
1189 -- If change of representation, then extract the real right hand side
1190 -- from the type conversion, and proceed with component-wise assignment,
1191 -- since the two types are not the same as far as the back end is
1192 -- concerned.
1194 if Change_Of_Representation (N) then
1195 Rhs := Expression (Rhs);
1197 -- If this may be a case of a large bit aligned component, then proceed
1198 -- with component-wise assignment, to avoid possible clobbering of other
1199 -- components sharing bits in the first or last byte of the component to
1200 -- be assigned.
1202 elsif Possible_Bit_Aligned_Component (Lhs)
1204 Possible_Bit_Aligned_Component (Rhs)
1205 then
1206 null;
1208 -- If we have a tagged type that has a complete record representation
1209 -- clause, we must do we must do component-wise assignments, since child
1210 -- types may have used gaps for their components, and we might be
1211 -- dealing with a view conversion.
1213 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1214 null;
1216 -- If neither condition met, then nothing special to do, the back end
1217 -- can handle assignment of the entire component as a single entity.
1219 else
1220 return;
1221 end if;
1223 -- At this stage we know that we must do a component wise assignment
1225 declare
1226 Loc : constant Source_Ptr := Sloc (N);
1227 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1228 Decl : constant Node_Id := Declaration_Node (R_Typ);
1229 RDef : Node_Id;
1230 F : Entity_Id;
1232 function Find_Component
1233 (Typ : Entity_Id;
1234 Comp : Entity_Id) return Entity_Id;
1235 -- Find the component with the given name in the underlying record
1236 -- declaration for Typ. We need to use the actual entity because the
1237 -- type may be private and resolution by identifier alone would fail.
1239 function Make_Component_List_Assign
1240 (CL : Node_Id;
1241 U_U : Boolean := False) return List_Id;
1242 -- Returns a sequence of statements to assign the components that
1243 -- are referenced in the given component list. The flag U_U is
1244 -- used to force the usage of the inferred value of the variant
1245 -- part expression as the switch for the generated case statement.
1247 function Make_Field_Assign
1248 (C : Entity_Id;
1249 U_U : Boolean := False) return Node_Id;
1250 -- Given C, the entity for a discriminant or component, build an
1251 -- assignment for the corresponding field values. The flag U_U
1252 -- signals the presence of an Unchecked_Union and forces the usage
1253 -- of the inferred discriminant value of C as the right hand side
1254 -- of the assignment.
1256 function Make_Field_Assigns (CI : List_Id) return List_Id;
1257 -- Given CI, a component items list, construct series of statements
1258 -- for fieldwise assignment of the corresponding components.
1260 --------------------
1261 -- Find_Component --
1262 --------------------
1264 function Find_Component
1265 (Typ : Entity_Id;
1266 Comp : Entity_Id) return Entity_Id
1268 Utyp : constant Entity_Id := Underlying_Type (Typ);
1269 C : Entity_Id;
1271 begin
1272 C := First_Entity (Utyp);
1273 while Present (C) loop
1274 if Chars (C) = Chars (Comp) then
1275 return C;
1276 end if;
1278 Next_Entity (C);
1279 end loop;
1281 raise Program_Error;
1282 end Find_Component;
1284 --------------------------------
1285 -- Make_Component_List_Assign --
1286 --------------------------------
1288 function Make_Component_List_Assign
1289 (CL : Node_Id;
1290 U_U : Boolean := False) return List_Id
1292 CI : constant List_Id := Component_Items (CL);
1293 VP : constant Node_Id := Variant_Part (CL);
1295 Alts : List_Id;
1296 DC : Node_Id;
1297 DCH : List_Id;
1298 Expr : Node_Id;
1299 Result : List_Id;
1300 V : Node_Id;
1302 begin
1303 Result := Make_Field_Assigns (CI);
1305 if Present (VP) then
1306 V := First_Non_Pragma (Variants (VP));
1307 Alts := New_List;
1308 while Present (V) loop
1309 DCH := New_List;
1310 DC := First (Discrete_Choices (V));
1311 while Present (DC) loop
1312 Append_To (DCH, New_Copy_Tree (DC));
1313 Next (DC);
1314 end loop;
1316 Append_To (Alts,
1317 Make_Case_Statement_Alternative (Loc,
1318 Discrete_Choices => DCH,
1319 Statements =>
1320 Make_Component_List_Assign (Component_List (V))));
1321 Next_Non_Pragma (V);
1322 end loop;
1324 -- If we have an Unchecked_Union, use the value of the inferred
1325 -- discriminant of the variant part expression as the switch
1326 -- for the case statement. The case statement may later be
1327 -- folded.
1329 if U_U then
1330 Expr :=
1331 New_Copy (Get_Discriminant_Value (
1332 Entity (Name (VP)),
1333 Etype (Rhs),
1334 Discriminant_Constraint (Etype (Rhs))));
1335 else
1336 Expr :=
1337 Make_Selected_Component (Loc,
1338 Prefix => Duplicate_Subexpr (Rhs),
1339 Selector_Name =>
1340 Make_Identifier (Loc, Chars (Name (VP))));
1341 end if;
1343 Append_To (Result,
1344 Make_Case_Statement (Loc,
1345 Expression => Expr,
1346 Alternatives => Alts));
1347 end if;
1349 return Result;
1350 end Make_Component_List_Assign;
1352 -----------------------
1353 -- Make_Field_Assign --
1354 -----------------------
1356 function Make_Field_Assign
1357 (C : Entity_Id;
1358 U_U : Boolean := False) return Node_Id
1360 A : Node_Id;
1361 Expr : Node_Id;
1363 begin
1364 -- In the case of an Unchecked_Union, use the discriminant
1365 -- constraint value as on the right hand side of the assignment.
1367 if U_U then
1368 Expr :=
1369 New_Copy (Get_Discriminant_Value (C,
1370 Etype (Rhs),
1371 Discriminant_Constraint (Etype (Rhs))));
1372 else
1373 Expr :=
1374 Make_Selected_Component (Loc,
1375 Prefix => Duplicate_Subexpr (Rhs),
1376 Selector_Name => New_Occurrence_Of (C, Loc));
1377 end if;
1379 A :=
1380 Make_Assignment_Statement (Loc,
1381 Name =>
1382 Make_Selected_Component (Loc,
1383 Prefix => Duplicate_Subexpr (Lhs),
1384 Selector_Name =>
1385 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1386 Expression => Expr);
1388 -- Set Assignment_OK, so discriminants can be assigned
1390 Set_Assignment_OK (Name (A), True);
1392 if Componentwise_Assignment (N)
1393 and then Nkind (Name (A)) = N_Selected_Component
1394 and then Chars (Selector_Name (Name (A))) = Name_uParent
1395 then
1396 Set_Componentwise_Assignment (A);
1397 end if;
1399 return A;
1400 end Make_Field_Assign;
1402 ------------------------
1403 -- Make_Field_Assigns --
1404 ------------------------
1406 function Make_Field_Assigns (CI : List_Id) return List_Id is
1407 Item : Node_Id;
1408 Result : List_Id;
1410 begin
1411 Item := First (CI);
1412 Result := New_List;
1414 while Present (Item) loop
1416 -- Look for components, but exclude _tag field assignment if
1417 -- the special Componentwise_Assignment flag is set.
1419 if Nkind (Item) = N_Component_Declaration
1420 and then not (Is_Tag (Defining_Identifier (Item))
1421 and then Componentwise_Assignment (N))
1422 then
1423 Append_To
1424 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1425 end if;
1427 Next (Item);
1428 end loop;
1430 return Result;
1431 end Make_Field_Assigns;
1433 -- Start of processing for Expand_Assign_Record
1435 begin
1436 -- Note that we use the base types for this processing. This results
1437 -- in some extra work in the constrained case, but the change of
1438 -- representation case is so unusual that it is not worth the effort.
1440 -- First copy the discriminants. This is done unconditionally. It
1441 -- is required in the unconstrained left side case, and also in the
1442 -- case where this assignment was constructed during the expansion
1443 -- of a type conversion (since initialization of discriminants is
1444 -- suppressed in this case). It is unnecessary but harmless in
1445 -- other cases.
1447 if Has_Discriminants (L_Typ) then
1448 F := First_Discriminant (R_Typ);
1449 while Present (F) loop
1451 -- If we are expanding the initialization of a derived record
1452 -- that constrains or renames discriminants of the parent, we
1453 -- must use the corresponding discriminant in the parent.
1455 declare
1456 CF : Entity_Id;
1458 begin
1459 if Inside_Init_Proc
1460 and then Present (Corresponding_Discriminant (F))
1461 then
1462 CF := Corresponding_Discriminant (F);
1463 else
1464 CF := F;
1465 end if;
1467 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1469 -- Within an initialization procedure this is the
1470 -- assignment to an unchecked union component, in which
1471 -- case there is no discriminant to initialize.
1473 if Inside_Init_Proc then
1474 null;
1476 else
1477 -- The assignment is part of a conversion from a
1478 -- derived unchecked union type with an inferable
1479 -- discriminant, to a parent type.
1481 Insert_Action (N, Make_Field_Assign (CF, True));
1482 end if;
1484 else
1485 Insert_Action (N, Make_Field_Assign (CF));
1486 end if;
1488 Next_Discriminant (F);
1489 end;
1490 end loop;
1491 end if;
1493 -- We know the underlying type is a record, but its current view
1494 -- may be private. We must retrieve the usable record declaration.
1496 if Nkind_In (Decl, N_Private_Type_Declaration,
1497 N_Private_Extension_Declaration)
1498 and then Present (Full_View (R_Typ))
1499 then
1500 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1501 else
1502 RDef := Type_Definition (Decl);
1503 end if;
1505 if Nkind (RDef) = N_Derived_Type_Definition then
1506 RDef := Record_Extension_Part (RDef);
1507 end if;
1509 if Nkind (RDef) = N_Record_Definition
1510 and then Present (Component_List (RDef))
1511 then
1512 if Is_Unchecked_Union (R_Typ) then
1513 Insert_Actions (N,
1514 Make_Component_List_Assign (Component_List (RDef), True));
1515 else
1516 Insert_Actions
1517 (N, Make_Component_List_Assign (Component_List (RDef)));
1518 end if;
1520 Rewrite (N, Make_Null_Statement (Loc));
1521 end if;
1522 end;
1523 end Expand_Assign_Record;
1525 -----------------------------------
1526 -- Expand_N_Assignment_Statement --
1527 -----------------------------------
1529 -- This procedure implements various cases where an assignment statement
1530 -- cannot just be passed on to the back end in untransformed state.
1532 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1533 Loc : constant Source_Ptr := Sloc (N);
1534 Crep : constant Boolean := Change_Of_Representation (N);
1535 Lhs : constant Node_Id := Name (N);
1536 Rhs : constant Node_Id := Expression (N);
1537 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1538 Exp : Node_Id;
1540 begin
1541 -- Special case to check right away, if the Componentwise_Assignment
1542 -- flag is set, this is a reanalysis from the expansion of the primitive
1543 -- assignment procedure for a tagged type, and all we need to do is to
1544 -- expand to assignment of components, because otherwise, we would get
1545 -- infinite recursion (since this looks like a tagged assignment which
1546 -- would normally try to *call* the primitive assignment procedure).
1548 if Componentwise_Assignment (N) then
1549 Expand_Assign_Record (N);
1550 return;
1551 end if;
1553 -- Defend against invalid subscripts on left side if we are in standard
1554 -- validity checking mode. No need to do this if we are checking all
1555 -- subscripts.
1557 -- Note that we do this right away, because there are some early return
1558 -- paths in this procedure, and this is required on all paths.
1560 if Validity_Checks_On
1561 and then Validity_Check_Default
1562 and then not Validity_Check_Subscripts
1563 then
1564 Check_Valid_Lvalue_Subscripts (Lhs);
1565 end if;
1567 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1569 -- Rewrite an assignment to X'Priority into a run-time call
1571 -- For example: X'Priority := New_Prio_Expr;
1572 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1574 -- Note that although X'Priority is notionally an object, it is quite
1575 -- deliberately not defined as an aliased object in the RM. This means
1576 -- that it works fine to rewrite it as a call, without having to worry
1577 -- about complications that would other arise from X'Priority'Access,
1578 -- which is illegal, because of the lack of aliasing.
1580 if Ada_Version >= Ada_2005 then
1581 declare
1582 Call : Node_Id;
1583 Conctyp : Entity_Id;
1584 Ent : Entity_Id;
1585 Subprg : Entity_Id;
1586 RT_Subprg_Name : Node_Id;
1588 begin
1589 -- Handle chains of renamings
1591 Ent := Name (N);
1592 while Nkind (Ent) in N_Has_Entity
1593 and then Present (Entity (Ent))
1594 and then Present (Renamed_Object (Entity (Ent)))
1595 loop
1596 Ent := Renamed_Object (Entity (Ent));
1597 end loop;
1599 -- The attribute Priority applied to protected objects has been
1600 -- previously expanded into a call to the Get_Ceiling run-time
1601 -- subprogram.
1603 if Nkind (Ent) = N_Function_Call
1604 and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1605 or else
1606 Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1607 then
1608 -- Look for the enclosing concurrent type
1610 Conctyp := Current_Scope;
1611 while not Is_Concurrent_Type (Conctyp) loop
1612 Conctyp := Scope (Conctyp);
1613 end loop;
1615 pragma Assert (Is_Protected_Type (Conctyp));
1617 -- Generate the first actual of the call
1619 Subprg := Current_Scope;
1620 while not Present (Protected_Body_Subprogram (Subprg)) loop
1621 Subprg := Scope (Subprg);
1622 end loop;
1624 -- Select the appropriate run-time call
1626 if Number_Entries (Conctyp) = 0 then
1627 RT_Subprg_Name :=
1628 New_Reference_To (RTE (RE_Set_Ceiling), Loc);
1629 else
1630 RT_Subprg_Name :=
1631 New_Reference_To (RTE (RO_PE_Set_Ceiling), Loc);
1632 end if;
1634 Call :=
1635 Make_Procedure_Call_Statement (Loc,
1636 Name => RT_Subprg_Name,
1637 Parameter_Associations => New_List (
1638 New_Copy_Tree (First (Parameter_Associations (Ent))),
1639 Relocate_Node (Expression (N))));
1641 Rewrite (N, Call);
1642 Analyze (N);
1643 return;
1644 end if;
1645 end;
1646 end if;
1648 -- Deal with assignment checks unless suppressed
1650 if not Suppress_Assignment_Checks (N) then
1652 -- First deal with generation of range check if required
1654 if Do_Range_Check (Rhs) then
1655 Set_Do_Range_Check (Rhs, False);
1656 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1657 end if;
1659 -- Then generate predicate check if required
1661 Apply_Predicate_Check (Rhs, Typ);
1662 end if;
1664 -- Check for a special case where a high level transformation is
1665 -- required. If we have either of:
1667 -- P.field := rhs;
1668 -- P (sub) := rhs;
1670 -- where P is a reference to a bit packed array, then we have to unwind
1671 -- the assignment. The exact meaning of being a reference to a bit
1672 -- packed array is as follows:
1674 -- An indexed component whose prefix is a bit packed array is a
1675 -- reference to a bit packed array.
1677 -- An indexed component or selected component whose prefix is a
1678 -- reference to a bit packed array is itself a reference ot a
1679 -- bit packed array.
1681 -- The required transformation is
1683 -- Tnn : prefix_type := P;
1684 -- Tnn.field := rhs;
1685 -- P := Tnn;
1687 -- or
1689 -- Tnn : prefix_type := P;
1690 -- Tnn (subscr) := rhs;
1691 -- P := Tnn;
1693 -- Since P is going to be evaluated more than once, any subscripts
1694 -- in P must have their evaluation forced.
1696 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1697 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1698 then
1699 declare
1700 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1701 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1702 Tnn : constant Entity_Id :=
1703 Make_Temporary (Loc, 'T', BPAR_Expr);
1705 begin
1706 -- Insert the post assignment first, because we want to copy the
1707 -- BPAR_Expr tree before it gets analyzed in the context of the
1708 -- pre assignment. Note that we do not analyze the post assignment
1709 -- yet (we cannot till we have completed the analysis of the pre
1710 -- assignment). As usual, the analysis of this post assignment
1711 -- will happen on its own when we "run into" it after finishing
1712 -- the current assignment.
1714 Insert_After (N,
1715 Make_Assignment_Statement (Loc,
1716 Name => New_Copy_Tree (BPAR_Expr),
1717 Expression => New_Occurrence_Of (Tnn, Loc)));
1719 -- At this stage BPAR_Expr is a reference to a bit packed array
1720 -- where the reference was not expanded in the original tree,
1721 -- since it was on the left side of an assignment. But in the
1722 -- pre-assignment statement (the object definition), BPAR_Expr
1723 -- will end up on the right hand side, and must be reexpanded. To
1724 -- achieve this, we reset the analyzed flag of all selected and
1725 -- indexed components down to the actual indexed component for
1726 -- the packed array.
1728 Exp := BPAR_Expr;
1729 loop
1730 Set_Analyzed (Exp, False);
1732 if Nkind_In
1733 (Exp, N_Selected_Component, N_Indexed_Component)
1734 then
1735 Exp := Prefix (Exp);
1736 else
1737 exit;
1738 end if;
1739 end loop;
1741 -- Now we can insert and analyze the pre-assignment
1743 -- If the right-hand side requires a transient scope, it has
1744 -- already been placed on the stack. However, the declaration is
1745 -- inserted in the tree outside of this scope, and must reflect
1746 -- the proper scope for its variable. This awkward bit is forced
1747 -- by the stricter scope discipline imposed by GCC 2.97.
1749 declare
1750 Uses_Transient_Scope : constant Boolean :=
1751 Scope_Is_Transient
1752 and then N = Node_To_Be_Wrapped;
1754 begin
1755 if Uses_Transient_Scope then
1756 Push_Scope (Scope (Current_Scope));
1757 end if;
1759 Insert_Before_And_Analyze (N,
1760 Make_Object_Declaration (Loc,
1761 Defining_Identifier => Tnn,
1762 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
1763 Expression => BPAR_Expr));
1765 if Uses_Transient_Scope then
1766 Pop_Scope;
1767 end if;
1768 end;
1770 -- Now fix up the original assignment and continue processing
1772 Rewrite (Prefix (Lhs),
1773 New_Occurrence_Of (Tnn, Loc));
1775 -- We do not need to reanalyze that assignment, and we do not need
1776 -- to worry about references to the temporary, but we do need to
1777 -- make sure that the temporary is not marked as a true constant
1778 -- since we now have a generated assignment to it!
1780 Set_Is_True_Constant (Tnn, False);
1781 end;
1782 end if;
1784 -- When we have the appropriate type of aggregate in the expression (it
1785 -- has been determined during analysis of the aggregate by setting the
1786 -- delay flag), let's perform in place assignment and thus avoid
1787 -- creating a temporary.
1789 if Is_Delayed_Aggregate (Rhs) then
1790 Convert_Aggr_In_Assignment (N);
1791 Rewrite (N, Make_Null_Statement (Loc));
1792 Analyze (N);
1793 return;
1794 end if;
1796 -- Apply discriminant check if required. If Lhs is an access type to a
1797 -- designated type with discriminants, we must always check. If the
1798 -- type has unknown discriminants, more elaborate processing below.
1800 if Has_Discriminants (Etype (Lhs))
1801 and then not Has_Unknown_Discriminants (Etype (Lhs))
1802 then
1803 -- Skip discriminant check if change of representation. Will be
1804 -- done when the change of representation is expanded out.
1806 if not Crep then
1807 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1808 end if;
1810 -- If the type is private without discriminants, and the full type
1811 -- has discriminants (necessarily with defaults) a check may still be
1812 -- necessary if the Lhs is aliased. The private discriminants must be
1813 -- visible to build the discriminant constraints.
1815 -- Only an explicit dereference that comes from source indicates
1816 -- aliasing. Access to formals of protected operations and entries
1817 -- create dereferences but are not semantic aliasings.
1819 elsif Is_Private_Type (Etype (Lhs))
1820 and then Has_Discriminants (Typ)
1821 and then Nkind (Lhs) = N_Explicit_Dereference
1822 and then Comes_From_Source (Lhs)
1823 then
1824 declare
1825 Lt : constant Entity_Id := Etype (Lhs);
1826 Ubt : Entity_Id := Base_Type (Typ);
1828 begin
1829 -- In the case of an expander-generated record subtype whose base
1830 -- type still appears private, Typ will have been set to that
1831 -- private type rather than the underlying record type (because
1832 -- Underlying type will have returned the record subtype), so it's
1833 -- necessary to apply Underlying_Type again to the base type to
1834 -- get the record type we need for the discriminant check. Such
1835 -- subtypes can be created for assignments in certain cases, such
1836 -- as within an instantiation passed this kind of private type.
1837 -- It would be good to avoid this special test, but making changes
1838 -- to prevent this odd form of record subtype seems difficult. ???
1840 if Is_Private_Type (Ubt) then
1841 Ubt := Underlying_Type (Ubt);
1842 end if;
1844 Set_Etype (Lhs, Ubt);
1845 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
1846 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
1847 Set_Etype (Lhs, Lt);
1848 end;
1850 -- If the Lhs has a private type with unknown discriminants, it
1851 -- may have a full view with discriminants, but those are nameable
1852 -- only in the underlying type, so convert the Rhs to it before
1853 -- potential checking.
1855 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1856 and then Has_Discriminants (Typ)
1857 then
1858 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1859 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1861 -- In the access type case, we need the same discriminant check, and
1862 -- also range checks if we have an access to constrained array.
1864 elsif Is_Access_Type (Etype (Lhs))
1865 and then Is_Constrained (Designated_Type (Etype (Lhs)))
1866 then
1867 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1869 -- Skip discriminant check if change of representation. Will be
1870 -- done when the change of representation is expanded out.
1872 if not Crep then
1873 Apply_Discriminant_Check (Rhs, Etype (Lhs));
1874 end if;
1876 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
1877 Apply_Range_Check (Rhs, Etype (Lhs));
1879 if Is_Constrained (Etype (Lhs)) then
1880 Apply_Length_Check (Rhs, Etype (Lhs));
1881 end if;
1883 if Nkind (Rhs) = N_Allocator then
1884 declare
1885 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
1886 C_Es : Check_Result;
1888 begin
1889 C_Es :=
1890 Get_Range_Checks
1891 (Lhs,
1892 Target_Typ,
1893 Etype (Designated_Type (Etype (Lhs))));
1895 Insert_Range_Checks
1896 (C_Es,
1898 Target_Typ,
1899 Sloc (Lhs),
1900 Lhs);
1901 end;
1902 end if;
1903 end if;
1905 -- Apply range check for access type case
1907 elsif Is_Access_Type (Etype (Lhs))
1908 and then Nkind (Rhs) = N_Allocator
1909 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
1910 then
1911 Analyze_And_Resolve (Expression (Rhs));
1912 Apply_Range_Check
1913 (Expression (Rhs), Designated_Type (Etype (Lhs)));
1914 end if;
1916 -- Ada 2005 (AI-231): Generate the run-time check
1918 if Is_Access_Type (Typ)
1919 and then Can_Never_Be_Null (Etype (Lhs))
1920 and then not Can_Never_Be_Null (Etype (Rhs))
1921 then
1922 Apply_Constraint_Check (Rhs, Etype (Lhs));
1923 end if;
1925 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
1926 -- stand-alone obj of an anonymous access type.
1928 if Is_Access_Type (Typ)
1929 and then Is_Entity_Name (Lhs)
1930 and then Present (Effective_Extra_Accessibility (Entity (Lhs))) then
1931 declare
1932 function Lhs_Entity return Entity_Id;
1933 -- Look through renames to find the underlying entity.
1934 -- For assignment to a rename, we don't care about the
1935 -- Enclosing_Dynamic_Scope of the rename declaration.
1937 ----------------
1938 -- Lhs_Entity --
1939 ----------------
1941 function Lhs_Entity return Entity_Id is
1942 Result : Entity_Id := Entity (Lhs);
1944 begin
1945 while Present (Renamed_Object (Result)) loop
1947 -- Renamed_Object must return an Entity_Name here
1948 -- because of preceding "Present (E_E_A (...))" test.
1950 Result := Entity (Renamed_Object (Result));
1951 end loop;
1953 return Result;
1954 end Lhs_Entity;
1956 -- Local Declarations
1958 Access_Check : constant Node_Id :=
1959 Make_Raise_Program_Error (Loc,
1960 Condition =>
1961 Make_Op_Gt (Loc,
1962 Left_Opnd =>
1963 Dynamic_Accessibility_Level (Rhs),
1964 Right_Opnd =>
1965 Make_Integer_Literal (Loc,
1966 Intval =>
1967 Scope_Depth
1968 (Enclosing_Dynamic_Scope
1969 (Lhs_Entity)))),
1970 Reason => PE_Accessibility_Check_Failed);
1972 Access_Level_Update : constant Node_Id :=
1973 Make_Assignment_Statement (Loc,
1974 Name =>
1975 New_Occurrence_Of
1976 (Effective_Extra_Accessibility
1977 (Entity (Lhs)), Loc),
1978 Expression =>
1979 Dynamic_Accessibility_Level (Rhs));
1981 begin
1982 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
1983 Insert_Action (N, Access_Check);
1984 end if;
1986 Insert_Action (N, Access_Level_Update);
1987 end;
1988 end if;
1990 -- Case of assignment to a bit packed array element. If there is a
1991 -- change of representation this must be expanded into components,
1992 -- otherwise this is a bit-field assignment.
1994 if Nkind (Lhs) = N_Indexed_Component
1995 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
1996 then
1997 -- Normal case, no change of representation
1999 if not Crep then
2000 Expand_Bit_Packed_Element_Set (N);
2001 return;
2003 -- Change of representation case
2005 else
2006 -- Generate the following, to force component-by-component
2007 -- assignments in an efficient way. Otherwise each component
2008 -- will require a temporary and two bit-field manipulations.
2010 -- T1 : Elmt_Type;
2011 -- T1 := RhS;
2012 -- Lhs := T1;
2014 declare
2015 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2016 Stats : List_Id;
2018 begin
2019 Stats :=
2020 New_List (
2021 Make_Object_Declaration (Loc,
2022 Defining_Identifier => Tnn,
2023 Object_Definition =>
2024 New_Occurrence_Of (Etype (Lhs), Loc)),
2025 Make_Assignment_Statement (Loc,
2026 Name => New_Occurrence_Of (Tnn, Loc),
2027 Expression => Relocate_Node (Rhs)),
2028 Make_Assignment_Statement (Loc,
2029 Name => Relocate_Node (Lhs),
2030 Expression => New_Occurrence_Of (Tnn, Loc)));
2032 Insert_Actions (N, Stats);
2033 Rewrite (N, Make_Null_Statement (Loc));
2034 Analyze (N);
2035 end;
2036 end if;
2038 -- Build-in-place function call case. Note that we're not yet doing
2039 -- build-in-place for user-written assignment statements (the assignment
2040 -- here came from an aggregate.)
2042 elsif Ada_Version >= Ada_2005
2043 and then Is_Build_In_Place_Function_Call (Rhs)
2044 then
2045 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2047 elsif Is_Tagged_Type (Typ) and then Is_Value_Type (Etype (Lhs)) then
2049 -- Nothing to do for valuetypes
2050 -- ??? Set_Scope_Is_Transient (False);
2052 return;
2054 elsif Is_Tagged_Type (Typ)
2055 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2056 then
2057 Tagged_Case : declare
2058 L : List_Id := No_List;
2059 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2061 begin
2062 -- In the controlled case, we ensure that function calls are
2063 -- evaluated before finalizing the target. In all cases, it makes
2064 -- the expansion easier if the side-effects are removed first.
2066 Remove_Side_Effects (Lhs);
2067 Remove_Side_Effects (Rhs);
2069 -- Avoid recursion in the mechanism
2071 Set_Analyzed (N);
2073 -- If dispatching assignment, we need to dispatch to _assign
2075 if Is_Class_Wide_Type (Typ)
2077 -- If the type is tagged, we may as well use the predefined
2078 -- primitive assignment. This avoids inlining a lot of code
2079 -- and in the class-wide case, the assignment is replaced
2080 -- by a dispatching call to _assign. It is suppressed in the
2081 -- case of assignments created by the expander that correspond
2082 -- to initializations, where we do want to copy the tag
2083 -- (Expand_Ctrl_Actions flag is set True in this case). It is
2084 -- also suppressed if restriction No_Dispatching_Calls is in
2085 -- force because in that case predefined primitives are not
2086 -- generated.
2088 or else (Is_Tagged_Type (Typ)
2089 and then not Is_Value_Type (Etype (Lhs))
2090 and then Chars (Current_Scope) /= Name_uAssign
2091 and then Expand_Ctrl_Actions
2092 and then
2093 not Restriction_Active (No_Dispatching_Calls))
2094 then
2095 if Is_Limited_Type (Typ) then
2097 -- This can happen in an instance when the formal is an
2098 -- extension of a limited interface, and the actual is
2099 -- limited. This is an error according to AI05-0087, but
2100 -- is not caught at the point of instantiation in earlier
2101 -- versions.
2103 -- This is wrong, error messages cannot be issued during
2104 -- expansion, since they would be missed in -gnatc mode ???
2106 Error_Msg_N ("assignment not available on limited type", N);
2107 return;
2108 end if;
2110 -- Fetch the primitive op _assign and proper type to call it.
2111 -- Because of possible conflicts between private and full view,
2112 -- fetch the proper type directly from the operation profile.
2114 declare
2115 Op : constant Entity_Id :=
2116 Find_Prim_Op (Typ, Name_uAssign);
2117 F_Typ : Entity_Id := Etype (First_Formal (Op));
2119 begin
2120 -- If the assignment is dispatching, make sure to use the
2121 -- proper type.
2123 if Is_Class_Wide_Type (Typ) then
2124 F_Typ := Class_Wide_Type (F_Typ);
2125 end if;
2127 L := New_List;
2129 -- In case of assignment to a class-wide tagged type, before
2130 -- the assignment we generate run-time check to ensure that
2131 -- the tags of source and target match.
2133 if not Tag_Checks_Suppressed (Typ)
2134 and then Is_Class_Wide_Type (Typ)
2135 and then Is_Tagged_Type (Typ)
2136 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2137 then
2138 Append_To (L,
2139 Make_Raise_Constraint_Error (Loc,
2140 Condition =>
2141 Make_Op_Ne (Loc,
2142 Left_Opnd =>
2143 Make_Selected_Component (Loc,
2144 Prefix => Duplicate_Subexpr (Lhs),
2145 Selector_Name =>
2146 Make_Identifier (Loc, Name_uTag)),
2147 Right_Opnd =>
2148 Make_Selected_Component (Loc,
2149 Prefix => Duplicate_Subexpr (Rhs),
2150 Selector_Name =>
2151 Make_Identifier (Loc, Name_uTag))),
2152 Reason => CE_Tag_Check_Failed));
2153 end if;
2155 declare
2156 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2157 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2159 begin
2160 -- In order to dispatch the call to _assign the type of
2161 -- the actuals must match. Add conversion (if required).
2163 if Etype (Lhs) /= F_Typ then
2164 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2165 end if;
2167 if Etype (Rhs) /= F_Typ then
2168 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2169 end if;
2171 Append_To (L,
2172 Make_Procedure_Call_Statement (Loc,
2173 Name => New_Reference_To (Op, Loc),
2174 Parameter_Associations => New_List (
2175 Node1 => Left_N,
2176 Node2 => Right_N)));
2177 end;
2178 end;
2180 else
2181 L := Make_Tag_Ctrl_Assignment (N);
2183 -- We can't afford to have destructive Finalization Actions in
2184 -- the Self assignment case, so if the target and the source
2185 -- are not obviously different, code is generated to avoid the
2186 -- self assignment case:
2188 -- if lhs'address /= rhs'address then
2189 -- <code for controlled and/or tagged assignment>
2190 -- end if;
2192 -- Skip this if Restriction (No_Finalization) is active
2194 if not Statically_Different (Lhs, Rhs)
2195 and then Expand_Ctrl_Actions
2196 and then not Restriction_Active (No_Finalization)
2197 then
2198 L := New_List (
2199 Make_Implicit_If_Statement (N,
2200 Condition =>
2201 Make_Op_Ne (Loc,
2202 Left_Opnd =>
2203 Make_Attribute_Reference (Loc,
2204 Prefix => Duplicate_Subexpr (Lhs),
2205 Attribute_Name => Name_Address),
2207 Right_Opnd =>
2208 Make_Attribute_Reference (Loc,
2209 Prefix => Duplicate_Subexpr (Rhs),
2210 Attribute_Name => Name_Address)),
2212 Then_Statements => L));
2213 end if;
2215 -- We need to set up an exception handler for implementing
2216 -- 7.6.1(18). The remaining adjustments are tackled by the
2217 -- implementation of adjust for record_controllers (see
2218 -- s-finimp.adb).
2220 -- This is skipped if we have no finalization
2222 if Expand_Ctrl_Actions
2223 and then not Restriction_Active (No_Finalization)
2224 then
2225 L := New_List (
2226 Make_Block_Statement (Loc,
2227 Handled_Statement_Sequence =>
2228 Make_Handled_Sequence_Of_Statements (Loc,
2229 Statements => L,
2230 Exception_Handlers => New_List (
2231 Make_Handler_For_Ctrl_Operation (Loc)))));
2232 end if;
2233 end if;
2235 Rewrite (N,
2236 Make_Block_Statement (Loc,
2237 Handled_Statement_Sequence =>
2238 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2240 -- If no restrictions on aborts, protect the whole assignment
2241 -- for controlled objects as per 9.8(11).
2243 if Needs_Finalization (Typ)
2244 and then Expand_Ctrl_Actions
2245 and then Abort_Allowed
2246 then
2247 declare
2248 Blk : constant Entity_Id :=
2249 New_Internal_Entity
2250 (E_Block, Current_Scope, Sloc (N), 'B');
2252 begin
2253 Set_Scope (Blk, Current_Scope);
2254 Set_Etype (Blk, Standard_Void_Type);
2255 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2257 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2258 Set_At_End_Proc (Handled_Statement_Sequence (N),
2259 New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
2260 Expand_At_End_Handler
2261 (Handled_Statement_Sequence (N), Blk);
2262 end;
2263 end if;
2265 -- N has been rewritten to a block statement for which it is
2266 -- known by construction that no checks are necessary: analyze
2267 -- it with all checks suppressed.
2269 Analyze (N, Suppress => All_Checks);
2270 return;
2271 end Tagged_Case;
2273 -- Array types
2275 elsif Is_Array_Type (Typ) then
2276 declare
2277 Actual_Rhs : Node_Id := Rhs;
2279 begin
2280 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2281 N_Qualified_Expression)
2282 loop
2283 Actual_Rhs := Expression (Actual_Rhs);
2284 end loop;
2286 Expand_Assign_Array (N, Actual_Rhs);
2287 return;
2288 end;
2290 -- Record types
2292 elsif Is_Record_Type (Typ) then
2293 Expand_Assign_Record (N);
2294 return;
2296 -- Scalar types. This is where we perform the processing related to the
2297 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2298 -- scalar values.
2300 elsif Is_Scalar_Type (Typ) then
2302 -- Case where right side is known valid
2304 if Expr_Known_Valid (Rhs) then
2306 -- Here the right side is valid, so it is fine. The case to deal
2307 -- with is when the left side is a local variable reference whose
2308 -- value is not currently known to be valid. If this is the case,
2309 -- and the assignment appears in an unconditional context, then
2310 -- we can mark the left side as now being valid if one of these
2311 -- conditions holds:
2313 -- The expression of the right side has Do_Range_Check set so
2314 -- that we know a range check will be performed. Note that it
2315 -- can be the case that a range check is omitted because we
2316 -- make the assumption that we can assume validity for operands
2317 -- appearing in the right side in determining whether a range
2318 -- check is required
2320 -- The subtype of the right side matches the subtype of the
2321 -- left side. In this case, even though we have not checked
2322 -- the range of the right side, we know it is in range of its
2323 -- subtype if the expression is valid.
2325 if Is_Local_Variable_Reference (Lhs)
2326 and then not Is_Known_Valid (Entity (Lhs))
2327 and then In_Unconditional_Context (N)
2328 then
2329 if Do_Range_Check (Rhs)
2330 or else Etype (Lhs) = Etype (Rhs)
2331 then
2332 Set_Is_Known_Valid (Entity (Lhs), True);
2333 end if;
2334 end if;
2336 -- Case where right side may be invalid in the sense of the RM
2337 -- reference above. The RM does not require that we check for the
2338 -- validity on an assignment, but it does require that the assignment
2339 -- of an invalid value not cause erroneous behavior.
2341 -- The general approach in GNAT is to use the Is_Known_Valid flag
2342 -- to avoid the need for validity checking on assignments. However
2343 -- in some cases, we have to do validity checking in order to make
2344 -- sure that the setting of this flag is correct.
2346 else
2347 -- Validate right side if we are validating copies
2349 if Validity_Checks_On
2350 and then Validity_Check_Copies
2351 then
2352 -- Skip this if left hand side is an array or record component
2353 -- and elementary component validity checks are suppressed.
2355 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2356 and then not Validity_Check_Components
2357 then
2358 null;
2359 else
2360 Ensure_Valid (Rhs);
2361 end if;
2363 -- We can propagate this to the left side where appropriate
2365 if Is_Local_Variable_Reference (Lhs)
2366 and then not Is_Known_Valid (Entity (Lhs))
2367 and then In_Unconditional_Context (N)
2368 then
2369 Set_Is_Known_Valid (Entity (Lhs), True);
2370 end if;
2372 -- Otherwise check to see what should be done
2374 -- If left side is a local variable, then we just set its flag to
2375 -- indicate that its value may no longer be valid, since we are
2376 -- copying a potentially invalid value.
2378 elsif Is_Local_Variable_Reference (Lhs) then
2379 Set_Is_Known_Valid (Entity (Lhs), False);
2381 -- Check for case of a nonlocal variable on the left side which
2382 -- is currently known to be valid. In this case, we simply ensure
2383 -- that the right side is valid. We only play the game of copying
2384 -- validity status for local variables, since we are doing this
2385 -- statically, not by tracing the full flow graph.
2387 elsif Is_Entity_Name (Lhs)
2388 and then Is_Known_Valid (Entity (Lhs))
2389 then
2390 -- Note: If Validity_Checking mode is set to none, we ignore
2391 -- the Ensure_Valid call so don't worry about that case here.
2393 Ensure_Valid (Rhs);
2395 -- In all other cases, we can safely copy an invalid value without
2396 -- worrying about the status of the left side. Since it is not a
2397 -- variable reference it will not be considered
2398 -- as being known to be valid in any case.
2400 else
2401 null;
2402 end if;
2403 end if;
2404 end if;
2406 exception
2407 when RE_Not_Available =>
2408 return;
2409 end Expand_N_Assignment_Statement;
2411 ------------------------------
2412 -- Expand_N_Block_Statement --
2413 ------------------------------
2415 -- Encode entity names defined in block statement
2417 procedure Expand_N_Block_Statement (N : Node_Id) is
2418 begin
2419 Qualify_Entity_Names (N);
2420 end Expand_N_Block_Statement;
2422 -----------------------------
2423 -- Expand_N_Case_Statement --
2424 -----------------------------
2426 procedure Expand_N_Case_Statement (N : Node_Id) is
2427 Loc : constant Source_Ptr := Sloc (N);
2428 Expr : constant Node_Id := Expression (N);
2429 Alt : Node_Id;
2430 Len : Nat;
2431 Cond : Node_Id;
2432 Choice : Node_Id;
2433 Chlist : List_Id;
2435 begin
2436 -- Check for the situation where we know at compile time which branch
2437 -- will be taken
2439 if Compile_Time_Known_Value (Expr) then
2440 Alt := Find_Static_Alternative (N);
2442 Process_Statements_For_Controlled_Objects (Alt);
2444 -- Move statements from this alternative after the case statement.
2445 -- They are already analyzed, so will be skipped by the analyzer.
2447 Insert_List_After (N, Statements (Alt));
2449 -- That leaves the case statement as a shell. So now we can kill all
2450 -- other alternatives in the case statement.
2452 Kill_Dead_Code (Expression (N));
2454 declare
2455 Dead_Alt : Node_Id;
2457 begin
2458 -- Loop through case alternatives, skipping pragmas, and skipping
2459 -- the one alternative that we select (and therefore retain).
2461 Dead_Alt := First (Alternatives (N));
2462 while Present (Dead_Alt) loop
2463 if Dead_Alt /= Alt
2464 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2465 then
2466 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2467 end if;
2469 Next (Dead_Alt);
2470 end loop;
2471 end;
2473 Rewrite (N, Make_Null_Statement (Loc));
2474 return;
2475 end if;
2477 -- Here if the choice is not determined at compile time
2479 declare
2480 Last_Alt : constant Node_Id := Last (Alternatives (N));
2482 Others_Present : Boolean;
2483 Others_Node : Node_Id;
2485 Then_Stms : List_Id;
2486 Else_Stms : List_Id;
2488 begin
2489 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2490 Others_Present := True;
2491 Others_Node := Last_Alt;
2492 else
2493 Others_Present := False;
2494 end if;
2496 -- First step is to worry about possible invalid argument. The RM
2497 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2498 -- outside the base range), then Constraint_Error must be raised.
2500 -- Case of validity check required (validity checks are on, the
2501 -- expression is not known to be valid, and the case statement
2502 -- comes from source -- no need to validity check internally
2503 -- generated case statements).
2505 if Validity_Check_Default then
2506 Ensure_Valid (Expr);
2507 end if;
2509 -- If there is only a single alternative, just replace it with the
2510 -- sequence of statements since obviously that is what is going to
2511 -- be executed in all cases.
2513 Len := List_Length (Alternatives (N));
2515 if Len = 1 then
2517 -- We still need to evaluate the expression if it has any side
2518 -- effects.
2520 Remove_Side_Effects (Expression (N));
2522 Alt := First (Alternatives (N));
2524 Process_Statements_For_Controlled_Objects (Alt);
2525 Insert_List_After (N, Statements (Alt));
2527 -- That leaves the case statement as a shell. The alternative that
2528 -- will be executed is reset to a null list. So now we can kill
2529 -- the entire case statement.
2531 Kill_Dead_Code (Expression (N));
2532 Rewrite (N, Make_Null_Statement (Loc));
2533 return;
2535 -- An optimization. If there are only two alternatives, and only
2536 -- a single choice, then rewrite the whole case statement as an
2537 -- if statement, since this can result in subsequent optimizations.
2538 -- This helps not only with case statements in the source of a
2539 -- simple form, but also with generated code (discriminant check
2540 -- functions in particular)
2542 elsif Len = 2 then
2543 Chlist := Discrete_Choices (First (Alternatives (N)));
2545 if List_Length (Chlist) = 1 then
2546 Choice := First (Chlist);
2548 Then_Stms := Statements (First (Alternatives (N)));
2549 Else_Stms := Statements (Last (Alternatives (N)));
2551 -- For TRUE, generate "expression", not expression = true
2553 if Nkind (Choice) = N_Identifier
2554 and then Entity (Choice) = Standard_True
2555 then
2556 Cond := Expression (N);
2558 -- For FALSE, generate "expression" and switch then/else
2560 elsif Nkind (Choice) = N_Identifier
2561 and then Entity (Choice) = Standard_False
2562 then
2563 Cond := Expression (N);
2564 Else_Stms := Statements (First (Alternatives (N)));
2565 Then_Stms := Statements (Last (Alternatives (N)));
2567 -- For a range, generate "expression in range"
2569 elsif Nkind (Choice) = N_Range
2570 or else (Nkind (Choice) = N_Attribute_Reference
2571 and then Attribute_Name (Choice) = Name_Range)
2572 or else (Is_Entity_Name (Choice)
2573 and then Is_Type (Entity (Choice)))
2574 or else Nkind (Choice) = N_Subtype_Indication
2575 then
2576 Cond :=
2577 Make_In (Loc,
2578 Left_Opnd => Expression (N),
2579 Right_Opnd => Relocate_Node (Choice));
2581 -- For any other subexpression "expression = value"
2583 else
2584 Cond :=
2585 Make_Op_Eq (Loc,
2586 Left_Opnd => Expression (N),
2587 Right_Opnd => Relocate_Node (Choice));
2588 end if;
2590 -- Now rewrite the case as an IF
2592 Rewrite (N,
2593 Make_If_Statement (Loc,
2594 Condition => Cond,
2595 Then_Statements => Then_Stms,
2596 Else_Statements => Else_Stms));
2597 Analyze (N);
2598 return;
2599 end if;
2600 end if;
2602 -- If the last alternative is not an Others choice, replace it with
2603 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2604 -- the modified case statement, since it's only effect would be to
2605 -- compute the contents of the Others_Discrete_Choices which is not
2606 -- needed by the back end anyway.
2608 -- The reason we do this is that the back end always needs some
2609 -- default for a switch, so if we have not supplied one in the
2610 -- processing above for validity checking, then we need to supply
2611 -- one here.
2613 if not Others_Present then
2614 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2615 Set_Others_Discrete_Choices
2616 (Others_Node, Discrete_Choices (Last_Alt));
2617 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2618 end if;
2620 Alt := First (Alternatives (N));
2621 while Present (Alt)
2622 and then Nkind (Alt) = N_Case_Statement_Alternative
2623 loop
2624 Process_Statements_For_Controlled_Objects (Alt);
2625 Next (Alt);
2626 end loop;
2627 end;
2628 end Expand_N_Case_Statement;
2630 -----------------------------
2631 -- Expand_N_Exit_Statement --
2632 -----------------------------
2634 -- The only processing required is to deal with a possible C/Fortran
2635 -- boolean value used as the condition for the exit statement.
2637 procedure Expand_N_Exit_Statement (N : Node_Id) is
2638 begin
2639 Adjust_Condition (Condition (N));
2640 end Expand_N_Exit_Statement;
2642 -----------------------------
2643 -- Expand_N_Goto_Statement --
2644 -----------------------------
2646 -- Add poll before goto if polling active
2648 procedure Expand_N_Goto_Statement (N : Node_Id) is
2649 begin
2650 Generate_Poll_Call (N);
2651 end Expand_N_Goto_Statement;
2653 ---------------------------
2654 -- Expand_N_If_Statement --
2655 ---------------------------
2657 -- First we deal with the case of C and Fortran convention boolean values,
2658 -- with zero/non-zero semantics.
2660 -- Second, we deal with the obvious rewriting for the cases where the
2661 -- condition of the IF is known at compile time to be True or False.
2663 -- Third, we remove elsif parts which have non-empty Condition_Actions and
2664 -- rewrite as independent if statements. For example:
2666 -- if x then xs
2667 -- elsif y then ys
2668 -- ...
2669 -- end if;
2671 -- becomes
2673 -- if x then xs
2674 -- else
2675 -- <<condition actions of y>>
2676 -- if y then ys
2677 -- ...
2678 -- end if;
2679 -- end if;
2681 -- This rewriting is needed if at least one elsif part has a non-empty
2682 -- Condition_Actions list. We also do the same processing if there is a
2683 -- constant condition in an elsif part (in conjunction with the first
2684 -- processing step mentioned above, for the recursive call made to deal
2685 -- with the created inner if, this deals with properly optimizing the
2686 -- cases of constant elsif conditions).
2688 procedure Expand_N_If_Statement (N : Node_Id) is
2689 Loc : constant Source_Ptr := Sloc (N);
2690 Hed : Node_Id;
2691 E : Node_Id;
2692 New_If : Node_Id;
2694 Warn_If_Deleted : constant Boolean :=
2695 Warn_On_Deleted_Code and then Comes_From_Source (N);
2696 -- Indicates whether we want warnings when we delete branches of the
2697 -- if statement based on constant condition analysis. We never want
2698 -- these warnings for expander generated code.
2700 begin
2701 Process_Statements_For_Controlled_Objects (N);
2703 Adjust_Condition (Condition (N));
2705 -- The following loop deals with constant conditions for the IF. We
2706 -- need a loop because as we eliminate False conditions, we grab the
2707 -- first elsif condition and use it as the primary condition.
2709 while Compile_Time_Known_Value (Condition (N)) loop
2711 -- If condition is True, we can simply rewrite the if statement now
2712 -- by replacing it by the series of then statements.
2714 if Is_True (Expr_Value (Condition (N))) then
2716 -- All the else parts can be killed
2718 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
2719 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
2721 Hed := Remove_Head (Then_Statements (N));
2722 Insert_List_After (N, Then_Statements (N));
2723 Rewrite (N, Hed);
2724 return;
2726 -- If condition is False, then we can delete the condition and
2727 -- the Then statements
2729 else
2730 -- We do not delete the condition if constant condition warnings
2731 -- are enabled, since otherwise we end up deleting the desired
2732 -- warning. Of course the backend will get rid of this True/False
2733 -- test anyway, so nothing is lost here.
2735 if not Constant_Condition_Warnings then
2736 Kill_Dead_Code (Condition (N));
2737 end if;
2739 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
2741 -- If there are no elsif statements, then we simply replace the
2742 -- entire if statement by the sequence of else statements.
2744 if No (Elsif_Parts (N)) then
2745 if No (Else_Statements (N))
2746 or else Is_Empty_List (Else_Statements (N))
2747 then
2748 Rewrite (N,
2749 Make_Null_Statement (Sloc (N)));
2750 else
2751 Hed := Remove_Head (Else_Statements (N));
2752 Insert_List_After (N, Else_Statements (N));
2753 Rewrite (N, Hed);
2754 end if;
2756 return;
2758 -- If there are elsif statements, the first of them becomes the
2759 -- if/then section of the rebuilt if statement This is the case
2760 -- where we loop to reprocess this copied condition.
2762 else
2763 Hed := Remove_Head (Elsif_Parts (N));
2764 Insert_Actions (N, Condition_Actions (Hed));
2765 Set_Condition (N, Condition (Hed));
2766 Set_Then_Statements (N, Then_Statements (Hed));
2768 -- Hed might have been captured as the condition determining
2769 -- the current value for an entity. Now it is detached from
2770 -- the tree, so a Current_Value pointer in the condition might
2771 -- need to be updated.
2773 Set_Current_Value_Condition (N);
2775 if Is_Empty_List (Elsif_Parts (N)) then
2776 Set_Elsif_Parts (N, No_List);
2777 end if;
2778 end if;
2779 end if;
2780 end loop;
2782 -- Loop through elsif parts, dealing with constant conditions and
2783 -- possible condition actions that are present.
2785 if Present (Elsif_Parts (N)) then
2786 E := First (Elsif_Parts (N));
2787 while Present (E) loop
2788 Process_Statements_For_Controlled_Objects (E);
2790 Adjust_Condition (Condition (E));
2792 -- If there are condition actions, then rewrite the if statement
2793 -- as indicated above. We also do the same rewrite for a True or
2794 -- False condition. The further processing of this constant
2795 -- condition is then done by the recursive call to expand the
2796 -- newly created if statement
2798 if Present (Condition_Actions (E))
2799 or else Compile_Time_Known_Value (Condition (E))
2800 then
2801 -- Note this is not an implicit if statement, since it is part
2802 -- of an explicit if statement in the source (or of an implicit
2803 -- if statement that has already been tested).
2805 New_If :=
2806 Make_If_Statement (Sloc (E),
2807 Condition => Condition (E),
2808 Then_Statements => Then_Statements (E),
2809 Elsif_Parts => No_List,
2810 Else_Statements => Else_Statements (N));
2812 -- Elsif parts for new if come from remaining elsif's of parent
2814 while Present (Next (E)) loop
2815 if No (Elsif_Parts (New_If)) then
2816 Set_Elsif_Parts (New_If, New_List);
2817 end if;
2819 Append (Remove_Next (E), Elsif_Parts (New_If));
2820 end loop;
2822 Set_Else_Statements (N, New_List (New_If));
2824 if Present (Condition_Actions (E)) then
2825 Insert_List_Before (New_If, Condition_Actions (E));
2826 end if;
2828 Remove (E);
2830 if Is_Empty_List (Elsif_Parts (N)) then
2831 Set_Elsif_Parts (N, No_List);
2832 end if;
2834 Analyze (New_If);
2835 return;
2837 -- No special processing for that elsif part, move to next
2839 else
2840 Next (E);
2841 end if;
2842 end loop;
2843 end if;
2845 -- Some more optimizations applicable if we still have an IF statement
2847 if Nkind (N) /= N_If_Statement then
2848 return;
2849 end if;
2851 -- Another optimization, special cases that can be simplified
2853 -- if expression then
2854 -- return true;
2855 -- else
2856 -- return false;
2857 -- end if;
2859 -- can be changed to:
2861 -- return expression;
2863 -- and
2865 -- if expression then
2866 -- return false;
2867 -- else
2868 -- return true;
2869 -- end if;
2871 -- can be changed to:
2873 -- return not (expression);
2875 -- Only do these optimizations if we are at least at -O1 level and
2876 -- do not do them if control flow optimizations are suppressed.
2878 if Optimization_Level > 0
2879 and then not Opt.Suppress_Control_Flow_Optimizations
2880 then
2881 if Nkind (N) = N_If_Statement
2882 and then No (Elsif_Parts (N))
2883 and then Present (Else_Statements (N))
2884 and then List_Length (Then_Statements (N)) = 1
2885 and then List_Length (Else_Statements (N)) = 1
2886 then
2887 declare
2888 Then_Stm : constant Node_Id := First (Then_Statements (N));
2889 Else_Stm : constant Node_Id := First (Else_Statements (N));
2891 begin
2892 if Nkind (Then_Stm) = N_Simple_Return_Statement
2893 and then
2894 Nkind (Else_Stm) = N_Simple_Return_Statement
2895 then
2896 declare
2897 Then_Expr : constant Node_Id := Expression (Then_Stm);
2898 Else_Expr : constant Node_Id := Expression (Else_Stm);
2900 begin
2901 if Nkind (Then_Expr) = N_Identifier
2902 and then
2903 Nkind (Else_Expr) = N_Identifier
2904 then
2905 if Entity (Then_Expr) = Standard_True
2906 and then Entity (Else_Expr) = Standard_False
2907 then
2908 Rewrite (N,
2909 Make_Simple_Return_Statement (Loc,
2910 Expression => Relocate_Node (Condition (N))));
2911 Analyze (N);
2912 return;
2914 elsif Entity (Then_Expr) = Standard_False
2915 and then Entity (Else_Expr) = Standard_True
2916 then
2917 Rewrite (N,
2918 Make_Simple_Return_Statement (Loc,
2919 Expression =>
2920 Make_Op_Not (Loc,
2921 Right_Opnd =>
2922 Relocate_Node (Condition (N)))));
2923 Analyze (N);
2924 return;
2925 end if;
2926 end if;
2927 end;
2928 end if;
2929 end;
2930 end if;
2931 end if;
2932 end Expand_N_If_Statement;
2934 --------------------------
2935 -- Expand_Iterator_Loop --
2936 --------------------------
2938 procedure Expand_Iterator_Loop (N : Node_Id) is
2939 Isc : constant Node_Id := Iteration_Scheme (N);
2940 I_Spec : constant Node_Id := Iterator_Specification (Isc);
2941 Id : constant Entity_Id := Defining_Identifier (I_Spec);
2942 Loc : constant Source_Ptr := Sloc (N);
2944 Container : constant Node_Id := Name (I_Spec);
2945 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
2946 Cursor : Entity_Id;
2947 Iterator : Entity_Id;
2948 New_Loop : Node_Id;
2949 Stats : List_Id := Statements (N);
2951 begin
2952 -- Processing for arrays
2954 if Is_Array_Type (Container_Typ) then
2955 Expand_Iterator_Loop_Over_Array (N);
2956 return;
2957 end if;
2959 -- Processing for containers
2961 -- For an "of" iterator the name is a container expression, which
2962 -- is transformed into a call to the default iterator.
2964 -- For an iterator of the form "in" the name is a function call
2965 -- that delivers an iterator type.
2967 -- In both cases, analysis of the iterator has introduced an object
2968 -- declaration to capture the domain, so that Container is an entity.
2970 -- The for loop is expanded into a while loop which uses a container
2971 -- specific cursor to desgnate each element.
2973 -- Iter : Iterator_Type := Container.Iterate;
2974 -- Cursor : Cursor_type := First (Iter);
2975 -- while Has_Element (Iter) loop
2976 -- declare
2977 -- -- The block is added when Element_Type is controlled
2979 -- Obj : Pack.Element_Type := Element (Cursor);
2980 -- -- for the "of" loop form
2981 -- begin
2982 -- <original loop statements>
2983 -- end;
2985 -- Cursor := Iter.Next (Cursor);
2986 -- end loop;
2988 -- If "reverse" is present, then the initialization of the cursor
2989 -- uses Last and the step becomes Prev. Pack is the name of the
2990 -- scope where the container package is instantiated.
2992 declare
2993 Element_Type : constant Entity_Id := Etype (Id);
2994 Iter_Type : Entity_Id;
2995 Pack : Entity_Id;
2996 Decl : Node_Id;
2997 Name_Init : Name_Id;
2998 Name_Step : Name_Id;
3000 begin
3001 -- The type of the iterator is the return type of the Iterate
3002 -- function used. For the "of" form this is the default iterator
3003 -- for the type, otherwise it is the type of the explicit
3004 -- function used in the iterator specification. The most common
3005 -- case will be an Iterate function in the container package.
3007 -- The primitive operations of the container type may not be
3008 -- use-visible, so we introduce the name of the enclosing package
3009 -- in the declarations below. The Iterator type is declared in a
3010 -- an instance within the container package itself.
3012 -- If the container type is a derived type, the cursor type is
3013 -- found in the package of the parent type.
3015 if Is_Derived_Type (Container_Typ) then
3016 Pack := Scope (Root_Type (Container_Typ));
3017 else
3018 Pack := Scope (Container_Typ);
3019 end if;
3021 Iter_Type := Etype (Name (I_Spec));
3023 -- The "of" case uses an internally generated cursor whose type
3024 -- is found in the container package. The domain of iteration
3025 -- is expanded into a call to the default Iterator function, but
3026 -- this expansion does not take place in quantified expressions
3027 -- that are analyzed with expansion disabled, and in that case the
3028 -- type of the iterator must be obtained from the aspect.
3030 if Of_Present (I_Spec) then
3031 declare
3032 Default_Iter : constant Entity_Id :=
3033 Entity
3034 (Find_Value_Of_Aspect
3035 (Etype (Container),
3036 Aspect_Default_Iterator));
3038 Container_Arg : Node_Id;
3039 Ent : Entity_Id;
3041 begin
3042 Cursor := Make_Temporary (Loc, 'I');
3044 -- For an container element iterator, the iterator type
3045 -- is obtained from the corresponding aspect, whose return
3046 -- type is descended from the corresponding interface type
3047 -- in some instance of Ada.Iterator_Interfaces. The actuals
3048 -- of that instantiation are Cursor and Has_Element.
3050 Iter_Type := Etype (Default_Iter);
3052 -- The iterator type, which is a class_wide type, may itself
3053 -- be derived locally, so the desired instantiation is the
3054 -- scope of the root type of the iterator type.
3056 Pack := Scope (Root_Type (Etype (Iter_Type)));
3058 -- Rewrite domain of iteration as a call to the default
3059 -- iterator for the container type. If the container is
3060 -- a derived type and the aspect is inherited, convert
3061 -- container to parent type. The Cursor type is also
3062 -- inherited from the scope of the parent.
3064 if Base_Type (Etype (Container)) =
3065 Base_Type (Etype (First_Formal (Default_Iter)))
3066 then
3067 Container_Arg := New_Copy_Tree (Container);
3069 else
3070 Container_Arg :=
3071 Make_Type_Conversion (Loc,
3072 Subtype_Mark =>
3073 New_Occurrence_Of
3074 (Etype (First_Formal (Default_Iter)), Loc),
3075 Expression => New_Copy_Tree (Container));
3076 end if;
3078 Rewrite (Name (I_Spec),
3079 Make_Function_Call (Loc,
3080 Name => New_Occurrence_Of (Default_Iter, Loc),
3081 Parameter_Associations =>
3082 New_List (Container_Arg)));
3083 Analyze_And_Resolve (Name (I_Spec));
3085 -- Find cursor type in proper iterator package, which is an
3086 -- instantiation of Iterator_Interfaces.
3088 Ent := First_Entity (Pack);
3089 while Present (Ent) loop
3090 if Chars (Ent) = Name_Cursor then
3091 Set_Etype (Cursor, Etype (Ent));
3092 exit;
3093 end if;
3094 Next_Entity (Ent);
3095 end loop;
3097 -- Generate:
3098 -- Id : Element_Type renames Container (Cursor);
3099 -- This assumes that the container type has an indexing
3100 -- operation with Cursor. The check that this operation
3101 -- exists is performed in Check_Container_Indexing.
3103 Decl :=
3104 Make_Object_Renaming_Declaration (Loc,
3105 Defining_Identifier => Id,
3106 Subtype_Mark =>
3107 New_Reference_To (Element_Type, Loc),
3108 Name =>
3109 Make_Indexed_Component (Loc,
3110 Prefix => Relocate_Node (Container_Arg),
3111 Expressions =>
3112 New_List (New_Occurrence_Of (Cursor, Loc))));
3114 -- The defining identifier in the iterator is user-visible
3115 -- and must be visible in the debugger.
3117 Set_Debug_Info_Needed (Id);
3119 -- If the container holds controlled objects, wrap the loop
3120 -- statements and element renaming declaration with a block.
3121 -- This ensures that the result of Element (Cusor) is
3122 -- cleaned up after each iteration of the loop.
3124 if Needs_Finalization (Element_Type) then
3126 -- Generate:
3127 -- declare
3128 -- Id : Element_Type := Element (curosr);
3129 -- begin
3130 -- <original loop statements>
3131 -- end;
3133 Stats := New_List (
3134 Make_Block_Statement (Loc,
3135 Declarations => New_List (Decl),
3136 Handled_Statement_Sequence =>
3137 Make_Handled_Sequence_Of_Statements (Loc,
3138 Statements => Stats)));
3140 -- Elements do not need finalization
3142 else
3143 Prepend_To (Stats, Decl);
3144 end if;
3145 end;
3147 -- X in Iterate (S) : type of iterator is type of explicitly
3148 -- given Iterate function, and the loop variable is the cursor.
3149 -- It will be assigned in the loop and must be a variable.
3151 else
3152 Cursor := Id;
3153 Set_Ekind (Cursor, E_Variable);
3154 end if;
3156 Iterator := Make_Temporary (Loc, 'I');
3158 -- Determine the advancement and initialization steps for the
3159 -- cursor.
3161 -- Analysis of the expanded loop will verify that the container
3162 -- has a reverse iterator.
3164 if Reverse_Present (I_Spec) then
3165 Name_Init := Name_Last;
3166 Name_Step := Name_Previous;
3168 else
3169 Name_Init := Name_First;
3170 Name_Step := Name_Next;
3171 end if;
3173 -- For both iterator forms, add a call to the step operation to
3174 -- advance the cursor. Generate:
3176 -- Cursor := Iterator.Next (Cursor);
3178 -- or else
3180 -- Cursor := Next (Cursor);
3182 declare
3183 Rhs : Node_Id;
3185 begin
3186 Rhs :=
3187 Make_Function_Call (Loc,
3188 Name =>
3189 Make_Selected_Component (Loc,
3190 Prefix => New_Reference_To (Iterator, Loc),
3191 Selector_Name => Make_Identifier (Loc, Name_Step)),
3192 Parameter_Associations => New_List (
3193 New_Reference_To (Cursor, Loc)));
3195 Append_To (Stats,
3196 Make_Assignment_Statement (Loc,
3197 Name => New_Occurrence_Of (Cursor, Loc),
3198 Expression => Rhs));
3199 end;
3201 -- Generate:
3202 -- while Iterator.Has_Element loop
3203 -- <Stats>
3204 -- end loop;
3206 -- Has_Element is the second actual in the iterator package
3208 New_Loop :=
3209 Make_Loop_Statement (Loc,
3210 Iteration_Scheme =>
3211 Make_Iteration_Scheme (Loc,
3212 Condition =>
3213 Make_Function_Call (Loc,
3214 Name =>
3215 New_Occurrence_Of (
3216 Next_Entity (First_Entity (Pack)), Loc),
3217 Parameter_Associations =>
3218 New_List (New_Reference_To (Cursor, Loc)))),
3220 Statements => Stats,
3221 End_Label => Empty);
3223 -- If present, preserve identifier of loop, which can be used in
3224 -- an exit statement in the body.
3226 if Present (Identifier (N)) then
3227 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
3228 end if;
3230 -- Create the declarations for Iterator and cursor and insert them
3231 -- before the source loop. Given that the domain of iteration is
3232 -- already an entity, the iterator is just a renaming of that
3233 -- entity. Possible optimization ???
3234 -- Generate:
3236 -- I : Iterator_Type renames Container;
3237 -- C : Cursor_Type := Container.[First | Last];
3239 Insert_Action (N,
3240 Make_Object_Renaming_Declaration (Loc,
3241 Defining_Identifier => Iterator,
3242 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
3243 Name => Relocate_Node (Name (I_Spec))));
3245 -- Create declaration for cursor
3247 declare
3248 Decl : Node_Id;
3250 begin
3251 Decl :=
3252 Make_Object_Declaration (Loc,
3253 Defining_Identifier => Cursor,
3254 Object_Definition =>
3255 New_Occurrence_Of (Etype (Cursor), Loc),
3256 Expression =>
3257 Make_Selected_Component (Loc,
3258 Prefix => New_Reference_To (Iterator, Loc),
3259 Selector_Name =>
3260 Make_Identifier (Loc, Name_Init)));
3262 -- The cursor is only modified in expanded code, so it appears
3263 -- as unassigned to the warning machinery. We must suppress
3264 -- this spurious warning explicitly.
3266 Set_Warnings_Off (Cursor);
3267 Set_Assignment_OK (Decl);
3269 Insert_Action (N, Decl);
3270 end;
3272 -- If the range of iteration is given by a function call that
3273 -- returns a container, the finalization actions have been saved
3274 -- in the Condition_Actions of the iterator. Insert them now at
3275 -- the head of the loop.
3277 if Present (Condition_Actions (Isc)) then
3278 Insert_List_Before (N, Condition_Actions (Isc));
3279 end if;
3280 end;
3282 Rewrite (N, New_Loop);
3283 Analyze (N);
3284 end Expand_Iterator_Loop;
3286 -------------------------------------
3287 -- Expand_Iterator_Loop_Over_Array --
3288 -------------------------------------
3290 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3291 Isc : constant Node_Id := Iteration_Scheme (N);
3292 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3293 Array_Node : constant Node_Id := Name (I_Spec);
3294 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3295 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3296 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3297 Loc : constant Source_Ptr := Sloc (N);
3298 Stats : constant List_Id := Statements (N);
3299 Core_Loop : Node_Id;
3300 Ind_Comp : Node_Id;
3301 Iterator : Entity_Id;
3303 -- Start of processing for Expand_Iterator_Loop_Over_Array
3305 begin
3306 -- for Element of Array loop
3308 -- This case requires an internally generated cursor to iterate over
3309 -- the array.
3311 if Of_Present (I_Spec) then
3312 Iterator := Make_Temporary (Loc, 'C');
3314 -- Generate:
3315 -- Element : Component_Type renames Array (Iterator);
3317 Ind_Comp :=
3318 Make_Indexed_Component (Loc,
3319 Prefix => Relocate_Node (Array_Node),
3320 Expressions => New_List (New_Reference_To (Iterator, Loc)));
3322 Prepend_To (Stats,
3323 Make_Object_Renaming_Declaration (Loc,
3324 Defining_Identifier => Id,
3325 Subtype_Mark =>
3326 New_Reference_To (Component_Type (Array_Typ), Loc),
3327 Name => Ind_Comp));
3329 -- Mark the loop variable as needing debug info, so that expansion
3330 -- of the renaming will result in Materialize_Entity getting set via
3331 -- Debug_Renaming_Declaration. (This setting is needed here because
3332 -- the setting in Freeze_Entity comes after the expansion, which is
3333 -- too late. ???)
3335 Set_Debug_Info_Needed (Id);
3337 -- for Index in Array loop
3339 -- This case utilizes the already given iterator name
3341 else
3342 Iterator := Id;
3343 end if;
3345 -- Generate:
3347 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3348 -- Element : Component_Type renames Array (Iterator);
3349 -- <original loop statements>
3350 -- end loop;
3352 Core_Loop :=
3353 Make_Loop_Statement (Loc,
3354 Iteration_Scheme =>
3355 Make_Iteration_Scheme (Loc,
3356 Loop_Parameter_Specification =>
3357 Make_Loop_Parameter_Specification (Loc,
3358 Defining_Identifier => Iterator,
3359 Discrete_Subtype_Definition =>
3360 Make_Attribute_Reference (Loc,
3361 Prefix => Relocate_Node (Array_Node),
3362 Attribute_Name => Name_Range,
3363 Expressions => New_List (
3364 Make_Integer_Literal (Loc, Array_Dim))),
3365 Reverse_Present => Reverse_Present (I_Spec))),
3366 Statements => Stats,
3367 End_Label => Empty);
3369 -- Processing for multidimensional array
3371 if Array_Dim > 1 then
3372 for Dim in 1 .. Array_Dim - 1 loop
3373 Iterator := Make_Temporary (Loc, 'C');
3375 -- Generate the dimension loops starting from the innermost one
3377 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3378 -- <core loop>
3379 -- end loop;
3381 Core_Loop :=
3382 Make_Loop_Statement (Loc,
3383 Iteration_Scheme =>
3384 Make_Iteration_Scheme (Loc,
3385 Loop_Parameter_Specification =>
3386 Make_Loop_Parameter_Specification (Loc,
3387 Defining_Identifier => Iterator,
3388 Discrete_Subtype_Definition =>
3389 Make_Attribute_Reference (Loc,
3390 Prefix => Relocate_Node (Array_Node),
3391 Attribute_Name => Name_Range,
3392 Expressions => New_List (
3393 Make_Integer_Literal (Loc, Array_Dim - Dim))),
3394 Reverse_Present => Reverse_Present (I_Spec))),
3395 Statements => New_List (Core_Loop),
3396 End_Label => Empty);
3398 -- Update the previously created object renaming declaration with
3399 -- the new iterator.
3401 Prepend_To (Expressions (Ind_Comp),
3402 New_Reference_To (Iterator, Loc));
3403 end loop;
3404 end if;
3406 -- If original loop has a source name, preserve it so it can be
3407 -- recognized by an exit statement in the body of the rewritten loop.
3408 -- This only concerns source names: the generated name of an anonymous
3409 -- loop will be create again during the subsequent analysis below.
3411 if Present (Identifier (N))
3412 and then Comes_From_Source (Identifier (N))
3413 then
3414 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3415 end if;
3417 Rewrite (N, Core_Loop);
3418 Analyze (N);
3419 end Expand_Iterator_Loop_Over_Array;
3421 -----------------------------
3422 -- Expand_N_Loop_Statement --
3423 -----------------------------
3425 -- 1. Remove null loop entirely
3426 -- 2. Deal with while condition for C/Fortran boolean
3427 -- 3. Deal with loops with a non-standard enumeration type range
3428 -- 4. Deal with while loops where Condition_Actions is set
3429 -- 5. Deal with loops over predicated subtypes
3430 -- 6. Deal with loops with iterators over arrays and containers
3431 -- 7. Insert polling call if required
3433 procedure Expand_N_Loop_Statement (N : Node_Id) is
3434 Loc : constant Source_Ptr := Sloc (N);
3435 Scheme : constant Node_Id := Iteration_Scheme (N);
3436 Stmt : Node_Id;
3438 begin
3439 -- Delete null loop
3441 if Is_Null_Loop (N) then
3442 Rewrite (N, Make_Null_Statement (Loc));
3443 return;
3444 end if;
3446 -- Deal with condition for C/Fortran Boolean
3448 if Present (Scheme) then
3449 Adjust_Condition (Condition (Scheme));
3450 end if;
3452 -- Generate polling call
3454 if Is_Non_Empty_List (Statements (N)) then
3455 Generate_Poll_Call (First (Statements (N)));
3456 end if;
3458 -- Nothing more to do for plain loop with no iteration scheme
3460 if No (Scheme) then
3461 null;
3463 -- Case of for loop (Loop_Parameter_Specification present)
3465 -- Note: we do not have to worry about validity checking of the for loop
3466 -- range bounds here, since they were frozen with constant declarations
3467 -- and it is during that process that the validity checking is done.
3469 elsif Present (Loop_Parameter_Specification (Scheme)) then
3470 declare
3471 LPS : constant Node_Id :=
3472 Loop_Parameter_Specification (Scheme);
3473 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
3474 Ltype : constant Entity_Id := Etype (Loop_Id);
3475 Btype : constant Entity_Id := Base_Type (Ltype);
3476 Expr : Node_Id;
3477 Decls : List_Id;
3478 New_Id : Entity_Id;
3480 begin
3481 -- Deal with loop over predicates
3483 if Is_Discrete_Type (Ltype)
3484 and then Present (Predicate_Function (Ltype))
3485 then
3486 Expand_Predicated_Loop (N);
3488 -- Handle the case where we have a for loop with the range type
3489 -- being an enumeration type with non-standard representation.
3490 -- In this case we expand:
3492 -- for x in [reverse] a .. b loop
3493 -- ...
3494 -- end loop;
3496 -- to
3498 -- for xP in [reverse] integer
3499 -- range etype'Pos (a) .. etype'Pos (b)
3500 -- loop
3501 -- declare
3502 -- x : constant etype := Pos_To_Rep (xP);
3503 -- begin
3504 -- ...
3505 -- end;
3506 -- end loop;
3508 elsif Is_Enumeration_Type (Btype)
3509 and then Present (Enum_Pos_To_Rep (Btype))
3510 then
3511 New_Id :=
3512 Make_Defining_Identifier (Loc,
3513 Chars => New_External_Name (Chars (Loop_Id), 'P'));
3515 -- If the type has a contiguous representation, successive
3516 -- values can be generated as offsets from the first literal.
3518 if Has_Contiguous_Rep (Btype) then
3519 Expr :=
3520 Unchecked_Convert_To (Btype,
3521 Make_Op_Add (Loc,
3522 Left_Opnd =>
3523 Make_Integer_Literal (Loc,
3524 Enumeration_Rep (First_Literal (Btype))),
3525 Right_Opnd => New_Reference_To (New_Id, Loc)));
3526 else
3527 -- Use the constructed array Enum_Pos_To_Rep
3529 Expr :=
3530 Make_Indexed_Component (Loc,
3531 Prefix =>
3532 New_Reference_To (Enum_Pos_To_Rep (Btype), Loc),
3533 Expressions =>
3534 New_List (New_Reference_To (New_Id, Loc)));
3535 end if;
3537 -- Build declaration for loop identifier
3539 Decls :=
3540 New_List (
3541 Make_Object_Declaration (Loc,
3542 Defining_Identifier => Loop_Id,
3543 Constant_Present => True,
3544 Object_Definition => New_Reference_To (Ltype, Loc),
3545 Expression => Expr));
3547 Rewrite (N,
3548 Make_Loop_Statement (Loc,
3549 Identifier => Identifier (N),
3551 Iteration_Scheme =>
3552 Make_Iteration_Scheme (Loc,
3553 Loop_Parameter_Specification =>
3554 Make_Loop_Parameter_Specification (Loc,
3555 Defining_Identifier => New_Id,
3556 Reverse_Present => Reverse_Present (LPS),
3558 Discrete_Subtype_Definition =>
3559 Make_Subtype_Indication (Loc,
3561 Subtype_Mark =>
3562 New_Reference_To (Standard_Natural, Loc),
3564 Constraint =>
3565 Make_Range_Constraint (Loc,
3566 Range_Expression =>
3567 Make_Range (Loc,
3569 Low_Bound =>
3570 Make_Attribute_Reference (Loc,
3571 Prefix =>
3572 New_Reference_To (Btype, Loc),
3574 Attribute_Name => Name_Pos,
3576 Expressions => New_List (
3577 Relocate_Node
3578 (Type_Low_Bound (Ltype)))),
3580 High_Bound =>
3581 Make_Attribute_Reference (Loc,
3582 Prefix =>
3583 New_Reference_To (Btype, Loc),
3585 Attribute_Name => Name_Pos,
3587 Expressions => New_List (
3588 Relocate_Node
3589 (Type_High_Bound
3590 (Ltype))))))))),
3592 Statements => New_List (
3593 Make_Block_Statement (Loc,
3594 Declarations => Decls,
3595 Handled_Statement_Sequence =>
3596 Make_Handled_Sequence_Of_Statements (Loc,
3597 Statements => Statements (N)))),
3599 End_Label => End_Label (N)));
3601 -- The loop parameter's entity must be removed from the loop
3602 -- scope's entity list and rendered invisible, since it will
3603 -- now be located in the new block scope. Any other entities
3604 -- already associated with the loop scope, such as the loop
3605 -- parameter's subtype, will remain there.
3607 -- In an element loop, the loop will contain a declaration for
3608 -- a cursor variable; otherwise the loop id is the first entity
3609 -- in the scope constructed for the loop.
3611 if Comes_From_Source (Loop_Id) then
3612 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
3613 null;
3614 end if;
3616 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
3617 Remove_Homonym (Loop_Id);
3619 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
3620 Set_Last_Entity (Scope (Loop_Id), Empty);
3621 end if;
3623 Analyze (N);
3625 -- Nothing to do with other cases of for loops
3627 else
3628 null;
3629 end if;
3630 end;
3632 -- Second case, if we have a while loop with Condition_Actions set, then
3633 -- we change it into a plain loop:
3635 -- while C loop
3636 -- ...
3637 -- end loop;
3639 -- changed to:
3641 -- loop
3642 -- <<condition actions>>
3643 -- exit when not C;
3644 -- ...
3645 -- end loop
3647 elsif Present (Scheme)
3648 and then Present (Condition_Actions (Scheme))
3649 and then Present (Condition (Scheme))
3650 then
3651 declare
3652 ES : Node_Id;
3654 begin
3655 ES :=
3656 Make_Exit_Statement (Sloc (Condition (Scheme)),
3657 Condition =>
3658 Make_Op_Not (Sloc (Condition (Scheme)),
3659 Right_Opnd => Condition (Scheme)));
3661 Prepend (ES, Statements (N));
3662 Insert_List_Before (ES, Condition_Actions (Scheme));
3664 -- This is not an implicit loop, since it is generated in response
3665 -- to the loop statement being processed. If this is itself
3666 -- implicit, the restriction has already been checked. If not,
3667 -- it is an explicit loop.
3669 Rewrite (N,
3670 Make_Loop_Statement (Sloc (N),
3671 Identifier => Identifier (N),
3672 Statements => Statements (N),
3673 End_Label => End_Label (N)));
3675 Analyze (N);
3676 end;
3678 -- Here to deal with iterator case
3680 elsif Present (Scheme)
3681 and then Present (Iterator_Specification (Scheme))
3682 then
3683 Expand_Iterator_Loop (N);
3684 end if;
3686 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
3687 -- is transformed into a conditional block where the original loop is
3688 -- the sole statement. Inspect the statements of the nested loop for
3689 -- controlled objects.
3691 Stmt := N;
3693 if Subject_To_Loop_Entry_Attributes (Stmt) then
3694 Stmt := Find_Loop_In_Conditional_Block (Stmt);
3695 end if;
3697 Process_Statements_For_Controlled_Objects (Stmt);
3698 end Expand_N_Loop_Statement;
3700 ----------------------------
3701 -- Expand_Predicated_Loop --
3702 ----------------------------
3704 -- Note: the expander can handle generation of loops over predicated
3705 -- subtypes for both the dynamic and static cases. Depending on what
3706 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
3707 -- mode, the semantic analyzer may disallow one or both forms.
3709 procedure Expand_Predicated_Loop (N : Node_Id) is
3710 Loc : constant Source_Ptr := Sloc (N);
3711 Isc : constant Node_Id := Iteration_Scheme (N);
3712 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
3713 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
3714 Ltype : constant Entity_Id := Etype (Loop_Id);
3715 Stat : constant List_Id := Static_Predicate (Ltype);
3716 Stmts : constant List_Id := Statements (N);
3718 begin
3719 -- Case of iteration over non-static predicate, should not be possible
3720 -- since this is not allowed by the semantics and should have been
3721 -- caught during analysis of the loop statement.
3723 if No (Stat) then
3724 raise Program_Error;
3726 -- If the predicate list is empty, that corresponds to a predicate of
3727 -- False, in which case the loop won't run at all, and we rewrite the
3728 -- entire loop as a null statement.
3730 elsif Is_Empty_List (Stat) then
3731 Rewrite (N, Make_Null_Statement (Loc));
3732 Analyze (N);
3734 -- For expansion over a static predicate we generate the following
3736 -- declare
3737 -- J : Ltype := min-val;
3738 -- begin
3739 -- loop
3740 -- body
3741 -- case J is
3742 -- when endpoint => J := startpoint;
3743 -- when endpoint => J := startpoint;
3744 -- ...
3745 -- when max-val => exit;
3746 -- when others => J := Lval'Succ (J);
3747 -- end case;
3748 -- end loop;
3749 -- end;
3751 -- To make this a little clearer, let's take a specific example:
3753 -- type Int is range 1 .. 10;
3754 -- subtype L is Int with
3755 -- predicate => L in 3 | 10 | 5 .. 7;
3756 -- ...
3757 -- for L in StaticP loop
3758 -- Put_Line ("static:" & J'Img);
3759 -- end loop;
3761 -- In this case, the loop is transformed into
3763 -- begin
3764 -- J : L := 3;
3765 -- loop
3766 -- body
3767 -- case J is
3768 -- when 3 => J := 5;
3769 -- when 7 => J := 10;
3770 -- when 10 => exit;
3771 -- when others => J := L'Succ (J);
3772 -- end case;
3773 -- end loop;
3774 -- end;
3776 else
3777 Static_Predicate : declare
3778 S : Node_Id;
3779 D : Node_Id;
3780 P : Node_Id;
3781 Alts : List_Id;
3782 Cstm : Node_Id;
3784 function Lo_Val (N : Node_Id) return Node_Id;
3785 -- Given static expression or static range, returns an identifier
3786 -- whose value is the low bound of the expression value or range.
3788 function Hi_Val (N : Node_Id) return Node_Id;
3789 -- Given static expression or static range, returns an identifier
3790 -- whose value is the high bound of the expression value or range.
3792 ------------
3793 -- Hi_Val --
3794 ------------
3796 function Hi_Val (N : Node_Id) return Node_Id is
3797 begin
3798 if Is_Static_Expression (N) then
3799 return New_Copy (N);
3800 else
3801 pragma Assert (Nkind (N) = N_Range);
3802 return New_Copy (High_Bound (N));
3803 end if;
3804 end Hi_Val;
3806 ------------
3807 -- Lo_Val --
3808 ------------
3810 function Lo_Val (N : Node_Id) return Node_Id is
3811 begin
3812 if Is_Static_Expression (N) then
3813 return New_Copy (N);
3814 else
3815 pragma Assert (Nkind (N) = N_Range);
3816 return New_Copy (Low_Bound (N));
3817 end if;
3818 end Lo_Val;
3820 -- Start of processing for Static_Predicate
3822 begin
3823 -- Convert loop identifier to normal variable and reanalyze it so
3824 -- that this conversion works. We have to use the same defining
3825 -- identifier, since there may be references in the loop body.
3827 Set_Analyzed (Loop_Id, False);
3828 Set_Ekind (Loop_Id, E_Variable);
3830 -- In most loops the loop variable is assigned in various
3831 -- alternatives in the body. However, in the rare case when
3832 -- the range specifies a single element, the loop variable
3833 -- may trigger a spurious warning that is could be constant.
3834 -- This warning might as well be suppressed.
3836 Set_Warnings_Off (Loop_Id);
3838 -- Loop to create branches of case statement
3840 Alts := New_List;
3841 P := First (Stat);
3842 while Present (P) loop
3843 if No (Next (P)) then
3844 S := Make_Exit_Statement (Loc);
3845 else
3846 S :=
3847 Make_Assignment_Statement (Loc,
3848 Name => New_Occurrence_Of (Loop_Id, Loc),
3849 Expression => Lo_Val (Next (P)));
3850 Set_Suppress_Assignment_Checks (S);
3851 end if;
3853 Append_To (Alts,
3854 Make_Case_Statement_Alternative (Loc,
3855 Statements => New_List (S),
3856 Discrete_Choices => New_List (Hi_Val (P))));
3858 Next (P);
3859 end loop;
3861 -- Add others choice
3863 S :=
3864 Make_Assignment_Statement (Loc,
3865 Name => New_Occurrence_Of (Loop_Id, Loc),
3866 Expression =>
3867 Make_Attribute_Reference (Loc,
3868 Prefix => New_Occurrence_Of (Ltype, Loc),
3869 Attribute_Name => Name_Succ,
3870 Expressions => New_List (
3871 New_Occurrence_Of (Loop_Id, Loc))));
3872 Set_Suppress_Assignment_Checks (S);
3874 Append_To (Alts,
3875 Make_Case_Statement_Alternative (Loc,
3876 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
3877 Statements => New_List (S)));
3879 -- Construct case statement and append to body statements
3881 Cstm :=
3882 Make_Case_Statement (Loc,
3883 Expression => New_Occurrence_Of (Loop_Id, Loc),
3884 Alternatives => Alts);
3885 Append_To (Stmts, Cstm);
3887 -- Rewrite the loop
3889 D :=
3890 Make_Object_Declaration (Loc,
3891 Defining_Identifier => Loop_Id,
3892 Object_Definition => New_Occurrence_Of (Ltype, Loc),
3893 Expression => Lo_Val (First (Stat)));
3894 Set_Suppress_Assignment_Checks (D);
3896 Rewrite (N,
3897 Make_Block_Statement (Loc,
3898 Declarations => New_List (D),
3899 Handled_Statement_Sequence =>
3900 Make_Handled_Sequence_Of_Statements (Loc,
3901 Statements => New_List (
3902 Make_Loop_Statement (Loc,
3903 Statements => Stmts,
3904 End_Label => Empty)))));
3906 Analyze (N);
3907 end Static_Predicate;
3908 end if;
3909 end Expand_Predicated_Loop;
3911 ------------------------------
3912 -- Make_Tag_Ctrl_Assignment --
3913 ------------------------------
3915 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
3916 Asn : constant Node_Id := Relocate_Node (N);
3917 L : constant Node_Id := Name (N);
3918 Loc : constant Source_Ptr := Sloc (N);
3919 Res : constant List_Id := New_List;
3920 T : constant Entity_Id := Underlying_Type (Etype (L));
3922 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
3923 Ctrl_Act : constant Boolean := Needs_Finalization (T)
3924 and then not No_Ctrl_Actions (N);
3925 Save_Tag : constant Boolean := Is_Tagged_Type (T)
3926 and then not Comp_Asn
3927 and then not No_Ctrl_Actions (N)
3928 and then Tagged_Type_Expansion;
3929 -- Tags are not saved and restored when VM_Target because VM tags are
3930 -- represented implicitly in objects.
3932 Next_Id : Entity_Id;
3933 Prev_Id : Entity_Id;
3934 Tag_Id : Entity_Id;
3936 begin
3937 -- Finalize the target of the assignment when controlled
3939 -- We have two exceptions here:
3941 -- 1. If we are in an init proc since it is an initialization more
3942 -- than an assignment.
3944 -- 2. If the left-hand side is a temporary that was not initialized
3945 -- (or the parent part of a temporary since it is the case in
3946 -- extension aggregates). Such a temporary does not come from
3947 -- source. We must examine the original node for the prefix, because
3948 -- it may be a component of an entry formal, in which case it has
3949 -- been rewritten and does not appear to come from source either.
3951 -- Case of init proc
3953 if not Ctrl_Act then
3954 null;
3956 -- The left hand side is an uninitialized temporary object
3958 elsif Nkind (L) = N_Type_Conversion
3959 and then Is_Entity_Name (Expression (L))
3960 and then Nkind (Parent (Entity (Expression (L)))) =
3961 N_Object_Declaration
3962 and then No_Initialization (Parent (Entity (Expression (L))))
3963 then
3964 null;
3966 else
3967 Append_To (Res,
3968 Make_Final_Call
3969 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
3970 Typ => Etype (L)));
3971 end if;
3973 -- Save the Tag in a local variable Tag_Id
3975 if Save_Tag then
3976 Tag_Id := Make_Temporary (Loc, 'A');
3978 Append_To (Res,
3979 Make_Object_Declaration (Loc,
3980 Defining_Identifier => Tag_Id,
3981 Object_Definition => New_Reference_To (RTE (RE_Tag), Loc),
3982 Expression =>
3983 Make_Selected_Component (Loc,
3984 Prefix => Duplicate_Subexpr_No_Checks (L),
3985 Selector_Name =>
3986 New_Reference_To (First_Tag_Component (T), Loc))));
3988 -- Otherwise Tag_Id is not used
3990 else
3991 Tag_Id := Empty;
3992 end if;
3994 -- Save the Prev and Next fields on .NET/JVM. This is not needed on non
3995 -- VM targets since the fields are not part of the object.
3997 if VM_Target /= No_VM
3998 and then Is_Controlled (T)
3999 then
4000 Prev_Id := Make_Temporary (Loc, 'P');
4001 Next_Id := Make_Temporary (Loc, 'N');
4003 -- Generate:
4004 -- Pnn : Root_Controlled_Ptr := Root_Controlled (L).Prev;
4006 Append_To (Res,
4007 Make_Object_Declaration (Loc,
4008 Defining_Identifier => Prev_Id,
4009 Object_Definition =>
4010 New_Reference_To (RTE (RE_Root_Controlled_Ptr), Loc),
4011 Expression =>
4012 Make_Selected_Component (Loc,
4013 Prefix =>
4014 Unchecked_Convert_To
4015 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4016 Selector_Name =>
4017 Make_Identifier (Loc, Name_Prev))));
4019 -- Generate:
4020 -- Nnn : Root_Controlled_Ptr := Root_Controlled (L).Next;
4022 Append_To (Res,
4023 Make_Object_Declaration (Loc,
4024 Defining_Identifier => Next_Id,
4025 Object_Definition =>
4026 New_Reference_To (RTE (RE_Root_Controlled_Ptr), Loc),
4027 Expression =>
4028 Make_Selected_Component (Loc,
4029 Prefix =>
4030 Unchecked_Convert_To
4031 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4032 Selector_Name =>
4033 Make_Identifier (Loc, Name_Next))));
4034 end if;
4036 -- If the tagged type has a full rep clause, expand the assignment into
4037 -- component-wise assignments. Mark the node as unanalyzed in order to
4038 -- generate the proper code and propagate this scenario by setting a
4039 -- flag to avoid infinite recursion.
4041 if Comp_Asn then
4042 Set_Analyzed (Asn, False);
4043 Set_Componentwise_Assignment (Asn, True);
4044 end if;
4046 Append_To (Res, Asn);
4048 -- Restore the tag
4050 if Save_Tag then
4051 Append_To (Res,
4052 Make_Assignment_Statement (Loc,
4053 Name =>
4054 Make_Selected_Component (Loc,
4055 Prefix => Duplicate_Subexpr_No_Checks (L),
4056 Selector_Name =>
4057 New_Reference_To (First_Tag_Component (T), Loc)),
4058 Expression => New_Reference_To (Tag_Id, Loc)));
4059 end if;
4061 -- Restore the Prev and Next fields on .NET/JVM
4063 if VM_Target /= No_VM
4064 and then Is_Controlled (T)
4065 then
4066 -- Generate:
4067 -- Root_Controlled (L).Prev := Prev_Id;
4069 Append_To (Res,
4070 Make_Assignment_Statement (Loc,
4071 Name =>
4072 Make_Selected_Component (Loc,
4073 Prefix =>
4074 Unchecked_Convert_To
4075 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4076 Selector_Name =>
4077 Make_Identifier (Loc, Name_Prev)),
4078 Expression => New_Reference_To (Prev_Id, Loc)));
4080 -- Generate:
4081 -- Root_Controlled (L).Next := Next_Id;
4083 Append_To (Res,
4084 Make_Assignment_Statement (Loc,
4085 Name =>
4086 Make_Selected_Component (Loc,
4087 Prefix =>
4088 Unchecked_Convert_To
4089 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4090 Selector_Name => Make_Identifier (Loc, Name_Next)),
4091 Expression => New_Reference_To (Next_Id, Loc)));
4092 end if;
4094 -- Adjust the target after the assignment when controlled (not in the
4095 -- init proc since it is an initialization more than an assignment).
4097 if Ctrl_Act then
4098 Append_To (Res,
4099 Make_Adjust_Call
4100 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
4101 Typ => Etype (L)));
4102 end if;
4104 return Res;
4106 exception
4108 -- Could use comment here ???
4110 when RE_Not_Available =>
4111 return Empty_List;
4112 end Make_Tag_Ctrl_Assignment;
4114 end Exp_Ch5;