Daily bump.
[official-gcc.git] / gcc / ada / exp_ch5.adb
blob7156c76a8ef2eea63d8917d0aa1050f853abc019
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-2015, 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 Elists; use Elists;
32 with Errout; use Errout;
33 with Exp_Aggr; use Exp_Aggr;
34 with Exp_Ch6; use Exp_Ch6;
35 with Exp_Ch7; use Exp_Ch7;
36 with Exp_Ch11; use Exp_Ch11;
37 with Exp_Dbug; use Exp_Dbug;
38 with Exp_Pakd; use Exp_Pakd;
39 with Exp_Tss; use Exp_Tss;
40 with Exp_Util; use Exp_Util;
41 with Ghost; use Ghost;
42 with Inline; use Inline;
43 with Namet; use Namet;
44 with Nlists; use Nlists;
45 with Nmake; use Nmake;
46 with Opt; use Opt;
47 with Restrict; use Restrict;
48 with Rident; use Rident;
49 with Rtsfind; use Rtsfind;
50 with Sinfo; use Sinfo;
51 with Sem; use Sem;
52 with Sem_Aux; use Sem_Aux;
53 with Sem_Ch3; use Sem_Ch3;
54 with Sem_Ch8; use Sem_Ch8;
55 with Sem_Ch13; use Sem_Ch13;
56 with Sem_Eval; use Sem_Eval;
57 with Sem_Res; use Sem_Res;
58 with Sem_Util; use Sem_Util;
59 with Snames; use Snames;
60 with Stand; use Stand;
61 with Stringt; use Stringt;
62 with Targparm; use Targparm;
63 with Tbuild; use Tbuild;
64 with Uintp; use Uintp;
65 with Validsw; use Validsw;
67 package body Exp_Ch5 is
69 procedure Build_Formal_Container_Iteration
70 (N : Node_Id;
71 Container : Entity_Id;
72 Cursor : Entity_Id;
73 Init : out Node_Id;
74 Advance : out Node_Id;
75 New_Loop : out Node_Id);
76 -- Utility to create declarations and loop statement for both forms
77 -- of formal container iterators.
79 function Change_Of_Representation (N : Node_Id) return Boolean;
80 -- Determine if the right hand side of assignment N is a type conversion
81 -- which requires a change of representation. Called only for the array
82 -- and record cases.
84 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id);
85 -- N is an assignment which assigns an array value. This routine process
86 -- the various special cases and checks required for such assignments,
87 -- including change of representation. Rhs is normally simply the right
88 -- hand side of the assignment, except that if the right hand side is a
89 -- type conversion or a qualified expression, then the RHS is the actual
90 -- expression inside any such type conversions or qualifications.
92 function Expand_Assign_Array_Loop
93 (N : Node_Id;
94 Larray : Entity_Id;
95 Rarray : Entity_Id;
96 L_Type : Entity_Id;
97 R_Type : Entity_Id;
98 Ndim : Pos;
99 Rev : Boolean) return Node_Id;
100 -- N is an assignment statement which assigns an array value. This routine
101 -- expands the assignment into a loop (or nested loops for the case of a
102 -- multi-dimensional array) to do the assignment component by component.
103 -- Larray and Rarray are the entities of the actual arrays on the left
104 -- hand and right hand sides. L_Type and R_Type are the types of these
105 -- arrays (which may not be the same, due to either sliding, or to a
106 -- change of representation case). Ndim is the number of dimensions and
107 -- the parameter Rev indicates if the loops run normally (Rev = False),
108 -- or reversed (Rev = True). The value returned is the constructed
109 -- loop statement. Auxiliary declarations are inserted before node N
110 -- using the standard Insert_Actions mechanism.
112 procedure Expand_Assign_Record (N : Node_Id);
113 -- N is an assignment of an untagged record value. This routine handles
114 -- the case where the assignment must be made component by component,
115 -- either because the target is not byte aligned, or there is a change
116 -- of representation, or when we have a tagged type with a representation
117 -- clause (this last case is required because holes in the tagged type
118 -- might be filled with components from child types).
120 procedure Expand_Formal_Container_Loop (N : Node_Id);
121 -- Use the primitives specified in an Iterable aspect to expand a loop
122 -- over a so-called formal container, primarily for SPARK usage.
124 procedure Expand_Formal_Container_Element_Loop (N : Node_Id);
125 -- Same, for an iterator of the form " For E of C". In this case the
126 -- iterator provides the name of the element, and the cursor is generated
127 -- internally.
129 procedure Expand_Iterator_Loop (N : Node_Id);
130 -- Expand loop over arrays and containers that uses the form "for X of C"
131 -- with an optional subtype mark, or "for Y in C".
133 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id);
134 -- Expand loop over arrays that uses the form "for X of C"
136 procedure Expand_Iterator_Loop_Over_Container
137 (N : Node_Id;
138 Isc : Node_Id;
139 I_Spec : Node_Id;
140 Container : Node_Id;
141 Container_Typ : Entity_Id);
142 -- Expand loop over containers that uses the form "for X of C" with an
143 -- optional subtype mark, or "for Y in C". Isc is the iteration scheme.
144 -- I_Spec is the iterator specification and Container is either the
145 -- Container (for OF) or the iterator (for IN).
147 procedure Expand_Predicated_Loop (N : Node_Id);
148 -- Expand for loop over predicated subtype
150 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id;
151 -- Generate the necessary code for controlled and tagged assignment, that
152 -- is to say, finalization of the target before, adjustment of the target
153 -- after and save and restore of the tag and finalization pointers which
154 -- are not 'part of the value' and must not be changed upon assignment. N
155 -- is the original Assignment node.
157 --------------------------------------
158 -- Build_Formal_Container_iteration --
159 --------------------------------------
161 procedure Build_Formal_Container_Iteration
162 (N : Node_Id;
163 Container : Entity_Id;
164 Cursor : Entity_Id;
165 Init : out Node_Id;
166 Advance : out Node_Id;
167 New_Loop : out Node_Id)
169 Loc : constant Source_Ptr := Sloc (N);
170 Stats : constant List_Id := Statements (N);
171 Typ : constant Entity_Id := Base_Type (Etype (Container));
172 First_Op : constant Entity_Id :=
173 Get_Iterable_Type_Primitive (Typ, Name_First);
174 Next_Op : constant Entity_Id :=
175 Get_Iterable_Type_Primitive (Typ, Name_Next);
177 Has_Element_Op : constant Entity_Id :=
178 Get_Iterable_Type_Primitive (Typ, Name_Has_Element);
179 begin
180 -- Declaration for Cursor
182 Init :=
183 Make_Object_Declaration (Loc,
184 Defining_Identifier => Cursor,
185 Object_Definition => New_Occurrence_Of (Etype (First_Op), Loc),
186 Expression =>
187 Make_Function_Call (Loc,
188 Name => New_Occurrence_Of (First_Op, Loc),
189 Parameter_Associations => New_List (
190 New_Occurrence_Of (Container, Loc))));
192 -- Statement that advances cursor in loop
194 Advance :=
195 Make_Assignment_Statement (Loc,
196 Name => New_Occurrence_Of (Cursor, Loc),
197 Expression =>
198 Make_Function_Call (Loc,
199 Name => New_Occurrence_Of (Next_Op, Loc),
200 Parameter_Associations => New_List (
201 New_Occurrence_Of (Container, Loc),
202 New_Occurrence_Of (Cursor, Loc))));
204 -- Iterator is rewritten as a while_loop
206 New_Loop :=
207 Make_Loop_Statement (Loc,
208 Iteration_Scheme =>
209 Make_Iteration_Scheme (Loc,
210 Condition =>
211 Make_Function_Call (Loc,
212 Name => New_Occurrence_Of (Has_Element_Op, Loc),
213 Parameter_Associations => New_List (
214 New_Occurrence_Of (Container, Loc),
215 New_Occurrence_Of (Cursor, Loc)))),
216 Statements => Stats,
217 End_Label => Empty);
218 end Build_Formal_Container_Iteration;
220 ------------------------------
221 -- Change_Of_Representation --
222 ------------------------------
224 function Change_Of_Representation (N : Node_Id) return Boolean is
225 Rhs : constant Node_Id := Expression (N);
226 begin
227 return
228 Nkind (Rhs) = N_Type_Conversion
229 and then
230 not Same_Representation (Etype (Rhs), Etype (Expression (Rhs)));
231 end Change_Of_Representation;
233 -------------------------
234 -- Expand_Assign_Array --
235 -------------------------
237 -- There are two issues here. First, do we let Gigi do a block move, or
238 -- do we expand out into a loop? Second, we need to set the two flags
239 -- Forwards_OK and Backwards_OK which show whether the block move (or
240 -- corresponding loops) can be legitimately done in a forwards (low to
241 -- high) or backwards (high to low) manner.
243 procedure Expand_Assign_Array (N : Node_Id; Rhs : Node_Id) is
244 Loc : constant Source_Ptr := Sloc (N);
246 Lhs : constant Node_Id := Name (N);
248 Act_Lhs : constant Node_Id := Get_Referenced_Object (Lhs);
249 Act_Rhs : Node_Id := Get_Referenced_Object (Rhs);
251 L_Type : constant Entity_Id :=
252 Underlying_Type (Get_Actual_Subtype (Act_Lhs));
253 R_Type : Entity_Id :=
254 Underlying_Type (Get_Actual_Subtype (Act_Rhs));
256 L_Slice : constant Boolean := Nkind (Act_Lhs) = N_Slice;
257 R_Slice : constant Boolean := Nkind (Act_Rhs) = N_Slice;
259 Crep : constant Boolean := Change_Of_Representation (N);
261 Larray : Node_Id;
262 Rarray : Node_Id;
264 Ndim : constant Pos := Number_Dimensions (L_Type);
266 Loop_Required : Boolean := False;
267 -- This switch is set to True if the array move must be done using
268 -- an explicit front end generated loop.
270 procedure Apply_Dereference (Arg : Node_Id);
271 -- If the argument is an access to an array, and the assignment is
272 -- converted into a procedure call, apply explicit dereference.
274 function Has_Address_Clause (Exp : Node_Id) return Boolean;
275 -- Test if Exp is a reference to an array whose declaration has
276 -- an address clause, or it is a slice of such an array.
278 function Is_Formal_Array (Exp : Node_Id) return Boolean;
279 -- Test if Exp is a reference to an array which is either a formal
280 -- parameter or a slice of a formal parameter. These are the cases
281 -- where hidden aliasing can occur.
283 function Is_Non_Local_Array (Exp : Node_Id) return Boolean;
284 -- Determine if Exp is a reference to an array variable which is other
285 -- than an object defined in the current scope, or a slice of such
286 -- an object. Such objects can be aliased to parameters (unlike local
287 -- array references).
289 -----------------------
290 -- Apply_Dereference --
291 -----------------------
293 procedure Apply_Dereference (Arg : Node_Id) is
294 Typ : constant Entity_Id := Etype (Arg);
295 begin
296 if Is_Access_Type (Typ) then
297 Rewrite (Arg, Make_Explicit_Dereference (Loc,
298 Prefix => Relocate_Node (Arg)));
299 Analyze_And_Resolve (Arg, Designated_Type (Typ));
300 end if;
301 end Apply_Dereference;
303 ------------------------
304 -- Has_Address_Clause --
305 ------------------------
307 function Has_Address_Clause (Exp : Node_Id) return Boolean is
308 begin
309 return
310 (Is_Entity_Name (Exp) and then
311 Present (Address_Clause (Entity (Exp))))
312 or else
313 (Nkind (Exp) = N_Slice and then Has_Address_Clause (Prefix (Exp)));
314 end Has_Address_Clause;
316 ---------------------
317 -- Is_Formal_Array --
318 ---------------------
320 function Is_Formal_Array (Exp : Node_Id) return Boolean is
321 begin
322 return
323 (Is_Entity_Name (Exp) and then Is_Formal (Entity (Exp)))
324 or else
325 (Nkind (Exp) = N_Slice and then Is_Formal_Array (Prefix (Exp)));
326 end Is_Formal_Array;
328 ------------------------
329 -- Is_Non_Local_Array --
330 ------------------------
332 function Is_Non_Local_Array (Exp : Node_Id) return Boolean is
333 begin
334 return (Is_Entity_Name (Exp)
335 and then Scope (Entity (Exp)) /= Current_Scope)
336 or else (Nkind (Exp) = N_Slice
337 and then Is_Non_Local_Array (Prefix (Exp)));
338 end Is_Non_Local_Array;
340 -- Determine if Lhs, Rhs are formal arrays or nonlocal arrays
342 Lhs_Formal : constant Boolean := Is_Formal_Array (Act_Lhs);
343 Rhs_Formal : constant Boolean := Is_Formal_Array (Act_Rhs);
345 Lhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Lhs);
346 Rhs_Non_Local_Var : constant Boolean := Is_Non_Local_Array (Act_Rhs);
348 -- Start of processing for Expand_Assign_Array
350 begin
351 -- Deal with length check. Note that the length check is done with
352 -- respect to the right hand side as given, not a possible underlying
353 -- renamed object, since this would generate incorrect extra checks.
355 Apply_Length_Check (Rhs, L_Type);
357 -- We start by assuming that the move can be done in either direction,
358 -- i.e. that the two sides are completely disjoint.
360 Set_Forwards_OK (N, True);
361 Set_Backwards_OK (N, True);
363 -- Normally it is only the slice case that can lead to overlap, and
364 -- explicit checks for slices are made below. But there is one case
365 -- where the slice can be implicit and invisible to us: when we have a
366 -- one dimensional array, and either both operands are parameters, or
367 -- one is a parameter (which can be a slice passed by reference) and the
368 -- other is a non-local variable. In this case the parameter could be a
369 -- slice that overlaps with the other operand.
371 -- However, if the array subtype is a constrained first subtype in the
372 -- parameter case, then we don't have to worry about overlap, since
373 -- slice assignments aren't possible (other than for a slice denoting
374 -- the whole array).
376 -- Note: No overlap is possible if there is a change of representation,
377 -- so we can exclude this case.
379 if Ndim = 1
380 and then not Crep
381 and then
382 ((Lhs_Formal and Rhs_Formal)
383 or else
384 (Lhs_Formal and Rhs_Non_Local_Var)
385 or else
386 (Rhs_Formal and Lhs_Non_Local_Var))
387 and then
388 (not Is_Constrained (Etype (Lhs))
389 or else not Is_First_Subtype (Etype (Lhs)))
391 -- In the case of compiling for the Java or .NET Virtual Machine,
392 -- slices are always passed by making a copy, so we don't have to
393 -- worry about overlap. We also want to prevent generation of "<"
394 -- comparisons for array addresses, since that's a meaningless
395 -- operation on the VM.
397 and then VM_Target = No_VM
398 then
399 Set_Forwards_OK (N, False);
400 Set_Backwards_OK (N, False);
402 -- Note: the bit-packed case is not worrisome here, since if we have
403 -- a slice passed as a parameter, it is always aligned on a byte
404 -- boundary, and if there are no explicit slices, the assignment
405 -- can be performed directly.
406 end if;
408 -- If either operand has an address clause clear Backwards_OK and
409 -- Forwards_OK, since we cannot tell if the operands overlap. We
410 -- exclude this treatment when Rhs is an aggregate, since we know
411 -- that overlap can't occur.
413 if (Has_Address_Clause (Lhs) and then Nkind (Rhs) /= N_Aggregate)
414 or else Has_Address_Clause (Rhs)
415 then
416 Set_Forwards_OK (N, False);
417 Set_Backwards_OK (N, False);
418 end if;
420 -- We certainly must use a loop for change of representation and also
421 -- we use the operand of the conversion on the right hand side as the
422 -- effective right hand side (the component types must match in this
423 -- situation).
425 if Crep then
426 Act_Rhs := Get_Referenced_Object (Rhs);
427 R_Type := Get_Actual_Subtype (Act_Rhs);
428 Loop_Required := True;
430 -- We require a loop if the left side is possibly bit unaligned
432 elsif Possible_Bit_Aligned_Component (Lhs)
433 or else
434 Possible_Bit_Aligned_Component (Rhs)
435 then
436 Loop_Required := True;
438 -- Arrays with controlled components are expanded into a loop to force
439 -- calls to Adjust at the component level.
441 elsif Has_Controlled_Component (L_Type) then
442 Loop_Required := True;
444 -- If object is atomic/VFA, we cannot tolerate a loop
446 elsif Is_Atomic_Or_VFA_Object (Act_Lhs)
447 or else
448 Is_Atomic_Or_VFA_Object (Act_Rhs)
449 then
450 return;
452 -- Loop is required if we have atomic components since we have to
453 -- be sure to do any accesses on an element by element basis.
455 elsif Has_Atomic_Components (L_Type)
456 or else Has_Atomic_Components (R_Type)
457 or else Is_Atomic_Or_VFA (Component_Type (L_Type))
458 or else Is_Atomic_Or_VFA (Component_Type (R_Type))
459 then
460 Loop_Required := True;
462 -- Case where no slice is involved
464 elsif not L_Slice and not R_Slice then
466 -- The following code deals with the case of unconstrained bit packed
467 -- arrays. The problem is that the template for such arrays contains
468 -- the bounds of the actual source level array, but the copy of an
469 -- entire array requires the bounds of the underlying array. It would
470 -- be nice if the back end could take care of this, but right now it
471 -- does not know how, so if we have such a type, then we expand out
472 -- into a loop, which is inefficient but works correctly. If we don't
473 -- do this, we get the wrong length computed for the array to be
474 -- moved. The two cases we need to worry about are:
476 -- Explicit dereference of an unconstrained packed array type as in
477 -- the following example:
479 -- procedure C52 is
480 -- type BITS is array(INTEGER range <>) of BOOLEAN;
481 -- pragma PACK(BITS);
482 -- type A is access BITS;
483 -- P1,P2 : A;
484 -- begin
485 -- P1 := new BITS (1 .. 65_535);
486 -- P2 := new BITS (1 .. 65_535);
487 -- P2.ALL := P1.ALL;
488 -- end C52;
490 -- A formal parameter reference with an unconstrained bit array type
491 -- is the other case we need to worry about (here we assume the same
492 -- BITS type declared above):
494 -- procedure Write_All (File : out BITS; Contents : BITS);
495 -- begin
496 -- File.Storage := Contents;
497 -- end Write_All;
499 -- We expand to a loop in either of these two cases
501 -- Question for future thought. Another potentially more efficient
502 -- approach would be to create the actual subtype, and then do an
503 -- unchecked conversion to this actual subtype ???
505 Check_Unconstrained_Bit_Packed_Array : declare
507 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean;
508 -- Function to perform required test for the first case, above
509 -- (dereference of an unconstrained bit packed array).
511 -----------------------
512 -- Is_UBPA_Reference --
513 -----------------------
515 function Is_UBPA_Reference (Opnd : Node_Id) return Boolean is
516 Typ : constant Entity_Id := Underlying_Type (Etype (Opnd));
517 P_Type : Entity_Id;
518 Des_Type : Entity_Id;
520 begin
521 if Present (Packed_Array_Impl_Type (Typ))
522 and then Is_Array_Type (Packed_Array_Impl_Type (Typ))
523 and then not Is_Constrained (Packed_Array_Impl_Type (Typ))
524 then
525 return True;
527 elsif Nkind (Opnd) = N_Explicit_Dereference then
528 P_Type := Underlying_Type (Etype (Prefix (Opnd)));
530 if not Is_Access_Type (P_Type) then
531 return False;
533 else
534 Des_Type := Designated_Type (P_Type);
535 return
536 Is_Bit_Packed_Array (Des_Type)
537 and then not Is_Constrained (Des_Type);
538 end if;
540 else
541 return False;
542 end if;
543 end Is_UBPA_Reference;
545 -- Start of processing for Check_Unconstrained_Bit_Packed_Array
547 begin
548 if Is_UBPA_Reference (Lhs)
549 or else
550 Is_UBPA_Reference (Rhs)
551 then
552 Loop_Required := True;
554 -- Here if we do not have the case of a reference to a bit packed
555 -- unconstrained array case. In this case gigi can most certainly
556 -- handle the assignment if a forwards move is allowed.
558 -- (could it handle the backwards case also???)
560 elsif Forwards_OK (N) then
561 return;
562 end if;
563 end Check_Unconstrained_Bit_Packed_Array;
565 -- The back end can always handle the assignment if the right side is a
566 -- string literal (note that overlap is definitely impossible in this
567 -- case). If the type is packed, a string literal is always converted
568 -- into an aggregate, except in the case of a null slice, for which no
569 -- aggregate can be written. In that case, rewrite the assignment as a
570 -- null statement, a length check has already been emitted to verify
571 -- that the range of the left-hand side is empty.
573 -- Note that this code is not executed if we have an assignment of a
574 -- string literal to a non-bit aligned component of a record, a case
575 -- which cannot be handled by the backend.
577 elsif Nkind (Rhs) = N_String_Literal then
578 if String_Length (Strval (Rhs)) = 0
579 and then Is_Bit_Packed_Array (L_Type)
580 then
581 Rewrite (N, Make_Null_Statement (Loc));
582 Analyze (N);
583 end if;
585 return;
587 -- If either operand is bit packed, then we need a loop, since we can't
588 -- be sure that the slice is byte aligned. Similarly, if either operand
589 -- is a possibly unaligned slice, then we need a loop (since the back
590 -- end cannot handle unaligned slices).
592 elsif Is_Bit_Packed_Array (L_Type)
593 or else Is_Bit_Packed_Array (R_Type)
594 or else Is_Possibly_Unaligned_Slice (Lhs)
595 or else Is_Possibly_Unaligned_Slice (Rhs)
596 then
597 Loop_Required := True;
599 -- If we are not bit-packed, and we have only one slice, then no overlap
600 -- is possible except in the parameter case, so we can let the back end
601 -- handle things.
603 elsif not (L_Slice and R_Slice) then
604 if Forwards_OK (N) then
605 return;
606 end if;
607 end if;
609 -- If the right-hand side is a string literal, introduce a temporary for
610 -- it, for use in the generated loop that will follow.
612 if Nkind (Rhs) = N_String_Literal then
613 declare
614 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Rhs);
615 Decl : Node_Id;
617 begin
618 Decl :=
619 Make_Object_Declaration (Loc,
620 Defining_Identifier => Temp,
621 Object_Definition => New_Occurrence_Of (L_Type, Loc),
622 Expression => Relocate_Node (Rhs));
624 Insert_Action (N, Decl);
625 Rewrite (Rhs, New_Occurrence_Of (Temp, Loc));
626 R_Type := Etype (Temp);
627 end;
628 end if;
630 -- Come here to complete the analysis
632 -- Loop_Required: Set to True if we know that a loop is required
633 -- regardless of overlap considerations.
635 -- Forwards_OK: Set to False if we already know that a forwards
636 -- move is not safe, else set to True.
638 -- Backwards_OK: Set to False if we already know that a backwards
639 -- move is not safe, else set to True
641 -- Our task at this stage is to complete the overlap analysis, which can
642 -- result in possibly setting Forwards_OK or Backwards_OK to False, and
643 -- then generating the final code, either by deciding that it is OK
644 -- after all to let Gigi handle it, or by generating appropriate code
645 -- in the front end.
647 declare
648 L_Index_Typ : constant Node_Id := Etype (First_Index (L_Type));
649 R_Index_Typ : constant Node_Id := Etype (First_Index (R_Type));
651 Left_Lo : constant Node_Id := Type_Low_Bound (L_Index_Typ);
652 Left_Hi : constant Node_Id := Type_High_Bound (L_Index_Typ);
653 Right_Lo : constant Node_Id := Type_Low_Bound (R_Index_Typ);
654 Right_Hi : constant Node_Id := Type_High_Bound (R_Index_Typ);
656 Act_L_Array : Node_Id;
657 Act_R_Array : Node_Id;
659 Cleft_Lo : Node_Id;
660 Cright_Lo : Node_Id;
661 Condition : Node_Id;
663 Cresult : Compare_Result;
665 begin
666 -- Get the expressions for the arrays. If we are dealing with a
667 -- private type, then convert to the underlying type. We can do
668 -- direct assignments to an array that is a private type, but we
669 -- cannot assign to elements of the array without this extra
670 -- unchecked conversion.
672 -- Note: We propagate Parent to the conversion nodes to generate
673 -- a well-formed subtree.
675 if Nkind (Act_Lhs) = N_Slice then
676 Larray := Prefix (Act_Lhs);
677 else
678 Larray := Act_Lhs;
680 if Is_Private_Type (Etype (Larray)) then
681 declare
682 Par : constant Node_Id := Parent (Larray);
683 begin
684 Larray :=
685 Unchecked_Convert_To
686 (Underlying_Type (Etype (Larray)), Larray);
687 Set_Parent (Larray, Par);
688 end;
689 end if;
690 end if;
692 if Nkind (Act_Rhs) = N_Slice then
693 Rarray := Prefix (Act_Rhs);
694 else
695 Rarray := Act_Rhs;
697 if Is_Private_Type (Etype (Rarray)) then
698 declare
699 Par : constant Node_Id := Parent (Rarray);
700 begin
701 Rarray :=
702 Unchecked_Convert_To
703 (Underlying_Type (Etype (Rarray)), Rarray);
704 Set_Parent (Rarray, Par);
705 end;
706 end if;
707 end if;
709 -- If both sides are slices, we must figure out whether it is safe
710 -- to do the move in one direction or the other. It is always safe
711 -- if there is a change of representation since obviously two arrays
712 -- with different representations cannot possibly overlap.
714 if (not Crep) and L_Slice and R_Slice then
715 Act_L_Array := Get_Referenced_Object (Prefix (Act_Lhs));
716 Act_R_Array := Get_Referenced_Object (Prefix (Act_Rhs));
718 -- If both left and right hand arrays are entity names, and refer
719 -- to different entities, then we know that the move is safe (the
720 -- two storage areas are completely disjoint).
722 if Is_Entity_Name (Act_L_Array)
723 and then Is_Entity_Name (Act_R_Array)
724 and then Entity (Act_L_Array) /= Entity (Act_R_Array)
725 then
726 null;
728 -- Otherwise, we assume the worst, which is that the two arrays
729 -- are the same array. There is no need to check if we know that
730 -- is the case, because if we don't know it, we still have to
731 -- assume it.
733 -- Generally if the same array is involved, then we have an
734 -- overlapping case. We will have to really assume the worst (i.e.
735 -- set neither of the OK flags) unless we can determine the lower
736 -- or upper bounds at compile time and compare them.
738 else
739 Cresult :=
740 Compile_Time_Compare
741 (Left_Lo, Right_Lo, Assume_Valid => True);
743 if Cresult = Unknown then
744 Cresult :=
745 Compile_Time_Compare
746 (Left_Hi, Right_Hi, Assume_Valid => True);
747 end if;
749 case Cresult is
750 when LT | LE | EQ => Set_Backwards_OK (N, False);
751 when GT | GE => Set_Forwards_OK (N, False);
752 when NE | Unknown => Set_Backwards_OK (N, False);
753 Set_Forwards_OK (N, False);
754 end case;
755 end if;
756 end if;
758 -- If after that analysis Loop_Required is False, meaning that we
759 -- have not discovered some non-overlap reason for requiring a loop,
760 -- then the outcome depends on the capabilities of the back end.
762 if not Loop_Required then
764 -- The GCC back end can deal with all cases of overlap by falling
765 -- back to memmove if it cannot use a more efficient approach.
767 if VM_Target = No_VM and not AAMP_On_Target then
768 return;
770 -- Assume other back ends can handle it if Forwards_OK is set
772 elsif Forwards_OK (N) then
773 return;
775 -- If Forwards_OK is not set, the back end will need something
776 -- like memmove to handle the move. For now, this processing is
777 -- activated using the .s debug flag (-gnatd.s).
779 elsif Debug_Flag_Dot_S then
780 return;
781 end if;
782 end if;
784 -- At this stage we have to generate an explicit loop, and we have
785 -- the following cases:
787 -- Forwards_OK = True
789 -- Rnn : right_index := right_index'First;
790 -- for Lnn in left-index loop
791 -- left (Lnn) := right (Rnn);
792 -- Rnn := right_index'Succ (Rnn);
793 -- end loop;
795 -- Note: the above code MUST be analyzed with checks off, because
796 -- otherwise the Succ could overflow. But in any case this is more
797 -- efficient.
799 -- Forwards_OK = False, Backwards_OK = True
801 -- Rnn : right_index := right_index'Last;
802 -- for Lnn in reverse left-index loop
803 -- left (Lnn) := right (Rnn);
804 -- Rnn := right_index'Pred (Rnn);
805 -- end loop;
807 -- Note: the above code MUST be analyzed with checks off, because
808 -- otherwise the Pred could overflow. But in any case this is more
809 -- efficient.
811 -- Forwards_OK = Backwards_OK = False
813 -- This only happens if we have the same array on each side. It is
814 -- possible to create situations using overlays that violate this,
815 -- but we simply do not promise to get this "right" in this case.
817 -- There are two possible subcases. If the No_Implicit_Conditionals
818 -- restriction is set, then we generate the following code:
820 -- declare
821 -- T : constant <operand-type> := rhs;
822 -- begin
823 -- lhs := T;
824 -- end;
826 -- If implicit conditionals are permitted, then we generate:
828 -- if Left_Lo <= Right_Lo then
829 -- <code for Forwards_OK = True above>
830 -- else
831 -- <code for Backwards_OK = True above>
832 -- end if;
834 -- In order to detect possible aliasing, we examine the renamed
835 -- expression when the source or target is a renaming. However,
836 -- the renaming may be intended to capture an address that may be
837 -- affected by subsequent code, and therefore we must recover
838 -- the actual entity for the expansion that follows, not the
839 -- object it renames. In particular, if source or target designate
840 -- a portion of a dynamically allocated object, the pointer to it
841 -- may be reassigned but the renaming preserves the proper location.
843 if Is_Entity_Name (Rhs)
844 and then
845 Nkind (Parent (Entity (Rhs))) = N_Object_Renaming_Declaration
846 and then Nkind (Act_Rhs) = N_Slice
847 then
848 Rarray := Rhs;
849 end if;
851 if Is_Entity_Name (Lhs)
852 and then
853 Nkind (Parent (Entity (Lhs))) = N_Object_Renaming_Declaration
854 and then Nkind (Act_Lhs) = N_Slice
855 then
856 Larray := Lhs;
857 end if;
859 -- Cases where either Forwards_OK or Backwards_OK is true
861 if Forwards_OK (N) or else Backwards_OK (N) then
862 if Needs_Finalization (Component_Type (L_Type))
863 and then Base_Type (L_Type) = Base_Type (R_Type)
864 and then Ndim = 1
865 and then not No_Ctrl_Actions (N)
866 then
867 declare
868 Proc : constant Entity_Id :=
869 TSS (Base_Type (L_Type), TSS_Slice_Assign);
870 Actuals : List_Id;
872 begin
873 Apply_Dereference (Larray);
874 Apply_Dereference (Rarray);
875 Actuals := New_List (
876 Duplicate_Subexpr (Larray, Name_Req => True),
877 Duplicate_Subexpr (Rarray, Name_Req => True),
878 Duplicate_Subexpr (Left_Lo, Name_Req => True),
879 Duplicate_Subexpr (Left_Hi, Name_Req => True),
880 Duplicate_Subexpr (Right_Lo, Name_Req => True),
881 Duplicate_Subexpr (Right_Hi, Name_Req => True));
883 Append_To (Actuals,
884 New_Occurrence_Of (
885 Boolean_Literals (not Forwards_OK (N)), Loc));
887 Rewrite (N,
888 Make_Procedure_Call_Statement (Loc,
889 Name => New_Occurrence_Of (Proc, Loc),
890 Parameter_Associations => Actuals));
891 end;
893 else
894 Rewrite (N,
895 Expand_Assign_Array_Loop
896 (N, Larray, Rarray, L_Type, R_Type, Ndim,
897 Rev => not Forwards_OK (N)));
898 end if;
900 -- Case of both are false with No_Implicit_Conditionals
902 elsif Restriction_Active (No_Implicit_Conditionals) then
903 declare
904 T : constant Entity_Id :=
905 Make_Defining_Identifier (Loc, Chars => Name_T);
907 begin
908 Rewrite (N,
909 Make_Block_Statement (Loc,
910 Declarations => New_List (
911 Make_Object_Declaration (Loc,
912 Defining_Identifier => T,
913 Constant_Present => True,
914 Object_Definition =>
915 New_Occurrence_Of (Etype (Rhs), Loc),
916 Expression => Relocate_Node (Rhs))),
918 Handled_Statement_Sequence =>
919 Make_Handled_Sequence_Of_Statements (Loc,
920 Statements => New_List (
921 Make_Assignment_Statement (Loc,
922 Name => Relocate_Node (Lhs),
923 Expression => New_Occurrence_Of (T, Loc))))));
924 end;
926 -- Case of both are false with implicit conditionals allowed
928 else
929 -- Before we generate this code, we must ensure that the left and
930 -- right side array types are defined. They may be itypes, and we
931 -- cannot let them be defined inside the if, since the first use
932 -- in the then may not be executed.
934 Ensure_Defined (L_Type, N);
935 Ensure_Defined (R_Type, N);
937 -- We normally compare addresses to find out which way round to
938 -- do the loop, since this is reliable, and handles the cases of
939 -- parameters, conversions etc. But we can't do that in the bit
940 -- packed case or the VM case, because addresses don't work there.
942 if not Is_Bit_Packed_Array (L_Type) and then VM_Target = No_VM then
943 Condition :=
944 Make_Op_Le (Loc,
945 Left_Opnd =>
946 Unchecked_Convert_To (RTE (RE_Integer_Address),
947 Make_Attribute_Reference (Loc,
948 Prefix =>
949 Make_Indexed_Component (Loc,
950 Prefix =>
951 Duplicate_Subexpr_Move_Checks (Larray, True),
952 Expressions => New_List (
953 Make_Attribute_Reference (Loc,
954 Prefix =>
955 New_Occurrence_Of
956 (L_Index_Typ, Loc),
957 Attribute_Name => Name_First))),
958 Attribute_Name => Name_Address)),
960 Right_Opnd =>
961 Unchecked_Convert_To (RTE (RE_Integer_Address),
962 Make_Attribute_Reference (Loc,
963 Prefix =>
964 Make_Indexed_Component (Loc,
965 Prefix =>
966 Duplicate_Subexpr_Move_Checks (Rarray, True),
967 Expressions => New_List (
968 Make_Attribute_Reference (Loc,
969 Prefix =>
970 New_Occurrence_Of
971 (R_Index_Typ, Loc),
972 Attribute_Name => Name_First))),
973 Attribute_Name => Name_Address)));
975 -- For the bit packed and VM cases we use the bounds. That's OK,
976 -- because we don't have to worry about parameters, since they
977 -- cannot cause overlap. Perhaps we should worry about weird slice
978 -- conversions ???
980 else
981 -- Copy the bounds
983 Cleft_Lo := New_Copy_Tree (Left_Lo);
984 Cright_Lo := New_Copy_Tree (Right_Lo);
986 -- If the types do not match we add an implicit conversion
987 -- here to ensure proper match
989 if Etype (Left_Lo) /= Etype (Right_Lo) then
990 Cright_Lo :=
991 Unchecked_Convert_To (Etype (Left_Lo), Cright_Lo);
992 end if;
994 -- Reset the Analyzed flag, because the bounds of the index
995 -- type itself may be universal, and must must be reanalyzed
996 -- to acquire the proper type for the back end.
998 Set_Analyzed (Cleft_Lo, False);
999 Set_Analyzed (Cright_Lo, False);
1001 Condition :=
1002 Make_Op_Le (Loc,
1003 Left_Opnd => Cleft_Lo,
1004 Right_Opnd => Cright_Lo);
1005 end if;
1007 if Needs_Finalization (Component_Type (L_Type))
1008 and then Base_Type (L_Type) = Base_Type (R_Type)
1009 and then Ndim = 1
1010 and then not No_Ctrl_Actions (N)
1011 then
1013 -- Call TSS procedure for array assignment, passing the
1014 -- explicit bounds of right and left hand sides.
1016 declare
1017 Proc : constant Entity_Id :=
1018 TSS (Base_Type (L_Type), TSS_Slice_Assign);
1019 Actuals : List_Id;
1021 begin
1022 Apply_Dereference (Larray);
1023 Apply_Dereference (Rarray);
1024 Actuals := New_List (
1025 Duplicate_Subexpr (Larray, Name_Req => True),
1026 Duplicate_Subexpr (Rarray, Name_Req => True),
1027 Duplicate_Subexpr (Left_Lo, Name_Req => True),
1028 Duplicate_Subexpr (Left_Hi, Name_Req => True),
1029 Duplicate_Subexpr (Right_Lo, Name_Req => True),
1030 Duplicate_Subexpr (Right_Hi, Name_Req => True));
1032 Append_To (Actuals,
1033 Make_Op_Not (Loc,
1034 Right_Opnd => Condition));
1036 Rewrite (N,
1037 Make_Procedure_Call_Statement (Loc,
1038 Name => New_Occurrence_Of (Proc, Loc),
1039 Parameter_Associations => Actuals));
1040 end;
1042 else
1043 Rewrite (N,
1044 Make_Implicit_If_Statement (N,
1045 Condition => Condition,
1047 Then_Statements => New_List (
1048 Expand_Assign_Array_Loop
1049 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1050 Rev => False)),
1052 Else_Statements => New_List (
1053 Expand_Assign_Array_Loop
1054 (N, Larray, Rarray, L_Type, R_Type, Ndim,
1055 Rev => True))));
1056 end if;
1057 end if;
1059 Analyze (N, Suppress => All_Checks);
1060 end;
1062 exception
1063 when RE_Not_Available =>
1064 return;
1065 end Expand_Assign_Array;
1067 ------------------------------
1068 -- Expand_Assign_Array_Loop --
1069 ------------------------------
1071 -- The following is an example of the loop generated for the case of a
1072 -- two-dimensional array:
1074 -- declare
1075 -- R2b : Tm1X1 := 1;
1076 -- begin
1077 -- for L1b in 1 .. 100 loop
1078 -- declare
1079 -- R4b : Tm1X2 := 1;
1080 -- begin
1081 -- for L3b in 1 .. 100 loop
1082 -- vm1 (L1b, L3b) := vm2 (R2b, R4b);
1083 -- R4b := Tm1X2'succ(R4b);
1084 -- end loop;
1085 -- end;
1086 -- R2b := Tm1X1'succ(R2b);
1087 -- end loop;
1088 -- end;
1090 -- Here Rev is False, and Tm1Xn are the subscript types for the right hand
1091 -- side. The declarations of R2b and R4b are inserted before the original
1092 -- assignment statement.
1094 function Expand_Assign_Array_Loop
1095 (N : Node_Id;
1096 Larray : Entity_Id;
1097 Rarray : Entity_Id;
1098 L_Type : Entity_Id;
1099 R_Type : Entity_Id;
1100 Ndim : Pos;
1101 Rev : Boolean) return Node_Id
1103 Loc : constant Source_Ptr := Sloc (N);
1105 Lnn : array (1 .. Ndim) of Entity_Id;
1106 Rnn : array (1 .. Ndim) of Entity_Id;
1107 -- Entities used as subscripts on left and right sides
1109 L_Index_Type : array (1 .. Ndim) of Entity_Id;
1110 R_Index_Type : array (1 .. Ndim) of Entity_Id;
1111 -- Left and right index types
1113 Assign : Node_Id;
1115 F_Or_L : Name_Id;
1116 S_Or_P : Name_Id;
1118 function Build_Step (J : Nat) return Node_Id;
1119 -- The increment step for the index of the right-hand side is written
1120 -- as an attribute reference (Succ or Pred). This function returns
1121 -- the corresponding node, which is placed at the end of the loop body.
1123 ----------------
1124 -- Build_Step --
1125 ----------------
1127 function Build_Step (J : Nat) return Node_Id is
1128 Step : Node_Id;
1129 Lim : Name_Id;
1131 begin
1132 if Rev then
1133 Lim := Name_First;
1134 else
1135 Lim := Name_Last;
1136 end if;
1138 Step :=
1139 Make_Assignment_Statement (Loc,
1140 Name => New_Occurrence_Of (Rnn (J), Loc),
1141 Expression =>
1142 Make_Attribute_Reference (Loc,
1143 Prefix =>
1144 New_Occurrence_Of (R_Index_Type (J), Loc),
1145 Attribute_Name => S_Or_P,
1146 Expressions => New_List (
1147 New_Occurrence_Of (Rnn (J), Loc))));
1149 -- Note that on the last iteration of the loop, the index is increased
1150 -- (or decreased) past the corresponding bound. This is consistent with
1151 -- the C semantics of the back-end, where such an off-by-one value on a
1152 -- dead index variable is OK. However, in CodePeer mode this leads to
1153 -- spurious warnings, and thus we place a guard around the attribute
1154 -- reference. For obvious reasons we only do this for CodePeer.
1156 if CodePeer_Mode then
1157 Step :=
1158 Make_If_Statement (Loc,
1159 Condition =>
1160 Make_Op_Ne (Loc,
1161 Left_Opnd => New_Occurrence_Of (Lnn (J), Loc),
1162 Right_Opnd =>
1163 Make_Attribute_Reference (Loc,
1164 Prefix => New_Occurrence_Of (L_Index_Type (J), Loc),
1165 Attribute_Name => Lim)),
1166 Then_Statements => New_List (Step));
1167 end if;
1169 return Step;
1170 end Build_Step;
1172 -- Start of processing for Expand_Assign_Array_Loop
1174 begin
1175 if Rev then
1176 F_Or_L := Name_Last;
1177 S_Or_P := Name_Pred;
1178 else
1179 F_Or_L := Name_First;
1180 S_Or_P := Name_Succ;
1181 end if;
1183 -- Setup index types and subscript entities
1185 declare
1186 L_Index : Node_Id;
1187 R_Index : Node_Id;
1189 begin
1190 L_Index := First_Index (L_Type);
1191 R_Index := First_Index (R_Type);
1193 for J in 1 .. Ndim loop
1194 Lnn (J) := Make_Temporary (Loc, 'L');
1195 Rnn (J) := Make_Temporary (Loc, 'R');
1197 L_Index_Type (J) := Etype (L_Index);
1198 R_Index_Type (J) := Etype (R_Index);
1200 Next_Index (L_Index);
1201 Next_Index (R_Index);
1202 end loop;
1203 end;
1205 -- Now construct the assignment statement
1207 declare
1208 ExprL : constant List_Id := New_List;
1209 ExprR : constant List_Id := New_List;
1211 begin
1212 for J in 1 .. Ndim loop
1213 Append_To (ExprL, New_Occurrence_Of (Lnn (J), Loc));
1214 Append_To (ExprR, New_Occurrence_Of (Rnn (J), Loc));
1215 end loop;
1217 Assign :=
1218 Make_Assignment_Statement (Loc,
1219 Name =>
1220 Make_Indexed_Component (Loc,
1221 Prefix => Duplicate_Subexpr (Larray, Name_Req => True),
1222 Expressions => ExprL),
1223 Expression =>
1224 Make_Indexed_Component (Loc,
1225 Prefix => Duplicate_Subexpr (Rarray, Name_Req => True),
1226 Expressions => ExprR));
1228 -- We set assignment OK, since there are some cases, e.g. in object
1229 -- declarations, where we are actually assigning into a constant.
1230 -- If there really is an illegality, it was caught long before now,
1231 -- and was flagged when the original assignment was analyzed.
1233 Set_Assignment_OK (Name (Assign));
1235 -- Propagate the No_Ctrl_Actions flag to individual assignments
1237 Set_No_Ctrl_Actions (Assign, No_Ctrl_Actions (N));
1238 end;
1240 -- Now construct the loop from the inside out, with the last subscript
1241 -- varying most rapidly. Note that Assign is first the raw assignment
1242 -- statement, and then subsequently the loop that wraps it up.
1244 for J in reverse 1 .. Ndim loop
1245 Assign :=
1246 Make_Block_Statement (Loc,
1247 Declarations => New_List (
1248 Make_Object_Declaration (Loc,
1249 Defining_Identifier => Rnn (J),
1250 Object_Definition =>
1251 New_Occurrence_Of (R_Index_Type (J), Loc),
1252 Expression =>
1253 Make_Attribute_Reference (Loc,
1254 Prefix => New_Occurrence_Of (R_Index_Type (J), Loc),
1255 Attribute_Name => F_Or_L))),
1257 Handled_Statement_Sequence =>
1258 Make_Handled_Sequence_Of_Statements (Loc,
1259 Statements => New_List (
1260 Make_Implicit_Loop_Statement (N,
1261 Iteration_Scheme =>
1262 Make_Iteration_Scheme (Loc,
1263 Loop_Parameter_Specification =>
1264 Make_Loop_Parameter_Specification (Loc,
1265 Defining_Identifier => Lnn (J),
1266 Reverse_Present => Rev,
1267 Discrete_Subtype_Definition =>
1268 New_Occurrence_Of (L_Index_Type (J), Loc))),
1270 Statements => New_List (Assign, Build_Step (J))))));
1271 end loop;
1273 return Assign;
1274 end Expand_Assign_Array_Loop;
1276 --------------------------
1277 -- Expand_Assign_Record --
1278 --------------------------
1280 procedure Expand_Assign_Record (N : Node_Id) is
1281 Lhs : constant Node_Id := Name (N);
1282 Rhs : Node_Id := Expression (N);
1283 L_Typ : constant Entity_Id := Base_Type (Etype (Lhs));
1285 begin
1286 -- If change of representation, then extract the real right hand side
1287 -- from the type conversion, and proceed with component-wise assignment,
1288 -- since the two types are not the same as far as the back end is
1289 -- concerned.
1291 if Change_Of_Representation (N) then
1292 Rhs := Expression (Rhs);
1294 -- If this may be a case of a large bit aligned component, then proceed
1295 -- with component-wise assignment, to avoid possible clobbering of other
1296 -- components sharing bits in the first or last byte of the component to
1297 -- be assigned.
1299 elsif Possible_Bit_Aligned_Component (Lhs)
1301 Possible_Bit_Aligned_Component (Rhs)
1302 then
1303 null;
1305 -- If we have a tagged type that has a complete record representation
1306 -- clause, we must do we must do component-wise assignments, since child
1307 -- types may have used gaps for their components, and we might be
1308 -- dealing with a view conversion.
1310 elsif Is_Fully_Repped_Tagged_Type (L_Typ) then
1311 null;
1313 -- If neither condition met, then nothing special to do, the back end
1314 -- can handle assignment of the entire component as a single entity.
1316 else
1317 return;
1318 end if;
1320 -- At this stage we know that we must do a component wise assignment
1322 declare
1323 Loc : constant Source_Ptr := Sloc (N);
1324 R_Typ : constant Entity_Id := Base_Type (Etype (Rhs));
1325 Decl : constant Node_Id := Declaration_Node (R_Typ);
1326 RDef : Node_Id;
1327 F : Entity_Id;
1329 function Find_Component
1330 (Typ : Entity_Id;
1331 Comp : Entity_Id) return Entity_Id;
1332 -- Find the component with the given name in the underlying record
1333 -- declaration for Typ. We need to use the actual entity because the
1334 -- type may be private and resolution by identifier alone would fail.
1336 function Make_Component_List_Assign
1337 (CL : Node_Id;
1338 U_U : Boolean := False) return List_Id;
1339 -- Returns a sequence of statements to assign the components that
1340 -- are referenced in the given component list. The flag U_U is
1341 -- used to force the usage of the inferred value of the variant
1342 -- part expression as the switch for the generated case statement.
1344 function Make_Field_Assign
1345 (C : Entity_Id;
1346 U_U : Boolean := False) return Node_Id;
1347 -- Given C, the entity for a discriminant or component, build an
1348 -- assignment for the corresponding field values. The flag U_U
1349 -- signals the presence of an Unchecked_Union and forces the usage
1350 -- of the inferred discriminant value of C as the right hand side
1351 -- of the assignment.
1353 function Make_Field_Assigns (CI : List_Id) return List_Id;
1354 -- Given CI, a component items list, construct series of statements
1355 -- for fieldwise assignment of the corresponding components.
1357 --------------------
1358 -- Find_Component --
1359 --------------------
1361 function Find_Component
1362 (Typ : Entity_Id;
1363 Comp : Entity_Id) return Entity_Id
1365 Utyp : constant Entity_Id := Underlying_Type (Typ);
1366 C : Entity_Id;
1368 begin
1369 C := First_Entity (Utyp);
1370 while Present (C) loop
1371 if Chars (C) = Chars (Comp) then
1372 return C;
1373 end if;
1375 Next_Entity (C);
1376 end loop;
1378 raise Program_Error;
1379 end Find_Component;
1381 --------------------------------
1382 -- Make_Component_List_Assign --
1383 --------------------------------
1385 function Make_Component_List_Assign
1386 (CL : Node_Id;
1387 U_U : Boolean := False) return List_Id
1389 CI : constant List_Id := Component_Items (CL);
1390 VP : constant Node_Id := Variant_Part (CL);
1392 Alts : List_Id;
1393 DC : Node_Id;
1394 DCH : List_Id;
1395 Expr : Node_Id;
1396 Result : List_Id;
1397 V : Node_Id;
1399 begin
1400 Result := Make_Field_Assigns (CI);
1402 if Present (VP) then
1403 V := First_Non_Pragma (Variants (VP));
1404 Alts := New_List;
1405 while Present (V) loop
1406 DCH := New_List;
1407 DC := First (Discrete_Choices (V));
1408 while Present (DC) loop
1409 Append_To (DCH, New_Copy_Tree (DC));
1410 Next (DC);
1411 end loop;
1413 Append_To (Alts,
1414 Make_Case_Statement_Alternative (Loc,
1415 Discrete_Choices => DCH,
1416 Statements =>
1417 Make_Component_List_Assign (Component_List (V))));
1418 Next_Non_Pragma (V);
1419 end loop;
1421 -- If we have an Unchecked_Union, use the value of the inferred
1422 -- discriminant of the variant part expression as the switch
1423 -- for the case statement. The case statement may later be
1424 -- folded.
1426 if U_U then
1427 Expr :=
1428 New_Copy (Get_Discriminant_Value (
1429 Entity (Name (VP)),
1430 Etype (Rhs),
1431 Discriminant_Constraint (Etype (Rhs))));
1432 else
1433 Expr :=
1434 Make_Selected_Component (Loc,
1435 Prefix => Duplicate_Subexpr (Rhs),
1436 Selector_Name =>
1437 Make_Identifier (Loc, Chars (Name (VP))));
1438 end if;
1440 Append_To (Result,
1441 Make_Case_Statement (Loc,
1442 Expression => Expr,
1443 Alternatives => Alts));
1444 end if;
1446 return Result;
1447 end Make_Component_List_Assign;
1449 -----------------------
1450 -- Make_Field_Assign --
1451 -----------------------
1453 function Make_Field_Assign
1454 (C : Entity_Id;
1455 U_U : Boolean := False) return Node_Id
1457 A : Node_Id;
1458 Expr : Node_Id;
1460 begin
1461 -- In the case of an Unchecked_Union, use the discriminant
1462 -- constraint value as on the right hand side of the assignment.
1464 if U_U then
1465 Expr :=
1466 New_Copy (Get_Discriminant_Value (C,
1467 Etype (Rhs),
1468 Discriminant_Constraint (Etype (Rhs))));
1469 else
1470 Expr :=
1471 Make_Selected_Component (Loc,
1472 Prefix => Duplicate_Subexpr (Rhs),
1473 Selector_Name => New_Occurrence_Of (C, Loc));
1474 end if;
1476 A :=
1477 Make_Assignment_Statement (Loc,
1478 Name =>
1479 Make_Selected_Component (Loc,
1480 Prefix => Duplicate_Subexpr (Lhs),
1481 Selector_Name =>
1482 New_Occurrence_Of (Find_Component (L_Typ, C), Loc)),
1483 Expression => Expr);
1485 -- Set Assignment_OK, so discriminants can be assigned
1487 Set_Assignment_OK (Name (A), True);
1489 if Componentwise_Assignment (N)
1490 and then Nkind (Name (A)) = N_Selected_Component
1491 and then Chars (Selector_Name (Name (A))) = Name_uParent
1492 then
1493 Set_Componentwise_Assignment (A);
1494 end if;
1496 return A;
1497 end Make_Field_Assign;
1499 ------------------------
1500 -- Make_Field_Assigns --
1501 ------------------------
1503 function Make_Field_Assigns (CI : List_Id) return List_Id is
1504 Item : Node_Id;
1505 Result : List_Id;
1507 begin
1508 Item := First (CI);
1509 Result := New_List;
1511 while Present (Item) loop
1513 -- Look for components, but exclude _tag field assignment if
1514 -- the special Componentwise_Assignment flag is set.
1516 if Nkind (Item) = N_Component_Declaration
1517 and then not (Is_Tag (Defining_Identifier (Item))
1518 and then Componentwise_Assignment (N))
1519 then
1520 Append_To
1521 (Result, Make_Field_Assign (Defining_Identifier (Item)));
1522 end if;
1524 Next (Item);
1525 end loop;
1527 return Result;
1528 end Make_Field_Assigns;
1530 -- Start of processing for Expand_Assign_Record
1532 begin
1533 -- Note that we use the base types for this processing. This results
1534 -- in some extra work in the constrained case, but the change of
1535 -- representation case is so unusual that it is not worth the effort.
1537 -- First copy the discriminants. This is done unconditionally. It
1538 -- is required in the unconstrained left side case, and also in the
1539 -- case where this assignment was constructed during the expansion
1540 -- of a type conversion (since initialization of discriminants is
1541 -- suppressed in this case). It is unnecessary but harmless in
1542 -- other cases.
1544 if Has_Discriminants (L_Typ) then
1545 F := First_Discriminant (R_Typ);
1546 while Present (F) loop
1548 -- If we are expanding the initialization of a derived record
1549 -- that constrains or renames discriminants of the parent, we
1550 -- must use the corresponding discriminant in the parent.
1552 declare
1553 CF : Entity_Id;
1555 begin
1556 if Inside_Init_Proc
1557 and then Present (Corresponding_Discriminant (F))
1558 then
1559 CF := Corresponding_Discriminant (F);
1560 else
1561 CF := F;
1562 end if;
1564 if Is_Unchecked_Union (Base_Type (R_Typ)) then
1566 -- Within an initialization procedure this is the
1567 -- assignment to an unchecked union component, in which
1568 -- case there is no discriminant to initialize.
1570 if Inside_Init_Proc then
1571 null;
1573 else
1574 -- The assignment is part of a conversion from a
1575 -- derived unchecked union type with an inferable
1576 -- discriminant, to a parent type.
1578 Insert_Action (N, Make_Field_Assign (CF, True));
1579 end if;
1581 else
1582 Insert_Action (N, Make_Field_Assign (CF));
1583 end if;
1585 Next_Discriminant (F);
1586 end;
1587 end loop;
1588 end if;
1590 -- We know the underlying type is a record, but its current view
1591 -- may be private. We must retrieve the usable record declaration.
1593 if Nkind_In (Decl, N_Private_Type_Declaration,
1594 N_Private_Extension_Declaration)
1595 and then Present (Full_View (R_Typ))
1596 then
1597 RDef := Type_Definition (Declaration_Node (Full_View (R_Typ)));
1598 else
1599 RDef := Type_Definition (Decl);
1600 end if;
1602 if Nkind (RDef) = N_Derived_Type_Definition then
1603 RDef := Record_Extension_Part (RDef);
1604 end if;
1606 if Nkind (RDef) = N_Record_Definition
1607 and then Present (Component_List (RDef))
1608 then
1609 if Is_Unchecked_Union (R_Typ) then
1610 Insert_Actions (N,
1611 Make_Component_List_Assign (Component_List (RDef), True));
1612 else
1613 Insert_Actions
1614 (N, Make_Component_List_Assign (Component_List (RDef)));
1615 end if;
1617 Rewrite (N, Make_Null_Statement (Loc));
1618 end if;
1619 end;
1620 end Expand_Assign_Record;
1622 -----------------------------------
1623 -- Expand_N_Assignment_Statement --
1624 -----------------------------------
1626 -- This procedure implements various cases where an assignment statement
1627 -- cannot just be passed on to the back end in untransformed state.
1629 procedure Expand_N_Assignment_Statement (N : Node_Id) is
1630 GM : constant Ghost_Mode_Type := Ghost_Mode;
1632 procedure Restore_Globals;
1633 -- Restore the values of all saved global variables
1635 ---------------------
1636 -- Restore_Globals --
1637 ---------------------
1639 procedure Restore_Globals is
1640 begin
1641 Ghost_Mode := GM;
1642 end Restore_Globals;
1644 -- Local variables
1646 Crep : constant Boolean := Change_Of_Representation (N);
1647 Lhs : constant Node_Id := Name (N);
1648 Loc : constant Source_Ptr := Sloc (N);
1649 Rhs : constant Node_Id := Expression (N);
1650 Typ : constant Entity_Id := Underlying_Type (Etype (Lhs));
1651 Exp : Node_Id;
1653 -- Start of processing for Expand_N_Assignment_Statement
1655 begin
1656 -- The assignment statement may be Ghost if the left hand side is Ghost.
1657 -- Set the mode now to ensure that any nodes generated during expansion
1658 -- are properly flagged as ignored Ghost.
1660 Set_Ghost_Mode (N);
1662 -- Special case to check right away, if the Componentwise_Assignment
1663 -- flag is set, this is a reanalysis from the expansion of the primitive
1664 -- assignment procedure for a tagged type, and all we need to do is to
1665 -- expand to assignment of components, because otherwise, we would get
1666 -- infinite recursion (since this looks like a tagged assignment which
1667 -- would normally try to *call* the primitive assignment procedure).
1669 if Componentwise_Assignment (N) then
1670 Expand_Assign_Record (N);
1671 Restore_Globals;
1672 return;
1673 end if;
1675 -- Defend against invalid subscripts on left side if we are in standard
1676 -- validity checking mode. No need to do this if we are checking all
1677 -- subscripts.
1679 -- Note that we do this right away, because there are some early return
1680 -- paths in this procedure, and this is required on all paths.
1682 if Validity_Checks_On
1683 and then Validity_Check_Default
1684 and then not Validity_Check_Subscripts
1685 then
1686 Check_Valid_Lvalue_Subscripts (Lhs);
1687 end if;
1689 -- Ada 2005 (AI-327): Handle assignment to priority of protected object
1691 -- Rewrite an assignment to X'Priority into a run-time call
1693 -- For example: X'Priority := New_Prio_Expr;
1694 -- ...is expanded into Set_Ceiling (X._Object, New_Prio_Expr);
1696 -- Note that although X'Priority is notionally an object, it is quite
1697 -- deliberately not defined as an aliased object in the RM. This means
1698 -- that it works fine to rewrite it as a call, without having to worry
1699 -- about complications that would other arise from X'Priority'Access,
1700 -- which is illegal, because of the lack of aliasing.
1702 if Ada_Version >= Ada_2005 then
1703 declare
1704 Call : Node_Id;
1705 Conctyp : Entity_Id;
1706 Ent : Entity_Id;
1707 Subprg : Entity_Id;
1708 RT_Subprg_Name : Node_Id;
1710 begin
1711 -- Handle chains of renamings
1713 Ent := Name (N);
1714 while Nkind (Ent) in N_Has_Entity
1715 and then Present (Entity (Ent))
1716 and then Present (Renamed_Object (Entity (Ent)))
1717 loop
1718 Ent := Renamed_Object (Entity (Ent));
1719 end loop;
1721 -- The attribute Priority applied to protected objects has been
1722 -- previously expanded into a call to the Get_Ceiling run-time
1723 -- subprogram.
1725 if Nkind (Ent) = N_Function_Call
1726 and then (Entity (Name (Ent)) = RTE (RE_Get_Ceiling)
1727 or else
1728 Entity (Name (Ent)) = RTE (RO_PE_Get_Ceiling))
1729 then
1730 -- Look for the enclosing concurrent type
1732 Conctyp := Current_Scope;
1733 while not Is_Concurrent_Type (Conctyp) loop
1734 Conctyp := Scope (Conctyp);
1735 end loop;
1737 pragma Assert (Is_Protected_Type (Conctyp));
1739 -- Generate the first actual of the call
1741 Subprg := Current_Scope;
1742 while not Present (Protected_Body_Subprogram (Subprg)) loop
1743 Subprg := Scope (Subprg);
1744 end loop;
1746 -- Select the appropriate run-time call
1748 if Number_Entries (Conctyp) = 0 then
1749 RT_Subprg_Name :=
1750 New_Occurrence_Of (RTE (RE_Set_Ceiling), Loc);
1751 else
1752 RT_Subprg_Name :=
1753 New_Occurrence_Of (RTE (RO_PE_Set_Ceiling), Loc);
1754 end if;
1756 Call :=
1757 Make_Procedure_Call_Statement (Loc,
1758 Name => RT_Subprg_Name,
1759 Parameter_Associations => New_List (
1760 New_Copy_Tree (First (Parameter_Associations (Ent))),
1761 Relocate_Node (Expression (N))));
1763 Rewrite (N, Call);
1764 Analyze (N);
1766 Restore_Globals;
1767 return;
1768 end if;
1769 end;
1770 end if;
1772 -- Deal with assignment checks unless suppressed
1774 if not Suppress_Assignment_Checks (N) then
1776 -- First deal with generation of range check if required
1778 if Do_Range_Check (Rhs) then
1779 Generate_Range_Check (Rhs, Typ, CE_Range_Check_Failed);
1780 end if;
1782 -- Then generate predicate check if required
1784 Apply_Predicate_Check (Rhs, Typ);
1785 end if;
1787 -- Check for a special case where a high level transformation is
1788 -- required. If we have either of:
1790 -- P.field := rhs;
1791 -- P (sub) := rhs;
1793 -- where P is a reference to a bit packed array, then we have to unwind
1794 -- the assignment. The exact meaning of being a reference to a bit
1795 -- packed array is as follows:
1797 -- An indexed component whose prefix is a bit packed array is a
1798 -- reference to a bit packed array.
1800 -- An indexed component or selected component whose prefix is a
1801 -- reference to a bit packed array is itself a reference ot a
1802 -- bit packed array.
1804 -- The required transformation is
1806 -- Tnn : prefix_type := P;
1807 -- Tnn.field := rhs;
1808 -- P := Tnn;
1810 -- or
1812 -- Tnn : prefix_type := P;
1813 -- Tnn (subscr) := rhs;
1814 -- P := Tnn;
1816 -- Since P is going to be evaluated more than once, any subscripts
1817 -- in P must have their evaluation forced.
1819 if Nkind_In (Lhs, N_Indexed_Component, N_Selected_Component)
1820 and then Is_Ref_To_Bit_Packed_Array (Prefix (Lhs))
1821 then
1822 declare
1823 BPAR_Expr : constant Node_Id := Relocate_Node (Prefix (Lhs));
1824 BPAR_Typ : constant Entity_Id := Etype (BPAR_Expr);
1825 Tnn : constant Entity_Id :=
1826 Make_Temporary (Loc, 'T', BPAR_Expr);
1828 begin
1829 -- Insert the post assignment first, because we want to copy the
1830 -- BPAR_Expr tree before it gets analyzed in the context of the
1831 -- pre assignment. Note that we do not analyze the post assignment
1832 -- yet (we cannot till we have completed the analysis of the pre
1833 -- assignment). As usual, the analysis of this post assignment
1834 -- will happen on its own when we "run into" it after finishing
1835 -- the current assignment.
1837 Insert_After (N,
1838 Make_Assignment_Statement (Loc,
1839 Name => New_Copy_Tree (BPAR_Expr),
1840 Expression => New_Occurrence_Of (Tnn, Loc)));
1842 -- At this stage BPAR_Expr is a reference to a bit packed array
1843 -- where the reference was not expanded in the original tree,
1844 -- since it was on the left side of an assignment. But in the
1845 -- pre-assignment statement (the object definition), BPAR_Expr
1846 -- will end up on the right hand side, and must be reexpanded. To
1847 -- achieve this, we reset the analyzed flag of all selected and
1848 -- indexed components down to the actual indexed component for
1849 -- the packed array.
1851 Exp := BPAR_Expr;
1852 loop
1853 Set_Analyzed (Exp, False);
1855 if Nkind_In
1856 (Exp, N_Selected_Component, N_Indexed_Component)
1857 then
1858 Exp := Prefix (Exp);
1859 else
1860 exit;
1861 end if;
1862 end loop;
1864 -- Now we can insert and analyze the pre-assignment
1866 -- If the right-hand side requires a transient scope, it has
1867 -- already been placed on the stack. However, the declaration is
1868 -- inserted in the tree outside of this scope, and must reflect
1869 -- the proper scope for its variable. This awkward bit is forced
1870 -- by the stricter scope discipline imposed by GCC 2.97.
1872 declare
1873 Uses_Transient_Scope : constant Boolean :=
1874 Scope_Is_Transient
1875 and then N = Node_To_Be_Wrapped;
1877 begin
1878 if Uses_Transient_Scope then
1879 Push_Scope (Scope (Current_Scope));
1880 end if;
1882 Insert_Before_And_Analyze (N,
1883 Make_Object_Declaration (Loc,
1884 Defining_Identifier => Tnn,
1885 Object_Definition => New_Occurrence_Of (BPAR_Typ, Loc),
1886 Expression => BPAR_Expr));
1888 if Uses_Transient_Scope then
1889 Pop_Scope;
1890 end if;
1891 end;
1893 -- Now fix up the original assignment and continue processing
1895 Rewrite (Prefix (Lhs),
1896 New_Occurrence_Of (Tnn, Loc));
1898 -- We do not need to reanalyze that assignment, and we do not need
1899 -- to worry about references to the temporary, but we do need to
1900 -- make sure that the temporary is not marked as a true constant
1901 -- since we now have a generated assignment to it.
1903 Set_Is_True_Constant (Tnn, False);
1904 end;
1905 end if;
1907 -- When we have the appropriate type of aggregate in the expression (it
1908 -- has been determined during analysis of the aggregate by setting the
1909 -- delay flag), let's perform in place assignment and thus avoid
1910 -- creating a temporary.
1912 if Is_Delayed_Aggregate (Rhs) then
1913 Convert_Aggr_In_Assignment (N);
1914 Rewrite (N, Make_Null_Statement (Loc));
1915 Analyze (N);
1917 Restore_Globals;
1918 return;
1919 end if;
1921 -- Apply discriminant check if required. If Lhs is an access type to a
1922 -- designated type with discriminants, we must always check. If the
1923 -- type has unknown discriminants, more elaborate processing below.
1925 if Has_Discriminants (Etype (Lhs))
1926 and then not Has_Unknown_Discriminants (Etype (Lhs))
1927 then
1928 -- Skip discriminant check if change of representation. Will be
1929 -- done when the change of representation is expanded out.
1931 if not Crep then
1932 Apply_Discriminant_Check (Rhs, Etype (Lhs), Lhs);
1933 end if;
1935 -- If the type is private without discriminants, and the full type
1936 -- has discriminants (necessarily with defaults) a check may still be
1937 -- necessary if the Lhs is aliased. The private discriminants must be
1938 -- visible to build the discriminant constraints.
1940 -- Only an explicit dereference that comes from source indicates
1941 -- aliasing. Access to formals of protected operations and entries
1942 -- create dereferences but are not semantic aliasings.
1944 elsif Is_Private_Type (Etype (Lhs))
1945 and then Has_Discriminants (Typ)
1946 and then Nkind (Lhs) = N_Explicit_Dereference
1947 and then Comes_From_Source (Lhs)
1948 then
1949 declare
1950 Lt : constant Entity_Id := Etype (Lhs);
1951 Ubt : Entity_Id := Base_Type (Typ);
1953 begin
1954 -- In the case of an expander-generated record subtype whose base
1955 -- type still appears private, Typ will have been set to that
1956 -- private type rather than the underlying record type (because
1957 -- Underlying type will have returned the record subtype), so it's
1958 -- necessary to apply Underlying_Type again to the base type to
1959 -- get the record type we need for the discriminant check. Such
1960 -- subtypes can be created for assignments in certain cases, such
1961 -- as within an instantiation passed this kind of private type.
1962 -- It would be good to avoid this special test, but making changes
1963 -- to prevent this odd form of record subtype seems difficult. ???
1965 if Is_Private_Type (Ubt) then
1966 Ubt := Underlying_Type (Ubt);
1967 end if;
1969 Set_Etype (Lhs, Ubt);
1970 Rewrite (Rhs, OK_Convert_To (Base_Type (Ubt), Rhs));
1971 Apply_Discriminant_Check (Rhs, Ubt, Lhs);
1972 Set_Etype (Lhs, Lt);
1973 end;
1975 -- If the Lhs has a private type with unknown discriminants, it may
1976 -- have a full view with discriminants, but those are nameable only
1977 -- in the underlying type, so convert the Rhs to it before potential
1978 -- checking. Convert Lhs as well, otherwise the actual subtype might
1979 -- not be constructible.
1981 elsif Has_Unknown_Discriminants (Base_Type (Etype (Lhs)))
1982 and then Has_Discriminants (Typ)
1983 then
1984 Rewrite (Rhs, OK_Convert_To (Base_Type (Typ), Rhs));
1985 Rewrite (Lhs, OK_Convert_To (Base_Type (Typ), Lhs));
1986 Apply_Discriminant_Check (Rhs, Typ, Lhs);
1988 -- In the access type case, we need the same discriminant check, and
1989 -- also range checks if we have an access to constrained array.
1991 elsif Is_Access_Type (Etype (Lhs))
1992 and then Is_Constrained (Designated_Type (Etype (Lhs)))
1993 then
1994 if Has_Discriminants (Designated_Type (Etype (Lhs))) then
1996 -- Skip discriminant check if change of representation. Will be
1997 -- done when the change of representation is expanded out.
1999 if not Crep then
2000 Apply_Discriminant_Check (Rhs, Etype (Lhs));
2001 end if;
2003 elsif Is_Array_Type (Designated_Type (Etype (Lhs))) then
2004 Apply_Range_Check (Rhs, Etype (Lhs));
2006 if Is_Constrained (Etype (Lhs)) then
2007 Apply_Length_Check (Rhs, Etype (Lhs));
2008 end if;
2010 if Nkind (Rhs) = N_Allocator then
2011 declare
2012 Target_Typ : constant Entity_Id := Etype (Expression (Rhs));
2013 C_Es : Check_Result;
2015 begin
2016 C_Es :=
2017 Get_Range_Checks
2018 (Lhs,
2019 Target_Typ,
2020 Etype (Designated_Type (Etype (Lhs))));
2022 Insert_Range_Checks
2023 (C_Es,
2025 Target_Typ,
2026 Sloc (Lhs),
2027 Lhs);
2028 end;
2029 end if;
2030 end if;
2032 -- Apply range check for access type case
2034 elsif Is_Access_Type (Etype (Lhs))
2035 and then Nkind (Rhs) = N_Allocator
2036 and then Nkind (Expression (Rhs)) = N_Qualified_Expression
2037 then
2038 Analyze_And_Resolve (Expression (Rhs));
2039 Apply_Range_Check
2040 (Expression (Rhs), Designated_Type (Etype (Lhs)));
2041 end if;
2043 -- Ada 2005 (AI-231): Generate the run-time check
2045 if Is_Access_Type (Typ)
2046 and then Can_Never_Be_Null (Etype (Lhs))
2047 and then not Can_Never_Be_Null (Etype (Rhs))
2049 -- If an actual is an out parameter of a null-excluding access
2050 -- type, there is access check on entry, so we set the flag
2051 -- Suppress_Assignment_Checks on the generated statement to
2052 -- assign the actual to the parameter block, and we do not want
2053 -- to generate an additional check at this point.
2055 and then not Suppress_Assignment_Checks (N)
2056 then
2057 Apply_Constraint_Check (Rhs, Etype (Lhs));
2058 end if;
2060 -- Ada 2012 (AI05-148): Update current accessibility level if Rhs is a
2061 -- stand-alone obj of an anonymous access type.
2063 if Is_Access_Type (Typ)
2064 and then Is_Entity_Name (Lhs)
2065 and then Present (Effective_Extra_Accessibility (Entity (Lhs)))
2066 then
2067 declare
2068 function Lhs_Entity return Entity_Id;
2069 -- Look through renames to find the underlying entity.
2070 -- For assignment to a rename, we don't care about the
2071 -- Enclosing_Dynamic_Scope of the rename declaration.
2073 ----------------
2074 -- Lhs_Entity --
2075 ----------------
2077 function Lhs_Entity return Entity_Id is
2078 Result : Entity_Id := Entity (Lhs);
2080 begin
2081 while Present (Renamed_Object (Result)) loop
2083 -- Renamed_Object must return an Entity_Name here
2084 -- because of preceding "Present (E_E_A (...))" test.
2086 Result := Entity (Renamed_Object (Result));
2087 end loop;
2089 return Result;
2090 end Lhs_Entity;
2092 -- Local Declarations
2094 Access_Check : constant Node_Id :=
2095 Make_Raise_Program_Error (Loc,
2096 Condition =>
2097 Make_Op_Gt (Loc,
2098 Left_Opnd =>
2099 Dynamic_Accessibility_Level (Rhs),
2100 Right_Opnd =>
2101 Make_Integer_Literal (Loc,
2102 Intval =>
2103 Scope_Depth
2104 (Enclosing_Dynamic_Scope
2105 (Lhs_Entity)))),
2106 Reason => PE_Accessibility_Check_Failed);
2108 Access_Level_Update : constant Node_Id :=
2109 Make_Assignment_Statement (Loc,
2110 Name =>
2111 New_Occurrence_Of
2112 (Effective_Extra_Accessibility
2113 (Entity (Lhs)), Loc),
2114 Expression =>
2115 Dynamic_Accessibility_Level (Rhs));
2117 begin
2118 if not Accessibility_Checks_Suppressed (Entity (Lhs)) then
2119 Insert_Action (N, Access_Check);
2120 end if;
2122 Insert_Action (N, Access_Level_Update);
2123 end;
2124 end if;
2126 -- Case of assignment to a bit packed array element. If there is a
2127 -- change of representation this must be expanded into components,
2128 -- otherwise this is a bit-field assignment.
2130 if Nkind (Lhs) = N_Indexed_Component
2131 and then Is_Bit_Packed_Array (Etype (Prefix (Lhs)))
2132 then
2133 -- Normal case, no change of representation
2135 if not Crep then
2136 Expand_Bit_Packed_Element_Set (N);
2137 Restore_Globals;
2138 return;
2140 -- Change of representation case
2142 else
2143 -- Generate the following, to force component-by-component
2144 -- assignments in an efficient way. Otherwise each component
2145 -- will require a temporary and two bit-field manipulations.
2147 -- T1 : Elmt_Type;
2148 -- T1 := RhS;
2149 -- Lhs := T1;
2151 declare
2152 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
2153 Stats : List_Id;
2155 begin
2156 Stats :=
2157 New_List (
2158 Make_Object_Declaration (Loc,
2159 Defining_Identifier => Tnn,
2160 Object_Definition =>
2161 New_Occurrence_Of (Etype (Lhs), Loc)),
2162 Make_Assignment_Statement (Loc,
2163 Name => New_Occurrence_Of (Tnn, Loc),
2164 Expression => Relocate_Node (Rhs)),
2165 Make_Assignment_Statement (Loc,
2166 Name => Relocate_Node (Lhs),
2167 Expression => New_Occurrence_Of (Tnn, Loc)));
2169 Insert_Actions (N, Stats);
2170 Rewrite (N, Make_Null_Statement (Loc));
2171 Analyze (N);
2172 end;
2173 end if;
2175 -- Build-in-place function call case. Note that we're not yet doing
2176 -- build-in-place for user-written assignment statements (the assignment
2177 -- here came from an aggregate.)
2179 elsif Ada_Version >= Ada_2005
2180 and then Is_Build_In_Place_Function_Call (Rhs)
2181 then
2182 Make_Build_In_Place_Call_In_Assignment (N, Rhs);
2184 elsif Is_Tagged_Type (Typ) and then Is_Value_Type (Etype (Lhs)) then
2186 -- Nothing to do for valuetypes
2187 -- ??? Set_Scope_Is_Transient (False);
2189 Restore_Globals;
2190 return;
2192 elsif Is_Tagged_Type (Typ)
2193 or else (Needs_Finalization (Typ) and then not Is_Array_Type (Typ))
2194 then
2195 Tagged_Case : declare
2196 L : List_Id := No_List;
2197 Expand_Ctrl_Actions : constant Boolean := not No_Ctrl_Actions (N);
2199 begin
2200 -- In the controlled case, we ensure that function calls are
2201 -- evaluated before finalizing the target. In all cases, it makes
2202 -- the expansion easier if the side-effects are removed first.
2204 Remove_Side_Effects (Lhs);
2205 Remove_Side_Effects (Rhs);
2207 -- Avoid recursion in the mechanism
2209 Set_Analyzed (N);
2211 -- If dispatching assignment, we need to dispatch to _assign
2213 if Is_Class_Wide_Type (Typ)
2215 -- If the type is tagged, we may as well use the predefined
2216 -- primitive assignment. This avoids inlining a lot of code
2217 -- and in the class-wide case, the assignment is replaced
2218 -- by a dispatching call to _assign. It is suppressed in the
2219 -- case of assignments created by the expander that correspond
2220 -- to initializations, where we do want to copy the tag
2221 -- (Expand_Ctrl_Actions flag is set False in this case). It is
2222 -- also suppressed if restriction No_Dispatching_Calls is in
2223 -- force because in that case predefined primitives are not
2224 -- generated.
2226 or else (Is_Tagged_Type (Typ)
2227 and then not Is_Value_Type (Etype (Lhs))
2228 and then Chars (Current_Scope) /= Name_uAssign
2229 and then Expand_Ctrl_Actions
2230 and then
2231 not Restriction_Active (No_Dispatching_Calls))
2232 then
2233 if Is_Limited_Type (Typ) then
2235 -- This can happen in an instance when the formal is an
2236 -- extension of a limited interface, and the actual is
2237 -- limited. This is an error according to AI05-0087, but
2238 -- is not caught at the point of instantiation in earlier
2239 -- versions.
2241 -- This is wrong, error messages cannot be issued during
2242 -- expansion, since they would be missed in -gnatc mode ???
2244 Error_Msg_N ("assignment not available on limited type", N);
2245 Restore_Globals;
2246 return;
2247 end if;
2249 -- Fetch the primitive op _assign and proper type to call it.
2250 -- Because of possible conflicts between private and full view,
2251 -- fetch the proper type directly from the operation profile.
2253 declare
2254 Op : constant Entity_Id :=
2255 Find_Prim_Op (Typ, Name_uAssign);
2256 F_Typ : Entity_Id := Etype (First_Formal (Op));
2258 begin
2259 -- If the assignment is dispatching, make sure to use the
2260 -- proper type.
2262 if Is_Class_Wide_Type (Typ) then
2263 F_Typ := Class_Wide_Type (F_Typ);
2264 end if;
2266 L := New_List;
2268 -- In case of assignment to a class-wide tagged type, before
2269 -- the assignment we generate run-time check to ensure that
2270 -- the tags of source and target match.
2272 if not Tag_Checks_Suppressed (Typ)
2273 and then Is_Class_Wide_Type (Typ)
2274 and then Is_Tagged_Type (Typ)
2275 and then Is_Tagged_Type (Underlying_Type (Etype (Rhs)))
2276 then
2277 Append_To (L,
2278 Make_Raise_Constraint_Error (Loc,
2279 Condition =>
2280 Make_Op_Ne (Loc,
2281 Left_Opnd =>
2282 Make_Selected_Component (Loc,
2283 Prefix => Duplicate_Subexpr (Lhs),
2284 Selector_Name =>
2285 Make_Identifier (Loc, Name_uTag)),
2286 Right_Opnd =>
2287 Make_Selected_Component (Loc,
2288 Prefix => Duplicate_Subexpr (Rhs),
2289 Selector_Name =>
2290 Make_Identifier (Loc, Name_uTag))),
2291 Reason => CE_Tag_Check_Failed));
2292 end if;
2294 declare
2295 Left_N : Node_Id := Duplicate_Subexpr (Lhs);
2296 Right_N : Node_Id := Duplicate_Subexpr (Rhs);
2298 begin
2299 -- In order to dispatch the call to _assign the type of
2300 -- the actuals must match. Add conversion (if required).
2302 if Etype (Lhs) /= F_Typ then
2303 Left_N := Unchecked_Convert_To (F_Typ, Left_N);
2304 end if;
2306 if Etype (Rhs) /= F_Typ then
2307 Right_N := Unchecked_Convert_To (F_Typ, Right_N);
2308 end if;
2310 Append_To (L,
2311 Make_Procedure_Call_Statement (Loc,
2312 Name => New_Occurrence_Of (Op, Loc),
2313 Parameter_Associations => New_List (
2314 Node1 => Left_N,
2315 Node2 => Right_N)));
2316 end;
2317 end;
2319 else
2320 L := Make_Tag_Ctrl_Assignment (N);
2322 -- We can't afford to have destructive Finalization Actions in
2323 -- the Self assignment case, so if the target and the source
2324 -- are not obviously different, code is generated to avoid the
2325 -- self assignment case:
2327 -- if lhs'address /= rhs'address then
2328 -- <code for controlled and/or tagged assignment>
2329 -- end if;
2331 -- Skip this if Restriction (No_Finalization) is active
2333 if not Statically_Different (Lhs, Rhs)
2334 and then Expand_Ctrl_Actions
2335 and then not Restriction_Active (No_Finalization)
2336 then
2337 L := New_List (
2338 Make_Implicit_If_Statement (N,
2339 Condition =>
2340 Make_Op_Ne (Loc,
2341 Left_Opnd =>
2342 Make_Attribute_Reference (Loc,
2343 Prefix => Duplicate_Subexpr (Lhs),
2344 Attribute_Name => Name_Address),
2346 Right_Opnd =>
2347 Make_Attribute_Reference (Loc,
2348 Prefix => Duplicate_Subexpr (Rhs),
2349 Attribute_Name => Name_Address)),
2351 Then_Statements => L));
2352 end if;
2354 -- We need to set up an exception handler for implementing
2355 -- 7.6.1(18). The remaining adjustments are tackled by the
2356 -- implementation of adjust for record_controllers (see
2357 -- s-finimp.adb).
2359 -- This is skipped if we have no finalization
2361 if Expand_Ctrl_Actions
2362 and then not Restriction_Active (No_Finalization)
2363 then
2364 L := New_List (
2365 Make_Block_Statement (Loc,
2366 Handled_Statement_Sequence =>
2367 Make_Handled_Sequence_Of_Statements (Loc,
2368 Statements => L,
2369 Exception_Handlers => New_List (
2370 Make_Handler_For_Ctrl_Operation (Loc)))));
2371 end if;
2372 end if;
2374 Rewrite (N,
2375 Make_Block_Statement (Loc,
2376 Handled_Statement_Sequence =>
2377 Make_Handled_Sequence_Of_Statements (Loc, Statements => L)));
2379 -- If no restrictions on aborts, protect the whole assignment
2380 -- for controlled objects as per 9.8(11).
2382 if Needs_Finalization (Typ)
2383 and then Expand_Ctrl_Actions
2384 and then Abort_Allowed
2385 then
2386 declare
2387 Blk : constant Entity_Id :=
2388 New_Internal_Entity
2389 (E_Block, Current_Scope, Sloc (N), 'B');
2390 AUD : constant Entity_Id := RTE (RE_Abort_Undefer_Direct);
2392 begin
2393 Set_Scope (Blk, Current_Scope);
2394 Set_Etype (Blk, Standard_Void_Type);
2395 Set_Identifier (N, New_Occurrence_Of (Blk, Sloc (N)));
2397 Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
2398 Set_At_End_Proc (Handled_Statement_Sequence (N),
2399 New_Occurrence_Of (AUD, Loc));
2401 -- Present the Abort_Undefer_Direct function to the backend
2402 -- so that it can inline the call to the function.
2404 Add_Inlined_Body (AUD, N);
2406 Expand_At_End_Handler
2407 (Handled_Statement_Sequence (N), Blk);
2408 end;
2409 end if;
2411 -- N has been rewritten to a block statement for which it is
2412 -- known by construction that no checks are necessary: analyze
2413 -- it with all checks suppressed.
2415 Analyze (N, Suppress => All_Checks);
2416 Restore_Globals;
2417 return;
2418 end Tagged_Case;
2420 -- Array types
2422 elsif Is_Array_Type (Typ) then
2423 declare
2424 Actual_Rhs : Node_Id := Rhs;
2426 begin
2427 while Nkind_In (Actual_Rhs, N_Type_Conversion,
2428 N_Qualified_Expression)
2429 loop
2430 Actual_Rhs := Expression (Actual_Rhs);
2431 end loop;
2433 Expand_Assign_Array (N, Actual_Rhs);
2434 Restore_Globals;
2435 return;
2436 end;
2438 -- Record types
2440 elsif Is_Record_Type (Typ) then
2441 Expand_Assign_Record (N);
2442 Restore_Globals;
2443 return;
2445 -- Scalar types. This is where we perform the processing related to the
2446 -- requirements of (RM 13.9.1(9-11)) concerning the handling of invalid
2447 -- scalar values.
2449 elsif Is_Scalar_Type (Typ) then
2451 -- Case where right side is known valid
2453 if Expr_Known_Valid (Rhs) then
2455 -- Here the right side is valid, so it is fine. The case to deal
2456 -- with is when the left side is a local variable reference whose
2457 -- value is not currently known to be valid. If this is the case,
2458 -- and the assignment appears in an unconditional context, then
2459 -- we can mark the left side as now being valid if one of these
2460 -- conditions holds:
2462 -- The expression of the right side has Do_Range_Check set so
2463 -- that we know a range check will be performed. Note that it
2464 -- can be the case that a range check is omitted because we
2465 -- make the assumption that we can assume validity for operands
2466 -- appearing in the right side in determining whether a range
2467 -- check is required
2469 -- The subtype of the right side matches the subtype of the
2470 -- left side. In this case, even though we have not checked
2471 -- the range of the right side, we know it is in range of its
2472 -- subtype if the expression is valid.
2474 if Is_Local_Variable_Reference (Lhs)
2475 and then not Is_Known_Valid (Entity (Lhs))
2476 and then In_Unconditional_Context (N)
2477 then
2478 if Do_Range_Check (Rhs)
2479 or else Etype (Lhs) = Etype (Rhs)
2480 then
2481 Set_Is_Known_Valid (Entity (Lhs), True);
2482 end if;
2483 end if;
2485 -- Case where right side may be invalid in the sense of the RM
2486 -- reference above. The RM does not require that we check for the
2487 -- validity on an assignment, but it does require that the assignment
2488 -- of an invalid value not cause erroneous behavior.
2490 -- The general approach in GNAT is to use the Is_Known_Valid flag
2491 -- to avoid the need for validity checking on assignments. However
2492 -- in some cases, we have to do validity checking in order to make
2493 -- sure that the setting of this flag is correct.
2495 else
2496 -- Validate right side if we are validating copies
2498 if Validity_Checks_On
2499 and then Validity_Check_Copies
2500 then
2501 -- Skip this if left hand side is an array or record component
2502 -- and elementary component validity checks are suppressed.
2504 if Nkind_In (Lhs, N_Selected_Component, N_Indexed_Component)
2505 and then not Validity_Check_Components
2506 then
2507 null;
2508 else
2509 Ensure_Valid (Rhs);
2510 end if;
2512 -- We can propagate this to the left side where appropriate
2514 if Is_Local_Variable_Reference (Lhs)
2515 and then not Is_Known_Valid (Entity (Lhs))
2516 and then In_Unconditional_Context (N)
2517 then
2518 Set_Is_Known_Valid (Entity (Lhs), True);
2519 end if;
2521 -- Otherwise check to see what should be done
2523 -- If left side is a local variable, then we just set its flag to
2524 -- indicate that its value may no longer be valid, since we are
2525 -- copying a potentially invalid value.
2527 elsif Is_Local_Variable_Reference (Lhs) then
2528 Set_Is_Known_Valid (Entity (Lhs), False);
2530 -- Check for case of a nonlocal variable on the left side which
2531 -- is currently known to be valid. In this case, we simply ensure
2532 -- that the right side is valid. We only play the game of copying
2533 -- validity status for local variables, since we are doing this
2534 -- statically, not by tracing the full flow graph.
2536 elsif Is_Entity_Name (Lhs)
2537 and then Is_Known_Valid (Entity (Lhs))
2538 then
2539 -- Note: If Validity_Checking mode is set to none, we ignore
2540 -- the Ensure_Valid call so don't worry about that case here.
2542 Ensure_Valid (Rhs);
2544 -- In all other cases, we can safely copy an invalid value without
2545 -- worrying about the status of the left side. Since it is not a
2546 -- variable reference it will not be considered
2547 -- as being known to be valid in any case.
2549 else
2550 null;
2551 end if;
2552 end if;
2553 end if;
2555 Restore_Globals;
2557 exception
2558 when RE_Not_Available =>
2559 Restore_Globals;
2560 return;
2561 end Expand_N_Assignment_Statement;
2563 ------------------------------
2564 -- Expand_N_Block_Statement --
2565 ------------------------------
2567 -- Encode entity names defined in block statement
2569 procedure Expand_N_Block_Statement (N : Node_Id) is
2570 begin
2571 Qualify_Entity_Names (N);
2572 end Expand_N_Block_Statement;
2574 -----------------------------
2575 -- Expand_N_Case_Statement --
2576 -----------------------------
2578 procedure Expand_N_Case_Statement (N : Node_Id) is
2579 Loc : constant Source_Ptr := Sloc (N);
2580 Expr : constant Node_Id := Expression (N);
2581 Alt : Node_Id;
2582 Len : Nat;
2583 Cond : Node_Id;
2584 Choice : Node_Id;
2585 Chlist : List_Id;
2587 begin
2588 -- Check for the situation where we know at compile time which branch
2589 -- will be taken.
2591 -- If the value is static but its subtype is predicated and the value
2592 -- does not obey the predicate, the value is marked non-static, and
2593 -- there can be no corresponding static alternative.
2595 if Compile_Time_Known_Value (Expr)
2596 and then (not Has_Predicates (Etype (Expr))
2597 or else Is_Static_Expression (Expr))
2598 then
2599 Alt := Find_Static_Alternative (N);
2601 -- Do not consider controlled objects found in a case statement which
2602 -- actually models a case expression because their early finalization
2603 -- will affect the result of the expression.
2605 if not From_Conditional_Expression (N) then
2606 Process_Statements_For_Controlled_Objects (Alt);
2607 end if;
2609 -- Move statements from this alternative after the case statement.
2610 -- They are already analyzed, so will be skipped by the analyzer.
2612 Insert_List_After (N, Statements (Alt));
2614 -- That leaves the case statement as a shell. So now we can kill all
2615 -- other alternatives in the case statement.
2617 Kill_Dead_Code (Expression (N));
2619 declare
2620 Dead_Alt : Node_Id;
2622 begin
2623 -- Loop through case alternatives, skipping pragmas, and skipping
2624 -- the one alternative that we select (and therefore retain).
2626 Dead_Alt := First (Alternatives (N));
2627 while Present (Dead_Alt) loop
2628 if Dead_Alt /= Alt
2629 and then Nkind (Dead_Alt) = N_Case_Statement_Alternative
2630 then
2631 Kill_Dead_Code (Statements (Dead_Alt), Warn_On_Deleted_Code);
2632 end if;
2634 Next (Dead_Alt);
2635 end loop;
2636 end;
2638 Rewrite (N, Make_Null_Statement (Loc));
2639 return;
2640 end if;
2642 -- Here if the choice is not determined at compile time
2644 declare
2645 Last_Alt : constant Node_Id := Last (Alternatives (N));
2647 Others_Present : Boolean;
2648 Others_Node : Node_Id;
2650 Then_Stms : List_Id;
2651 Else_Stms : List_Id;
2653 begin
2654 if Nkind (First (Discrete_Choices (Last_Alt))) = N_Others_Choice then
2655 Others_Present := True;
2656 Others_Node := Last_Alt;
2657 else
2658 Others_Present := False;
2659 end if;
2661 -- First step is to worry about possible invalid argument. The RM
2662 -- requires (RM 5.4(13)) that if the result is invalid (e.g. it is
2663 -- outside the base range), then Constraint_Error must be raised.
2665 -- Case of validity check required (validity checks are on, the
2666 -- expression is not known to be valid, and the case statement
2667 -- comes from source -- no need to validity check internally
2668 -- generated case statements).
2670 if Validity_Check_Default then
2671 Ensure_Valid (Expr);
2672 end if;
2674 -- If there is only a single alternative, just replace it with the
2675 -- sequence of statements since obviously that is what is going to
2676 -- be executed in all cases.
2678 Len := List_Length (Alternatives (N));
2680 if Len = 1 then
2682 -- We still need to evaluate the expression if it has any side
2683 -- effects.
2685 Remove_Side_Effects (Expression (N));
2686 Alt := First (Alternatives (N));
2688 -- Do not consider controlled objects found in a case statement
2689 -- which actually models a case expression because their early
2690 -- finalization will affect the result of the expression.
2692 if not From_Conditional_Expression (N) then
2693 Process_Statements_For_Controlled_Objects (Alt);
2694 end if;
2696 Insert_List_After (N, Statements (Alt));
2698 -- That leaves the case statement as a shell. The alternative that
2699 -- will be executed is reset to a null list. So now we can kill
2700 -- the entire case statement.
2702 Kill_Dead_Code (Expression (N));
2703 Rewrite (N, Make_Null_Statement (Loc));
2704 return;
2706 -- An optimization. If there are only two alternatives, and only
2707 -- a single choice, then rewrite the whole case statement as an
2708 -- if statement, since this can result in subsequent optimizations.
2709 -- This helps not only with case statements in the source of a
2710 -- simple form, but also with generated code (discriminant check
2711 -- functions in particular).
2713 -- Note: it is OK to do this before expanding out choices for any
2714 -- static predicates, since the if statement processing will handle
2715 -- the static predicate case fine.
2717 elsif Len = 2 then
2718 Chlist := Discrete_Choices (First (Alternatives (N)));
2720 if List_Length (Chlist) = 1 then
2721 Choice := First (Chlist);
2723 Then_Stms := Statements (First (Alternatives (N)));
2724 Else_Stms := Statements (Last (Alternatives (N)));
2726 -- For TRUE, generate "expression", not expression = true
2728 if Nkind (Choice) = N_Identifier
2729 and then Entity (Choice) = Standard_True
2730 then
2731 Cond := Expression (N);
2733 -- For FALSE, generate "expression" and switch then/else
2735 elsif Nkind (Choice) = N_Identifier
2736 and then Entity (Choice) = Standard_False
2737 then
2738 Cond := Expression (N);
2739 Else_Stms := Statements (First (Alternatives (N)));
2740 Then_Stms := Statements (Last (Alternatives (N)));
2742 -- For a range, generate "expression in range"
2744 elsif Nkind (Choice) = N_Range
2745 or else (Nkind (Choice) = N_Attribute_Reference
2746 and then Attribute_Name (Choice) = Name_Range)
2747 or else (Is_Entity_Name (Choice)
2748 and then Is_Type (Entity (Choice)))
2749 then
2750 Cond :=
2751 Make_In (Loc,
2752 Left_Opnd => Expression (N),
2753 Right_Opnd => Relocate_Node (Choice));
2755 -- A subtype indication is not a legal operator in a membership
2756 -- test, so retrieve its range.
2758 elsif Nkind (Choice) = N_Subtype_Indication then
2759 Cond :=
2760 Make_In (Loc,
2761 Left_Opnd => Expression (N),
2762 Right_Opnd =>
2763 Relocate_Node
2764 (Range_Expression (Constraint (Choice))));
2766 -- For any other subexpression "expression = value"
2768 else
2769 Cond :=
2770 Make_Op_Eq (Loc,
2771 Left_Opnd => Expression (N),
2772 Right_Opnd => Relocate_Node (Choice));
2773 end if;
2775 -- Now rewrite the case as an IF
2777 Rewrite (N,
2778 Make_If_Statement (Loc,
2779 Condition => Cond,
2780 Then_Statements => Then_Stms,
2781 Else_Statements => Else_Stms));
2782 Analyze (N);
2783 return;
2784 end if;
2785 end if;
2787 -- If the last alternative is not an Others choice, replace it with
2788 -- an N_Others_Choice. Note that we do not bother to call Analyze on
2789 -- the modified case statement, since it's only effect would be to
2790 -- compute the contents of the Others_Discrete_Choices which is not
2791 -- needed by the back end anyway.
2793 -- The reason for this is that the back end always needs some default
2794 -- for a switch, so if we have not supplied one in the processing
2795 -- above for validity checking, then we need to supply one here.
2797 if not Others_Present then
2798 Others_Node := Make_Others_Choice (Sloc (Last_Alt));
2799 Set_Others_Discrete_Choices
2800 (Others_Node, Discrete_Choices (Last_Alt));
2801 Set_Discrete_Choices (Last_Alt, New_List (Others_Node));
2802 end if;
2804 -- Deal with possible declarations of controlled objects, and also
2805 -- with rewriting choice sequences for static predicate references.
2807 Alt := First_Non_Pragma (Alternatives (N));
2808 while Present (Alt) loop
2810 -- Do not consider controlled objects found in a case statement
2811 -- which actually models a case expression because their early
2812 -- finalization will affect the result of the expression.
2814 if not From_Conditional_Expression (N) then
2815 Process_Statements_For_Controlled_Objects (Alt);
2816 end if;
2818 if Has_SP_Choice (Alt) then
2819 Expand_Static_Predicates_In_Choices (Alt);
2820 end if;
2822 Next_Non_Pragma (Alt);
2823 end loop;
2824 end;
2825 end Expand_N_Case_Statement;
2827 -----------------------------
2828 -- Expand_N_Exit_Statement --
2829 -----------------------------
2831 -- The only processing required is to deal with a possible C/Fortran
2832 -- boolean value used as the condition for the exit statement.
2834 procedure Expand_N_Exit_Statement (N : Node_Id) is
2835 begin
2836 Adjust_Condition (Condition (N));
2837 end Expand_N_Exit_Statement;
2839 ----------------------------------
2840 -- Expand_Formal_Container_Loop --
2841 ----------------------------------
2843 procedure Expand_Formal_Container_Loop (N : Node_Id) is
2844 Loc : constant Source_Ptr := Sloc (N);
2845 Isc : constant Node_Id := Iteration_Scheme (N);
2846 I_Spec : constant Node_Id := Iterator_Specification (Isc);
2847 Cursor : constant Entity_Id := Defining_Identifier (I_Spec);
2848 Container : constant Node_Id := Entity (Name (I_Spec));
2849 Stats : constant List_Id := Statements (N);
2851 Advance : Node_Id;
2852 Blk_Nod : Node_Id;
2853 Init : Node_Id;
2854 New_Loop : Node_Id;
2856 begin
2857 -- The expansion resembles the one for Ada containers, but the
2858 -- primitives mention the domain of iteration explicitly, and
2859 -- function First applied to the container yields a cursor directly.
2861 -- Cursor : Cursor_type := First (Container);
2862 -- while Has_Element (Cursor, Container) loop
2863 -- <original loop statements>
2864 -- Cursor := Next (Container, Cursor);
2865 -- end loop;
2867 Build_Formal_Container_Iteration
2868 (N, Container, Cursor, Init, Advance, New_Loop);
2870 Set_Ekind (Cursor, E_Variable);
2871 Append_To (Stats, Advance);
2873 -- Build block to capture declaration of cursor entity.
2875 Blk_Nod :=
2876 Make_Block_Statement (Loc,
2877 Declarations => New_List (Init),
2878 Handled_Statement_Sequence =>
2879 Make_Handled_Sequence_Of_Statements (Loc,
2880 Statements => New_List (New_Loop)));
2882 Rewrite (N, Blk_Nod);
2883 Analyze (N);
2884 end Expand_Formal_Container_Loop;
2886 ------------------------------------------
2887 -- Expand_Formal_Container_Element_Loop --
2888 ------------------------------------------
2890 procedure Expand_Formal_Container_Element_Loop (N : Node_Id) is
2891 Loc : constant Source_Ptr := Sloc (N);
2892 Isc : constant Node_Id := Iteration_Scheme (N);
2893 I_Spec : constant Node_Id := Iterator_Specification (Isc);
2894 Element : constant Entity_Id := Defining_Identifier (I_Spec);
2895 Container : constant Node_Id := Entity (Name (I_Spec));
2896 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
2897 Stats : constant List_Id := Statements (N);
2899 Cursor : constant Entity_Id :=
2900 Make_Defining_Identifier (Loc,
2901 Chars => New_External_Name (Chars (Element), 'C'));
2902 Elmt_Decl : Node_Id;
2903 Elmt_Ref : Node_Id;
2905 Element_Op : constant Entity_Id :=
2906 Get_Iterable_Type_Primitive (Container_Typ, Name_Element);
2908 Advance : Node_Id;
2909 Init : Node_Id;
2910 New_Loop : Node_Id;
2912 begin
2913 -- For an element iterator, the Element aspect must be present,
2914 -- (this is checked during analysis) and the expansion takes the form:
2916 -- Cursor : Cursor_type := First (Container);
2917 -- Elmt : Element_Type;
2918 -- while Has_Element (Cursor, Container) loop
2919 -- Elmt := Element (Container, Cursor);
2920 -- <original loop statements>
2921 -- Cursor := Next (Container, Cursor);
2922 -- end loop;
2924 Build_Formal_Container_Iteration
2925 (N, Container, Cursor, Init, Advance, New_Loop);
2927 Set_Ekind (Cursor, E_Variable);
2928 Insert_Action (N, Init);
2930 -- Declaration for Element.
2932 Elmt_Decl :=
2933 Make_Object_Declaration (Loc,
2934 Defining_Identifier => Element,
2935 Object_Definition => New_Occurrence_Of (Etype (Element_Op), Loc));
2937 -- The element is only modified in expanded code, so it appears as
2938 -- unassigned to the warning machinery. We must suppress this spurious
2939 -- warning explicitly.
2941 Set_Warnings_Off (Element);
2943 Elmt_Ref :=
2944 Make_Assignment_Statement (Loc,
2945 Name => New_Occurrence_Of (Element, Loc),
2946 Expression =>
2947 Make_Function_Call (Loc,
2948 Name => New_Occurrence_Of (Element_Op, Loc),
2949 Parameter_Associations => New_List (
2950 New_Occurrence_Of (Container, Loc),
2951 New_Occurrence_Of (Cursor, Loc))));
2953 Prepend (Elmt_Ref, Stats);
2954 Append_To (Stats, Advance);
2956 -- The loop is rewritten as a block, to hold the element declaration
2958 New_Loop :=
2959 Make_Block_Statement (Loc,
2960 Declarations => New_List (Elmt_Decl),
2961 Handled_Statement_Sequence =>
2962 Make_Handled_Sequence_Of_Statements (Loc,
2963 Statements => New_List (New_Loop)));
2965 Rewrite (N, New_Loop);
2967 -- The loop parameter is declared by an object declaration, but within
2968 -- the loop we must prevent user assignments to it, so we analyze the
2969 -- declaration and reset the entity kind, before analyzing the rest of
2970 -- the loop;
2972 Analyze (Elmt_Decl);
2973 Set_Ekind (Defining_Identifier (Elmt_Decl), E_Loop_Parameter);
2974 Set_Assignment_OK (Name (Elmt_Ref));
2976 Analyze (N);
2977 end Expand_Formal_Container_Element_Loop;
2979 -----------------------------
2980 -- Expand_N_Goto_Statement --
2981 -----------------------------
2983 -- Add poll before goto if polling active
2985 procedure Expand_N_Goto_Statement (N : Node_Id) is
2986 begin
2987 Generate_Poll_Call (N);
2988 end Expand_N_Goto_Statement;
2990 ---------------------------
2991 -- Expand_N_If_Statement --
2992 ---------------------------
2994 -- First we deal with the case of C and Fortran convention boolean values,
2995 -- with zero/non-zero semantics.
2997 -- Second, we deal with the obvious rewriting for the cases where the
2998 -- condition of the IF is known at compile time to be True or False.
3000 -- Third, we remove elsif parts which have non-empty Condition_Actions and
3001 -- rewrite as independent if statements. For example:
3003 -- if x then xs
3004 -- elsif y then ys
3005 -- ...
3006 -- end if;
3008 -- becomes
3010 -- if x then xs
3011 -- else
3012 -- <<condition actions of y>>
3013 -- if y then ys
3014 -- ...
3015 -- end if;
3016 -- end if;
3018 -- This rewriting is needed if at least one elsif part has a non-empty
3019 -- Condition_Actions list. We also do the same processing if there is a
3020 -- constant condition in an elsif part (in conjunction with the first
3021 -- processing step mentioned above, for the recursive call made to deal
3022 -- with the created inner if, this deals with properly optimizing the
3023 -- cases of constant elsif conditions).
3025 procedure Expand_N_If_Statement (N : Node_Id) is
3026 Loc : constant Source_Ptr := Sloc (N);
3027 Hed : Node_Id;
3028 E : Node_Id;
3029 New_If : Node_Id;
3031 Warn_If_Deleted : constant Boolean :=
3032 Warn_On_Deleted_Code and then Comes_From_Source (N);
3033 -- Indicates whether we want warnings when we delete branches of the
3034 -- if statement based on constant condition analysis. We never want
3035 -- these warnings for expander generated code.
3037 begin
3038 -- Do not consider controlled objects found in an if statement which
3039 -- actually models an if expression because their early finalization
3040 -- will affect the result of the expression.
3042 if not From_Conditional_Expression (N) then
3043 Process_Statements_For_Controlled_Objects (N);
3044 end if;
3046 Adjust_Condition (Condition (N));
3048 -- The following loop deals with constant conditions for the IF. We
3049 -- need a loop because as we eliminate False conditions, we grab the
3050 -- first elsif condition and use it as the primary condition.
3052 while Compile_Time_Known_Value (Condition (N)) loop
3054 -- If condition is True, we can simply rewrite the if statement now
3055 -- by replacing it by the series of then statements.
3057 if Is_True (Expr_Value (Condition (N))) then
3059 -- All the else parts can be killed
3061 Kill_Dead_Code (Elsif_Parts (N), Warn_If_Deleted);
3062 Kill_Dead_Code (Else_Statements (N), Warn_If_Deleted);
3064 Hed := Remove_Head (Then_Statements (N));
3065 Insert_List_After (N, Then_Statements (N));
3066 Rewrite (N, Hed);
3067 return;
3069 -- If condition is False, then we can delete the condition and
3070 -- the Then statements
3072 else
3073 -- We do not delete the condition if constant condition warnings
3074 -- are enabled, since otherwise we end up deleting the desired
3075 -- warning. Of course the backend will get rid of this True/False
3076 -- test anyway, so nothing is lost here.
3078 if not Constant_Condition_Warnings then
3079 Kill_Dead_Code (Condition (N));
3080 end if;
3082 Kill_Dead_Code (Then_Statements (N), Warn_If_Deleted);
3084 -- If there are no elsif statements, then we simply replace the
3085 -- entire if statement by the sequence of else statements.
3087 if No (Elsif_Parts (N)) then
3088 if No (Else_Statements (N))
3089 or else Is_Empty_List (Else_Statements (N))
3090 then
3091 Rewrite (N,
3092 Make_Null_Statement (Sloc (N)));
3093 else
3094 Hed := Remove_Head (Else_Statements (N));
3095 Insert_List_After (N, Else_Statements (N));
3096 Rewrite (N, Hed);
3097 end if;
3099 return;
3101 -- If there are elsif statements, the first of them becomes the
3102 -- if/then section of the rebuilt if statement This is the case
3103 -- where we loop to reprocess this copied condition.
3105 else
3106 Hed := Remove_Head (Elsif_Parts (N));
3107 Insert_Actions (N, Condition_Actions (Hed));
3108 Set_Condition (N, Condition (Hed));
3109 Set_Then_Statements (N, Then_Statements (Hed));
3111 -- Hed might have been captured as the condition determining
3112 -- the current value for an entity. Now it is detached from
3113 -- the tree, so a Current_Value pointer in the condition might
3114 -- need to be updated.
3116 Set_Current_Value_Condition (N);
3118 if Is_Empty_List (Elsif_Parts (N)) then
3119 Set_Elsif_Parts (N, No_List);
3120 end if;
3121 end if;
3122 end if;
3123 end loop;
3125 -- Loop through elsif parts, dealing with constant conditions and
3126 -- possible condition actions that are present.
3128 if Present (Elsif_Parts (N)) then
3129 E := First (Elsif_Parts (N));
3130 while Present (E) loop
3132 -- Do not consider controlled objects found in an if statement
3133 -- which actually models an if expression because their early
3134 -- finalization will affect the result of the expression.
3136 if not From_Conditional_Expression (N) then
3137 Process_Statements_For_Controlled_Objects (E);
3138 end if;
3140 Adjust_Condition (Condition (E));
3142 -- If there are condition actions, then rewrite the if statement
3143 -- as indicated above. We also do the same rewrite for a True or
3144 -- False condition. The further processing of this constant
3145 -- condition is then done by the recursive call to expand the
3146 -- newly created if statement
3148 if Present (Condition_Actions (E))
3149 or else Compile_Time_Known_Value (Condition (E))
3150 then
3151 -- Note this is not an implicit if statement, since it is part
3152 -- of an explicit if statement in the source (or of an implicit
3153 -- if statement that has already been tested).
3155 New_If :=
3156 Make_If_Statement (Sloc (E),
3157 Condition => Condition (E),
3158 Then_Statements => Then_Statements (E),
3159 Elsif_Parts => No_List,
3160 Else_Statements => Else_Statements (N));
3162 -- Elsif parts for new if come from remaining elsif's of parent
3164 while Present (Next (E)) loop
3165 if No (Elsif_Parts (New_If)) then
3166 Set_Elsif_Parts (New_If, New_List);
3167 end if;
3169 Append (Remove_Next (E), Elsif_Parts (New_If));
3170 end loop;
3172 Set_Else_Statements (N, New_List (New_If));
3174 if Present (Condition_Actions (E)) then
3175 Insert_List_Before (New_If, Condition_Actions (E));
3176 end if;
3178 Remove (E);
3180 if Is_Empty_List (Elsif_Parts (N)) then
3181 Set_Elsif_Parts (N, No_List);
3182 end if;
3184 Analyze (New_If);
3185 return;
3187 -- No special processing for that elsif part, move to next
3189 else
3190 Next (E);
3191 end if;
3192 end loop;
3193 end if;
3195 -- Some more optimizations applicable if we still have an IF statement
3197 if Nkind (N) /= N_If_Statement then
3198 return;
3199 end if;
3201 -- Another optimization, special cases that can be simplified
3203 -- if expression then
3204 -- return true;
3205 -- else
3206 -- return false;
3207 -- end if;
3209 -- can be changed to:
3211 -- return expression;
3213 -- and
3215 -- if expression then
3216 -- return false;
3217 -- else
3218 -- return true;
3219 -- end if;
3221 -- can be changed to:
3223 -- return not (expression);
3225 -- Only do these optimizations if we are at least at -O1 level and
3226 -- do not do them if control flow optimizations are suppressed.
3228 if Optimization_Level > 0
3229 and then not Opt.Suppress_Control_Flow_Optimizations
3230 then
3231 if Nkind (N) = N_If_Statement
3232 and then No (Elsif_Parts (N))
3233 and then Present (Else_Statements (N))
3234 and then List_Length (Then_Statements (N)) = 1
3235 and then List_Length (Else_Statements (N)) = 1
3236 then
3237 declare
3238 Then_Stm : constant Node_Id := First (Then_Statements (N));
3239 Else_Stm : constant Node_Id := First (Else_Statements (N));
3241 begin
3242 if Nkind (Then_Stm) = N_Simple_Return_Statement
3243 and then
3244 Nkind (Else_Stm) = N_Simple_Return_Statement
3245 then
3246 declare
3247 Then_Expr : constant Node_Id := Expression (Then_Stm);
3248 Else_Expr : constant Node_Id := Expression (Else_Stm);
3250 begin
3251 if Nkind (Then_Expr) = N_Identifier
3252 and then
3253 Nkind (Else_Expr) = N_Identifier
3254 then
3255 if Entity (Then_Expr) = Standard_True
3256 and then Entity (Else_Expr) = Standard_False
3257 then
3258 Rewrite (N,
3259 Make_Simple_Return_Statement (Loc,
3260 Expression => Relocate_Node (Condition (N))));
3261 Analyze (N);
3262 return;
3264 elsif Entity (Then_Expr) = Standard_False
3265 and then Entity (Else_Expr) = Standard_True
3266 then
3267 Rewrite (N,
3268 Make_Simple_Return_Statement (Loc,
3269 Expression =>
3270 Make_Op_Not (Loc,
3271 Right_Opnd =>
3272 Relocate_Node (Condition (N)))));
3273 Analyze (N);
3274 return;
3275 end if;
3276 end if;
3277 end;
3278 end if;
3279 end;
3280 end if;
3281 end if;
3282 end Expand_N_If_Statement;
3284 --------------------------
3285 -- Expand_Iterator_Loop --
3286 --------------------------
3288 procedure Expand_Iterator_Loop (N : Node_Id) is
3289 Isc : constant Node_Id := Iteration_Scheme (N);
3290 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3292 Container : constant Node_Id := Name (I_Spec);
3293 Container_Typ : constant Entity_Id := Base_Type (Etype (Container));
3295 begin
3296 -- Processing for arrays
3298 if Is_Array_Type (Container_Typ) then
3299 pragma Assert (Of_Present (I_Spec));
3300 Expand_Iterator_Loop_Over_Array (N);
3302 elsif Has_Aspect (Container_Typ, Aspect_Iterable) then
3303 if Of_Present (I_Spec) then
3304 Expand_Formal_Container_Element_Loop (N);
3305 else
3306 Expand_Formal_Container_Loop (N);
3307 end if;
3309 -- Processing for containers
3311 else
3312 Expand_Iterator_Loop_Over_Container
3313 (N, Isc, I_Spec, Container, Container_Typ);
3314 end if;
3315 end Expand_Iterator_Loop;
3317 -------------------------------------
3318 -- Expand_Iterator_Loop_Over_Array --
3319 -------------------------------------
3321 procedure Expand_Iterator_Loop_Over_Array (N : Node_Id) is
3322 Isc : constant Node_Id := Iteration_Scheme (N);
3323 I_Spec : constant Node_Id := Iterator_Specification (Isc);
3324 Array_Node : constant Node_Id := Name (I_Spec);
3325 Array_Typ : constant Entity_Id := Base_Type (Etype (Array_Node));
3326 Array_Dim : constant Pos := Number_Dimensions (Array_Typ);
3327 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3328 Loc : constant Source_Ptr := Sloc (N);
3329 Stats : constant List_Id := Statements (N);
3330 Core_Loop : Node_Id;
3331 Dim1 : Int;
3332 Ind_Comp : Node_Id;
3333 Iterator : Entity_Id;
3335 -- Start of processing for Expand_Iterator_Loop_Over_Array
3337 begin
3338 -- for Element of Array loop
3340 -- This case requires an internally generated cursor to iterate over
3341 -- the array.
3343 if Of_Present (I_Spec) then
3344 Iterator := Make_Temporary (Loc, 'C');
3346 -- Generate:
3347 -- Element : Component_Type renames Array (Iterator);
3348 -- Iterator is the index value, or a list of index values
3349 -- in the case of a multidimensional array.
3351 Ind_Comp :=
3352 Make_Indexed_Component (Loc,
3353 Prefix => Relocate_Node (Array_Node),
3354 Expressions => New_List (New_Occurrence_Of (Iterator, Loc)));
3356 Prepend_To (Stats,
3357 Make_Object_Renaming_Declaration (Loc,
3358 Defining_Identifier => Id,
3359 Subtype_Mark =>
3360 New_Occurrence_Of (Component_Type (Array_Typ), Loc),
3361 Name => Ind_Comp));
3363 -- Mark the loop variable as needing debug info, so that expansion
3364 -- of the renaming will result in Materialize_Entity getting set via
3365 -- Debug_Renaming_Declaration. (This setting is needed here because
3366 -- the setting in Freeze_Entity comes after the expansion, which is
3367 -- too late. ???)
3369 Set_Debug_Info_Needed (Id);
3371 -- for Index in Array loop
3373 -- This case utilizes the already given iterator name
3375 else
3376 Iterator := Id;
3377 end if;
3379 -- Generate:
3381 -- for Iterator in [reverse] Array'Range (Array_Dim) loop
3382 -- Element : Component_Type renames Array (Iterator);
3383 -- <original loop statements>
3384 -- end loop;
3386 -- If this is an iteration over a multidimensional array, the
3387 -- innermost loop is over the last dimension in Ada, and over
3388 -- the first dimension in Fortran.
3390 if Convention (Array_Typ) = Convention_Fortran then
3391 Dim1 := 1;
3392 else
3393 Dim1 := Array_Dim;
3394 end if;
3396 Core_Loop :=
3397 Make_Loop_Statement (Loc,
3398 Iteration_Scheme =>
3399 Make_Iteration_Scheme (Loc,
3400 Loop_Parameter_Specification =>
3401 Make_Loop_Parameter_Specification (Loc,
3402 Defining_Identifier => Iterator,
3403 Discrete_Subtype_Definition =>
3404 Make_Attribute_Reference (Loc,
3405 Prefix => Relocate_Node (Array_Node),
3406 Attribute_Name => Name_Range,
3407 Expressions => New_List (
3408 Make_Integer_Literal (Loc, Dim1))),
3409 Reverse_Present => Reverse_Present (I_Spec))),
3410 Statements => Stats,
3411 End_Label => Empty);
3413 -- Processing for multidimensional array. The body of each loop is
3414 -- a loop over a previous dimension, going in decreasing order in Ada
3415 -- and in increasing order in Fortran.
3417 if Array_Dim > 1 then
3418 for Dim in 1 .. Array_Dim - 1 loop
3419 if Convention (Array_Typ) = Convention_Fortran then
3420 Dim1 := Dim + 1;
3421 else
3422 Dim1 := Array_Dim - Dim;
3423 end if;
3425 Iterator := Make_Temporary (Loc, 'C');
3427 -- Generate the dimension loops starting from the innermost one
3429 -- for Iterator in [reverse] Array'Range (Array_Dim - Dim) loop
3430 -- <core loop>
3431 -- end loop;
3433 Core_Loop :=
3434 Make_Loop_Statement (Loc,
3435 Iteration_Scheme =>
3436 Make_Iteration_Scheme (Loc,
3437 Loop_Parameter_Specification =>
3438 Make_Loop_Parameter_Specification (Loc,
3439 Defining_Identifier => Iterator,
3440 Discrete_Subtype_Definition =>
3441 Make_Attribute_Reference (Loc,
3442 Prefix => Relocate_Node (Array_Node),
3443 Attribute_Name => Name_Range,
3444 Expressions => New_List (
3445 Make_Integer_Literal (Loc, Dim1))),
3446 Reverse_Present => Reverse_Present (I_Spec))),
3447 Statements => New_List (Core_Loop),
3448 End_Label => Empty);
3450 -- Update the previously created object renaming declaration with
3451 -- the new iterator, by adding the index of the next loop to the
3452 -- indexed component, in the order that corresponds to the
3453 -- convention.
3455 if Convention (Array_Typ) = Convention_Fortran then
3456 Append_To (Expressions (Ind_Comp),
3457 New_Occurrence_Of (Iterator, Loc));
3458 else
3459 Prepend_To (Expressions (Ind_Comp),
3460 New_Occurrence_Of (Iterator, Loc));
3461 end if;
3462 end loop;
3463 end if;
3465 -- Inherit the loop identifier from the original loop. This ensures that
3466 -- the scope stack is consistent after the rewriting.
3468 if Present (Identifier (N)) then
3469 Set_Identifier (Core_Loop, Relocate_Node (Identifier (N)));
3470 end if;
3472 Rewrite (N, Core_Loop);
3473 Analyze (N);
3474 end Expand_Iterator_Loop_Over_Array;
3476 -----------------------------------------
3477 -- Expand_Iterator_Loop_Over_Container --
3478 -----------------------------------------
3480 -- For a 'for ... in' loop, such as:
3482 -- for Cursor in Iterator_Function (...) loop
3483 -- ...
3484 -- end loop;
3486 -- we generate:
3488 -- Iter : Iterator_Type := Iterator_Function (...);
3489 -- Cursor : Cursor_type := First (Iter); -- or Last for "reverse"
3490 -- while Has_Element (Cursor) loop
3491 -- ...
3493 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3494 -- end loop;
3496 -- For a 'for ... of' loop, such as:
3498 -- for X of Container loop
3499 -- ...
3500 -- end loop;
3502 -- the RM implies the generation of:
3504 -- Iter : Iterator_Type := Container.Iterate; -- the Default_Iterator
3505 -- Cursor : Cursor_Type := First (Iter); -- or Last for "reverse"
3506 -- while Has_Element (Cursor) loop
3507 -- declare
3508 -- X : Element_Type renames Element (Cursor).Element.all;
3509 -- -- or Constant_Element
3510 -- begin
3511 -- ...
3512 -- end;
3513 -- Cursor := Iter.Next (Cursor); -- or Prev for "reverse"
3514 -- end loop;
3516 -- In the general case, we do what the RM says. However, the operations
3517 -- Element and Iter.Next are slow, which is bad inside a loop, because they
3518 -- involve dispatching via interfaces, secondary stack manipulation,
3519 -- Busy/Lock incr/decr, and adjust/finalization/at-end handling. So for the
3520 -- predefined containers, we use an equivalent but optimized expansion.
3522 -- In the optimized case, we make use of these:
3524 -- procedure Next (Position : in out Cursor); -- instead of Iter.Next
3526 -- function Pseudo_Reference
3527 -- (Container : aliased Vector'Class) return Reference_Control_Type;
3529 -- type Element_Access is access all Element_Type;
3531 -- function Get_Element_Access
3532 -- (Position : Cursor) return not null Element_Access;
3534 -- Next is declared in the visible part of the container packages.
3535 -- The other three are added in the private part. (We're not supposed to
3536 -- pollute the namespace for clients. The compiler has no trouble breaking
3537 -- privacy to call things in the private part of an instance.)
3539 -- Source:
3541 -- for X of My_Vector loop
3542 -- X.Count := X.Count + 1;
3543 -- ...
3544 -- end loop;
3546 -- The compiler will generate:
3548 -- Iter : Reversible_Iterator'Class := Iterate (My_Vector);
3549 -- -- Reversible_Iterator is an interface. Iterate is the
3550 -- -- Default_Iterator aspect of Vector. This increments Lock,
3551 -- -- disallowing tampering with cursors. Unfortunately, it does not
3552 -- -- increment Busy. The result of Iterate is Limited_Controlled;
3553 -- -- finalization will decrement Lock. This is a build-in-place
3554 -- -- dispatching call to Iterate.
3556 -- Cur : Cursor := First (Iter); -- or Last
3557 -- -- Dispatching call via interface.
3559 -- Control : Reference_Control_Type := Pseudo_Reference (My_Vector);
3560 -- -- Pseudo_Reference increments Busy, to detect tampering with
3561 -- -- elements, as required by RM. Also redundantly increment
3562 -- -- Lock. Finalization of Control will decrement both Busy and
3563 -- -- Lock. Pseudo_Reference returns a record containing a pointer to
3564 -- -- My_Vector, used by Finalize.
3565 -- --
3566 -- -- Control is not used below, except to finalize it -- it's purely
3567 -- -- an RAII thing. This is needed because we are eliminating the
3568 -- -- call to Reference within the loop.
3570 -- while Has_Element (Cur) loop
3571 -- declare
3572 -- X : My_Element renames Get_Element_Access (Cur).all;
3573 -- -- Get_Element_Access returns a pointer to the element
3574 -- -- designated by Cur. No dispatching here, and no horsing
3575 -- -- around with access discriminants. This is instead of the
3576 -- -- existing
3577 -- --
3578 -- -- X : My_Element renames Reference (Cur).Element.all;
3579 -- --
3580 -- -- which creates a controlled object.
3581 -- begin
3582 -- -- Any attempt to tamper with My_Vector here in the loop
3583 -- -- will correctly raise Program_Error, because of the
3584 -- -- Control.
3586 -- X.Count := X.Count + 1;
3587 -- ...
3589 -- Next (Cur); -- or Prev
3590 -- -- This is instead of "Cur := Next (Iter, Cur);"
3591 -- end;
3592 -- -- No finalization here
3593 -- end loop;
3594 -- Finalize Iter and Control here, decrementing Lock twice and Busy
3595 -- once.
3597 -- This optimization makes "for ... of" loops over 30 times faster in cases
3598 -- measured.
3600 procedure Expand_Iterator_Loop_Over_Container
3601 (N : Node_Id;
3602 Isc : Node_Id;
3603 I_Spec : Node_Id;
3604 Container : Node_Id;
3605 Container_Typ : Entity_Id)
3607 Id : constant Entity_Id := Defining_Identifier (I_Spec);
3608 Loc : constant Source_Ptr := Sloc (N);
3610 I_Kind : constant Entity_Kind := Ekind (Id);
3611 Cursor : Entity_Id;
3612 Iterator : Entity_Id;
3613 New_Loop : Node_Id;
3614 Stats : constant List_Id := Statements (N);
3616 Element_Type : constant Entity_Id := Etype (Id);
3617 Iter_Type : Entity_Id;
3618 Pack : Entity_Id;
3619 Decl : Node_Id;
3620 Name_Init : Name_Id;
3621 Name_Step : Name_Id;
3623 Fast_Element_Access_Op, Fast_Step_Op : Entity_Id := Empty;
3624 -- Only for optimized version of "for ... of"
3626 begin
3627 -- Determine the advancement and initialization steps for the cursor.
3628 -- Analysis of the expanded loop will verify that the container has a
3629 -- reverse iterator.
3631 if Reverse_Present (I_Spec) then
3632 Name_Init := Name_Last;
3633 Name_Step := Name_Previous;
3634 else
3635 Name_Init := Name_First;
3636 Name_Step := Name_Next;
3637 end if;
3639 -- The type of the iterator is the return type of the Iterate function
3640 -- used. For the "of" form this is the default iterator for the type,
3641 -- otherwise it is the type of the explicit function used in the
3642 -- iterator specification. The most common case will be an Iterate
3643 -- function in the container package.
3645 -- The Iterator type is declared in an instance within the container
3646 -- package itself, for example:
3648 -- package Vector_Iterator_Interfaces is new
3649 -- Ada.Iterator_Interfaces (Cursor, Has_Element);
3651 -- If the container type is a derived type, the cursor type is found in
3652 -- the package of the ultimate ancestor type.
3654 if Is_Derived_Type (Container_Typ) then
3655 Pack := Scope (Root_Type (Container_Typ));
3656 else
3657 Pack := Scope (Container_Typ);
3658 end if;
3660 Iter_Type := Etype (Name (I_Spec));
3662 if Of_Present (I_Spec) then
3663 Handle_Of : declare
3664 Container_Arg : Node_Id;
3666 function Get_Default_Iterator
3667 (T : Entity_Id) return Entity_Id;
3668 -- If the container is a derived type, the aspect holds the parent
3669 -- operation. The required one is a primitive of the derived type
3670 -- and is either inherited or overridden. Also sets Container_Arg.
3672 --------------------------
3673 -- Get_Default_Iterator --
3674 --------------------------
3676 function Get_Default_Iterator
3677 (T : Entity_Id) return Entity_Id
3679 Iter : constant Entity_Id :=
3680 Entity (Find_Value_Of_Aspect (T, Aspect_Default_Iterator));
3681 Prim : Elmt_Id;
3682 Op : Entity_Id;
3684 begin
3685 Container_Arg := New_Copy_Tree (Container);
3687 -- A previous version of GNAT allowed indexing aspects to
3688 -- be redefined on derived container types, while the
3689 -- default iterator was inherited from the parent type.
3690 -- This non-standard extension is preserved temporarily for
3691 -- use by the modelling project under debug flag d.X.
3693 if Debug_Flag_Dot_XX then
3694 if Base_Type (Etype (Container)) /=
3695 Base_Type (Etype (First_Formal (Iter)))
3696 then
3697 Container_Arg :=
3698 Make_Type_Conversion (Loc,
3699 Subtype_Mark =>
3700 New_Occurrence_Of
3701 (Etype (First_Formal (Iter)), Loc),
3702 Expression => Container_Arg);
3703 end if;
3705 return Iter;
3707 elsif Is_Derived_Type (T) then
3709 -- The default iterator must be a primitive operation of the
3710 -- type, at the same dispatch slot position.
3712 Prim := First_Elmt (Primitive_Operations (T));
3713 while Present (Prim) loop
3714 Op := Node (Prim);
3716 if Chars (Op) = Chars (Iter)
3717 and then DT_Position (Op) = DT_Position (Iter)
3718 then
3719 return Op;
3720 end if;
3722 Next_Elmt (Prim);
3723 end loop;
3725 -- Default iterator must exist
3727 pragma Assert (False);
3729 -- Otherwise not a derived type
3731 else
3732 return Iter;
3733 end if;
3734 end Get_Default_Iterator;
3736 Default_Iter : Entity_Id;
3737 Ent : Entity_Id;
3739 Reference_Control_Type : Entity_Id := Empty;
3740 Pseudo_Reference : Entity_Id := Empty;
3742 -- Start of processing for Handle_Of
3744 begin
3745 if Is_Class_Wide_Type (Container_Typ) then
3746 Default_Iter :=
3747 Get_Default_Iterator (Etype (Base_Type (Container_Typ)));
3748 else
3749 Default_Iter := Get_Default_Iterator (Etype (Container));
3750 end if;
3752 Cursor := Make_Temporary (Loc, 'C');
3754 -- For a container element iterator, the iterator type is obtained
3755 -- from the corresponding aspect, whose return type is descended
3756 -- from the corresponding interface type in some instance of
3757 -- Ada.Iterator_Interfaces. The actuals of that instantiation
3758 -- are Cursor and Has_Element.
3760 Iter_Type := Etype (Default_Iter);
3762 -- Find declarations needed for "for ... of" optimization
3764 Ent := First_Entity (Pack);
3765 while Present (Ent) loop
3766 if Chars (Ent) = Name_Get_Element_Access then
3767 Fast_Element_Access_Op := Ent;
3769 elsif Chars (Ent) = Name_Step
3770 and then Ekind (Ent) = E_Procedure
3771 then
3772 Fast_Step_Op := Ent;
3774 elsif Chars (Ent) = Name_Reference_Control_Type then
3775 Reference_Control_Type := Ent;
3777 elsif Chars (Ent) = Name_Pseudo_Reference then
3778 Pseudo_Reference := Ent;
3779 end if;
3781 Next_Entity (Ent);
3782 end loop;
3784 if Present (Reference_Control_Type)
3785 and then Present (Pseudo_Reference)
3786 then
3787 Insert_Action (N,
3788 Make_Object_Declaration (Loc,
3789 Defining_Identifier => Make_Temporary (Loc, 'D'),
3790 Object_Definition =>
3791 New_Occurrence_Of (Reference_Control_Type, Loc),
3792 Expression =>
3793 Make_Function_Call (Loc,
3794 Name =>
3795 New_Occurrence_Of (Pseudo_Reference, Loc),
3796 Parameter_Associations =>
3797 New_List (New_Copy_Tree (Container_Arg)))));
3798 end if;
3800 -- The iterator type, which is a class-wide type, may itself be
3801 -- derived locally, so the desired instantiation is the scope of
3802 -- the root type of the iterator type. Currently, Pack is the
3803 -- container instance; this overwrites it with the iterator
3804 -- package.
3806 Pack := Scope (Root_Type (Etype (Iter_Type)));
3808 -- Rewrite domain of iteration as a call to the default iterator
3809 -- for the container type.
3811 Rewrite (Name (I_Spec),
3812 Make_Function_Call (Loc,
3813 Name =>
3814 New_Occurrence_Of (Default_Iter, Loc),
3815 Parameter_Associations => New_List (Container_Arg)));
3816 Analyze_And_Resolve (Name (I_Spec));
3818 -- Find cursor type in proper iterator package, which is an
3819 -- instantiation of Iterator_Interfaces.
3821 Ent := First_Entity (Pack);
3822 while Present (Ent) loop
3823 if Chars (Ent) = Name_Cursor then
3824 Set_Etype (Cursor, Etype (Ent));
3825 exit;
3826 end if;
3828 Next_Entity (Ent);
3829 end loop;
3831 if Present (Fast_Element_Access_Op) then
3832 Decl :=
3833 Make_Object_Renaming_Declaration (Loc,
3834 Defining_Identifier => Id,
3835 Subtype_Mark =>
3836 New_Occurrence_Of (Element_Type, Loc),
3837 Name =>
3838 Make_Explicit_Dereference (Loc,
3839 Prefix =>
3840 Make_Function_Call (Loc,
3841 Name =>
3842 New_Occurrence_Of (Fast_Element_Access_Op, Loc),
3843 Parameter_Associations =>
3844 New_List (New_Occurrence_Of (Cursor, Loc)))));
3846 else
3847 Decl :=
3848 Make_Object_Renaming_Declaration (Loc,
3849 Defining_Identifier => Id,
3850 Subtype_Mark =>
3851 New_Occurrence_Of (Element_Type, Loc),
3852 Name =>
3853 Make_Indexed_Component (Loc,
3854 Prefix => Relocate_Node (Container_Arg),
3855 Expressions =>
3856 New_List (New_Occurrence_Of (Cursor, Loc))));
3857 end if;
3859 -- The defining identifier in the iterator is user-visible
3860 -- and must be visible in the debugger.
3862 Set_Debug_Info_Needed (Id);
3864 -- If the container does not have a variable indexing aspect,
3865 -- the element is a constant in the loop.
3867 if No (Find_Value_Of_Aspect
3868 (Container_Typ, Aspect_Variable_Indexing))
3869 then
3870 Set_Ekind (Id, E_Constant);
3871 end if;
3873 Prepend_To (Stats, Decl);
3874 end Handle_Of;
3876 -- X in Iterate (S) : type of iterator is type of explicitly
3877 -- given Iterate function, and the loop variable is the cursor.
3878 -- It will be assigned in the loop and must be a variable.
3880 else
3881 Cursor := Id;
3882 end if;
3884 Iterator := Make_Temporary (Loc, 'I');
3886 -- For both iterator forms, add a call to the step operation to
3887 -- advance the cursor. Generate:
3889 -- Cursor := Iterator.Next (Cursor);
3891 -- or else
3893 -- Cursor := Next (Cursor);
3895 if Present (Fast_Element_Access_Op) and then Present (Fast_Step_Op) then
3896 declare
3897 Step_Call : Node_Id;
3898 Curs_Name : constant Node_Id := New_Occurrence_Of (Cursor, Loc);
3899 begin
3900 Step_Call :=
3901 Make_Procedure_Call_Statement (Loc,
3902 Name =>
3903 New_Occurrence_Of (Fast_Step_Op, Loc),
3904 Parameter_Associations => New_List (Curs_Name));
3906 Append_To (Stats, Step_Call);
3907 Set_Assignment_OK (Curs_Name);
3908 end;
3910 else
3911 declare
3912 Rhs : Node_Id;
3914 begin
3915 Rhs :=
3916 Make_Function_Call (Loc,
3917 Name =>
3918 Make_Selected_Component (Loc,
3919 Prefix => New_Occurrence_Of (Iterator, Loc),
3920 Selector_Name => Make_Identifier (Loc, Name_Step)),
3921 Parameter_Associations => New_List (
3922 New_Occurrence_Of (Cursor, Loc)));
3924 Append_To (Stats,
3925 Make_Assignment_Statement (Loc,
3926 Name => New_Occurrence_Of (Cursor, Loc),
3927 Expression => Rhs));
3928 Set_Assignment_OK (Name (Last (Stats)));
3929 end;
3930 end if;
3932 -- Generate:
3933 -- while Has_Element (Cursor) loop
3934 -- <Stats>
3935 -- end loop;
3937 -- Has_Element is the second actual in the iterator package
3939 New_Loop :=
3940 Make_Loop_Statement (Loc,
3941 Iteration_Scheme =>
3942 Make_Iteration_Scheme (Loc,
3943 Condition =>
3944 Make_Function_Call (Loc,
3945 Name =>
3946 New_Occurrence_Of (
3947 Next_Entity (First_Entity (Pack)), Loc),
3948 Parameter_Associations =>
3949 New_List (New_Occurrence_Of (Cursor, Loc)))),
3951 Statements => Stats,
3952 End_Label => Empty);
3954 -- If present, preserve identifier of loop, which can be used in
3955 -- an exit statement in the body.
3957 if Present (Identifier (N)) then
3958 Set_Identifier (New_Loop, Relocate_Node (Identifier (N)));
3959 end if;
3961 -- Create the declarations for Iterator and cursor and insert them
3962 -- before the source loop. Given that the domain of iteration is already
3963 -- an entity, the iterator is just a renaming of that entity. Possible
3964 -- optimization ???
3966 Insert_Action (N,
3967 Make_Object_Renaming_Declaration (Loc,
3968 Defining_Identifier => Iterator,
3969 Subtype_Mark => New_Occurrence_Of (Iter_Type, Loc),
3970 Name => Relocate_Node (Name (I_Spec))));
3972 -- Create declaration for cursor
3974 declare
3975 Cursor_Decl : constant Node_Id :=
3976 Make_Object_Declaration (Loc,
3977 Defining_Identifier => Cursor,
3978 Object_Definition =>
3979 New_Occurrence_Of (Etype (Cursor), Loc),
3980 Expression =>
3981 Make_Selected_Component (Loc,
3982 Prefix => New_Occurrence_Of (Iterator, Loc),
3983 Selector_Name =>
3984 Make_Identifier (Loc, Name_Init)));
3986 begin
3987 -- The cursor is only modified in expanded code, so it appears
3988 -- as unassigned to the warning machinery. We must suppress this
3989 -- spurious warning explicitly. The cursor's kind is that of the
3990 -- original loop parameter (it is a constant if the domain of
3991 -- iteration is constant).
3993 Set_Warnings_Off (Cursor);
3994 Set_Assignment_OK (Cursor_Decl);
3996 Insert_Action (N, Cursor_Decl);
3997 Set_Ekind (Cursor, I_Kind);
3998 end;
4000 -- If the range of iteration is given by a function call that returns
4001 -- a container, the finalization actions have been saved in the
4002 -- Condition_Actions of the iterator. Insert them now at the head of
4003 -- the loop.
4005 if Present (Condition_Actions (Isc)) then
4006 Insert_List_Before (N, Condition_Actions (Isc));
4007 end if;
4009 Rewrite (N, New_Loop);
4010 Analyze (N);
4011 end Expand_Iterator_Loop_Over_Container;
4013 -----------------------------
4014 -- Expand_N_Loop_Statement --
4015 -----------------------------
4017 -- 1. Remove null loop entirely
4018 -- 2. Deal with while condition for C/Fortran boolean
4019 -- 3. Deal with loops with a non-standard enumeration type range
4020 -- 4. Deal with while loops where Condition_Actions is set
4021 -- 5. Deal with loops over predicated subtypes
4022 -- 6. Deal with loops with iterators over arrays and containers
4023 -- 7. Insert polling call if required
4025 procedure Expand_N_Loop_Statement (N : Node_Id) is
4026 Loc : constant Source_Ptr := Sloc (N);
4027 Scheme : constant Node_Id := Iteration_Scheme (N);
4028 Stmt : Node_Id;
4030 begin
4031 -- Delete null loop
4033 if Is_Null_Loop (N) then
4034 Rewrite (N, Make_Null_Statement (Loc));
4035 return;
4036 end if;
4038 -- Deal with condition for C/Fortran Boolean
4040 if Present (Scheme) then
4041 Adjust_Condition (Condition (Scheme));
4042 end if;
4044 -- Generate polling call
4046 if Is_Non_Empty_List (Statements (N)) then
4047 Generate_Poll_Call (First (Statements (N)));
4048 end if;
4050 -- Nothing more to do for plain loop with no iteration scheme
4052 if No (Scheme) then
4053 null;
4055 -- Case of for loop (Loop_Parameter_Specification present)
4057 -- Note: we do not have to worry about validity checking of the for loop
4058 -- range bounds here, since they were frozen with constant declarations
4059 -- and it is during that process that the validity checking is done.
4061 elsif Present (Loop_Parameter_Specification (Scheme)) then
4062 declare
4063 LPS : constant Node_Id :=
4064 Loop_Parameter_Specification (Scheme);
4065 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4066 Ltype : constant Entity_Id := Etype (Loop_Id);
4067 Btype : constant Entity_Id := Base_Type (Ltype);
4068 Expr : Node_Id;
4069 Decls : List_Id;
4070 New_Id : Entity_Id;
4072 begin
4073 -- Deal with loop over predicates
4075 if Is_Discrete_Type (Ltype)
4076 and then Present (Predicate_Function (Ltype))
4077 then
4078 Expand_Predicated_Loop (N);
4080 -- Handle the case where we have a for loop with the range type
4081 -- being an enumeration type with non-standard representation.
4082 -- In this case we expand:
4084 -- for x in [reverse] a .. b loop
4085 -- ...
4086 -- end loop;
4088 -- to
4090 -- for xP in [reverse] integer
4091 -- range etype'Pos (a) .. etype'Pos (b)
4092 -- loop
4093 -- declare
4094 -- x : constant etype := Pos_To_Rep (xP);
4095 -- begin
4096 -- ...
4097 -- end;
4098 -- end loop;
4100 elsif Is_Enumeration_Type (Btype)
4101 and then Present (Enum_Pos_To_Rep (Btype))
4102 then
4103 New_Id :=
4104 Make_Defining_Identifier (Loc,
4105 Chars => New_External_Name (Chars (Loop_Id), 'P'));
4107 -- If the type has a contiguous representation, successive
4108 -- values can be generated as offsets from the first literal.
4110 if Has_Contiguous_Rep (Btype) then
4111 Expr :=
4112 Unchecked_Convert_To (Btype,
4113 Make_Op_Add (Loc,
4114 Left_Opnd =>
4115 Make_Integer_Literal (Loc,
4116 Enumeration_Rep (First_Literal (Btype))),
4117 Right_Opnd => New_Occurrence_Of (New_Id, Loc)));
4118 else
4119 -- Use the constructed array Enum_Pos_To_Rep
4121 Expr :=
4122 Make_Indexed_Component (Loc,
4123 Prefix =>
4124 New_Occurrence_Of (Enum_Pos_To_Rep (Btype), Loc),
4125 Expressions =>
4126 New_List (New_Occurrence_Of (New_Id, Loc)));
4127 end if;
4129 -- Build declaration for loop identifier
4131 Decls :=
4132 New_List (
4133 Make_Object_Declaration (Loc,
4134 Defining_Identifier => Loop_Id,
4135 Constant_Present => True,
4136 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4137 Expression => Expr));
4139 Rewrite (N,
4140 Make_Loop_Statement (Loc,
4141 Identifier => Identifier (N),
4143 Iteration_Scheme =>
4144 Make_Iteration_Scheme (Loc,
4145 Loop_Parameter_Specification =>
4146 Make_Loop_Parameter_Specification (Loc,
4147 Defining_Identifier => New_Id,
4148 Reverse_Present => Reverse_Present (LPS),
4150 Discrete_Subtype_Definition =>
4151 Make_Subtype_Indication (Loc,
4153 Subtype_Mark =>
4154 New_Occurrence_Of (Standard_Natural, Loc),
4156 Constraint =>
4157 Make_Range_Constraint (Loc,
4158 Range_Expression =>
4159 Make_Range (Loc,
4161 Low_Bound =>
4162 Make_Attribute_Reference (Loc,
4163 Prefix =>
4164 New_Occurrence_Of (Btype, Loc),
4166 Attribute_Name => Name_Pos,
4168 Expressions => New_List (
4169 Relocate_Node
4170 (Type_Low_Bound (Ltype)))),
4172 High_Bound =>
4173 Make_Attribute_Reference (Loc,
4174 Prefix =>
4175 New_Occurrence_Of (Btype, Loc),
4177 Attribute_Name => Name_Pos,
4179 Expressions => New_List (
4180 Relocate_Node
4181 (Type_High_Bound
4182 (Ltype))))))))),
4184 Statements => New_List (
4185 Make_Block_Statement (Loc,
4186 Declarations => Decls,
4187 Handled_Statement_Sequence =>
4188 Make_Handled_Sequence_Of_Statements (Loc,
4189 Statements => Statements (N)))),
4191 End_Label => End_Label (N)));
4193 -- The loop parameter's entity must be removed from the loop
4194 -- scope's entity list and rendered invisible, since it will
4195 -- now be located in the new block scope. Any other entities
4196 -- already associated with the loop scope, such as the loop
4197 -- parameter's subtype, will remain there.
4199 -- In an element loop, the loop will contain a declaration for
4200 -- a cursor variable; otherwise the loop id is the first entity
4201 -- in the scope constructed for the loop.
4203 if Comes_From_Source (Loop_Id) then
4204 pragma Assert (First_Entity (Scope (Loop_Id)) = Loop_Id);
4205 null;
4206 end if;
4208 Set_First_Entity (Scope (Loop_Id), Next_Entity (Loop_Id));
4209 Remove_Homonym (Loop_Id);
4211 if Last_Entity (Scope (Loop_Id)) = Loop_Id then
4212 Set_Last_Entity (Scope (Loop_Id), Empty);
4213 end if;
4215 Analyze (N);
4217 -- Nothing to do with other cases of for loops
4219 else
4220 null;
4221 end if;
4222 end;
4224 -- Second case, if we have a while loop with Condition_Actions set, then
4225 -- we change it into a plain loop:
4227 -- while C loop
4228 -- ...
4229 -- end loop;
4231 -- changed to:
4233 -- loop
4234 -- <<condition actions>>
4235 -- exit when not C;
4236 -- ...
4237 -- end loop
4239 elsif Present (Scheme)
4240 and then Present (Condition_Actions (Scheme))
4241 and then Present (Condition (Scheme))
4242 then
4243 declare
4244 ES : Node_Id;
4246 begin
4247 ES :=
4248 Make_Exit_Statement (Sloc (Condition (Scheme)),
4249 Condition =>
4250 Make_Op_Not (Sloc (Condition (Scheme)),
4251 Right_Opnd => Condition (Scheme)));
4253 Prepend (ES, Statements (N));
4254 Insert_List_Before (ES, Condition_Actions (Scheme));
4256 -- This is not an implicit loop, since it is generated in response
4257 -- to the loop statement being processed. If this is itself
4258 -- implicit, the restriction has already been checked. If not,
4259 -- it is an explicit loop.
4261 Rewrite (N,
4262 Make_Loop_Statement (Sloc (N),
4263 Identifier => Identifier (N),
4264 Statements => Statements (N),
4265 End_Label => End_Label (N)));
4267 Analyze (N);
4268 end;
4270 -- Here to deal with iterator case
4272 elsif Present (Scheme)
4273 and then Present (Iterator_Specification (Scheme))
4274 then
4275 Expand_Iterator_Loop (N);
4277 -- An iterator loop may generate renaming declarations for elements
4278 -- that require debug information. This is the case in particular
4279 -- with element iterators, where debug information must be generated
4280 -- for the temporary that holds the element value. These temporaries
4281 -- are created within a transient block whose local declarations are
4282 -- transferred to the loop, which now has non-trivial local objects.
4284 if Nkind (N) = N_Loop_Statement
4285 and then Present (Identifier (N))
4286 then
4287 Qualify_Entity_Names (N);
4288 end if;
4289 end if;
4291 -- When the iteration scheme mentiones attribute 'Loop_Entry, the loop
4292 -- is transformed into a conditional block where the original loop is
4293 -- the sole statement. Inspect the statements of the nested loop for
4294 -- controlled objects.
4296 Stmt := N;
4298 if Subject_To_Loop_Entry_Attributes (Stmt) then
4299 Stmt := Find_Loop_In_Conditional_Block (Stmt);
4300 end if;
4302 Process_Statements_For_Controlled_Objects (Stmt);
4303 end Expand_N_Loop_Statement;
4305 ----------------------------
4306 -- Expand_Predicated_Loop --
4307 ----------------------------
4309 -- Note: the expander can handle generation of loops over predicated
4310 -- subtypes for both the dynamic and static cases. Depending on what
4311 -- we decide is allowed in Ada 2012 mode and/or extensions allowed
4312 -- mode, the semantic analyzer may disallow one or both forms.
4314 procedure Expand_Predicated_Loop (N : Node_Id) is
4315 Loc : constant Source_Ptr := Sloc (N);
4316 Isc : constant Node_Id := Iteration_Scheme (N);
4317 LPS : constant Node_Id := Loop_Parameter_Specification (Isc);
4318 Loop_Id : constant Entity_Id := Defining_Identifier (LPS);
4319 Ltype : constant Entity_Id := Etype (Loop_Id);
4320 Stat : constant List_Id := Static_Discrete_Predicate (Ltype);
4321 Stmts : constant List_Id := Statements (N);
4323 begin
4324 -- Case of iteration over non-static predicate, should not be possible
4325 -- since this is not allowed by the semantics and should have been
4326 -- caught during analysis of the loop statement.
4328 if No (Stat) then
4329 raise Program_Error;
4331 -- If the predicate list is empty, that corresponds to a predicate of
4332 -- False, in which case the loop won't run at all, and we rewrite the
4333 -- entire loop as a null statement.
4335 elsif Is_Empty_List (Stat) then
4336 Rewrite (N, Make_Null_Statement (Loc));
4337 Analyze (N);
4339 -- For expansion over a static predicate we generate the following
4341 -- declare
4342 -- J : Ltype := min-val;
4343 -- begin
4344 -- loop
4345 -- body
4346 -- case J is
4347 -- when endpoint => J := startpoint;
4348 -- when endpoint => J := startpoint;
4349 -- ...
4350 -- when max-val => exit;
4351 -- when others => J := Lval'Succ (J);
4352 -- end case;
4353 -- end loop;
4354 -- end;
4356 -- with min-val replaced by max-val and Succ replaced by Pred if the
4357 -- loop parameter specification carries a Reverse indicator.
4359 -- To make this a little clearer, let's take a specific example:
4361 -- type Int is range 1 .. 10;
4362 -- subtype StaticP is Int with
4363 -- predicate => StaticP in 3 | 10 | 5 .. 7;
4364 -- ...
4365 -- for L in StaticP loop
4366 -- Put_Line ("static:" & J'Img);
4367 -- end loop;
4369 -- In this case, the loop is transformed into
4371 -- begin
4372 -- J : L := 3;
4373 -- loop
4374 -- body
4375 -- case J is
4376 -- when 3 => J := 5;
4377 -- when 7 => J := 10;
4378 -- when 10 => exit;
4379 -- when others => J := L'Succ (J);
4380 -- end case;
4381 -- end loop;
4382 -- end;
4384 else
4385 Static_Predicate : declare
4386 S : Node_Id;
4387 D : Node_Id;
4388 P : Node_Id;
4389 Alts : List_Id;
4390 Cstm : Node_Id;
4392 function Lo_Val (N : Node_Id) return Node_Id;
4393 -- Given static expression or static range, returns an identifier
4394 -- whose value is the low bound of the expression value or range.
4396 function Hi_Val (N : Node_Id) return Node_Id;
4397 -- Given static expression or static range, returns an identifier
4398 -- whose value is the high bound of the expression value or range.
4400 ------------
4401 -- Hi_Val --
4402 ------------
4404 function Hi_Val (N : Node_Id) return Node_Id is
4405 begin
4406 if Is_OK_Static_Expression (N) then
4407 return New_Copy (N);
4408 else
4409 pragma Assert (Nkind (N) = N_Range);
4410 return New_Copy (High_Bound (N));
4411 end if;
4412 end Hi_Val;
4414 ------------
4415 -- Lo_Val --
4416 ------------
4418 function Lo_Val (N : Node_Id) return Node_Id is
4419 begin
4420 if Is_OK_Static_Expression (N) then
4421 return New_Copy (N);
4422 else
4423 pragma Assert (Nkind (N) = N_Range);
4424 return New_Copy (Low_Bound (N));
4425 end if;
4426 end Lo_Val;
4428 -- Start of processing for Static_Predicate
4430 begin
4431 -- Convert loop identifier to normal variable and reanalyze it so
4432 -- that this conversion works. We have to use the same defining
4433 -- identifier, since there may be references in the loop body.
4435 Set_Analyzed (Loop_Id, False);
4436 Set_Ekind (Loop_Id, E_Variable);
4438 -- In most loops the loop variable is assigned in various
4439 -- alternatives in the body. However, in the rare case when
4440 -- the range specifies a single element, the loop variable
4441 -- may trigger a spurious warning that is could be constant.
4442 -- This warning might as well be suppressed.
4444 Set_Warnings_Off (Loop_Id);
4446 -- Loop to create branches of case statement
4448 Alts := New_List;
4450 if Reverse_Present (LPS) then
4452 -- Initial value is largest value in predicate.
4454 D :=
4455 Make_Object_Declaration (Loc,
4456 Defining_Identifier => Loop_Id,
4457 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4458 Expression => Hi_Val (Last (Stat)));
4460 P := Last (Stat);
4461 while Present (P) loop
4462 if No (Prev (P)) then
4463 S := Make_Exit_Statement (Loc);
4464 else
4465 S :=
4466 Make_Assignment_Statement (Loc,
4467 Name => New_Occurrence_Of (Loop_Id, Loc),
4468 Expression => Hi_Val (Prev (P)));
4469 Set_Suppress_Assignment_Checks (S);
4470 end if;
4472 Append_To (Alts,
4473 Make_Case_Statement_Alternative (Loc,
4474 Statements => New_List (S),
4475 Discrete_Choices => New_List (Lo_Val (P))));
4477 Prev (P);
4478 end loop;
4480 else
4482 -- Initial value is smallest value in predicate.
4484 D :=
4485 Make_Object_Declaration (Loc,
4486 Defining_Identifier => Loop_Id,
4487 Object_Definition => New_Occurrence_Of (Ltype, Loc),
4488 Expression => Lo_Val (First (Stat)));
4490 P := First (Stat);
4491 while Present (P) loop
4492 if No (Next (P)) then
4493 S := Make_Exit_Statement (Loc);
4494 else
4495 S :=
4496 Make_Assignment_Statement (Loc,
4497 Name => New_Occurrence_Of (Loop_Id, Loc),
4498 Expression => Lo_Val (Next (P)));
4499 Set_Suppress_Assignment_Checks (S);
4500 end if;
4502 Append_To (Alts,
4503 Make_Case_Statement_Alternative (Loc,
4504 Statements => New_List (S),
4505 Discrete_Choices => New_List (Hi_Val (P))));
4507 Next (P);
4508 end loop;
4509 end if;
4511 -- Add others choice
4513 declare
4514 Name_Next : Name_Id;
4516 begin
4517 if Reverse_Present (LPS) then
4518 Name_Next := Name_Pred;
4519 else
4520 Name_Next := Name_Succ;
4521 end if;
4523 S :=
4524 Make_Assignment_Statement (Loc,
4525 Name => New_Occurrence_Of (Loop_Id, Loc),
4526 Expression =>
4527 Make_Attribute_Reference (Loc,
4528 Prefix => New_Occurrence_Of (Ltype, Loc),
4529 Attribute_Name => Name_Next,
4530 Expressions => New_List (
4531 New_Occurrence_Of (Loop_Id, Loc))));
4532 Set_Suppress_Assignment_Checks (S);
4533 end;
4535 Append_To (Alts,
4536 Make_Case_Statement_Alternative (Loc,
4537 Discrete_Choices => New_List (Make_Others_Choice (Loc)),
4538 Statements => New_List (S)));
4540 -- Construct case statement and append to body statements
4542 Cstm :=
4543 Make_Case_Statement (Loc,
4544 Expression => New_Occurrence_Of (Loop_Id, Loc),
4545 Alternatives => Alts);
4546 Append_To (Stmts, Cstm);
4548 -- Rewrite the loop
4550 Set_Suppress_Assignment_Checks (D);
4552 Rewrite (N,
4553 Make_Block_Statement (Loc,
4554 Declarations => New_List (D),
4555 Handled_Statement_Sequence =>
4556 Make_Handled_Sequence_Of_Statements (Loc,
4557 Statements => New_List (
4558 Make_Loop_Statement (Loc,
4559 Statements => Stmts,
4560 End_Label => Empty)))));
4562 Analyze (N);
4563 end Static_Predicate;
4564 end if;
4565 end Expand_Predicated_Loop;
4567 ------------------------------
4568 -- Make_Tag_Ctrl_Assignment --
4569 ------------------------------
4571 function Make_Tag_Ctrl_Assignment (N : Node_Id) return List_Id is
4572 Asn : constant Node_Id := Relocate_Node (N);
4573 L : constant Node_Id := Name (N);
4574 Loc : constant Source_Ptr := Sloc (N);
4575 Res : constant List_Id := New_List;
4576 T : constant Entity_Id := Underlying_Type (Etype (L));
4578 Comp_Asn : constant Boolean := Is_Fully_Repped_Tagged_Type (T);
4579 Ctrl_Act : constant Boolean := Needs_Finalization (T)
4580 and then not No_Ctrl_Actions (N);
4581 Save_Tag : constant Boolean := Is_Tagged_Type (T)
4582 and then not Comp_Asn
4583 and then not No_Ctrl_Actions (N)
4584 and then Tagged_Type_Expansion;
4585 -- Tags are not saved and restored when VM_Target because VM tags are
4586 -- represented implicitly in objects.
4588 Next_Id : Entity_Id;
4589 Prev_Id : Entity_Id;
4590 Tag_Id : Entity_Id;
4592 begin
4593 -- Finalize the target of the assignment when controlled
4595 -- We have two exceptions here:
4597 -- 1. If we are in an init proc since it is an initialization more
4598 -- than an assignment.
4600 -- 2. If the left-hand side is a temporary that was not initialized
4601 -- (or the parent part of a temporary since it is the case in
4602 -- extension aggregates). Such a temporary does not come from
4603 -- source. We must examine the original node for the prefix, because
4604 -- it may be a component of an entry formal, in which case it has
4605 -- been rewritten and does not appear to come from source either.
4607 -- Case of init proc
4609 if not Ctrl_Act then
4610 null;
4612 -- The left hand side is an uninitialized temporary object
4614 elsif Nkind (L) = N_Type_Conversion
4615 and then Is_Entity_Name (Expression (L))
4616 and then Nkind (Parent (Entity (Expression (L)))) =
4617 N_Object_Declaration
4618 and then No_Initialization (Parent (Entity (Expression (L))))
4619 then
4620 null;
4622 else
4623 Append_To (Res,
4624 Make_Final_Call
4625 (Obj_Ref => Duplicate_Subexpr_No_Checks (L),
4626 Typ => Etype (L)));
4627 end if;
4629 -- Save the Tag in a local variable Tag_Id
4631 if Save_Tag then
4632 Tag_Id := Make_Temporary (Loc, 'A');
4634 Append_To (Res,
4635 Make_Object_Declaration (Loc,
4636 Defining_Identifier => Tag_Id,
4637 Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc),
4638 Expression =>
4639 Make_Selected_Component (Loc,
4640 Prefix => Duplicate_Subexpr_No_Checks (L),
4641 Selector_Name =>
4642 New_Occurrence_Of (First_Tag_Component (T), Loc))));
4644 -- Otherwise Tag_Id is not used
4646 else
4647 Tag_Id := Empty;
4648 end if;
4650 -- Save the Prev and Next fields on .NET/JVM. This is not needed on non
4651 -- VM targets since the fields are not part of the object.
4653 if VM_Target /= No_VM
4654 and then Is_Controlled (T)
4655 then
4656 Prev_Id := Make_Temporary (Loc, 'P');
4657 Next_Id := Make_Temporary (Loc, 'N');
4659 -- Generate:
4660 -- Pnn : Root_Controlled_Ptr := Root_Controlled (L).Prev;
4662 Append_To (Res,
4663 Make_Object_Declaration (Loc,
4664 Defining_Identifier => Prev_Id,
4665 Object_Definition =>
4666 New_Occurrence_Of (RTE (RE_Root_Controlled_Ptr), Loc),
4667 Expression =>
4668 Make_Selected_Component (Loc,
4669 Prefix =>
4670 Unchecked_Convert_To
4671 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4672 Selector_Name =>
4673 Make_Identifier (Loc, Name_Prev))));
4675 -- Generate:
4676 -- Nnn : Root_Controlled_Ptr := Root_Controlled (L).Next;
4678 Append_To (Res,
4679 Make_Object_Declaration (Loc,
4680 Defining_Identifier => Next_Id,
4681 Object_Definition =>
4682 New_Occurrence_Of (RTE (RE_Root_Controlled_Ptr), Loc),
4683 Expression =>
4684 Make_Selected_Component (Loc,
4685 Prefix =>
4686 Unchecked_Convert_To
4687 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4688 Selector_Name =>
4689 Make_Identifier (Loc, Name_Next))));
4690 end if;
4692 -- If the tagged type has a full rep clause, expand the assignment into
4693 -- component-wise assignments. Mark the node as unanalyzed in order to
4694 -- generate the proper code and propagate this scenario by setting a
4695 -- flag to avoid infinite recursion.
4697 if Comp_Asn then
4698 Set_Analyzed (Asn, False);
4699 Set_Componentwise_Assignment (Asn, True);
4700 end if;
4702 Append_To (Res, Asn);
4704 -- Restore the tag
4706 if Save_Tag then
4707 Append_To (Res,
4708 Make_Assignment_Statement (Loc,
4709 Name =>
4710 Make_Selected_Component (Loc,
4711 Prefix => Duplicate_Subexpr_No_Checks (L),
4712 Selector_Name =>
4713 New_Occurrence_Of (First_Tag_Component (T), Loc)),
4714 Expression => New_Occurrence_Of (Tag_Id, Loc)));
4715 end if;
4717 -- Restore the Prev and Next fields on .NET/JVM
4719 if VM_Target /= No_VM
4720 and then Is_Controlled (T)
4721 then
4722 -- Generate:
4723 -- Root_Controlled (L).Prev := Prev_Id;
4725 Append_To (Res,
4726 Make_Assignment_Statement (Loc,
4727 Name =>
4728 Make_Selected_Component (Loc,
4729 Prefix =>
4730 Unchecked_Convert_To
4731 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4732 Selector_Name =>
4733 Make_Identifier (Loc, Name_Prev)),
4734 Expression => New_Occurrence_Of (Prev_Id, Loc)));
4736 -- Generate:
4737 -- Root_Controlled (L).Next := Next_Id;
4739 Append_To (Res,
4740 Make_Assignment_Statement (Loc,
4741 Name =>
4742 Make_Selected_Component (Loc,
4743 Prefix =>
4744 Unchecked_Convert_To
4745 (RTE (RE_Root_Controlled), New_Copy_Tree (L)),
4746 Selector_Name => Make_Identifier (Loc, Name_Next)),
4747 Expression => New_Occurrence_Of (Next_Id, Loc)));
4748 end if;
4750 -- Adjust the target after the assignment when controlled (not in the
4751 -- init proc since it is an initialization more than an assignment).
4753 if Ctrl_Act then
4754 Append_To (Res,
4755 Make_Adjust_Call
4756 (Obj_Ref => Duplicate_Subexpr_Move_Checks (L),
4757 Typ => Etype (L)));
4758 end if;
4760 return Res;
4762 exception
4764 -- Could use comment here ???
4766 when RE_Not_Available =>
4767 return Empty_List;
4768 end Make_Tag_Ctrl_Assignment;
4770 end Exp_Ch5;