2014-08-04 Yannick Moy <moy@adacore.com>
[official-gcc.git] / gcc / ada / exp_ch4.adb
blob9068fdcdfbb5f5b1c433d24dfd714f3def61f6ef
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- E X P _ C H 4 --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2014, 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 Atree; use Atree;
27 with Checks; use Checks;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Elists; use Elists;
31 with Errout; use Errout;
32 with Exp_Aggr; use Exp_Aggr;
33 with Exp_Atag; use Exp_Atag;
34 with Exp_Ch2; use Exp_Ch2;
35 with Exp_Ch3; use Exp_Ch3;
36 with Exp_Ch6; use Exp_Ch6;
37 with Exp_Ch7; use Exp_Ch7;
38 with Exp_Ch9; use Exp_Ch9;
39 with Exp_Disp; use Exp_Disp;
40 with Exp_Fixd; use Exp_Fixd;
41 with Exp_Intr; use Exp_Intr;
42 with Exp_Pakd; use Exp_Pakd;
43 with Exp_Tss; use Exp_Tss;
44 with Exp_Util; use Exp_Util;
45 with Freeze; use Freeze;
46 with Inline; use Inline;
47 with Lib; use Lib;
48 with Namet; use Namet;
49 with Nlists; use Nlists;
50 with Nmake; use Nmake;
51 with Opt; use Opt;
52 with Par_SCO; use Par_SCO;
53 with Restrict; use Restrict;
54 with Rident; use Rident;
55 with Rtsfind; use Rtsfind;
56 with Sem; use Sem;
57 with Sem_Aux; use Sem_Aux;
58 with Sem_Cat; use Sem_Cat;
59 with Sem_Ch3; use Sem_Ch3;
60 with Sem_Ch8; use Sem_Ch8;
61 with Sem_Ch13; use Sem_Ch13;
62 with Sem_Eval; use Sem_Eval;
63 with Sem_Res; use Sem_Res;
64 with Sem_Type; use Sem_Type;
65 with Sem_Util; use Sem_Util;
66 with Sem_Warn; use Sem_Warn;
67 with Sinfo; use Sinfo;
68 with Snames; use Snames;
69 with Stand; use Stand;
70 with SCIL_LL; use SCIL_LL;
71 with Targparm; use Targparm;
72 with Tbuild; use Tbuild;
73 with Ttypes; use Ttypes;
74 with Uintp; use Uintp;
75 with Urealp; use Urealp;
76 with Validsw; use Validsw;
78 package body Exp_Ch4 is
80 -----------------------
81 -- Local Subprograms --
82 -----------------------
84 procedure Binary_Op_Validity_Checks (N : Node_Id);
85 pragma Inline (Binary_Op_Validity_Checks);
86 -- Performs validity checks for a binary operator
88 procedure Build_Boolean_Array_Proc_Call
89 (N : Node_Id;
90 Op1 : Node_Id;
91 Op2 : Node_Id);
92 -- If a boolean array assignment can be done in place, build call to
93 -- corresponding library procedure.
95 function Current_Anonymous_Master return Entity_Id;
96 -- Return the entity of the heterogeneous finalization master belonging to
97 -- the current unit (either function, package or procedure). This master
98 -- services all anonymous access-to-controlled types. If the current unit
99 -- does not have such master, create one.
101 procedure Displace_Allocator_Pointer (N : Node_Id);
102 -- Ada 2005 (AI-251): Subsidiary procedure to Expand_N_Allocator and
103 -- Expand_Allocator_Expression. Allocating class-wide interface objects
104 -- this routine displaces the pointer to the allocated object to reference
105 -- the component referencing the corresponding secondary dispatch table.
107 procedure Expand_Allocator_Expression (N : Node_Id);
108 -- Subsidiary to Expand_N_Allocator, for the case when the expression
109 -- is a qualified expression or an aggregate.
111 procedure Expand_Array_Comparison (N : Node_Id);
112 -- This routine handles expansion of the comparison operators (N_Op_Lt,
113 -- N_Op_Le, N_Op_Gt, N_Op_Ge) when operating on an array type. The basic
114 -- code for these operators is similar, differing only in the details of
115 -- the actual comparison call that is made. Special processing (call a
116 -- run-time routine)
118 function Expand_Array_Equality
119 (Nod : Node_Id;
120 Lhs : Node_Id;
121 Rhs : Node_Id;
122 Bodies : List_Id;
123 Typ : Entity_Id) return Node_Id;
124 -- Expand an array equality into a call to a function implementing this
125 -- equality, and a call to it. Loc is the location for the generated nodes.
126 -- Lhs and Rhs are the array expressions to be compared. Bodies is a list
127 -- on which to attach bodies of local functions that are created in the
128 -- process. It is the responsibility of the caller to insert those bodies
129 -- at the right place. Nod provides the Sloc value for the generated code.
130 -- Normally the types used for the generated equality routine are taken
131 -- from Lhs and Rhs. However, in some situations of generated code, the
132 -- Etype fields of Lhs and Rhs are not set yet. In such cases, Typ supplies
133 -- the type to be used for the formal parameters.
135 procedure Expand_Boolean_Operator (N : Node_Id);
136 -- Common expansion processing for Boolean operators (And, Or, Xor) for the
137 -- case of array type arguments.
139 procedure Expand_Short_Circuit_Operator (N : Node_Id);
140 -- Common expansion processing for short-circuit boolean operators
142 procedure Expand_Compare_Minimize_Eliminate_Overflow (N : Node_Id);
143 -- Deal with comparison in MINIMIZED/ELIMINATED overflow mode. This is
144 -- where we allow comparison of "out of range" values.
146 function Expand_Composite_Equality
147 (Nod : Node_Id;
148 Typ : Entity_Id;
149 Lhs : Node_Id;
150 Rhs : Node_Id;
151 Bodies : List_Id) return Node_Id;
152 -- Local recursive function used to expand equality for nested composite
153 -- types. Used by Expand_Record/Array_Equality, Bodies is a list on which
154 -- to attach bodies of local functions that are created in the process. It
155 -- is the responsibility of the caller to insert those bodies at the right
156 -- place. Nod provides the Sloc value for generated code. Lhs and Rhs are
157 -- the left and right sides for the comparison, and Typ is the type of the
158 -- objects to compare.
160 procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id);
161 -- Routine to expand concatenation of a sequence of two or more operands
162 -- (in the list Operands) and replace node Cnode with the result of the
163 -- concatenation. The operands can be of any appropriate type, and can
164 -- include both arrays and singleton elements.
166 procedure Expand_Membership_Minimize_Eliminate_Overflow (N : Node_Id);
167 -- N is an N_In membership test mode, with the overflow check mode set to
168 -- MINIMIZED or ELIMINATED, and the type of the left operand is a signed
169 -- integer type. This is a case where top level processing is required to
170 -- handle overflow checks in subtrees.
172 procedure Fixup_Universal_Fixed_Operation (N : Node_Id);
173 -- N is a N_Op_Divide or N_Op_Multiply node whose result is universal
174 -- fixed. We do not have such a type at runtime, so the purpose of this
175 -- routine is to find the real type by looking up the tree. We also
176 -- determine if the operation must be rounded.
178 function Has_Inferable_Discriminants (N : Node_Id) return Boolean;
179 -- Ada 2005 (AI-216): A view of an Unchecked_Union object has inferable
180 -- discriminants if it has a constrained nominal type, unless the object
181 -- is a component of an enclosing Unchecked_Union object that is subject
182 -- to a per-object constraint and the enclosing object lacks inferable
183 -- discriminants.
185 -- An expression of an Unchecked_Union type has inferable discriminants
186 -- if it is either a name of an object with inferable discriminants or a
187 -- qualified expression whose subtype mark denotes a constrained subtype.
189 procedure Insert_Dereference_Action (N : Node_Id);
190 -- N is an expression whose type is an access. When the type of the
191 -- associated storage pool is derived from Checked_Pool, generate a
192 -- call to the 'Dereference' primitive operation.
194 function Make_Array_Comparison_Op
195 (Typ : Entity_Id;
196 Nod : Node_Id) return Node_Id;
197 -- Comparisons between arrays are expanded in line. This function produces
198 -- the body of the implementation of (a > b), where a and b are one-
199 -- dimensional arrays of some discrete type. The original node is then
200 -- expanded into the appropriate call to this function. Nod provides the
201 -- Sloc value for the generated code.
203 function Make_Boolean_Array_Op
204 (Typ : Entity_Id;
205 N : Node_Id) return Node_Id;
206 -- Boolean operations on boolean arrays are expanded in line. This function
207 -- produce the body for the node N, which is (a and b), (a or b), or (a xor
208 -- b). It is used only the normal case and not the packed case. The type
209 -- involved, Typ, is the Boolean array type, and the logical operations in
210 -- the body are simple boolean operations. Note that Typ is always a
211 -- constrained type (the caller has ensured this by using
212 -- Convert_To_Actual_Subtype if necessary).
214 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean;
215 -- For signed arithmetic operations when the current overflow mode is
216 -- MINIMIZED or ELIMINATED, we must call Apply_Arithmetic_Overflow_Checks
217 -- as the first thing we do. We then return. We count on the recursive
218 -- apparatus for overflow checks to call us back with an equivalent
219 -- operation that is in CHECKED mode, avoiding a recursive entry into this
220 -- routine, and that is when we will proceed with the expansion of the
221 -- operator (e.g. converting X+0 to X, or X**2 to X*X). We cannot do
222 -- these optimizations without first making this check, since there may be
223 -- operands further down the tree that are relying on the recursive calls
224 -- triggered by the top level nodes to properly process overflow checking
225 -- and remaining expansion on these nodes. Note that this call back may be
226 -- skipped if the operation is done in Bignum mode but that's fine, since
227 -- the Bignum call takes care of everything.
229 procedure Optimize_Length_Comparison (N : Node_Id);
230 -- Given an expression, if it is of the form X'Length op N (or the other
231 -- way round), where N is known at compile time to be 0 or 1, and X is a
232 -- simple entity, and op is a comparison operator, optimizes it into a
233 -- comparison of First and Last.
235 procedure Process_Transient_Object
236 (Decl : Node_Id;
237 Rel_Node : Node_Id);
238 -- Subsidiary routine to the expansion of expression_with_actions and if
239 -- expressions. Generate all the necessary code to finalize a transient
240 -- controlled object when the enclosing context is elaborated or evaluated.
241 -- Decl denotes the declaration of the transient controlled object which is
242 -- usually the result of a controlled function call. Rel_Node denotes the
243 -- context, either an expression_with_actions or an if expression.
245 procedure Rewrite_Comparison (N : Node_Id);
246 -- If N is the node for a comparison whose outcome can be determined at
247 -- compile time, then the node N can be rewritten with True or False. If
248 -- the outcome cannot be determined at compile time, the call has no
249 -- effect. If N is a type conversion, then this processing is applied to
250 -- its expression. If N is neither comparison nor a type conversion, the
251 -- call has no effect.
253 procedure Tagged_Membership
254 (N : Node_Id;
255 SCIL_Node : out Node_Id;
256 Result : out Node_Id);
257 -- Construct the expression corresponding to the tagged membership test.
258 -- Deals with a second operand being (or not) a class-wide type.
260 function Safe_In_Place_Array_Op
261 (Lhs : Node_Id;
262 Op1 : Node_Id;
263 Op2 : Node_Id) return Boolean;
264 -- In the context of an assignment, where the right-hand side is a boolean
265 -- operation on arrays, check whether operation can be performed in place.
267 procedure Unary_Op_Validity_Checks (N : Node_Id);
268 pragma Inline (Unary_Op_Validity_Checks);
269 -- Performs validity checks for a unary operator
271 -------------------------------
272 -- Binary_Op_Validity_Checks --
273 -------------------------------
275 procedure Binary_Op_Validity_Checks (N : Node_Id) is
276 begin
277 if Validity_Checks_On and Validity_Check_Operands then
278 Ensure_Valid (Left_Opnd (N));
279 Ensure_Valid (Right_Opnd (N));
280 end if;
281 end Binary_Op_Validity_Checks;
283 ------------------------------------
284 -- Build_Boolean_Array_Proc_Call --
285 ------------------------------------
287 procedure Build_Boolean_Array_Proc_Call
288 (N : Node_Id;
289 Op1 : Node_Id;
290 Op2 : Node_Id)
292 Loc : constant Source_Ptr := Sloc (N);
293 Kind : constant Node_Kind := Nkind (Expression (N));
294 Target : constant Node_Id :=
295 Make_Attribute_Reference (Loc,
296 Prefix => Name (N),
297 Attribute_Name => Name_Address);
299 Arg1 : Node_Id := Op1;
300 Arg2 : Node_Id := Op2;
301 Call_Node : Node_Id;
302 Proc_Name : Entity_Id;
304 begin
305 if Kind = N_Op_Not then
306 if Nkind (Op1) in N_Binary_Op then
308 -- Use negated version of the binary operators
310 if Nkind (Op1) = N_Op_And then
311 Proc_Name := RTE (RE_Vector_Nand);
313 elsif Nkind (Op1) = N_Op_Or then
314 Proc_Name := RTE (RE_Vector_Nor);
316 else pragma Assert (Nkind (Op1) = N_Op_Xor);
317 Proc_Name := RTE (RE_Vector_Xor);
318 end if;
320 Call_Node :=
321 Make_Procedure_Call_Statement (Loc,
322 Name => New_Occurrence_Of (Proc_Name, Loc),
324 Parameter_Associations => New_List (
325 Target,
326 Make_Attribute_Reference (Loc,
327 Prefix => Left_Opnd (Op1),
328 Attribute_Name => Name_Address),
330 Make_Attribute_Reference (Loc,
331 Prefix => Right_Opnd (Op1),
332 Attribute_Name => Name_Address),
334 Make_Attribute_Reference (Loc,
335 Prefix => Left_Opnd (Op1),
336 Attribute_Name => Name_Length)));
338 else
339 Proc_Name := RTE (RE_Vector_Not);
341 Call_Node :=
342 Make_Procedure_Call_Statement (Loc,
343 Name => New_Occurrence_Of (Proc_Name, Loc),
344 Parameter_Associations => New_List (
345 Target,
347 Make_Attribute_Reference (Loc,
348 Prefix => Op1,
349 Attribute_Name => Name_Address),
351 Make_Attribute_Reference (Loc,
352 Prefix => Op1,
353 Attribute_Name => Name_Length)));
354 end if;
356 else
357 -- We use the following equivalences:
359 -- (not X) or (not Y) = not (X and Y) = Nand (X, Y)
360 -- (not X) and (not Y) = not (X or Y) = Nor (X, Y)
361 -- (not X) xor (not Y) = X xor Y
362 -- X xor (not Y) = not (X xor Y) = Nxor (X, Y)
364 if Nkind (Op1) = N_Op_Not then
365 Arg1 := Right_Opnd (Op1);
366 Arg2 := Right_Opnd (Op2);
368 if Kind = N_Op_And then
369 Proc_Name := RTE (RE_Vector_Nor);
370 elsif Kind = N_Op_Or then
371 Proc_Name := RTE (RE_Vector_Nand);
372 else
373 Proc_Name := RTE (RE_Vector_Xor);
374 end if;
376 else
377 if Kind = N_Op_And then
378 Proc_Name := RTE (RE_Vector_And);
379 elsif Kind = N_Op_Or then
380 Proc_Name := RTE (RE_Vector_Or);
381 elsif Nkind (Op2) = N_Op_Not then
382 Proc_Name := RTE (RE_Vector_Nxor);
383 Arg2 := Right_Opnd (Op2);
384 else
385 Proc_Name := RTE (RE_Vector_Xor);
386 end if;
387 end if;
389 Call_Node :=
390 Make_Procedure_Call_Statement (Loc,
391 Name => New_Occurrence_Of (Proc_Name, Loc),
392 Parameter_Associations => New_List (
393 Target,
394 Make_Attribute_Reference (Loc,
395 Prefix => Arg1,
396 Attribute_Name => Name_Address),
397 Make_Attribute_Reference (Loc,
398 Prefix => Arg2,
399 Attribute_Name => Name_Address),
400 Make_Attribute_Reference (Loc,
401 Prefix => Arg1,
402 Attribute_Name => Name_Length)));
403 end if;
405 Rewrite (N, Call_Node);
406 Analyze (N);
408 exception
409 when RE_Not_Available =>
410 return;
411 end Build_Boolean_Array_Proc_Call;
413 ------------------------------
414 -- Current_Anonymous_Master --
415 ------------------------------
417 function Current_Anonymous_Master return Entity_Id is
418 Decls : List_Id;
419 Loc : Source_Ptr;
420 Subp_Body : Node_Id;
421 Unit_Decl : Node_Id;
422 Unit_Id : Entity_Id;
424 begin
425 Unit_Id := Cunit_Entity (Current_Sem_Unit);
427 -- Find the entity of the current unit
429 if Ekind (Unit_Id) = E_Subprogram_Body then
431 -- When processing subprogram bodies, the proper scope is always that
432 -- of the spec.
434 Subp_Body := Unit_Id;
435 while Present (Subp_Body)
436 and then Nkind (Subp_Body) /= N_Subprogram_Body
437 loop
438 Subp_Body := Parent (Subp_Body);
439 end loop;
441 Unit_Id := Corresponding_Spec (Subp_Body);
442 end if;
444 Loc := Sloc (Unit_Id);
445 Unit_Decl := Unit (Cunit (Current_Sem_Unit));
447 -- Find the declarations list of the current unit
449 if Nkind (Unit_Decl) = N_Package_Declaration then
450 Unit_Decl := Specification (Unit_Decl);
451 Decls := Visible_Declarations (Unit_Decl);
453 if No (Decls) then
454 Decls := New_List (Make_Null_Statement (Loc));
455 Set_Visible_Declarations (Unit_Decl, Decls);
457 elsif Is_Empty_List (Decls) then
458 Append_To (Decls, Make_Null_Statement (Loc));
459 end if;
461 else
462 Decls := Declarations (Unit_Decl);
464 if No (Decls) then
465 Decls := New_List (Make_Null_Statement (Loc));
466 Set_Declarations (Unit_Decl, Decls);
468 elsif Is_Empty_List (Decls) then
469 Append_To (Decls, Make_Null_Statement (Loc));
470 end if;
471 end if;
473 -- The current unit has an existing anonymous master, traverse its
474 -- declarations and locate the entity.
476 if Has_Anonymous_Master (Unit_Id) then
477 declare
478 Decl : Node_Id;
479 Fin_Mas_Id : Entity_Id;
481 begin
482 Decl := First (Decls);
483 while Present (Decl) loop
485 -- Look for the first variable in the declarations whole type
486 -- is Finalization_Master.
488 if Nkind (Decl) = N_Object_Declaration then
489 Fin_Mas_Id := Defining_Identifier (Decl);
491 if Ekind (Fin_Mas_Id) = E_Variable
492 and then Etype (Fin_Mas_Id) = RTE (RE_Finalization_Master)
493 then
494 return Fin_Mas_Id;
495 end if;
496 end if;
498 Next (Decl);
499 end loop;
501 -- The master was not found even though the unit was labeled as
502 -- having one.
504 raise Program_Error;
505 end;
507 -- Create a new anonymous master
509 else
510 declare
511 First_Decl : constant Node_Id := First (Decls);
512 Action : Node_Id;
513 Fin_Mas_Id : Entity_Id;
515 begin
516 -- Since the master and its associated initialization is inserted
517 -- at top level, use the scope of the unit when analyzing.
519 Push_Scope (Unit_Id);
521 -- Create the finalization master
523 Fin_Mas_Id :=
524 Make_Defining_Identifier (Loc,
525 Chars => New_External_Name (Chars (Unit_Id), "AM"));
527 -- Generate:
528 -- <Fin_Mas_Id> : Finalization_Master;
530 Action :=
531 Make_Object_Declaration (Loc,
532 Defining_Identifier => Fin_Mas_Id,
533 Object_Definition =>
534 New_Occurrence_Of (RTE (RE_Finalization_Master), Loc));
536 Insert_Before_And_Analyze (First_Decl, Action);
538 -- Mark the unit to prevent the generation of multiple masters
540 Set_Has_Anonymous_Master (Unit_Id);
542 -- Do not set the base pool and mode of operation on .NET/JVM
543 -- since those targets do not support pools and all VM masters
544 -- are heterogeneous by default.
546 if VM_Target = No_VM then
548 -- Generate:
549 -- Set_Base_Pool
550 -- (<Fin_Mas_Id>, Global_Pool_Object'Unrestricted_Access);
552 Action :=
553 Make_Procedure_Call_Statement (Loc,
554 Name =>
555 New_Occurrence_Of (RTE (RE_Set_Base_Pool), Loc),
557 Parameter_Associations => New_List (
558 New_Occurrence_Of (Fin_Mas_Id, Loc),
559 Make_Attribute_Reference (Loc,
560 Prefix =>
561 New_Occurrence_Of (RTE (RE_Global_Pool_Object), Loc),
562 Attribute_Name => Name_Unrestricted_Access)));
564 Insert_Before_And_Analyze (First_Decl, Action);
566 -- Generate:
567 -- Set_Is_Heterogeneous (<Fin_Mas_Id>);
569 Action :=
570 Make_Procedure_Call_Statement (Loc,
571 Name =>
572 New_Occurrence_Of (RTE (RE_Set_Is_Heterogeneous), Loc),
573 Parameter_Associations => New_List (
574 New_Occurrence_Of (Fin_Mas_Id, Loc)));
576 Insert_Before_And_Analyze (First_Decl, Action);
577 end if;
579 -- Restore the original state of the scope stack
581 Pop_Scope;
583 return Fin_Mas_Id;
584 end;
585 end if;
586 end Current_Anonymous_Master;
588 --------------------------------
589 -- Displace_Allocator_Pointer --
590 --------------------------------
592 procedure Displace_Allocator_Pointer (N : Node_Id) is
593 Loc : constant Source_Ptr := Sloc (N);
594 Orig_Node : constant Node_Id := Original_Node (N);
595 Dtyp : Entity_Id;
596 Etyp : Entity_Id;
597 PtrT : Entity_Id;
599 begin
600 -- Do nothing in case of VM targets: the virtual machine will handle
601 -- interfaces directly.
603 if not Tagged_Type_Expansion then
604 return;
605 end if;
607 pragma Assert (Nkind (N) = N_Identifier
608 and then Nkind (Orig_Node) = N_Allocator);
610 PtrT := Etype (Orig_Node);
611 Dtyp := Available_View (Designated_Type (PtrT));
612 Etyp := Etype (Expression (Orig_Node));
614 if Is_Class_Wide_Type (Dtyp) and then Is_Interface (Dtyp) then
616 -- If the type of the allocator expression is not an interface type
617 -- we can generate code to reference the record component containing
618 -- the pointer to the secondary dispatch table.
620 if not Is_Interface (Etyp) then
621 declare
622 Saved_Typ : constant Entity_Id := Etype (Orig_Node);
624 begin
625 -- 1) Get access to the allocated object
627 Rewrite (N,
628 Make_Explicit_Dereference (Loc, Relocate_Node (N)));
629 Set_Etype (N, Etyp);
630 Set_Analyzed (N);
632 -- 2) Add the conversion to displace the pointer to reference
633 -- the secondary dispatch table.
635 Rewrite (N, Convert_To (Dtyp, Relocate_Node (N)));
636 Analyze_And_Resolve (N, Dtyp);
638 -- 3) The 'access to the secondary dispatch table will be used
639 -- as the value returned by the allocator.
641 Rewrite (N,
642 Make_Attribute_Reference (Loc,
643 Prefix => Relocate_Node (N),
644 Attribute_Name => Name_Access));
645 Set_Etype (N, Saved_Typ);
646 Set_Analyzed (N);
647 end;
649 -- If the type of the allocator expression is an interface type we
650 -- generate a run-time call to displace "this" to reference the
651 -- component containing the pointer to the secondary dispatch table
652 -- or else raise Constraint_Error if the actual object does not
653 -- implement the target interface. This case corresponds to the
654 -- following example:
656 -- function Op (Obj : Iface_1'Class) return access Iface_2'Class is
657 -- begin
658 -- return new Iface_2'Class'(Obj);
659 -- end Op;
661 else
662 Rewrite (N,
663 Unchecked_Convert_To (PtrT,
664 Make_Function_Call (Loc,
665 Name => New_Occurrence_Of (RTE (RE_Displace), Loc),
666 Parameter_Associations => New_List (
667 Unchecked_Convert_To (RTE (RE_Address),
668 Relocate_Node (N)),
670 New_Occurrence_Of
671 (Elists.Node
672 (First_Elmt
673 (Access_Disp_Table (Etype (Base_Type (Dtyp))))),
674 Loc)))));
675 Analyze_And_Resolve (N, PtrT);
676 end if;
677 end if;
678 end Displace_Allocator_Pointer;
680 ---------------------------------
681 -- Expand_Allocator_Expression --
682 ---------------------------------
684 procedure Expand_Allocator_Expression (N : Node_Id) is
685 Loc : constant Source_Ptr := Sloc (N);
686 Exp : constant Node_Id := Expression (Expression (N));
687 PtrT : constant Entity_Id := Etype (N);
688 DesigT : constant Entity_Id := Designated_Type (PtrT);
690 procedure Apply_Accessibility_Check
691 (Ref : Node_Id;
692 Built_In_Place : Boolean := False);
693 -- Ada 2005 (AI-344): For an allocator with a class-wide designated
694 -- type, generate an accessibility check to verify that the level of the
695 -- type of the created object is not deeper than the level of the access
696 -- type. If the type of the qualified expression is class-wide, then
697 -- always generate the check (except in the case where it is known to be
698 -- unnecessary, see comment below). Otherwise, only generate the check
699 -- if the level of the qualified expression type is statically deeper
700 -- than the access type.
702 -- Although the static accessibility will generally have been performed
703 -- as a legality check, it won't have been done in cases where the
704 -- allocator appears in generic body, so a run-time check is needed in
705 -- general. One special case is when the access type is declared in the
706 -- same scope as the class-wide allocator, in which case the check can
707 -- never fail, so it need not be generated.
709 -- As an open issue, there seem to be cases where the static level
710 -- associated with the class-wide object's underlying type is not
711 -- sufficient to perform the proper accessibility check, such as for
712 -- allocators in nested subprograms or accept statements initialized by
713 -- class-wide formals when the actual originates outside at a deeper
714 -- static level. The nested subprogram case might require passing
715 -- accessibility levels along with class-wide parameters, and the task
716 -- case seems to be an actual gap in the language rules that needs to
717 -- be fixed by the ARG. ???
719 -------------------------------
720 -- Apply_Accessibility_Check --
721 -------------------------------
723 procedure Apply_Accessibility_Check
724 (Ref : Node_Id;
725 Built_In_Place : Boolean := False)
727 Pool_Id : constant Entity_Id := Associated_Storage_Pool (PtrT);
728 Cond : Node_Id;
729 Fin_Call : Node_Id;
730 Free_Stmt : Node_Id;
731 Obj_Ref : Node_Id;
732 Stmts : List_Id;
734 begin
735 if Ada_Version >= Ada_2005
736 and then Is_Class_Wide_Type (DesigT)
737 and then (Tagged_Type_Expansion or else VM_Target /= No_VM)
738 and then not Scope_Suppress.Suppress (Accessibility_Check)
739 and then
740 (Type_Access_Level (Etype (Exp)) > Type_Access_Level (PtrT)
741 or else
742 (Is_Class_Wide_Type (Etype (Exp))
743 and then Scope (PtrT) /= Current_Scope))
744 then
745 -- If the allocator was built in place, Ref is already a reference
746 -- to the access object initialized to the result of the allocator
747 -- (see Exp_Ch6.Make_Build_In_Place_Call_In_Allocator). We call
748 -- Remove_Side_Effects for cases where the build-in-place call may
749 -- still be the prefix of the reference (to avoid generating
750 -- duplicate calls). Otherwise, it is the entity associated with
751 -- the object containing the address of the allocated object.
753 if Built_In_Place then
754 Remove_Side_Effects (Ref);
755 Obj_Ref := New_Copy_Tree (Ref);
756 else
757 Obj_Ref := New_Occurrence_Of (Ref, Loc);
758 end if;
760 -- For access to interface types we must generate code to displace
761 -- the pointer to the base of the object since the subsequent code
762 -- references components located in the TSD of the object (which
763 -- is associated with the primary dispatch table --see a-tags.ads)
764 -- and also generates code invoking Free, which requires also a
765 -- reference to the base of the unallocated object.
767 if Is_Interface (DesigT) and then Tagged_Type_Expansion then
768 Obj_Ref :=
769 Unchecked_Convert_To (Etype (Obj_Ref),
770 Make_Function_Call (Loc,
771 Name =>
772 New_Occurrence_Of (RTE (RE_Base_Address), Loc),
773 Parameter_Associations => New_List (
774 Unchecked_Convert_To (RTE (RE_Address),
775 New_Copy_Tree (Obj_Ref)))));
776 end if;
778 -- Step 1: Create the object clean up code
780 Stmts := New_List;
782 -- Deallocate the object if the accessibility check fails. This
783 -- is done only on targets or profiles that support deallocation.
785 -- Free (Obj_Ref);
787 if RTE_Available (RE_Free) then
788 Free_Stmt := Make_Free_Statement (Loc, New_Copy_Tree (Obj_Ref));
789 Set_Storage_Pool (Free_Stmt, Pool_Id);
791 Append_To (Stmts, Free_Stmt);
793 -- The target or profile cannot deallocate objects
795 else
796 Free_Stmt := Empty;
797 end if;
799 -- Finalize the object if applicable. Generate:
801 -- [Deep_]Finalize (Obj_Ref.all);
803 if Needs_Finalization (DesigT) then
804 Fin_Call :=
805 Make_Final_Call
806 (Obj_Ref =>
807 Make_Explicit_Dereference (Loc, New_Copy (Obj_Ref)),
808 Typ => DesigT);
810 -- When the target or profile supports deallocation, wrap the
811 -- finalization call in a block to ensure proper deallocation
812 -- even if finalization fails. Generate:
814 -- begin
815 -- <Fin_Call>
816 -- exception
817 -- when others =>
818 -- <Free_Stmt>
819 -- raise;
820 -- end;
822 if Present (Free_Stmt) then
823 Fin_Call :=
824 Make_Block_Statement (Loc,
825 Handled_Statement_Sequence =>
826 Make_Handled_Sequence_Of_Statements (Loc,
827 Statements => New_List (Fin_Call),
829 Exception_Handlers => New_List (
830 Make_Exception_Handler (Loc,
831 Exception_Choices => New_List (
832 Make_Others_Choice (Loc)),
834 Statements => New_List (
835 New_Copy_Tree (Free_Stmt),
836 Make_Raise_Statement (Loc))))));
837 end if;
839 Prepend_To (Stmts, Fin_Call);
840 end if;
842 -- Signal the accessibility failure through a Program_Error
844 Append_To (Stmts,
845 Make_Raise_Program_Error (Loc,
846 Condition => New_Occurrence_Of (Standard_True, Loc),
847 Reason => PE_Accessibility_Check_Failed));
849 -- Step 2: Create the accessibility comparison
851 -- Generate:
852 -- Ref'Tag
854 Obj_Ref :=
855 Make_Attribute_Reference (Loc,
856 Prefix => Obj_Ref,
857 Attribute_Name => Name_Tag);
859 -- For tagged types, determine the accessibility level by looking
860 -- at the type specific data of the dispatch table. Generate:
862 -- Type_Specific_Data (Address (Ref'Tag)).Access_Level
864 if Tagged_Type_Expansion then
865 Cond := Build_Get_Access_Level (Loc, Obj_Ref);
867 -- Use a runtime call to determine the accessibility level when
868 -- compiling on virtual machine targets. Generate:
870 -- Get_Access_Level (Ref'Tag)
872 else
873 Cond :=
874 Make_Function_Call (Loc,
875 Name =>
876 New_Occurrence_Of (RTE (RE_Get_Access_Level), Loc),
877 Parameter_Associations => New_List (Obj_Ref));
878 end if;
880 Cond :=
881 Make_Op_Gt (Loc,
882 Left_Opnd => Cond,
883 Right_Opnd =>
884 Make_Integer_Literal (Loc, Type_Access_Level (PtrT)));
886 -- Due to the complexity and side effects of the check, utilize an
887 -- if statement instead of the regular Program_Error circuitry.
889 Insert_Action (N,
890 Make_Implicit_If_Statement (N,
891 Condition => Cond,
892 Then_Statements => Stmts));
893 end if;
894 end Apply_Accessibility_Check;
896 -- Local variables
898 Aggr_In_Place : constant Boolean := Is_Delayed_Aggregate (Exp);
899 Indic : constant Node_Id := Subtype_Mark (Expression (N));
900 T : constant Entity_Id := Entity (Indic);
901 Node : Node_Id;
902 Tag_Assign : Node_Id;
903 Temp : Entity_Id;
904 Temp_Decl : Node_Id;
906 TagT : Entity_Id := Empty;
907 -- Type used as source for tag assignment
909 TagR : Node_Id := Empty;
910 -- Target reference for tag assignment
912 -- Start of processing for Expand_Allocator_Expression
914 begin
915 -- Handle call to C++ constructor
917 if Is_CPP_Constructor_Call (Exp) then
918 Make_CPP_Constructor_Call_In_Allocator
919 (Allocator => N,
920 Function_Call => Exp);
921 return;
922 end if;
924 -- In the case of an Ada 2012 allocator whose initial value comes from a
925 -- function call, pass "the accessibility level determined by the point
926 -- of call" (AI05-0234) to the function. Conceptually, this belongs in
927 -- Expand_Call but it couldn't be done there (because the Etype of the
928 -- allocator wasn't set then) so we generate the parameter here. See
929 -- the Boolean variable Defer in (a block within) Expand_Call.
931 if Ada_Version >= Ada_2012 and then Nkind (Exp) = N_Function_Call then
932 declare
933 Subp : Entity_Id;
935 begin
936 if Nkind (Name (Exp)) = N_Explicit_Dereference then
937 Subp := Designated_Type (Etype (Prefix (Name (Exp))));
938 else
939 Subp := Entity (Name (Exp));
940 end if;
942 Subp := Ultimate_Alias (Subp);
944 if Present (Extra_Accessibility_Of_Result (Subp)) then
945 Add_Extra_Actual_To_Call
946 (Subprogram_Call => Exp,
947 Extra_Formal => Extra_Accessibility_Of_Result (Subp),
948 Extra_Actual => Dynamic_Accessibility_Level (PtrT));
949 end if;
950 end;
951 end if;
953 -- Case of tagged type or type requiring finalization
955 if Is_Tagged_Type (T) or else Needs_Finalization (T) then
957 -- Ada 2005 (AI-318-02): If the initialization expression is a call
958 -- to a build-in-place function, then access to the allocated object
959 -- must be passed to the function. Currently we limit such functions
960 -- to those with constrained limited result subtypes, but eventually
961 -- we plan to expand the allowed forms of functions that are treated
962 -- as build-in-place.
964 if Ada_Version >= Ada_2005
965 and then Is_Build_In_Place_Function_Call (Exp)
966 then
967 Make_Build_In_Place_Call_In_Allocator (N, Exp);
968 Apply_Accessibility_Check (N, Built_In_Place => True);
969 return;
970 end if;
972 -- Actions inserted before:
973 -- Temp : constant ptr_T := new T'(Expression);
974 -- Temp._tag = T'tag; -- when not class-wide
975 -- [Deep_]Adjust (Temp.all);
977 -- We analyze by hand the new internal allocator to avoid any
978 -- recursion and inappropriate call to Initialize.
980 -- We don't want to remove side effects when the expression must be
981 -- built in place. In the case of a build-in-place function call,
982 -- that could lead to a duplication of the call, which was already
983 -- substituted for the allocator.
985 if not Aggr_In_Place then
986 Remove_Side_Effects (Exp);
987 end if;
989 Temp := Make_Temporary (Loc, 'P', N);
991 -- For a class wide allocation generate the following code:
993 -- type Equiv_Record is record ... end record;
994 -- implicit subtype CW is <Class_Wide_Subytpe>;
995 -- temp : PtrT := new CW'(CW!(expr));
997 if Is_Class_Wide_Type (T) then
998 Expand_Subtype_From_Expr (Empty, T, Indic, Exp);
1000 -- Ada 2005 (AI-251): If the expression is a class-wide interface
1001 -- object we generate code to move up "this" to reference the
1002 -- base of the object before allocating the new object.
1004 -- Note that Exp'Address is recursively expanded into a call
1005 -- to Base_Address (Exp.Tag)
1007 if Is_Class_Wide_Type (Etype (Exp))
1008 and then Is_Interface (Etype (Exp))
1009 and then Tagged_Type_Expansion
1010 then
1011 Set_Expression
1012 (Expression (N),
1013 Unchecked_Convert_To (Entity (Indic),
1014 Make_Explicit_Dereference (Loc,
1015 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
1016 Make_Attribute_Reference (Loc,
1017 Prefix => Exp,
1018 Attribute_Name => Name_Address)))));
1019 else
1020 Set_Expression
1021 (Expression (N),
1022 Unchecked_Convert_To (Entity (Indic), Exp));
1023 end if;
1025 Analyze_And_Resolve (Expression (N), Entity (Indic));
1026 end if;
1028 -- Processing for allocators returning non-interface types
1030 if not Is_Interface (Directly_Designated_Type (PtrT)) then
1031 if Aggr_In_Place then
1032 Temp_Decl :=
1033 Make_Object_Declaration (Loc,
1034 Defining_Identifier => Temp,
1035 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1036 Expression =>
1037 Make_Allocator (Loc,
1038 Expression =>
1039 New_Occurrence_Of (Etype (Exp), Loc)));
1041 -- Copy the Comes_From_Source flag for the allocator we just
1042 -- built, since logically this allocator is a replacement of
1043 -- the original allocator node. This is for proper handling of
1044 -- restriction No_Implicit_Heap_Allocations.
1046 Set_Comes_From_Source
1047 (Expression (Temp_Decl), Comes_From_Source (N));
1049 Set_No_Initialization (Expression (Temp_Decl));
1050 Insert_Action (N, Temp_Decl);
1052 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1053 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1055 -- Attach the object to the associated finalization master.
1056 -- This is done manually on .NET/JVM since those compilers do
1057 -- no support pools and can't benefit from internally generated
1058 -- Allocate / Deallocate procedures.
1060 if VM_Target /= No_VM
1061 and then Is_Controlled (DesigT)
1062 and then Present (Finalization_Master (PtrT))
1063 then
1064 Insert_Action (N,
1065 Make_Attach_Call
1066 (Obj_Ref => New_Occurrence_Of (Temp, Loc),
1067 Ptr_Typ => PtrT));
1068 end if;
1070 else
1071 Node := Relocate_Node (N);
1072 Set_Analyzed (Node);
1074 Temp_Decl :=
1075 Make_Object_Declaration (Loc,
1076 Defining_Identifier => Temp,
1077 Constant_Present => True,
1078 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1079 Expression => Node);
1081 Insert_Action (N, Temp_Decl);
1082 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1084 -- Attach the object to the associated finalization master.
1085 -- This is done manually on .NET/JVM since those compilers do
1086 -- no support pools and can't benefit from internally generated
1087 -- Allocate / Deallocate procedures.
1089 if VM_Target /= No_VM
1090 and then Is_Controlled (DesigT)
1091 and then Present (Finalization_Master (PtrT))
1092 then
1093 Insert_Action (N,
1094 Make_Attach_Call
1095 (Obj_Ref => New_Occurrence_Of (Temp, Loc),
1096 Ptr_Typ => PtrT));
1097 end if;
1098 end if;
1100 -- Ada 2005 (AI-251): Handle allocators whose designated type is an
1101 -- interface type. In this case we use the type of the qualified
1102 -- expression to allocate the object.
1104 else
1105 declare
1106 Def_Id : constant Entity_Id := Make_Temporary (Loc, 'T');
1107 New_Decl : Node_Id;
1109 begin
1110 New_Decl :=
1111 Make_Full_Type_Declaration (Loc,
1112 Defining_Identifier => Def_Id,
1113 Type_Definition =>
1114 Make_Access_To_Object_Definition (Loc,
1115 All_Present => True,
1116 Null_Exclusion_Present => False,
1117 Constant_Present =>
1118 Is_Access_Constant (Etype (N)),
1119 Subtype_Indication =>
1120 New_Occurrence_Of (Etype (Exp), Loc)));
1122 Insert_Action (N, New_Decl);
1124 -- Inherit the allocation-related attributes from the original
1125 -- access type.
1127 Set_Finalization_Master
1128 (Def_Id, Finalization_Master (PtrT));
1130 Set_Associated_Storage_Pool
1131 (Def_Id, Associated_Storage_Pool (PtrT));
1133 -- Declare the object using the previous type declaration
1135 if Aggr_In_Place then
1136 Temp_Decl :=
1137 Make_Object_Declaration (Loc,
1138 Defining_Identifier => Temp,
1139 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
1140 Expression =>
1141 Make_Allocator (Loc,
1142 New_Occurrence_Of (Etype (Exp), Loc)));
1144 -- Copy the Comes_From_Source flag for the allocator we just
1145 -- built, since logically this allocator is a replacement of
1146 -- the original allocator node. This is for proper handling
1147 -- of restriction No_Implicit_Heap_Allocations.
1149 Set_Comes_From_Source
1150 (Expression (Temp_Decl), Comes_From_Source (N));
1152 Set_No_Initialization (Expression (Temp_Decl));
1153 Insert_Action (N, Temp_Decl);
1155 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1156 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1158 else
1159 Node := Relocate_Node (N);
1160 Set_Analyzed (Node);
1162 Temp_Decl :=
1163 Make_Object_Declaration (Loc,
1164 Defining_Identifier => Temp,
1165 Constant_Present => True,
1166 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
1167 Expression => Node);
1169 Insert_Action (N, Temp_Decl);
1170 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1171 end if;
1173 -- Generate an additional object containing the address of the
1174 -- returned object. The type of this second object declaration
1175 -- is the correct type required for the common processing that
1176 -- is still performed by this subprogram. The displacement of
1177 -- this pointer to reference the component associated with the
1178 -- interface type will be done at the end of common processing.
1180 New_Decl :=
1181 Make_Object_Declaration (Loc,
1182 Defining_Identifier => Make_Temporary (Loc, 'P'),
1183 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1184 Expression =>
1185 Unchecked_Convert_To (PtrT,
1186 New_Occurrence_Of (Temp, Loc)));
1188 Insert_Action (N, New_Decl);
1190 Temp_Decl := New_Decl;
1191 Temp := Defining_Identifier (New_Decl);
1192 end;
1193 end if;
1195 Apply_Accessibility_Check (Temp);
1197 -- Generate the tag assignment
1199 -- Suppress the tag assignment when VM_Target because VM tags are
1200 -- represented implicitly in objects.
1202 if not Tagged_Type_Expansion then
1203 null;
1205 -- Ada 2005 (AI-251): Suppress the tag assignment with class-wide
1206 -- interface objects because in this case the tag does not change.
1208 elsif Is_Interface (Directly_Designated_Type (Etype (N))) then
1209 pragma Assert (Is_Class_Wide_Type
1210 (Directly_Designated_Type (Etype (N))));
1211 null;
1213 elsif Is_Tagged_Type (T) and then not Is_Class_Wide_Type (T) then
1214 TagT := T;
1215 TagR := New_Occurrence_Of (Temp, Loc);
1217 elsif Is_Private_Type (T)
1218 and then Is_Tagged_Type (Underlying_Type (T))
1219 then
1220 TagT := Underlying_Type (T);
1221 TagR :=
1222 Unchecked_Convert_To (Underlying_Type (T),
1223 Make_Explicit_Dereference (Loc,
1224 Prefix => New_Occurrence_Of (Temp, Loc)));
1225 end if;
1227 if Present (TagT) then
1228 declare
1229 Full_T : constant Entity_Id := Underlying_Type (TagT);
1231 begin
1232 Tag_Assign :=
1233 Make_Assignment_Statement (Loc,
1234 Name =>
1235 Make_Selected_Component (Loc,
1236 Prefix => TagR,
1237 Selector_Name =>
1238 New_Occurrence_Of
1239 (First_Tag_Component (Full_T), Loc)),
1241 Expression =>
1242 Unchecked_Convert_To (RTE (RE_Tag),
1243 New_Occurrence_Of
1244 (Elists.Node
1245 (First_Elmt (Access_Disp_Table (Full_T))), Loc)));
1246 end;
1248 -- The previous assignment has to be done in any case
1250 Set_Assignment_OK (Name (Tag_Assign));
1251 Insert_Action (N, Tag_Assign);
1252 end if;
1254 if Needs_Finalization (DesigT) and then Needs_Finalization (T) then
1256 -- Generate an Adjust call if the object will be moved. In Ada
1257 -- 2005, the object may be inherently limited, in which case
1258 -- there is no Adjust procedure, and the object is built in
1259 -- place. In Ada 95, the object can be limited but not
1260 -- inherently limited if this allocator came from a return
1261 -- statement (we're allocating the result on the secondary
1262 -- stack). In that case, the object will be moved, so we _do_
1263 -- want to Adjust.
1265 if not Aggr_In_Place
1266 and then not Is_Limited_View (T)
1267 then
1268 Insert_Action (N,
1270 -- An unchecked conversion is needed in the classwide case
1271 -- because the designated type can be an ancestor of the
1272 -- subtype mark of the allocator.
1274 Make_Adjust_Call
1275 (Obj_Ref =>
1276 Unchecked_Convert_To (T,
1277 Make_Explicit_Dereference (Loc,
1278 Prefix => New_Occurrence_Of (Temp, Loc))),
1279 Typ => T));
1280 end if;
1282 -- Generate:
1283 -- Set_Finalize_Address (<PtrT>FM, <T>FD'Unrestricted_Access);
1285 -- Do not generate this call in the following cases:
1287 -- * .NET/JVM - these targets do not support address arithmetic
1288 -- and unchecked conversion, key elements of Finalize_Address.
1290 -- * CodePeer mode - TSS primitive Finalize_Address is not
1291 -- created in this mode.
1293 if VM_Target = No_VM
1294 and then not CodePeer_Mode
1295 and then Present (Finalization_Master (PtrT))
1296 and then Present (Temp_Decl)
1297 and then Nkind (Expression (Temp_Decl)) = N_Allocator
1298 then
1299 Insert_Action (N,
1300 Make_Set_Finalize_Address_Call
1301 (Loc => Loc,
1302 Typ => T,
1303 Ptr_Typ => PtrT));
1304 end if;
1305 end if;
1307 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1308 Analyze_And_Resolve (N, PtrT);
1310 -- Ada 2005 (AI-251): Displace the pointer to reference the record
1311 -- component containing the secondary dispatch table of the interface
1312 -- type.
1314 if Is_Interface (Directly_Designated_Type (PtrT)) then
1315 Displace_Allocator_Pointer (N);
1316 end if;
1318 elsif Aggr_In_Place then
1319 Temp := Make_Temporary (Loc, 'P', N);
1320 Temp_Decl :=
1321 Make_Object_Declaration (Loc,
1322 Defining_Identifier => Temp,
1323 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1324 Expression =>
1325 Make_Allocator (Loc,
1326 Expression => New_Occurrence_Of (Etype (Exp), Loc)));
1328 -- Copy the Comes_From_Source flag for the allocator we just built,
1329 -- since logically this allocator is a replacement of the original
1330 -- allocator node. This is for proper handling of restriction
1331 -- No_Implicit_Heap_Allocations.
1333 Set_Comes_From_Source
1334 (Expression (Temp_Decl), Comes_From_Source (N));
1336 Set_No_Initialization (Expression (Temp_Decl));
1337 Insert_Action (N, Temp_Decl);
1339 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1340 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1342 -- Attach the object to the associated finalization master. Thisis
1343 -- done manually on .NET/JVM since those compilers do no support
1344 -- pools and cannot benefit from internally generated Allocate and
1345 -- Deallocate procedures.
1347 if VM_Target /= No_VM
1348 and then Is_Controlled (DesigT)
1349 and then Present (Finalization_Master (PtrT))
1350 then
1351 Insert_Action (N,
1352 Make_Attach_Call
1353 (Obj_Ref => New_Occurrence_Of (Temp, Loc),
1354 Ptr_Typ => PtrT));
1355 end if;
1357 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1358 Analyze_And_Resolve (N, PtrT);
1360 elsif Is_Access_Type (T) and then Can_Never_Be_Null (T) then
1361 Install_Null_Excluding_Check (Exp);
1363 elsif Is_Access_Type (DesigT)
1364 and then Nkind (Exp) = N_Allocator
1365 and then Nkind (Expression (Exp)) /= N_Qualified_Expression
1366 then
1367 -- Apply constraint to designated subtype indication
1369 Apply_Constraint_Check
1370 (Expression (Exp), Designated_Type (DesigT), No_Sliding => True);
1372 if Nkind (Expression (Exp)) = N_Raise_Constraint_Error then
1374 -- Propagate constraint_error to enclosing allocator
1376 Rewrite (Exp, New_Copy (Expression (Exp)));
1377 end if;
1379 else
1380 Build_Allocate_Deallocate_Proc (N, True);
1382 -- If we have:
1383 -- type A is access T1;
1384 -- X : A := new T2'(...);
1385 -- T1 and T2 can be different subtypes, and we might need to check
1386 -- both constraints. First check against the type of the qualified
1387 -- expression.
1389 Apply_Constraint_Check (Exp, T, No_Sliding => True);
1391 if Do_Range_Check (Exp) then
1392 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1393 end if;
1395 -- A check is also needed in cases where the designated subtype is
1396 -- constrained and differs from the subtype given in the qualified
1397 -- expression. Note that the check on the qualified expression does
1398 -- not allow sliding, but this check does (a relaxation from Ada 83).
1400 if Is_Constrained (DesigT)
1401 and then not Subtypes_Statically_Match (T, DesigT)
1402 then
1403 Apply_Constraint_Check
1404 (Exp, DesigT, No_Sliding => False);
1406 if Do_Range_Check (Exp) then
1407 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1408 end if;
1409 end if;
1411 -- For an access to unconstrained packed array, GIGI needs to see an
1412 -- expression with a constrained subtype in order to compute the
1413 -- proper size for the allocator.
1415 if Is_Array_Type (T)
1416 and then not Is_Constrained (T)
1417 and then Is_Packed (T)
1418 then
1419 declare
1420 ConstrT : constant Entity_Id := Make_Temporary (Loc, 'A');
1421 Internal_Exp : constant Node_Id := Relocate_Node (Exp);
1422 begin
1423 Insert_Action (Exp,
1424 Make_Subtype_Declaration (Loc,
1425 Defining_Identifier => ConstrT,
1426 Subtype_Indication =>
1427 Make_Subtype_From_Expr (Internal_Exp, T)));
1428 Freeze_Itype (ConstrT, Exp);
1429 Rewrite (Exp, OK_Convert_To (ConstrT, Internal_Exp));
1430 end;
1431 end if;
1433 -- Ada 2005 (AI-318-02): If the initialization expression is a call
1434 -- to a build-in-place function, then access to the allocated object
1435 -- must be passed to the function. Currently we limit such functions
1436 -- to those with constrained limited result subtypes, but eventually
1437 -- we plan to expand the allowed forms of functions that are treated
1438 -- as build-in-place.
1440 if Ada_Version >= Ada_2005
1441 and then Is_Build_In_Place_Function_Call (Exp)
1442 then
1443 Make_Build_In_Place_Call_In_Allocator (N, Exp);
1444 end if;
1445 end if;
1447 exception
1448 when RE_Not_Available =>
1449 return;
1450 end Expand_Allocator_Expression;
1452 -----------------------------
1453 -- Expand_Array_Comparison --
1454 -----------------------------
1456 -- Expansion is only required in the case of array types. For the unpacked
1457 -- case, an appropriate runtime routine is called. For packed cases, and
1458 -- also in some other cases where a runtime routine cannot be called, the
1459 -- form of the expansion is:
1461 -- [body for greater_nn; boolean_expression]
1463 -- The body is built by Make_Array_Comparison_Op, and the form of the
1464 -- Boolean expression depends on the operator involved.
1466 procedure Expand_Array_Comparison (N : Node_Id) is
1467 Loc : constant Source_Ptr := Sloc (N);
1468 Op1 : Node_Id := Left_Opnd (N);
1469 Op2 : Node_Id := Right_Opnd (N);
1470 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
1471 Ctyp : constant Entity_Id := Component_Type (Typ1);
1473 Expr : Node_Id;
1474 Func_Body : Node_Id;
1475 Func_Name : Entity_Id;
1477 Comp : RE_Id;
1479 Byte_Addressable : constant Boolean := System_Storage_Unit = Byte'Size;
1480 -- True for byte addressable target
1482 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean;
1483 -- Returns True if the length of the given operand is known to be less
1484 -- than 4. Returns False if this length is known to be four or greater
1485 -- or is not known at compile time.
1487 ------------------------
1488 -- Length_Less_Than_4 --
1489 ------------------------
1491 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean is
1492 Otyp : constant Entity_Id := Etype (Opnd);
1494 begin
1495 if Ekind (Otyp) = E_String_Literal_Subtype then
1496 return String_Literal_Length (Otyp) < 4;
1498 else
1499 declare
1500 Ityp : constant Entity_Id := Etype (First_Index (Otyp));
1501 Lo : constant Node_Id := Type_Low_Bound (Ityp);
1502 Hi : constant Node_Id := Type_High_Bound (Ityp);
1503 Lov : Uint;
1504 Hiv : Uint;
1506 begin
1507 if Compile_Time_Known_Value (Lo) then
1508 Lov := Expr_Value (Lo);
1509 else
1510 return False;
1511 end if;
1513 if Compile_Time_Known_Value (Hi) then
1514 Hiv := Expr_Value (Hi);
1515 else
1516 return False;
1517 end if;
1519 return Hiv < Lov + 3;
1520 end;
1521 end if;
1522 end Length_Less_Than_4;
1524 -- Start of processing for Expand_Array_Comparison
1526 begin
1527 -- Deal first with unpacked case, where we can call a runtime routine
1528 -- except that we avoid this for targets for which are not addressable
1529 -- by bytes, and for the JVM/CIL, since they do not support direct
1530 -- addressing of array components.
1532 if not Is_Bit_Packed_Array (Typ1)
1533 and then Byte_Addressable
1534 and then VM_Target = No_VM
1535 then
1536 -- The call we generate is:
1538 -- Compare_Array_xn[_Unaligned]
1539 -- (left'address, right'address, left'length, right'length) <op> 0
1541 -- x = U for unsigned, S for signed
1542 -- n = 8,16,32,64 for component size
1543 -- Add _Unaligned if length < 4 and component size is 8.
1544 -- <op> is the standard comparison operator
1546 if Component_Size (Typ1) = 8 then
1547 if Length_Less_Than_4 (Op1)
1548 or else
1549 Length_Less_Than_4 (Op2)
1550 then
1551 if Is_Unsigned_Type (Ctyp) then
1552 Comp := RE_Compare_Array_U8_Unaligned;
1553 else
1554 Comp := RE_Compare_Array_S8_Unaligned;
1555 end if;
1557 else
1558 if Is_Unsigned_Type (Ctyp) then
1559 Comp := RE_Compare_Array_U8;
1560 else
1561 Comp := RE_Compare_Array_S8;
1562 end if;
1563 end if;
1565 elsif Component_Size (Typ1) = 16 then
1566 if Is_Unsigned_Type (Ctyp) then
1567 Comp := RE_Compare_Array_U16;
1568 else
1569 Comp := RE_Compare_Array_S16;
1570 end if;
1572 elsif Component_Size (Typ1) = 32 then
1573 if Is_Unsigned_Type (Ctyp) then
1574 Comp := RE_Compare_Array_U32;
1575 else
1576 Comp := RE_Compare_Array_S32;
1577 end if;
1579 else pragma Assert (Component_Size (Typ1) = 64);
1580 if Is_Unsigned_Type (Ctyp) then
1581 Comp := RE_Compare_Array_U64;
1582 else
1583 Comp := RE_Compare_Array_S64;
1584 end if;
1585 end if;
1587 Remove_Side_Effects (Op1, Name_Req => True);
1588 Remove_Side_Effects (Op2, Name_Req => True);
1590 Rewrite (Op1,
1591 Make_Function_Call (Sloc (Op1),
1592 Name => New_Occurrence_Of (RTE (Comp), Loc),
1594 Parameter_Associations => New_List (
1595 Make_Attribute_Reference (Loc,
1596 Prefix => Relocate_Node (Op1),
1597 Attribute_Name => Name_Address),
1599 Make_Attribute_Reference (Loc,
1600 Prefix => Relocate_Node (Op2),
1601 Attribute_Name => Name_Address),
1603 Make_Attribute_Reference (Loc,
1604 Prefix => Relocate_Node (Op1),
1605 Attribute_Name => Name_Length),
1607 Make_Attribute_Reference (Loc,
1608 Prefix => Relocate_Node (Op2),
1609 Attribute_Name => Name_Length))));
1611 Rewrite (Op2,
1612 Make_Integer_Literal (Sloc (Op2),
1613 Intval => Uint_0));
1615 Analyze_And_Resolve (Op1, Standard_Integer);
1616 Analyze_And_Resolve (Op2, Standard_Integer);
1617 return;
1618 end if;
1620 -- Cases where we cannot make runtime call
1622 -- For (a <= b) we convert to not (a > b)
1624 if Chars (N) = Name_Op_Le then
1625 Rewrite (N,
1626 Make_Op_Not (Loc,
1627 Right_Opnd =>
1628 Make_Op_Gt (Loc,
1629 Left_Opnd => Op1,
1630 Right_Opnd => Op2)));
1631 Analyze_And_Resolve (N, Standard_Boolean);
1632 return;
1634 -- For < the Boolean expression is
1635 -- greater__nn (op2, op1)
1637 elsif Chars (N) = Name_Op_Lt then
1638 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1640 -- Switch operands
1642 Op1 := Right_Opnd (N);
1643 Op2 := Left_Opnd (N);
1645 -- For (a >= b) we convert to not (a < b)
1647 elsif Chars (N) = Name_Op_Ge then
1648 Rewrite (N,
1649 Make_Op_Not (Loc,
1650 Right_Opnd =>
1651 Make_Op_Lt (Loc,
1652 Left_Opnd => Op1,
1653 Right_Opnd => Op2)));
1654 Analyze_And_Resolve (N, Standard_Boolean);
1655 return;
1657 -- For > the Boolean expression is
1658 -- greater__nn (op1, op2)
1660 else
1661 pragma Assert (Chars (N) = Name_Op_Gt);
1662 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1663 end if;
1665 Func_Name := Defining_Unit_Name (Specification (Func_Body));
1666 Expr :=
1667 Make_Function_Call (Loc,
1668 Name => New_Occurrence_Of (Func_Name, Loc),
1669 Parameter_Associations => New_List (Op1, Op2));
1671 Insert_Action (N, Func_Body);
1672 Rewrite (N, Expr);
1673 Analyze_And_Resolve (N, Standard_Boolean);
1675 exception
1676 when RE_Not_Available =>
1677 return;
1678 end Expand_Array_Comparison;
1680 ---------------------------
1681 -- Expand_Array_Equality --
1682 ---------------------------
1684 -- Expand an equality function for multi-dimensional arrays. Here is an
1685 -- example of such a function for Nb_Dimension = 2
1687 -- function Enn (A : atyp; B : btyp) return boolean is
1688 -- begin
1689 -- if (A'length (1) = 0 or else A'length (2) = 0)
1690 -- and then
1691 -- (B'length (1) = 0 or else B'length (2) = 0)
1692 -- then
1693 -- return True; -- RM 4.5.2(22)
1694 -- end if;
1696 -- if A'length (1) /= B'length (1)
1697 -- or else
1698 -- A'length (2) /= B'length (2)
1699 -- then
1700 -- return False; -- RM 4.5.2(23)
1701 -- end if;
1703 -- declare
1704 -- A1 : Index_T1 := A'first (1);
1705 -- B1 : Index_T1 := B'first (1);
1706 -- begin
1707 -- loop
1708 -- declare
1709 -- A2 : Index_T2 := A'first (2);
1710 -- B2 : Index_T2 := B'first (2);
1711 -- begin
1712 -- loop
1713 -- if A (A1, A2) /= B (B1, B2) then
1714 -- return False;
1715 -- end if;
1717 -- exit when A2 = A'last (2);
1718 -- A2 := Index_T2'succ (A2);
1719 -- B2 := Index_T2'succ (B2);
1720 -- end loop;
1721 -- end;
1723 -- exit when A1 = A'last (1);
1724 -- A1 := Index_T1'succ (A1);
1725 -- B1 := Index_T1'succ (B1);
1726 -- end loop;
1727 -- end;
1729 -- return true;
1730 -- end Enn;
1732 -- Note on the formal types used (atyp and btyp). If either of the arrays
1733 -- is of a private type, we use the underlying type, and do an unchecked
1734 -- conversion of the actual. If either of the arrays has a bound depending
1735 -- on a discriminant, then we use the base type since otherwise we have an
1736 -- escaped discriminant in the function.
1738 -- If both arrays are constrained and have the same bounds, we can generate
1739 -- a loop with an explicit iteration scheme using a 'Range attribute over
1740 -- the first array.
1742 function Expand_Array_Equality
1743 (Nod : Node_Id;
1744 Lhs : Node_Id;
1745 Rhs : Node_Id;
1746 Bodies : List_Id;
1747 Typ : Entity_Id) return Node_Id
1749 Loc : constant Source_Ptr := Sloc (Nod);
1750 Decls : constant List_Id := New_List;
1751 Index_List1 : constant List_Id := New_List;
1752 Index_List2 : constant List_Id := New_List;
1754 Actuals : List_Id;
1755 Formals : List_Id;
1756 Func_Name : Entity_Id;
1757 Func_Body : Node_Id;
1759 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
1760 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
1762 Ltyp : Entity_Id;
1763 Rtyp : Entity_Id;
1764 -- The parameter types to be used for the formals
1766 function Arr_Attr
1767 (Arr : Entity_Id;
1768 Nam : Name_Id;
1769 Num : Int) return Node_Id;
1770 -- This builds the attribute reference Arr'Nam (Expr)
1772 function Component_Equality (Typ : Entity_Id) return Node_Id;
1773 -- Create one statement to compare corresponding components, designated
1774 -- by a full set of indexes.
1776 function Get_Arg_Type (N : Node_Id) return Entity_Id;
1777 -- Given one of the arguments, computes the appropriate type to be used
1778 -- for that argument in the corresponding function formal
1780 function Handle_One_Dimension
1781 (N : Int;
1782 Index : Node_Id) return Node_Id;
1783 -- This procedure returns the following code
1785 -- declare
1786 -- Bn : Index_T := B'First (N);
1787 -- begin
1788 -- loop
1789 -- xxx
1790 -- exit when An = A'Last (N);
1791 -- An := Index_T'Succ (An)
1792 -- Bn := Index_T'Succ (Bn)
1793 -- end loop;
1794 -- end;
1796 -- If both indexes are constrained and identical, the procedure
1797 -- returns a simpler loop:
1799 -- for An in A'Range (N) loop
1800 -- xxx
1801 -- end loop
1803 -- N is the dimension for which we are generating a loop. Index is the
1804 -- N'th index node, whose Etype is Index_Type_n in the above code. The
1805 -- xxx statement is either the loop or declare for the next dimension
1806 -- or if this is the last dimension the comparison of corresponding
1807 -- components of the arrays.
1809 -- The actual way the code works is to return the comparison of
1810 -- corresponding components for the N+1 call. That's neater.
1812 function Test_Empty_Arrays return Node_Id;
1813 -- This function constructs the test for both arrays being empty
1814 -- (A'length (1) = 0 or else A'length (2) = 0 or else ...)
1815 -- and then
1816 -- (B'length (1) = 0 or else B'length (2) = 0 or else ...)
1818 function Test_Lengths_Correspond return Node_Id;
1819 -- This function constructs the test for arrays having different lengths
1820 -- in at least one index position, in which case the resulting code is:
1822 -- A'length (1) /= B'length (1)
1823 -- or else
1824 -- A'length (2) /= B'length (2)
1825 -- or else
1826 -- ...
1828 --------------
1829 -- Arr_Attr --
1830 --------------
1832 function Arr_Attr
1833 (Arr : Entity_Id;
1834 Nam : Name_Id;
1835 Num : Int) return Node_Id
1837 begin
1838 return
1839 Make_Attribute_Reference (Loc,
1840 Attribute_Name => Nam,
1841 Prefix => New_Occurrence_Of (Arr, Loc),
1842 Expressions => New_List (Make_Integer_Literal (Loc, Num)));
1843 end Arr_Attr;
1845 ------------------------
1846 -- Component_Equality --
1847 ------------------------
1849 function Component_Equality (Typ : Entity_Id) return Node_Id is
1850 Test : Node_Id;
1851 L, R : Node_Id;
1853 begin
1854 -- if a(i1...) /= b(j1...) then return false; end if;
1856 L :=
1857 Make_Indexed_Component (Loc,
1858 Prefix => Make_Identifier (Loc, Chars (A)),
1859 Expressions => Index_List1);
1861 R :=
1862 Make_Indexed_Component (Loc,
1863 Prefix => Make_Identifier (Loc, Chars (B)),
1864 Expressions => Index_List2);
1866 Test := Expand_Composite_Equality
1867 (Nod, Component_Type (Typ), L, R, Decls);
1869 -- If some (sub)component is an unchecked_union, the whole operation
1870 -- will raise program error.
1872 if Nkind (Test) = N_Raise_Program_Error then
1874 -- This node is going to be inserted at a location where a
1875 -- statement is expected: clear its Etype so analysis will set
1876 -- it to the expected Standard_Void_Type.
1878 Set_Etype (Test, Empty);
1879 return Test;
1881 else
1882 return
1883 Make_Implicit_If_Statement (Nod,
1884 Condition => Make_Op_Not (Loc, Right_Opnd => Test),
1885 Then_Statements => New_List (
1886 Make_Simple_Return_Statement (Loc,
1887 Expression => New_Occurrence_Of (Standard_False, Loc))));
1888 end if;
1889 end Component_Equality;
1891 ------------------
1892 -- Get_Arg_Type --
1893 ------------------
1895 function Get_Arg_Type (N : Node_Id) return Entity_Id is
1896 T : Entity_Id;
1897 X : Node_Id;
1899 begin
1900 T := Etype (N);
1902 if No (T) then
1903 return Typ;
1905 else
1906 T := Underlying_Type (T);
1908 X := First_Index (T);
1909 while Present (X) loop
1910 if Denotes_Discriminant (Type_Low_Bound (Etype (X)))
1911 or else
1912 Denotes_Discriminant (Type_High_Bound (Etype (X)))
1913 then
1914 T := Base_Type (T);
1915 exit;
1916 end if;
1918 Next_Index (X);
1919 end loop;
1921 return T;
1922 end if;
1923 end Get_Arg_Type;
1925 --------------------------
1926 -- Handle_One_Dimension --
1927 ---------------------------
1929 function Handle_One_Dimension
1930 (N : Int;
1931 Index : Node_Id) return Node_Id
1933 Need_Separate_Indexes : constant Boolean :=
1934 Ltyp /= Rtyp or else not Is_Constrained (Ltyp);
1935 -- If the index types are identical, and we are working with
1936 -- constrained types, then we can use the same index for both
1937 -- of the arrays.
1939 An : constant Entity_Id := Make_Temporary (Loc, 'A');
1941 Bn : Entity_Id;
1942 Index_T : Entity_Id;
1943 Stm_List : List_Id;
1944 Loop_Stm : Node_Id;
1946 begin
1947 if N > Number_Dimensions (Ltyp) then
1948 return Component_Equality (Ltyp);
1949 end if;
1951 -- Case where we generate a loop
1953 Index_T := Base_Type (Etype (Index));
1955 if Need_Separate_Indexes then
1956 Bn := Make_Temporary (Loc, 'B');
1957 else
1958 Bn := An;
1959 end if;
1961 Append (New_Occurrence_Of (An, Loc), Index_List1);
1962 Append (New_Occurrence_Of (Bn, Loc), Index_List2);
1964 Stm_List := New_List (
1965 Handle_One_Dimension (N + 1, Next_Index (Index)));
1967 if Need_Separate_Indexes then
1969 -- Generate guard for loop, followed by increments of indexes
1971 Append_To (Stm_List,
1972 Make_Exit_Statement (Loc,
1973 Condition =>
1974 Make_Op_Eq (Loc,
1975 Left_Opnd => New_Occurrence_Of (An, Loc),
1976 Right_Opnd => Arr_Attr (A, Name_Last, N))));
1978 Append_To (Stm_List,
1979 Make_Assignment_Statement (Loc,
1980 Name => New_Occurrence_Of (An, Loc),
1981 Expression =>
1982 Make_Attribute_Reference (Loc,
1983 Prefix => New_Occurrence_Of (Index_T, Loc),
1984 Attribute_Name => Name_Succ,
1985 Expressions => New_List (
1986 New_Occurrence_Of (An, Loc)))));
1988 Append_To (Stm_List,
1989 Make_Assignment_Statement (Loc,
1990 Name => New_Occurrence_Of (Bn, Loc),
1991 Expression =>
1992 Make_Attribute_Reference (Loc,
1993 Prefix => New_Occurrence_Of (Index_T, Loc),
1994 Attribute_Name => Name_Succ,
1995 Expressions => New_List (
1996 New_Occurrence_Of (Bn, Loc)))));
1997 end if;
1999 -- If separate indexes, we need a declare block for An and Bn, and a
2000 -- loop without an iteration scheme.
2002 if Need_Separate_Indexes then
2003 Loop_Stm :=
2004 Make_Implicit_Loop_Statement (Nod, Statements => Stm_List);
2006 return
2007 Make_Block_Statement (Loc,
2008 Declarations => New_List (
2009 Make_Object_Declaration (Loc,
2010 Defining_Identifier => An,
2011 Object_Definition => New_Occurrence_Of (Index_T, Loc),
2012 Expression => Arr_Attr (A, Name_First, N)),
2014 Make_Object_Declaration (Loc,
2015 Defining_Identifier => Bn,
2016 Object_Definition => New_Occurrence_Of (Index_T, Loc),
2017 Expression => Arr_Attr (B, Name_First, N))),
2019 Handled_Statement_Sequence =>
2020 Make_Handled_Sequence_Of_Statements (Loc,
2021 Statements => New_List (Loop_Stm)));
2023 -- If no separate indexes, return loop statement with explicit
2024 -- iteration scheme on its own
2026 else
2027 Loop_Stm :=
2028 Make_Implicit_Loop_Statement (Nod,
2029 Statements => Stm_List,
2030 Iteration_Scheme =>
2031 Make_Iteration_Scheme (Loc,
2032 Loop_Parameter_Specification =>
2033 Make_Loop_Parameter_Specification (Loc,
2034 Defining_Identifier => An,
2035 Discrete_Subtype_Definition =>
2036 Arr_Attr (A, Name_Range, N))));
2037 return Loop_Stm;
2038 end if;
2039 end Handle_One_Dimension;
2041 -----------------------
2042 -- Test_Empty_Arrays --
2043 -----------------------
2045 function Test_Empty_Arrays return Node_Id is
2046 Alist : Node_Id;
2047 Blist : Node_Id;
2049 Atest : Node_Id;
2050 Btest : Node_Id;
2052 begin
2053 Alist := Empty;
2054 Blist := Empty;
2055 for J in 1 .. Number_Dimensions (Ltyp) loop
2056 Atest :=
2057 Make_Op_Eq (Loc,
2058 Left_Opnd => Arr_Attr (A, Name_Length, J),
2059 Right_Opnd => Make_Integer_Literal (Loc, 0));
2061 Btest :=
2062 Make_Op_Eq (Loc,
2063 Left_Opnd => Arr_Attr (B, Name_Length, J),
2064 Right_Opnd => Make_Integer_Literal (Loc, 0));
2066 if No (Alist) then
2067 Alist := Atest;
2068 Blist := Btest;
2070 else
2071 Alist :=
2072 Make_Or_Else (Loc,
2073 Left_Opnd => Relocate_Node (Alist),
2074 Right_Opnd => Atest);
2076 Blist :=
2077 Make_Or_Else (Loc,
2078 Left_Opnd => Relocate_Node (Blist),
2079 Right_Opnd => Btest);
2080 end if;
2081 end loop;
2083 return
2084 Make_And_Then (Loc,
2085 Left_Opnd => Alist,
2086 Right_Opnd => Blist);
2087 end Test_Empty_Arrays;
2089 -----------------------------
2090 -- Test_Lengths_Correspond --
2091 -----------------------------
2093 function Test_Lengths_Correspond return Node_Id is
2094 Result : Node_Id;
2095 Rtest : Node_Id;
2097 begin
2098 Result := Empty;
2099 for J in 1 .. Number_Dimensions (Ltyp) loop
2100 Rtest :=
2101 Make_Op_Ne (Loc,
2102 Left_Opnd => Arr_Attr (A, Name_Length, J),
2103 Right_Opnd => Arr_Attr (B, Name_Length, J));
2105 if No (Result) then
2106 Result := Rtest;
2107 else
2108 Result :=
2109 Make_Or_Else (Loc,
2110 Left_Opnd => Relocate_Node (Result),
2111 Right_Opnd => Rtest);
2112 end if;
2113 end loop;
2115 return Result;
2116 end Test_Lengths_Correspond;
2118 -- Start of processing for Expand_Array_Equality
2120 begin
2121 Ltyp := Get_Arg_Type (Lhs);
2122 Rtyp := Get_Arg_Type (Rhs);
2124 -- For now, if the argument types are not the same, go to the base type,
2125 -- since the code assumes that the formals have the same type. This is
2126 -- fixable in future ???
2128 if Ltyp /= Rtyp then
2129 Ltyp := Base_Type (Ltyp);
2130 Rtyp := Base_Type (Rtyp);
2131 pragma Assert (Ltyp = Rtyp);
2132 end if;
2134 -- Build list of formals for function
2136 Formals := New_List (
2137 Make_Parameter_Specification (Loc,
2138 Defining_Identifier => A,
2139 Parameter_Type => New_Occurrence_Of (Ltyp, Loc)),
2141 Make_Parameter_Specification (Loc,
2142 Defining_Identifier => B,
2143 Parameter_Type => New_Occurrence_Of (Rtyp, Loc)));
2145 Func_Name := Make_Temporary (Loc, 'E');
2147 -- Build statement sequence for function
2149 Func_Body :=
2150 Make_Subprogram_Body (Loc,
2151 Specification =>
2152 Make_Function_Specification (Loc,
2153 Defining_Unit_Name => Func_Name,
2154 Parameter_Specifications => Formals,
2155 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
2157 Declarations => Decls,
2159 Handled_Statement_Sequence =>
2160 Make_Handled_Sequence_Of_Statements (Loc,
2161 Statements => New_List (
2163 Make_Implicit_If_Statement (Nod,
2164 Condition => Test_Empty_Arrays,
2165 Then_Statements => New_List (
2166 Make_Simple_Return_Statement (Loc,
2167 Expression =>
2168 New_Occurrence_Of (Standard_True, Loc)))),
2170 Make_Implicit_If_Statement (Nod,
2171 Condition => Test_Lengths_Correspond,
2172 Then_Statements => New_List (
2173 Make_Simple_Return_Statement (Loc,
2174 Expression => New_Occurrence_Of (Standard_False, Loc)))),
2176 Handle_One_Dimension (1, First_Index (Ltyp)),
2178 Make_Simple_Return_Statement (Loc,
2179 Expression => New_Occurrence_Of (Standard_True, Loc)))));
2181 Set_Has_Completion (Func_Name, True);
2182 Set_Is_Inlined (Func_Name);
2184 -- If the array type is distinct from the type of the arguments, it
2185 -- is the full view of a private type. Apply an unchecked conversion
2186 -- to insure that analysis of the call succeeds.
2188 declare
2189 L, R : Node_Id;
2191 begin
2192 L := Lhs;
2193 R := Rhs;
2195 if No (Etype (Lhs))
2196 or else Base_Type (Etype (Lhs)) /= Base_Type (Ltyp)
2197 then
2198 L := OK_Convert_To (Ltyp, Lhs);
2199 end if;
2201 if No (Etype (Rhs))
2202 or else Base_Type (Etype (Rhs)) /= Base_Type (Rtyp)
2203 then
2204 R := OK_Convert_To (Rtyp, Rhs);
2205 end if;
2207 Actuals := New_List (L, R);
2208 end;
2210 Append_To (Bodies, Func_Body);
2212 return
2213 Make_Function_Call (Loc,
2214 Name => New_Occurrence_Of (Func_Name, Loc),
2215 Parameter_Associations => Actuals);
2216 end Expand_Array_Equality;
2218 -----------------------------
2219 -- Expand_Boolean_Operator --
2220 -----------------------------
2222 -- Note that we first get the actual subtypes of the operands, since we
2223 -- always want to deal with types that have bounds.
2225 procedure Expand_Boolean_Operator (N : Node_Id) is
2226 Typ : constant Entity_Id := Etype (N);
2228 begin
2229 -- Special case of bit packed array where both operands are known to be
2230 -- properly aligned. In this case we use an efficient run time routine
2231 -- to carry out the operation (see System.Bit_Ops).
2233 if Is_Bit_Packed_Array (Typ)
2234 and then not Is_Possibly_Unaligned_Object (Left_Opnd (N))
2235 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
2236 then
2237 Expand_Packed_Boolean_Operator (N);
2238 return;
2239 end if;
2241 -- For the normal non-packed case, the general expansion is to build
2242 -- function for carrying out the comparison (use Make_Boolean_Array_Op)
2243 -- and then inserting it into the tree. The original operator node is
2244 -- then rewritten as a call to this function. We also use this in the
2245 -- packed case if either operand is a possibly unaligned object.
2247 declare
2248 Loc : constant Source_Ptr := Sloc (N);
2249 L : constant Node_Id := Relocate_Node (Left_Opnd (N));
2250 R : constant Node_Id := Relocate_Node (Right_Opnd (N));
2251 Func_Body : Node_Id;
2252 Func_Name : Entity_Id;
2254 begin
2255 Convert_To_Actual_Subtype (L);
2256 Convert_To_Actual_Subtype (R);
2257 Ensure_Defined (Etype (L), N);
2258 Ensure_Defined (Etype (R), N);
2259 Apply_Length_Check (R, Etype (L));
2261 if Nkind (N) = N_Op_Xor then
2262 Silly_Boolean_Array_Xor_Test (N, Etype (L));
2263 end if;
2265 if Nkind (Parent (N)) = N_Assignment_Statement
2266 and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
2267 then
2268 Build_Boolean_Array_Proc_Call (Parent (N), L, R);
2270 elsif Nkind (Parent (N)) = N_Op_Not
2271 and then Nkind (N) = N_Op_And
2272 and then Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
2273 then
2274 return;
2275 else
2277 Func_Body := Make_Boolean_Array_Op (Etype (L), N);
2278 Func_Name := Defining_Unit_Name (Specification (Func_Body));
2279 Insert_Action (N, Func_Body);
2281 -- Now rewrite the expression with a call
2283 Rewrite (N,
2284 Make_Function_Call (Loc,
2285 Name => New_Occurrence_Of (Func_Name, Loc),
2286 Parameter_Associations =>
2287 New_List (
2289 Make_Type_Conversion
2290 (Loc, New_Occurrence_Of (Etype (L), Loc), R))));
2292 Analyze_And_Resolve (N, Typ);
2293 end if;
2294 end;
2295 end Expand_Boolean_Operator;
2297 ------------------------------------------------
2298 -- Expand_Compare_Minimize_Eliminate_Overflow --
2299 ------------------------------------------------
2301 procedure Expand_Compare_Minimize_Eliminate_Overflow (N : Node_Id) is
2302 Loc : constant Source_Ptr := Sloc (N);
2304 Result_Type : constant Entity_Id := Etype (N);
2305 -- Capture result type (could be a derived boolean type)
2307 Llo, Lhi : Uint;
2308 Rlo, Rhi : Uint;
2310 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
2311 -- Entity for Long_Long_Integer'Base
2313 Check : constant Overflow_Mode_Type := Overflow_Check_Mode;
2314 -- Current overflow checking mode
2316 procedure Set_True;
2317 procedure Set_False;
2318 -- These procedures rewrite N with an occurrence of Standard_True or
2319 -- Standard_False, and then makes a call to Warn_On_Known_Condition.
2321 ---------------
2322 -- Set_False --
2323 ---------------
2325 procedure Set_False is
2326 begin
2327 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
2328 Warn_On_Known_Condition (N);
2329 end Set_False;
2331 --------------
2332 -- Set_True --
2333 --------------
2335 procedure Set_True is
2336 begin
2337 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
2338 Warn_On_Known_Condition (N);
2339 end Set_True;
2341 -- Start of processing for Expand_Compare_Minimize_Eliminate_Overflow
2343 begin
2344 -- Nothing to do unless we have a comparison operator with operands
2345 -- that are signed integer types, and we are operating in either
2346 -- MINIMIZED or ELIMINATED overflow checking mode.
2348 if Nkind (N) not in N_Op_Compare
2349 or else Check not in Minimized_Or_Eliminated
2350 or else not Is_Signed_Integer_Type (Etype (Left_Opnd (N)))
2351 then
2352 return;
2353 end if;
2355 -- OK, this is the case we are interested in. First step is to process
2356 -- our operands using the Minimize_Eliminate circuitry which applies
2357 -- this processing to the two operand subtrees.
2359 Minimize_Eliminate_Overflows
2360 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
2361 Minimize_Eliminate_Overflows
2362 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
2364 -- See if the range information decides the result of the comparison.
2365 -- We can only do this if we in fact have full range information (which
2366 -- won't be the case if either operand is bignum at this stage).
2368 if Llo /= No_Uint and then Rlo /= No_Uint then
2369 case N_Op_Compare (Nkind (N)) is
2370 when N_Op_Eq =>
2371 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2372 Set_True;
2373 elsif Llo > Rhi or else Lhi < Rlo then
2374 Set_False;
2375 end if;
2377 when N_Op_Ge =>
2378 if Llo >= Rhi then
2379 Set_True;
2380 elsif Lhi < Rlo then
2381 Set_False;
2382 end if;
2384 when N_Op_Gt =>
2385 if Llo > Rhi then
2386 Set_True;
2387 elsif Lhi <= Rlo then
2388 Set_False;
2389 end if;
2391 when N_Op_Le =>
2392 if Llo > Rhi then
2393 Set_False;
2394 elsif Lhi <= Rlo then
2395 Set_True;
2396 end if;
2398 when N_Op_Lt =>
2399 if Llo >= Rhi then
2400 Set_False;
2401 elsif Lhi < Rlo then
2402 Set_True;
2403 end if;
2405 when N_Op_Ne =>
2406 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2407 Set_False;
2408 elsif Llo > Rhi or else Lhi < Rlo then
2409 Set_True;
2410 end if;
2411 end case;
2413 -- All done if we did the rewrite
2415 if Nkind (N) not in N_Op_Compare then
2416 return;
2417 end if;
2418 end if;
2420 -- Otherwise, time to do the comparison
2422 declare
2423 Ltype : constant Entity_Id := Etype (Left_Opnd (N));
2424 Rtype : constant Entity_Id := Etype (Right_Opnd (N));
2426 begin
2427 -- If the two operands have the same signed integer type we are
2428 -- all set, nothing more to do. This is the case where either
2429 -- both operands were unchanged, or we rewrote both of them to
2430 -- be Long_Long_Integer.
2432 -- Note: Entity for the comparison may be wrong, but it's not worth
2433 -- the effort to change it, since the back end does not use it.
2435 if Is_Signed_Integer_Type (Ltype)
2436 and then Base_Type (Ltype) = Base_Type (Rtype)
2437 then
2438 return;
2440 -- Here if bignums are involved (can only happen in ELIMINATED mode)
2442 elsif Is_RTE (Ltype, RE_Bignum) or else Is_RTE (Rtype, RE_Bignum) then
2443 declare
2444 Left : Node_Id := Left_Opnd (N);
2445 Right : Node_Id := Right_Opnd (N);
2446 -- Bignum references for left and right operands
2448 begin
2449 if not Is_RTE (Ltype, RE_Bignum) then
2450 Left := Convert_To_Bignum (Left);
2451 elsif not Is_RTE (Rtype, RE_Bignum) then
2452 Right := Convert_To_Bignum (Right);
2453 end if;
2455 -- We rewrite our node with:
2457 -- do
2458 -- Bnn : Result_Type;
2459 -- declare
2460 -- M : Mark_Id := SS_Mark;
2461 -- begin
2462 -- Bnn := Big_xx (Left, Right); (xx = EQ, NT etc)
2463 -- SS_Release (M);
2464 -- end;
2465 -- in
2466 -- Bnn
2467 -- end
2469 declare
2470 Blk : constant Node_Id := Make_Bignum_Block (Loc);
2471 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
2472 Ent : RE_Id;
2474 begin
2475 case N_Op_Compare (Nkind (N)) is
2476 when N_Op_Eq => Ent := RE_Big_EQ;
2477 when N_Op_Ge => Ent := RE_Big_GE;
2478 when N_Op_Gt => Ent := RE_Big_GT;
2479 when N_Op_Le => Ent := RE_Big_LE;
2480 when N_Op_Lt => Ent := RE_Big_LT;
2481 when N_Op_Ne => Ent := RE_Big_NE;
2482 end case;
2484 -- Insert assignment to Bnn into the bignum block
2486 Insert_Before
2487 (First (Statements (Handled_Statement_Sequence (Blk))),
2488 Make_Assignment_Statement (Loc,
2489 Name => New_Occurrence_Of (Bnn, Loc),
2490 Expression =>
2491 Make_Function_Call (Loc,
2492 Name =>
2493 New_Occurrence_Of (RTE (Ent), Loc),
2494 Parameter_Associations => New_List (Left, Right))));
2496 -- Now do the rewrite with expression actions
2498 Rewrite (N,
2499 Make_Expression_With_Actions (Loc,
2500 Actions => New_List (
2501 Make_Object_Declaration (Loc,
2502 Defining_Identifier => Bnn,
2503 Object_Definition =>
2504 New_Occurrence_Of (Result_Type, Loc)),
2505 Blk),
2506 Expression => New_Occurrence_Of (Bnn, Loc)));
2507 Analyze_And_Resolve (N, Result_Type);
2508 end;
2509 end;
2511 -- No bignums involved, but types are different, so we must have
2512 -- rewritten one of the operands as a Long_Long_Integer but not
2513 -- the other one.
2515 -- If left operand is Long_Long_Integer, convert right operand
2516 -- and we are done (with a comparison of two Long_Long_Integers).
2518 elsif Ltype = LLIB then
2519 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
2520 Analyze_And_Resolve (Right_Opnd (N), LLIB, Suppress => All_Checks);
2521 return;
2523 -- If right operand is Long_Long_Integer, convert left operand
2524 -- and we are done (with a comparison of two Long_Long_Integers).
2526 -- This is the only remaining possibility
2528 else pragma Assert (Rtype = LLIB);
2529 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
2530 Analyze_And_Resolve (Left_Opnd (N), LLIB, Suppress => All_Checks);
2531 return;
2532 end if;
2533 end;
2534 end Expand_Compare_Minimize_Eliminate_Overflow;
2536 -------------------------------
2537 -- Expand_Composite_Equality --
2538 -------------------------------
2540 -- This function is only called for comparing internal fields of composite
2541 -- types when these fields are themselves composites. This is a special
2542 -- case because it is not possible to respect normal Ada visibility rules.
2544 function Expand_Composite_Equality
2545 (Nod : Node_Id;
2546 Typ : Entity_Id;
2547 Lhs : Node_Id;
2548 Rhs : Node_Id;
2549 Bodies : List_Id) return Node_Id
2551 Loc : constant Source_Ptr := Sloc (Nod);
2552 Full_Type : Entity_Id;
2553 Prim : Elmt_Id;
2554 Eq_Op : Entity_Id;
2556 function Find_Primitive_Eq return Node_Id;
2557 -- AI05-0123: Locate primitive equality for type if it exists, and
2558 -- build the corresponding call. If operation is abstract, replace
2559 -- call with an explicit raise. Return Empty if there is no primitive.
2561 -----------------------
2562 -- Find_Primitive_Eq --
2563 -----------------------
2565 function Find_Primitive_Eq return Node_Id is
2566 Prim_E : Elmt_Id;
2567 Prim : Node_Id;
2569 begin
2570 Prim_E := First_Elmt (Collect_Primitive_Operations (Typ));
2571 while Present (Prim_E) loop
2572 Prim := Node (Prim_E);
2574 -- Locate primitive equality with the right signature
2576 if Chars (Prim) = Name_Op_Eq
2577 and then Etype (First_Formal (Prim)) =
2578 Etype (Next_Formal (First_Formal (Prim)))
2579 and then Etype (Prim) = Standard_Boolean
2580 then
2581 if Is_Abstract_Subprogram (Prim) then
2582 return
2583 Make_Raise_Program_Error (Loc,
2584 Reason => PE_Explicit_Raise);
2586 else
2587 return
2588 Make_Function_Call (Loc,
2589 Name => New_Occurrence_Of (Prim, Loc),
2590 Parameter_Associations => New_List (Lhs, Rhs));
2591 end if;
2592 end if;
2594 Next_Elmt (Prim_E);
2595 end loop;
2597 -- If not found, predefined operation will be used
2599 return Empty;
2600 end Find_Primitive_Eq;
2602 -- Start of processing for Expand_Composite_Equality
2604 begin
2605 if Is_Private_Type (Typ) then
2606 Full_Type := Underlying_Type (Typ);
2607 else
2608 Full_Type := Typ;
2609 end if;
2611 -- If the private type has no completion the context may be the
2612 -- expansion of a composite equality for a composite type with some
2613 -- still incomplete components. The expression will not be analyzed
2614 -- until the enclosing type is completed, at which point this will be
2615 -- properly expanded, unless there is a bona fide completion error.
2617 if No (Full_Type) then
2618 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2619 end if;
2621 Full_Type := Base_Type (Full_Type);
2623 -- When the base type itself is private, use the full view to expand
2624 -- the composite equality.
2626 if Is_Private_Type (Full_Type) then
2627 Full_Type := Underlying_Type (Full_Type);
2628 end if;
2630 -- Case of array types
2632 if Is_Array_Type (Full_Type) then
2634 -- If the operand is an elementary type other than a floating-point
2635 -- type, then we can simply use the built-in block bitwise equality,
2636 -- since the predefined equality operators always apply and bitwise
2637 -- equality is fine for all these cases.
2639 if Is_Elementary_Type (Component_Type (Full_Type))
2640 and then not Is_Floating_Point_Type (Component_Type (Full_Type))
2641 then
2642 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2644 -- For composite component types, and floating-point types, use the
2645 -- expansion. This deals with tagged component types (where we use
2646 -- the applicable equality routine) and floating-point, (where we
2647 -- need to worry about negative zeroes), and also the case of any
2648 -- composite type recursively containing such fields.
2650 else
2651 return Expand_Array_Equality (Nod, Lhs, Rhs, Bodies, Full_Type);
2652 end if;
2654 -- Case of tagged record types
2656 elsif Is_Tagged_Type (Full_Type) then
2658 -- Call the primitive operation "=" of this type
2660 if Is_Class_Wide_Type (Full_Type) then
2661 Full_Type := Root_Type (Full_Type);
2662 end if;
2664 -- If this is derived from an untagged private type completed with a
2665 -- tagged type, it does not have a full view, so we use the primitive
2666 -- operations of the private type. This check should no longer be
2667 -- necessary when these types receive their full views ???
2669 if Is_Private_Type (Typ)
2670 and then not Is_Tagged_Type (Typ)
2671 and then not Is_Controlled (Typ)
2672 and then Is_Derived_Type (Typ)
2673 and then No (Full_View (Typ))
2674 then
2675 Prim := First_Elmt (Collect_Primitive_Operations (Typ));
2676 else
2677 Prim := First_Elmt (Primitive_Operations (Full_Type));
2678 end if;
2680 loop
2681 Eq_Op := Node (Prim);
2682 exit when Chars (Eq_Op) = Name_Op_Eq
2683 and then Etype (First_Formal (Eq_Op)) =
2684 Etype (Next_Formal (First_Formal (Eq_Op)))
2685 and then Base_Type (Etype (Eq_Op)) = Standard_Boolean;
2686 Next_Elmt (Prim);
2687 pragma Assert (Present (Prim));
2688 end loop;
2690 Eq_Op := Node (Prim);
2692 return
2693 Make_Function_Call (Loc,
2694 Name => New_Occurrence_Of (Eq_Op, Loc),
2695 Parameter_Associations =>
2696 New_List
2697 (Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Lhs),
2698 Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Rhs)));
2700 -- Case of untagged record types
2702 elsif Is_Record_Type (Full_Type) then
2703 Eq_Op := TSS (Full_Type, TSS_Composite_Equality);
2705 if Present (Eq_Op) then
2706 if Etype (First_Formal (Eq_Op)) /= Full_Type then
2708 -- Inherited equality from parent type. Convert the actuals to
2709 -- match signature of operation.
2711 declare
2712 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2714 begin
2715 return
2716 Make_Function_Call (Loc,
2717 Name => New_Occurrence_Of (Eq_Op, Loc),
2718 Parameter_Associations => New_List (
2719 OK_Convert_To (T, Lhs),
2720 OK_Convert_To (T, Rhs)));
2721 end;
2723 else
2724 -- Comparison between Unchecked_Union components
2726 if Is_Unchecked_Union (Full_Type) then
2727 declare
2728 Lhs_Type : Node_Id := Full_Type;
2729 Rhs_Type : Node_Id := Full_Type;
2730 Lhs_Discr_Val : Node_Id;
2731 Rhs_Discr_Val : Node_Id;
2733 begin
2734 -- Lhs subtype
2736 if Nkind (Lhs) = N_Selected_Component then
2737 Lhs_Type := Etype (Entity (Selector_Name (Lhs)));
2738 end if;
2740 -- Rhs subtype
2742 if Nkind (Rhs) = N_Selected_Component then
2743 Rhs_Type := Etype (Entity (Selector_Name (Rhs)));
2744 end if;
2746 -- Lhs of the composite equality
2748 if Is_Constrained (Lhs_Type) then
2750 -- Since the enclosing record type can never be an
2751 -- Unchecked_Union (this code is executed for records
2752 -- that do not have variants), we may reference its
2753 -- discriminant(s).
2755 if Nkind (Lhs) = N_Selected_Component
2756 and then Has_Per_Object_Constraint
2757 (Entity (Selector_Name (Lhs)))
2758 then
2759 Lhs_Discr_Val :=
2760 Make_Selected_Component (Loc,
2761 Prefix => Prefix (Lhs),
2762 Selector_Name =>
2763 New_Copy
2764 (Get_Discriminant_Value
2765 (First_Discriminant (Lhs_Type),
2766 Lhs_Type,
2767 Stored_Constraint (Lhs_Type))));
2769 else
2770 Lhs_Discr_Val :=
2771 New_Copy
2772 (Get_Discriminant_Value
2773 (First_Discriminant (Lhs_Type),
2774 Lhs_Type,
2775 Stored_Constraint (Lhs_Type)));
2777 end if;
2778 else
2779 -- It is not possible to infer the discriminant since
2780 -- the subtype is not constrained.
2782 return
2783 Make_Raise_Program_Error (Loc,
2784 Reason => PE_Unchecked_Union_Restriction);
2785 end if;
2787 -- Rhs of the composite equality
2789 if Is_Constrained (Rhs_Type) then
2790 if Nkind (Rhs) = N_Selected_Component
2791 and then Has_Per_Object_Constraint
2792 (Entity (Selector_Name (Rhs)))
2793 then
2794 Rhs_Discr_Val :=
2795 Make_Selected_Component (Loc,
2796 Prefix => Prefix (Rhs),
2797 Selector_Name =>
2798 New_Copy
2799 (Get_Discriminant_Value
2800 (First_Discriminant (Rhs_Type),
2801 Rhs_Type,
2802 Stored_Constraint (Rhs_Type))));
2804 else
2805 Rhs_Discr_Val :=
2806 New_Copy
2807 (Get_Discriminant_Value
2808 (First_Discriminant (Rhs_Type),
2809 Rhs_Type,
2810 Stored_Constraint (Rhs_Type)));
2812 end if;
2813 else
2814 return
2815 Make_Raise_Program_Error (Loc,
2816 Reason => PE_Unchecked_Union_Restriction);
2817 end if;
2819 -- Call the TSS equality function with the inferred
2820 -- discriminant values.
2822 return
2823 Make_Function_Call (Loc,
2824 Name => New_Occurrence_Of (Eq_Op, Loc),
2825 Parameter_Associations => New_List (
2826 Lhs,
2827 Rhs,
2828 Lhs_Discr_Val,
2829 Rhs_Discr_Val));
2830 end;
2832 -- All cases other than comparing Unchecked_Union types
2834 else
2835 declare
2836 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2837 begin
2838 return
2839 Make_Function_Call (Loc,
2840 Name =>
2841 New_Occurrence_Of (Eq_Op, Loc),
2842 Parameter_Associations => New_List (
2843 OK_Convert_To (T, Lhs),
2844 OK_Convert_To (T, Rhs)));
2845 end;
2846 end if;
2847 end if;
2849 -- Equality composes in Ada 2012 for untagged record types. It also
2850 -- composes for bounded strings, because they are part of the
2851 -- predefined environment. We could make it compose for bounded
2852 -- strings by making them tagged, or by making sure all subcomponents
2853 -- are set to the same value, even when not used. Instead, we have
2854 -- this special case in the compiler, because it's more efficient.
2856 elsif Ada_Version >= Ada_2012 or else Is_Bounded_String (Typ) then
2858 -- If no TSS has been created for the type, check whether there is
2859 -- a primitive equality declared for it.
2861 declare
2862 Op : constant Node_Id := Find_Primitive_Eq;
2864 begin
2865 -- Use user-defined primitive if it exists, otherwise use
2866 -- predefined equality.
2868 if Present (Op) then
2869 return Op;
2870 else
2871 return Make_Op_Eq (Loc, Lhs, Rhs);
2872 end if;
2873 end;
2875 else
2876 return Expand_Record_Equality (Nod, Full_Type, Lhs, Rhs, Bodies);
2877 end if;
2879 -- Non-composite types (always use predefined equality)
2881 else
2882 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2883 end if;
2884 end Expand_Composite_Equality;
2886 ------------------------
2887 -- Expand_Concatenate --
2888 ------------------------
2890 procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id) is
2891 Loc : constant Source_Ptr := Sloc (Cnode);
2893 Atyp : constant Entity_Id := Base_Type (Etype (Cnode));
2894 -- Result type of concatenation
2896 Ctyp : constant Entity_Id := Base_Type (Component_Type (Etype (Cnode)));
2897 -- Component type. Elements of this component type can appear as one
2898 -- of the operands of concatenation as well as arrays.
2900 Istyp : constant Entity_Id := Etype (First_Index (Atyp));
2901 -- Index subtype
2903 Ityp : constant Entity_Id := Base_Type (Istyp);
2904 -- Index type. This is the base type of the index subtype, and is used
2905 -- for all computed bounds (which may be out of range of Istyp in the
2906 -- case of null ranges).
2908 Artyp : Entity_Id;
2909 -- This is the type we use to do arithmetic to compute the bounds and
2910 -- lengths of operands. The choice of this type is a little subtle and
2911 -- is discussed in a separate section at the start of the body code.
2913 Concatenation_Error : exception;
2914 -- Raised if concatenation is sure to raise a CE
2916 Result_May_Be_Null : Boolean := True;
2917 -- Reset to False if at least one operand is encountered which is known
2918 -- at compile time to be non-null. Used for handling the special case
2919 -- of setting the high bound to the last operand high bound for a null
2920 -- result, thus ensuring a proper high bound in the super-flat case.
2922 N : constant Nat := List_Length (Opnds);
2923 -- Number of concatenation operands including possibly null operands
2925 NN : Nat := 0;
2926 -- Number of operands excluding any known to be null, except that the
2927 -- last operand is always retained, in case it provides the bounds for
2928 -- a null result.
2930 Opnd : Node_Id;
2931 -- Current operand being processed in the loop through operands. After
2932 -- this loop is complete, always contains the last operand (which is not
2933 -- the same as Operands (NN), since null operands are skipped).
2935 -- Arrays describing the operands, only the first NN entries of each
2936 -- array are set (NN < N when we exclude known null operands).
2938 Is_Fixed_Length : array (1 .. N) of Boolean;
2939 -- True if length of corresponding operand known at compile time
2941 Operands : array (1 .. N) of Node_Id;
2942 -- Set to the corresponding entry in the Opnds list (but note that null
2943 -- operands are excluded, so not all entries in the list are stored).
2945 Fixed_Length : array (1 .. N) of Uint;
2946 -- Set to length of operand. Entries in this array are set only if the
2947 -- corresponding entry in Is_Fixed_Length is True.
2949 Opnd_Low_Bound : array (1 .. N) of Node_Id;
2950 -- Set to lower bound of operand. Either an integer literal in the case
2951 -- where the bound is known at compile time, else actual lower bound.
2952 -- The operand low bound is of type Ityp.
2954 Var_Length : array (1 .. N) of Entity_Id;
2955 -- Set to an entity of type Natural that contains the length of an
2956 -- operand whose length is not known at compile time. Entries in this
2957 -- array are set only if the corresponding entry in Is_Fixed_Length
2958 -- is False. The entity is of type Artyp.
2960 Aggr_Length : array (0 .. N) of Node_Id;
2961 -- The J'th entry in an expression node that represents the total length
2962 -- of operands 1 through J. It is either an integer literal node, or a
2963 -- reference to a constant entity with the right value, so it is fine
2964 -- to just do a Copy_Node to get an appropriate copy. The extra zero'th
2965 -- entry always is set to zero. The length is of type Artyp.
2967 Low_Bound : Node_Id;
2968 -- A tree node representing the low bound of the result (of type Ityp).
2969 -- This is either an integer literal node, or an identifier reference to
2970 -- a constant entity initialized to the appropriate value.
2972 Last_Opnd_Low_Bound : Node_Id;
2973 -- A tree node representing the low bound of the last operand. This
2974 -- need only be set if the result could be null. It is used for the
2975 -- special case of setting the right low bound for a null result.
2976 -- This is of type Ityp.
2978 Last_Opnd_High_Bound : Node_Id;
2979 -- A tree node representing the high bound of the last operand. This
2980 -- need only be set if the result could be null. It is used for the
2981 -- special case of setting the right high bound for a null result.
2982 -- This is of type Ityp.
2984 High_Bound : Node_Id;
2985 -- A tree node representing the high bound of the result (of type Ityp)
2987 Result : Node_Id;
2988 -- Result of the concatenation (of type Ityp)
2990 Actions : constant List_Id := New_List;
2991 -- Collect actions to be inserted
2993 Known_Non_Null_Operand_Seen : Boolean;
2994 -- Set True during generation of the assignments of operands into
2995 -- result once an operand known to be non-null has been seen.
2997 function Make_Artyp_Literal (Val : Nat) return Node_Id;
2998 -- This function makes an N_Integer_Literal node that is returned in
2999 -- analyzed form with the type set to Artyp. Importantly this literal
3000 -- is not flagged as static, so that if we do computations with it that
3001 -- result in statically detected out of range conditions, we will not
3002 -- generate error messages but instead warning messages.
3004 function To_Artyp (X : Node_Id) return Node_Id;
3005 -- Given a node of type Ityp, returns the corresponding value of type
3006 -- Artyp. For non-enumeration types, this is a plain integer conversion.
3007 -- For enum types, the Pos of the value is returned.
3009 function To_Ityp (X : Node_Id) return Node_Id;
3010 -- The inverse function (uses Val in the case of enumeration types)
3012 ------------------------
3013 -- Make_Artyp_Literal --
3014 ------------------------
3016 function Make_Artyp_Literal (Val : Nat) return Node_Id is
3017 Result : constant Node_Id := Make_Integer_Literal (Loc, Val);
3018 begin
3019 Set_Etype (Result, Artyp);
3020 Set_Analyzed (Result, True);
3021 Set_Is_Static_Expression (Result, False);
3022 return Result;
3023 end Make_Artyp_Literal;
3025 --------------
3026 -- To_Artyp --
3027 --------------
3029 function To_Artyp (X : Node_Id) return Node_Id is
3030 begin
3031 if Ityp = Base_Type (Artyp) then
3032 return X;
3034 elsif Is_Enumeration_Type (Ityp) then
3035 return
3036 Make_Attribute_Reference (Loc,
3037 Prefix => New_Occurrence_Of (Ityp, Loc),
3038 Attribute_Name => Name_Pos,
3039 Expressions => New_List (X));
3041 else
3042 return Convert_To (Artyp, X);
3043 end if;
3044 end To_Artyp;
3046 -------------
3047 -- To_Ityp --
3048 -------------
3050 function To_Ityp (X : Node_Id) return Node_Id is
3051 begin
3052 if Is_Enumeration_Type (Ityp) then
3053 return
3054 Make_Attribute_Reference (Loc,
3055 Prefix => New_Occurrence_Of (Ityp, Loc),
3056 Attribute_Name => Name_Val,
3057 Expressions => New_List (X));
3059 -- Case where we will do a type conversion
3061 else
3062 if Ityp = Base_Type (Artyp) then
3063 return X;
3064 else
3065 return Convert_To (Ityp, X);
3066 end if;
3067 end if;
3068 end To_Ityp;
3070 -- Local Declarations
3072 Lib_Level_Target : constant Boolean :=
3073 Nkind (Parent (Cnode)) = N_Object_Declaration
3074 and then
3075 Is_Library_Level_Entity (Defining_Identifier (Parent (Cnode)));
3077 -- If the concatenation declares a library level entity, we call the
3078 -- built-in concatenation routines to prevent code bloat, regardless
3079 -- of optimization level. This is space-efficient, and prevent linking
3080 -- problems when units are compiled with different optimizations.
3082 Opnd_Typ : Entity_Id;
3083 Ent : Entity_Id;
3084 Len : Uint;
3085 J : Nat;
3086 Clen : Node_Id;
3087 Set : Boolean;
3089 -- Start of processing for Expand_Concatenate
3091 begin
3092 -- Choose an appropriate computational type
3094 -- We will be doing calculations of lengths and bounds in this routine
3095 -- and computing one from the other in some cases, e.g. getting the high
3096 -- bound by adding the length-1 to the low bound.
3098 -- We can't just use the index type, or even its base type for this
3099 -- purpose for two reasons. First it might be an enumeration type which
3100 -- is not suitable for computations of any kind, and second it may
3101 -- simply not have enough range. For example if the index type is
3102 -- -128..+127 then lengths can be up to 256, which is out of range of
3103 -- the type.
3105 -- For enumeration types, we can simply use Standard_Integer, this is
3106 -- sufficient since the actual number of enumeration literals cannot
3107 -- possibly exceed the range of integer (remember we will be doing the
3108 -- arithmetic with POS values, not representation values).
3110 if Is_Enumeration_Type (Ityp) then
3111 Artyp := Standard_Integer;
3113 -- If index type is Positive, we use the standard unsigned type, to give
3114 -- more room on the top of the range, obviating the need for an overflow
3115 -- check when creating the upper bound. This is needed to avoid junk
3116 -- overflow checks in the common case of String types.
3118 -- ??? Disabled for now
3120 -- elsif Istyp = Standard_Positive then
3121 -- Artyp := Standard_Unsigned;
3123 -- For modular types, we use a 32-bit modular type for types whose size
3124 -- is in the range 1-31 bits. For 32-bit unsigned types, we use the
3125 -- identity type, and for larger unsigned types we use 64-bits.
3127 elsif Is_Modular_Integer_Type (Ityp) then
3128 if RM_Size (Ityp) < RM_Size (Standard_Unsigned) then
3129 Artyp := Standard_Unsigned;
3130 elsif RM_Size (Ityp) = RM_Size (Standard_Unsigned) then
3131 Artyp := Ityp;
3132 else
3133 Artyp := RTE (RE_Long_Long_Unsigned);
3134 end if;
3136 -- Similar treatment for signed types
3138 else
3139 if RM_Size (Ityp) < RM_Size (Standard_Integer) then
3140 Artyp := Standard_Integer;
3141 elsif RM_Size (Ityp) = RM_Size (Standard_Integer) then
3142 Artyp := Ityp;
3143 else
3144 Artyp := Standard_Long_Long_Integer;
3145 end if;
3146 end if;
3148 -- Supply dummy entry at start of length array
3150 Aggr_Length (0) := Make_Artyp_Literal (0);
3152 -- Go through operands setting up the above arrays
3154 J := 1;
3155 while J <= N loop
3156 Opnd := Remove_Head (Opnds);
3157 Opnd_Typ := Etype (Opnd);
3159 -- The parent got messed up when we put the operands in a list,
3160 -- so now put back the proper parent for the saved operand, that
3161 -- is to say the concatenation node, to make sure that each operand
3162 -- is seen as a subexpression, e.g. if actions must be inserted.
3164 Set_Parent (Opnd, Cnode);
3166 -- Set will be True when we have setup one entry in the array
3168 Set := False;
3170 -- Singleton element (or character literal) case
3172 if Base_Type (Opnd_Typ) = Ctyp then
3173 NN := NN + 1;
3174 Operands (NN) := Opnd;
3175 Is_Fixed_Length (NN) := True;
3176 Fixed_Length (NN) := Uint_1;
3177 Result_May_Be_Null := False;
3179 -- Set low bound of operand (no need to set Last_Opnd_High_Bound
3180 -- since we know that the result cannot be null).
3182 Opnd_Low_Bound (NN) :=
3183 Make_Attribute_Reference (Loc,
3184 Prefix => New_Occurrence_Of (Istyp, Loc),
3185 Attribute_Name => Name_First);
3187 Set := True;
3189 -- String literal case (can only occur for strings of course)
3191 elsif Nkind (Opnd) = N_String_Literal then
3192 Len := String_Literal_Length (Opnd_Typ);
3194 if Len /= 0 then
3195 Result_May_Be_Null := False;
3196 end if;
3198 -- Capture last operand low and high bound if result could be null
3200 if J = N and then Result_May_Be_Null then
3201 Last_Opnd_Low_Bound :=
3202 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3204 Last_Opnd_High_Bound :=
3205 Make_Op_Subtract (Loc,
3206 Left_Opnd =>
3207 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ)),
3208 Right_Opnd => Make_Integer_Literal (Loc, 1));
3209 end if;
3211 -- Skip null string literal
3213 if J < N and then Len = 0 then
3214 goto Continue;
3215 end if;
3217 NN := NN + 1;
3218 Operands (NN) := Opnd;
3219 Is_Fixed_Length (NN) := True;
3221 -- Set length and bounds
3223 Fixed_Length (NN) := Len;
3225 Opnd_Low_Bound (NN) :=
3226 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3228 Set := True;
3230 -- All other cases
3232 else
3233 -- Check constrained case with known bounds
3235 if Is_Constrained (Opnd_Typ) then
3236 declare
3237 Index : constant Node_Id := First_Index (Opnd_Typ);
3238 Indx_Typ : constant Entity_Id := Etype (Index);
3239 Lo : constant Node_Id := Type_Low_Bound (Indx_Typ);
3240 Hi : constant Node_Id := Type_High_Bound (Indx_Typ);
3242 begin
3243 -- Fixed length constrained array type with known at compile
3244 -- time bounds is last case of fixed length operand.
3246 if Compile_Time_Known_Value (Lo)
3247 and then
3248 Compile_Time_Known_Value (Hi)
3249 then
3250 declare
3251 Loval : constant Uint := Expr_Value (Lo);
3252 Hival : constant Uint := Expr_Value (Hi);
3253 Len : constant Uint :=
3254 UI_Max (Hival - Loval + 1, Uint_0);
3256 begin
3257 if Len > 0 then
3258 Result_May_Be_Null := False;
3259 end if;
3261 -- Capture last operand bounds if result could be null
3263 if J = N and then Result_May_Be_Null then
3264 Last_Opnd_Low_Bound :=
3265 Convert_To (Ityp,
3266 Make_Integer_Literal (Loc, Expr_Value (Lo)));
3268 Last_Opnd_High_Bound :=
3269 Convert_To (Ityp,
3270 Make_Integer_Literal (Loc, Expr_Value (Hi)));
3271 end if;
3273 -- Exclude null length case unless last operand
3275 if J < N and then Len = 0 then
3276 goto Continue;
3277 end if;
3279 NN := NN + 1;
3280 Operands (NN) := Opnd;
3281 Is_Fixed_Length (NN) := True;
3282 Fixed_Length (NN) := Len;
3284 Opnd_Low_Bound (NN) :=
3285 To_Ityp
3286 (Make_Integer_Literal (Loc, Expr_Value (Lo)));
3287 Set := True;
3288 end;
3289 end if;
3290 end;
3291 end if;
3293 -- All cases where the length is not known at compile time, or the
3294 -- special case of an operand which is known to be null but has a
3295 -- lower bound other than 1 or is other than a string type.
3297 if not Set then
3298 NN := NN + 1;
3300 -- Capture operand bounds
3302 Opnd_Low_Bound (NN) :=
3303 Make_Attribute_Reference (Loc,
3304 Prefix =>
3305 Duplicate_Subexpr (Opnd, Name_Req => True),
3306 Attribute_Name => Name_First);
3308 -- Capture last operand bounds if result could be null
3310 if J = N and Result_May_Be_Null then
3311 Last_Opnd_Low_Bound :=
3312 Convert_To (Ityp,
3313 Make_Attribute_Reference (Loc,
3314 Prefix =>
3315 Duplicate_Subexpr (Opnd, Name_Req => True),
3316 Attribute_Name => Name_First));
3318 Last_Opnd_High_Bound :=
3319 Convert_To (Ityp,
3320 Make_Attribute_Reference (Loc,
3321 Prefix =>
3322 Duplicate_Subexpr (Opnd, Name_Req => True),
3323 Attribute_Name => Name_Last));
3324 end if;
3326 -- Capture length of operand in entity
3328 Operands (NN) := Opnd;
3329 Is_Fixed_Length (NN) := False;
3331 Var_Length (NN) := Make_Temporary (Loc, 'L');
3333 Append_To (Actions,
3334 Make_Object_Declaration (Loc,
3335 Defining_Identifier => Var_Length (NN),
3336 Constant_Present => True,
3337 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3338 Expression =>
3339 Make_Attribute_Reference (Loc,
3340 Prefix =>
3341 Duplicate_Subexpr (Opnd, Name_Req => True),
3342 Attribute_Name => Name_Length)));
3343 end if;
3344 end if;
3346 -- Set next entry in aggregate length array
3348 -- For first entry, make either integer literal for fixed length
3349 -- or a reference to the saved length for variable length.
3351 if NN = 1 then
3352 if Is_Fixed_Length (1) then
3353 Aggr_Length (1) := Make_Integer_Literal (Loc, Fixed_Length (1));
3354 else
3355 Aggr_Length (1) := New_Occurrence_Of (Var_Length (1), Loc);
3356 end if;
3358 -- If entry is fixed length and only fixed lengths so far, make
3359 -- appropriate new integer literal adding new length.
3361 elsif Is_Fixed_Length (NN)
3362 and then Nkind (Aggr_Length (NN - 1)) = N_Integer_Literal
3363 then
3364 Aggr_Length (NN) :=
3365 Make_Integer_Literal (Loc,
3366 Intval => Fixed_Length (NN) + Intval (Aggr_Length (NN - 1)));
3368 -- All other cases, construct an addition node for the length and
3369 -- create an entity initialized to this length.
3371 else
3372 Ent := Make_Temporary (Loc, 'L');
3374 if Is_Fixed_Length (NN) then
3375 Clen := Make_Integer_Literal (Loc, Fixed_Length (NN));
3376 else
3377 Clen := New_Occurrence_Of (Var_Length (NN), Loc);
3378 end if;
3380 Append_To (Actions,
3381 Make_Object_Declaration (Loc,
3382 Defining_Identifier => Ent,
3383 Constant_Present => True,
3384 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3385 Expression =>
3386 Make_Op_Add (Loc,
3387 Left_Opnd => New_Copy (Aggr_Length (NN - 1)),
3388 Right_Opnd => Clen)));
3390 Aggr_Length (NN) := Make_Identifier (Loc, Chars => Chars (Ent));
3391 end if;
3393 <<Continue>>
3394 J := J + 1;
3395 end loop;
3397 -- If we have only skipped null operands, return the last operand
3399 if NN = 0 then
3400 Result := Opnd;
3401 goto Done;
3402 end if;
3404 -- If we have only one non-null operand, return it and we are done.
3405 -- There is one case in which this cannot be done, and that is when
3406 -- the sole operand is of the element type, in which case it must be
3407 -- converted to an array, and the easiest way of doing that is to go
3408 -- through the normal general circuit.
3410 if NN = 1 and then Base_Type (Etype (Operands (1))) /= Ctyp then
3411 Result := Operands (1);
3412 goto Done;
3413 end if;
3415 -- Cases where we have a real concatenation
3417 -- Next step is to find the low bound for the result array that we
3418 -- will allocate. The rules for this are in (RM 4.5.6(5-7)).
3420 -- If the ultimate ancestor of the index subtype is a constrained array
3421 -- definition, then the lower bound is that of the index subtype as
3422 -- specified by (RM 4.5.3(6)).
3424 -- The right test here is to go to the root type, and then the ultimate
3425 -- ancestor is the first subtype of this root type.
3427 if Is_Constrained (First_Subtype (Root_Type (Atyp))) then
3428 Low_Bound :=
3429 Make_Attribute_Reference (Loc,
3430 Prefix =>
3431 New_Occurrence_Of (First_Subtype (Root_Type (Atyp)), Loc),
3432 Attribute_Name => Name_First);
3434 -- If the first operand in the list has known length we know that
3435 -- the lower bound of the result is the lower bound of this operand.
3437 elsif Is_Fixed_Length (1) then
3438 Low_Bound := Opnd_Low_Bound (1);
3440 -- OK, we don't know the lower bound, we have to build a horrible
3441 -- if expression node of the form
3443 -- if Cond1'Length /= 0 then
3444 -- Opnd1 low bound
3445 -- else
3446 -- if Opnd2'Length /= 0 then
3447 -- Opnd2 low bound
3448 -- else
3449 -- ...
3451 -- The nesting ends either when we hit an operand whose length is known
3452 -- at compile time, or on reaching the last operand, whose low bound we
3453 -- take unconditionally whether or not it is null. It's easiest to do
3454 -- this with a recursive procedure:
3456 else
3457 declare
3458 function Get_Known_Bound (J : Nat) return Node_Id;
3459 -- Returns the lower bound determined by operands J .. NN
3461 ---------------------
3462 -- Get_Known_Bound --
3463 ---------------------
3465 function Get_Known_Bound (J : Nat) return Node_Id is
3466 begin
3467 if Is_Fixed_Length (J) or else J = NN then
3468 return New_Copy (Opnd_Low_Bound (J));
3470 else
3471 return
3472 Make_If_Expression (Loc,
3473 Expressions => New_List (
3475 Make_Op_Ne (Loc,
3476 Left_Opnd =>
3477 New_Occurrence_Of (Var_Length (J), Loc),
3478 Right_Opnd =>
3479 Make_Integer_Literal (Loc, 0)),
3481 New_Copy (Opnd_Low_Bound (J)),
3482 Get_Known_Bound (J + 1)));
3483 end if;
3484 end Get_Known_Bound;
3486 begin
3487 Ent := Make_Temporary (Loc, 'L');
3489 Append_To (Actions,
3490 Make_Object_Declaration (Loc,
3491 Defining_Identifier => Ent,
3492 Constant_Present => True,
3493 Object_Definition => New_Occurrence_Of (Ityp, Loc),
3494 Expression => Get_Known_Bound (1)));
3496 Low_Bound := New_Occurrence_Of (Ent, Loc);
3497 end;
3498 end if;
3500 -- Now we can safely compute the upper bound, normally
3501 -- Low_Bound + Length - 1.
3503 High_Bound :=
3504 To_Ityp
3505 (Make_Op_Add (Loc,
3506 Left_Opnd => To_Artyp (New_Copy (Low_Bound)),
3507 Right_Opnd =>
3508 Make_Op_Subtract (Loc,
3509 Left_Opnd => New_Copy (Aggr_Length (NN)),
3510 Right_Opnd => Make_Artyp_Literal (1))));
3512 -- Note that calculation of the high bound may cause overflow in some
3513 -- very weird cases, so in the general case we need an overflow check on
3514 -- the high bound. We can avoid this for the common case of string types
3515 -- and other types whose index is Positive, since we chose a wider range
3516 -- for the arithmetic type.
3518 if Istyp /= Standard_Positive then
3519 Activate_Overflow_Check (High_Bound);
3520 end if;
3522 -- Handle the exceptional case where the result is null, in which case
3523 -- case the bounds come from the last operand (so that we get the proper
3524 -- bounds if the last operand is super-flat).
3526 if Result_May_Be_Null then
3527 Low_Bound :=
3528 Make_If_Expression (Loc,
3529 Expressions => New_List (
3530 Make_Op_Eq (Loc,
3531 Left_Opnd => New_Copy (Aggr_Length (NN)),
3532 Right_Opnd => Make_Artyp_Literal (0)),
3533 Last_Opnd_Low_Bound,
3534 Low_Bound));
3536 High_Bound :=
3537 Make_If_Expression (Loc,
3538 Expressions => New_List (
3539 Make_Op_Eq (Loc,
3540 Left_Opnd => New_Copy (Aggr_Length (NN)),
3541 Right_Opnd => Make_Artyp_Literal (0)),
3542 Last_Opnd_High_Bound,
3543 High_Bound));
3544 end if;
3546 -- Here is where we insert the saved up actions
3548 Insert_Actions (Cnode, Actions, Suppress => All_Checks);
3550 -- Now we construct an array object with appropriate bounds. We mark
3551 -- the target as internal to prevent useless initialization when
3552 -- Initialize_Scalars is enabled. Also since this is the actual result
3553 -- entity, we make sure we have debug information for the result.
3555 Ent := Make_Temporary (Loc, 'S');
3556 Set_Is_Internal (Ent);
3557 Set_Needs_Debug_Info (Ent);
3559 -- If the bound is statically known to be out of range, we do not want
3560 -- to abort, we want a warning and a runtime constraint error. Note that
3561 -- we have arranged that the result will not be treated as a static
3562 -- constant, so we won't get an illegality during this insertion.
3564 Insert_Action (Cnode,
3565 Make_Object_Declaration (Loc,
3566 Defining_Identifier => Ent,
3567 Object_Definition =>
3568 Make_Subtype_Indication (Loc,
3569 Subtype_Mark => New_Occurrence_Of (Atyp, Loc),
3570 Constraint =>
3571 Make_Index_Or_Discriminant_Constraint (Loc,
3572 Constraints => New_List (
3573 Make_Range (Loc,
3574 Low_Bound => Low_Bound,
3575 High_Bound => High_Bound))))),
3576 Suppress => All_Checks);
3578 -- If the result of the concatenation appears as the initializing
3579 -- expression of an object declaration, we can just rename the
3580 -- result, rather than copying it.
3582 Set_OK_To_Rename (Ent);
3584 -- Catch the static out of range case now
3586 if Raises_Constraint_Error (High_Bound) then
3587 raise Concatenation_Error;
3588 end if;
3590 -- Now we will generate the assignments to do the actual concatenation
3592 -- There is one case in which we will not do this, namely when all the
3593 -- following conditions are met:
3595 -- The result type is Standard.String
3597 -- There are nine or fewer retained (non-null) operands
3599 -- The optimization level is -O0
3601 -- The corresponding System.Concat_n.Str_Concat_n routine is
3602 -- available in the run time.
3604 -- The debug flag gnatd.c is not set
3606 -- If all these conditions are met then we generate a call to the
3607 -- relevant concatenation routine. The purpose of this is to avoid
3608 -- undesirable code bloat at -O0.
3610 if Atyp = Standard_String
3611 and then NN in 2 .. 9
3612 and then (Lib_Level_Target
3613 or else ((Opt.Optimization_Level = 0 or else Debug_Flag_Dot_CC)
3614 and then not Debug_Flag_Dot_C))
3615 then
3616 declare
3617 RR : constant array (Nat range 2 .. 9) of RE_Id :=
3618 (RE_Str_Concat_2,
3619 RE_Str_Concat_3,
3620 RE_Str_Concat_4,
3621 RE_Str_Concat_5,
3622 RE_Str_Concat_6,
3623 RE_Str_Concat_7,
3624 RE_Str_Concat_8,
3625 RE_Str_Concat_9);
3627 begin
3628 if RTE_Available (RR (NN)) then
3629 declare
3630 Opnds : constant List_Id :=
3631 New_List (New_Occurrence_Of (Ent, Loc));
3633 begin
3634 for J in 1 .. NN loop
3635 if Is_List_Member (Operands (J)) then
3636 Remove (Operands (J));
3637 end if;
3639 if Base_Type (Etype (Operands (J))) = Ctyp then
3640 Append_To (Opnds,
3641 Make_Aggregate (Loc,
3642 Component_Associations => New_List (
3643 Make_Component_Association (Loc,
3644 Choices => New_List (
3645 Make_Integer_Literal (Loc, 1)),
3646 Expression => Operands (J)))));
3648 else
3649 Append_To (Opnds, Operands (J));
3650 end if;
3651 end loop;
3653 Insert_Action (Cnode,
3654 Make_Procedure_Call_Statement (Loc,
3655 Name => New_Occurrence_Of (RTE (RR (NN)), Loc),
3656 Parameter_Associations => Opnds));
3658 Result := New_Occurrence_Of (Ent, Loc);
3659 goto Done;
3660 end;
3661 end if;
3662 end;
3663 end if;
3665 -- Not special case so generate the assignments
3667 Known_Non_Null_Operand_Seen := False;
3669 for J in 1 .. NN loop
3670 declare
3671 Lo : constant Node_Id :=
3672 Make_Op_Add (Loc,
3673 Left_Opnd => To_Artyp (New_Copy (Low_Bound)),
3674 Right_Opnd => Aggr_Length (J - 1));
3676 Hi : constant Node_Id :=
3677 Make_Op_Add (Loc,
3678 Left_Opnd => To_Artyp (New_Copy (Low_Bound)),
3679 Right_Opnd =>
3680 Make_Op_Subtract (Loc,
3681 Left_Opnd => Aggr_Length (J),
3682 Right_Opnd => Make_Artyp_Literal (1)));
3684 begin
3685 -- Singleton case, simple assignment
3687 if Base_Type (Etype (Operands (J))) = Ctyp then
3688 Known_Non_Null_Operand_Seen := True;
3689 Insert_Action (Cnode,
3690 Make_Assignment_Statement (Loc,
3691 Name =>
3692 Make_Indexed_Component (Loc,
3693 Prefix => New_Occurrence_Of (Ent, Loc),
3694 Expressions => New_List (To_Ityp (Lo))),
3695 Expression => Operands (J)),
3696 Suppress => All_Checks);
3698 -- Array case, slice assignment, skipped when argument is fixed
3699 -- length and known to be null.
3701 elsif (not Is_Fixed_Length (J)) or else (Fixed_Length (J) > 0) then
3702 declare
3703 Assign : Node_Id :=
3704 Make_Assignment_Statement (Loc,
3705 Name =>
3706 Make_Slice (Loc,
3707 Prefix =>
3708 New_Occurrence_Of (Ent, Loc),
3709 Discrete_Range =>
3710 Make_Range (Loc,
3711 Low_Bound => To_Ityp (Lo),
3712 High_Bound => To_Ityp (Hi))),
3713 Expression => Operands (J));
3714 begin
3715 if Is_Fixed_Length (J) then
3716 Known_Non_Null_Operand_Seen := True;
3718 elsif not Known_Non_Null_Operand_Seen then
3720 -- Here if operand length is not statically known and no
3721 -- operand known to be non-null has been processed yet.
3722 -- If operand length is 0, we do not need to perform the
3723 -- assignment, and we must avoid the evaluation of the
3724 -- high bound of the slice, since it may underflow if the
3725 -- low bound is Ityp'First.
3727 Assign :=
3728 Make_Implicit_If_Statement (Cnode,
3729 Condition =>
3730 Make_Op_Ne (Loc,
3731 Left_Opnd =>
3732 New_Occurrence_Of (Var_Length (J), Loc),
3733 Right_Opnd => Make_Integer_Literal (Loc, 0)),
3734 Then_Statements => New_List (Assign));
3735 end if;
3737 Insert_Action (Cnode, Assign, Suppress => All_Checks);
3738 end;
3739 end if;
3740 end;
3741 end loop;
3743 -- Finally we build the result, which is a reference to the array object
3745 Result := New_Occurrence_Of (Ent, Loc);
3747 <<Done>>
3748 Rewrite (Cnode, Result);
3749 Analyze_And_Resolve (Cnode, Atyp);
3751 exception
3752 when Concatenation_Error =>
3754 -- Kill warning generated for the declaration of the static out of
3755 -- range high bound, and instead generate a Constraint_Error with
3756 -- an appropriate specific message.
3758 Kill_Dead_Code (Declaration_Node (Entity (High_Bound)));
3759 Apply_Compile_Time_Constraint_Error
3760 (N => Cnode,
3761 Msg => "concatenation result upper bound out of range??",
3762 Reason => CE_Range_Check_Failed);
3763 end Expand_Concatenate;
3765 ---------------------------------------------------
3766 -- Expand_Membership_Minimize_Eliminate_Overflow --
3767 ---------------------------------------------------
3769 procedure Expand_Membership_Minimize_Eliminate_Overflow (N : Node_Id) is
3770 pragma Assert (Nkind (N) = N_In);
3771 -- Despite the name, this routine applies only to N_In, not to
3772 -- N_Not_In. The latter is always rewritten as not (X in Y).
3774 Result_Type : constant Entity_Id := Etype (N);
3775 -- Capture result type, may be a derived boolean type
3777 Loc : constant Source_Ptr := Sloc (N);
3778 Lop : constant Node_Id := Left_Opnd (N);
3779 Rop : constant Node_Id := Right_Opnd (N);
3781 -- Note: there are many referencs to Etype (Lop) and Etype (Rop). It
3782 -- is thus tempting to capture these values, but due to the rewrites
3783 -- that occur as a result of overflow checking, these values change
3784 -- as we go along, and it is safe just to always use Etype explicitly.
3786 Restype : constant Entity_Id := Etype (N);
3787 -- Save result type
3789 Lo, Hi : Uint;
3790 -- Bounds in Minimize calls, not used currently
3792 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
3793 -- Entity for Long_Long_Integer'Base (Standard should export this???)
3795 begin
3796 Minimize_Eliminate_Overflows (Lop, Lo, Hi, Top_Level => False);
3798 -- If right operand is a subtype name, and the subtype name has no
3799 -- predicate, then we can just replace the right operand with an
3800 -- explicit range T'First .. T'Last, and use the explicit range code.
3802 if Nkind (Rop) /= N_Range
3803 and then No (Predicate_Function (Etype (Rop)))
3804 then
3805 declare
3806 Rtyp : constant Entity_Id := Etype (Rop);
3807 begin
3808 Rewrite (Rop,
3809 Make_Range (Loc,
3810 Low_Bound =>
3811 Make_Attribute_Reference (Loc,
3812 Attribute_Name => Name_First,
3813 Prefix => New_Occurrence_Of (Rtyp, Loc)),
3814 High_Bound =>
3815 Make_Attribute_Reference (Loc,
3816 Attribute_Name => Name_Last,
3817 Prefix => New_Occurrence_Of (Rtyp, Loc))));
3818 Analyze_And_Resolve (Rop, Rtyp, Suppress => All_Checks);
3819 end;
3820 end if;
3822 -- Here for the explicit range case. Note that the bounds of the range
3823 -- have not been processed for minimized or eliminated checks.
3825 if Nkind (Rop) = N_Range then
3826 Minimize_Eliminate_Overflows
3827 (Low_Bound (Rop), Lo, Hi, Top_Level => False);
3828 Minimize_Eliminate_Overflows
3829 (High_Bound (Rop), Lo, Hi, Top_Level => False);
3831 -- We have A in B .. C, treated as A >= B and then A <= C
3833 -- Bignum case
3835 if Is_RTE (Etype (Lop), RE_Bignum)
3836 or else Is_RTE (Etype (Low_Bound (Rop)), RE_Bignum)
3837 or else Is_RTE (Etype (High_Bound (Rop)), RE_Bignum)
3838 then
3839 declare
3840 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3841 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
3842 L : constant Entity_Id :=
3843 Make_Defining_Identifier (Loc, Name_uL);
3844 Lopnd : constant Node_Id := Convert_To_Bignum (Lop);
3845 Lbound : constant Node_Id :=
3846 Convert_To_Bignum (Low_Bound (Rop));
3847 Hbound : constant Node_Id :=
3848 Convert_To_Bignum (High_Bound (Rop));
3850 -- Now we rewrite the membership test node to look like
3852 -- do
3853 -- Bnn : Result_Type;
3854 -- declare
3855 -- M : Mark_Id := SS_Mark;
3856 -- L : Bignum := Lopnd;
3857 -- begin
3858 -- Bnn := Big_GE (L, Lbound) and then Big_LE (L, Hbound)
3859 -- SS_Release (M);
3860 -- end;
3861 -- in
3862 -- Bnn
3863 -- end
3865 begin
3866 -- Insert declaration of L into declarations of bignum block
3868 Insert_After
3869 (Last (Declarations (Blk)),
3870 Make_Object_Declaration (Loc,
3871 Defining_Identifier => L,
3872 Object_Definition =>
3873 New_Occurrence_Of (RTE (RE_Bignum), Loc),
3874 Expression => Lopnd));
3876 -- Insert assignment to Bnn into expressions of bignum block
3878 Insert_Before
3879 (First (Statements (Handled_Statement_Sequence (Blk))),
3880 Make_Assignment_Statement (Loc,
3881 Name => New_Occurrence_Of (Bnn, Loc),
3882 Expression =>
3883 Make_And_Then (Loc,
3884 Left_Opnd =>
3885 Make_Function_Call (Loc,
3886 Name =>
3887 New_Occurrence_Of (RTE (RE_Big_GE), Loc),
3888 Parameter_Associations => New_List (
3889 New_Occurrence_Of (L, Loc),
3890 Lbound)),
3892 Right_Opnd =>
3893 Make_Function_Call (Loc,
3894 Name =>
3895 New_Occurrence_Of (RTE (RE_Big_LE), Loc),
3896 Parameter_Associations => New_List (
3897 New_Occurrence_Of (L, Loc),
3898 Hbound)))));
3900 -- Now rewrite the node
3902 Rewrite (N,
3903 Make_Expression_With_Actions (Loc,
3904 Actions => New_List (
3905 Make_Object_Declaration (Loc,
3906 Defining_Identifier => Bnn,
3907 Object_Definition =>
3908 New_Occurrence_Of (Result_Type, Loc)),
3909 Blk),
3910 Expression => New_Occurrence_Of (Bnn, Loc)));
3911 Analyze_And_Resolve (N, Result_Type);
3912 return;
3913 end;
3915 -- Here if no bignums around
3917 else
3918 -- Case where types are all the same
3920 if Base_Type (Etype (Lop)) = Base_Type (Etype (Low_Bound (Rop)))
3921 and then
3922 Base_Type (Etype (Lop)) = Base_Type (Etype (High_Bound (Rop)))
3923 then
3924 null;
3926 -- If types are not all the same, it means that we have rewritten
3927 -- at least one of them to be of type Long_Long_Integer, and we
3928 -- will convert the other operands to Long_Long_Integer.
3930 else
3931 Convert_To_And_Rewrite (LLIB, Lop);
3932 Set_Analyzed (Lop, False);
3933 Analyze_And_Resolve (Lop, LLIB);
3935 -- For the right operand, avoid unnecessary recursion into
3936 -- this routine, we know that overflow is not possible.
3938 Convert_To_And_Rewrite (LLIB, Low_Bound (Rop));
3939 Convert_To_And_Rewrite (LLIB, High_Bound (Rop));
3940 Set_Analyzed (Rop, False);
3941 Analyze_And_Resolve (Rop, LLIB, Suppress => Overflow_Check);
3942 end if;
3944 -- Now the three operands are of the same signed integer type,
3945 -- so we can use the normal expansion routine for membership,
3946 -- setting the flag to prevent recursion into this procedure.
3948 Set_No_Minimize_Eliminate (N);
3949 Expand_N_In (N);
3950 end if;
3952 -- Right operand is a subtype name and the subtype has a predicate. We
3953 -- have to make sure the predicate is checked, and for that we need to
3954 -- use the standard N_In circuitry with appropriate types.
3956 else
3957 pragma Assert (Present (Predicate_Function (Etype (Rop))));
3959 -- If types are "right", just call Expand_N_In preventing recursion
3961 if Base_Type (Etype (Lop)) = Base_Type (Etype (Rop)) then
3962 Set_No_Minimize_Eliminate (N);
3963 Expand_N_In (N);
3965 -- Bignum case
3967 elsif Is_RTE (Etype (Lop), RE_Bignum) then
3969 -- For X in T, we want to rewrite our node as
3971 -- do
3972 -- Bnn : Result_Type;
3974 -- declare
3975 -- M : Mark_Id := SS_Mark;
3976 -- Lnn : Long_Long_Integer'Base
3977 -- Nnn : Bignum;
3979 -- begin
3980 -- Nnn := X;
3982 -- if not Bignum_In_LLI_Range (Nnn) then
3983 -- Bnn := False;
3984 -- else
3985 -- Lnn := From_Bignum (Nnn);
3986 -- Bnn :=
3987 -- Lnn in LLIB (T'Base'First) .. LLIB (T'Base'Last)
3988 -- and then T'Base (Lnn) in T;
3989 -- end if;
3991 -- SS_Release (M);
3992 -- end
3993 -- in
3994 -- Bnn
3995 -- end
3997 -- A bit gruesome, but there doesn't seem to be a simpler way
3999 declare
4000 Blk : constant Node_Id := Make_Bignum_Block (Loc);
4001 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
4002 Lnn : constant Entity_Id := Make_Temporary (Loc, 'L', N);
4003 Nnn : constant Entity_Id := Make_Temporary (Loc, 'N', N);
4004 T : constant Entity_Id := Etype (Rop);
4005 TB : constant Entity_Id := Base_Type (T);
4006 Nin : Node_Id;
4008 begin
4009 -- Mark the last membership operation to prevent recursion
4011 Nin :=
4012 Make_In (Loc,
4013 Left_Opnd => Convert_To (TB, New_Occurrence_Of (Lnn, Loc)),
4014 Right_Opnd => New_Occurrence_Of (T, Loc));
4015 Set_No_Minimize_Eliminate (Nin);
4017 -- Now decorate the block
4019 Insert_After
4020 (Last (Declarations (Blk)),
4021 Make_Object_Declaration (Loc,
4022 Defining_Identifier => Lnn,
4023 Object_Definition => New_Occurrence_Of (LLIB, Loc)));
4025 Insert_After
4026 (Last (Declarations (Blk)),
4027 Make_Object_Declaration (Loc,
4028 Defining_Identifier => Nnn,
4029 Object_Definition =>
4030 New_Occurrence_Of (RTE (RE_Bignum), Loc)));
4032 Insert_List_Before
4033 (First (Statements (Handled_Statement_Sequence (Blk))),
4034 New_List (
4035 Make_Assignment_Statement (Loc,
4036 Name => New_Occurrence_Of (Nnn, Loc),
4037 Expression => Relocate_Node (Lop)),
4039 Make_Implicit_If_Statement (N,
4040 Condition =>
4041 Make_Op_Not (Loc,
4042 Right_Opnd =>
4043 Make_Function_Call (Loc,
4044 Name =>
4045 New_Occurrence_Of
4046 (RTE (RE_Bignum_In_LLI_Range), Loc),
4047 Parameter_Associations => New_List (
4048 New_Occurrence_Of (Nnn, Loc)))),
4050 Then_Statements => New_List (
4051 Make_Assignment_Statement (Loc,
4052 Name => New_Occurrence_Of (Bnn, Loc),
4053 Expression =>
4054 New_Occurrence_Of (Standard_False, Loc))),
4056 Else_Statements => New_List (
4057 Make_Assignment_Statement (Loc,
4058 Name => New_Occurrence_Of (Lnn, Loc),
4059 Expression =>
4060 Make_Function_Call (Loc,
4061 Name =>
4062 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
4063 Parameter_Associations => New_List (
4064 New_Occurrence_Of (Nnn, Loc)))),
4066 Make_Assignment_Statement (Loc,
4067 Name => New_Occurrence_Of (Bnn, Loc),
4068 Expression =>
4069 Make_And_Then (Loc,
4070 Left_Opnd =>
4071 Make_In (Loc,
4072 Left_Opnd => New_Occurrence_Of (Lnn, Loc),
4073 Right_Opnd =>
4074 Make_Range (Loc,
4075 Low_Bound =>
4076 Convert_To (LLIB,
4077 Make_Attribute_Reference (Loc,
4078 Attribute_Name => Name_First,
4079 Prefix =>
4080 New_Occurrence_Of (TB, Loc))),
4082 High_Bound =>
4083 Convert_To (LLIB,
4084 Make_Attribute_Reference (Loc,
4085 Attribute_Name => Name_Last,
4086 Prefix =>
4087 New_Occurrence_Of (TB, Loc))))),
4089 Right_Opnd => Nin))))));
4091 -- Now we can do the rewrite
4093 Rewrite (N,
4094 Make_Expression_With_Actions (Loc,
4095 Actions => New_List (
4096 Make_Object_Declaration (Loc,
4097 Defining_Identifier => Bnn,
4098 Object_Definition =>
4099 New_Occurrence_Of (Result_Type, Loc)),
4100 Blk),
4101 Expression => New_Occurrence_Of (Bnn, Loc)));
4102 Analyze_And_Resolve (N, Result_Type);
4103 return;
4104 end;
4106 -- Not bignum case, but types don't match (this means we rewrote the
4107 -- left operand to be Long_Long_Integer).
4109 else
4110 pragma Assert (Base_Type (Etype (Lop)) = LLIB);
4112 -- We rewrite the membership test as (where T is the type with
4113 -- the predicate, i.e. the type of the right operand)
4115 -- Lop in LLIB (T'Base'First) .. LLIB (T'Base'Last)
4116 -- and then T'Base (Lop) in T
4118 declare
4119 T : constant Entity_Id := Etype (Rop);
4120 TB : constant Entity_Id := Base_Type (T);
4121 Nin : Node_Id;
4123 begin
4124 -- The last membership test is marked to prevent recursion
4126 Nin :=
4127 Make_In (Loc,
4128 Left_Opnd => Convert_To (TB, Duplicate_Subexpr (Lop)),
4129 Right_Opnd => New_Occurrence_Of (T, Loc));
4130 Set_No_Minimize_Eliminate (Nin);
4132 -- Now do the rewrite
4134 Rewrite (N,
4135 Make_And_Then (Loc,
4136 Left_Opnd =>
4137 Make_In (Loc,
4138 Left_Opnd => Lop,
4139 Right_Opnd =>
4140 Make_Range (Loc,
4141 Low_Bound =>
4142 Convert_To (LLIB,
4143 Make_Attribute_Reference (Loc,
4144 Attribute_Name => Name_First,
4145 Prefix =>
4146 New_Occurrence_Of (TB, Loc))),
4147 High_Bound =>
4148 Convert_To (LLIB,
4149 Make_Attribute_Reference (Loc,
4150 Attribute_Name => Name_Last,
4151 Prefix =>
4152 New_Occurrence_Of (TB, Loc))))),
4153 Right_Opnd => Nin));
4154 Set_Analyzed (N, False);
4155 Analyze_And_Resolve (N, Restype);
4156 end;
4157 end if;
4158 end if;
4159 end Expand_Membership_Minimize_Eliminate_Overflow;
4161 ------------------------
4162 -- Expand_N_Allocator --
4163 ------------------------
4165 procedure Expand_N_Allocator (N : Node_Id) is
4166 Etyp : constant Entity_Id := Etype (Expression (N));
4167 Loc : constant Source_Ptr := Sloc (N);
4168 PtrT : constant Entity_Id := Etype (N);
4170 procedure Rewrite_Coextension (N : Node_Id);
4171 -- Static coextensions have the same lifetime as the entity they
4172 -- constrain. Such occurrences can be rewritten as aliased objects
4173 -- and their unrestricted access used instead of the coextension.
4175 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id;
4176 -- Given a constrained array type E, returns a node representing the
4177 -- code to compute the size in storage elements for the given type.
4178 -- This is done without using the attribute (which malfunctions for
4179 -- large sizes ???)
4181 -------------------------
4182 -- Rewrite_Coextension --
4183 -------------------------
4185 procedure Rewrite_Coextension (N : Node_Id) is
4186 Temp_Id : constant Node_Id := Make_Temporary (Loc, 'C');
4187 Temp_Decl : Node_Id;
4189 begin
4190 -- Generate:
4191 -- Cnn : aliased Etyp;
4193 Temp_Decl :=
4194 Make_Object_Declaration (Loc,
4195 Defining_Identifier => Temp_Id,
4196 Aliased_Present => True,
4197 Object_Definition => New_Occurrence_Of (Etyp, Loc));
4199 if Nkind (Expression (N)) = N_Qualified_Expression then
4200 Set_Expression (Temp_Decl, Expression (Expression (N)));
4201 end if;
4203 Insert_Action (N, Temp_Decl);
4204 Rewrite (N,
4205 Make_Attribute_Reference (Loc,
4206 Prefix => New_Occurrence_Of (Temp_Id, Loc),
4207 Attribute_Name => Name_Unrestricted_Access));
4209 Analyze_And_Resolve (N, PtrT);
4210 end Rewrite_Coextension;
4212 ------------------------------
4213 -- Size_In_Storage_Elements --
4214 ------------------------------
4216 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id is
4217 begin
4218 -- Logically this just returns E'Max_Size_In_Storage_Elements.
4219 -- However, the reason for the existence of this function is
4220 -- to construct a test for sizes too large, which means near the
4221 -- 32-bit limit on a 32-bit machine, and precisely the trouble
4222 -- is that we get overflows when sizes are greater than 2**31.
4224 -- So what we end up doing for array types is to use the expression:
4226 -- number-of-elements * component_type'Max_Size_In_Storage_Elements
4228 -- which avoids this problem. All this is a bit bogus, but it does
4229 -- mean we catch common cases of trying to allocate arrays that
4230 -- are too large, and which in the absence of a check results in
4231 -- undetected chaos ???
4233 -- Note in particular that this is a pessimistic estimate in the
4234 -- case of packed array types, where an array element might occupy
4235 -- just a fraction of a storage element???
4237 declare
4238 Len : Node_Id;
4239 Res : Node_Id;
4241 begin
4242 for J in 1 .. Number_Dimensions (E) loop
4243 Len :=
4244 Make_Attribute_Reference (Loc,
4245 Prefix => New_Occurrence_Of (E, Loc),
4246 Attribute_Name => Name_Length,
4247 Expressions => New_List (Make_Integer_Literal (Loc, J)));
4249 if J = 1 then
4250 Res := Len;
4252 else
4253 Res :=
4254 Make_Op_Multiply (Loc,
4255 Left_Opnd => Res,
4256 Right_Opnd => Len);
4257 end if;
4258 end loop;
4260 return
4261 Make_Op_Multiply (Loc,
4262 Left_Opnd => Len,
4263 Right_Opnd =>
4264 Make_Attribute_Reference (Loc,
4265 Prefix => New_Occurrence_Of (Component_Type (E), Loc),
4266 Attribute_Name => Name_Max_Size_In_Storage_Elements));
4267 end;
4268 end Size_In_Storage_Elements;
4270 -- Local variables
4272 Dtyp : constant Entity_Id := Available_View (Designated_Type (PtrT));
4273 Desig : Entity_Id;
4274 Nod : Node_Id;
4275 Pool : Entity_Id;
4276 Rel_Typ : Entity_Id;
4277 Temp : Entity_Id;
4279 -- Start of processing for Expand_N_Allocator
4281 begin
4282 -- RM E.2.3(22). We enforce that the expected type of an allocator
4283 -- shall not be a remote access-to-class-wide-limited-private type
4285 -- Why is this being done at expansion time, seems clearly wrong ???
4287 Validate_Remote_Access_To_Class_Wide_Type (N);
4289 -- Processing for anonymous access-to-controlled types. These access
4290 -- types receive a special finalization master which appears in the
4291 -- declarations of the enclosing semantic unit. This expansion is done
4292 -- now to ensure that any additional types generated by this routine or
4293 -- Expand_Allocator_Expression inherit the proper type attributes.
4295 if (Ekind (PtrT) = E_Anonymous_Access_Type
4296 or else (Is_Itype (PtrT) and then No (Finalization_Master (PtrT))))
4297 and then Needs_Finalization (Dtyp)
4298 then
4299 -- Detect the allocation of an anonymous controlled object where the
4300 -- type of the context is named. For example:
4302 -- procedure Proc (Ptr : Named_Access_Typ);
4303 -- Proc (new Designated_Typ);
4305 -- Regardless of the anonymous-to-named access type conversion, the
4306 -- lifetime of the object must be associated with the named access
4307 -- type. Use the finalization-related attributes of this type.
4309 if Nkind_In (Parent (N), N_Type_Conversion,
4310 N_Unchecked_Type_Conversion)
4311 and then Ekind_In (Etype (Parent (N)), E_Access_Subtype,
4312 E_Access_Type,
4313 E_General_Access_Type)
4314 then
4315 Rel_Typ := Etype (Parent (N));
4316 else
4317 Rel_Typ := Empty;
4318 end if;
4320 -- Anonymous access-to-controlled types allocate on the global pool.
4321 -- Do not set this attribute on .NET/JVM since those targets do not
4322 -- support pools. Note that this is a "root type only" attribute.
4324 if No (Associated_Storage_Pool (PtrT)) and then VM_Target = No_VM then
4325 if Present (Rel_Typ) then
4326 Set_Associated_Storage_Pool
4327 (Root_Type (PtrT), Associated_Storage_Pool (Rel_Typ));
4328 else
4329 Set_Associated_Storage_Pool
4330 (Root_Type (PtrT), RTE (RE_Global_Pool_Object));
4331 end if;
4332 end if;
4334 -- The finalization master must be inserted and analyzed as part of
4335 -- the current semantic unit. Note that the master is updated when
4336 -- analysis changes current units. Note that this is a "root type
4337 -- only" attribute.
4339 if Present (Rel_Typ) then
4340 Set_Finalization_Master
4341 (Root_Type (PtrT), Finalization_Master (Rel_Typ));
4342 else
4343 Set_Finalization_Master
4344 (Root_Type (PtrT), Current_Anonymous_Master);
4345 end if;
4346 end if;
4348 -- Set the storage pool and find the appropriate version of Allocate to
4349 -- call. Do not overwrite the storage pool if it is already set, which
4350 -- can happen for build-in-place function returns (see
4351 -- Exp_Ch4.Expand_N_Extended_Return_Statement).
4353 if No (Storage_Pool (N)) then
4354 Pool := Associated_Storage_Pool (Root_Type (PtrT));
4356 if Present (Pool) then
4357 Set_Storage_Pool (N, Pool);
4359 if Is_RTE (Pool, RE_SS_Pool) then
4360 if VM_Target = No_VM then
4361 Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
4362 end if;
4364 -- In the case of an allocator for a simple storage pool, locate
4365 -- and save a reference to the pool type's Allocate routine.
4367 elsif Present (Get_Rep_Pragma
4368 (Etype (Pool), Name_Simple_Storage_Pool_Type))
4369 then
4370 declare
4371 Pool_Type : constant Entity_Id := Base_Type (Etype (Pool));
4372 Alloc_Op : Entity_Id;
4373 begin
4374 Alloc_Op := Get_Name_Entity_Id (Name_Allocate);
4375 while Present (Alloc_Op) loop
4376 if Scope (Alloc_Op) = Scope (Pool_Type)
4377 and then Present (First_Formal (Alloc_Op))
4378 and then Etype (First_Formal (Alloc_Op)) = Pool_Type
4379 then
4380 Set_Procedure_To_Call (N, Alloc_Op);
4381 exit;
4382 else
4383 Alloc_Op := Homonym (Alloc_Op);
4384 end if;
4385 end loop;
4386 end;
4388 elsif Is_Class_Wide_Type (Etype (Pool)) then
4389 Set_Procedure_To_Call (N, RTE (RE_Allocate_Any));
4391 else
4392 Set_Procedure_To_Call (N,
4393 Find_Prim_Op (Etype (Pool), Name_Allocate));
4394 end if;
4395 end if;
4396 end if;
4398 -- Under certain circumstances we can replace an allocator by an access
4399 -- to statically allocated storage. The conditions, as noted in AARM
4400 -- 3.10 (10c) are as follows:
4402 -- Size and initial value is known at compile time
4403 -- Access type is access-to-constant
4405 -- The allocator is not part of a constraint on a record component,
4406 -- because in that case the inserted actions are delayed until the
4407 -- record declaration is fully analyzed, which is too late for the
4408 -- analysis of the rewritten allocator.
4410 if Is_Access_Constant (PtrT)
4411 and then Nkind (Expression (N)) = N_Qualified_Expression
4412 and then Compile_Time_Known_Value (Expression (Expression (N)))
4413 and then Size_Known_At_Compile_Time
4414 (Etype (Expression (Expression (N))))
4415 and then not Is_Record_Type (Current_Scope)
4416 then
4417 -- Here we can do the optimization. For the allocator
4419 -- new x'(y)
4421 -- We insert an object declaration
4423 -- Tnn : aliased x := y;
4425 -- and replace the allocator by Tnn'Unrestricted_Access. Tnn is
4426 -- marked as requiring static allocation.
4428 Temp := Make_Temporary (Loc, 'T', Expression (Expression (N)));
4429 Desig := Subtype_Mark (Expression (N));
4431 -- If context is constrained, use constrained subtype directly,
4432 -- so that the constant is not labelled as having a nominally
4433 -- unconstrained subtype.
4435 if Entity (Desig) = Base_Type (Dtyp) then
4436 Desig := New_Occurrence_Of (Dtyp, Loc);
4437 end if;
4439 Insert_Action (N,
4440 Make_Object_Declaration (Loc,
4441 Defining_Identifier => Temp,
4442 Aliased_Present => True,
4443 Constant_Present => Is_Access_Constant (PtrT),
4444 Object_Definition => Desig,
4445 Expression => Expression (Expression (N))));
4447 Rewrite (N,
4448 Make_Attribute_Reference (Loc,
4449 Prefix => New_Occurrence_Of (Temp, Loc),
4450 Attribute_Name => Name_Unrestricted_Access));
4452 Analyze_And_Resolve (N, PtrT);
4454 -- We set the variable as statically allocated, since we don't want
4455 -- it going on the stack of the current procedure.
4457 Set_Is_Statically_Allocated (Temp);
4458 return;
4459 end if;
4461 -- Same if the allocator is an access discriminant for a local object:
4462 -- instead of an allocator we create a local value and constrain the
4463 -- enclosing object with the corresponding access attribute.
4465 if Is_Static_Coextension (N) then
4466 Rewrite_Coextension (N);
4467 return;
4468 end if;
4470 -- Check for size too large, we do this because the back end misses
4471 -- proper checks here and can generate rubbish allocation calls when
4472 -- we are near the limit. We only do this for the 32-bit address case
4473 -- since that is from a practical point of view where we see a problem.
4475 if System_Address_Size = 32
4476 and then not Storage_Checks_Suppressed (PtrT)
4477 and then not Storage_Checks_Suppressed (Dtyp)
4478 and then not Storage_Checks_Suppressed (Etyp)
4479 then
4480 -- The check we want to generate should look like
4482 -- if Etyp'Max_Size_In_Storage_Elements > 3.5 gigabytes then
4483 -- raise Storage_Error;
4484 -- end if;
4486 -- where 3.5 gigabytes is a constant large enough to accommodate any
4487 -- reasonable request for. But we can't do it this way because at
4488 -- least at the moment we don't compute this attribute right, and
4489 -- can silently give wrong results when the result gets large. Since
4490 -- this is all about large results, that's bad, so instead we only
4491 -- apply the check for constrained arrays, and manually compute the
4492 -- value of the attribute ???
4494 if Is_Array_Type (Etyp) and then Is_Constrained (Etyp) then
4495 Insert_Action (N,
4496 Make_Raise_Storage_Error (Loc,
4497 Condition =>
4498 Make_Op_Gt (Loc,
4499 Left_Opnd => Size_In_Storage_Elements (Etyp),
4500 Right_Opnd =>
4501 Make_Integer_Literal (Loc, Uint_7 * (Uint_2 ** 29))),
4502 Reason => SE_Object_Too_Large));
4503 end if;
4504 end if;
4506 -- If no storage pool has been specified and we have the restriction
4507 -- No_Standard_Allocators_After_Elaboration is present, then generate
4508 -- a call to Elaboration_Allocators.Check_Standard_Allocator.
4510 if Nkind (N) = N_Allocator
4511 and then No (Storage_Pool (N))
4512 and then Restriction_Active (No_Standard_Allocators_After_Elaboration)
4513 then
4514 Insert_Action (N,
4515 Make_Procedure_Call_Statement (Loc,
4516 Name =>
4517 New_Occurrence_Of (RTE (RE_Check_Standard_Allocator), Loc)));
4518 end if;
4520 -- Handle case of qualified expression (other than optimization above)
4521 -- First apply constraint checks, because the bounds or discriminants
4522 -- in the aggregate might not match the subtype mark in the allocator.
4524 if Nkind (Expression (N)) = N_Qualified_Expression then
4525 Apply_Constraint_Check
4526 (Expression (Expression (N)), Etype (Expression (N)));
4528 Expand_Allocator_Expression (N);
4529 return;
4530 end if;
4532 -- If the allocator is for a type which requires initialization, and
4533 -- there is no initial value (i.e. operand is a subtype indication
4534 -- rather than a qualified expression), then we must generate a call to
4535 -- the initialization routine using an expressions action node:
4537 -- [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
4539 -- Here ptr_T is the pointer type for the allocator, and T is the
4540 -- subtype of the allocator. A special case arises if the designated
4541 -- type of the access type is a task or contains tasks. In this case
4542 -- the call to Init (Temp.all ...) is replaced by code that ensures
4543 -- that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
4544 -- for details). In addition, if the type T is a task type, then the
4545 -- first argument to Init must be converted to the task record type.
4547 declare
4548 T : constant Entity_Id := Entity (Expression (N));
4549 Args : List_Id;
4550 Decls : List_Id;
4551 Decl : Node_Id;
4552 Discr : Elmt_Id;
4553 Init : Entity_Id;
4554 Init_Arg1 : Node_Id;
4555 Temp_Decl : Node_Id;
4556 Temp_Type : Entity_Id;
4558 begin
4559 if No_Initialization (N) then
4561 -- Even though this might be a simple allocation, create a custom
4562 -- Allocate if the context requires it. Since .NET/JVM compilers
4563 -- do not support pools, this step is skipped.
4565 if VM_Target = No_VM
4566 and then Present (Finalization_Master (PtrT))
4567 then
4568 Build_Allocate_Deallocate_Proc
4569 (N => N,
4570 Is_Allocate => True);
4571 end if;
4573 -- Case of no initialization procedure present
4575 elsif not Has_Non_Null_Base_Init_Proc (T) then
4577 -- Case of simple initialization required
4579 if Needs_Simple_Initialization (T) then
4580 Check_Restriction (No_Default_Initialization, N);
4581 Rewrite (Expression (N),
4582 Make_Qualified_Expression (Loc,
4583 Subtype_Mark => New_Occurrence_Of (T, Loc),
4584 Expression => Get_Simple_Init_Val (T, N)));
4586 Analyze_And_Resolve (Expression (Expression (N)), T);
4587 Analyze_And_Resolve (Expression (N), T);
4588 Set_Paren_Count (Expression (Expression (N)), 1);
4589 Expand_N_Allocator (N);
4591 -- No initialization required
4593 else
4594 null;
4595 end if;
4597 -- Case of initialization procedure present, must be called
4599 else
4600 Check_Restriction (No_Default_Initialization, N);
4602 if not Restriction_Active (No_Default_Initialization) then
4603 Init := Base_Init_Proc (T);
4604 Nod := N;
4605 Temp := Make_Temporary (Loc, 'P');
4607 -- Construct argument list for the initialization routine call
4609 Init_Arg1 :=
4610 Make_Explicit_Dereference (Loc,
4611 Prefix =>
4612 New_Occurrence_Of (Temp, Loc));
4614 Set_Assignment_OK (Init_Arg1);
4615 Temp_Type := PtrT;
4617 -- The initialization procedure expects a specific type. if the
4618 -- context is access to class wide, indicate that the object
4619 -- being allocated has the right specific type.
4621 if Is_Class_Wide_Type (Dtyp) then
4622 Init_Arg1 := Unchecked_Convert_To (T, Init_Arg1);
4623 end if;
4625 -- If designated type is a concurrent type or if it is private
4626 -- type whose definition is a concurrent type, the first
4627 -- argument in the Init routine has to be unchecked conversion
4628 -- to the corresponding record type. If the designated type is
4629 -- a derived type, also convert the argument to its root type.
4631 if Is_Concurrent_Type (T) then
4632 Init_Arg1 :=
4633 Unchecked_Convert_To (
4634 Corresponding_Record_Type (T), Init_Arg1);
4636 elsif Is_Private_Type (T)
4637 and then Present (Full_View (T))
4638 and then Is_Concurrent_Type (Full_View (T))
4639 then
4640 Init_Arg1 :=
4641 Unchecked_Convert_To
4642 (Corresponding_Record_Type (Full_View (T)), Init_Arg1);
4644 elsif Etype (First_Formal (Init)) /= Base_Type (T) then
4645 declare
4646 Ftyp : constant Entity_Id := Etype (First_Formal (Init));
4648 begin
4649 Init_Arg1 := OK_Convert_To (Etype (Ftyp), Init_Arg1);
4650 Set_Etype (Init_Arg1, Ftyp);
4651 end;
4652 end if;
4654 Args := New_List (Init_Arg1);
4656 -- For the task case, pass the Master_Id of the access type as
4657 -- the value of the _Master parameter, and _Chain as the value
4658 -- of the _Chain parameter (_Chain will be defined as part of
4659 -- the generated code for the allocator).
4661 -- In Ada 2005, the context may be a function that returns an
4662 -- anonymous access type. In that case the Master_Id has been
4663 -- created when expanding the function declaration.
4665 if Has_Task (T) then
4666 if No (Master_Id (Base_Type (PtrT))) then
4668 -- The designated type was an incomplete type, and the
4669 -- access type did not get expanded. Salvage it now.
4671 if not Restriction_Active (No_Task_Hierarchy) then
4672 if Present (Parent (Base_Type (PtrT))) then
4673 Expand_N_Full_Type_Declaration
4674 (Parent (Base_Type (PtrT)));
4676 -- The only other possibility is an itype. For this
4677 -- case, the master must exist in the context. This is
4678 -- the case when the allocator initializes an access
4679 -- component in an init-proc.
4681 else
4682 pragma Assert (Is_Itype (PtrT));
4683 Build_Master_Renaming (PtrT, N);
4684 end if;
4685 end if;
4686 end if;
4688 -- If the context of the allocator is a declaration or an
4689 -- assignment, we can generate a meaningful image for it,
4690 -- even though subsequent assignments might remove the
4691 -- connection between task and entity. We build this image
4692 -- when the left-hand side is a simple variable, a simple
4693 -- indexed assignment or a simple selected component.
4695 if Nkind (Parent (N)) = N_Assignment_Statement then
4696 declare
4697 Nam : constant Node_Id := Name (Parent (N));
4699 begin
4700 if Is_Entity_Name (Nam) then
4701 Decls :=
4702 Build_Task_Image_Decls
4703 (Loc,
4704 New_Occurrence_Of
4705 (Entity (Nam), Sloc (Nam)), T);
4707 elsif Nkind_In (Nam, N_Indexed_Component,
4708 N_Selected_Component)
4709 and then Is_Entity_Name (Prefix (Nam))
4710 then
4711 Decls :=
4712 Build_Task_Image_Decls
4713 (Loc, Nam, Etype (Prefix (Nam)));
4714 else
4715 Decls := Build_Task_Image_Decls (Loc, T, T);
4716 end if;
4717 end;
4719 elsif Nkind (Parent (N)) = N_Object_Declaration then
4720 Decls :=
4721 Build_Task_Image_Decls
4722 (Loc, Defining_Identifier (Parent (N)), T);
4724 else
4725 Decls := Build_Task_Image_Decls (Loc, T, T);
4726 end if;
4728 if Restriction_Active (No_Task_Hierarchy) then
4729 Append_To (Args,
4730 New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc));
4731 else
4732 Append_To (Args,
4733 New_Occurrence_Of
4734 (Master_Id (Base_Type (Root_Type (PtrT))), Loc));
4735 end if;
4737 Append_To (Args, Make_Identifier (Loc, Name_uChain));
4739 Decl := Last (Decls);
4740 Append_To (Args,
4741 New_Occurrence_Of (Defining_Identifier (Decl), Loc));
4743 -- Has_Task is false, Decls not used
4745 else
4746 Decls := No_List;
4747 end if;
4749 -- Add discriminants if discriminated type
4751 declare
4752 Dis : Boolean := False;
4753 Typ : Entity_Id;
4755 begin
4756 if Has_Discriminants (T) then
4757 Dis := True;
4758 Typ := T;
4760 elsif Is_Private_Type (T)
4761 and then Present (Full_View (T))
4762 and then Has_Discriminants (Full_View (T))
4763 then
4764 Dis := True;
4765 Typ := Full_View (T);
4766 end if;
4768 if Dis then
4770 -- If the allocated object will be constrained by the
4771 -- default values for discriminants, then build a subtype
4772 -- with those defaults, and change the allocated subtype
4773 -- to that. Note that this happens in fewer cases in Ada
4774 -- 2005 (AI-363).
4776 if not Is_Constrained (Typ)
4777 and then Present (Discriminant_Default_Value
4778 (First_Discriminant (Typ)))
4779 and then (Ada_Version < Ada_2005
4780 or else not
4781 Object_Type_Has_Constrained_Partial_View
4782 (Typ, Current_Scope))
4783 then
4784 Typ := Build_Default_Subtype (Typ, N);
4785 Set_Expression (N, New_Occurrence_Of (Typ, Loc));
4786 end if;
4788 Discr := First_Elmt (Discriminant_Constraint (Typ));
4789 while Present (Discr) loop
4790 Nod := Node (Discr);
4791 Append (New_Copy_Tree (Node (Discr)), Args);
4793 -- AI-416: when the discriminant constraint is an
4794 -- anonymous access type make sure an accessibility
4795 -- check is inserted if necessary (3.10.2(22.q/2))
4797 if Ada_Version >= Ada_2005
4798 and then
4799 Ekind (Etype (Nod)) = E_Anonymous_Access_Type
4800 then
4801 Apply_Accessibility_Check
4802 (Nod, Typ, Insert_Node => Nod);
4803 end if;
4805 Next_Elmt (Discr);
4806 end loop;
4807 end if;
4808 end;
4810 -- We set the allocator as analyzed so that when we analyze
4811 -- the if expression node, we do not get an unwanted recursive
4812 -- expansion of the allocator expression.
4814 Set_Analyzed (N, True);
4815 Nod := Relocate_Node (N);
4817 -- Here is the transformation:
4818 -- input: new Ctrl_Typ
4819 -- output: Temp : constant Ctrl_Typ_Ptr := new Ctrl_Typ;
4820 -- Ctrl_TypIP (Temp.all, ...);
4821 -- [Deep_]Initialize (Temp.all);
4823 -- Here Ctrl_Typ_Ptr is the pointer type for the allocator, and
4824 -- is the subtype of the allocator.
4826 Temp_Decl :=
4827 Make_Object_Declaration (Loc,
4828 Defining_Identifier => Temp,
4829 Constant_Present => True,
4830 Object_Definition => New_Occurrence_Of (Temp_Type, Loc),
4831 Expression => Nod);
4833 Set_Assignment_OK (Temp_Decl);
4834 Insert_Action (N, Temp_Decl, Suppress => All_Checks);
4836 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
4838 -- If the designated type is a task type or contains tasks,
4839 -- create block to activate created tasks, and insert
4840 -- declaration for Task_Image variable ahead of call.
4842 if Has_Task (T) then
4843 declare
4844 L : constant List_Id := New_List;
4845 Blk : Node_Id;
4846 begin
4847 Build_Task_Allocate_Block (L, Nod, Args);
4848 Blk := Last (L);
4849 Insert_List_Before (First (Declarations (Blk)), Decls);
4850 Insert_Actions (N, L);
4851 end;
4853 else
4854 Insert_Action (N,
4855 Make_Procedure_Call_Statement (Loc,
4856 Name => New_Occurrence_Of (Init, Loc),
4857 Parameter_Associations => Args));
4858 end if;
4860 if Needs_Finalization (T) then
4862 -- Generate:
4863 -- [Deep_]Initialize (Init_Arg1);
4865 Insert_Action (N,
4866 Make_Init_Call
4867 (Obj_Ref => New_Copy_Tree (Init_Arg1),
4868 Typ => T));
4870 if Present (Finalization_Master (PtrT)) then
4872 -- Special processing for .NET/JVM, the allocated object
4873 -- is attached to the finalization master. Generate:
4875 -- Attach (<PtrT>FM, Root_Controlled_Ptr (Init_Arg1));
4877 -- Types derived from [Limited_]Controlled are the only
4878 -- ones considered since they have fields Prev and Next.
4880 if VM_Target /= No_VM then
4881 if Is_Controlled (T) then
4882 Insert_Action (N,
4883 Make_Attach_Call
4884 (Obj_Ref => New_Copy_Tree (Init_Arg1),
4885 Ptr_Typ => PtrT));
4886 end if;
4888 -- Default case, generate:
4890 -- Set_Finalize_Address
4891 -- (<PtrT>FM, <T>FD'Unrestricted_Access);
4893 -- Do not generate this call in CodePeer mode, as TSS
4894 -- primitive Finalize_Address is not created in this
4895 -- mode.
4897 elsif not CodePeer_Mode then
4898 Insert_Action (N,
4899 Make_Set_Finalize_Address_Call
4900 (Loc => Loc,
4901 Typ => T,
4902 Ptr_Typ => PtrT));
4903 end if;
4904 end if;
4905 end if;
4907 Rewrite (N, New_Occurrence_Of (Temp, Loc));
4908 Analyze_And_Resolve (N, PtrT);
4909 end if;
4910 end if;
4911 end;
4913 -- Ada 2005 (AI-251): If the allocator is for a class-wide interface
4914 -- object that has been rewritten as a reference, we displace "this"
4915 -- to reference properly its secondary dispatch table.
4917 if Nkind (N) = N_Identifier and then Is_Interface (Dtyp) then
4918 Displace_Allocator_Pointer (N);
4919 end if;
4921 exception
4922 when RE_Not_Available =>
4923 return;
4924 end Expand_N_Allocator;
4926 -----------------------
4927 -- Expand_N_And_Then --
4928 -----------------------
4930 procedure Expand_N_And_Then (N : Node_Id)
4931 renames Expand_Short_Circuit_Operator;
4933 ------------------------------
4934 -- Expand_N_Case_Expression --
4935 ------------------------------
4937 procedure Expand_N_Case_Expression (N : Node_Id) is
4938 Loc : constant Source_Ptr := Sloc (N);
4939 Typ : constant Entity_Id := Etype (N);
4940 Cstmt : Node_Id;
4941 Decl : Node_Id;
4942 Tnn : Entity_Id;
4943 Pnn : Entity_Id;
4944 Actions : List_Id;
4945 Ttyp : Entity_Id;
4946 Alt : Node_Id;
4947 Fexp : Node_Id;
4949 begin
4950 -- Check for MINIMIZED/ELIMINATED overflow mode
4952 if Minimized_Eliminated_Overflow_Check (N) then
4953 Apply_Arithmetic_Overflow_Check (N);
4954 return;
4955 end if;
4957 -- If the case expression is a predicate specification, do not
4958 -- expand, because it will be converted to the proper predicate
4959 -- form when building the predicate function.
4961 if Ekind_In (Current_Scope, E_Function, E_Procedure)
4962 and then Is_Predicate_Function (Current_Scope)
4963 then
4964 return;
4965 end if;
4967 -- We expand
4969 -- case X is when A => AX, when B => BX ...
4971 -- to
4973 -- do
4974 -- Tnn : typ;
4975 -- case X is
4976 -- when A =>
4977 -- Tnn := AX;
4978 -- when B =>
4979 -- Tnn := BX;
4980 -- ...
4981 -- end case;
4982 -- in Tnn end;
4984 -- However, this expansion is wrong for limited types, and also
4985 -- wrong for unconstrained types (since the bounds may not be the
4986 -- same in all branches). Furthermore it involves an extra copy
4987 -- for large objects. So we take care of this by using the following
4988 -- modified expansion for non-elementary types:
4990 -- do
4991 -- type Pnn is access all typ;
4992 -- Tnn : Pnn;
4993 -- case X is
4994 -- when A =>
4995 -- T := AX'Unrestricted_Access;
4996 -- when B =>
4997 -- T := BX'Unrestricted_Access;
4998 -- ...
4999 -- end case;
5000 -- in Tnn.all end;
5002 Cstmt :=
5003 Make_Case_Statement (Loc,
5004 Expression => Expression (N),
5005 Alternatives => New_List);
5007 -- Preserve the original context for which the case statement is being
5008 -- generated. This is needed by the finalization machinery to prevent
5009 -- the premature finalization of controlled objects found within the
5010 -- case statement.
5012 Set_From_Conditional_Expression (Cstmt);
5014 Actions := New_List;
5016 -- Scalar case
5018 if Is_Elementary_Type (Typ) then
5019 Ttyp := Typ;
5021 else
5022 Pnn := Make_Temporary (Loc, 'P');
5023 Append_To (Actions,
5024 Make_Full_Type_Declaration (Loc,
5025 Defining_Identifier => Pnn,
5026 Type_Definition =>
5027 Make_Access_To_Object_Definition (Loc,
5028 All_Present => True,
5029 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5030 Ttyp := Pnn;
5031 end if;
5033 Tnn := Make_Temporary (Loc, 'T');
5035 -- Create declaration for target of expression, and indicate that it
5036 -- does not require initialization.
5038 Decl :=
5039 Make_Object_Declaration (Loc,
5040 Defining_Identifier => Tnn,
5041 Object_Definition => New_Occurrence_Of (Ttyp, Loc));
5042 Set_No_Initialization (Decl);
5043 Append_To (Actions, Decl);
5045 -- Now process the alternatives
5047 Alt := First (Alternatives (N));
5048 while Present (Alt) loop
5049 declare
5050 Aexp : Node_Id := Expression (Alt);
5051 Aloc : constant Source_Ptr := Sloc (Aexp);
5052 Stats : List_Id;
5054 begin
5055 -- As described above, take Unrestricted_Access for case of non-
5056 -- scalar types, to avoid big copies, and special cases.
5058 if not Is_Elementary_Type (Typ) then
5059 Aexp :=
5060 Make_Attribute_Reference (Aloc,
5061 Prefix => Relocate_Node (Aexp),
5062 Attribute_Name => Name_Unrestricted_Access);
5063 end if;
5065 Stats := New_List (
5066 Make_Assignment_Statement (Aloc,
5067 Name => New_Occurrence_Of (Tnn, Loc),
5068 Expression => Aexp));
5070 -- Propagate declarations inserted in the node by Insert_Actions
5071 -- (for example, temporaries generated to remove side effects).
5072 -- These actions must remain attached to the alternative, given
5073 -- that they are generated by the corresponding expression.
5075 if Present (Sinfo.Actions (Alt)) then
5076 Prepend_List (Sinfo.Actions (Alt), Stats);
5077 end if;
5079 Append_To
5080 (Alternatives (Cstmt),
5081 Make_Case_Statement_Alternative (Sloc (Alt),
5082 Discrete_Choices => Discrete_Choices (Alt),
5083 Statements => Stats));
5084 end;
5086 Next (Alt);
5087 end loop;
5089 Append_To (Actions, Cstmt);
5091 -- Construct and return final expression with actions
5093 if Is_Elementary_Type (Typ) then
5094 Fexp := New_Occurrence_Of (Tnn, Loc);
5095 else
5096 Fexp :=
5097 Make_Explicit_Dereference (Loc,
5098 Prefix => New_Occurrence_Of (Tnn, Loc));
5099 end if;
5101 Rewrite (N,
5102 Make_Expression_With_Actions (Loc,
5103 Expression => Fexp,
5104 Actions => Actions));
5106 Analyze_And_Resolve (N, Typ);
5107 end Expand_N_Case_Expression;
5109 -----------------------------------
5110 -- Expand_N_Explicit_Dereference --
5111 -----------------------------------
5113 procedure Expand_N_Explicit_Dereference (N : Node_Id) is
5114 begin
5115 -- Insert explicit dereference call for the checked storage pool case
5117 Insert_Dereference_Action (Prefix (N));
5119 -- If the type is an Atomic type for which Atomic_Sync is enabled, then
5120 -- we set the atomic sync flag.
5122 if Is_Atomic (Etype (N))
5123 and then not Atomic_Synchronization_Disabled (Etype (N))
5124 then
5125 Activate_Atomic_Synchronization (N);
5126 end if;
5127 end Expand_N_Explicit_Dereference;
5129 --------------------------------------
5130 -- Expand_N_Expression_With_Actions --
5131 --------------------------------------
5133 procedure Expand_N_Expression_With_Actions (N : Node_Id) is
5135 function Process_Action (Act : Node_Id) return Traverse_Result;
5136 -- Inspect and process a single action of an expression_with_actions for
5137 -- transient controlled objects. If such objects are found, the routine
5138 -- generates code to clean them up when the context of the expression is
5139 -- evaluated or elaborated.
5141 --------------------
5142 -- Process_Action --
5143 --------------------
5145 function Process_Action (Act : Node_Id) return Traverse_Result is
5146 begin
5147 if Nkind (Act) = N_Object_Declaration
5148 and then Is_Finalizable_Transient (Act, N)
5149 then
5150 Process_Transient_Object (Act, N);
5151 return Abandon;
5153 -- Avoid processing temporary function results multiple times when
5154 -- dealing with nested expression_with_actions.
5156 elsif Nkind (Act) = N_Expression_With_Actions then
5157 return Abandon;
5159 -- Do not process temporary function results in loops. This is done
5160 -- by Expand_N_Loop_Statement and Build_Finalizer.
5162 elsif Nkind (Act) = N_Loop_Statement then
5163 return Abandon;
5164 end if;
5166 return OK;
5167 end Process_Action;
5169 procedure Process_Single_Action is new Traverse_Proc (Process_Action);
5171 -- Local variables
5173 Act : Node_Id;
5175 -- Start of processing for Expand_N_Expression_With_Actions
5177 begin
5178 -- Process the actions as described above
5180 Act := First (Actions (N));
5181 while Present (Act) loop
5182 Process_Single_Action (Act);
5183 Next (Act);
5184 end loop;
5186 -- Deal with case where there are no actions. In this case we simply
5187 -- rewrite the node with its expression since we don't need the actions
5188 -- and the specification of this node does not allow a null action list.
5190 -- Note: we use Rewrite instead of Replace, because Codepeer is using
5191 -- the expanded tree and relying on being able to retrieve the original
5192 -- tree in cases like this. This raises a whole lot of issues of whether
5193 -- we have problems elsewhere, which will be addressed in the future???
5195 if Is_Empty_List (Actions (N)) then
5196 Rewrite (N, Relocate_Node (Expression (N)));
5197 end if;
5198 end Expand_N_Expression_With_Actions;
5200 ----------------------------
5201 -- Expand_N_If_Expression --
5202 ----------------------------
5204 -- Deal with limited types and condition actions
5206 procedure Expand_N_If_Expression (N : Node_Id) is
5207 procedure Process_Actions (Actions : List_Id);
5208 -- Inspect and process a single action list of an if expression for
5209 -- transient controlled objects. If such objects are found, the routine
5210 -- generates code to clean them up when the context of the expression is
5211 -- evaluated or elaborated.
5213 ---------------------
5214 -- Process_Actions --
5215 ---------------------
5217 procedure Process_Actions (Actions : List_Id) is
5218 Act : Node_Id;
5220 begin
5221 Act := First (Actions);
5222 while Present (Act) loop
5223 if Nkind (Act) = N_Object_Declaration
5224 and then Is_Finalizable_Transient (Act, N)
5225 then
5226 Process_Transient_Object (Act, N);
5227 end if;
5229 Next (Act);
5230 end loop;
5231 end Process_Actions;
5233 -- Local variables
5235 Loc : constant Source_Ptr := Sloc (N);
5236 Cond : constant Node_Id := First (Expressions (N));
5237 Thenx : constant Node_Id := Next (Cond);
5238 Elsex : constant Node_Id := Next (Thenx);
5239 Typ : constant Entity_Id := Etype (N);
5241 Actions : List_Id;
5242 Cnn : Entity_Id;
5243 Decl : Node_Id;
5244 Expr : Node_Id;
5245 New_If : Node_Id;
5246 New_N : Node_Id;
5247 Ptr_Typ : Entity_Id;
5249 -- Start of processing for Expand_N_If_Expression
5251 begin
5252 -- Check for MINIMIZED/ELIMINATED overflow mode
5254 if Minimized_Eliminated_Overflow_Check (N) then
5255 Apply_Arithmetic_Overflow_Check (N);
5256 return;
5257 end if;
5259 -- Fold at compile time if condition known. We have already folded
5260 -- static if expressions, but it is possible to fold any case in which
5261 -- the condition is known at compile time, even though the result is
5262 -- non-static.
5264 -- Note that we don't do the fold of such cases in Sem_Elab because
5265 -- it can cause infinite loops with the expander adding a conditional
5266 -- expression, and Sem_Elab circuitry removing it repeatedly.
5268 if Compile_Time_Known_Value (Cond) then
5269 if Is_True (Expr_Value (Cond)) then
5270 Expr := Thenx;
5271 Actions := Then_Actions (N);
5272 else
5273 Expr := Elsex;
5274 Actions := Else_Actions (N);
5275 end if;
5277 Remove (Expr);
5279 if Present (Actions) then
5280 Rewrite (N,
5281 Make_Expression_With_Actions (Loc,
5282 Expression => Relocate_Node (Expr),
5283 Actions => Actions));
5284 Analyze_And_Resolve (N, Typ);
5285 else
5286 Rewrite (N, Relocate_Node (Expr));
5287 end if;
5289 -- Note that the result is never static (legitimate cases of static
5290 -- if expressions were folded in Sem_Eval).
5292 Set_Is_Static_Expression (N, False);
5293 return;
5294 end if;
5296 -- If the type is limited, and the back end does not handle limited
5297 -- types, then we expand as follows to avoid the possibility of
5298 -- improper copying.
5300 -- type Ptr is access all Typ;
5301 -- Cnn : Ptr;
5302 -- if cond then
5303 -- <<then actions>>
5304 -- Cnn := then-expr'Unrestricted_Access;
5305 -- else
5306 -- <<else actions>>
5307 -- Cnn := else-expr'Unrestricted_Access;
5308 -- end if;
5310 -- and replace the if expression by a reference to Cnn.all.
5312 -- This special case can be skipped if the back end handles limited
5313 -- types properly and ensures that no incorrect copies are made.
5315 if Is_By_Reference_Type (Typ)
5316 and then not Back_End_Handles_Limited_Types
5317 then
5318 -- When the "then" or "else" expressions involve controlled function
5319 -- calls, generated temporaries are chained on the corresponding list
5320 -- of actions. These temporaries need to be finalized after the if
5321 -- expression is evaluated.
5323 Process_Actions (Then_Actions (N));
5324 Process_Actions (Else_Actions (N));
5326 -- Generate:
5327 -- type Ann is access all Typ;
5329 Ptr_Typ := Make_Temporary (Loc, 'A');
5331 Insert_Action (N,
5332 Make_Full_Type_Declaration (Loc,
5333 Defining_Identifier => Ptr_Typ,
5334 Type_Definition =>
5335 Make_Access_To_Object_Definition (Loc,
5336 All_Present => True,
5337 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5339 -- Generate:
5340 -- Cnn : Ann;
5342 Cnn := Make_Temporary (Loc, 'C', N);
5344 Decl :=
5345 Make_Object_Declaration (Loc,
5346 Defining_Identifier => Cnn,
5347 Object_Definition => New_Occurrence_Of (Ptr_Typ, Loc));
5349 -- Generate:
5350 -- if Cond then
5351 -- Cnn := <Thenx>'Unrestricted_Access;
5352 -- else
5353 -- Cnn := <Elsex>'Unrestricted_Access;
5354 -- end if;
5356 New_If :=
5357 Make_Implicit_If_Statement (N,
5358 Condition => Relocate_Node (Cond),
5359 Then_Statements => New_List (
5360 Make_Assignment_Statement (Sloc (Thenx),
5361 Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
5362 Expression =>
5363 Make_Attribute_Reference (Loc,
5364 Prefix => Relocate_Node (Thenx),
5365 Attribute_Name => Name_Unrestricted_Access))),
5367 Else_Statements => New_List (
5368 Make_Assignment_Statement (Sloc (Elsex),
5369 Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
5370 Expression =>
5371 Make_Attribute_Reference (Loc,
5372 Prefix => Relocate_Node (Elsex),
5373 Attribute_Name => Name_Unrestricted_Access))));
5375 -- Preserve the original context for which the if statement is being
5376 -- generated. This is needed by the finalization machinery to prevent
5377 -- the premature finalization of controlled objects found within the
5378 -- if statement.
5380 Set_From_Conditional_Expression (New_If);
5382 New_N :=
5383 Make_Explicit_Dereference (Loc,
5384 Prefix => New_Occurrence_Of (Cnn, Loc));
5386 -- If the result is an unconstrained array and the if expression is in a
5387 -- context other than the initializing expression of the declaration of
5388 -- an object, then we pull out the if expression as follows:
5390 -- Cnn : constant typ := if-expression
5392 -- and then replace the if expression with an occurrence of Cnn. This
5393 -- avoids the need in the back end to create on-the-fly variable length
5394 -- temporaries (which it cannot do!)
5396 -- Note that the test for being in an object declaration avoids doing an
5397 -- unnecessary expansion, and also avoids infinite recursion.
5399 elsif Is_Array_Type (Typ) and then not Is_Constrained (Typ)
5400 and then (Nkind (Parent (N)) /= N_Object_Declaration
5401 or else Expression (Parent (N)) /= N)
5402 then
5403 declare
5404 Cnn : constant Node_Id := Make_Temporary (Loc, 'C', N);
5405 begin
5406 Insert_Action (N,
5407 Make_Object_Declaration (Loc,
5408 Defining_Identifier => Cnn,
5409 Constant_Present => True,
5410 Object_Definition => New_Occurrence_Of (Typ, Loc),
5411 Expression => Relocate_Node (N),
5412 Has_Init_Expression => True));
5414 Rewrite (N, New_Occurrence_Of (Cnn, Loc));
5415 return;
5416 end;
5418 -- For other types, we only need to expand if there are other actions
5419 -- associated with either branch.
5421 elsif Present (Then_Actions (N)) or else Present (Else_Actions (N)) then
5423 -- We now wrap the actions into the appropriate expression
5425 if Present (Then_Actions (N)) then
5426 Rewrite (Thenx,
5427 Make_Expression_With_Actions (Sloc (Thenx),
5428 Actions => Then_Actions (N),
5429 Expression => Relocate_Node (Thenx)));
5431 Set_Then_Actions (N, No_List);
5432 Analyze_And_Resolve (Thenx, Typ);
5433 end if;
5435 if Present (Else_Actions (N)) then
5436 Rewrite (Elsex,
5437 Make_Expression_With_Actions (Sloc (Elsex),
5438 Actions => Else_Actions (N),
5439 Expression => Relocate_Node (Elsex)));
5441 Set_Else_Actions (N, No_List);
5442 Analyze_And_Resolve (Elsex, Typ);
5443 end if;
5445 return;
5447 -- If no actions then no expansion needed, gigi will handle it using the
5448 -- same approach as a C conditional expression.
5450 else
5451 return;
5452 end if;
5454 -- Fall through here for either the limited expansion, or the case of
5455 -- inserting actions for non-limited types. In both these cases, we must
5456 -- move the SLOC of the parent If statement to the newly created one and
5457 -- change it to the SLOC of the expression which, after expansion, will
5458 -- correspond to what is being evaluated.
5460 if Present (Parent (N)) and then Nkind (Parent (N)) = N_If_Statement then
5461 Set_Sloc (New_If, Sloc (Parent (N)));
5462 Set_Sloc (Parent (N), Loc);
5463 end if;
5465 -- Make sure Then_Actions and Else_Actions are appropriately moved
5466 -- to the new if statement.
5468 if Present (Then_Actions (N)) then
5469 Insert_List_Before
5470 (First (Then_Statements (New_If)), Then_Actions (N));
5471 end if;
5473 if Present (Else_Actions (N)) then
5474 Insert_List_Before
5475 (First (Else_Statements (New_If)), Else_Actions (N));
5476 end if;
5478 Insert_Action (N, Decl);
5479 Insert_Action (N, New_If);
5480 Rewrite (N, New_N);
5481 Analyze_And_Resolve (N, Typ);
5482 end Expand_N_If_Expression;
5484 -----------------
5485 -- Expand_N_In --
5486 -----------------
5488 procedure Expand_N_In (N : Node_Id) is
5489 Loc : constant Source_Ptr := Sloc (N);
5490 Restyp : constant Entity_Id := Etype (N);
5491 Lop : constant Node_Id := Left_Opnd (N);
5492 Rop : constant Node_Id := Right_Opnd (N);
5493 Static : constant Boolean := Is_OK_Static_Expression (N);
5495 Ltyp : Entity_Id;
5496 Rtyp : Entity_Id;
5498 procedure Substitute_Valid_Check;
5499 -- Replaces node N by Lop'Valid. This is done when we have an explicit
5500 -- test for the left operand being in range of its subtype.
5502 ----------------------------
5503 -- Substitute_Valid_Check --
5504 ----------------------------
5506 procedure Substitute_Valid_Check is
5507 begin
5508 Rewrite (N,
5509 Make_Attribute_Reference (Loc,
5510 Prefix => Relocate_Node (Lop),
5511 Attribute_Name => Name_Valid));
5513 Analyze_And_Resolve (N, Restyp);
5515 -- Give warning unless overflow checking is MINIMIZED or ELIMINATED,
5516 -- in which case, this usage makes sense, and in any case, we have
5517 -- actually eliminated the danger of optimization above.
5519 if Overflow_Check_Mode not in Minimized_Or_Eliminated then
5520 Error_Msg_N
5521 ("??explicit membership test may be optimized away", N);
5522 Error_Msg_N -- CODEFIX
5523 ("\??use ''Valid attribute instead", N);
5524 end if;
5526 return;
5527 end Substitute_Valid_Check;
5529 -- Start of processing for Expand_N_In
5531 begin
5532 -- If set membership case, expand with separate procedure
5534 if Present (Alternatives (N)) then
5535 Expand_Set_Membership (N);
5536 return;
5537 end if;
5539 -- Not set membership, proceed with expansion
5541 Ltyp := Etype (Left_Opnd (N));
5542 Rtyp := Etype (Right_Opnd (N));
5544 -- If MINIMIZED/ELIMINATED overflow mode and type is a signed integer
5545 -- type, then expand with a separate procedure. Note the use of the
5546 -- flag No_Minimize_Eliminate to prevent infinite recursion.
5548 if Overflow_Check_Mode in Minimized_Or_Eliminated
5549 and then Is_Signed_Integer_Type (Ltyp)
5550 and then not No_Minimize_Eliminate (N)
5551 then
5552 Expand_Membership_Minimize_Eliminate_Overflow (N);
5553 return;
5554 end if;
5556 -- Check case of explicit test for an expression in range of its
5557 -- subtype. This is suspicious usage and we replace it with a 'Valid
5558 -- test and give a warning for scalar types.
5560 if Is_Scalar_Type (Ltyp)
5562 -- Only relevant for source comparisons
5564 and then Comes_From_Source (N)
5566 -- In floating-point this is a standard way to check for finite values
5567 -- and using 'Valid would typically be a pessimization.
5569 and then not Is_Floating_Point_Type (Ltyp)
5571 -- Don't give the message unless right operand is a type entity and
5572 -- the type of the left operand matches this type. Note that this
5573 -- eliminates the cases where MINIMIZED/ELIMINATED mode overflow
5574 -- checks have changed the type of the left operand.
5576 and then Nkind (Rop) in N_Has_Entity
5577 and then Ltyp = Entity (Rop)
5579 -- Skip in VM mode, where we have no sense of invalid values. The
5580 -- warning still seems relevant, but not important enough to worry.
5582 and then VM_Target = No_VM
5584 -- Skip this for predicated types, where such expressions are a
5585 -- reasonable way of testing if something meets the predicate.
5587 and then not Present (Predicate_Function (Ltyp))
5588 then
5589 Substitute_Valid_Check;
5590 return;
5591 end if;
5593 -- Do validity check on operands
5595 if Validity_Checks_On and Validity_Check_Operands then
5596 Ensure_Valid (Left_Opnd (N));
5597 Validity_Check_Range (Right_Opnd (N));
5598 end if;
5600 -- Case of explicit range
5602 if Nkind (Rop) = N_Range then
5603 declare
5604 Lo : constant Node_Id := Low_Bound (Rop);
5605 Hi : constant Node_Id := High_Bound (Rop);
5607 Lo_Orig : constant Node_Id := Original_Node (Lo);
5608 Hi_Orig : constant Node_Id := Original_Node (Hi);
5610 Lcheck : Compare_Result;
5611 Ucheck : Compare_Result;
5613 Warn1 : constant Boolean :=
5614 Constant_Condition_Warnings
5615 and then Comes_From_Source (N)
5616 and then not In_Instance;
5617 -- This must be true for any of the optimization warnings, we
5618 -- clearly want to give them only for source with the flag on. We
5619 -- also skip these warnings in an instance since it may be the
5620 -- case that different instantiations have different ranges.
5622 Warn2 : constant Boolean :=
5623 Warn1
5624 and then Nkind (Original_Node (Rop)) = N_Range
5625 and then Is_Integer_Type (Etype (Lo));
5626 -- For the case where only one bound warning is elided, we also
5627 -- insist on an explicit range and an integer type. The reason is
5628 -- that the use of enumeration ranges including an end point is
5629 -- common, as is the use of a subtype name, one of whose bounds is
5630 -- the same as the type of the expression.
5632 begin
5633 -- If test is explicit x'First .. x'Last, replace by valid check
5635 -- Could use some individual comments for this complex test ???
5637 if Is_Scalar_Type (Ltyp)
5639 -- And left operand is X'First where X matches left operand
5640 -- type (this eliminates cases of type mismatch, including
5641 -- the cases where ELIMINATED/MINIMIZED mode has changed the
5642 -- type of the left operand.
5644 and then Nkind (Lo_Orig) = N_Attribute_Reference
5645 and then Attribute_Name (Lo_Orig) = Name_First
5646 and then Nkind (Prefix (Lo_Orig)) in N_Has_Entity
5647 and then Entity (Prefix (Lo_Orig)) = Ltyp
5649 -- Same tests for right operand
5651 and then Nkind (Hi_Orig) = N_Attribute_Reference
5652 and then Attribute_Name (Hi_Orig) = Name_Last
5653 and then Nkind (Prefix (Hi_Orig)) in N_Has_Entity
5654 and then Entity (Prefix (Hi_Orig)) = Ltyp
5656 -- Relevant only for source cases
5658 and then Comes_From_Source (N)
5660 -- Omit for VM cases, where we don't have invalid values
5662 and then VM_Target = No_VM
5663 then
5664 Substitute_Valid_Check;
5665 goto Leave;
5666 end if;
5668 -- If bounds of type are known at compile time, and the end points
5669 -- are known at compile time and identical, this is another case
5670 -- for substituting a valid test. We only do this for discrete
5671 -- types, since it won't arise in practice for float types.
5673 if Comes_From_Source (N)
5674 and then Is_Discrete_Type (Ltyp)
5675 and then Compile_Time_Known_Value (Type_High_Bound (Ltyp))
5676 and then Compile_Time_Known_Value (Type_Low_Bound (Ltyp))
5677 and then Compile_Time_Known_Value (Lo)
5678 and then Compile_Time_Known_Value (Hi)
5679 and then Expr_Value (Type_High_Bound (Ltyp)) = Expr_Value (Hi)
5680 and then Expr_Value (Type_Low_Bound (Ltyp)) = Expr_Value (Lo)
5682 -- Kill warnings in instances, since they may be cases where we
5683 -- have a test in the generic that makes sense with some types
5684 -- and not with other types.
5686 and then not In_Instance
5687 then
5688 Substitute_Valid_Check;
5689 goto Leave;
5690 end if;
5692 -- If we have an explicit range, do a bit of optimization based on
5693 -- range analysis (we may be able to kill one or both checks).
5695 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => False);
5696 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => False);
5698 -- If either check is known to fail, replace result by False since
5699 -- the other check does not matter. Preserve the static flag for
5700 -- legality checks, because we are constant-folding beyond RM 4.9.
5702 if Lcheck = LT or else Ucheck = GT then
5703 if Warn1 then
5704 Error_Msg_N ("?c?range test optimized away", N);
5705 Error_Msg_N ("\?c?value is known to be out of range", N);
5706 end if;
5708 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
5709 Analyze_And_Resolve (N, Restyp);
5710 Set_Is_Static_Expression (N, Static);
5711 goto Leave;
5713 -- If both checks are known to succeed, replace result by True,
5714 -- since we know we are in range.
5716 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
5717 if Warn1 then
5718 Error_Msg_N ("?c?range test optimized away", N);
5719 Error_Msg_N ("\?c?value is known to be in range", N);
5720 end if;
5722 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
5723 Analyze_And_Resolve (N, Restyp);
5724 Set_Is_Static_Expression (N, Static);
5725 goto Leave;
5727 -- If lower bound check succeeds and upper bound check is not
5728 -- known to succeed or fail, then replace the range check with
5729 -- a comparison against the upper bound.
5731 elsif Lcheck in Compare_GE then
5732 if Warn2 and then not In_Instance then
5733 Error_Msg_N ("??lower bound test optimized away", Lo);
5734 Error_Msg_N ("\??value is known to be in range", Lo);
5735 end if;
5737 Rewrite (N,
5738 Make_Op_Le (Loc,
5739 Left_Opnd => Lop,
5740 Right_Opnd => High_Bound (Rop)));
5741 Analyze_And_Resolve (N, Restyp);
5742 goto Leave;
5744 -- If upper bound check succeeds and lower bound check is not
5745 -- known to succeed or fail, then replace the range check with
5746 -- a comparison against the lower bound.
5748 elsif Ucheck in Compare_LE then
5749 if Warn2 and then not In_Instance then
5750 Error_Msg_N ("??upper bound test optimized away", Hi);
5751 Error_Msg_N ("\??value is known to be in range", Hi);
5752 end if;
5754 Rewrite (N,
5755 Make_Op_Ge (Loc,
5756 Left_Opnd => Lop,
5757 Right_Opnd => Low_Bound (Rop)));
5758 Analyze_And_Resolve (N, Restyp);
5759 goto Leave;
5760 end if;
5762 -- We couldn't optimize away the range check, but there is one
5763 -- more issue. If we are checking constant conditionals, then we
5764 -- see if we can determine the outcome assuming everything is
5765 -- valid, and if so give an appropriate warning.
5767 if Warn1 and then not Assume_No_Invalid_Values then
5768 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => True);
5769 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => True);
5771 -- Result is out of range for valid value
5773 if Lcheck = LT or else Ucheck = GT then
5774 Error_Msg_N
5775 ("?c?value can only be in range if it is invalid", N);
5777 -- Result is in range for valid value
5779 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
5780 Error_Msg_N
5781 ("?c?value can only be out of range if it is invalid", N);
5783 -- Lower bound check succeeds if value is valid
5785 elsif Warn2 and then Lcheck in Compare_GE then
5786 Error_Msg_N
5787 ("?c?lower bound check only fails if it is invalid", Lo);
5789 -- Upper bound check succeeds if value is valid
5791 elsif Warn2 and then Ucheck in Compare_LE then
5792 Error_Msg_N
5793 ("?c?upper bound check only fails for invalid values", Hi);
5794 end if;
5795 end if;
5796 end;
5798 -- For all other cases of an explicit range, nothing to be done
5800 goto Leave;
5802 -- Here right operand is a subtype mark
5804 else
5805 declare
5806 Typ : Entity_Id := Etype (Rop);
5807 Is_Acc : constant Boolean := Is_Access_Type (Typ);
5808 Cond : Node_Id := Empty;
5809 New_N : Node_Id;
5810 Obj : Node_Id := Lop;
5811 SCIL_Node : Node_Id;
5813 begin
5814 Remove_Side_Effects (Obj);
5816 -- For tagged type, do tagged membership operation
5818 if Is_Tagged_Type (Typ) then
5820 -- No expansion will be performed when VM_Target, as the VM
5821 -- back-ends will handle the membership tests directly (tags
5822 -- are not explicitly represented in Java objects, so the
5823 -- normal tagged membership expansion is not what we want).
5825 if Tagged_Type_Expansion then
5826 Tagged_Membership (N, SCIL_Node, New_N);
5827 Rewrite (N, New_N);
5828 Analyze_And_Resolve (N, Restyp);
5830 -- Update decoration of relocated node referenced by the
5831 -- SCIL node.
5833 if Generate_SCIL and then Present (SCIL_Node) then
5834 Set_SCIL_Node (N, SCIL_Node);
5835 end if;
5836 end if;
5838 goto Leave;
5840 -- If type is scalar type, rewrite as x in t'First .. t'Last.
5841 -- This reason we do this is that the bounds may have the wrong
5842 -- type if they come from the original type definition. Also this
5843 -- way we get all the processing above for an explicit range.
5845 -- Don't do this for predicated types, since in this case we
5846 -- want to check the predicate.
5848 elsif Is_Scalar_Type (Typ) then
5849 if No (Predicate_Function (Typ)) then
5850 Rewrite (Rop,
5851 Make_Range (Loc,
5852 Low_Bound =>
5853 Make_Attribute_Reference (Loc,
5854 Attribute_Name => Name_First,
5855 Prefix => New_Occurrence_Of (Typ, Loc)),
5857 High_Bound =>
5858 Make_Attribute_Reference (Loc,
5859 Attribute_Name => Name_Last,
5860 Prefix => New_Occurrence_Of (Typ, Loc))));
5861 Analyze_And_Resolve (N, Restyp);
5862 end if;
5864 goto Leave;
5866 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
5867 -- a membership test if the subtype mark denotes a constrained
5868 -- Unchecked_Union subtype and the expression lacks inferable
5869 -- discriminants.
5871 elsif Is_Unchecked_Union (Base_Type (Typ))
5872 and then Is_Constrained (Typ)
5873 and then not Has_Inferable_Discriminants (Lop)
5874 then
5875 Insert_Action (N,
5876 Make_Raise_Program_Error (Loc,
5877 Reason => PE_Unchecked_Union_Restriction));
5879 -- Prevent Gigi from generating incorrect code by rewriting the
5880 -- test as False. What is this undocumented thing about ???
5882 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
5883 goto Leave;
5884 end if;
5886 -- Here we have a non-scalar type
5888 if Is_Acc then
5889 Typ := Designated_Type (Typ);
5890 end if;
5892 if not Is_Constrained (Typ) then
5893 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
5894 Analyze_And_Resolve (N, Restyp);
5896 -- For the constrained array case, we have to check the subscripts
5897 -- for an exact match if the lengths are non-zero (the lengths
5898 -- must match in any case).
5900 elsif Is_Array_Type (Typ) then
5901 Check_Subscripts : declare
5902 function Build_Attribute_Reference
5903 (E : Node_Id;
5904 Nam : Name_Id;
5905 Dim : Nat) return Node_Id;
5906 -- Build attribute reference E'Nam (Dim)
5908 -------------------------------
5909 -- Build_Attribute_Reference --
5910 -------------------------------
5912 function Build_Attribute_Reference
5913 (E : Node_Id;
5914 Nam : Name_Id;
5915 Dim : Nat) return Node_Id
5917 begin
5918 return
5919 Make_Attribute_Reference (Loc,
5920 Prefix => E,
5921 Attribute_Name => Nam,
5922 Expressions => New_List (
5923 Make_Integer_Literal (Loc, Dim)));
5924 end Build_Attribute_Reference;
5926 -- Start of processing for Check_Subscripts
5928 begin
5929 for J in 1 .. Number_Dimensions (Typ) loop
5930 Evolve_And_Then (Cond,
5931 Make_Op_Eq (Loc,
5932 Left_Opnd =>
5933 Build_Attribute_Reference
5934 (Duplicate_Subexpr_No_Checks (Obj),
5935 Name_First, J),
5936 Right_Opnd =>
5937 Build_Attribute_Reference
5938 (New_Occurrence_Of (Typ, Loc), Name_First, J)));
5940 Evolve_And_Then (Cond,
5941 Make_Op_Eq (Loc,
5942 Left_Opnd =>
5943 Build_Attribute_Reference
5944 (Duplicate_Subexpr_No_Checks (Obj),
5945 Name_Last, J),
5946 Right_Opnd =>
5947 Build_Attribute_Reference
5948 (New_Occurrence_Of (Typ, Loc), Name_Last, J)));
5949 end loop;
5951 if Is_Acc then
5952 Cond :=
5953 Make_Or_Else (Loc,
5954 Left_Opnd =>
5955 Make_Op_Eq (Loc,
5956 Left_Opnd => Obj,
5957 Right_Opnd => Make_Null (Loc)),
5958 Right_Opnd => Cond);
5959 end if;
5961 Rewrite (N, Cond);
5962 Analyze_And_Resolve (N, Restyp);
5963 end Check_Subscripts;
5965 -- These are the cases where constraint checks may be required,
5966 -- e.g. records with possible discriminants
5968 else
5969 -- Expand the test into a series of discriminant comparisons.
5970 -- The expression that is built is the negation of the one that
5971 -- is used for checking discriminant constraints.
5973 Obj := Relocate_Node (Left_Opnd (N));
5975 if Has_Discriminants (Typ) then
5976 Cond := Make_Op_Not (Loc,
5977 Right_Opnd => Build_Discriminant_Checks (Obj, Typ));
5979 if Is_Acc then
5980 Cond := Make_Or_Else (Loc,
5981 Left_Opnd =>
5982 Make_Op_Eq (Loc,
5983 Left_Opnd => Obj,
5984 Right_Opnd => Make_Null (Loc)),
5985 Right_Opnd => Cond);
5986 end if;
5988 else
5989 Cond := New_Occurrence_Of (Standard_True, Loc);
5990 end if;
5992 Rewrite (N, Cond);
5993 Analyze_And_Resolve (N, Restyp);
5994 end if;
5996 -- Ada 2012 (AI05-0149): Handle membership tests applied to an
5997 -- expression of an anonymous access type. This can involve an
5998 -- accessibility test and a tagged type membership test in the
5999 -- case of tagged designated types.
6001 if Ada_Version >= Ada_2012
6002 and then Is_Acc
6003 and then Ekind (Ltyp) = E_Anonymous_Access_Type
6004 then
6005 declare
6006 Expr_Entity : Entity_Id := Empty;
6007 New_N : Node_Id;
6008 Param_Level : Node_Id;
6009 Type_Level : Node_Id;
6011 begin
6012 if Is_Entity_Name (Lop) then
6013 Expr_Entity := Param_Entity (Lop);
6015 if not Present (Expr_Entity) then
6016 Expr_Entity := Entity (Lop);
6017 end if;
6018 end if;
6020 -- If a conversion of the anonymous access value to the
6021 -- tested type would be illegal, then the result is False.
6023 if not Valid_Conversion
6024 (Lop, Rtyp, Lop, Report_Errs => False)
6025 then
6026 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6027 Analyze_And_Resolve (N, Restyp);
6029 -- Apply an accessibility check if the access object has an
6030 -- associated access level and when the level of the type is
6031 -- less deep than the level of the access parameter. This
6032 -- only occur for access parameters and stand-alone objects
6033 -- of an anonymous access type.
6035 else
6036 if Present (Expr_Entity)
6037 and then
6038 Present
6039 (Effective_Extra_Accessibility (Expr_Entity))
6040 and then UI_Gt (Object_Access_Level (Lop),
6041 Type_Access_Level (Rtyp))
6042 then
6043 Param_Level :=
6044 New_Occurrence_Of
6045 (Effective_Extra_Accessibility (Expr_Entity), Loc);
6047 Type_Level :=
6048 Make_Integer_Literal (Loc, Type_Access_Level (Rtyp));
6050 -- Return True only if the accessibility level of the
6051 -- expression entity is not deeper than the level of
6052 -- the tested access type.
6054 Rewrite (N,
6055 Make_And_Then (Loc,
6056 Left_Opnd => Relocate_Node (N),
6057 Right_Opnd => Make_Op_Le (Loc,
6058 Left_Opnd => Param_Level,
6059 Right_Opnd => Type_Level)));
6061 Analyze_And_Resolve (N);
6062 end if;
6064 -- If the designated type is tagged, do tagged membership
6065 -- operation.
6067 -- *** NOTE: we have to check not null before doing the
6068 -- tagged membership test (but maybe that can be done
6069 -- inside Tagged_Membership?).
6071 if Is_Tagged_Type (Typ) then
6072 Rewrite (N,
6073 Make_And_Then (Loc,
6074 Left_Opnd => Relocate_Node (N),
6075 Right_Opnd =>
6076 Make_Op_Ne (Loc,
6077 Left_Opnd => Obj,
6078 Right_Opnd => Make_Null (Loc))));
6080 -- No expansion will be performed when VM_Target, as
6081 -- the VM back-ends will handle the membership tests
6082 -- directly (tags are not explicitly represented in
6083 -- Java objects, so the normal tagged membership
6084 -- expansion is not what we want).
6086 if Tagged_Type_Expansion then
6088 -- Note that we have to pass Original_Node, because
6089 -- the membership test might already have been
6090 -- rewritten by earlier parts of membership test.
6092 Tagged_Membership
6093 (Original_Node (N), SCIL_Node, New_N);
6095 -- Update decoration of relocated node referenced
6096 -- by the SCIL node.
6098 if Generate_SCIL and then Present (SCIL_Node) then
6099 Set_SCIL_Node (New_N, SCIL_Node);
6100 end if;
6102 Rewrite (N,
6103 Make_And_Then (Loc,
6104 Left_Opnd => Relocate_Node (N),
6105 Right_Opnd => New_N));
6107 Analyze_And_Resolve (N, Restyp);
6108 end if;
6109 end if;
6110 end if;
6111 end;
6112 end if;
6113 end;
6114 end if;
6116 -- At this point, we have done the processing required for the basic
6117 -- membership test, but not yet dealt with the predicate.
6119 <<Leave>>
6121 -- If a predicate is present, then we do the predicate test, but we
6122 -- most certainly want to omit this if we are within the predicate
6123 -- function itself, since otherwise we have an infinite recursion.
6124 -- The check should also not be emitted when testing against a range
6125 -- (the check is only done when the right operand is a subtype; see
6126 -- RM12-4.5.2 (28.1/3-30/3)).
6128 declare
6129 PFunc : constant Entity_Id := Predicate_Function (Rtyp);
6131 begin
6132 if Present (PFunc)
6133 and then Current_Scope /= PFunc
6134 and then Nkind (Rop) /= N_Range
6135 then
6136 Rewrite (N,
6137 Make_And_Then (Loc,
6138 Left_Opnd => Relocate_Node (N),
6139 Right_Opnd => Make_Predicate_Call (Rtyp, Lop, Mem => True)));
6141 -- Analyze new expression, mark left operand as analyzed to
6142 -- avoid infinite recursion adding predicate calls. Similarly,
6143 -- suppress further range checks on the call.
6145 Set_Analyzed (Left_Opnd (N));
6146 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6148 -- All done, skip attempt at compile time determination of result
6150 return;
6151 end if;
6152 end;
6153 end Expand_N_In;
6155 --------------------------------
6156 -- Expand_N_Indexed_Component --
6157 --------------------------------
6159 procedure Expand_N_Indexed_Component (N : Node_Id) is
6160 Loc : constant Source_Ptr := Sloc (N);
6161 Typ : constant Entity_Id := Etype (N);
6162 P : constant Node_Id := Prefix (N);
6163 T : constant Entity_Id := Etype (P);
6164 Atp : Entity_Id;
6166 begin
6167 -- A special optimization, if we have an indexed component that is
6168 -- selecting from a slice, then we can eliminate the slice, since, for
6169 -- example, x (i .. j)(k) is identical to x(k). The only difference is
6170 -- the range check required by the slice. The range check for the slice
6171 -- itself has already been generated. The range check for the
6172 -- subscripting operation is ensured by converting the subject to
6173 -- the subtype of the slice.
6175 -- This optimization not only generates better code, avoiding slice
6176 -- messing especially in the packed case, but more importantly bypasses
6177 -- some problems in handling this peculiar case, for example, the issue
6178 -- of dealing specially with object renamings.
6180 if Nkind (P) = N_Slice
6182 -- This optimization is disabled for CodePeer because it can transform
6183 -- an index-check constraint_error into a range-check constraint_error
6184 -- and CodePeer cares about that distinction.
6186 and then not CodePeer_Mode
6187 then
6188 Rewrite (N,
6189 Make_Indexed_Component (Loc,
6190 Prefix => Prefix (P),
6191 Expressions => New_List (
6192 Convert_To
6193 (Etype (First_Index (Etype (P))),
6194 First (Expressions (N))))));
6195 Analyze_And_Resolve (N, Typ);
6196 return;
6197 end if;
6199 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
6200 -- function, then additional actuals must be passed.
6202 if Ada_Version >= Ada_2005
6203 and then Is_Build_In_Place_Function_Call (P)
6204 then
6205 Make_Build_In_Place_Call_In_Anonymous_Context (P);
6206 end if;
6208 -- If the prefix is an access type, then we unconditionally rewrite if
6209 -- as an explicit dereference. This simplifies processing for several
6210 -- cases, including packed array cases and certain cases in which checks
6211 -- must be generated. We used to try to do this only when it was
6212 -- necessary, but it cleans up the code to do it all the time.
6214 if Is_Access_Type (T) then
6215 Insert_Explicit_Dereference (P);
6216 Analyze_And_Resolve (P, Designated_Type (T));
6217 Atp := Designated_Type (T);
6218 else
6219 Atp := T;
6220 end if;
6222 -- Generate index and validity checks
6224 Generate_Index_Checks (N);
6226 if Validity_Checks_On and then Validity_Check_Subscripts then
6227 Apply_Subscript_Validity_Checks (N);
6228 end if;
6230 -- If selecting from an array with atomic components, and atomic sync
6231 -- is not suppressed for this array type, set atomic sync flag.
6233 if (Has_Atomic_Components (Atp)
6234 and then not Atomic_Synchronization_Disabled (Atp))
6235 or else (Is_Atomic (Typ)
6236 and then not Atomic_Synchronization_Disabled (Typ))
6237 then
6238 Activate_Atomic_Synchronization (N);
6239 end if;
6241 -- All done for the non-packed case
6243 if not Is_Packed (Etype (Prefix (N))) then
6244 return;
6245 end if;
6247 -- For packed arrays that are not bit-packed (i.e. the case of an array
6248 -- with one or more index types with a non-contiguous enumeration type),
6249 -- we can always use the normal packed element get circuit.
6251 if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
6252 Expand_Packed_Element_Reference (N);
6253 return;
6254 end if;
6256 -- For a reference to a component of a bit packed array, we convert it
6257 -- to a reference to the corresponding Packed_Array_Impl_Type. We only
6258 -- want to do this for simple references, and not for:
6260 -- Left side of assignment, or prefix of left side of assignment, or
6261 -- prefix of the prefix, to handle packed arrays of packed arrays,
6262 -- This case is handled in Exp_Ch5.Expand_N_Assignment_Statement
6264 -- Renaming objects in renaming associations
6265 -- This case is handled when a use of the renamed variable occurs
6267 -- Actual parameters for a procedure call
6268 -- This case is handled in Exp_Ch6.Expand_Actuals
6270 -- The second expression in a 'Read attribute reference
6272 -- The prefix of an address or bit or size attribute reference
6274 -- The following circuit detects these exceptions
6276 declare
6277 Child : Node_Id := N;
6278 Parnt : Node_Id := Parent (N);
6280 begin
6281 loop
6282 if Nkind (Parnt) = N_Unchecked_Expression then
6283 null;
6285 elsif Nkind_In (Parnt, N_Object_Renaming_Declaration,
6286 N_Procedure_Call_Statement)
6287 or else (Nkind (Parnt) = N_Parameter_Association
6288 and then
6289 Nkind (Parent (Parnt)) = N_Procedure_Call_Statement)
6290 then
6291 return;
6293 elsif Nkind (Parnt) = N_Attribute_Reference
6294 and then Nam_In (Attribute_Name (Parnt), Name_Address,
6295 Name_Bit,
6296 Name_Size)
6297 and then Prefix (Parnt) = Child
6298 then
6299 return;
6301 elsif Nkind (Parnt) = N_Assignment_Statement
6302 and then Name (Parnt) = Child
6303 then
6304 return;
6306 -- If the expression is an index of an indexed component, it must
6307 -- be expanded regardless of context.
6309 elsif Nkind (Parnt) = N_Indexed_Component
6310 and then Child /= Prefix (Parnt)
6311 then
6312 Expand_Packed_Element_Reference (N);
6313 return;
6315 elsif Nkind (Parent (Parnt)) = N_Assignment_Statement
6316 and then Name (Parent (Parnt)) = Parnt
6317 then
6318 return;
6320 elsif Nkind (Parnt) = N_Attribute_Reference
6321 and then Attribute_Name (Parnt) = Name_Read
6322 and then Next (First (Expressions (Parnt))) = Child
6323 then
6324 return;
6326 elsif Nkind_In (Parnt, N_Indexed_Component, N_Selected_Component)
6327 and then Prefix (Parnt) = Child
6328 then
6329 null;
6331 else
6332 Expand_Packed_Element_Reference (N);
6333 return;
6334 end if;
6336 -- Keep looking up tree for unchecked expression, or if we are the
6337 -- prefix of a possible assignment left side.
6339 Child := Parnt;
6340 Parnt := Parent (Child);
6341 end loop;
6342 end;
6343 end Expand_N_Indexed_Component;
6345 ---------------------
6346 -- Expand_N_Not_In --
6347 ---------------------
6349 -- Replace a not in b by not (a in b) so that the expansions for (a in b)
6350 -- can be done. This avoids needing to duplicate this expansion code.
6352 procedure Expand_N_Not_In (N : Node_Id) is
6353 Loc : constant Source_Ptr := Sloc (N);
6354 Typ : constant Entity_Id := Etype (N);
6355 Cfs : constant Boolean := Comes_From_Source (N);
6357 begin
6358 Rewrite (N,
6359 Make_Op_Not (Loc,
6360 Right_Opnd =>
6361 Make_In (Loc,
6362 Left_Opnd => Left_Opnd (N),
6363 Right_Opnd => Right_Opnd (N))));
6365 -- If this is a set membership, preserve list of alternatives
6367 Set_Alternatives (Right_Opnd (N), Alternatives (Original_Node (N)));
6369 -- We want this to appear as coming from source if original does (see
6370 -- transformations in Expand_N_In).
6372 Set_Comes_From_Source (N, Cfs);
6373 Set_Comes_From_Source (Right_Opnd (N), Cfs);
6375 -- Now analyze transformed node
6377 Analyze_And_Resolve (N, Typ);
6378 end Expand_N_Not_In;
6380 -------------------
6381 -- Expand_N_Null --
6382 -------------------
6384 -- The only replacement required is for the case of a null of a type that
6385 -- is an access to protected subprogram, or a subtype thereof. We represent
6386 -- such access values as a record, and so we must replace the occurrence of
6387 -- null by the equivalent record (with a null address and a null pointer in
6388 -- it), so that the backend creates the proper value.
6390 procedure Expand_N_Null (N : Node_Id) is
6391 Loc : constant Source_Ptr := Sloc (N);
6392 Typ : constant Entity_Id := Base_Type (Etype (N));
6393 Agg : Node_Id;
6395 begin
6396 if Is_Access_Protected_Subprogram_Type (Typ) then
6397 Agg :=
6398 Make_Aggregate (Loc,
6399 Expressions => New_List (
6400 New_Occurrence_Of (RTE (RE_Null_Address), Loc),
6401 Make_Null (Loc)));
6403 Rewrite (N, Agg);
6404 Analyze_And_Resolve (N, Equivalent_Type (Typ));
6406 -- For subsequent semantic analysis, the node must retain its type.
6407 -- Gigi in any case replaces this type by the corresponding record
6408 -- type before processing the node.
6410 Set_Etype (N, Typ);
6411 end if;
6413 exception
6414 when RE_Not_Available =>
6415 return;
6416 end Expand_N_Null;
6418 ---------------------
6419 -- Expand_N_Op_Abs --
6420 ---------------------
6422 procedure Expand_N_Op_Abs (N : Node_Id) is
6423 Loc : constant Source_Ptr := Sloc (N);
6424 Expr : constant Node_Id := Right_Opnd (N);
6426 begin
6427 Unary_Op_Validity_Checks (N);
6429 -- Check for MINIMIZED/ELIMINATED overflow mode
6431 if Minimized_Eliminated_Overflow_Check (N) then
6432 Apply_Arithmetic_Overflow_Check (N);
6433 return;
6434 end if;
6436 -- Deal with software overflow checking
6438 if not Backend_Overflow_Checks_On_Target
6439 and then Is_Signed_Integer_Type (Etype (N))
6440 and then Do_Overflow_Check (N)
6441 then
6442 -- The only case to worry about is when the argument is equal to the
6443 -- largest negative number, so what we do is to insert the check:
6445 -- [constraint_error when Expr = typ'Base'First]
6447 -- with the usual Duplicate_Subexpr use coding for expr
6449 Insert_Action (N,
6450 Make_Raise_Constraint_Error (Loc,
6451 Condition =>
6452 Make_Op_Eq (Loc,
6453 Left_Opnd => Duplicate_Subexpr (Expr),
6454 Right_Opnd =>
6455 Make_Attribute_Reference (Loc,
6456 Prefix =>
6457 New_Occurrence_Of (Base_Type (Etype (Expr)), Loc),
6458 Attribute_Name => Name_First)),
6459 Reason => CE_Overflow_Check_Failed));
6460 end if;
6461 end Expand_N_Op_Abs;
6463 ---------------------
6464 -- Expand_N_Op_Add --
6465 ---------------------
6467 procedure Expand_N_Op_Add (N : Node_Id) is
6468 Typ : constant Entity_Id := Etype (N);
6470 begin
6471 Binary_Op_Validity_Checks (N);
6473 -- Check for MINIMIZED/ELIMINATED overflow mode
6475 if Minimized_Eliminated_Overflow_Check (N) then
6476 Apply_Arithmetic_Overflow_Check (N);
6477 return;
6478 end if;
6480 -- N + 0 = 0 + N = N for integer types
6482 if Is_Integer_Type (Typ) then
6483 if Compile_Time_Known_Value (Right_Opnd (N))
6484 and then Expr_Value (Right_Opnd (N)) = Uint_0
6485 then
6486 Rewrite (N, Left_Opnd (N));
6487 return;
6489 elsif Compile_Time_Known_Value (Left_Opnd (N))
6490 and then Expr_Value (Left_Opnd (N)) = Uint_0
6491 then
6492 Rewrite (N, Right_Opnd (N));
6493 return;
6494 end if;
6495 end if;
6497 -- Arithmetic overflow checks for signed integer/fixed point types
6499 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
6500 Apply_Arithmetic_Overflow_Check (N);
6501 return;
6502 end if;
6504 -- Overflow checks for floating-point if -gnateF mode active
6506 Check_Float_Op_Overflow (N);
6507 end Expand_N_Op_Add;
6509 ---------------------
6510 -- Expand_N_Op_And --
6511 ---------------------
6513 procedure Expand_N_Op_And (N : Node_Id) is
6514 Typ : constant Entity_Id := Etype (N);
6516 begin
6517 Binary_Op_Validity_Checks (N);
6519 if Is_Array_Type (Etype (N)) then
6520 Expand_Boolean_Operator (N);
6522 elsif Is_Boolean_Type (Etype (N)) then
6523 Adjust_Condition (Left_Opnd (N));
6524 Adjust_Condition (Right_Opnd (N));
6525 Set_Etype (N, Standard_Boolean);
6526 Adjust_Result_Type (N, Typ);
6528 elsif Is_Intrinsic_Subprogram (Entity (N)) then
6529 Expand_Intrinsic_Call (N, Entity (N));
6531 end if;
6532 end Expand_N_Op_And;
6534 ------------------------
6535 -- Expand_N_Op_Concat --
6536 ------------------------
6538 procedure Expand_N_Op_Concat (N : Node_Id) is
6539 Opnds : List_Id;
6540 -- List of operands to be concatenated
6542 Cnode : Node_Id;
6543 -- Node which is to be replaced by the result of concatenating the nodes
6544 -- in the list Opnds.
6546 begin
6547 -- Ensure validity of both operands
6549 Binary_Op_Validity_Checks (N);
6551 -- If we are the left operand of a concatenation higher up the tree,
6552 -- then do nothing for now, since we want to deal with a series of
6553 -- concatenations as a unit.
6555 if Nkind (Parent (N)) = N_Op_Concat
6556 and then N = Left_Opnd (Parent (N))
6557 then
6558 return;
6559 end if;
6561 -- We get here with a concatenation whose left operand may be a
6562 -- concatenation itself with a consistent type. We need to process
6563 -- these concatenation operands from left to right, which means
6564 -- from the deepest node in the tree to the highest node.
6566 Cnode := N;
6567 while Nkind (Left_Opnd (Cnode)) = N_Op_Concat loop
6568 Cnode := Left_Opnd (Cnode);
6569 end loop;
6571 -- Now Cnode is the deepest concatenation, and its parents are the
6572 -- concatenation nodes above, so now we process bottom up, doing the
6573 -- operands.
6575 -- The outer loop runs more than once if more than one concatenation
6576 -- type is involved.
6578 Outer : loop
6579 Opnds := New_List (Left_Opnd (Cnode), Right_Opnd (Cnode));
6580 Set_Parent (Opnds, N);
6582 -- The inner loop gathers concatenation operands
6584 Inner : while Cnode /= N
6585 and then Base_Type (Etype (Cnode)) =
6586 Base_Type (Etype (Parent (Cnode)))
6587 loop
6588 Cnode := Parent (Cnode);
6589 Append (Right_Opnd (Cnode), Opnds);
6590 end loop Inner;
6592 Expand_Concatenate (Cnode, Opnds);
6594 exit Outer when Cnode = N;
6595 Cnode := Parent (Cnode);
6596 end loop Outer;
6597 end Expand_N_Op_Concat;
6599 ------------------------
6600 -- Expand_N_Op_Divide --
6601 ------------------------
6603 procedure Expand_N_Op_Divide (N : Node_Id) is
6604 Loc : constant Source_Ptr := Sloc (N);
6605 Lopnd : constant Node_Id := Left_Opnd (N);
6606 Ropnd : constant Node_Id := Right_Opnd (N);
6607 Ltyp : constant Entity_Id := Etype (Lopnd);
6608 Rtyp : constant Entity_Id := Etype (Ropnd);
6609 Typ : Entity_Id := Etype (N);
6610 Rknow : constant Boolean := Is_Integer_Type (Typ)
6611 and then
6612 Compile_Time_Known_Value (Ropnd);
6613 Rval : Uint;
6615 begin
6616 Binary_Op_Validity_Checks (N);
6618 -- Check for MINIMIZED/ELIMINATED overflow mode
6620 if Minimized_Eliminated_Overflow_Check (N) then
6621 Apply_Arithmetic_Overflow_Check (N);
6622 return;
6623 end if;
6625 -- Otherwise proceed with expansion of division
6627 if Rknow then
6628 Rval := Expr_Value (Ropnd);
6629 end if;
6631 -- N / 1 = N for integer types
6633 if Rknow and then Rval = Uint_1 then
6634 Rewrite (N, Lopnd);
6635 return;
6636 end if;
6638 -- Convert x / 2 ** y to Shift_Right (x, y). Note that the fact that
6639 -- Is_Power_Of_2_For_Shift is set means that we know that our left
6640 -- operand is an unsigned integer, as required for this to work.
6642 if Nkind (Ropnd) = N_Op_Expon
6643 and then Is_Power_Of_2_For_Shift (Ropnd)
6645 -- We cannot do this transformation in configurable run time mode if we
6646 -- have 64-bit integers and long shifts are not available.
6648 and then (Esize (Ltyp) <= 32 or else Support_Long_Shifts_On_Target)
6649 then
6650 Rewrite (N,
6651 Make_Op_Shift_Right (Loc,
6652 Left_Opnd => Lopnd,
6653 Right_Opnd =>
6654 Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
6655 Analyze_And_Resolve (N, Typ);
6656 return;
6657 end if;
6659 -- Do required fixup of universal fixed operation
6661 if Typ = Universal_Fixed then
6662 Fixup_Universal_Fixed_Operation (N);
6663 Typ := Etype (N);
6664 end if;
6666 -- Divisions with fixed-point results
6668 if Is_Fixed_Point_Type (Typ) then
6670 -- No special processing if Treat_Fixed_As_Integer is set, since
6671 -- from a semantic point of view such operations are simply integer
6672 -- operations and will be treated that way.
6674 if not Treat_Fixed_As_Integer (N) then
6675 if Is_Integer_Type (Rtyp) then
6676 Expand_Divide_Fixed_By_Integer_Giving_Fixed (N);
6677 else
6678 Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N);
6679 end if;
6680 end if;
6682 -- Other cases of division of fixed-point operands. Again we exclude the
6683 -- case where Treat_Fixed_As_Integer is set.
6685 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
6686 and then not Treat_Fixed_As_Integer (N)
6687 then
6688 if Is_Integer_Type (Typ) then
6689 Expand_Divide_Fixed_By_Fixed_Giving_Integer (N);
6690 else
6691 pragma Assert (Is_Floating_Point_Type (Typ));
6692 Expand_Divide_Fixed_By_Fixed_Giving_Float (N);
6693 end if;
6695 -- Mixed-mode operations can appear in a non-static universal context,
6696 -- in which case the integer argument must be converted explicitly.
6698 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
6699 Rewrite (Ropnd,
6700 Convert_To (Universal_Real, Relocate_Node (Ropnd)));
6702 Analyze_And_Resolve (Ropnd, Universal_Real);
6704 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
6705 Rewrite (Lopnd,
6706 Convert_To (Universal_Real, Relocate_Node (Lopnd)));
6708 Analyze_And_Resolve (Lopnd, Universal_Real);
6710 -- Non-fixed point cases, do integer zero divide and overflow checks
6712 elsif Is_Integer_Type (Typ) then
6713 Apply_Divide_Checks (N);
6714 end if;
6716 -- Overflow checks for floating-point if -gnateF mode active
6718 Check_Float_Op_Overflow (N);
6719 end Expand_N_Op_Divide;
6721 --------------------
6722 -- Expand_N_Op_Eq --
6723 --------------------
6725 procedure Expand_N_Op_Eq (N : Node_Id) is
6726 Loc : constant Source_Ptr := Sloc (N);
6727 Typ : constant Entity_Id := Etype (N);
6728 Lhs : constant Node_Id := Left_Opnd (N);
6729 Rhs : constant Node_Id := Right_Opnd (N);
6730 Bodies : constant List_Id := New_List;
6731 A_Typ : constant Entity_Id := Etype (Lhs);
6733 Typl : Entity_Id := A_Typ;
6734 Op_Name : Entity_Id;
6735 Prim : Elmt_Id;
6737 procedure Build_Equality_Call (Eq : Entity_Id);
6738 -- If a constructed equality exists for the type or for its parent,
6739 -- build and analyze call, adding conversions if the operation is
6740 -- inherited.
6742 function Has_Unconstrained_UU_Component (Typ : Node_Id) return Boolean;
6743 -- Determines whether a type has a subcomponent of an unconstrained
6744 -- Unchecked_Union subtype. Typ is a record type.
6746 -------------------------
6747 -- Build_Equality_Call --
6748 -------------------------
6750 procedure Build_Equality_Call (Eq : Entity_Id) is
6751 Op_Type : constant Entity_Id := Etype (First_Formal (Eq));
6752 L_Exp : Node_Id := Relocate_Node (Lhs);
6753 R_Exp : Node_Id := Relocate_Node (Rhs);
6755 begin
6756 -- Adjust operands if necessary to comparison type
6758 if Base_Type (Op_Type) /= Base_Type (A_Typ)
6759 and then not Is_Class_Wide_Type (A_Typ)
6760 then
6761 L_Exp := OK_Convert_To (Op_Type, L_Exp);
6762 R_Exp := OK_Convert_To (Op_Type, R_Exp);
6763 end if;
6765 -- If we have an Unchecked_Union, we need to add the inferred
6766 -- discriminant values as actuals in the function call. At this
6767 -- point, the expansion has determined that both operands have
6768 -- inferable discriminants.
6770 if Is_Unchecked_Union (Op_Type) then
6771 declare
6772 Lhs_Type : constant Node_Id := Etype (L_Exp);
6773 Rhs_Type : constant Node_Id := Etype (R_Exp);
6775 Lhs_Discr_Vals : Elist_Id;
6776 -- List of inferred discriminant values for left operand.
6778 Rhs_Discr_Vals : Elist_Id;
6779 -- List of inferred discriminant values for right operand.
6781 Discr : Entity_Id;
6783 begin
6784 Lhs_Discr_Vals := New_Elmt_List;
6785 Rhs_Discr_Vals := New_Elmt_List;
6787 -- Per-object constrained selected components require special
6788 -- attention. If the enclosing scope of the component is an
6789 -- Unchecked_Union, we cannot reference its discriminants
6790 -- directly. This is why we use the extra parameters of the
6791 -- equality function of the enclosing Unchecked_Union.
6793 -- type UU_Type (Discr : Integer := 0) is
6794 -- . . .
6795 -- end record;
6796 -- pragma Unchecked_Union (UU_Type);
6798 -- 1. Unchecked_Union enclosing record:
6800 -- type Enclosing_UU_Type (Discr : Integer := 0) is record
6801 -- . . .
6802 -- Comp : UU_Type (Discr);
6803 -- . . .
6804 -- end Enclosing_UU_Type;
6805 -- pragma Unchecked_Union (Enclosing_UU_Type);
6807 -- Obj1 : Enclosing_UU_Type;
6808 -- Obj2 : Enclosing_UU_Type (1);
6810 -- [. . .] Obj1 = Obj2 [. . .]
6812 -- Generated code:
6814 -- if not (uu_typeEQ (obj1.comp, obj2.comp, a, b)) then
6816 -- A and B are the formal parameters of the equality function
6817 -- of Enclosing_UU_Type. The function always has two extra
6818 -- formals to capture the inferred discriminant values for
6819 -- each discriminant of the type.
6821 -- 2. Non-Unchecked_Union enclosing record:
6823 -- type
6824 -- Enclosing_Non_UU_Type (Discr : Integer := 0)
6825 -- is record
6826 -- . . .
6827 -- Comp : UU_Type (Discr);
6828 -- . . .
6829 -- end Enclosing_Non_UU_Type;
6831 -- Obj1 : Enclosing_Non_UU_Type;
6832 -- Obj2 : Enclosing_Non_UU_Type (1);
6834 -- ... Obj1 = Obj2 ...
6836 -- Generated code:
6838 -- if not (uu_typeEQ (obj1.comp, obj2.comp,
6839 -- obj1.discr, obj2.discr)) then
6841 -- In this case we can directly reference the discriminants of
6842 -- the enclosing record.
6844 -- Process left operand of equality
6846 if Nkind (Lhs) = N_Selected_Component
6847 and then
6848 Has_Per_Object_Constraint (Entity (Selector_Name (Lhs)))
6849 then
6850 -- If enclosing record is an Unchecked_Union, use formals
6851 -- corresponding to each discriminant. The name of the
6852 -- formal is that of the discriminant, with added suffix,
6853 -- see Exp_Ch3.Build_Record_Equality for details.
6855 if Is_Unchecked_Union (Scope (Entity (Selector_Name (Lhs))))
6856 then
6857 Discr :=
6858 First_Discriminant
6859 (Scope (Entity (Selector_Name (Lhs))));
6860 while Present (Discr) loop
6861 Append_Elmt
6862 (Make_Identifier (Loc,
6863 Chars => New_External_Name (Chars (Discr), 'A')),
6864 To => Lhs_Discr_Vals);
6865 Next_Discriminant (Discr);
6866 end loop;
6868 -- If enclosing record is of a non-Unchecked_Union type, it
6869 -- is possible to reference its discriminants directly.
6871 else
6872 Discr := First_Discriminant (Lhs_Type);
6873 while Present (Discr) loop
6874 Append_Elmt
6875 (Make_Selected_Component (Loc,
6876 Prefix => Prefix (Lhs),
6877 Selector_Name =>
6878 New_Copy
6879 (Get_Discriminant_Value (Discr,
6880 Lhs_Type,
6881 Stored_Constraint (Lhs_Type)))),
6882 To => Lhs_Discr_Vals);
6883 Next_Discriminant (Discr);
6884 end loop;
6885 end if;
6887 -- Otherwise operand is on object with a constrained type.
6888 -- Infer the discriminant values from the constraint.
6890 else
6892 Discr := First_Discriminant (Lhs_Type);
6893 while Present (Discr) loop
6894 Append_Elmt
6895 (New_Copy
6896 (Get_Discriminant_Value (Discr,
6897 Lhs_Type,
6898 Stored_Constraint (Lhs_Type))),
6899 To => Lhs_Discr_Vals);
6900 Next_Discriminant (Discr);
6901 end loop;
6902 end if;
6904 -- Similar processing for right operand of equality
6906 if Nkind (Rhs) = N_Selected_Component
6907 and then
6908 Has_Per_Object_Constraint (Entity (Selector_Name (Rhs)))
6909 then
6910 if Is_Unchecked_Union
6911 (Scope (Entity (Selector_Name (Rhs))))
6912 then
6913 Discr :=
6914 First_Discriminant
6915 (Scope (Entity (Selector_Name (Rhs))));
6916 while Present (Discr) loop
6917 Append_Elmt
6918 (Make_Identifier (Loc,
6919 Chars => New_External_Name (Chars (Discr), 'B')),
6920 To => Rhs_Discr_Vals);
6921 Next_Discriminant (Discr);
6922 end loop;
6924 else
6925 Discr := First_Discriminant (Rhs_Type);
6926 while Present (Discr) loop
6927 Append_Elmt
6928 (Make_Selected_Component (Loc,
6929 Prefix => Prefix (Rhs),
6930 Selector_Name =>
6931 New_Copy (Get_Discriminant_Value
6932 (Discr,
6933 Rhs_Type,
6934 Stored_Constraint (Rhs_Type)))),
6935 To => Rhs_Discr_Vals);
6936 Next_Discriminant (Discr);
6937 end loop;
6938 end if;
6940 else
6941 Discr := First_Discriminant (Rhs_Type);
6942 while Present (Discr) loop
6943 Append_Elmt
6944 (New_Copy (Get_Discriminant_Value
6945 (Discr,
6946 Rhs_Type,
6947 Stored_Constraint (Rhs_Type))),
6948 To => Rhs_Discr_Vals);
6949 Next_Discriminant (Discr);
6950 end loop;
6951 end if;
6953 -- Now merge the list of discriminant values so that values
6954 -- of corresponding discriminants are adjacent.
6956 declare
6957 Params : List_Id;
6958 L_Elmt : Elmt_Id;
6959 R_Elmt : Elmt_Id;
6961 begin
6962 Params := New_List (L_Exp, R_Exp);
6963 L_Elmt := First_Elmt (Lhs_Discr_Vals);
6964 R_Elmt := First_Elmt (Rhs_Discr_Vals);
6965 while Present (L_Elmt) loop
6966 Append_To (Params, Node (L_Elmt));
6967 Append_To (Params, Node (R_Elmt));
6968 Next_Elmt (L_Elmt);
6969 Next_Elmt (R_Elmt);
6970 end loop;
6972 Rewrite (N,
6973 Make_Function_Call (Loc,
6974 Name => New_Occurrence_Of (Eq, Loc),
6975 Parameter_Associations => Params));
6976 end;
6977 end;
6979 -- Normal case, not an unchecked union
6981 else
6982 Rewrite (N,
6983 Make_Function_Call (Loc,
6984 Name => New_Occurrence_Of (Eq, Loc),
6985 Parameter_Associations => New_List (L_Exp, R_Exp)));
6986 end if;
6988 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6989 end Build_Equality_Call;
6991 ------------------------------------
6992 -- Has_Unconstrained_UU_Component --
6993 ------------------------------------
6995 function Has_Unconstrained_UU_Component
6996 (Typ : Node_Id) return Boolean
6998 Tdef : constant Node_Id :=
6999 Type_Definition (Declaration_Node (Base_Type (Typ)));
7000 Clist : Node_Id;
7001 Vpart : Node_Id;
7003 function Component_Is_Unconstrained_UU
7004 (Comp : Node_Id) return Boolean;
7005 -- Determines whether the subtype of the component is an
7006 -- unconstrained Unchecked_Union.
7008 function Variant_Is_Unconstrained_UU
7009 (Variant : Node_Id) return Boolean;
7010 -- Determines whether a component of the variant has an unconstrained
7011 -- Unchecked_Union subtype.
7013 -----------------------------------
7014 -- Component_Is_Unconstrained_UU --
7015 -----------------------------------
7017 function Component_Is_Unconstrained_UU
7018 (Comp : Node_Id) return Boolean
7020 begin
7021 if Nkind (Comp) /= N_Component_Declaration then
7022 return False;
7023 end if;
7025 declare
7026 Sindic : constant Node_Id :=
7027 Subtype_Indication (Component_Definition (Comp));
7029 begin
7030 -- Unconstrained nominal type. In the case of a constraint
7031 -- present, the node kind would have been N_Subtype_Indication.
7033 if Nkind (Sindic) = N_Identifier then
7034 return Is_Unchecked_Union (Base_Type (Etype (Sindic)));
7035 end if;
7037 return False;
7038 end;
7039 end Component_Is_Unconstrained_UU;
7041 ---------------------------------
7042 -- Variant_Is_Unconstrained_UU --
7043 ---------------------------------
7045 function Variant_Is_Unconstrained_UU
7046 (Variant : Node_Id) return Boolean
7048 Clist : constant Node_Id := Component_List (Variant);
7050 begin
7051 if Is_Empty_List (Component_Items (Clist)) then
7052 return False;
7053 end if;
7055 -- We only need to test one component
7057 declare
7058 Comp : Node_Id := First (Component_Items (Clist));
7060 begin
7061 while Present (Comp) loop
7062 if Component_Is_Unconstrained_UU (Comp) then
7063 return True;
7064 end if;
7066 Next (Comp);
7067 end loop;
7068 end;
7070 -- None of the components withing the variant were of
7071 -- unconstrained Unchecked_Union type.
7073 return False;
7074 end Variant_Is_Unconstrained_UU;
7076 -- Start of processing for Has_Unconstrained_UU_Component
7078 begin
7079 if Null_Present (Tdef) then
7080 return False;
7081 end if;
7083 Clist := Component_List (Tdef);
7084 Vpart := Variant_Part (Clist);
7086 -- Inspect available components
7088 if Present (Component_Items (Clist)) then
7089 declare
7090 Comp : Node_Id := First (Component_Items (Clist));
7092 begin
7093 while Present (Comp) loop
7095 -- One component is sufficient
7097 if Component_Is_Unconstrained_UU (Comp) then
7098 return True;
7099 end if;
7101 Next (Comp);
7102 end loop;
7103 end;
7104 end if;
7106 -- Inspect available components withing variants
7108 if Present (Vpart) then
7109 declare
7110 Variant : Node_Id := First (Variants (Vpart));
7112 begin
7113 while Present (Variant) loop
7115 -- One component within a variant is sufficient
7117 if Variant_Is_Unconstrained_UU (Variant) then
7118 return True;
7119 end if;
7121 Next (Variant);
7122 end loop;
7123 end;
7124 end if;
7126 -- Neither the available components, nor the components inside the
7127 -- variant parts were of an unconstrained Unchecked_Union subtype.
7129 return False;
7130 end Has_Unconstrained_UU_Component;
7132 -- Start of processing for Expand_N_Op_Eq
7134 begin
7135 Binary_Op_Validity_Checks (N);
7137 -- Deal with private types
7139 if Ekind (Typl) = E_Private_Type then
7140 Typl := Underlying_Type (Typl);
7141 elsif Ekind (Typl) = E_Private_Subtype then
7142 Typl := Underlying_Type (Base_Type (Typl));
7143 else
7144 null;
7145 end if;
7147 -- It may happen in error situations that the underlying type is not
7148 -- set. The error will be detected later, here we just defend the
7149 -- expander code.
7151 if No (Typl) then
7152 return;
7153 end if;
7155 Typl := Base_Type (Typl);
7157 -- Equality between variant records results in a call to a routine
7158 -- that has conditional tests of the discriminant value(s), and hence
7159 -- violates the No_Implicit_Conditionals restriction.
7161 if Has_Variant_Part (Typl) then
7162 declare
7163 Msg : Boolean;
7165 begin
7166 Check_Restriction (Msg, No_Implicit_Conditionals, N);
7168 if Msg then
7169 Error_Msg_N
7170 ("\comparison of variant records tests discriminants", N);
7171 return;
7172 end if;
7173 end;
7174 end if;
7176 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7177 -- means we no longer have a comparison operation, we are all done.
7179 Expand_Compare_Minimize_Eliminate_Overflow (N);
7181 if Nkind (N) /= N_Op_Eq then
7182 return;
7183 end if;
7185 -- Boolean types (requiring handling of non-standard case)
7187 if Is_Boolean_Type (Typl) then
7188 Adjust_Condition (Left_Opnd (N));
7189 Adjust_Condition (Right_Opnd (N));
7190 Set_Etype (N, Standard_Boolean);
7191 Adjust_Result_Type (N, Typ);
7193 -- Array types
7195 elsif Is_Array_Type (Typl) then
7197 -- If we are doing full validity checking, and it is possible for the
7198 -- array elements to be invalid then expand out array comparisons to
7199 -- make sure that we check the array elements.
7201 if Validity_Check_Operands
7202 and then not Is_Known_Valid (Component_Type (Typl))
7203 then
7204 declare
7205 Save_Force_Validity_Checks : constant Boolean :=
7206 Force_Validity_Checks;
7207 begin
7208 Force_Validity_Checks := True;
7209 Rewrite (N,
7210 Expand_Array_Equality
7212 Relocate_Node (Lhs),
7213 Relocate_Node (Rhs),
7214 Bodies,
7215 Typl));
7216 Insert_Actions (N, Bodies);
7217 Analyze_And_Resolve (N, Standard_Boolean);
7218 Force_Validity_Checks := Save_Force_Validity_Checks;
7219 end;
7221 -- Packed case where both operands are known aligned
7223 elsif Is_Bit_Packed_Array (Typl)
7224 and then not Is_Possibly_Unaligned_Object (Lhs)
7225 and then not Is_Possibly_Unaligned_Object (Rhs)
7226 then
7227 Expand_Packed_Eq (N);
7229 -- Where the component type is elementary we can use a block bit
7230 -- comparison (if supported on the target) exception in the case
7231 -- of floating-point (negative zero issues require element by
7232 -- element comparison), and atomic types (where we must be sure
7233 -- to load elements independently) and possibly unaligned arrays.
7235 elsif Is_Elementary_Type (Component_Type (Typl))
7236 and then not Is_Floating_Point_Type (Component_Type (Typl))
7237 and then not Is_Atomic (Component_Type (Typl))
7238 and then not Is_Possibly_Unaligned_Object (Lhs)
7239 and then not Is_Possibly_Unaligned_Object (Rhs)
7240 and then Support_Composite_Compare_On_Target
7241 then
7242 null;
7244 -- For composite and floating-point cases, expand equality loop to
7245 -- make sure of using proper comparisons for tagged types, and
7246 -- correctly handling the floating-point case.
7248 else
7249 Rewrite (N,
7250 Expand_Array_Equality
7252 Relocate_Node (Lhs),
7253 Relocate_Node (Rhs),
7254 Bodies,
7255 Typl));
7256 Insert_Actions (N, Bodies, Suppress => All_Checks);
7257 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7258 end if;
7260 -- Record Types
7262 elsif Is_Record_Type (Typl) then
7264 -- For tagged types, use the primitive "="
7266 if Is_Tagged_Type (Typl) then
7268 -- No need to do anything else compiling under restriction
7269 -- No_Dispatching_Calls. During the semantic analysis we
7270 -- already notified such violation.
7272 if Restriction_Active (No_Dispatching_Calls) then
7273 return;
7274 end if;
7276 -- If this is derived from an untagged private type completed with
7277 -- a tagged type, it does not have a full view, so we use the
7278 -- primitive operations of the private type. This check should no
7279 -- longer be necessary when these types get their full views???
7281 if Is_Private_Type (A_Typ)
7282 and then not Is_Tagged_Type (A_Typ)
7283 and then Is_Derived_Type (A_Typ)
7284 and then No (Full_View (A_Typ))
7285 then
7286 -- Search for equality operation, checking that the operands
7287 -- have the same type. Note that we must find a matching entry,
7288 -- or something is very wrong.
7290 Prim := First_Elmt (Collect_Primitive_Operations (A_Typ));
7292 while Present (Prim) loop
7293 exit when Chars (Node (Prim)) = Name_Op_Eq
7294 and then Etype (First_Formal (Node (Prim))) =
7295 Etype (Next_Formal (First_Formal (Node (Prim))))
7296 and then
7297 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7299 Next_Elmt (Prim);
7300 end loop;
7302 pragma Assert (Present (Prim));
7303 Op_Name := Node (Prim);
7305 -- Find the type's predefined equality or an overriding
7306 -- user-defined equality. The reason for not simply calling
7307 -- Find_Prim_Op here is that there may be a user-defined
7308 -- overloaded equality op that precedes the equality that we
7309 -- want, so we have to explicitly search (e.g., there could be
7310 -- an equality with two different parameter types).
7312 else
7313 if Is_Class_Wide_Type (Typl) then
7314 Typl := Find_Specific_Type (Typl);
7315 end if;
7317 Prim := First_Elmt (Primitive_Operations (Typl));
7318 while Present (Prim) loop
7319 exit when Chars (Node (Prim)) = Name_Op_Eq
7320 and then Etype (First_Formal (Node (Prim))) =
7321 Etype (Next_Formal (First_Formal (Node (Prim))))
7322 and then
7323 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7325 Next_Elmt (Prim);
7326 end loop;
7328 pragma Assert (Present (Prim));
7329 Op_Name := Node (Prim);
7330 end if;
7332 Build_Equality_Call (Op_Name);
7334 -- Ada 2005 (AI-216): Program_Error is raised when evaluating the
7335 -- predefined equality operator for a type which has a subcomponent
7336 -- of an Unchecked_Union type whose nominal subtype is unconstrained.
7338 elsif Has_Unconstrained_UU_Component (Typl) then
7339 Insert_Action (N,
7340 Make_Raise_Program_Error (Loc,
7341 Reason => PE_Unchecked_Union_Restriction));
7343 -- Prevent Gigi from generating incorrect code by rewriting the
7344 -- equality as a standard False. (is this documented somewhere???)
7346 Rewrite (N,
7347 New_Occurrence_Of (Standard_False, Loc));
7349 elsif Is_Unchecked_Union (Typl) then
7351 -- If we can infer the discriminants of the operands, we make a
7352 -- call to the TSS equality function.
7354 if Has_Inferable_Discriminants (Lhs)
7355 and then
7356 Has_Inferable_Discriminants (Rhs)
7357 then
7358 Build_Equality_Call
7359 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7361 else
7362 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
7363 -- the predefined equality operator for an Unchecked_Union type
7364 -- if either of the operands lack inferable discriminants.
7366 Insert_Action (N,
7367 Make_Raise_Program_Error (Loc,
7368 Reason => PE_Unchecked_Union_Restriction));
7370 -- Emit a warning on source equalities only, otherwise the
7371 -- message may appear out of place due to internal use. The
7372 -- warning is unconditional because it is required by the
7373 -- language.
7375 if Comes_From_Source (N) then
7376 Error_Msg_N
7377 ("Unchecked_Union discriminants cannot be determined??",
7379 Error_Msg_N
7380 ("\Program_Error will be raised for equality operation??",
7382 end if;
7384 -- Prevent Gigi from generating incorrect code by rewriting
7385 -- the equality as a standard False (documented where???).
7387 Rewrite (N,
7388 New_Occurrence_Of (Standard_False, Loc));
7389 end if;
7391 -- If a type support function is present (for complex cases), use it
7393 elsif Present (TSS (Root_Type (Typl), TSS_Composite_Equality)) then
7394 Build_Equality_Call
7395 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7397 -- When comparing two Bounded_Strings, use the primitive equality of
7398 -- the root Super_String type.
7400 elsif Is_Bounded_String (Typl) then
7401 Prim :=
7402 First_Elmt (Collect_Primitive_Operations (Root_Type (Typl)));
7404 while Present (Prim) loop
7405 exit when Chars (Node (Prim)) = Name_Op_Eq
7406 and then Etype (First_Formal (Node (Prim))) =
7407 Etype (Next_Formal (First_Formal (Node (Prim))))
7408 and then Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7410 Next_Elmt (Prim);
7411 end loop;
7413 -- A Super_String type should always have a primitive equality
7415 pragma Assert (Present (Prim));
7416 Build_Equality_Call (Node (Prim));
7418 -- Otherwise expand the component by component equality. Note that
7419 -- we never use block-bit comparisons for records, because of the
7420 -- problems with gaps. The backend will often be able to recombine
7421 -- the separate comparisons that we generate here.
7423 else
7424 Remove_Side_Effects (Lhs);
7425 Remove_Side_Effects (Rhs);
7426 Rewrite (N,
7427 Expand_Record_Equality (N, Typl, Lhs, Rhs, Bodies));
7429 Insert_Actions (N, Bodies, Suppress => All_Checks);
7430 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7431 end if;
7432 end if;
7434 -- Test if result is known at compile time
7436 Rewrite_Comparison (N);
7438 Optimize_Length_Comparison (N);
7439 end Expand_N_Op_Eq;
7441 -----------------------
7442 -- Expand_N_Op_Expon --
7443 -----------------------
7445 procedure Expand_N_Op_Expon (N : Node_Id) is
7446 Loc : constant Source_Ptr := Sloc (N);
7447 Typ : constant Entity_Id := Etype (N);
7448 Rtyp : constant Entity_Id := Root_Type (Typ);
7449 Base : constant Node_Id := Relocate_Node (Left_Opnd (N));
7450 Bastyp : constant Node_Id := Etype (Base);
7451 Exp : constant Node_Id := Relocate_Node (Right_Opnd (N));
7452 Exptyp : constant Entity_Id := Etype (Exp);
7453 Ovflo : constant Boolean := Do_Overflow_Check (N);
7454 Expv : Uint;
7455 Temp : Node_Id;
7456 Rent : RE_Id;
7457 Ent : Entity_Id;
7458 Etyp : Entity_Id;
7459 Xnode : Node_Id;
7461 begin
7462 Binary_Op_Validity_Checks (N);
7464 -- CodePeer wants to see the unexpanded N_Op_Expon node
7466 if CodePeer_Mode then
7467 return;
7468 end if;
7470 -- If either operand is of a private type, then we have the use of an
7471 -- intrinsic operator, and we get rid of the privateness, by using root
7472 -- types of underlying types for the actual operation. Otherwise the
7473 -- private types will cause trouble if we expand multiplications or
7474 -- shifts etc. We also do this transformation if the result type is
7475 -- different from the base type.
7477 if Is_Private_Type (Etype (Base))
7478 or else Is_Private_Type (Typ)
7479 or else Is_Private_Type (Exptyp)
7480 or else Rtyp /= Root_Type (Bastyp)
7481 then
7482 declare
7483 Bt : constant Entity_Id := Root_Type (Underlying_Type (Bastyp));
7484 Et : constant Entity_Id := Root_Type (Underlying_Type (Exptyp));
7485 begin
7486 Rewrite (N,
7487 Unchecked_Convert_To (Typ,
7488 Make_Op_Expon (Loc,
7489 Left_Opnd => Unchecked_Convert_To (Bt, Base),
7490 Right_Opnd => Unchecked_Convert_To (Et, Exp))));
7491 Analyze_And_Resolve (N, Typ);
7492 return;
7493 end;
7494 end if;
7496 -- Check for MINIMIZED/ELIMINATED overflow mode
7498 if Minimized_Eliminated_Overflow_Check (N) then
7499 Apply_Arithmetic_Overflow_Check (N);
7500 return;
7501 end if;
7503 -- Test for case of known right argument where we can replace the
7504 -- exponentiation by an equivalent expression using multiplication.
7506 -- Note: use CRT_Safe version of Compile_Time_Known_Value because in
7507 -- configurable run-time mode, we may not have the exponentiation
7508 -- routine available, and we don't want the legality of the program
7509 -- to depend on how clever the compiler is in knowing values.
7511 if CRT_Safe_Compile_Time_Known_Value (Exp) then
7512 Expv := Expr_Value (Exp);
7514 -- We only fold small non-negative exponents. You might think we
7515 -- could fold small negative exponents for the real case, but we
7516 -- can't because we are required to raise Constraint_Error for
7517 -- the case of 0.0 ** (negative) even if Machine_Overflows = False.
7518 -- See ACVC test C4A012B.
7520 if Expv >= 0 and then Expv <= 4 then
7522 -- X ** 0 = 1 (or 1.0)
7524 if Expv = 0 then
7526 -- Call Remove_Side_Effects to ensure that any side effects
7527 -- in the ignored left operand (in particular function calls
7528 -- to user defined functions) are properly executed.
7530 Remove_Side_Effects (Base);
7532 if Ekind (Typ) in Integer_Kind then
7533 Xnode := Make_Integer_Literal (Loc, Intval => 1);
7534 else
7535 Xnode := Make_Real_Literal (Loc, Ureal_1);
7536 end if;
7538 -- X ** 1 = X
7540 elsif Expv = 1 then
7541 Xnode := Base;
7543 -- X ** 2 = X * X
7545 elsif Expv = 2 then
7546 Xnode :=
7547 Make_Op_Multiply (Loc,
7548 Left_Opnd => Duplicate_Subexpr (Base),
7549 Right_Opnd => Duplicate_Subexpr_No_Checks (Base));
7551 -- X ** 3 = X * X * X
7553 elsif Expv = 3 then
7554 Xnode :=
7555 Make_Op_Multiply (Loc,
7556 Left_Opnd =>
7557 Make_Op_Multiply (Loc,
7558 Left_Opnd => Duplicate_Subexpr (Base),
7559 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)),
7560 Right_Opnd => Duplicate_Subexpr_No_Checks (Base));
7562 -- X ** 4 ->
7564 -- do
7565 -- En : constant base'type := base * base;
7566 -- in
7567 -- En * En
7569 else
7570 pragma Assert (Expv = 4);
7571 Temp := Make_Temporary (Loc, 'E', Base);
7573 Xnode :=
7574 Make_Expression_With_Actions (Loc,
7575 Actions => New_List (
7576 Make_Object_Declaration (Loc,
7577 Defining_Identifier => Temp,
7578 Constant_Present => True,
7579 Object_Definition => New_Occurrence_Of (Typ, Loc),
7580 Expression =>
7581 Make_Op_Multiply (Loc,
7582 Left_Opnd =>
7583 Duplicate_Subexpr (Base),
7584 Right_Opnd =>
7585 Duplicate_Subexpr_No_Checks (Base)))),
7587 Expression =>
7588 Make_Op_Multiply (Loc,
7589 Left_Opnd => New_Occurrence_Of (Temp, Loc),
7590 Right_Opnd => New_Occurrence_Of (Temp, Loc)));
7591 end if;
7593 Rewrite (N, Xnode);
7594 Analyze_And_Resolve (N, Typ);
7595 return;
7596 end if;
7597 end if;
7599 -- Case of (2 ** expression) appearing as an argument of an integer
7600 -- multiplication, or as the right argument of a division of a non-
7601 -- negative integer. In such cases we leave the node untouched, setting
7602 -- the flag Is_Natural_Power_Of_2_for_Shift set, then the expansion
7603 -- of the higher level node converts it into a shift.
7605 -- Another case is 2 ** N in any other context. We simply convert
7606 -- this to 1 * 2 ** N, and then the above transformation applies.
7608 -- Note: this transformation is not applicable for a modular type with
7609 -- a non-binary modulus in the multiplication case, since we get a wrong
7610 -- result if the shift causes an overflow before the modular reduction.
7612 -- Note: we used to check that Exptyp was an unsigned type. But that is
7613 -- an unnecessary check, since if Exp is negative, we have a run-time
7614 -- error that is either caught (so we get the right result) or we have
7615 -- suppressed the check, in which case the code is erroneous anyway.
7617 if Nkind (Base) = N_Integer_Literal
7618 and then CRT_Safe_Compile_Time_Known_Value (Base)
7619 and then Expr_Value (Base) = Uint_2
7620 and then Is_Integer_Type (Root_Type (Exptyp))
7621 and then Esize (Root_Type (Exptyp)) <= Esize (Standard_Integer)
7622 and then not Ovflo
7623 then
7624 -- First the multiply and divide cases
7626 if Nkind_In (Parent (N), N_Op_Divide, N_Op_Multiply) then
7627 declare
7628 P : constant Node_Id := Parent (N);
7629 L : constant Node_Id := Left_Opnd (P);
7630 R : constant Node_Id := Right_Opnd (P);
7632 begin
7633 if (Nkind (P) = N_Op_Multiply
7634 and then not Non_Binary_Modulus (Typ)
7635 and then
7636 ((Is_Integer_Type (Etype (L)) and then R = N)
7637 or else
7638 (Is_Integer_Type (Etype (R)) and then L = N))
7639 and then not Do_Overflow_Check (P))
7640 or else
7641 (Nkind (P) = N_Op_Divide
7642 and then Is_Integer_Type (Etype (L))
7643 and then Is_Unsigned_Type (Etype (L))
7644 and then R = N
7645 and then not Do_Overflow_Check (P))
7646 then
7647 Set_Is_Power_Of_2_For_Shift (N);
7648 return;
7649 end if;
7650 end;
7652 -- Now the other cases
7654 elsif not Non_Binary_Modulus (Typ) then
7655 Rewrite (N,
7656 Make_Op_Multiply (Loc,
7657 Left_Opnd => Make_Integer_Literal (Loc, 1),
7658 Right_Opnd => Relocate_Node (N)));
7659 Analyze_And_Resolve (N, Typ);
7660 return;
7661 end if;
7662 end if;
7664 -- Fall through if exponentiation must be done using a runtime routine
7666 -- First deal with modular case
7668 if Is_Modular_Integer_Type (Rtyp) then
7670 -- Non-binary case, we call the special exponentiation routine for
7671 -- the non-binary case, converting the argument to Long_Long_Integer
7672 -- and passing the modulus value. Then the result is converted back
7673 -- to the base type.
7675 if Non_Binary_Modulus (Rtyp) then
7676 Rewrite (N,
7677 Convert_To (Typ,
7678 Make_Function_Call (Loc,
7679 Name =>
7680 New_Occurrence_Of (RTE (RE_Exp_Modular), Loc),
7681 Parameter_Associations => New_List (
7682 Convert_To (RTE (RE_Unsigned), Base),
7683 Make_Integer_Literal (Loc, Modulus (Rtyp)),
7684 Exp))));
7686 -- Binary case, in this case, we call one of two routines, either the
7687 -- unsigned integer case, or the unsigned long long integer case,
7688 -- with a final "and" operation to do the required mod.
7690 else
7691 if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
7692 Ent := RTE (RE_Exp_Unsigned);
7693 else
7694 Ent := RTE (RE_Exp_Long_Long_Unsigned);
7695 end if;
7697 Rewrite (N,
7698 Convert_To (Typ,
7699 Make_Op_And (Loc,
7700 Left_Opnd =>
7701 Make_Function_Call (Loc,
7702 Name => New_Occurrence_Of (Ent, Loc),
7703 Parameter_Associations => New_List (
7704 Convert_To (Etype (First_Formal (Ent)), Base),
7705 Exp)),
7706 Right_Opnd =>
7707 Make_Integer_Literal (Loc, Modulus (Rtyp) - 1))));
7709 end if;
7711 -- Common exit point for modular type case
7713 Analyze_And_Resolve (N, Typ);
7714 return;
7716 -- Signed integer cases, done using either Integer or Long_Long_Integer.
7717 -- It is not worth having routines for Short_[Short_]Integer, since for
7718 -- most machines it would not help, and it would generate more code that
7719 -- might need certification when a certified run time is required.
7721 -- In the integer cases, we have two routines, one for when overflow
7722 -- checks are required, and one when they are not required, since there
7723 -- is a real gain in omitting checks on many machines.
7725 elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
7726 or else (Rtyp = Base_Type (Standard_Long_Integer)
7727 and then
7728 Esize (Standard_Long_Integer) > Esize (Standard_Integer))
7729 or else Rtyp = Universal_Integer
7730 then
7731 Etyp := Standard_Long_Long_Integer;
7733 -- Overflow checking is the only choice on the AAMP target, where
7734 -- arithmetic instructions check overflow automatically, so only
7735 -- one version of the exponentiation unit is needed.
7737 if Ovflo or AAMP_On_Target then
7738 Rent := RE_Exp_Long_Long_Integer;
7739 else
7740 Rent := RE_Exn_Long_Long_Integer;
7741 end if;
7743 elsif Is_Signed_Integer_Type (Rtyp) then
7744 Etyp := Standard_Integer;
7746 -- Overflow checking is the only choice on the AAMP target, where
7747 -- arithmetic instructions check overflow automatically, so only
7748 -- one version of the exponentiation unit is needed.
7750 if Ovflo or AAMP_On_Target then
7751 Rent := RE_Exp_Integer;
7752 else
7753 Rent := RE_Exn_Integer;
7754 end if;
7756 -- Floating-point cases, always done using Long_Long_Float. We do not
7757 -- need separate routines for the overflow case here, since in the case
7758 -- of floating-point, we generate infinities anyway as a rule (either
7759 -- that or we automatically trap overflow), and if there is an infinity
7760 -- generated and a range check is required, the check will fail anyway.
7762 else
7763 pragma Assert (Is_Floating_Point_Type (Rtyp));
7764 Etyp := Standard_Long_Long_Float;
7765 Rent := RE_Exn_Long_Long_Float;
7766 end if;
7768 -- Common processing for integer cases and floating-point cases.
7769 -- If we are in the right type, we can call runtime routine directly
7771 if Typ = Etyp
7772 and then Rtyp /= Universal_Integer
7773 and then Rtyp /= Universal_Real
7774 then
7775 Rewrite (N,
7776 Make_Function_Call (Loc,
7777 Name => New_Occurrence_Of (RTE (Rent), Loc),
7778 Parameter_Associations => New_List (Base, Exp)));
7780 -- Otherwise we have to introduce conversions (conversions are also
7781 -- required in the universal cases, since the runtime routine is
7782 -- typed using one of the standard types).
7784 else
7785 Rewrite (N,
7786 Convert_To (Typ,
7787 Make_Function_Call (Loc,
7788 Name => New_Occurrence_Of (RTE (Rent), Loc),
7789 Parameter_Associations => New_List (
7790 Convert_To (Etyp, Base),
7791 Exp))));
7792 end if;
7794 Analyze_And_Resolve (N, Typ);
7795 return;
7797 exception
7798 when RE_Not_Available =>
7799 return;
7800 end Expand_N_Op_Expon;
7802 --------------------
7803 -- Expand_N_Op_Ge --
7804 --------------------
7806 procedure Expand_N_Op_Ge (N : Node_Id) is
7807 Typ : constant Entity_Id := Etype (N);
7808 Op1 : constant Node_Id := Left_Opnd (N);
7809 Op2 : constant Node_Id := Right_Opnd (N);
7810 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
7812 begin
7813 Binary_Op_Validity_Checks (N);
7815 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7816 -- means we no longer have a comparison operation, we are all done.
7818 Expand_Compare_Minimize_Eliminate_Overflow (N);
7820 if Nkind (N) /= N_Op_Ge then
7821 return;
7822 end if;
7824 -- Array type case
7826 if Is_Array_Type (Typ1) then
7827 Expand_Array_Comparison (N);
7828 return;
7829 end if;
7831 -- Deal with boolean operands
7833 if Is_Boolean_Type (Typ1) then
7834 Adjust_Condition (Op1);
7835 Adjust_Condition (Op2);
7836 Set_Etype (N, Standard_Boolean);
7837 Adjust_Result_Type (N, Typ);
7838 end if;
7840 Rewrite_Comparison (N);
7842 Optimize_Length_Comparison (N);
7843 end Expand_N_Op_Ge;
7845 --------------------
7846 -- Expand_N_Op_Gt --
7847 --------------------
7849 procedure Expand_N_Op_Gt (N : Node_Id) is
7850 Typ : constant Entity_Id := Etype (N);
7851 Op1 : constant Node_Id := Left_Opnd (N);
7852 Op2 : constant Node_Id := Right_Opnd (N);
7853 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
7855 begin
7856 Binary_Op_Validity_Checks (N);
7858 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7859 -- means we no longer have a comparison operation, we are all done.
7861 Expand_Compare_Minimize_Eliminate_Overflow (N);
7863 if Nkind (N) /= N_Op_Gt then
7864 return;
7865 end if;
7867 -- Deal with array type operands
7869 if Is_Array_Type (Typ1) then
7870 Expand_Array_Comparison (N);
7871 return;
7872 end if;
7874 -- Deal with boolean type operands
7876 if Is_Boolean_Type (Typ1) then
7877 Adjust_Condition (Op1);
7878 Adjust_Condition (Op2);
7879 Set_Etype (N, Standard_Boolean);
7880 Adjust_Result_Type (N, Typ);
7881 end if;
7883 Rewrite_Comparison (N);
7885 Optimize_Length_Comparison (N);
7886 end Expand_N_Op_Gt;
7888 --------------------
7889 -- Expand_N_Op_Le --
7890 --------------------
7892 procedure Expand_N_Op_Le (N : Node_Id) is
7893 Typ : constant Entity_Id := Etype (N);
7894 Op1 : constant Node_Id := Left_Opnd (N);
7895 Op2 : constant Node_Id := Right_Opnd (N);
7896 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
7898 begin
7899 Binary_Op_Validity_Checks (N);
7901 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7902 -- means we no longer have a comparison operation, we are all done.
7904 Expand_Compare_Minimize_Eliminate_Overflow (N);
7906 if Nkind (N) /= N_Op_Le then
7907 return;
7908 end if;
7910 -- Deal with array type operands
7912 if Is_Array_Type (Typ1) then
7913 Expand_Array_Comparison (N);
7914 return;
7915 end if;
7917 -- Deal with Boolean type operands
7919 if Is_Boolean_Type (Typ1) then
7920 Adjust_Condition (Op1);
7921 Adjust_Condition (Op2);
7922 Set_Etype (N, Standard_Boolean);
7923 Adjust_Result_Type (N, Typ);
7924 end if;
7926 Rewrite_Comparison (N);
7928 Optimize_Length_Comparison (N);
7929 end Expand_N_Op_Le;
7931 --------------------
7932 -- Expand_N_Op_Lt --
7933 --------------------
7935 procedure Expand_N_Op_Lt (N : Node_Id) is
7936 Typ : constant Entity_Id := Etype (N);
7937 Op1 : constant Node_Id := Left_Opnd (N);
7938 Op2 : constant Node_Id := Right_Opnd (N);
7939 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
7941 begin
7942 Binary_Op_Validity_Checks (N);
7944 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7945 -- means we no longer have a comparison operation, we are all done.
7947 Expand_Compare_Minimize_Eliminate_Overflow (N);
7949 if Nkind (N) /= N_Op_Lt then
7950 return;
7951 end if;
7953 -- Deal with array type operands
7955 if Is_Array_Type (Typ1) then
7956 Expand_Array_Comparison (N);
7957 return;
7958 end if;
7960 -- Deal with Boolean type operands
7962 if Is_Boolean_Type (Typ1) then
7963 Adjust_Condition (Op1);
7964 Adjust_Condition (Op2);
7965 Set_Etype (N, Standard_Boolean);
7966 Adjust_Result_Type (N, Typ);
7967 end if;
7969 Rewrite_Comparison (N);
7971 Optimize_Length_Comparison (N);
7972 end Expand_N_Op_Lt;
7974 -----------------------
7975 -- Expand_N_Op_Minus --
7976 -----------------------
7978 procedure Expand_N_Op_Minus (N : Node_Id) is
7979 Loc : constant Source_Ptr := Sloc (N);
7980 Typ : constant Entity_Id := Etype (N);
7982 begin
7983 Unary_Op_Validity_Checks (N);
7985 -- Check for MINIMIZED/ELIMINATED overflow mode
7987 if Minimized_Eliminated_Overflow_Check (N) then
7988 Apply_Arithmetic_Overflow_Check (N);
7989 return;
7990 end if;
7992 if not Backend_Overflow_Checks_On_Target
7993 and then Is_Signed_Integer_Type (Etype (N))
7994 and then Do_Overflow_Check (N)
7995 then
7996 -- Software overflow checking expands -expr into (0 - expr)
7998 Rewrite (N,
7999 Make_Op_Subtract (Loc,
8000 Left_Opnd => Make_Integer_Literal (Loc, 0),
8001 Right_Opnd => Right_Opnd (N)));
8003 Analyze_And_Resolve (N, Typ);
8004 end if;
8005 end Expand_N_Op_Minus;
8007 ---------------------
8008 -- Expand_N_Op_Mod --
8009 ---------------------
8011 procedure Expand_N_Op_Mod (N : Node_Id) is
8012 Loc : constant Source_Ptr := Sloc (N);
8013 Typ : constant Entity_Id := Etype (N);
8014 DDC : constant Boolean := Do_Division_Check (N);
8016 Left : Node_Id;
8017 Right : Node_Id;
8019 LLB : Uint;
8020 Llo : Uint;
8021 Lhi : Uint;
8022 LOK : Boolean;
8023 Rlo : Uint;
8024 Rhi : Uint;
8025 ROK : Boolean;
8027 pragma Warnings (Off, Lhi);
8029 begin
8030 Binary_Op_Validity_Checks (N);
8032 -- Check for MINIMIZED/ELIMINATED overflow mode
8034 if Minimized_Eliminated_Overflow_Check (N) then
8035 Apply_Arithmetic_Overflow_Check (N);
8036 return;
8037 end if;
8039 if Is_Integer_Type (Etype (N)) then
8040 Apply_Divide_Checks (N);
8042 -- All done if we don't have a MOD any more, which can happen as a
8043 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
8045 if Nkind (N) /= N_Op_Mod then
8046 return;
8047 end if;
8048 end if;
8050 -- Proceed with expansion of mod operator
8052 Left := Left_Opnd (N);
8053 Right := Right_Opnd (N);
8055 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
8056 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
8058 -- Convert mod to rem if operands are both known to be non-negative, or
8059 -- both known to be non-positive (these are the cases in which rem and
8060 -- mod are the same, see (RM 4.5.5(28-30)). We do this since it is quite
8061 -- likely that this will improve the quality of code, (the operation now
8062 -- corresponds to the hardware remainder), and it does not seem likely
8063 -- that it could be harmful. It also avoids some cases of the elaborate
8064 -- expansion in Modify_Tree_For_C mode below (since Ada rem = C %).
8066 if (LOK and ROK)
8067 and then ((Llo >= 0 and then Rlo >= 0)
8068 or else
8069 (Lhi <= 0 and then Rhi <= 0))
8070 then
8071 Rewrite (N,
8072 Make_Op_Rem (Sloc (N),
8073 Left_Opnd => Left_Opnd (N),
8074 Right_Opnd => Right_Opnd (N)));
8076 -- Instead of reanalyzing the node we do the analysis manually. This
8077 -- avoids anomalies when the replacement is done in an instance and
8078 -- is epsilon more efficient.
8080 Set_Entity (N, Standard_Entity (S_Op_Rem));
8081 Set_Etype (N, Typ);
8082 Set_Do_Division_Check (N, DDC);
8083 Expand_N_Op_Rem (N);
8084 Set_Analyzed (N);
8085 return;
8087 -- Otherwise, normal mod processing
8089 else
8090 -- Apply optimization x mod 1 = 0. We don't really need that with
8091 -- gcc, but it is useful with other back ends (e.g. AAMP), and is
8092 -- certainly harmless.
8094 if Is_Integer_Type (Etype (N))
8095 and then Compile_Time_Known_Value (Right)
8096 and then Expr_Value (Right) = Uint_1
8097 then
8098 -- Call Remove_Side_Effects to ensure that any side effects in
8099 -- the ignored left operand (in particular function calls to
8100 -- user defined functions) are properly executed.
8102 Remove_Side_Effects (Left);
8104 Rewrite (N, Make_Integer_Literal (Loc, 0));
8105 Analyze_And_Resolve (N, Typ);
8106 return;
8107 end if;
8109 -- If we still have a mod operator and we are in Modify_Tree_For_C
8110 -- mode, and we have a signed integer type, then here is where we do
8111 -- the rewrite in terms of Rem. Note this rewrite bypasses the need
8112 -- for the special handling of the annoying case of largest negative
8113 -- number mod minus one.
8115 if Nkind (N) = N_Op_Mod
8116 and then Is_Signed_Integer_Type (Typ)
8117 and then Modify_Tree_For_C
8118 then
8119 -- In the general case, we expand A mod B as
8121 -- Tnn : constant typ := A rem B;
8122 -- ..
8123 -- (if (A >= 0) = (B >= 0) then Tnn
8124 -- elsif Tnn = 0 then 0
8125 -- else Tnn + B)
8127 -- The comparison can be written simply as A >= 0 if we know that
8128 -- B >= 0 which is a very common case.
8130 -- An important optimization is when B is known at compile time
8131 -- to be 2**K for some constant. In this case we can simply AND
8132 -- the left operand with the bit string 2**K-1 (i.e. K 1-bits)
8133 -- and that works for both the positive and negative cases.
8135 declare
8136 P2 : constant Nat := Power_Of_Two (Right);
8138 begin
8139 if P2 /= 0 then
8140 Rewrite (N,
8141 Unchecked_Convert_To (Typ,
8142 Make_Op_And (Loc,
8143 Left_Opnd =>
8144 Unchecked_Convert_To
8145 (Corresponding_Unsigned_Type (Typ), Left),
8146 Right_Opnd =>
8147 Make_Integer_Literal (Loc, 2 ** P2 - 1))));
8148 Analyze_And_Resolve (N, Typ);
8149 return;
8150 end if;
8151 end;
8153 -- Here for the full rewrite
8155 declare
8156 Tnn : constant Entity_Id := Make_Temporary (Sloc (N), 'T', N);
8157 Cmp : Node_Id;
8159 begin
8160 Cmp :=
8161 Make_Op_Ge (Loc,
8162 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
8163 Right_Opnd => Make_Integer_Literal (Loc, 0));
8165 if not LOK or else Rlo < 0 then
8166 Cmp :=
8167 Make_Op_Eq (Loc,
8168 Left_Opnd => Cmp,
8169 Right_Opnd =>
8170 Make_Op_Ge (Loc,
8171 Left_Opnd => Duplicate_Subexpr_No_Checks (Right),
8172 Right_Opnd => Make_Integer_Literal (Loc, 0)));
8173 end if;
8175 Insert_Action (N,
8176 Make_Object_Declaration (Loc,
8177 Defining_Identifier => Tnn,
8178 Constant_Present => True,
8179 Object_Definition => New_Occurrence_Of (Typ, Loc),
8180 Expression =>
8181 Make_Op_Rem (Loc,
8182 Left_Opnd => Left,
8183 Right_Opnd => Right)));
8185 Rewrite (N,
8186 Make_If_Expression (Loc,
8187 Expressions => New_List (
8188 Cmp,
8189 New_Occurrence_Of (Tnn, Loc),
8190 Make_If_Expression (Loc,
8191 Is_Elsif => True,
8192 Expressions => New_List (
8193 Make_Op_Eq (Loc,
8194 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8195 Right_Opnd => Make_Integer_Literal (Loc, 0)),
8196 Make_Integer_Literal (Loc, 0),
8197 Make_Op_Add (Loc,
8198 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8199 Right_Opnd =>
8200 Duplicate_Subexpr_No_Checks (Right)))))));
8202 Analyze_And_Resolve (N, Typ);
8203 return;
8204 end;
8205 end if;
8207 -- Deal with annoying case of largest negative number mod minus one.
8208 -- Gigi may not handle this case correctly, because on some targets,
8209 -- the mod value is computed using a divide instruction which gives
8210 -- an overflow trap for this case.
8212 -- It would be a bit more efficient to figure out which targets
8213 -- this is really needed for, but in practice it is reasonable
8214 -- to do the following special check in all cases, since it means
8215 -- we get a clearer message, and also the overhead is minimal given
8216 -- that division is expensive in any case.
8218 -- In fact the check is quite easy, if the right operand is -1, then
8219 -- the mod value is always 0, and we can just ignore the left operand
8220 -- completely in this case.
8222 -- This only applies if we still have a mod operator. Skip if we
8223 -- have already rewritten this (e.g. in the case of eliminated
8224 -- overflow checks which have driven us into bignum mode).
8226 if Nkind (N) = N_Op_Mod then
8228 -- The operand type may be private (e.g. in the expansion of an
8229 -- intrinsic operation) so we must use the underlying type to get
8230 -- the bounds, and convert the literals explicitly.
8232 LLB :=
8233 Expr_Value
8234 (Type_Low_Bound (Base_Type (Underlying_Type (Etype (Left)))));
8236 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
8237 and then ((not LOK) or else (Llo = LLB))
8238 then
8239 Rewrite (N,
8240 Make_If_Expression (Loc,
8241 Expressions => New_List (
8242 Make_Op_Eq (Loc,
8243 Left_Opnd => Duplicate_Subexpr (Right),
8244 Right_Opnd =>
8245 Unchecked_Convert_To (Typ,
8246 Make_Integer_Literal (Loc, -1))),
8247 Unchecked_Convert_To (Typ,
8248 Make_Integer_Literal (Loc, Uint_0)),
8249 Relocate_Node (N))));
8251 Set_Analyzed (Next (Next (First (Expressions (N)))));
8252 Analyze_And_Resolve (N, Typ);
8253 end if;
8254 end if;
8255 end if;
8256 end Expand_N_Op_Mod;
8258 --------------------------
8259 -- Expand_N_Op_Multiply --
8260 --------------------------
8262 procedure Expand_N_Op_Multiply (N : Node_Id) is
8263 Loc : constant Source_Ptr := Sloc (N);
8264 Lop : constant Node_Id := Left_Opnd (N);
8265 Rop : constant Node_Id := Right_Opnd (N);
8267 Lp2 : constant Boolean :=
8268 Nkind (Lop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Lop);
8269 Rp2 : constant Boolean :=
8270 Nkind (Rop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Rop);
8272 Ltyp : constant Entity_Id := Etype (Lop);
8273 Rtyp : constant Entity_Id := Etype (Rop);
8274 Typ : Entity_Id := Etype (N);
8276 begin
8277 Binary_Op_Validity_Checks (N);
8279 -- Check for MINIMIZED/ELIMINATED overflow mode
8281 if Minimized_Eliminated_Overflow_Check (N) then
8282 Apply_Arithmetic_Overflow_Check (N);
8283 return;
8284 end if;
8286 -- Special optimizations for integer types
8288 if Is_Integer_Type (Typ) then
8290 -- N * 0 = 0 for integer types
8292 if Compile_Time_Known_Value (Rop)
8293 and then Expr_Value (Rop) = Uint_0
8294 then
8295 -- Call Remove_Side_Effects to ensure that any side effects in
8296 -- the ignored left operand (in particular function calls to
8297 -- user defined functions) are properly executed.
8299 Remove_Side_Effects (Lop);
8301 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
8302 Analyze_And_Resolve (N, Typ);
8303 return;
8304 end if;
8306 -- Similar handling for 0 * N = 0
8308 if Compile_Time_Known_Value (Lop)
8309 and then Expr_Value (Lop) = Uint_0
8310 then
8311 Remove_Side_Effects (Rop);
8312 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
8313 Analyze_And_Resolve (N, Typ);
8314 return;
8315 end if;
8317 -- N * 1 = 1 * N = N for integer types
8319 -- This optimisation is not done if we are going to
8320 -- rewrite the product 1 * 2 ** N to a shift.
8322 if Compile_Time_Known_Value (Rop)
8323 and then Expr_Value (Rop) = Uint_1
8324 and then not Lp2
8325 then
8326 Rewrite (N, Lop);
8327 return;
8329 elsif Compile_Time_Known_Value (Lop)
8330 and then Expr_Value (Lop) = Uint_1
8331 and then not Rp2
8332 then
8333 Rewrite (N, Rop);
8334 return;
8335 end if;
8336 end if;
8338 -- Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
8339 -- Is_Power_Of_2_For_Shift is set means that we know that our left
8340 -- operand is an integer, as required for this to work.
8342 if Rp2 then
8343 if Lp2 then
8345 -- Convert 2 ** A * 2 ** B into 2 ** (A + B)
8347 Rewrite (N,
8348 Make_Op_Expon (Loc,
8349 Left_Opnd => Make_Integer_Literal (Loc, 2),
8350 Right_Opnd =>
8351 Make_Op_Add (Loc,
8352 Left_Opnd => Right_Opnd (Lop),
8353 Right_Opnd => Right_Opnd (Rop))));
8354 Analyze_And_Resolve (N, Typ);
8355 return;
8357 else
8358 -- If the result is modular, perform the reduction of the result
8359 -- appropriately.
8361 if Is_Modular_Integer_Type (Typ)
8362 and then not Non_Binary_Modulus (Typ)
8363 then
8364 Rewrite (N,
8365 Make_Op_And (Loc,
8366 Left_Opnd =>
8367 Make_Op_Shift_Left (Loc,
8368 Left_Opnd => Lop,
8369 Right_Opnd =>
8370 Convert_To (Standard_Natural, Right_Opnd (Rop))),
8371 Right_Opnd =>
8372 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
8374 else
8375 Rewrite (N,
8376 Make_Op_Shift_Left (Loc,
8377 Left_Opnd => Lop,
8378 Right_Opnd =>
8379 Convert_To (Standard_Natural, Right_Opnd (Rop))));
8380 end if;
8382 Analyze_And_Resolve (N, Typ);
8383 return;
8384 end if;
8386 -- Same processing for the operands the other way round
8388 elsif Lp2 then
8389 if Is_Modular_Integer_Type (Typ)
8390 and then not Non_Binary_Modulus (Typ)
8391 then
8392 Rewrite (N,
8393 Make_Op_And (Loc,
8394 Left_Opnd =>
8395 Make_Op_Shift_Left (Loc,
8396 Left_Opnd => Rop,
8397 Right_Opnd =>
8398 Convert_To (Standard_Natural, Right_Opnd (Lop))),
8399 Right_Opnd =>
8400 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
8402 else
8403 Rewrite (N,
8404 Make_Op_Shift_Left (Loc,
8405 Left_Opnd => Rop,
8406 Right_Opnd =>
8407 Convert_To (Standard_Natural, Right_Opnd (Lop))));
8408 end if;
8410 Analyze_And_Resolve (N, Typ);
8411 return;
8412 end if;
8414 -- Do required fixup of universal fixed operation
8416 if Typ = Universal_Fixed then
8417 Fixup_Universal_Fixed_Operation (N);
8418 Typ := Etype (N);
8419 end if;
8421 -- Multiplications with fixed-point results
8423 if Is_Fixed_Point_Type (Typ) then
8425 -- No special processing if Treat_Fixed_As_Integer is set, since from
8426 -- a semantic point of view such operations are simply integer
8427 -- operations and will be treated that way.
8429 if not Treat_Fixed_As_Integer (N) then
8431 -- Case of fixed * integer => fixed
8433 if Is_Integer_Type (Rtyp) then
8434 Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N);
8436 -- Case of integer * fixed => fixed
8438 elsif Is_Integer_Type (Ltyp) then
8439 Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N);
8441 -- Case of fixed * fixed => fixed
8443 else
8444 Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N);
8445 end if;
8446 end if;
8448 -- Other cases of multiplication of fixed-point operands. Again we
8449 -- exclude the cases where Treat_Fixed_As_Integer flag is set.
8451 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
8452 and then not Treat_Fixed_As_Integer (N)
8453 then
8454 if Is_Integer_Type (Typ) then
8455 Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N);
8456 else
8457 pragma Assert (Is_Floating_Point_Type (Typ));
8458 Expand_Multiply_Fixed_By_Fixed_Giving_Float (N);
8459 end if;
8461 -- Mixed-mode operations can appear in a non-static universal context,
8462 -- in which case the integer argument must be converted explicitly.
8464 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
8465 Rewrite (Rop, Convert_To (Universal_Real, Relocate_Node (Rop)));
8466 Analyze_And_Resolve (Rop, Universal_Real);
8468 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
8469 Rewrite (Lop, Convert_To (Universal_Real, Relocate_Node (Lop)));
8470 Analyze_And_Resolve (Lop, Universal_Real);
8472 -- Non-fixed point cases, check software overflow checking required
8474 elsif Is_Signed_Integer_Type (Etype (N)) then
8475 Apply_Arithmetic_Overflow_Check (N);
8476 end if;
8478 -- Overflow checks for floating-point if -gnateF mode active
8480 Check_Float_Op_Overflow (N);
8481 end Expand_N_Op_Multiply;
8483 --------------------
8484 -- Expand_N_Op_Ne --
8485 --------------------
8487 procedure Expand_N_Op_Ne (N : Node_Id) is
8488 Typ : constant Entity_Id := Etype (Left_Opnd (N));
8490 begin
8491 -- Case of elementary type with standard operator
8493 if Is_Elementary_Type (Typ)
8494 and then Sloc (Entity (N)) = Standard_Location
8495 then
8496 Binary_Op_Validity_Checks (N);
8498 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if
8499 -- means we no longer have a /= operation, we are all done.
8501 Expand_Compare_Minimize_Eliminate_Overflow (N);
8503 if Nkind (N) /= N_Op_Ne then
8504 return;
8505 end if;
8507 -- Boolean types (requiring handling of non-standard case)
8509 if Is_Boolean_Type (Typ) then
8510 Adjust_Condition (Left_Opnd (N));
8511 Adjust_Condition (Right_Opnd (N));
8512 Set_Etype (N, Standard_Boolean);
8513 Adjust_Result_Type (N, Typ);
8514 end if;
8516 Rewrite_Comparison (N);
8518 -- For all cases other than elementary types, we rewrite node as the
8519 -- negation of an equality operation, and reanalyze. The equality to be
8520 -- used is defined in the same scope and has the same signature. This
8521 -- signature must be set explicitly since in an instance it may not have
8522 -- the same visibility as in the generic unit. This avoids duplicating
8523 -- or factoring the complex code for record/array equality tests etc.
8525 else
8526 declare
8527 Loc : constant Source_Ptr := Sloc (N);
8528 Neg : Node_Id;
8529 Ne : constant Entity_Id := Entity (N);
8531 begin
8532 Binary_Op_Validity_Checks (N);
8534 Neg :=
8535 Make_Op_Not (Loc,
8536 Right_Opnd =>
8537 Make_Op_Eq (Loc,
8538 Left_Opnd => Left_Opnd (N),
8539 Right_Opnd => Right_Opnd (N)));
8540 Set_Paren_Count (Right_Opnd (Neg), 1);
8542 if Scope (Ne) /= Standard_Standard then
8543 Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
8544 end if;
8546 -- For navigation purposes, we want to treat the inequality as an
8547 -- implicit reference to the corresponding equality. Preserve the
8548 -- Comes_From_ source flag to generate proper Xref entries.
8550 Preserve_Comes_From_Source (Neg, N);
8551 Preserve_Comes_From_Source (Right_Opnd (Neg), N);
8552 Rewrite (N, Neg);
8553 Analyze_And_Resolve (N, Standard_Boolean);
8554 end;
8555 end if;
8557 Optimize_Length_Comparison (N);
8558 end Expand_N_Op_Ne;
8560 ---------------------
8561 -- Expand_N_Op_Not --
8562 ---------------------
8564 -- If the argument is other than a Boolean array type, there is no special
8565 -- expansion required, except for dealing with validity checks, and non-
8566 -- standard boolean representations.
8568 -- For the packed array case, we call the special routine in Exp_Pakd,
8569 -- except that if the component size is greater than one, we use the
8570 -- standard routine generating a gruesome loop (it is so peculiar to have
8571 -- packed arrays with non-standard Boolean representations anyway, so it
8572 -- does not matter that we do not handle this case efficiently).
8574 -- For the unpacked array case (and for the special packed case where we
8575 -- have non standard Booleans, as discussed above), we generate and insert
8576 -- into the tree the following function definition:
8578 -- function Nnnn (A : arr) is
8579 -- B : arr;
8580 -- begin
8581 -- for J in a'range loop
8582 -- B (J) := not A (J);
8583 -- end loop;
8584 -- return B;
8585 -- end Nnnn;
8587 -- Here arr is the actual subtype of the parameter (and hence always
8588 -- constrained). Then we replace the not with a call to this function.
8590 procedure Expand_N_Op_Not (N : Node_Id) is
8591 Loc : constant Source_Ptr := Sloc (N);
8592 Typ : constant Entity_Id := Etype (N);
8593 Opnd : Node_Id;
8594 Arr : Entity_Id;
8595 A : Entity_Id;
8596 B : Entity_Id;
8597 J : Entity_Id;
8598 A_J : Node_Id;
8599 B_J : Node_Id;
8601 Func_Name : Entity_Id;
8602 Loop_Statement : Node_Id;
8604 begin
8605 Unary_Op_Validity_Checks (N);
8607 -- For boolean operand, deal with non-standard booleans
8609 if Is_Boolean_Type (Typ) then
8610 Adjust_Condition (Right_Opnd (N));
8611 Set_Etype (N, Standard_Boolean);
8612 Adjust_Result_Type (N, Typ);
8613 return;
8614 end if;
8616 -- Only array types need any other processing
8618 if not Is_Array_Type (Typ) then
8619 return;
8620 end if;
8622 -- Case of array operand. If bit packed with a component size of 1,
8623 -- handle it in Exp_Pakd if the operand is known to be aligned.
8625 if Is_Bit_Packed_Array (Typ)
8626 and then Component_Size (Typ) = 1
8627 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
8628 then
8629 Expand_Packed_Not (N);
8630 return;
8631 end if;
8633 -- Case of array operand which is not bit-packed. If the context is
8634 -- a safe assignment, call in-place operation, If context is a larger
8635 -- boolean expression in the context of a safe assignment, expansion is
8636 -- done by enclosing operation.
8638 Opnd := Relocate_Node (Right_Opnd (N));
8639 Convert_To_Actual_Subtype (Opnd);
8640 Arr := Etype (Opnd);
8641 Ensure_Defined (Arr, N);
8642 Silly_Boolean_Array_Not_Test (N, Arr);
8644 if Nkind (Parent (N)) = N_Assignment_Statement then
8645 if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
8646 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
8647 return;
8649 -- Special case the negation of a binary operation
8651 elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
8652 and then Safe_In_Place_Array_Op
8653 (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
8654 then
8655 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
8656 return;
8657 end if;
8659 elsif Nkind (Parent (N)) in N_Binary_Op
8660 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
8661 then
8662 declare
8663 Op1 : constant Node_Id := Left_Opnd (Parent (N));
8664 Op2 : constant Node_Id := Right_Opnd (Parent (N));
8665 Lhs : constant Node_Id := Name (Parent (Parent (N)));
8667 begin
8668 if Safe_In_Place_Array_Op (Lhs, Op1, Op2) then
8670 -- (not A) op (not B) can be reduced to a single call
8672 if N = Op1 and then Nkind (Op2) = N_Op_Not then
8673 return;
8675 elsif N = Op2 and then Nkind (Op1) = N_Op_Not then
8676 return;
8678 -- A xor (not B) can also be special-cased
8680 elsif N = Op2 and then Nkind (Parent (N)) = N_Op_Xor then
8681 return;
8682 end if;
8683 end if;
8684 end;
8685 end if;
8687 A := Make_Defining_Identifier (Loc, Name_uA);
8688 B := Make_Defining_Identifier (Loc, Name_uB);
8689 J := Make_Defining_Identifier (Loc, Name_uJ);
8691 A_J :=
8692 Make_Indexed_Component (Loc,
8693 Prefix => New_Occurrence_Of (A, Loc),
8694 Expressions => New_List (New_Occurrence_Of (J, Loc)));
8696 B_J :=
8697 Make_Indexed_Component (Loc,
8698 Prefix => New_Occurrence_Of (B, Loc),
8699 Expressions => New_List (New_Occurrence_Of (J, Loc)));
8701 Loop_Statement :=
8702 Make_Implicit_Loop_Statement (N,
8703 Identifier => Empty,
8705 Iteration_Scheme =>
8706 Make_Iteration_Scheme (Loc,
8707 Loop_Parameter_Specification =>
8708 Make_Loop_Parameter_Specification (Loc,
8709 Defining_Identifier => J,
8710 Discrete_Subtype_Definition =>
8711 Make_Attribute_Reference (Loc,
8712 Prefix => Make_Identifier (Loc, Chars (A)),
8713 Attribute_Name => Name_Range))),
8715 Statements => New_List (
8716 Make_Assignment_Statement (Loc,
8717 Name => B_J,
8718 Expression => Make_Op_Not (Loc, A_J))));
8720 Func_Name := Make_Temporary (Loc, 'N');
8721 Set_Is_Inlined (Func_Name);
8723 Insert_Action (N,
8724 Make_Subprogram_Body (Loc,
8725 Specification =>
8726 Make_Function_Specification (Loc,
8727 Defining_Unit_Name => Func_Name,
8728 Parameter_Specifications => New_List (
8729 Make_Parameter_Specification (Loc,
8730 Defining_Identifier => A,
8731 Parameter_Type => New_Occurrence_Of (Typ, Loc))),
8732 Result_Definition => New_Occurrence_Of (Typ, Loc)),
8734 Declarations => New_List (
8735 Make_Object_Declaration (Loc,
8736 Defining_Identifier => B,
8737 Object_Definition => New_Occurrence_Of (Arr, Loc))),
8739 Handled_Statement_Sequence =>
8740 Make_Handled_Sequence_Of_Statements (Loc,
8741 Statements => New_List (
8742 Loop_Statement,
8743 Make_Simple_Return_Statement (Loc,
8744 Expression => Make_Identifier (Loc, Chars (B)))))));
8746 Rewrite (N,
8747 Make_Function_Call (Loc,
8748 Name => New_Occurrence_Of (Func_Name, Loc),
8749 Parameter_Associations => New_List (Opnd)));
8751 Analyze_And_Resolve (N, Typ);
8752 end Expand_N_Op_Not;
8754 --------------------
8755 -- Expand_N_Op_Or --
8756 --------------------
8758 procedure Expand_N_Op_Or (N : Node_Id) is
8759 Typ : constant Entity_Id := Etype (N);
8761 begin
8762 Binary_Op_Validity_Checks (N);
8764 if Is_Array_Type (Etype (N)) then
8765 Expand_Boolean_Operator (N);
8767 elsif Is_Boolean_Type (Etype (N)) then
8768 Adjust_Condition (Left_Opnd (N));
8769 Adjust_Condition (Right_Opnd (N));
8770 Set_Etype (N, Standard_Boolean);
8771 Adjust_Result_Type (N, Typ);
8773 elsif Is_Intrinsic_Subprogram (Entity (N)) then
8774 Expand_Intrinsic_Call (N, Entity (N));
8776 end if;
8777 end Expand_N_Op_Or;
8779 ----------------------
8780 -- Expand_N_Op_Plus --
8781 ----------------------
8783 procedure Expand_N_Op_Plus (N : Node_Id) is
8784 begin
8785 Unary_Op_Validity_Checks (N);
8787 -- Check for MINIMIZED/ELIMINATED overflow mode
8789 if Minimized_Eliminated_Overflow_Check (N) then
8790 Apply_Arithmetic_Overflow_Check (N);
8791 return;
8792 end if;
8793 end Expand_N_Op_Plus;
8795 ---------------------
8796 -- Expand_N_Op_Rem --
8797 ---------------------
8799 procedure Expand_N_Op_Rem (N : Node_Id) is
8800 Loc : constant Source_Ptr := Sloc (N);
8801 Typ : constant Entity_Id := Etype (N);
8803 Left : Node_Id;
8804 Right : Node_Id;
8806 Lo : Uint;
8807 Hi : Uint;
8808 OK : Boolean;
8810 Lneg : Boolean;
8811 Rneg : Boolean;
8812 -- Set if corresponding operand can be negative
8814 pragma Unreferenced (Hi);
8816 begin
8817 Binary_Op_Validity_Checks (N);
8819 -- Check for MINIMIZED/ELIMINATED overflow mode
8821 if Minimized_Eliminated_Overflow_Check (N) then
8822 Apply_Arithmetic_Overflow_Check (N);
8823 return;
8824 end if;
8826 if Is_Integer_Type (Etype (N)) then
8827 Apply_Divide_Checks (N);
8829 -- All done if we don't have a REM any more, which can happen as a
8830 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
8832 if Nkind (N) /= N_Op_Rem then
8833 return;
8834 end if;
8835 end if;
8837 -- Proceed with expansion of REM
8839 Left := Left_Opnd (N);
8840 Right := Right_Opnd (N);
8842 -- Apply optimization x rem 1 = 0. We don't really need that with gcc,
8843 -- but it is useful with other back ends (e.g. AAMP), and is certainly
8844 -- harmless.
8846 if Is_Integer_Type (Etype (N))
8847 and then Compile_Time_Known_Value (Right)
8848 and then Expr_Value (Right) = Uint_1
8849 then
8850 -- Call Remove_Side_Effects to ensure that any side effects in the
8851 -- ignored left operand (in particular function calls to user defined
8852 -- functions) are properly executed.
8854 Remove_Side_Effects (Left);
8856 Rewrite (N, Make_Integer_Literal (Loc, 0));
8857 Analyze_And_Resolve (N, Typ);
8858 return;
8859 end if;
8861 -- Deal with annoying case of largest negative number remainder minus
8862 -- one. Gigi may not handle this case correctly, because on some
8863 -- targets, the mod value is computed using a divide instruction
8864 -- which gives an overflow trap for this case.
8866 -- It would be a bit more efficient to figure out which targets this
8867 -- is really needed for, but in practice it is reasonable to do the
8868 -- following special check in all cases, since it means we get a clearer
8869 -- message, and also the overhead is minimal given that division is
8870 -- expensive in any case.
8872 -- In fact the check is quite easy, if the right operand is -1, then
8873 -- the remainder is always 0, and we can just ignore the left operand
8874 -- completely in this case.
8876 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
8877 Lneg := (not OK) or else Lo < 0;
8879 Determine_Range (Left, OK, Lo, Hi, Assume_Valid => True);
8880 Rneg := (not OK) or else Lo < 0;
8882 -- We won't mess with trying to find out if the left operand can really
8883 -- be the largest negative number (that's a pain in the case of private
8884 -- types and this is really marginal). We will just assume that we need
8885 -- the test if the left operand can be negative at all.
8887 if Lneg and Rneg then
8888 Rewrite (N,
8889 Make_If_Expression (Loc,
8890 Expressions => New_List (
8891 Make_Op_Eq (Loc,
8892 Left_Opnd => Duplicate_Subexpr (Right),
8893 Right_Opnd =>
8894 Unchecked_Convert_To (Typ, Make_Integer_Literal (Loc, -1))),
8896 Unchecked_Convert_To (Typ,
8897 Make_Integer_Literal (Loc, Uint_0)),
8899 Relocate_Node (N))));
8901 Set_Analyzed (Next (Next (First (Expressions (N)))));
8902 Analyze_And_Resolve (N, Typ);
8903 end if;
8904 end Expand_N_Op_Rem;
8906 -----------------------------
8907 -- Expand_N_Op_Rotate_Left --
8908 -----------------------------
8910 procedure Expand_N_Op_Rotate_Left (N : Node_Id) is
8911 begin
8912 Binary_Op_Validity_Checks (N);
8914 -- If we are in Modify_Tree_For_C mode, there is no rotate left in C,
8915 -- so we rewrite in terms of logical shifts
8917 -- Shift_Left (Num, Bits) or Shift_Right (num, Esize - Bits)
8919 -- where Bits is the shift count mod Esize (the mod operation here
8920 -- deals with ludicrous large shift counts, which are apparently OK).
8922 -- What about non-binary modulus ???
8924 declare
8925 Loc : constant Source_Ptr := Sloc (N);
8926 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
8927 Typ : constant Entity_Id := Etype (N);
8929 begin
8930 if Modify_Tree_For_C then
8931 Rewrite (Right_Opnd (N),
8932 Make_Op_Rem (Loc,
8933 Left_Opnd => Relocate_Node (Right_Opnd (N)),
8934 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
8936 Analyze_And_Resolve (Right_Opnd (N), Rtp);
8938 Rewrite (N,
8939 Make_Op_Or (Loc,
8940 Left_Opnd =>
8941 Make_Op_Shift_Left (Loc,
8942 Left_Opnd => Left_Opnd (N),
8943 Right_Opnd => Right_Opnd (N)),
8945 Right_Opnd =>
8946 Make_Op_Shift_Right (Loc,
8947 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
8948 Right_Opnd =>
8949 Make_Op_Subtract (Loc,
8950 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
8951 Right_Opnd =>
8952 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
8954 Analyze_And_Resolve (N, Typ);
8955 end if;
8956 end;
8957 end Expand_N_Op_Rotate_Left;
8959 ------------------------------
8960 -- Expand_N_Op_Rotate_Right --
8961 ------------------------------
8963 procedure Expand_N_Op_Rotate_Right (N : Node_Id) is
8964 begin
8965 Binary_Op_Validity_Checks (N);
8967 -- If we are in Modify_Tree_For_C mode, there is no rotate right in C,
8968 -- so we rewrite in terms of logical shifts
8970 -- Shift_Right (Num, Bits) or Shift_Left (num, Esize - Bits)
8972 -- where Bits is the shift count mod Esize (the mod operation here
8973 -- deals with ludicrous large shift counts, which are apparently OK).
8975 -- What about non-binary modulus ???
8977 declare
8978 Loc : constant Source_Ptr := Sloc (N);
8979 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
8980 Typ : constant Entity_Id := Etype (N);
8982 begin
8983 Rewrite (Right_Opnd (N),
8984 Make_Op_Rem (Loc,
8985 Left_Opnd => Relocate_Node (Right_Opnd (N)),
8986 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
8988 Analyze_And_Resolve (Right_Opnd (N), Rtp);
8990 if Modify_Tree_For_C then
8991 Rewrite (N,
8992 Make_Op_Or (Loc,
8993 Left_Opnd =>
8994 Make_Op_Shift_Right (Loc,
8995 Left_Opnd => Left_Opnd (N),
8996 Right_Opnd => Right_Opnd (N)),
8998 Right_Opnd =>
8999 Make_Op_Shift_Left (Loc,
9000 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9001 Right_Opnd =>
9002 Make_Op_Subtract (Loc,
9003 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9004 Right_Opnd =>
9005 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9007 Analyze_And_Resolve (N, Typ);
9008 end if;
9009 end;
9010 end Expand_N_Op_Rotate_Right;
9012 ----------------------------
9013 -- Expand_N_Op_Shift_Left --
9014 ----------------------------
9016 -- Note: nothing in this routine depends on left as opposed to right shifts
9017 -- so we share the routine for expanding shift right operations.
9019 procedure Expand_N_Op_Shift_Left (N : Node_Id) is
9020 begin
9021 Binary_Op_Validity_Checks (N);
9023 -- If we are in Modify_Tree_For_C mode, then ensure that the right
9024 -- operand is not greater than the word size (since that would not
9025 -- be defined properly by the corresponding C shift operator).
9027 if Modify_Tree_For_C then
9028 declare
9029 Right : constant Node_Id := Right_Opnd (N);
9030 Loc : constant Source_Ptr := Sloc (Right);
9031 Typ : constant Entity_Id := Etype (N);
9032 Siz : constant Uint := Esize (Typ);
9033 Orig : Node_Id;
9034 OK : Boolean;
9035 Lo : Uint;
9036 Hi : Uint;
9038 begin
9039 if Compile_Time_Known_Value (Right) then
9040 if Expr_Value (Right) >= Siz then
9041 Rewrite (N, Make_Integer_Literal (Loc, 0));
9042 Analyze_And_Resolve (N, Typ);
9043 end if;
9045 -- Not compile time known, find range
9047 else
9048 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9050 -- Nothing to do if known to be OK range, otherwise expand
9052 if not OK or else Hi >= Siz then
9054 -- Prevent recursion on copy of shift node
9056 Orig := Relocate_Node (N);
9057 Set_Analyzed (Orig);
9059 -- Now do the rewrite
9061 Rewrite (N,
9062 Make_If_Expression (Loc,
9063 Expressions => New_List (
9064 Make_Op_Ge (Loc,
9065 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
9066 Right_Opnd => Make_Integer_Literal (Loc, Siz)),
9067 Make_Integer_Literal (Loc, 0),
9068 Orig)));
9069 Analyze_And_Resolve (N, Typ);
9070 end if;
9071 end if;
9072 end;
9073 end if;
9074 end Expand_N_Op_Shift_Left;
9076 -----------------------------
9077 -- Expand_N_Op_Shift_Right --
9078 -----------------------------
9080 procedure Expand_N_Op_Shift_Right (N : Node_Id) is
9081 begin
9082 -- Share shift left circuit
9084 Expand_N_Op_Shift_Left (N);
9085 end Expand_N_Op_Shift_Right;
9087 ----------------------------------------
9088 -- Expand_N_Op_Shift_Right_Arithmetic --
9089 ----------------------------------------
9091 procedure Expand_N_Op_Shift_Right_Arithmetic (N : Node_Id) is
9092 begin
9093 Binary_Op_Validity_Checks (N);
9095 -- If we are in Modify_Tree_For_C mode, there is no shift right
9096 -- arithmetic in C, so we rewrite in terms of logical shifts.
9098 -- Shift_Right (Num, Bits) or
9099 -- (if Num >= Sign
9100 -- then not (Shift_Right (Mask, bits))
9101 -- else 0)
9103 -- Here Mask is all 1 bits (2**size - 1), and Sign is 2**(size - 1)
9105 -- Note: in almost all C compilers it would work to just shift a
9106 -- signed integer right, but it's undefined and we cannot rely on it.
9108 -- Note: the above works fine for shift counts greater than or equal
9109 -- to the word size, since in this case (not (Shift_Right (Mask, bits)))
9110 -- generates all 1'bits.
9112 -- What about non-binary modulus ???
9114 declare
9115 Loc : constant Source_Ptr := Sloc (N);
9116 Typ : constant Entity_Id := Etype (N);
9117 Sign : constant Uint := 2 ** (Esize (Typ) - 1);
9118 Mask : constant Uint := (2 ** Esize (Typ)) - 1;
9119 Left : constant Node_Id := Left_Opnd (N);
9120 Right : constant Node_Id := Right_Opnd (N);
9121 Maskx : Node_Id;
9123 begin
9124 if Modify_Tree_For_C then
9126 -- Here if not (Shift_Right (Mask, bits)) can be computed at
9127 -- compile time as a single constant.
9129 if Compile_Time_Known_Value (Right) then
9130 declare
9131 Val : constant Uint := Expr_Value (Right);
9133 begin
9134 if Val >= Esize (Typ) then
9135 Maskx := Make_Integer_Literal (Loc, Mask);
9137 else
9138 Maskx :=
9139 Make_Integer_Literal (Loc,
9140 Intval => Mask - (Mask / (2 ** Expr_Value (Right))));
9141 end if;
9142 end;
9144 else
9145 Maskx :=
9146 Make_Op_Not (Loc,
9147 Right_Opnd =>
9148 Make_Op_Shift_Right (Loc,
9149 Left_Opnd => Make_Integer_Literal (Loc, Mask),
9150 Right_Opnd => Duplicate_Subexpr_No_Checks (Right)));
9151 end if;
9153 -- Now do the rewrite
9155 Rewrite (N,
9156 Make_Op_Or (Loc,
9157 Left_Opnd =>
9158 Make_Op_Shift_Right (Loc,
9159 Left_Opnd => Left,
9160 Right_Opnd => Right),
9161 Right_Opnd =>
9162 Make_If_Expression (Loc,
9163 Expressions => New_List (
9164 Make_Op_Ge (Loc,
9165 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
9166 Right_Opnd => Make_Integer_Literal (Loc, Sign)),
9167 Maskx,
9168 Make_Integer_Literal (Loc, 0)))));
9169 Analyze_And_Resolve (N, Typ);
9170 end if;
9171 end;
9172 end Expand_N_Op_Shift_Right_Arithmetic;
9174 --------------------------
9175 -- Expand_N_Op_Subtract --
9176 --------------------------
9178 procedure Expand_N_Op_Subtract (N : Node_Id) is
9179 Typ : constant Entity_Id := Etype (N);
9181 begin
9182 Binary_Op_Validity_Checks (N);
9184 -- Check for MINIMIZED/ELIMINATED overflow mode
9186 if Minimized_Eliminated_Overflow_Check (N) then
9187 Apply_Arithmetic_Overflow_Check (N);
9188 return;
9189 end if;
9191 -- N - 0 = N for integer types
9193 if Is_Integer_Type (Typ)
9194 and then Compile_Time_Known_Value (Right_Opnd (N))
9195 and then Expr_Value (Right_Opnd (N)) = 0
9196 then
9197 Rewrite (N, Left_Opnd (N));
9198 return;
9199 end if;
9201 -- Arithmetic overflow checks for signed integer/fixed point types
9203 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
9204 Apply_Arithmetic_Overflow_Check (N);
9205 end if;
9207 -- Overflow checks for floating-point if -gnateF mode active
9209 Check_Float_Op_Overflow (N);
9210 end Expand_N_Op_Subtract;
9212 ---------------------
9213 -- Expand_N_Op_Xor --
9214 ---------------------
9216 procedure Expand_N_Op_Xor (N : Node_Id) is
9217 Typ : constant Entity_Id := Etype (N);
9219 begin
9220 Binary_Op_Validity_Checks (N);
9222 if Is_Array_Type (Etype (N)) then
9223 Expand_Boolean_Operator (N);
9225 elsif Is_Boolean_Type (Etype (N)) then
9226 Adjust_Condition (Left_Opnd (N));
9227 Adjust_Condition (Right_Opnd (N));
9228 Set_Etype (N, Standard_Boolean);
9229 Adjust_Result_Type (N, Typ);
9231 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9232 Expand_Intrinsic_Call (N, Entity (N));
9234 end if;
9235 end Expand_N_Op_Xor;
9237 ----------------------
9238 -- Expand_N_Or_Else --
9239 ----------------------
9241 procedure Expand_N_Or_Else (N : Node_Id)
9242 renames Expand_Short_Circuit_Operator;
9244 -----------------------------------
9245 -- Expand_N_Qualified_Expression --
9246 -----------------------------------
9248 procedure Expand_N_Qualified_Expression (N : Node_Id) is
9249 Operand : constant Node_Id := Expression (N);
9250 Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
9252 begin
9253 -- Do validity check if validity checking operands
9255 if Validity_Checks_On and Validity_Check_Operands then
9256 Ensure_Valid (Operand);
9257 end if;
9259 -- Apply possible constraint check
9261 Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
9263 if Do_Range_Check (Operand) then
9264 Set_Do_Range_Check (Operand, False);
9265 Generate_Range_Check (Operand, Target_Type, CE_Range_Check_Failed);
9266 end if;
9267 end Expand_N_Qualified_Expression;
9269 ------------------------------------
9270 -- Expand_N_Quantified_Expression --
9271 ------------------------------------
9273 -- We expand:
9275 -- for all X in range => Cond
9277 -- into:
9279 -- T := True;
9280 -- for X in range loop
9281 -- if not Cond then
9282 -- T := False;
9283 -- exit;
9284 -- end if;
9285 -- end loop;
9287 -- Similarly, an existentially quantified expression:
9289 -- for some X in range => Cond
9291 -- becomes:
9293 -- T := False;
9294 -- for X in range loop
9295 -- if Cond then
9296 -- T := True;
9297 -- exit;
9298 -- end if;
9299 -- end loop;
9301 -- In both cases, the iteration may be over a container in which case it is
9302 -- given by an iterator specification, not a loop parameter specification.
9304 procedure Expand_N_Quantified_Expression (N : Node_Id) is
9305 Actions : constant List_Id := New_List;
9306 For_All : constant Boolean := All_Present (N);
9307 Iter_Spec : constant Node_Id := Iterator_Specification (N);
9308 Loc : constant Source_Ptr := Sloc (N);
9309 Loop_Spec : constant Node_Id := Loop_Parameter_Specification (N);
9310 Cond : Node_Id;
9311 Flag : Entity_Id;
9312 Scheme : Node_Id;
9313 Stmts : List_Id;
9315 begin
9316 -- Create the declaration of the flag which tracks the status of the
9317 -- quantified expression. Generate:
9319 -- Flag : Boolean := (True | False);
9321 Flag := Make_Temporary (Loc, 'T', N);
9323 Append_To (Actions,
9324 Make_Object_Declaration (Loc,
9325 Defining_Identifier => Flag,
9326 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
9327 Expression =>
9328 New_Occurrence_Of (Boolean_Literals (For_All), Loc)));
9330 -- Construct the circuitry which tracks the status of the quantified
9331 -- expression. Generate:
9333 -- if [not] Cond then
9334 -- Flag := (False | True);
9335 -- exit;
9336 -- end if;
9338 Cond := Relocate_Node (Condition (N));
9340 if For_All then
9341 Cond := Make_Op_Not (Loc, Cond);
9342 end if;
9344 Stmts := New_List (
9345 Make_Implicit_If_Statement (N,
9346 Condition => Cond,
9347 Then_Statements => New_List (
9348 Make_Assignment_Statement (Loc,
9349 Name => New_Occurrence_Of (Flag, Loc),
9350 Expression =>
9351 New_Occurrence_Of (Boolean_Literals (not For_All), Loc)),
9352 Make_Exit_Statement (Loc))));
9354 -- Build the loop equivalent of the quantified expression
9356 if Present (Iter_Spec) then
9357 Scheme :=
9358 Make_Iteration_Scheme (Loc,
9359 Iterator_Specification => Iter_Spec);
9360 else
9361 Scheme :=
9362 Make_Iteration_Scheme (Loc,
9363 Loop_Parameter_Specification => Loop_Spec);
9364 end if;
9366 Append_To (Actions,
9367 Make_Loop_Statement (Loc,
9368 Iteration_Scheme => Scheme,
9369 Statements => Stmts,
9370 End_Label => Empty));
9372 -- Transform the quantified expression
9374 Rewrite (N,
9375 Make_Expression_With_Actions (Loc,
9376 Expression => New_Occurrence_Of (Flag, Loc),
9377 Actions => Actions));
9378 Analyze_And_Resolve (N, Standard_Boolean);
9379 end Expand_N_Quantified_Expression;
9381 ---------------------------------
9382 -- Expand_N_Selected_Component --
9383 ---------------------------------
9385 procedure Expand_N_Selected_Component (N : Node_Id) is
9386 Loc : constant Source_Ptr := Sloc (N);
9387 Par : constant Node_Id := Parent (N);
9388 P : constant Node_Id := Prefix (N);
9389 S : constant Node_Id := Selector_Name (N);
9390 Ptyp : Entity_Id := Underlying_Type (Etype (P));
9391 Disc : Entity_Id;
9392 New_N : Node_Id;
9393 Dcon : Elmt_Id;
9394 Dval : Node_Id;
9396 function In_Left_Hand_Side (Comp : Node_Id) return Boolean;
9397 -- Gigi needs a temporary for prefixes that depend on a discriminant,
9398 -- unless the context of an assignment can provide size information.
9399 -- Don't we have a general routine that does this???
9401 function Is_Subtype_Declaration return Boolean;
9402 -- The replacement of a discriminant reference by its value is required
9403 -- if this is part of the initialization of an temporary generated by a
9404 -- change of representation. This shows up as the construction of a
9405 -- discriminant constraint for a subtype declared at the same point as
9406 -- the entity in the prefix of the selected component. We recognize this
9407 -- case when the context of the reference is:
9408 -- subtype ST is T(Obj.D);
9409 -- where the entity for Obj comes from source, and ST has the same sloc.
9411 -----------------------
9412 -- In_Left_Hand_Side --
9413 -----------------------
9415 function In_Left_Hand_Side (Comp : Node_Id) return Boolean is
9416 begin
9417 return (Nkind (Parent (Comp)) = N_Assignment_Statement
9418 and then Comp = Name (Parent (Comp)))
9419 or else (Present (Parent (Comp))
9420 and then Nkind (Parent (Comp)) in N_Subexpr
9421 and then In_Left_Hand_Side (Parent (Comp)));
9422 end In_Left_Hand_Side;
9424 -----------------------------
9425 -- Is_Subtype_Declaration --
9426 -----------------------------
9428 function Is_Subtype_Declaration return Boolean is
9429 Par : constant Node_Id := Parent (N);
9430 begin
9431 return
9432 Nkind (Par) = N_Index_Or_Discriminant_Constraint
9433 and then Nkind (Parent (Parent (Par))) = N_Subtype_Declaration
9434 and then Comes_From_Source (Entity (Prefix (N)))
9435 and then Sloc (Par) = Sloc (Entity (Prefix (N)));
9436 end Is_Subtype_Declaration;
9438 -- Start of processing for Expand_N_Selected_Component
9440 begin
9441 -- Insert explicit dereference if required
9443 if Is_Access_Type (Ptyp) then
9445 -- First set prefix type to proper access type, in case it currently
9446 -- has a private (non-access) view of this type.
9448 Set_Etype (P, Ptyp);
9450 Insert_Explicit_Dereference (P);
9451 Analyze_And_Resolve (P, Designated_Type (Ptyp));
9453 if Ekind (Etype (P)) = E_Private_Subtype
9454 and then Is_For_Access_Subtype (Etype (P))
9455 then
9456 Set_Etype (P, Base_Type (Etype (P)));
9457 end if;
9459 Ptyp := Etype (P);
9460 end if;
9462 -- Deal with discriminant check required
9464 if Do_Discriminant_Check (N) then
9465 if Present (Discriminant_Checking_Func
9466 (Original_Record_Component (Entity (S))))
9467 then
9468 -- Present the discriminant checking function to the backend, so
9469 -- that it can inline the call to the function.
9471 Add_Inlined_Body
9472 (Discriminant_Checking_Func
9473 (Original_Record_Component (Entity (S))));
9475 -- Now reset the flag and generate the call
9477 Set_Do_Discriminant_Check (N, False);
9478 Generate_Discriminant_Check (N);
9480 -- In the case of Unchecked_Union, no discriminant checking is
9481 -- actually performed.
9483 else
9484 Set_Do_Discriminant_Check (N, False);
9485 end if;
9486 end if;
9488 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
9489 -- function, then additional actuals must be passed.
9491 if Ada_Version >= Ada_2005
9492 and then Is_Build_In_Place_Function_Call (P)
9493 then
9494 Make_Build_In_Place_Call_In_Anonymous_Context (P);
9495 end if;
9497 -- Gigi cannot handle unchecked conversions that are the prefix of a
9498 -- selected component with discriminants. This must be checked during
9499 -- expansion, because during analysis the type of the selector is not
9500 -- known at the point the prefix is analyzed. If the conversion is the
9501 -- target of an assignment, then we cannot force the evaluation.
9503 if Nkind (Prefix (N)) = N_Unchecked_Type_Conversion
9504 and then Has_Discriminants (Etype (N))
9505 and then not In_Left_Hand_Side (N)
9506 then
9507 Force_Evaluation (Prefix (N));
9508 end if;
9510 -- Remaining processing applies only if selector is a discriminant
9512 if Ekind (Entity (Selector_Name (N))) = E_Discriminant then
9514 -- If the selector is a discriminant of a constrained record type,
9515 -- we may be able to rewrite the expression with the actual value
9516 -- of the discriminant, a useful optimization in some cases.
9518 if Is_Record_Type (Ptyp)
9519 and then Has_Discriminants (Ptyp)
9520 and then Is_Constrained (Ptyp)
9521 then
9522 -- Do this optimization for discrete types only, and not for
9523 -- access types (access discriminants get us into trouble).
9525 if not Is_Discrete_Type (Etype (N)) then
9526 null;
9528 -- Don't do this on the left hand of an assignment statement.
9529 -- Normally one would think that references like this would not
9530 -- occur, but they do in generated code, and mean that we really
9531 -- do want to assign the discriminant.
9533 elsif Nkind (Par) = N_Assignment_Statement
9534 and then Name (Par) = N
9535 then
9536 null;
9538 -- Don't do this optimization for the prefix of an attribute or
9539 -- the name of an object renaming declaration since these are
9540 -- contexts where we do not want the value anyway.
9542 elsif (Nkind (Par) = N_Attribute_Reference
9543 and then Prefix (Par) = N)
9544 or else Is_Renamed_Object (N)
9545 then
9546 null;
9548 -- Don't do this optimization if we are within the code for a
9549 -- discriminant check, since the whole point of such a check may
9550 -- be to verify the condition on which the code below depends.
9552 elsif Is_In_Discriminant_Check (N) then
9553 null;
9555 -- Green light to see if we can do the optimization. There is
9556 -- still one condition that inhibits the optimization below but
9557 -- now is the time to check the particular discriminant.
9559 else
9560 -- Loop through discriminants to find the matching discriminant
9561 -- constraint to see if we can copy it.
9563 Disc := First_Discriminant (Ptyp);
9564 Dcon := First_Elmt (Discriminant_Constraint (Ptyp));
9565 Discr_Loop : while Present (Dcon) loop
9566 Dval := Node (Dcon);
9568 -- Check if this is the matching discriminant and if the
9569 -- discriminant value is simple enough to make sense to
9570 -- copy. We don't want to copy complex expressions, and
9571 -- indeed to do so can cause trouble (before we put in
9572 -- this guard, a discriminant expression containing an
9573 -- AND THEN was copied, causing problems for coverage
9574 -- analysis tools).
9576 -- However, if the reference is part of the initialization
9577 -- code generated for an object declaration, we must use
9578 -- the discriminant value from the subtype constraint,
9579 -- because the selected component may be a reference to the
9580 -- object being initialized, whose discriminant is not yet
9581 -- set. This only happens in complex cases involving changes
9582 -- or representation.
9584 if Disc = Entity (Selector_Name (N))
9585 and then (Is_Entity_Name (Dval)
9586 or else Compile_Time_Known_Value (Dval)
9587 or else Is_Subtype_Declaration)
9588 then
9589 -- Here we have the matching discriminant. Check for
9590 -- the case of a discriminant of a component that is
9591 -- constrained by an outer discriminant, which cannot
9592 -- be optimized away.
9594 if Denotes_Discriminant
9595 (Dval, Check_Concurrent => True)
9596 then
9597 exit Discr_Loop;
9599 elsif Nkind (Original_Node (Dval)) = N_Selected_Component
9600 and then
9601 Denotes_Discriminant
9602 (Selector_Name (Original_Node (Dval)), True)
9603 then
9604 exit Discr_Loop;
9606 -- Do not retrieve value if constraint is not static. It
9607 -- is generally not useful, and the constraint may be a
9608 -- rewritten outer discriminant in which case it is in
9609 -- fact incorrect.
9611 elsif Is_Entity_Name (Dval)
9612 and then
9613 Nkind (Parent (Entity (Dval))) = N_Object_Declaration
9614 and then Present (Expression (Parent (Entity (Dval))))
9615 and then not
9616 Is_OK_Static_Expression
9617 (Expression (Parent (Entity (Dval))))
9618 then
9619 exit Discr_Loop;
9621 -- In the context of a case statement, the expression may
9622 -- have the base type of the discriminant, and we need to
9623 -- preserve the constraint to avoid spurious errors on
9624 -- missing cases.
9626 elsif Nkind (Parent (N)) = N_Case_Statement
9627 and then Etype (Dval) /= Etype (Disc)
9628 then
9629 Rewrite (N,
9630 Make_Qualified_Expression (Loc,
9631 Subtype_Mark =>
9632 New_Occurrence_Of (Etype (Disc), Loc),
9633 Expression =>
9634 New_Copy_Tree (Dval)));
9635 Analyze_And_Resolve (N, Etype (Disc));
9637 -- In case that comes out as a static expression,
9638 -- reset it (a selected component is never static).
9640 Set_Is_Static_Expression (N, False);
9641 return;
9643 -- Otherwise we can just copy the constraint, but the
9644 -- result is certainly not static. In some cases the
9645 -- discriminant constraint has been analyzed in the
9646 -- context of the original subtype indication, but for
9647 -- itypes the constraint might not have been analyzed
9648 -- yet, and this must be done now.
9650 else
9651 Rewrite (N, New_Copy_Tree (Dval));
9652 Analyze_And_Resolve (N);
9653 Set_Is_Static_Expression (N, False);
9654 return;
9655 end if;
9656 end if;
9658 Next_Elmt (Dcon);
9659 Next_Discriminant (Disc);
9660 end loop Discr_Loop;
9662 -- Note: the above loop should always find a matching
9663 -- discriminant, but if it does not, we just missed an
9664 -- optimization due to some glitch (perhaps a previous
9665 -- error), so ignore.
9667 end if;
9668 end if;
9670 -- The only remaining processing is in the case of a discriminant of
9671 -- a concurrent object, where we rewrite the prefix to denote the
9672 -- corresponding record type. If the type is derived and has renamed
9673 -- discriminants, use corresponding discriminant, which is the one
9674 -- that appears in the corresponding record.
9676 if not Is_Concurrent_Type (Ptyp) then
9677 return;
9678 end if;
9680 Disc := Entity (Selector_Name (N));
9682 if Is_Derived_Type (Ptyp)
9683 and then Present (Corresponding_Discriminant (Disc))
9684 then
9685 Disc := Corresponding_Discriminant (Disc);
9686 end if;
9688 New_N :=
9689 Make_Selected_Component (Loc,
9690 Prefix =>
9691 Unchecked_Convert_To (Corresponding_Record_Type (Ptyp),
9692 New_Copy_Tree (P)),
9693 Selector_Name => Make_Identifier (Loc, Chars (Disc)));
9695 Rewrite (N, New_N);
9696 Analyze (N);
9697 end if;
9699 -- Set Atomic_Sync_Required if necessary for atomic component
9701 if Nkind (N) = N_Selected_Component then
9702 declare
9703 E : constant Entity_Id := Entity (Selector_Name (N));
9704 Set : Boolean;
9706 begin
9707 -- If component is atomic, but type is not, setting depends on
9708 -- disable/enable state for the component.
9710 if Is_Atomic (E) and then not Is_Atomic (Etype (E)) then
9711 Set := not Atomic_Synchronization_Disabled (E);
9713 -- If component is not atomic, but its type is atomic, setting
9714 -- depends on disable/enable state for the type.
9716 elsif not Is_Atomic (E) and then Is_Atomic (Etype (E)) then
9717 Set := not Atomic_Synchronization_Disabled (Etype (E));
9719 -- If both component and type are atomic, we disable if either
9720 -- component or its type have sync disabled.
9722 elsif Is_Atomic (E) and then Is_Atomic (Etype (E)) then
9723 Set := (not Atomic_Synchronization_Disabled (E))
9724 and then
9725 (not Atomic_Synchronization_Disabled (Etype (E)));
9727 else
9728 Set := False;
9729 end if;
9731 -- Set flag if required
9733 if Set then
9734 Activate_Atomic_Synchronization (N);
9735 end if;
9736 end;
9737 end if;
9738 end Expand_N_Selected_Component;
9740 --------------------
9741 -- Expand_N_Slice --
9742 --------------------
9744 procedure Expand_N_Slice (N : Node_Id) is
9745 Loc : constant Source_Ptr := Sloc (N);
9746 Typ : constant Entity_Id := Etype (N);
9748 function Is_Procedure_Actual (N : Node_Id) return Boolean;
9749 -- Check whether the argument is an actual for a procedure call, in
9750 -- which case the expansion of a bit-packed slice is deferred until the
9751 -- call itself is expanded. The reason this is required is that we might
9752 -- have an IN OUT or OUT parameter, and the copy out is essential, and
9753 -- that copy out would be missed if we created a temporary here in
9754 -- Expand_N_Slice. Note that we don't bother to test specifically for an
9755 -- IN OUT or OUT mode parameter, since it is a bit tricky to do, and it
9756 -- is harmless to defer expansion in the IN case, since the call
9757 -- processing will still generate the appropriate copy in operation,
9758 -- which will take care of the slice.
9760 procedure Make_Temporary_For_Slice;
9761 -- Create a named variable for the value of the slice, in cases where
9762 -- the back-end cannot handle it properly, e.g. when packed types or
9763 -- unaligned slices are involved.
9765 -------------------------
9766 -- Is_Procedure_Actual --
9767 -------------------------
9769 function Is_Procedure_Actual (N : Node_Id) return Boolean is
9770 Par : Node_Id := Parent (N);
9772 begin
9773 loop
9774 -- If our parent is a procedure call we can return
9776 if Nkind (Par) = N_Procedure_Call_Statement then
9777 return True;
9779 -- If our parent is a type conversion, keep climbing the tree,
9780 -- since a type conversion can be a procedure actual. Also keep
9781 -- climbing if parameter association or a qualified expression,
9782 -- since these are additional cases that do can appear on
9783 -- procedure actuals.
9785 elsif Nkind_In (Par, N_Type_Conversion,
9786 N_Parameter_Association,
9787 N_Qualified_Expression)
9788 then
9789 Par := Parent (Par);
9791 -- Any other case is not what we are looking for
9793 else
9794 return False;
9795 end if;
9796 end loop;
9797 end Is_Procedure_Actual;
9799 ------------------------------
9800 -- Make_Temporary_For_Slice --
9801 ------------------------------
9803 procedure Make_Temporary_For_Slice is
9804 Ent : constant Entity_Id := Make_Temporary (Loc, 'T', N);
9805 Decl : Node_Id;
9807 begin
9808 Decl :=
9809 Make_Object_Declaration (Loc,
9810 Defining_Identifier => Ent,
9811 Object_Definition => New_Occurrence_Of (Typ, Loc));
9813 Set_No_Initialization (Decl);
9815 Insert_Actions (N, New_List (
9816 Decl,
9817 Make_Assignment_Statement (Loc,
9818 Name => New_Occurrence_Of (Ent, Loc),
9819 Expression => Relocate_Node (N))));
9821 Rewrite (N, New_Occurrence_Of (Ent, Loc));
9822 Analyze_And_Resolve (N, Typ);
9823 end Make_Temporary_For_Slice;
9825 -- Local variables
9827 Pref : constant Node_Id := Prefix (N);
9828 Pref_Typ : Entity_Id := Etype (Pref);
9830 -- Start of processing for Expand_N_Slice
9832 begin
9833 -- Special handling for access types
9835 if Is_Access_Type (Pref_Typ) then
9836 Pref_Typ := Designated_Type (Pref_Typ);
9838 Rewrite (Pref,
9839 Make_Explicit_Dereference (Sloc (N),
9840 Prefix => Relocate_Node (Pref)));
9842 Analyze_And_Resolve (Pref, Pref_Typ);
9843 end if;
9845 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
9846 -- function, then additional actuals must be passed.
9848 if Ada_Version >= Ada_2005
9849 and then Is_Build_In_Place_Function_Call (Pref)
9850 then
9851 Make_Build_In_Place_Call_In_Anonymous_Context (Pref);
9852 end if;
9854 -- The remaining case to be handled is packed slices. We can leave
9855 -- packed slices as they are in the following situations:
9857 -- 1. Right or left side of an assignment (we can handle this
9858 -- situation correctly in the assignment statement expansion).
9860 -- 2. Prefix of indexed component (the slide is optimized away in this
9861 -- case, see the start of Expand_N_Slice.)
9863 -- 3. Object renaming declaration, since we want the name of the
9864 -- slice, not the value.
9866 -- 4. Argument to procedure call, since copy-in/copy-out handling may
9867 -- be required, and this is handled in the expansion of call
9868 -- itself.
9870 -- 5. Prefix of an address attribute (this is an error which is caught
9871 -- elsewhere, and the expansion would interfere with generating the
9872 -- error message).
9874 if not Is_Packed (Typ) then
9876 -- Apply transformation for actuals of a function call, where
9877 -- Expand_Actuals is not used.
9879 if Nkind (Parent (N)) = N_Function_Call
9880 and then Is_Possibly_Unaligned_Slice (N)
9881 then
9882 Make_Temporary_For_Slice;
9883 end if;
9885 elsif Nkind (Parent (N)) = N_Assignment_Statement
9886 or else (Nkind (Parent (Parent (N))) = N_Assignment_Statement
9887 and then Parent (N) = Name (Parent (Parent (N))))
9888 then
9889 return;
9891 elsif Nkind (Parent (N)) = N_Indexed_Component
9892 or else Is_Renamed_Object (N)
9893 or else Is_Procedure_Actual (N)
9894 then
9895 return;
9897 elsif Nkind (Parent (N)) = N_Attribute_Reference
9898 and then Attribute_Name (Parent (N)) = Name_Address
9899 then
9900 return;
9902 else
9903 Make_Temporary_For_Slice;
9904 end if;
9905 end Expand_N_Slice;
9907 ------------------------------
9908 -- Expand_N_Type_Conversion --
9909 ------------------------------
9911 procedure Expand_N_Type_Conversion (N : Node_Id) is
9912 Loc : constant Source_Ptr := Sloc (N);
9913 Operand : constant Node_Id := Expression (N);
9914 Target_Type : constant Entity_Id := Etype (N);
9915 Operand_Type : Entity_Id := Etype (Operand);
9917 procedure Handle_Changed_Representation;
9918 -- This is called in the case of record and array type conversions to
9919 -- see if there is a change of representation to be handled. Change of
9920 -- representation is actually handled at the assignment statement level,
9921 -- and what this procedure does is rewrite node N conversion as an
9922 -- assignment to temporary. If there is no change of representation,
9923 -- then the conversion node is unchanged.
9925 procedure Raise_Accessibility_Error;
9926 -- Called when we know that an accessibility check will fail. Rewrites
9927 -- node N to an appropriate raise statement and outputs warning msgs.
9928 -- The Etype of the raise node is set to Target_Type.
9930 procedure Real_Range_Check;
9931 -- Handles generation of range check for real target value
9933 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean;
9934 -- True iff Present (Effective_Extra_Accessibility (Id)) successfully
9935 -- evaluates to True.
9937 -----------------------------------
9938 -- Handle_Changed_Representation --
9939 -----------------------------------
9941 procedure Handle_Changed_Representation is
9942 Temp : Entity_Id;
9943 Decl : Node_Id;
9944 Odef : Node_Id;
9945 Disc : Node_Id;
9946 N_Ix : Node_Id;
9947 Cons : List_Id;
9949 begin
9950 -- Nothing else to do if no change of representation
9952 if Same_Representation (Operand_Type, Target_Type) then
9953 return;
9955 -- The real change of representation work is done by the assignment
9956 -- statement processing. So if this type conversion is appearing as
9957 -- the expression of an assignment statement, nothing needs to be
9958 -- done to the conversion.
9960 elsif Nkind (Parent (N)) = N_Assignment_Statement then
9961 return;
9963 -- Otherwise we need to generate a temporary variable, and do the
9964 -- change of representation assignment into that temporary variable.
9965 -- The conversion is then replaced by a reference to this variable.
9967 else
9968 Cons := No_List;
9970 -- If type is unconstrained we have to add a constraint, copied
9971 -- from the actual value of the left hand side.
9973 if not Is_Constrained (Target_Type) then
9974 if Has_Discriminants (Operand_Type) then
9975 Disc := First_Discriminant (Operand_Type);
9977 if Disc /= First_Stored_Discriminant (Operand_Type) then
9978 Disc := First_Stored_Discriminant (Operand_Type);
9979 end if;
9981 Cons := New_List;
9982 while Present (Disc) loop
9983 Append_To (Cons,
9984 Make_Selected_Component (Loc,
9985 Prefix =>
9986 Duplicate_Subexpr_Move_Checks (Operand),
9987 Selector_Name =>
9988 Make_Identifier (Loc, Chars (Disc))));
9989 Next_Discriminant (Disc);
9990 end loop;
9992 elsif Is_Array_Type (Operand_Type) then
9993 N_Ix := First_Index (Target_Type);
9994 Cons := New_List;
9996 for J in 1 .. Number_Dimensions (Operand_Type) loop
9998 -- We convert the bounds explicitly. We use an unchecked
9999 -- conversion because bounds checks are done elsewhere.
10001 Append_To (Cons,
10002 Make_Range (Loc,
10003 Low_Bound =>
10004 Unchecked_Convert_To (Etype (N_Ix),
10005 Make_Attribute_Reference (Loc,
10006 Prefix =>
10007 Duplicate_Subexpr_No_Checks
10008 (Operand, Name_Req => True),
10009 Attribute_Name => Name_First,
10010 Expressions => New_List (
10011 Make_Integer_Literal (Loc, J)))),
10013 High_Bound =>
10014 Unchecked_Convert_To (Etype (N_Ix),
10015 Make_Attribute_Reference (Loc,
10016 Prefix =>
10017 Duplicate_Subexpr_No_Checks
10018 (Operand, Name_Req => True),
10019 Attribute_Name => Name_Last,
10020 Expressions => New_List (
10021 Make_Integer_Literal (Loc, J))))));
10023 Next_Index (N_Ix);
10024 end loop;
10025 end if;
10026 end if;
10028 Odef := New_Occurrence_Of (Target_Type, Loc);
10030 if Present (Cons) then
10031 Odef :=
10032 Make_Subtype_Indication (Loc,
10033 Subtype_Mark => Odef,
10034 Constraint =>
10035 Make_Index_Or_Discriminant_Constraint (Loc,
10036 Constraints => Cons));
10037 end if;
10039 Temp := Make_Temporary (Loc, 'C');
10040 Decl :=
10041 Make_Object_Declaration (Loc,
10042 Defining_Identifier => Temp,
10043 Object_Definition => Odef);
10045 Set_No_Initialization (Decl, True);
10047 -- Insert required actions. It is essential to suppress checks
10048 -- since we have suppressed default initialization, which means
10049 -- that the variable we create may have no discriminants.
10051 Insert_Actions (N,
10052 New_List (
10053 Decl,
10054 Make_Assignment_Statement (Loc,
10055 Name => New_Occurrence_Of (Temp, Loc),
10056 Expression => Relocate_Node (N))),
10057 Suppress => All_Checks);
10059 Rewrite (N, New_Occurrence_Of (Temp, Loc));
10060 return;
10061 end if;
10062 end Handle_Changed_Representation;
10064 -------------------------------
10065 -- Raise_Accessibility_Error --
10066 -------------------------------
10068 procedure Raise_Accessibility_Error is
10069 begin
10070 Error_Msg_Warn := SPARK_Mode /= On;
10071 Rewrite (N,
10072 Make_Raise_Program_Error (Sloc (N),
10073 Reason => PE_Accessibility_Check_Failed));
10074 Set_Etype (N, Target_Type);
10076 Error_Msg_N ("<<accessibility check failure", N);
10077 Error_Msg_NE ("\<<& [", N, Standard_Program_Error);
10078 end Raise_Accessibility_Error;
10080 ----------------------
10081 -- Real_Range_Check --
10082 ----------------------
10084 -- Case of conversions to floating-point or fixed-point. If range checks
10085 -- are enabled and the target type has a range constraint, we convert:
10087 -- typ (x)
10089 -- to
10091 -- Tnn : typ'Base := typ'Base (x);
10092 -- [constraint_error when Tnn < typ'First or else Tnn > typ'Last]
10093 -- Tnn
10095 -- This is necessary when there is a conversion of integer to float or
10096 -- to fixed-point to ensure that the correct checks are made. It is not
10097 -- necessary for float to float where it is enough to simply set the
10098 -- Do_Range_Check flag.
10100 procedure Real_Range_Check is
10101 Btyp : constant Entity_Id := Base_Type (Target_Type);
10102 Lo : constant Node_Id := Type_Low_Bound (Target_Type);
10103 Hi : constant Node_Id := Type_High_Bound (Target_Type);
10104 Xtyp : constant Entity_Id := Etype (Operand);
10105 Conv : Node_Id;
10106 Tnn : Entity_Id;
10108 begin
10109 -- Nothing to do if conversion was rewritten
10111 if Nkind (N) /= N_Type_Conversion then
10112 return;
10113 end if;
10115 -- Nothing to do if range checks suppressed, or target has the same
10116 -- range as the base type (or is the base type).
10118 if Range_Checks_Suppressed (Target_Type)
10119 or else (Lo = Type_Low_Bound (Btyp)
10120 and then
10121 Hi = Type_High_Bound (Btyp))
10122 then
10123 return;
10124 end if;
10126 -- Nothing to do if expression is an entity on which checks have been
10127 -- suppressed.
10129 if Is_Entity_Name (Operand)
10130 and then Range_Checks_Suppressed (Entity (Operand))
10131 then
10132 return;
10133 end if;
10135 -- Nothing to do if bounds are all static and we can tell that the
10136 -- expression is within the bounds of the target. Note that if the
10137 -- operand is of an unconstrained floating-point type, then we do
10138 -- not trust it to be in range (might be infinite)
10140 declare
10141 S_Lo : constant Node_Id := Type_Low_Bound (Xtyp);
10142 S_Hi : constant Node_Id := Type_High_Bound (Xtyp);
10144 begin
10145 if (not Is_Floating_Point_Type (Xtyp)
10146 or else Is_Constrained (Xtyp))
10147 and then Compile_Time_Known_Value (S_Lo)
10148 and then Compile_Time_Known_Value (S_Hi)
10149 and then Compile_Time_Known_Value (Hi)
10150 and then Compile_Time_Known_Value (Lo)
10151 then
10152 declare
10153 D_Lov : constant Ureal := Expr_Value_R (Lo);
10154 D_Hiv : constant Ureal := Expr_Value_R (Hi);
10155 S_Lov : Ureal;
10156 S_Hiv : Ureal;
10158 begin
10159 if Is_Real_Type (Xtyp) then
10160 S_Lov := Expr_Value_R (S_Lo);
10161 S_Hiv := Expr_Value_R (S_Hi);
10162 else
10163 S_Lov := UR_From_Uint (Expr_Value (S_Lo));
10164 S_Hiv := UR_From_Uint (Expr_Value (S_Hi));
10165 end if;
10167 if D_Hiv > D_Lov
10168 and then S_Lov >= D_Lov
10169 and then S_Hiv <= D_Hiv
10170 then
10171 -- Unset the range check flag on the current value of
10172 -- Expression (N), since the captured Operand may have
10173 -- been rewritten (such as for the case of a conversion
10174 -- to a fixed-point type).
10176 Set_Do_Range_Check (Expression (N), False);
10178 return;
10179 end if;
10180 end;
10181 end if;
10182 end;
10184 -- For float to float conversions, we are done
10186 if Is_Floating_Point_Type (Xtyp)
10187 and then
10188 Is_Floating_Point_Type (Btyp)
10189 then
10190 return;
10191 end if;
10193 -- Otherwise rewrite the conversion as described above
10195 Conv := Relocate_Node (N);
10196 Rewrite (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
10197 Set_Etype (Conv, Btyp);
10199 -- Enable overflow except for case of integer to float conversions,
10200 -- where it is never required, since we can never have overflow in
10201 -- this case.
10203 if not Is_Integer_Type (Etype (Operand)) then
10204 Enable_Overflow_Check (Conv);
10205 end if;
10207 Tnn := Make_Temporary (Loc, 'T', Conv);
10209 Insert_Actions (N, New_List (
10210 Make_Object_Declaration (Loc,
10211 Defining_Identifier => Tnn,
10212 Object_Definition => New_Occurrence_Of (Btyp, Loc),
10213 Constant_Present => True,
10214 Expression => Conv),
10216 Make_Raise_Constraint_Error (Loc,
10217 Condition =>
10218 Make_Or_Else (Loc,
10219 Left_Opnd =>
10220 Make_Op_Lt (Loc,
10221 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
10222 Right_Opnd =>
10223 Make_Attribute_Reference (Loc,
10224 Attribute_Name => Name_First,
10225 Prefix =>
10226 New_Occurrence_Of (Target_Type, Loc))),
10228 Right_Opnd =>
10229 Make_Op_Gt (Loc,
10230 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
10231 Right_Opnd =>
10232 Make_Attribute_Reference (Loc,
10233 Attribute_Name => Name_Last,
10234 Prefix =>
10235 New_Occurrence_Of (Target_Type, Loc)))),
10236 Reason => CE_Range_Check_Failed)));
10238 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
10239 Analyze_And_Resolve (N, Btyp);
10240 end Real_Range_Check;
10242 -----------------------------
10243 -- Has_Extra_Accessibility --
10244 -----------------------------
10246 -- Returns true for a formal of an anonymous access type or for
10247 -- an Ada 2012-style stand-alone object of an anonymous access type.
10249 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean is
10250 begin
10251 if Is_Formal (Id) or else Ekind_In (Id, E_Constant, E_Variable) then
10252 return Present (Effective_Extra_Accessibility (Id));
10253 else
10254 return False;
10255 end if;
10256 end Has_Extra_Accessibility;
10258 -- Start of processing for Expand_N_Type_Conversion
10260 begin
10261 -- First remove check marks put by the semantic analysis on the type
10262 -- conversion between array types. We need these checks, and they will
10263 -- be generated by this expansion routine, but we do not depend on these
10264 -- flags being set, and since we do intend to expand the checks in the
10265 -- front end, we don't want them on the tree passed to the back end.
10267 if Is_Array_Type (Target_Type) then
10268 if Is_Constrained (Target_Type) then
10269 Set_Do_Length_Check (N, False);
10270 else
10271 Set_Do_Range_Check (Operand, False);
10272 end if;
10273 end if;
10275 -- Nothing at all to do if conversion is to the identical type so remove
10276 -- the conversion completely, it is useless, except that it may carry
10277 -- an Assignment_OK attribute, which must be propagated to the operand.
10279 if Operand_Type = Target_Type then
10280 if Assignment_OK (N) then
10281 Set_Assignment_OK (Operand);
10282 end if;
10284 Rewrite (N, Relocate_Node (Operand));
10285 goto Done;
10286 end if;
10288 -- Nothing to do if this is the second argument of read. This is a
10289 -- "backwards" conversion that will be handled by the specialized code
10290 -- in attribute processing.
10292 if Nkind (Parent (N)) = N_Attribute_Reference
10293 and then Attribute_Name (Parent (N)) = Name_Read
10294 and then Next (First (Expressions (Parent (N)))) = N
10295 then
10296 goto Done;
10297 end if;
10299 -- Check for case of converting to a type that has an invariant
10300 -- associated with it. This required an invariant check. We convert
10302 -- typ (expr)
10304 -- into
10306 -- do invariant_check (typ (expr)) in typ (expr);
10308 -- using Duplicate_Subexpr to avoid multiple side effects
10310 -- Note: the Comes_From_Source check, and then the resetting of this
10311 -- flag prevents what would otherwise be an infinite recursion.
10313 if Has_Invariants (Target_Type)
10314 and then Present (Invariant_Procedure (Target_Type))
10315 and then Comes_From_Source (N)
10316 then
10317 Set_Comes_From_Source (N, False);
10318 Rewrite (N,
10319 Make_Expression_With_Actions (Loc,
10320 Actions => New_List (
10321 Make_Invariant_Call (Duplicate_Subexpr (N))),
10322 Expression => Duplicate_Subexpr_No_Checks (N)));
10323 Analyze_And_Resolve (N, Target_Type);
10324 goto Done;
10325 end if;
10327 -- Here if we may need to expand conversion
10329 -- If the operand of the type conversion is an arithmetic operation on
10330 -- signed integers, and the based type of the signed integer type in
10331 -- question is smaller than Standard.Integer, we promote both of the
10332 -- operands to type Integer.
10334 -- For example, if we have
10336 -- target-type (opnd1 + opnd2)
10338 -- and opnd1 and opnd2 are of type short integer, then we rewrite
10339 -- this as:
10341 -- target-type (integer(opnd1) + integer(opnd2))
10343 -- We do this because we are always allowed to compute in a larger type
10344 -- if we do the right thing with the result, and in this case we are
10345 -- going to do a conversion which will do an appropriate check to make
10346 -- sure that things are in range of the target type in any case. This
10347 -- avoids some unnecessary intermediate overflows.
10349 -- We might consider a similar transformation in the case where the
10350 -- target is a real type or a 64-bit integer type, and the operand
10351 -- is an arithmetic operation using a 32-bit integer type. However,
10352 -- we do not bother with this case, because it could cause significant
10353 -- inefficiencies on 32-bit machines. On a 64-bit machine it would be
10354 -- much cheaper, but we don't want different behavior on 32-bit and
10355 -- 64-bit machines. Note that the exclusion of the 64-bit case also
10356 -- handles the configurable run-time cases where 64-bit arithmetic
10357 -- may simply be unavailable.
10359 -- Note: this circuit is partially redundant with respect to the circuit
10360 -- in Checks.Apply_Arithmetic_Overflow_Check, but we catch more cases in
10361 -- the processing here. Also we still need the Checks circuit, since we
10362 -- have to be sure not to generate junk overflow checks in the first
10363 -- place, since it would be trick to remove them here.
10365 if Integer_Promotion_Possible (N) then
10367 -- All conditions met, go ahead with transformation
10369 declare
10370 Opnd : Node_Id;
10371 L, R : Node_Id;
10373 begin
10374 R :=
10375 Make_Type_Conversion (Loc,
10376 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
10377 Expression => Relocate_Node (Right_Opnd (Operand)));
10379 Opnd := New_Op_Node (Nkind (Operand), Loc);
10380 Set_Right_Opnd (Opnd, R);
10382 if Nkind (Operand) in N_Binary_Op then
10383 L :=
10384 Make_Type_Conversion (Loc,
10385 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
10386 Expression => Relocate_Node (Left_Opnd (Operand)));
10388 Set_Left_Opnd (Opnd, L);
10389 end if;
10391 Rewrite (N,
10392 Make_Type_Conversion (Loc,
10393 Subtype_Mark => Relocate_Node (Subtype_Mark (N)),
10394 Expression => Opnd));
10396 Analyze_And_Resolve (N, Target_Type);
10397 goto Done;
10398 end;
10399 end if;
10401 -- Do validity check if validity checking operands
10403 if Validity_Checks_On and Validity_Check_Operands then
10404 Ensure_Valid (Operand);
10405 end if;
10407 -- Special case of converting from non-standard boolean type
10409 if Is_Boolean_Type (Operand_Type)
10410 and then (Nonzero_Is_True (Operand_Type))
10411 then
10412 Adjust_Condition (Operand);
10413 Set_Etype (Operand, Standard_Boolean);
10414 Operand_Type := Standard_Boolean;
10415 end if;
10417 -- Case of converting to an access type
10419 if Is_Access_Type (Target_Type) then
10421 -- Apply an accessibility check when the conversion operand is an
10422 -- access parameter (or a renaming thereof), unless conversion was
10423 -- expanded from an Unchecked_ or Unrestricted_Access attribute.
10424 -- Note that other checks may still need to be applied below (such
10425 -- as tagged type checks).
10427 if Is_Entity_Name (Operand)
10428 and then Has_Extra_Accessibility (Entity (Operand))
10429 and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
10430 and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
10431 or else Attribute_Name (Original_Node (N)) = Name_Access)
10432 then
10433 Apply_Accessibility_Check
10434 (Operand, Target_Type, Insert_Node => Operand);
10436 -- If the level of the operand type is statically deeper than the
10437 -- level of the target type, then force Program_Error. Note that this
10438 -- can only occur for cases where the attribute is within the body of
10439 -- an instantiation, otherwise the conversion will already have been
10440 -- rejected as illegal.
10442 -- Note: warnings are issued by the analyzer for the instance cases
10444 elsif In_Instance_Body
10446 -- The case where the target type is an anonymous access type of
10447 -- a discriminant is excluded, because the level of such a type
10448 -- depends on the context and currently the level returned for such
10449 -- types is zero, resulting in warnings about about check failures
10450 -- in certain legal cases involving class-wide interfaces as the
10451 -- designated type (some cases, such as return statements, are
10452 -- checked at run time, but not clear if these are handled right
10453 -- in general, see 3.10.2(12/2-12.5/3) ???).
10455 and then
10456 not (Ekind (Target_Type) = E_Anonymous_Access_Type
10457 and then Present (Associated_Node_For_Itype (Target_Type))
10458 and then Nkind (Associated_Node_For_Itype (Target_Type)) =
10459 N_Discriminant_Specification)
10460 and then
10461 Type_Access_Level (Operand_Type) > Type_Access_Level (Target_Type)
10462 then
10463 Raise_Accessibility_Error;
10465 -- When the operand is a selected access discriminant the check needs
10466 -- to be made against the level of the object denoted by the prefix
10467 -- of the selected name. Force Program_Error for this case as well
10468 -- (this accessibility violation can only happen if within the body
10469 -- of an instantiation).
10471 elsif In_Instance_Body
10472 and then Ekind (Operand_Type) = E_Anonymous_Access_Type
10473 and then Nkind (Operand) = N_Selected_Component
10474 and then Object_Access_Level (Operand) >
10475 Type_Access_Level (Target_Type)
10476 then
10477 Raise_Accessibility_Error;
10478 goto Done;
10479 end if;
10480 end if;
10482 -- Case of conversions of tagged types and access to tagged types
10484 -- When needed, that is to say when the expression is class-wide, Add
10485 -- runtime a tag check for (strict) downward conversion by using the
10486 -- membership test, generating:
10488 -- [constraint_error when Operand not in Target_Type'Class]
10490 -- or in the access type case
10492 -- [constraint_error
10493 -- when Operand /= null
10494 -- and then Operand.all not in
10495 -- Designated_Type (Target_Type)'Class]
10497 if (Is_Access_Type (Target_Type)
10498 and then Is_Tagged_Type (Designated_Type (Target_Type)))
10499 or else Is_Tagged_Type (Target_Type)
10500 then
10501 -- Do not do any expansion in the access type case if the parent is a
10502 -- renaming, since this is an error situation which will be caught by
10503 -- Sem_Ch8, and the expansion can interfere with this error check.
10505 if Is_Access_Type (Target_Type) and then Is_Renamed_Object (N) then
10506 goto Done;
10507 end if;
10509 -- Otherwise, proceed with processing tagged conversion
10511 Tagged_Conversion : declare
10512 Actual_Op_Typ : Entity_Id;
10513 Actual_Targ_Typ : Entity_Id;
10514 Make_Conversion : Boolean := False;
10515 Root_Op_Typ : Entity_Id;
10517 procedure Make_Tag_Check (Targ_Typ : Entity_Id);
10518 -- Create a membership check to test whether Operand is a member
10519 -- of Targ_Typ. If the original Target_Type is an access, include
10520 -- a test for null value. The check is inserted at N.
10522 --------------------
10523 -- Make_Tag_Check --
10524 --------------------
10526 procedure Make_Tag_Check (Targ_Typ : Entity_Id) is
10527 Cond : Node_Id;
10529 begin
10530 -- Generate:
10531 -- [Constraint_Error
10532 -- when Operand /= null
10533 -- and then Operand.all not in Targ_Typ]
10535 if Is_Access_Type (Target_Type) then
10536 Cond :=
10537 Make_And_Then (Loc,
10538 Left_Opnd =>
10539 Make_Op_Ne (Loc,
10540 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
10541 Right_Opnd => Make_Null (Loc)),
10543 Right_Opnd =>
10544 Make_Not_In (Loc,
10545 Left_Opnd =>
10546 Make_Explicit_Dereference (Loc,
10547 Prefix => Duplicate_Subexpr_No_Checks (Operand)),
10548 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc)));
10550 -- Generate:
10551 -- [Constraint_Error when Operand not in Targ_Typ]
10553 else
10554 Cond :=
10555 Make_Not_In (Loc,
10556 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
10557 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc));
10558 end if;
10560 Insert_Action (N,
10561 Make_Raise_Constraint_Error (Loc,
10562 Condition => Cond,
10563 Reason => CE_Tag_Check_Failed));
10564 end Make_Tag_Check;
10566 -- Start of processing for Tagged_Conversion
10568 begin
10569 -- Handle entities from the limited view
10571 if Is_Access_Type (Operand_Type) then
10572 Actual_Op_Typ :=
10573 Available_View (Designated_Type (Operand_Type));
10574 else
10575 Actual_Op_Typ := Operand_Type;
10576 end if;
10578 if Is_Access_Type (Target_Type) then
10579 Actual_Targ_Typ :=
10580 Available_View (Designated_Type (Target_Type));
10581 else
10582 Actual_Targ_Typ := Target_Type;
10583 end if;
10585 Root_Op_Typ := Root_Type (Actual_Op_Typ);
10587 -- Ada 2005 (AI-251): Handle interface type conversion
10589 if Is_Interface (Actual_Op_Typ) then
10590 Expand_Interface_Conversion (N);
10591 goto Done;
10592 end if;
10594 if not Tag_Checks_Suppressed (Actual_Targ_Typ) then
10596 -- Create a runtime tag check for a downward class-wide type
10597 -- conversion.
10599 if Is_Class_Wide_Type (Actual_Op_Typ)
10600 and then Actual_Op_Typ /= Actual_Targ_Typ
10601 and then Root_Op_Typ /= Actual_Targ_Typ
10602 and then Is_Ancestor (Root_Op_Typ, Actual_Targ_Typ,
10603 Use_Full_View => True)
10604 then
10605 Make_Tag_Check (Class_Wide_Type (Actual_Targ_Typ));
10606 Make_Conversion := True;
10607 end if;
10609 -- AI05-0073: If the result subtype of the function is defined
10610 -- by an access_definition designating a specific tagged type
10611 -- T, a check is made that the result value is null or the tag
10612 -- of the object designated by the result value identifies T.
10613 -- Constraint_Error is raised if this check fails.
10615 if Nkind (Parent (N)) = N_Simple_Return_Statement then
10616 declare
10617 Func : Entity_Id;
10618 Func_Typ : Entity_Id;
10620 begin
10621 -- Climb scope stack looking for the enclosing function
10623 Func := Current_Scope;
10624 while Present (Func)
10625 and then Ekind (Func) /= E_Function
10626 loop
10627 Func := Scope (Func);
10628 end loop;
10630 -- The function's return subtype must be defined using
10631 -- an access definition.
10633 if Nkind (Result_Definition (Parent (Func))) =
10634 N_Access_Definition
10635 then
10636 Func_Typ := Directly_Designated_Type (Etype (Func));
10638 -- The return subtype denotes a specific tagged type,
10639 -- in other words, a non class-wide type.
10641 if Is_Tagged_Type (Func_Typ)
10642 and then not Is_Class_Wide_Type (Func_Typ)
10643 then
10644 Make_Tag_Check (Actual_Targ_Typ);
10645 Make_Conversion := True;
10646 end if;
10647 end if;
10648 end;
10649 end if;
10651 -- We have generated a tag check for either a class-wide type
10652 -- conversion or for AI05-0073.
10654 if Make_Conversion then
10655 declare
10656 Conv : Node_Id;
10657 begin
10658 Conv :=
10659 Make_Unchecked_Type_Conversion (Loc,
10660 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
10661 Expression => Relocate_Node (Expression (N)));
10662 Rewrite (N, Conv);
10663 Analyze_And_Resolve (N, Target_Type);
10664 end;
10665 end if;
10666 end if;
10667 end Tagged_Conversion;
10669 -- Case of other access type conversions
10671 elsif Is_Access_Type (Target_Type) then
10672 Apply_Constraint_Check (Operand, Target_Type);
10674 -- Case of conversions from a fixed-point type
10676 -- These conversions require special expansion and processing, found in
10677 -- the Exp_Fixd package. We ignore cases where Conversion_OK is set,
10678 -- since from a semantic point of view, these are simple integer
10679 -- conversions, which do not need further processing.
10681 elsif Is_Fixed_Point_Type (Operand_Type)
10682 and then not Conversion_OK (N)
10683 then
10684 -- We should never see universal fixed at this case, since the
10685 -- expansion of the constituent divide or multiply should have
10686 -- eliminated the explicit mention of universal fixed.
10688 pragma Assert (Operand_Type /= Universal_Fixed);
10690 -- Check for special case of the conversion to universal real that
10691 -- occurs as a result of the use of a round attribute. In this case,
10692 -- the real type for the conversion is taken from the target type of
10693 -- the Round attribute and the result must be marked as rounded.
10695 if Target_Type = Universal_Real
10696 and then Nkind (Parent (N)) = N_Attribute_Reference
10697 and then Attribute_Name (Parent (N)) = Name_Round
10698 then
10699 Set_Rounded_Result (N);
10700 Set_Etype (N, Etype (Parent (N)));
10701 end if;
10703 -- Otherwise do correct fixed-conversion, but skip these if the
10704 -- Conversion_OK flag is set, because from a semantic point of view
10705 -- these are simple integer conversions needing no further processing
10706 -- (the backend will simply treat them as integers).
10708 if not Conversion_OK (N) then
10709 if Is_Fixed_Point_Type (Etype (N)) then
10710 Expand_Convert_Fixed_To_Fixed (N);
10711 Real_Range_Check;
10713 elsif Is_Integer_Type (Etype (N)) then
10714 Expand_Convert_Fixed_To_Integer (N);
10716 else
10717 pragma Assert (Is_Floating_Point_Type (Etype (N)));
10718 Expand_Convert_Fixed_To_Float (N);
10719 Real_Range_Check;
10720 end if;
10721 end if;
10723 -- Case of conversions to a fixed-point type
10725 -- These conversions require special expansion and processing, found in
10726 -- the Exp_Fixd package. Again, ignore cases where Conversion_OK is set,
10727 -- since from a semantic point of view, these are simple integer
10728 -- conversions, which do not need further processing.
10730 elsif Is_Fixed_Point_Type (Target_Type)
10731 and then not Conversion_OK (N)
10732 then
10733 if Is_Integer_Type (Operand_Type) then
10734 Expand_Convert_Integer_To_Fixed (N);
10735 Real_Range_Check;
10736 else
10737 pragma Assert (Is_Floating_Point_Type (Operand_Type));
10738 Expand_Convert_Float_To_Fixed (N);
10739 Real_Range_Check;
10740 end if;
10742 -- Case of float-to-integer conversions
10744 -- We also handle float-to-fixed conversions with Conversion_OK set
10745 -- since semantically the fixed-point target is treated as though it
10746 -- were an integer in such cases.
10748 elsif Is_Floating_Point_Type (Operand_Type)
10749 and then
10750 (Is_Integer_Type (Target_Type)
10751 or else
10752 (Is_Fixed_Point_Type (Target_Type) and then Conversion_OK (N)))
10753 then
10754 -- One more check here, gcc is still not able to do conversions of
10755 -- this type with proper overflow checking, and so gigi is doing an
10756 -- approximation of what is required by doing floating-point compares
10757 -- with the end-point. But that can lose precision in some cases, and
10758 -- give a wrong result. Converting the operand to Universal_Real is
10759 -- helpful, but still does not catch all cases with 64-bit integers
10760 -- on targets with only 64-bit floats.
10762 -- The above comment seems obsoleted by Apply_Float_Conversion_Check
10763 -- Can this code be removed ???
10765 if Do_Range_Check (Operand) then
10766 Rewrite (Operand,
10767 Make_Type_Conversion (Loc,
10768 Subtype_Mark =>
10769 New_Occurrence_Of (Universal_Real, Loc),
10770 Expression =>
10771 Relocate_Node (Operand)));
10773 Set_Etype (Operand, Universal_Real);
10774 Enable_Range_Check (Operand);
10775 Set_Do_Range_Check (Expression (Operand), False);
10776 end if;
10778 -- Case of array conversions
10780 -- Expansion of array conversions, add required length/range checks but
10781 -- only do this if there is no change of representation. For handling of
10782 -- this case, see Handle_Changed_Representation.
10784 elsif Is_Array_Type (Target_Type) then
10785 if Is_Constrained (Target_Type) then
10786 Apply_Length_Check (Operand, Target_Type);
10787 else
10788 Apply_Range_Check (Operand, Target_Type);
10789 end if;
10791 Handle_Changed_Representation;
10793 -- Case of conversions of discriminated types
10795 -- Add required discriminant checks if target is constrained. Again this
10796 -- change is skipped if we have a change of representation.
10798 elsif Has_Discriminants (Target_Type)
10799 and then Is_Constrained (Target_Type)
10800 then
10801 Apply_Discriminant_Check (Operand, Target_Type);
10802 Handle_Changed_Representation;
10804 -- Case of all other record conversions. The only processing required
10805 -- is to check for a change of representation requiring the special
10806 -- assignment processing.
10808 elsif Is_Record_Type (Target_Type) then
10810 -- Ada 2005 (AI-216): Program_Error is raised when converting from
10811 -- a derived Unchecked_Union type to an unconstrained type that is
10812 -- not Unchecked_Union if the operand lacks inferable discriminants.
10814 if Is_Derived_Type (Operand_Type)
10815 and then Is_Unchecked_Union (Base_Type (Operand_Type))
10816 and then not Is_Constrained (Target_Type)
10817 and then not Is_Unchecked_Union (Base_Type (Target_Type))
10818 and then not Has_Inferable_Discriminants (Operand)
10819 then
10820 -- To prevent Gigi from generating illegal code, we generate a
10821 -- Program_Error node, but we give it the target type of the
10822 -- conversion (is this requirement documented somewhere ???)
10824 declare
10825 PE : constant Node_Id := Make_Raise_Program_Error (Loc,
10826 Reason => PE_Unchecked_Union_Restriction);
10828 begin
10829 Set_Etype (PE, Target_Type);
10830 Rewrite (N, PE);
10832 end;
10833 else
10834 Handle_Changed_Representation;
10835 end if;
10837 -- Case of conversions of enumeration types
10839 elsif Is_Enumeration_Type (Target_Type) then
10841 -- Special processing is required if there is a change of
10842 -- representation (from enumeration representation clauses).
10844 if not Same_Representation (Target_Type, Operand_Type) then
10846 -- Convert: x(y) to x'val (ytyp'val (y))
10848 Rewrite (N,
10849 Make_Attribute_Reference (Loc,
10850 Prefix => New_Occurrence_Of (Target_Type, Loc),
10851 Attribute_Name => Name_Val,
10852 Expressions => New_List (
10853 Make_Attribute_Reference (Loc,
10854 Prefix => New_Occurrence_Of (Operand_Type, Loc),
10855 Attribute_Name => Name_Pos,
10856 Expressions => New_List (Operand)))));
10858 Analyze_And_Resolve (N, Target_Type);
10859 end if;
10861 -- Case of conversions to floating-point
10863 elsif Is_Floating_Point_Type (Target_Type) then
10864 Real_Range_Check;
10865 end if;
10867 -- At this stage, either the conversion node has been transformed into
10868 -- some other equivalent expression, or left as a conversion that can be
10869 -- handled by Gigi, in the following cases:
10871 -- Conversions with no change of representation or type
10873 -- Numeric conversions involving integer, floating- and fixed-point
10874 -- values. Fixed-point values are allowed only if Conversion_OK is
10875 -- set, i.e. if the fixed-point values are to be treated as integers.
10877 -- No other conversions should be passed to Gigi
10879 -- Check: are these rules stated in sinfo??? if so, why restate here???
10881 -- The only remaining step is to generate a range check if we still have
10882 -- a type conversion at this stage and Do_Range_Check is set. For now we
10883 -- do this only for conversions of discrete types and for float-to-float
10884 -- conversions.
10886 if Nkind (N) = N_Type_Conversion then
10888 -- For now we only support floating-point cases where both source
10889 -- and target are floating-point types. Conversions where the source
10890 -- and target involve integer or fixed-point types are still TBD,
10891 -- though not clear whether those can even happen at this point, due
10892 -- to transformations above. ???
10894 if Is_Floating_Point_Type (Etype (N))
10895 and then Is_Floating_Point_Type (Etype (Expression (N)))
10896 then
10897 if Do_Range_Check (Expression (N))
10898 and then Is_Floating_Point_Type (Target_Type)
10899 then
10900 Generate_Range_Check
10901 (Expression (N), Target_Type, CE_Range_Check_Failed);
10902 end if;
10904 -- Discrete-to-discrete conversions
10906 elsif Is_Discrete_Type (Etype (N)) then
10907 declare
10908 Expr : constant Node_Id := Expression (N);
10909 Ftyp : Entity_Id;
10910 Ityp : Entity_Id;
10912 begin
10913 if Do_Range_Check (Expr)
10914 and then Is_Discrete_Type (Etype (Expr))
10915 then
10916 Set_Do_Range_Check (Expr, False);
10918 -- Before we do a range check, we have to deal with treating
10919 -- a fixed-point operand as an integer. The way we do this
10920 -- is simply to do an unchecked conversion to an appropriate
10921 -- integer type large enough to hold the result.
10923 -- This code is not active yet, because we are only dealing
10924 -- with discrete types so far ???
10926 if Nkind (Expr) in N_Has_Treat_Fixed_As_Integer
10927 and then Treat_Fixed_As_Integer (Expr)
10928 then
10929 Ftyp := Base_Type (Etype (Expr));
10931 if Esize (Ftyp) >= Esize (Standard_Integer) then
10932 Ityp := Standard_Long_Long_Integer;
10933 else
10934 Ityp := Standard_Integer;
10935 end if;
10937 Rewrite (Expr, Unchecked_Convert_To (Ityp, Expr));
10938 end if;
10940 -- Reset overflow flag, since the range check will include
10941 -- dealing with possible overflow, and generate the check.
10942 -- If Address is either a source type or target type,
10943 -- suppress range check to avoid typing anomalies when
10944 -- it is a visible integer type.
10946 Set_Do_Overflow_Check (N, False);
10948 if not Is_Descendent_Of_Address (Etype (Expr))
10949 and then not Is_Descendent_Of_Address (Target_Type)
10950 then
10951 Generate_Range_Check
10952 (Expr, Target_Type, CE_Range_Check_Failed);
10953 end if;
10954 end if;
10955 end;
10956 end if;
10957 end if;
10959 -- Here at end of processing
10961 <<Done>>
10962 -- Apply predicate check if required. Note that we can't just call
10963 -- Apply_Predicate_Check here, because the type looks right after
10964 -- the conversion and it would omit the check. The Comes_From_Source
10965 -- guard is necessary to prevent infinite recursions when we generate
10966 -- internal conversions for the purpose of checking predicates.
10968 if Present (Predicate_Function (Target_Type))
10969 and then Target_Type /= Operand_Type
10970 and then Comes_From_Source (N)
10971 then
10972 declare
10973 New_Expr : constant Node_Id := Duplicate_Subexpr (N);
10975 begin
10976 -- Avoid infinite recursion on the subsequent expansion of
10977 -- of the copy of the original type conversion.
10979 Set_Comes_From_Source (New_Expr, False);
10980 Insert_Action (N, Make_Predicate_Check (Target_Type, New_Expr));
10981 end;
10982 end if;
10983 end Expand_N_Type_Conversion;
10985 -----------------------------------
10986 -- Expand_N_Unchecked_Expression --
10987 -----------------------------------
10989 -- Remove the unchecked expression node from the tree. Its job was simply
10990 -- to make sure that its constituent expression was handled with checks
10991 -- off, and now that that is done, we can remove it from the tree, and
10992 -- indeed must, since Gigi does not expect to see these nodes.
10994 procedure Expand_N_Unchecked_Expression (N : Node_Id) is
10995 Exp : constant Node_Id := Expression (N);
10996 begin
10997 Set_Assignment_OK (Exp, Assignment_OK (N) or else Assignment_OK (Exp));
10998 Rewrite (N, Exp);
10999 end Expand_N_Unchecked_Expression;
11001 ----------------------------------------
11002 -- Expand_N_Unchecked_Type_Conversion --
11003 ----------------------------------------
11005 -- If this cannot be handled by Gigi and we haven't already made a
11006 -- temporary for it, do it now.
11008 procedure Expand_N_Unchecked_Type_Conversion (N : Node_Id) is
11009 Target_Type : constant Entity_Id := Etype (N);
11010 Operand : constant Node_Id := Expression (N);
11011 Operand_Type : constant Entity_Id := Etype (Operand);
11013 begin
11014 -- Nothing at all to do if conversion is to the identical type so remove
11015 -- the conversion completely, it is useless, except that it may carry
11016 -- an Assignment_OK indication which must be propagated to the operand.
11018 if Operand_Type = Target_Type then
11020 -- Code duplicates Expand_N_Unchecked_Expression above, factor???
11022 if Assignment_OK (N) then
11023 Set_Assignment_OK (Operand);
11024 end if;
11026 Rewrite (N, Relocate_Node (Operand));
11027 return;
11028 end if;
11030 -- If we have a conversion of a compile time known value to a target
11031 -- type and the value is in range of the target type, then we can simply
11032 -- replace the construct by an integer literal of the correct type. We
11033 -- only apply this to integer types being converted. Possibly it may
11034 -- apply in other cases, but it is too much trouble to worry about.
11036 -- Note that we do not do this transformation if the Kill_Range_Check
11037 -- flag is set, since then the value may be outside the expected range.
11038 -- This happens in the Normalize_Scalars case.
11040 -- We also skip this if either the target or operand type is biased
11041 -- because in this case, the unchecked conversion is supposed to
11042 -- preserve the bit pattern, not the integer value.
11044 if Is_Integer_Type (Target_Type)
11045 and then not Has_Biased_Representation (Target_Type)
11046 and then Is_Integer_Type (Operand_Type)
11047 and then not Has_Biased_Representation (Operand_Type)
11048 and then Compile_Time_Known_Value (Operand)
11049 and then not Kill_Range_Check (N)
11050 then
11051 declare
11052 Val : constant Uint := Expr_Value (Operand);
11054 begin
11055 if Compile_Time_Known_Value (Type_Low_Bound (Target_Type))
11056 and then
11057 Compile_Time_Known_Value (Type_High_Bound (Target_Type))
11058 and then
11059 Val >= Expr_Value (Type_Low_Bound (Target_Type))
11060 and then
11061 Val <= Expr_Value (Type_High_Bound (Target_Type))
11062 then
11063 Rewrite (N, Make_Integer_Literal (Sloc (N), Val));
11065 -- If Address is the target type, just set the type to avoid a
11066 -- spurious type error on the literal when Address is a visible
11067 -- integer type.
11069 if Is_Descendent_Of_Address (Target_Type) then
11070 Set_Etype (N, Target_Type);
11071 else
11072 Analyze_And_Resolve (N, Target_Type);
11073 end if;
11075 return;
11076 end if;
11077 end;
11078 end if;
11080 -- Nothing to do if conversion is safe
11082 if Safe_Unchecked_Type_Conversion (N) then
11083 return;
11084 end if;
11086 -- Otherwise force evaluation unless Assignment_OK flag is set (this
11087 -- flag indicates ??? More comments needed here)
11089 if Assignment_OK (N) then
11090 null;
11091 else
11092 Force_Evaluation (N);
11093 end if;
11094 end Expand_N_Unchecked_Type_Conversion;
11096 ----------------------------
11097 -- Expand_Record_Equality --
11098 ----------------------------
11100 -- For non-variant records, Equality is expanded when needed into:
11102 -- and then Lhs.Discr1 = Rhs.Discr1
11103 -- and then ...
11104 -- and then Lhs.Discrn = Rhs.Discrn
11105 -- and then Lhs.Cmp1 = Rhs.Cmp1
11106 -- and then ...
11107 -- and then Lhs.Cmpn = Rhs.Cmpn
11109 -- The expression is folded by the back-end for adjacent fields. This
11110 -- function is called for tagged record in only one occasion: for imple-
11111 -- menting predefined primitive equality (see Predefined_Primitives_Bodies)
11112 -- otherwise the primitive "=" is used directly.
11114 function Expand_Record_Equality
11115 (Nod : Node_Id;
11116 Typ : Entity_Id;
11117 Lhs : Node_Id;
11118 Rhs : Node_Id;
11119 Bodies : List_Id) return Node_Id
11121 Loc : constant Source_Ptr := Sloc (Nod);
11123 Result : Node_Id;
11124 C : Entity_Id;
11126 First_Time : Boolean := True;
11128 function Element_To_Compare (C : Entity_Id) return Entity_Id;
11129 -- Return the next discriminant or component to compare, starting with
11130 -- C, skipping inherited components.
11132 ------------------------
11133 -- Element_To_Compare --
11134 ------------------------
11136 function Element_To_Compare (C : Entity_Id) return Entity_Id is
11137 Comp : Entity_Id;
11139 begin
11140 Comp := C;
11141 loop
11142 -- Exit loop when the next element to be compared is found, or
11143 -- there is no more such element.
11145 exit when No (Comp);
11147 exit when Ekind_In (Comp, E_Discriminant, E_Component)
11148 and then not (
11150 -- Skip inherited components
11152 -- Note: for a tagged type, we always generate the "=" primitive
11153 -- for the base type (not on the first subtype), so the test for
11154 -- Comp /= Original_Record_Component (Comp) is True for
11155 -- inherited components only.
11157 (Is_Tagged_Type (Typ)
11158 and then Comp /= Original_Record_Component (Comp))
11160 -- Skip _Tag
11162 or else Chars (Comp) = Name_uTag
11164 -- The .NET/JVM version of type Root_Controlled contains two
11165 -- fields which should not be considered part of the object. To
11166 -- achieve proper equiality between two controlled objects on
11167 -- .NET/JVM, skip _Parent whenever it has type Root_Controlled.
11169 or else (Chars (Comp) = Name_uParent
11170 and then VM_Target /= No_VM
11171 and then Etype (Comp) = RTE (RE_Root_Controlled))
11173 -- Skip interface elements (secondary tags???)
11175 or else Is_Interface (Etype (Comp)));
11177 Next_Entity (Comp);
11178 end loop;
11180 return Comp;
11181 end Element_To_Compare;
11183 -- Start of processing for Expand_Record_Equality
11185 begin
11186 -- Generates the following code: (assuming that Typ has one Discr and
11187 -- component C2 is also a record)
11189 -- True
11190 -- and then Lhs.Discr1 = Rhs.Discr1
11191 -- and then Lhs.C1 = Rhs.C1
11192 -- and then Lhs.C2.C1=Rhs.C2.C1 and then ... Lhs.C2.Cn=Rhs.C2.Cn
11193 -- and then ...
11194 -- and then Lhs.Cmpn = Rhs.Cmpn
11196 Result := New_Occurrence_Of (Standard_True, Loc);
11197 C := Element_To_Compare (First_Entity (Typ));
11198 while Present (C) loop
11199 declare
11200 New_Lhs : Node_Id;
11201 New_Rhs : Node_Id;
11202 Check : Node_Id;
11204 begin
11205 if First_Time then
11206 First_Time := False;
11207 New_Lhs := Lhs;
11208 New_Rhs := Rhs;
11209 else
11210 New_Lhs := New_Copy_Tree (Lhs);
11211 New_Rhs := New_Copy_Tree (Rhs);
11212 end if;
11214 Check :=
11215 Expand_Composite_Equality (Nod, Etype (C),
11216 Lhs =>
11217 Make_Selected_Component (Loc,
11218 Prefix => New_Lhs,
11219 Selector_Name => New_Occurrence_Of (C, Loc)),
11220 Rhs =>
11221 Make_Selected_Component (Loc,
11222 Prefix => New_Rhs,
11223 Selector_Name => New_Occurrence_Of (C, Loc)),
11224 Bodies => Bodies);
11226 -- If some (sub)component is an unchecked_union, the whole
11227 -- operation will raise program error.
11229 if Nkind (Check) = N_Raise_Program_Error then
11230 Result := Check;
11231 Set_Etype (Result, Standard_Boolean);
11232 exit;
11233 else
11234 Result :=
11235 Make_And_Then (Loc,
11236 Left_Opnd => Result,
11237 Right_Opnd => Check);
11238 end if;
11239 end;
11241 C := Element_To_Compare (Next_Entity (C));
11242 end loop;
11244 return Result;
11245 end Expand_Record_Equality;
11247 ---------------------------
11248 -- Expand_Set_Membership --
11249 ---------------------------
11251 procedure Expand_Set_Membership (N : Node_Id) is
11252 Lop : constant Node_Id := Left_Opnd (N);
11253 Alt : Node_Id;
11254 Res : Node_Id;
11256 function Make_Cond (Alt : Node_Id) return Node_Id;
11257 -- If the alternative is a subtype mark, create a simple membership
11258 -- test. Otherwise create an equality test for it.
11260 ---------------
11261 -- Make_Cond --
11262 ---------------
11264 function Make_Cond (Alt : Node_Id) return Node_Id is
11265 Cond : Node_Id;
11266 L : constant Node_Id := New_Copy (Lop);
11267 R : constant Node_Id := Relocate_Node (Alt);
11269 begin
11270 if (Is_Entity_Name (Alt) and then Is_Type (Entity (Alt)))
11271 or else Nkind (Alt) = N_Range
11272 then
11273 Cond :=
11274 Make_In (Sloc (Alt),
11275 Left_Opnd => L,
11276 Right_Opnd => R);
11277 else
11278 Cond :=
11279 Make_Op_Eq (Sloc (Alt),
11280 Left_Opnd => L,
11281 Right_Opnd => R);
11282 end if;
11284 return Cond;
11285 end Make_Cond;
11287 -- Start of processing for Expand_Set_Membership
11289 begin
11290 Remove_Side_Effects (Lop);
11292 Alt := Last (Alternatives (N));
11293 Res := Make_Cond (Alt);
11295 Prev (Alt);
11296 while Present (Alt) loop
11297 Res :=
11298 Make_Or_Else (Sloc (Alt),
11299 Left_Opnd => Make_Cond (Alt),
11300 Right_Opnd => Res);
11301 Prev (Alt);
11302 end loop;
11304 Rewrite (N, Res);
11305 Analyze_And_Resolve (N, Standard_Boolean);
11306 end Expand_Set_Membership;
11308 -----------------------------------
11309 -- Expand_Short_Circuit_Operator --
11310 -----------------------------------
11312 -- Deal with special expansion if actions are present for the right operand
11313 -- and deal with optimizing case of arguments being True or False. We also
11314 -- deal with the special case of non-standard boolean values.
11316 procedure Expand_Short_Circuit_Operator (N : Node_Id) is
11317 Loc : constant Source_Ptr := Sloc (N);
11318 Typ : constant Entity_Id := Etype (N);
11319 Left : constant Node_Id := Left_Opnd (N);
11320 Right : constant Node_Id := Right_Opnd (N);
11321 LocR : constant Source_Ptr := Sloc (Right);
11322 Actlist : List_Id;
11324 Shortcut_Value : constant Boolean := Nkind (N) = N_Or_Else;
11325 Shortcut_Ent : constant Entity_Id := Boolean_Literals (Shortcut_Value);
11326 -- If Left = Shortcut_Value then Right need not be evaluated
11328 begin
11329 -- Deal with non-standard booleans
11331 if Is_Boolean_Type (Typ) then
11332 Adjust_Condition (Left);
11333 Adjust_Condition (Right);
11334 Set_Etype (N, Standard_Boolean);
11335 end if;
11337 -- Check for cases where left argument is known to be True or False
11339 if Compile_Time_Known_Value (Left) then
11341 -- Mark SCO for left condition as compile time known
11343 if Generate_SCO and then Comes_From_Source (Left) then
11344 Set_SCO_Condition (Left, Expr_Value_E (Left) = Standard_True);
11345 end if;
11347 -- Rewrite True AND THEN Right / False OR ELSE Right to Right.
11348 -- Any actions associated with Right will be executed unconditionally
11349 -- and can thus be inserted into the tree unconditionally.
11351 if Expr_Value_E (Left) /= Shortcut_Ent then
11352 if Present (Actions (N)) then
11353 Insert_Actions (N, Actions (N));
11354 end if;
11356 Rewrite (N, Right);
11358 -- Rewrite False AND THEN Right / True OR ELSE Right to Left.
11359 -- In this case we can forget the actions associated with Right,
11360 -- since they will never be executed.
11362 else
11363 Kill_Dead_Code (Right);
11364 Kill_Dead_Code (Actions (N));
11365 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
11366 end if;
11368 Adjust_Result_Type (N, Typ);
11369 return;
11370 end if;
11372 -- If Actions are present for the right operand, we have to do some
11373 -- special processing. We can't just let these actions filter back into
11374 -- code preceding the short circuit (which is what would have happened
11375 -- if we had not trapped them in the short-circuit form), since they
11376 -- must only be executed if the right operand of the short circuit is
11377 -- executed and not otherwise.
11379 if Present (Actions (N)) then
11380 Actlist := Actions (N);
11382 -- We now use an Expression_With_Actions node for the right operand
11383 -- of the short-circuit form. Note that this solves the traceability
11384 -- problems for coverage analysis.
11386 Rewrite (Right,
11387 Make_Expression_With_Actions (LocR,
11388 Expression => Relocate_Node (Right),
11389 Actions => Actlist));
11390 Set_Actions (N, No_List);
11391 Analyze_And_Resolve (Right, Standard_Boolean);
11393 Adjust_Result_Type (N, Typ);
11394 return;
11395 end if;
11397 -- No actions present, check for cases of right argument True/False
11399 if Compile_Time_Known_Value (Right) then
11401 -- Mark SCO for left condition as compile time known
11403 if Generate_SCO and then Comes_From_Source (Right) then
11404 Set_SCO_Condition (Right, Expr_Value_E (Right) = Standard_True);
11405 end if;
11407 -- Change (Left and then True), (Left or else False) to Left.
11408 -- Note that we know there are no actions associated with the right
11409 -- operand, since we just checked for this case above.
11411 if Expr_Value_E (Right) /= Shortcut_Ent then
11412 Rewrite (N, Left);
11414 -- Change (Left and then False), (Left or else True) to Right,
11415 -- making sure to preserve any side effects associated with the Left
11416 -- operand.
11418 else
11419 Remove_Side_Effects (Left);
11420 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
11421 end if;
11422 end if;
11424 Adjust_Result_Type (N, Typ);
11425 end Expand_Short_Circuit_Operator;
11427 -------------------------------------
11428 -- Fixup_Universal_Fixed_Operation --
11429 -------------------------------------
11431 procedure Fixup_Universal_Fixed_Operation (N : Node_Id) is
11432 Conv : constant Node_Id := Parent (N);
11434 begin
11435 -- We must have a type conversion immediately above us
11437 pragma Assert (Nkind (Conv) = N_Type_Conversion);
11439 -- Normally the type conversion gives our target type. The exception
11440 -- occurs in the case of the Round attribute, where the conversion
11441 -- will be to universal real, and our real type comes from the Round
11442 -- attribute (as well as an indication that we must round the result)
11444 if Nkind (Parent (Conv)) = N_Attribute_Reference
11445 and then Attribute_Name (Parent (Conv)) = Name_Round
11446 then
11447 Set_Etype (N, Etype (Parent (Conv)));
11448 Set_Rounded_Result (N);
11450 -- Normal case where type comes from conversion above us
11452 else
11453 Set_Etype (N, Etype (Conv));
11454 end if;
11455 end Fixup_Universal_Fixed_Operation;
11457 ---------------------------------
11458 -- Has_Inferable_Discriminants --
11459 ---------------------------------
11461 function Has_Inferable_Discriminants (N : Node_Id) return Boolean is
11463 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean;
11464 -- Determines whether the left-most prefix of a selected component is a
11465 -- formal parameter in a subprogram. Assumes N is a selected component.
11467 --------------------------------
11468 -- Prefix_Is_Formal_Parameter --
11469 --------------------------------
11471 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean is
11472 Sel_Comp : Node_Id;
11474 begin
11475 -- Move to the left-most prefix by climbing up the tree
11477 Sel_Comp := N;
11478 while Present (Parent (Sel_Comp))
11479 and then Nkind (Parent (Sel_Comp)) = N_Selected_Component
11480 loop
11481 Sel_Comp := Parent (Sel_Comp);
11482 end loop;
11484 return Ekind (Entity (Prefix (Sel_Comp))) in Formal_Kind;
11485 end Prefix_Is_Formal_Parameter;
11487 -- Start of processing for Has_Inferable_Discriminants
11489 begin
11490 -- For selected components, the subtype of the selector must be a
11491 -- constrained Unchecked_Union. If the component is subject to a
11492 -- per-object constraint, then the enclosing object must have inferable
11493 -- discriminants.
11495 if Nkind (N) = N_Selected_Component then
11496 if Has_Per_Object_Constraint (Entity (Selector_Name (N))) then
11498 -- A small hack. If we have a per-object constrained selected
11499 -- component of a formal parameter, return True since we do not
11500 -- know the actual parameter association yet.
11502 if Prefix_Is_Formal_Parameter (N) then
11503 return True;
11505 -- Otherwise, check the enclosing object and the selector
11507 else
11508 return Has_Inferable_Discriminants (Prefix (N))
11509 and then Has_Inferable_Discriminants (Selector_Name (N));
11510 end if;
11512 -- The call to Has_Inferable_Discriminants will determine whether
11513 -- the selector has a constrained Unchecked_Union nominal type.
11515 else
11516 return Has_Inferable_Discriminants (Selector_Name (N));
11517 end if;
11519 -- A qualified expression has inferable discriminants if its subtype
11520 -- mark is a constrained Unchecked_Union subtype.
11522 elsif Nkind (N) = N_Qualified_Expression then
11523 return Is_Unchecked_Union (Etype (Subtype_Mark (N)))
11524 and then Is_Constrained (Etype (Subtype_Mark (N)));
11526 -- For all other names, it is sufficient to have a constrained
11527 -- Unchecked_Union nominal subtype.
11529 else
11530 return Is_Unchecked_Union (Base_Type (Etype (N)))
11531 and then Is_Constrained (Etype (N));
11532 end if;
11533 end Has_Inferable_Discriminants;
11535 -------------------------------
11536 -- Insert_Dereference_Action --
11537 -------------------------------
11539 procedure Insert_Dereference_Action (N : Node_Id) is
11541 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean;
11542 -- Return true if type of P is derived from Checked_Pool;
11544 -----------------------------
11545 -- Is_Checked_Storage_Pool --
11546 -----------------------------
11548 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean is
11549 T : Entity_Id;
11551 begin
11552 if No (P) then
11553 return False;
11554 end if;
11556 T := Etype (P);
11557 while T /= Etype (T) loop
11558 if Is_RTE (T, RE_Checked_Pool) then
11559 return True;
11560 else
11561 T := Etype (T);
11562 end if;
11563 end loop;
11565 return False;
11566 end Is_Checked_Storage_Pool;
11568 -- Local variables
11570 Typ : constant Entity_Id := Etype (N);
11571 Desig : constant Entity_Id := Available_View (Designated_Type (Typ));
11572 Loc : constant Source_Ptr := Sloc (N);
11573 Pool : constant Entity_Id := Associated_Storage_Pool (Typ);
11574 Pnod : constant Node_Id := Parent (N);
11576 Addr : Entity_Id;
11577 Alig : Entity_Id;
11578 Deref : Node_Id;
11579 Size : Entity_Id;
11580 Size_Bits : Node_Id;
11581 Stmt : Node_Id;
11583 -- Start of processing for Insert_Dereference_Action
11585 begin
11586 pragma Assert (Nkind (Pnod) = N_Explicit_Dereference);
11588 -- Do not re-expand a dereference which has already been processed by
11589 -- this routine.
11591 if Has_Dereference_Action (Pnod) then
11592 return;
11594 -- Do not perform this type of expansion for internally-generated
11595 -- dereferences.
11597 elsif not Comes_From_Source (Original_Node (Pnod)) then
11598 return;
11600 -- A dereference action is only applicable to objects which have been
11601 -- allocated on a checked pool.
11603 elsif not Is_Checked_Storage_Pool (Pool) then
11604 return;
11605 end if;
11607 -- Extract the address of the dereferenced object. Generate:
11609 -- Addr : System.Address := <N>'Pool_Address;
11611 Addr := Make_Temporary (Loc, 'P');
11613 Insert_Action (N,
11614 Make_Object_Declaration (Loc,
11615 Defining_Identifier => Addr,
11616 Object_Definition =>
11617 New_Occurrence_Of (RTE (RE_Address), Loc),
11618 Expression =>
11619 Make_Attribute_Reference (Loc,
11620 Prefix => Duplicate_Subexpr_Move_Checks (N),
11621 Attribute_Name => Name_Pool_Address)));
11623 -- Calculate the size of the dereferenced object. Generate:
11625 -- Size : Storage_Count := <N>.all'Size / Storage_Unit;
11627 Deref :=
11628 Make_Explicit_Dereference (Loc,
11629 Prefix => Duplicate_Subexpr_Move_Checks (N));
11630 Set_Has_Dereference_Action (Deref);
11632 Size_Bits :=
11633 Make_Attribute_Reference (Loc,
11634 Prefix => Deref,
11635 Attribute_Name => Name_Size);
11637 -- Special case of an unconstrained array: need to add descriptor size
11639 if Is_Array_Type (Desig)
11640 and then not Is_Constrained (First_Subtype (Desig))
11641 then
11642 Size_Bits :=
11643 Make_Op_Add (Loc,
11644 Left_Opnd =>
11645 Make_Attribute_Reference (Loc,
11646 Prefix =>
11647 New_Occurrence_Of (First_Subtype (Desig), Loc),
11648 Attribute_Name => Name_Descriptor_Size),
11649 Right_Opnd => Size_Bits);
11650 end if;
11652 Size := Make_Temporary (Loc, 'S');
11653 Insert_Action (N,
11654 Make_Object_Declaration (Loc,
11655 Defining_Identifier => Size,
11656 Object_Definition =>
11657 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
11658 Expression =>
11659 Make_Op_Divide (Loc,
11660 Left_Opnd => Size_Bits,
11661 Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit))));
11663 -- Calculate the alignment of the dereferenced object. Generate:
11664 -- Alig : constant Storage_Count := <N>.all'Alignment;
11666 Deref :=
11667 Make_Explicit_Dereference (Loc,
11668 Prefix => Duplicate_Subexpr_Move_Checks (N));
11669 Set_Has_Dereference_Action (Deref);
11671 Alig := Make_Temporary (Loc, 'A');
11672 Insert_Action (N,
11673 Make_Object_Declaration (Loc,
11674 Defining_Identifier => Alig,
11675 Object_Definition =>
11676 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
11677 Expression =>
11678 Make_Attribute_Reference (Loc,
11679 Prefix => Deref,
11680 Attribute_Name => Name_Alignment)));
11682 -- A dereference of a controlled object requires special processing. The
11683 -- finalization machinery requests additional space from the underlying
11684 -- pool to allocate and hide two pointers. As a result, a checked pool
11685 -- may mark the wrong memory as valid. Since checked pools do not have
11686 -- knowledge of hidden pointers, we have to bring the two pointers back
11687 -- in view in order to restore the original state of the object.
11689 if Needs_Finalization (Desig) then
11691 -- Adjust the address and size of the dereferenced object. Generate:
11692 -- Adjust_Controlled_Dereference (Addr, Size, Alig);
11694 Stmt :=
11695 Make_Procedure_Call_Statement (Loc,
11696 Name =>
11697 New_Occurrence_Of (RTE (RE_Adjust_Controlled_Dereference), Loc),
11698 Parameter_Associations => New_List (
11699 New_Occurrence_Of (Addr, Loc),
11700 New_Occurrence_Of (Size, Loc),
11701 New_Occurrence_Of (Alig, Loc)));
11703 -- Class-wide types complicate things because we cannot determine
11704 -- statically whether the actual object is truly controlled. We must
11705 -- generate a runtime check to detect this property. Generate:
11707 -- if Needs_Finalization (<N>.all'Tag) then
11708 -- <Stmt>;
11709 -- end if;
11711 if Is_Class_Wide_Type (Desig) then
11712 Deref :=
11713 Make_Explicit_Dereference (Loc,
11714 Prefix => Duplicate_Subexpr_Move_Checks (N));
11715 Set_Has_Dereference_Action (Deref);
11717 Stmt :=
11718 Make_Implicit_If_Statement (N,
11719 Condition =>
11720 Make_Function_Call (Loc,
11721 Name =>
11722 New_Occurrence_Of (RTE (RE_Needs_Finalization), Loc),
11723 Parameter_Associations => New_List (
11724 Make_Attribute_Reference (Loc,
11725 Prefix => Deref,
11726 Attribute_Name => Name_Tag))),
11727 Then_Statements => New_List (Stmt));
11728 end if;
11730 Insert_Action (N, Stmt);
11731 end if;
11733 -- Generate:
11734 -- Dereference (Pool, Addr, Size, Alig);
11736 Insert_Action (N,
11737 Make_Procedure_Call_Statement (Loc,
11738 Name =>
11739 New_Occurrence_Of
11740 (Find_Prim_Op (Etype (Pool), Name_Dereference), Loc),
11741 Parameter_Associations => New_List (
11742 New_Occurrence_Of (Pool, Loc),
11743 New_Occurrence_Of (Addr, Loc),
11744 New_Occurrence_Of (Size, Loc),
11745 New_Occurrence_Of (Alig, Loc))));
11747 -- Mark the explicit dereference as processed to avoid potential
11748 -- infinite expansion.
11750 Set_Has_Dereference_Action (Pnod);
11752 exception
11753 when RE_Not_Available =>
11754 return;
11755 end Insert_Dereference_Action;
11757 --------------------------------
11758 -- Integer_Promotion_Possible --
11759 --------------------------------
11761 function Integer_Promotion_Possible (N : Node_Id) return Boolean is
11762 Operand : constant Node_Id := Expression (N);
11763 Operand_Type : constant Entity_Id := Etype (Operand);
11764 Root_Operand_Type : constant Entity_Id := Root_Type (Operand_Type);
11766 begin
11767 pragma Assert (Nkind (N) = N_Type_Conversion);
11769 return
11771 -- We only do the transformation for source constructs. We assume
11772 -- that the expander knows what it is doing when it generates code.
11774 Comes_From_Source (N)
11776 -- If the operand type is Short_Integer or Short_Short_Integer,
11777 -- then we will promote to Integer, which is available on all
11778 -- targets, and is sufficient to ensure no intermediate overflow.
11779 -- Furthermore it is likely to be as efficient or more efficient
11780 -- than using the smaller type for the computation so we do this
11781 -- unconditionally.
11783 and then
11784 (Root_Operand_Type = Base_Type (Standard_Short_Integer)
11785 or else
11786 Root_Operand_Type = Base_Type (Standard_Short_Short_Integer))
11788 -- Test for interesting operation, which includes addition,
11789 -- division, exponentiation, multiplication, subtraction, absolute
11790 -- value and unary negation. Unary "+" is omitted since it is a
11791 -- no-op and thus can't overflow.
11793 and then Nkind_In (Operand, N_Op_Abs,
11794 N_Op_Add,
11795 N_Op_Divide,
11796 N_Op_Expon,
11797 N_Op_Minus,
11798 N_Op_Multiply,
11799 N_Op_Subtract);
11800 end Integer_Promotion_Possible;
11802 ------------------------------
11803 -- Make_Array_Comparison_Op --
11804 ------------------------------
11806 -- This is a hand-coded expansion of the following generic function:
11808 -- generic
11809 -- type elem is (<>);
11810 -- type index is (<>);
11811 -- type a is array (index range <>) of elem;
11813 -- function Gnnn (X : a; Y: a) return boolean is
11814 -- J : index := Y'first;
11816 -- begin
11817 -- if X'length = 0 then
11818 -- return false;
11820 -- elsif Y'length = 0 then
11821 -- return true;
11823 -- else
11824 -- for I in X'range loop
11825 -- if X (I) = Y (J) then
11826 -- if J = Y'last then
11827 -- exit;
11828 -- else
11829 -- J := index'succ (J);
11830 -- end if;
11832 -- else
11833 -- return X (I) > Y (J);
11834 -- end if;
11835 -- end loop;
11837 -- return X'length > Y'length;
11838 -- end if;
11839 -- end Gnnn;
11841 -- Note that since we are essentially doing this expansion by hand, we
11842 -- do not need to generate an actual or formal generic part, just the
11843 -- instantiated function itself.
11845 -- Perhaps we could have the actual generic available in the run-time,
11846 -- obtained by rtsfind, and actually expand a real instantiation ???
11848 function Make_Array_Comparison_Op
11849 (Typ : Entity_Id;
11850 Nod : Node_Id) return Node_Id
11852 Loc : constant Source_Ptr := Sloc (Nod);
11854 X : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uX);
11855 Y : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uY);
11856 I : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uI);
11857 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
11859 Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
11861 Loop_Statement : Node_Id;
11862 Loop_Body : Node_Id;
11863 If_Stat : Node_Id;
11864 Inner_If : Node_Id;
11865 Final_Expr : Node_Id;
11866 Func_Body : Node_Id;
11867 Func_Name : Entity_Id;
11868 Formals : List_Id;
11869 Length1 : Node_Id;
11870 Length2 : Node_Id;
11872 begin
11873 -- if J = Y'last then
11874 -- exit;
11875 -- else
11876 -- J := index'succ (J);
11877 -- end if;
11879 Inner_If :=
11880 Make_Implicit_If_Statement (Nod,
11881 Condition =>
11882 Make_Op_Eq (Loc,
11883 Left_Opnd => New_Occurrence_Of (J, Loc),
11884 Right_Opnd =>
11885 Make_Attribute_Reference (Loc,
11886 Prefix => New_Occurrence_Of (Y, Loc),
11887 Attribute_Name => Name_Last)),
11889 Then_Statements => New_List (
11890 Make_Exit_Statement (Loc)),
11892 Else_Statements =>
11893 New_List (
11894 Make_Assignment_Statement (Loc,
11895 Name => New_Occurrence_Of (J, Loc),
11896 Expression =>
11897 Make_Attribute_Reference (Loc,
11898 Prefix => New_Occurrence_Of (Index, Loc),
11899 Attribute_Name => Name_Succ,
11900 Expressions => New_List (New_Occurrence_Of (J, Loc))))));
11902 -- if X (I) = Y (J) then
11903 -- if ... end if;
11904 -- else
11905 -- return X (I) > Y (J);
11906 -- end if;
11908 Loop_Body :=
11909 Make_Implicit_If_Statement (Nod,
11910 Condition =>
11911 Make_Op_Eq (Loc,
11912 Left_Opnd =>
11913 Make_Indexed_Component (Loc,
11914 Prefix => New_Occurrence_Of (X, Loc),
11915 Expressions => New_List (New_Occurrence_Of (I, Loc))),
11917 Right_Opnd =>
11918 Make_Indexed_Component (Loc,
11919 Prefix => New_Occurrence_Of (Y, Loc),
11920 Expressions => New_List (New_Occurrence_Of (J, Loc)))),
11922 Then_Statements => New_List (Inner_If),
11924 Else_Statements => New_List (
11925 Make_Simple_Return_Statement (Loc,
11926 Expression =>
11927 Make_Op_Gt (Loc,
11928 Left_Opnd =>
11929 Make_Indexed_Component (Loc,
11930 Prefix => New_Occurrence_Of (X, Loc),
11931 Expressions => New_List (New_Occurrence_Of (I, Loc))),
11933 Right_Opnd =>
11934 Make_Indexed_Component (Loc,
11935 Prefix => New_Occurrence_Of (Y, Loc),
11936 Expressions => New_List (
11937 New_Occurrence_Of (J, Loc)))))));
11939 -- for I in X'range loop
11940 -- if ... end if;
11941 -- end loop;
11943 Loop_Statement :=
11944 Make_Implicit_Loop_Statement (Nod,
11945 Identifier => Empty,
11947 Iteration_Scheme =>
11948 Make_Iteration_Scheme (Loc,
11949 Loop_Parameter_Specification =>
11950 Make_Loop_Parameter_Specification (Loc,
11951 Defining_Identifier => I,
11952 Discrete_Subtype_Definition =>
11953 Make_Attribute_Reference (Loc,
11954 Prefix => New_Occurrence_Of (X, Loc),
11955 Attribute_Name => Name_Range))),
11957 Statements => New_List (Loop_Body));
11959 -- if X'length = 0 then
11960 -- return false;
11961 -- elsif Y'length = 0 then
11962 -- return true;
11963 -- else
11964 -- for ... loop ... end loop;
11965 -- return X'length > Y'length;
11966 -- end if;
11968 Length1 :=
11969 Make_Attribute_Reference (Loc,
11970 Prefix => New_Occurrence_Of (X, Loc),
11971 Attribute_Name => Name_Length);
11973 Length2 :=
11974 Make_Attribute_Reference (Loc,
11975 Prefix => New_Occurrence_Of (Y, Loc),
11976 Attribute_Name => Name_Length);
11978 Final_Expr :=
11979 Make_Op_Gt (Loc,
11980 Left_Opnd => Length1,
11981 Right_Opnd => Length2);
11983 If_Stat :=
11984 Make_Implicit_If_Statement (Nod,
11985 Condition =>
11986 Make_Op_Eq (Loc,
11987 Left_Opnd =>
11988 Make_Attribute_Reference (Loc,
11989 Prefix => New_Occurrence_Of (X, Loc),
11990 Attribute_Name => Name_Length),
11991 Right_Opnd =>
11992 Make_Integer_Literal (Loc, 0)),
11994 Then_Statements =>
11995 New_List (
11996 Make_Simple_Return_Statement (Loc,
11997 Expression => New_Occurrence_Of (Standard_False, Loc))),
11999 Elsif_Parts => New_List (
12000 Make_Elsif_Part (Loc,
12001 Condition =>
12002 Make_Op_Eq (Loc,
12003 Left_Opnd =>
12004 Make_Attribute_Reference (Loc,
12005 Prefix => New_Occurrence_Of (Y, Loc),
12006 Attribute_Name => Name_Length),
12007 Right_Opnd =>
12008 Make_Integer_Literal (Loc, 0)),
12010 Then_Statements =>
12011 New_List (
12012 Make_Simple_Return_Statement (Loc,
12013 Expression => New_Occurrence_Of (Standard_True, Loc))))),
12015 Else_Statements => New_List (
12016 Loop_Statement,
12017 Make_Simple_Return_Statement (Loc,
12018 Expression => Final_Expr)));
12020 -- (X : a; Y: a)
12022 Formals := New_List (
12023 Make_Parameter_Specification (Loc,
12024 Defining_Identifier => X,
12025 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
12027 Make_Parameter_Specification (Loc,
12028 Defining_Identifier => Y,
12029 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
12031 -- function Gnnn (...) return boolean is
12032 -- J : index := Y'first;
12033 -- begin
12034 -- if ... end if;
12035 -- end Gnnn;
12037 Func_Name := Make_Temporary (Loc, 'G');
12039 Func_Body :=
12040 Make_Subprogram_Body (Loc,
12041 Specification =>
12042 Make_Function_Specification (Loc,
12043 Defining_Unit_Name => Func_Name,
12044 Parameter_Specifications => Formals,
12045 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
12047 Declarations => New_List (
12048 Make_Object_Declaration (Loc,
12049 Defining_Identifier => J,
12050 Object_Definition => New_Occurrence_Of (Index, Loc),
12051 Expression =>
12052 Make_Attribute_Reference (Loc,
12053 Prefix => New_Occurrence_Of (Y, Loc),
12054 Attribute_Name => Name_First))),
12056 Handled_Statement_Sequence =>
12057 Make_Handled_Sequence_Of_Statements (Loc,
12058 Statements => New_List (If_Stat)));
12060 return Func_Body;
12061 end Make_Array_Comparison_Op;
12063 ---------------------------
12064 -- Make_Boolean_Array_Op --
12065 ---------------------------
12067 -- For logical operations on boolean arrays, expand in line the following,
12068 -- replacing 'and' with 'or' or 'xor' where needed:
12070 -- function Annn (A : typ; B: typ) return typ is
12071 -- C : typ;
12072 -- begin
12073 -- for J in A'range loop
12074 -- C (J) := A (J) op B (J);
12075 -- end loop;
12076 -- return C;
12077 -- end Annn;
12079 -- Here typ is the boolean array type
12081 function Make_Boolean_Array_Op
12082 (Typ : Entity_Id;
12083 N : Node_Id) return Node_Id
12085 Loc : constant Source_Ptr := Sloc (N);
12087 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
12088 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
12089 C : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uC);
12090 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
12092 A_J : Node_Id;
12093 B_J : Node_Id;
12094 C_J : Node_Id;
12095 Op : Node_Id;
12097 Formals : List_Id;
12098 Func_Name : Entity_Id;
12099 Func_Body : Node_Id;
12100 Loop_Statement : Node_Id;
12102 begin
12103 A_J :=
12104 Make_Indexed_Component (Loc,
12105 Prefix => New_Occurrence_Of (A, Loc),
12106 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12108 B_J :=
12109 Make_Indexed_Component (Loc,
12110 Prefix => New_Occurrence_Of (B, Loc),
12111 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12113 C_J :=
12114 Make_Indexed_Component (Loc,
12115 Prefix => New_Occurrence_Of (C, Loc),
12116 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12118 if Nkind (N) = N_Op_And then
12119 Op :=
12120 Make_Op_And (Loc,
12121 Left_Opnd => A_J,
12122 Right_Opnd => B_J);
12124 elsif Nkind (N) = N_Op_Or then
12125 Op :=
12126 Make_Op_Or (Loc,
12127 Left_Opnd => A_J,
12128 Right_Opnd => B_J);
12130 else
12131 Op :=
12132 Make_Op_Xor (Loc,
12133 Left_Opnd => A_J,
12134 Right_Opnd => B_J);
12135 end if;
12137 Loop_Statement :=
12138 Make_Implicit_Loop_Statement (N,
12139 Identifier => Empty,
12141 Iteration_Scheme =>
12142 Make_Iteration_Scheme (Loc,
12143 Loop_Parameter_Specification =>
12144 Make_Loop_Parameter_Specification (Loc,
12145 Defining_Identifier => J,
12146 Discrete_Subtype_Definition =>
12147 Make_Attribute_Reference (Loc,
12148 Prefix => New_Occurrence_Of (A, Loc),
12149 Attribute_Name => Name_Range))),
12151 Statements => New_List (
12152 Make_Assignment_Statement (Loc,
12153 Name => C_J,
12154 Expression => Op)));
12156 Formals := New_List (
12157 Make_Parameter_Specification (Loc,
12158 Defining_Identifier => A,
12159 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
12161 Make_Parameter_Specification (Loc,
12162 Defining_Identifier => B,
12163 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
12165 Func_Name := Make_Temporary (Loc, 'A');
12166 Set_Is_Inlined (Func_Name);
12168 Func_Body :=
12169 Make_Subprogram_Body (Loc,
12170 Specification =>
12171 Make_Function_Specification (Loc,
12172 Defining_Unit_Name => Func_Name,
12173 Parameter_Specifications => Formals,
12174 Result_Definition => New_Occurrence_Of (Typ, Loc)),
12176 Declarations => New_List (
12177 Make_Object_Declaration (Loc,
12178 Defining_Identifier => C,
12179 Object_Definition => New_Occurrence_Of (Typ, Loc))),
12181 Handled_Statement_Sequence =>
12182 Make_Handled_Sequence_Of_Statements (Loc,
12183 Statements => New_List (
12184 Loop_Statement,
12185 Make_Simple_Return_Statement (Loc,
12186 Expression => New_Occurrence_Of (C, Loc)))));
12188 return Func_Body;
12189 end Make_Boolean_Array_Op;
12191 -----------------------------------------
12192 -- Minimized_Eliminated_Overflow_Check --
12193 -----------------------------------------
12195 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean is
12196 begin
12197 return
12198 Is_Signed_Integer_Type (Etype (N))
12199 and then Overflow_Check_Mode in Minimized_Or_Eliminated;
12200 end Minimized_Eliminated_Overflow_Check;
12202 --------------------------------
12203 -- Optimize_Length_Comparison --
12204 --------------------------------
12206 procedure Optimize_Length_Comparison (N : Node_Id) is
12207 Loc : constant Source_Ptr := Sloc (N);
12208 Typ : constant Entity_Id := Etype (N);
12209 Result : Node_Id;
12211 Left : Node_Id;
12212 Right : Node_Id;
12213 -- First and Last attribute reference nodes, which end up as left and
12214 -- right operands of the optimized result.
12216 Is_Zero : Boolean;
12217 -- True for comparison operand of zero
12219 Comp : Node_Id;
12220 -- Comparison operand, set only if Is_Zero is false
12222 Ent : Entity_Id;
12223 -- Entity whose length is being compared
12225 Index : Node_Id;
12226 -- Integer_Literal node for length attribute expression, or Empty
12227 -- if there is no such expression present.
12229 Ityp : Entity_Id;
12230 -- Type of array index to which 'Length is applied
12232 Op : Node_Kind := Nkind (N);
12233 -- Kind of comparison operator, gets flipped if operands backwards
12235 function Is_Optimizable (N : Node_Id) return Boolean;
12236 -- Tests N to see if it is an optimizable comparison value (defined as
12237 -- constant zero or one, or something else where the value is known to
12238 -- be positive and in the range of 32-bits, and where the corresponding
12239 -- Length value is also known to be 32-bits. If result is true, sets
12240 -- Is_Zero, Ityp, and Comp accordingly.
12242 function Is_Entity_Length (N : Node_Id) return Boolean;
12243 -- Tests if N is a length attribute applied to a simple entity. If so,
12244 -- returns True, and sets Ent to the entity, and Index to the integer
12245 -- literal provided as an attribute expression, or to Empty if none.
12246 -- Also returns True if the expression is a generated type conversion
12247 -- whose expression is of the desired form. This latter case arises
12248 -- when Apply_Universal_Integer_Attribute_Check installs a conversion
12249 -- to check for being in range, which is not needed in this context.
12250 -- Returns False if neither condition holds.
12252 function Prepare_64 (N : Node_Id) return Node_Id;
12253 -- Given a discrete expression, returns a Long_Long_Integer typed
12254 -- expression representing the underlying value of the expression.
12255 -- This is done with an unchecked conversion to the result type. We
12256 -- use unchecked conversion to handle the enumeration type case.
12258 ----------------------
12259 -- Is_Entity_Length --
12260 ----------------------
12262 function Is_Entity_Length (N : Node_Id) return Boolean is
12263 begin
12264 if Nkind (N) = N_Attribute_Reference
12265 and then Attribute_Name (N) = Name_Length
12266 and then Is_Entity_Name (Prefix (N))
12267 then
12268 Ent := Entity (Prefix (N));
12270 if Present (Expressions (N)) then
12271 Index := First (Expressions (N));
12272 else
12273 Index := Empty;
12274 end if;
12276 return True;
12278 elsif Nkind (N) = N_Type_Conversion
12279 and then not Comes_From_Source (N)
12280 then
12281 return Is_Entity_Length (Expression (N));
12283 else
12284 return False;
12285 end if;
12286 end Is_Entity_Length;
12288 --------------------
12289 -- Is_Optimizable --
12290 --------------------
12292 function Is_Optimizable (N : Node_Id) return Boolean is
12293 Val : Uint;
12294 OK : Boolean;
12295 Lo : Uint;
12296 Hi : Uint;
12297 Indx : Node_Id;
12299 begin
12300 if Compile_Time_Known_Value (N) then
12301 Val := Expr_Value (N);
12303 if Val = Uint_0 then
12304 Is_Zero := True;
12305 Comp := Empty;
12306 return True;
12308 elsif Val = Uint_1 then
12309 Is_Zero := False;
12310 Comp := Empty;
12311 return True;
12312 end if;
12313 end if;
12315 -- Here we have to make sure of being within 32-bits
12317 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
12319 if not OK
12320 or else Lo < Uint_1
12321 or else Hi > UI_From_Int (Int'Last)
12322 then
12323 return False;
12324 end if;
12326 -- Comparison value was within range, so now we must check the index
12327 -- value to make sure it is also within 32-bits.
12329 Indx := First_Index (Etype (Ent));
12331 if Present (Index) then
12332 for J in 2 .. UI_To_Int (Intval (Index)) loop
12333 Next_Index (Indx);
12334 end loop;
12335 end if;
12337 Ityp := Etype (Indx);
12339 if Esize (Ityp) > 32 then
12340 return False;
12341 end if;
12343 Is_Zero := False;
12344 Comp := N;
12345 return True;
12346 end Is_Optimizable;
12348 ----------------
12349 -- Prepare_64 --
12350 ----------------
12352 function Prepare_64 (N : Node_Id) return Node_Id is
12353 begin
12354 return Unchecked_Convert_To (Standard_Long_Long_Integer, N);
12355 end Prepare_64;
12357 -- Start of processing for Optimize_Length_Comparison
12359 begin
12360 -- Nothing to do if not a comparison
12362 if Op not in N_Op_Compare then
12363 return;
12364 end if;
12366 -- Nothing to do if special -gnatd.P debug flag set
12368 if Debug_Flag_Dot_PP then
12369 return;
12370 end if;
12372 -- Ent'Length op 0/1
12374 if Is_Entity_Length (Left_Opnd (N))
12375 and then Is_Optimizable (Right_Opnd (N))
12376 then
12377 null;
12379 -- 0/1 op Ent'Length
12381 elsif Is_Entity_Length (Right_Opnd (N))
12382 and then Is_Optimizable (Left_Opnd (N))
12383 then
12384 -- Flip comparison to opposite sense
12386 case Op is
12387 when N_Op_Lt => Op := N_Op_Gt;
12388 when N_Op_Le => Op := N_Op_Ge;
12389 when N_Op_Gt => Op := N_Op_Lt;
12390 when N_Op_Ge => Op := N_Op_Le;
12391 when others => null;
12392 end case;
12394 -- Else optimization not possible
12396 else
12397 return;
12398 end if;
12400 -- Fall through if we will do the optimization
12402 -- Cases to handle:
12404 -- X'Length = 0 => X'First > X'Last
12405 -- X'Length = 1 => X'First = X'Last
12406 -- X'Length = n => X'First + (n - 1) = X'Last
12408 -- X'Length /= 0 => X'First <= X'Last
12409 -- X'Length /= 1 => X'First /= X'Last
12410 -- X'Length /= n => X'First + (n - 1) /= X'Last
12412 -- X'Length >= 0 => always true, warn
12413 -- X'Length >= 1 => X'First <= X'Last
12414 -- X'Length >= n => X'First + (n - 1) <= X'Last
12416 -- X'Length > 0 => X'First <= X'Last
12417 -- X'Length > 1 => X'First < X'Last
12418 -- X'Length > n => X'First + (n - 1) < X'Last
12420 -- X'Length <= 0 => X'First > X'Last (warn, could be =)
12421 -- X'Length <= 1 => X'First >= X'Last
12422 -- X'Length <= n => X'First + (n - 1) >= X'Last
12424 -- X'Length < 0 => always false (warn)
12425 -- X'Length < 1 => X'First > X'Last
12426 -- X'Length < n => X'First + (n - 1) > X'Last
12428 -- Note: for the cases of n (not constant 0,1), we require that the
12429 -- corresponding index type be integer or shorter (i.e. not 64-bit),
12430 -- and the same for the comparison value. Then we do the comparison
12431 -- using 64-bit arithmetic (actually long long integer), so that we
12432 -- cannot have overflow intefering with the result.
12434 -- First deal with warning cases
12436 if Is_Zero then
12437 case Op is
12439 -- X'Length >= 0
12441 when N_Op_Ge =>
12442 Rewrite (N,
12443 Convert_To (Typ, New_Occurrence_Of (Standard_True, Loc)));
12444 Analyze_And_Resolve (N, Typ);
12445 Warn_On_Known_Condition (N);
12446 return;
12448 -- X'Length < 0
12450 when N_Op_Lt =>
12451 Rewrite (N,
12452 Convert_To (Typ, New_Occurrence_Of (Standard_False, Loc)));
12453 Analyze_And_Resolve (N, Typ);
12454 Warn_On_Known_Condition (N);
12455 return;
12457 when N_Op_Le =>
12458 if Constant_Condition_Warnings
12459 and then Comes_From_Source (Original_Node (N))
12460 then
12461 Error_Msg_N ("could replace by ""'=""?c?", N);
12462 end if;
12464 Op := N_Op_Eq;
12466 when others =>
12467 null;
12468 end case;
12469 end if;
12471 -- Build the First reference we will use
12473 Left :=
12474 Make_Attribute_Reference (Loc,
12475 Prefix => New_Occurrence_Of (Ent, Loc),
12476 Attribute_Name => Name_First);
12478 if Present (Index) then
12479 Set_Expressions (Left, New_List (New_Copy (Index)));
12480 end if;
12482 -- If general value case, then do the addition of (n - 1), and
12483 -- also add the needed conversions to type Long_Long_Integer.
12485 if Present (Comp) then
12486 Left :=
12487 Make_Op_Add (Loc,
12488 Left_Opnd => Prepare_64 (Left),
12489 Right_Opnd =>
12490 Make_Op_Subtract (Loc,
12491 Left_Opnd => Prepare_64 (Comp),
12492 Right_Opnd => Make_Integer_Literal (Loc, 1)));
12493 end if;
12495 -- Build the Last reference we will use
12497 Right :=
12498 Make_Attribute_Reference (Loc,
12499 Prefix => New_Occurrence_Of (Ent, Loc),
12500 Attribute_Name => Name_Last);
12502 if Present (Index) then
12503 Set_Expressions (Right, New_List (New_Copy (Index)));
12504 end if;
12506 -- If general operand, convert Last reference to Long_Long_Integer
12508 if Present (Comp) then
12509 Right := Prepare_64 (Right);
12510 end if;
12512 -- Check for cases to optimize
12514 -- X'Length = 0 => X'First > X'Last
12515 -- X'Length < 1 => X'First > X'Last
12516 -- X'Length < n => X'First + (n - 1) > X'Last
12518 if (Is_Zero and then Op = N_Op_Eq)
12519 or else (not Is_Zero and then Op = N_Op_Lt)
12520 then
12521 Result :=
12522 Make_Op_Gt (Loc,
12523 Left_Opnd => Left,
12524 Right_Opnd => Right);
12526 -- X'Length = 1 => X'First = X'Last
12527 -- X'Length = n => X'First + (n - 1) = X'Last
12529 elsif not Is_Zero and then Op = N_Op_Eq then
12530 Result :=
12531 Make_Op_Eq (Loc,
12532 Left_Opnd => Left,
12533 Right_Opnd => Right);
12535 -- X'Length /= 0 => X'First <= X'Last
12536 -- X'Length > 0 => X'First <= X'Last
12538 elsif Is_Zero and (Op = N_Op_Ne or else Op = N_Op_Gt) then
12539 Result :=
12540 Make_Op_Le (Loc,
12541 Left_Opnd => Left,
12542 Right_Opnd => Right);
12544 -- X'Length /= 1 => X'First /= X'Last
12545 -- X'Length /= n => X'First + (n - 1) /= X'Last
12547 elsif not Is_Zero and then Op = N_Op_Ne then
12548 Result :=
12549 Make_Op_Ne (Loc,
12550 Left_Opnd => Left,
12551 Right_Opnd => Right);
12553 -- X'Length >= 1 => X'First <= X'Last
12554 -- X'Length >= n => X'First + (n - 1) <= X'Last
12556 elsif not Is_Zero and then Op = N_Op_Ge then
12557 Result :=
12558 Make_Op_Le (Loc,
12559 Left_Opnd => Left,
12560 Right_Opnd => Right);
12562 -- X'Length > 1 => X'First < X'Last
12563 -- X'Length > n => X'First + (n = 1) < X'Last
12565 elsif not Is_Zero and then Op = N_Op_Gt then
12566 Result :=
12567 Make_Op_Lt (Loc,
12568 Left_Opnd => Left,
12569 Right_Opnd => Right);
12571 -- X'Length <= 1 => X'First >= X'Last
12572 -- X'Length <= n => X'First + (n - 1) >= X'Last
12574 elsif not Is_Zero and then Op = N_Op_Le then
12575 Result :=
12576 Make_Op_Ge (Loc,
12577 Left_Opnd => Left,
12578 Right_Opnd => Right);
12580 -- Should not happen at this stage
12582 else
12583 raise Program_Error;
12584 end if;
12586 -- Rewrite and finish up
12588 Rewrite (N, Result);
12589 Analyze_And_Resolve (N, Typ);
12590 return;
12591 end Optimize_Length_Comparison;
12593 ------------------------------
12594 -- Process_Transient_Object --
12595 ------------------------------
12597 procedure Process_Transient_Object
12598 (Decl : Node_Id;
12599 Rel_Node : Node_Id)
12601 Loc : constant Source_Ptr := Sloc (Decl);
12602 Obj_Id : constant Entity_Id := Defining_Identifier (Decl);
12603 Obj_Typ : constant Node_Id := Etype (Obj_Id);
12604 Desig_Typ : Entity_Id;
12605 Expr : Node_Id;
12606 Fin_Stmts : List_Id;
12607 Ptr_Id : Entity_Id;
12608 Temp_Id : Entity_Id;
12609 Temp_Ins : Node_Id;
12611 Hook_Context : constant Node_Id := Find_Hook_Context (Rel_Node);
12612 -- Node on which to insert the hook pointer (as an action): the
12613 -- innermost enclosing non-transient scope.
12615 Finalization_Context : Node_Id;
12616 -- Node after which to insert finalization actions
12618 Finalize_Always : Boolean;
12619 -- If False, call to finalizer includes a test of whether the hook
12620 -- pointer is null.
12622 begin
12623 -- Step 0: determine where to attach finalization actions in the tree
12625 -- Special case for Boolean EWAs: capture expression in a temporary,
12626 -- whose declaration will serve as the context around which to insert
12627 -- finalization code. The finalization thus remains local to the
12628 -- specific condition being evaluated.
12630 if Is_Boolean_Type (Etype (Rel_Node)) then
12632 -- In this case, the finalization context is chosen so that we know
12633 -- at finalization point that the hook pointer is never null, so no
12634 -- need for a test, we can call the finalizer unconditionally, except
12635 -- in the case where the object is created in a specific branch of a
12636 -- conditional expression.
12638 Finalize_Always :=
12639 not Within_Case_Or_If_Expression (Rel_Node)
12640 and then not Nkind_In
12641 (Original_Node (Rel_Node), N_Case_Expression,
12642 N_If_Expression);
12644 declare
12645 Loc : constant Source_Ptr := Sloc (Rel_Node);
12646 Temp : constant Entity_Id := Make_Temporary (Loc, 'E', Rel_Node);
12648 begin
12649 Append_To (Actions (Rel_Node),
12650 Make_Object_Declaration (Loc,
12651 Defining_Identifier => Temp,
12652 Constant_Present => True,
12653 Object_Definition =>
12654 New_Occurrence_Of (Etype (Rel_Node), Loc),
12655 Expression => Expression (Rel_Node)));
12656 Finalization_Context := Last (Actions (Rel_Node));
12658 Analyze (Last (Actions (Rel_Node)));
12660 Set_Expression (Rel_Node, New_Occurrence_Of (Temp, Loc));
12661 Analyze (Expression (Rel_Node));
12662 end;
12664 else
12665 Finalize_Always := False;
12666 Finalization_Context := Hook_Context;
12667 end if;
12669 -- Step 1: Create the access type which provides a reference to the
12670 -- transient controlled object.
12672 if Is_Access_Type (Obj_Typ) then
12673 Desig_Typ := Directly_Designated_Type (Obj_Typ);
12674 else
12675 Desig_Typ := Obj_Typ;
12676 end if;
12678 Desig_Typ := Base_Type (Desig_Typ);
12680 -- Generate:
12681 -- Ann : access [all] <Desig_Typ>;
12683 Ptr_Id := Make_Temporary (Loc, 'A');
12685 Insert_Action (Hook_Context,
12686 Make_Full_Type_Declaration (Loc,
12687 Defining_Identifier => Ptr_Id,
12688 Type_Definition =>
12689 Make_Access_To_Object_Definition (Loc,
12690 All_Present => Ekind (Obj_Typ) = E_General_Access_Type,
12691 Subtype_Indication => New_Occurrence_Of (Desig_Typ, Loc))));
12693 -- Step 2: Create a temporary which acts as a hook to the transient
12694 -- controlled object. Generate:
12696 -- Temp : Ptr_Id := null;
12698 Temp_Id := Make_Temporary (Loc, 'T');
12700 Insert_Action (Hook_Context,
12701 Make_Object_Declaration (Loc,
12702 Defining_Identifier => Temp_Id,
12703 Object_Definition => New_Occurrence_Of (Ptr_Id, Loc)));
12705 -- Mark the temporary as created for the purposes of exporting the
12706 -- transient controlled object out of the expression_with_action or if
12707 -- expression. This signals the machinery in Build_Finalizer to treat
12708 -- this case specially.
12710 Set_Status_Flag_Or_Transient_Decl (Temp_Id, Decl);
12712 -- Step 3: Hook the transient object to the temporary
12714 -- This must be inserted right after the object declaration, so that
12715 -- the assignment is executed if, and only if, the object is actually
12716 -- created (whereas the declaration of the hook pointer, and the
12717 -- finalization call, may be inserted at an outer level, and may
12718 -- remain unused for some executions, if the actual creation of
12719 -- the object is conditional).
12721 -- The use of unchecked conversion / unrestricted access is needed to
12722 -- avoid an accessibility violation. Note that the finalization code is
12723 -- structured in such a way that the "hook" is processed only when it
12724 -- points to an existing object.
12726 if Is_Access_Type (Obj_Typ) then
12727 Expr :=
12728 Unchecked_Convert_To (Ptr_Id, New_Occurrence_Of (Obj_Id, Loc));
12729 else
12730 Expr :=
12731 Make_Attribute_Reference (Loc,
12732 Prefix => New_Occurrence_Of (Obj_Id, Loc),
12733 Attribute_Name => Name_Unrestricted_Access);
12734 end if;
12736 -- Generate:
12737 -- Temp := Ptr_Id (Obj_Id);
12738 -- <or>
12739 -- Temp := Obj_Id'Unrestricted_Access;
12741 -- When the transient object is initialized by an aggregate, the hook
12742 -- must capture the object after the last component assignment takes
12743 -- place. Only then is the object fully initialized.
12745 if Ekind (Obj_Id) = E_Variable
12746 and then Present (Last_Aggregate_Assignment (Obj_Id))
12747 then
12748 Temp_Ins := Last_Aggregate_Assignment (Obj_Id);
12750 -- Otherwise the hook seizes the related object immediately
12752 else
12753 Temp_Ins := Decl;
12754 end if;
12756 Insert_After_And_Analyze (Temp_Ins,
12757 Make_Assignment_Statement (Loc,
12758 Name => New_Occurrence_Of (Temp_Id, Loc),
12759 Expression => Expr));
12761 -- Step 4: Finalize the transient controlled object after the context
12762 -- has been evaluated/elaborated. Generate:
12764 -- if Temp /= null then
12765 -- [Deep_]Finalize (Temp.all);
12766 -- Temp := null;
12767 -- end if;
12769 -- When the node is part of a return statement, there is no need to
12770 -- insert a finalization call, as the general finalization mechanism
12771 -- (see Build_Finalizer) would take care of the transient controlled
12772 -- object on subprogram exit. Note that it would also be impossible to
12773 -- insert the finalization code after the return statement as this will
12774 -- render it unreachable.
12776 if Nkind (Finalization_Context) /= N_Simple_Return_Statement then
12777 Fin_Stmts := New_List (
12778 Make_Final_Call
12779 (Obj_Ref =>
12780 Make_Explicit_Dereference (Loc,
12781 Prefix => New_Occurrence_Of (Temp_Id, Loc)),
12782 Typ => Desig_Typ),
12784 Make_Assignment_Statement (Loc,
12785 Name => New_Occurrence_Of (Temp_Id, Loc),
12786 Expression => Make_Null (Loc)));
12788 if not Finalize_Always then
12789 Fin_Stmts := New_List (
12790 Make_Implicit_If_Statement (Decl,
12791 Condition =>
12792 Make_Op_Ne (Loc,
12793 Left_Opnd => New_Occurrence_Of (Temp_Id, Loc),
12794 Right_Opnd => Make_Null (Loc)),
12795 Then_Statements => Fin_Stmts));
12796 end if;
12798 Insert_Actions_After (Finalization_Context, Fin_Stmts);
12799 end if;
12800 end Process_Transient_Object;
12802 ------------------------
12803 -- Rewrite_Comparison --
12804 ------------------------
12806 procedure Rewrite_Comparison (N : Node_Id) is
12807 Warning_Generated : Boolean := False;
12808 -- Set to True if first pass with Assume_Valid generates a warning in
12809 -- which case we skip the second pass to avoid warning overloaded.
12811 Result : Node_Id;
12812 -- Set to Standard_True or Standard_False
12814 begin
12815 if Nkind (N) = N_Type_Conversion then
12816 Rewrite_Comparison (Expression (N));
12817 return;
12819 elsif Nkind (N) not in N_Op_Compare then
12820 return;
12821 end if;
12823 -- Now start looking at the comparison in detail. We potentially go
12824 -- through this loop twice. The first time, Assume_Valid is set False
12825 -- in the call to Compile_Time_Compare. If this call results in a
12826 -- clear result of always True or Always False, that's decisive and
12827 -- we are done. Otherwise we repeat the processing with Assume_Valid
12828 -- set to True to generate additional warnings. We can skip that step
12829 -- if Constant_Condition_Warnings is False.
12831 for AV in False .. True loop
12832 declare
12833 Typ : constant Entity_Id := Etype (N);
12834 Op1 : constant Node_Id := Left_Opnd (N);
12835 Op2 : constant Node_Id := Right_Opnd (N);
12837 Res : constant Compare_Result :=
12838 Compile_Time_Compare (Op1, Op2, Assume_Valid => AV);
12839 -- Res indicates if compare outcome can be compile time determined
12841 True_Result : Boolean;
12842 False_Result : Boolean;
12844 begin
12845 case N_Op_Compare (Nkind (N)) is
12846 when N_Op_Eq =>
12847 True_Result := Res = EQ;
12848 False_Result := Res = LT or else Res = GT or else Res = NE;
12850 when N_Op_Ge =>
12851 True_Result := Res in Compare_GE;
12852 False_Result := Res = LT;
12854 if Res = LE
12855 and then Constant_Condition_Warnings
12856 and then Comes_From_Source (Original_Node (N))
12857 and then Nkind (Original_Node (N)) = N_Op_Ge
12858 and then not In_Instance
12859 and then Is_Integer_Type (Etype (Left_Opnd (N)))
12860 and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
12861 then
12862 Error_Msg_N
12863 ("can never be greater than, could replace by ""'=""?c?",
12865 Warning_Generated := True;
12866 end if;
12868 when N_Op_Gt =>
12869 True_Result := Res = GT;
12870 False_Result := Res in Compare_LE;
12872 when N_Op_Lt =>
12873 True_Result := Res = LT;
12874 False_Result := Res in Compare_GE;
12876 when N_Op_Le =>
12877 True_Result := Res in Compare_LE;
12878 False_Result := Res = GT;
12880 if Res = GE
12881 and then Constant_Condition_Warnings
12882 and then Comes_From_Source (Original_Node (N))
12883 and then Nkind (Original_Node (N)) = N_Op_Le
12884 and then not In_Instance
12885 and then Is_Integer_Type (Etype (Left_Opnd (N)))
12886 and then not Has_Warnings_Off (Etype (Left_Opnd (N)))
12887 then
12888 Error_Msg_N
12889 ("can never be less than, could replace by ""'=""?c?", N);
12890 Warning_Generated := True;
12891 end if;
12893 when N_Op_Ne =>
12894 True_Result := Res = NE or else Res = GT or else Res = LT;
12895 False_Result := Res = EQ;
12896 end case;
12898 -- If this is the first iteration, then we actually convert the
12899 -- comparison into True or False, if the result is certain.
12901 if AV = False then
12902 if True_Result or False_Result then
12903 Result := Boolean_Literals (True_Result);
12904 Rewrite (N,
12905 Convert_To (Typ,
12906 New_Occurrence_Of (Result, Sloc (N))));
12907 Analyze_And_Resolve (N, Typ);
12908 Warn_On_Known_Condition (N);
12909 return;
12910 end if;
12912 -- If this is the second iteration (AV = True), and the original
12913 -- node comes from source and we are not in an instance, then give
12914 -- a warning if we know result would be True or False. Note: we
12915 -- know Constant_Condition_Warnings is set if we get here.
12917 elsif Comes_From_Source (Original_Node (N))
12918 and then not In_Instance
12919 then
12920 if True_Result then
12921 Error_Msg_N
12922 ("condition can only be False if invalid values present??",
12924 elsif False_Result then
12925 Error_Msg_N
12926 ("condition can only be True if invalid values present??",
12928 end if;
12929 end if;
12930 end;
12932 -- Skip second iteration if not warning on constant conditions or
12933 -- if the first iteration already generated a warning of some kind or
12934 -- if we are in any case assuming all values are valid (so that the
12935 -- first iteration took care of the valid case).
12937 exit when not Constant_Condition_Warnings;
12938 exit when Warning_Generated;
12939 exit when Assume_No_Invalid_Values;
12940 end loop;
12941 end Rewrite_Comparison;
12943 ----------------------------
12944 -- Safe_In_Place_Array_Op --
12945 ----------------------------
12947 function Safe_In_Place_Array_Op
12948 (Lhs : Node_Id;
12949 Op1 : Node_Id;
12950 Op2 : Node_Id) return Boolean
12952 Target : Entity_Id;
12954 function Is_Safe_Operand (Op : Node_Id) return Boolean;
12955 -- Operand is safe if it cannot overlap part of the target of the
12956 -- operation. If the operand and the target are identical, the operand
12957 -- is safe. The operand can be empty in the case of negation.
12959 function Is_Unaliased (N : Node_Id) return Boolean;
12960 -- Check that N is a stand-alone entity
12962 ------------------
12963 -- Is_Unaliased --
12964 ------------------
12966 function Is_Unaliased (N : Node_Id) return Boolean is
12967 begin
12968 return
12969 Is_Entity_Name (N)
12970 and then No (Address_Clause (Entity (N)))
12971 and then No (Renamed_Object (Entity (N)));
12972 end Is_Unaliased;
12974 ---------------------
12975 -- Is_Safe_Operand --
12976 ---------------------
12978 function Is_Safe_Operand (Op : Node_Id) return Boolean is
12979 begin
12980 if No (Op) then
12981 return True;
12983 elsif Is_Entity_Name (Op) then
12984 return Is_Unaliased (Op);
12986 elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
12987 return Is_Unaliased (Prefix (Op));
12989 elsif Nkind (Op) = N_Slice then
12990 return
12991 Is_Unaliased (Prefix (Op))
12992 and then Entity (Prefix (Op)) /= Target;
12994 elsif Nkind (Op) = N_Op_Not then
12995 return Is_Safe_Operand (Right_Opnd (Op));
12997 else
12998 return False;
12999 end if;
13000 end Is_Safe_Operand;
13002 -- Start of processing for Safe_In_Place_Array_Op
13004 begin
13005 -- Skip this processing if the component size is different from system
13006 -- storage unit (since at least for NOT this would cause problems).
13008 if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
13009 return False;
13011 -- Cannot do in place stuff on VM_Target since cannot pass addresses
13013 elsif VM_Target /= No_VM then
13014 return False;
13016 -- Cannot do in place stuff if non-standard Boolean representation
13018 elsif Has_Non_Standard_Rep (Component_Type (Etype (Lhs))) then
13019 return False;
13021 elsif not Is_Unaliased (Lhs) then
13022 return False;
13024 else
13025 Target := Entity (Lhs);
13026 return Is_Safe_Operand (Op1) and then Is_Safe_Operand (Op2);
13027 end if;
13028 end Safe_In_Place_Array_Op;
13030 -----------------------
13031 -- Tagged_Membership --
13032 -----------------------
13034 -- There are two different cases to consider depending on whether the right
13035 -- operand is a class-wide type or not. If not we just compare the actual
13036 -- tag of the left expr to the target type tag:
13038 -- Left_Expr.Tag = Right_Type'Tag;
13040 -- If it is a class-wide type we use the RT function CW_Membership which is
13041 -- usually implemented by looking in the ancestor tables contained in the
13042 -- dispatch table pointed by Left_Expr.Tag for Typ'Tag
13044 -- Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
13045 -- function IW_Membership which is usually implemented by looking in the
13046 -- table of abstract interface types plus the ancestor table contained in
13047 -- the dispatch table pointed by Left_Expr.Tag for Typ'Tag
13049 procedure Tagged_Membership
13050 (N : Node_Id;
13051 SCIL_Node : out Node_Id;
13052 Result : out Node_Id)
13054 Left : constant Node_Id := Left_Opnd (N);
13055 Right : constant Node_Id := Right_Opnd (N);
13056 Loc : constant Source_Ptr := Sloc (N);
13058 Full_R_Typ : Entity_Id;
13059 Left_Type : Entity_Id;
13060 New_Node : Node_Id;
13061 Right_Type : Entity_Id;
13062 Obj_Tag : Node_Id;
13064 begin
13065 SCIL_Node := Empty;
13067 -- Handle entities from the limited view
13069 Left_Type := Available_View (Etype (Left));
13070 Right_Type := Available_View (Etype (Right));
13072 -- In the case where the type is an access type, the test is applied
13073 -- using the designated types (needed in Ada 2012 for implicit anonymous
13074 -- access conversions, for AI05-0149).
13076 if Is_Access_Type (Right_Type) then
13077 Left_Type := Designated_Type (Left_Type);
13078 Right_Type := Designated_Type (Right_Type);
13079 end if;
13081 if Is_Class_Wide_Type (Left_Type) then
13082 Left_Type := Root_Type (Left_Type);
13083 end if;
13085 if Is_Class_Wide_Type (Right_Type) then
13086 Full_R_Typ := Underlying_Type (Root_Type (Right_Type));
13087 else
13088 Full_R_Typ := Underlying_Type (Right_Type);
13089 end if;
13091 Obj_Tag :=
13092 Make_Selected_Component (Loc,
13093 Prefix => Relocate_Node (Left),
13094 Selector_Name =>
13095 New_Occurrence_Of (First_Tag_Component (Left_Type), Loc));
13097 if Is_Class_Wide_Type (Right_Type) then
13099 -- No need to issue a run-time check if we statically know that the
13100 -- result of this membership test is always true. For example,
13101 -- considering the following declarations:
13103 -- type Iface is interface;
13104 -- type T is tagged null record;
13105 -- type DT is new T and Iface with null record;
13107 -- Obj1 : T;
13108 -- Obj2 : DT;
13110 -- These membership tests are always true:
13112 -- Obj1 in T'Class
13113 -- Obj2 in T'Class;
13114 -- Obj2 in Iface'Class;
13116 -- We do not need to handle cases where the membership is illegal.
13117 -- For example:
13119 -- Obj1 in DT'Class; -- Compile time error
13120 -- Obj1 in Iface'Class; -- Compile time error
13122 if not Is_Class_Wide_Type (Left_Type)
13123 and then (Is_Ancestor (Etype (Right_Type), Left_Type,
13124 Use_Full_View => True)
13125 or else (Is_Interface (Etype (Right_Type))
13126 and then Interface_Present_In_Ancestor
13127 (Typ => Left_Type,
13128 Iface => Etype (Right_Type))))
13129 then
13130 Result := New_Occurrence_Of (Standard_True, Loc);
13131 return;
13132 end if;
13134 -- Ada 2005 (AI-251): Class-wide applied to interfaces
13136 if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
13138 -- Support to: "Iface_CW_Typ in Typ'Class"
13140 or else Is_Interface (Left_Type)
13141 then
13142 -- Issue error if IW_Membership operation not available in a
13143 -- configurable run time setting.
13145 if not RTE_Available (RE_IW_Membership) then
13146 Error_Msg_CRT
13147 ("dynamic membership test on interface types", N);
13148 Result := Empty;
13149 return;
13150 end if;
13152 Result :=
13153 Make_Function_Call (Loc,
13154 Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
13155 Parameter_Associations => New_List (
13156 Make_Attribute_Reference (Loc,
13157 Prefix => Obj_Tag,
13158 Attribute_Name => Name_Address),
13159 New_Occurrence_Of (
13160 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))),
13161 Loc)));
13163 -- Ada 95: Normal case
13165 else
13166 Build_CW_Membership (Loc,
13167 Obj_Tag_Node => Obj_Tag,
13168 Typ_Tag_Node =>
13169 New_Occurrence_Of (
13170 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc),
13171 Related_Nod => N,
13172 New_Node => New_Node);
13174 -- Generate the SCIL node for this class-wide membership test.
13175 -- Done here because the previous call to Build_CW_Membership
13176 -- relocates Obj_Tag.
13178 if Generate_SCIL then
13179 SCIL_Node := Make_SCIL_Membership_Test (Sloc (N));
13180 Set_SCIL_Entity (SCIL_Node, Etype (Right_Type));
13181 Set_SCIL_Tag_Value (SCIL_Node, Obj_Tag);
13182 end if;
13184 Result := New_Node;
13185 end if;
13187 -- Right_Type is not a class-wide type
13189 else
13190 -- No need to check the tag of the object if Right_Typ is abstract
13192 if Is_Abstract_Type (Right_Type) then
13193 Result := New_Occurrence_Of (Standard_False, Loc);
13195 else
13196 Result :=
13197 Make_Op_Eq (Loc,
13198 Left_Opnd => Obj_Tag,
13199 Right_Opnd =>
13200 New_Occurrence_Of
13201 (Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc));
13202 end if;
13203 end if;
13204 end Tagged_Membership;
13206 ------------------------------
13207 -- Unary_Op_Validity_Checks --
13208 ------------------------------
13210 procedure Unary_Op_Validity_Checks (N : Node_Id) is
13211 begin
13212 if Validity_Checks_On and Validity_Check_Operands then
13213 Ensure_Valid (Right_Opnd (N));
13214 end if;
13215 end Unary_Op_Validity_Checks;
13217 end Exp_Ch4;