Improve fstack_protector effective target
[official-gcc.git] / gcc / ada / exp_ch4.adb
blobaac0c5cced90d7c438362c46650fc6a7a9fbe791
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-2017, 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 Namet; use Namet;
48 with Nlists; use Nlists;
49 with Nmake; use Nmake;
50 with Opt; use Opt;
51 with Par_SCO; use Par_SCO;
52 with Restrict; use Restrict;
53 with Rident; use Rident;
54 with Rtsfind; use Rtsfind;
55 with Sem; use Sem;
56 with Sem_Aux; use Sem_Aux;
57 with Sem_Cat; use Sem_Cat;
58 with Sem_Ch3; use Sem_Ch3;
59 with Sem_Ch13; use Sem_Ch13;
60 with Sem_Eval; use Sem_Eval;
61 with Sem_Res; use Sem_Res;
62 with Sem_Type; use Sem_Type;
63 with Sem_Util; use Sem_Util;
64 with Sem_Warn; use Sem_Warn;
65 with Sinfo; use Sinfo;
66 with Snames; use Snames;
67 with Stand; use Stand;
68 with SCIL_LL; use SCIL_LL;
69 with Targparm; use Targparm;
70 with Tbuild; use Tbuild;
71 with Ttypes; use Ttypes;
72 with Uintp; use Uintp;
73 with Urealp; use Urealp;
74 with Validsw; use Validsw;
76 package body Exp_Ch4 is
78 -----------------------
79 -- Local Subprograms --
80 -----------------------
82 procedure Binary_Op_Validity_Checks (N : Node_Id);
83 pragma Inline (Binary_Op_Validity_Checks);
84 -- Performs validity checks for a binary operator
86 procedure Build_Boolean_Array_Proc_Call
87 (N : Node_Id;
88 Op1 : Node_Id;
89 Op2 : Node_Id);
90 -- If a boolean array assignment can be done in place, build call to
91 -- corresponding library procedure.
93 procedure Displace_Allocator_Pointer (N : Node_Id);
94 -- Ada 2005 (AI-251): Subsidiary procedure to Expand_N_Allocator and
95 -- Expand_Allocator_Expression. Allocating class-wide interface objects
96 -- this routine displaces the pointer to the allocated object to reference
97 -- the component referencing the corresponding secondary dispatch table.
99 procedure Expand_Allocator_Expression (N : Node_Id);
100 -- Subsidiary to Expand_N_Allocator, for the case when the expression
101 -- is a qualified expression or an aggregate.
103 procedure Expand_Array_Comparison (N : Node_Id);
104 -- This routine handles expansion of the comparison operators (N_Op_Lt,
105 -- N_Op_Le, N_Op_Gt, N_Op_Ge) when operating on an array type. The basic
106 -- code for these operators is similar, differing only in the details of
107 -- the actual comparison call that is made. Special processing (call a
108 -- run-time routine)
110 function Expand_Array_Equality
111 (Nod : Node_Id;
112 Lhs : Node_Id;
113 Rhs : Node_Id;
114 Bodies : List_Id;
115 Typ : Entity_Id) return Node_Id;
116 -- Expand an array equality into a call to a function implementing this
117 -- equality, and a call to it. Loc is the location for the generated nodes.
118 -- Lhs and Rhs are the array expressions to be compared. Bodies is a list
119 -- on which to attach bodies of local functions that are created in the
120 -- process. It is the responsibility of the caller to insert those bodies
121 -- at the right place. Nod provides the Sloc value for the generated code.
122 -- Normally the types used for the generated equality routine are taken
123 -- from Lhs and Rhs. However, in some situations of generated code, the
124 -- Etype fields of Lhs and Rhs are not set yet. In such cases, Typ supplies
125 -- the type to be used for the formal parameters.
127 procedure Expand_Boolean_Operator (N : Node_Id);
128 -- Common expansion processing for Boolean operators (And, Or, Xor) for the
129 -- case of array type arguments.
131 procedure Expand_Nonbinary_Modular_Op (N : Node_Id);
132 -- When generating C code, convert nonbinary modular arithmetic operations
133 -- into code that relies on the front-end expansion of operator Mod. No
134 -- expansion is performed if N is not a nonbinary modular operand.
136 procedure Expand_Short_Circuit_Operator (N : Node_Id);
137 -- Common expansion processing for short-circuit boolean operators
139 procedure Expand_Compare_Minimize_Eliminate_Overflow (N : Node_Id);
140 -- Deal with comparison in MINIMIZED/ELIMINATED overflow mode. This is
141 -- where we allow comparison of "out of range" values.
143 function Expand_Composite_Equality
144 (Nod : Node_Id;
145 Typ : Entity_Id;
146 Lhs : Node_Id;
147 Rhs : Node_Id;
148 Bodies : List_Id) return Node_Id;
149 -- Local recursive function used to expand equality for nested composite
150 -- types. Used by Expand_Record/Array_Equality, Bodies is a list on which
151 -- to attach bodies of local functions that are created in the process. It
152 -- is the responsibility of the caller to insert those bodies at the right
153 -- place. Nod provides the Sloc value for generated code. Lhs and Rhs are
154 -- the left and right sides for the comparison, and Typ is the type of the
155 -- objects to compare.
157 procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id);
158 -- Routine to expand concatenation of a sequence of two or more operands
159 -- (in the list Operands) and replace node Cnode with the result of the
160 -- concatenation. The operands can be of any appropriate type, and can
161 -- include both arrays and singleton elements.
163 procedure Expand_Membership_Minimize_Eliminate_Overflow (N : Node_Id);
164 -- N is an N_In membership test mode, with the overflow check mode set to
165 -- MINIMIZED or ELIMINATED, and the type of the left operand is a signed
166 -- integer type. This is a case where top level processing is required to
167 -- handle overflow checks in subtrees.
169 procedure Fixup_Universal_Fixed_Operation (N : Node_Id);
170 -- N is a N_Op_Divide or N_Op_Multiply node whose result is universal
171 -- fixed. We do not have such a type at runtime, so the purpose of this
172 -- routine is to find the real type by looking up the tree. We also
173 -- determine if the operation must be rounded.
175 function Has_Inferable_Discriminants (N : Node_Id) return Boolean;
176 -- Ada 2005 (AI-216): A view of an Unchecked_Union object has inferable
177 -- discriminants if it has a constrained nominal type, unless the object
178 -- is a component of an enclosing Unchecked_Union object that is subject
179 -- to a per-object constraint and the enclosing object lacks inferable
180 -- discriminants.
182 -- An expression of an Unchecked_Union type has inferable discriminants
183 -- if it is either a name of an object with inferable discriminants or a
184 -- qualified expression whose subtype mark denotes a constrained subtype.
186 procedure Insert_Dereference_Action (N : Node_Id);
187 -- N is an expression whose type is an access. When the type of the
188 -- associated storage pool is derived from Checked_Pool, generate a
189 -- call to the 'Dereference' primitive operation.
191 function Make_Array_Comparison_Op
192 (Typ : Entity_Id;
193 Nod : Node_Id) return Node_Id;
194 -- Comparisons between arrays are expanded in line. This function produces
195 -- the body of the implementation of (a > b), where a and b are one-
196 -- dimensional arrays of some discrete type. The original node is then
197 -- expanded into the appropriate call to this function. Nod provides the
198 -- Sloc value for the generated code.
200 function Make_Boolean_Array_Op
201 (Typ : Entity_Id;
202 N : Node_Id) return Node_Id;
203 -- Boolean operations on boolean arrays are expanded in line. This function
204 -- produce the body for the node N, which is (a and b), (a or b), or (a xor
205 -- b). It is used only the normal case and not the packed case. The type
206 -- involved, Typ, is the Boolean array type, and the logical operations in
207 -- the body are simple boolean operations. Note that Typ is always a
208 -- constrained type (the caller has ensured this by using
209 -- Convert_To_Actual_Subtype if necessary).
211 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean;
212 -- For signed arithmetic operations when the current overflow mode is
213 -- MINIMIZED or ELIMINATED, we must call Apply_Arithmetic_Overflow_Checks
214 -- as the first thing we do. We then return. We count on the recursive
215 -- apparatus for overflow checks to call us back with an equivalent
216 -- operation that is in CHECKED mode, avoiding a recursive entry into this
217 -- routine, and that is when we will proceed with the expansion of the
218 -- operator (e.g. converting X+0 to X, or X**2 to X*X). We cannot do
219 -- these optimizations without first making this check, since there may be
220 -- operands further down the tree that are relying on the recursive calls
221 -- triggered by the top level nodes to properly process overflow checking
222 -- and remaining expansion on these nodes. Note that this call back may be
223 -- skipped if the operation is done in Bignum mode but that's fine, since
224 -- the Bignum call takes care of everything.
226 procedure Optimize_Length_Comparison (N : Node_Id);
227 -- Given an expression, if it is of the form X'Length op N (or the other
228 -- way round), where N is known at compile time to be 0 or 1, and X is a
229 -- simple entity, and op is a comparison operator, optimizes it into a
230 -- comparison of First and Last.
232 procedure Process_If_Case_Statements (N : Node_Id; Stmts : List_Id);
233 -- Inspect and process statement list Stmt of if or case expression N for
234 -- transient objects. If such objects are found, the routine generates code
235 -- to clean them up when the context of the expression is evaluated.
237 procedure Process_Transient_In_Expression
238 (Obj_Decl : Node_Id;
239 Expr : Node_Id;
240 Stmts : List_Id);
241 -- Subsidiary routine to the expansion of expression_with_actions, if and
242 -- case expressions. Generate all necessary code to finalize a transient
243 -- object when the enclosing context is elaborated or evaluated. Obj_Decl
244 -- denotes the declaration of the transient object, which is usually the
245 -- result of a controlled function call. Expr denotes the expression with
246 -- actions, if expression, or case expression node. Stmts denotes the
247 -- statement list which contains Decl, either at the top level or within a
248 -- nested construct.
250 procedure Rewrite_Comparison (N : Node_Id);
251 -- If N is the node for a comparison whose outcome can be determined at
252 -- compile time, then the node N can be rewritten with True or False. If
253 -- the outcome cannot be determined at compile time, the call has no
254 -- effect. If N is a type conversion, then this processing is applied to
255 -- its expression. If N is neither comparison nor a type conversion, the
256 -- call has no effect.
258 procedure Tagged_Membership
259 (N : Node_Id;
260 SCIL_Node : out Node_Id;
261 Result : out Node_Id);
262 -- Construct the expression corresponding to the tagged membership test.
263 -- Deals with a second operand being (or not) a class-wide type.
265 function Safe_In_Place_Array_Op
266 (Lhs : Node_Id;
267 Op1 : Node_Id;
268 Op2 : Node_Id) return Boolean;
269 -- In the context of an assignment, where the right-hand side is a boolean
270 -- operation on arrays, check whether operation can be performed in place.
272 procedure Unary_Op_Validity_Checks (N : Node_Id);
273 pragma Inline (Unary_Op_Validity_Checks);
274 -- Performs validity checks for a unary operator
276 -------------------------------
277 -- Binary_Op_Validity_Checks --
278 -------------------------------
280 procedure Binary_Op_Validity_Checks (N : Node_Id) is
281 begin
282 if Validity_Checks_On and Validity_Check_Operands then
283 Ensure_Valid (Left_Opnd (N));
284 Ensure_Valid (Right_Opnd (N));
285 end if;
286 end Binary_Op_Validity_Checks;
288 ------------------------------------
289 -- Build_Boolean_Array_Proc_Call --
290 ------------------------------------
292 procedure Build_Boolean_Array_Proc_Call
293 (N : Node_Id;
294 Op1 : Node_Id;
295 Op2 : Node_Id)
297 Loc : constant Source_Ptr := Sloc (N);
298 Kind : constant Node_Kind := Nkind (Expression (N));
299 Target : constant Node_Id :=
300 Make_Attribute_Reference (Loc,
301 Prefix => Name (N),
302 Attribute_Name => Name_Address);
304 Arg1 : Node_Id := Op1;
305 Arg2 : Node_Id := Op2;
306 Call_Node : Node_Id;
307 Proc_Name : Entity_Id;
309 begin
310 if Kind = N_Op_Not then
311 if Nkind (Op1) in N_Binary_Op then
313 -- Use negated version of the binary operators
315 if Nkind (Op1) = N_Op_And then
316 Proc_Name := RTE (RE_Vector_Nand);
318 elsif Nkind (Op1) = N_Op_Or then
319 Proc_Name := RTE (RE_Vector_Nor);
321 else pragma Assert (Nkind (Op1) = N_Op_Xor);
322 Proc_Name := RTE (RE_Vector_Xor);
323 end if;
325 Call_Node :=
326 Make_Procedure_Call_Statement (Loc,
327 Name => New_Occurrence_Of (Proc_Name, Loc),
329 Parameter_Associations => New_List (
330 Target,
331 Make_Attribute_Reference (Loc,
332 Prefix => Left_Opnd (Op1),
333 Attribute_Name => Name_Address),
335 Make_Attribute_Reference (Loc,
336 Prefix => Right_Opnd (Op1),
337 Attribute_Name => Name_Address),
339 Make_Attribute_Reference (Loc,
340 Prefix => Left_Opnd (Op1),
341 Attribute_Name => Name_Length)));
343 else
344 Proc_Name := RTE (RE_Vector_Not);
346 Call_Node :=
347 Make_Procedure_Call_Statement (Loc,
348 Name => New_Occurrence_Of (Proc_Name, Loc),
349 Parameter_Associations => New_List (
350 Target,
352 Make_Attribute_Reference (Loc,
353 Prefix => Op1,
354 Attribute_Name => Name_Address),
356 Make_Attribute_Reference (Loc,
357 Prefix => Op1,
358 Attribute_Name => Name_Length)));
359 end if;
361 else
362 -- We use the following equivalences:
364 -- (not X) or (not Y) = not (X and Y) = Nand (X, Y)
365 -- (not X) and (not Y) = not (X or Y) = Nor (X, Y)
366 -- (not X) xor (not Y) = X xor Y
367 -- X xor (not Y) = not (X xor Y) = Nxor (X, Y)
369 if Nkind (Op1) = N_Op_Not then
370 Arg1 := Right_Opnd (Op1);
371 Arg2 := Right_Opnd (Op2);
373 if Kind = N_Op_And then
374 Proc_Name := RTE (RE_Vector_Nor);
375 elsif Kind = N_Op_Or then
376 Proc_Name := RTE (RE_Vector_Nand);
377 else
378 Proc_Name := RTE (RE_Vector_Xor);
379 end if;
381 else
382 if Kind = N_Op_And then
383 Proc_Name := RTE (RE_Vector_And);
384 elsif Kind = N_Op_Or then
385 Proc_Name := RTE (RE_Vector_Or);
386 elsif Nkind (Op2) = N_Op_Not then
387 Proc_Name := RTE (RE_Vector_Nxor);
388 Arg2 := Right_Opnd (Op2);
389 else
390 Proc_Name := RTE (RE_Vector_Xor);
391 end if;
392 end if;
394 Call_Node :=
395 Make_Procedure_Call_Statement (Loc,
396 Name => New_Occurrence_Of (Proc_Name, Loc),
397 Parameter_Associations => New_List (
398 Target,
399 Make_Attribute_Reference (Loc,
400 Prefix => Arg1,
401 Attribute_Name => Name_Address),
402 Make_Attribute_Reference (Loc,
403 Prefix => Arg2,
404 Attribute_Name => Name_Address),
405 Make_Attribute_Reference (Loc,
406 Prefix => Arg1,
407 Attribute_Name => Name_Length)));
408 end if;
410 Rewrite (N, Call_Node);
411 Analyze (N);
413 exception
414 when RE_Not_Available =>
415 return;
416 end Build_Boolean_Array_Proc_Call;
418 --------------------------------
419 -- Displace_Allocator_Pointer --
420 --------------------------------
422 procedure Displace_Allocator_Pointer (N : Node_Id) is
423 Loc : constant Source_Ptr := Sloc (N);
424 Orig_Node : constant Node_Id := Original_Node (N);
425 Dtyp : Entity_Id;
426 Etyp : Entity_Id;
427 PtrT : Entity_Id;
429 begin
430 -- Do nothing in case of VM targets: the virtual machine will handle
431 -- interfaces directly.
433 if not Tagged_Type_Expansion then
434 return;
435 end if;
437 pragma Assert (Nkind (N) = N_Identifier
438 and then Nkind (Orig_Node) = N_Allocator);
440 PtrT := Etype (Orig_Node);
441 Dtyp := Available_View (Designated_Type (PtrT));
442 Etyp := Etype (Expression (Orig_Node));
444 if Is_Class_Wide_Type (Dtyp) and then Is_Interface (Dtyp) then
446 -- If the type of the allocator expression is not an interface type
447 -- we can generate code to reference the record component containing
448 -- the pointer to the secondary dispatch table.
450 if not Is_Interface (Etyp) then
451 declare
452 Saved_Typ : constant Entity_Id := Etype (Orig_Node);
454 begin
455 -- 1) Get access to the allocated object
457 Rewrite (N,
458 Make_Explicit_Dereference (Loc, Relocate_Node (N)));
459 Set_Etype (N, Etyp);
460 Set_Analyzed (N);
462 -- 2) Add the conversion to displace the pointer to reference
463 -- the secondary dispatch table.
465 Rewrite (N, Convert_To (Dtyp, Relocate_Node (N)));
466 Analyze_And_Resolve (N, Dtyp);
468 -- 3) The 'access to the secondary dispatch table will be used
469 -- as the value returned by the allocator.
471 Rewrite (N,
472 Make_Attribute_Reference (Loc,
473 Prefix => Relocate_Node (N),
474 Attribute_Name => Name_Access));
475 Set_Etype (N, Saved_Typ);
476 Set_Analyzed (N);
477 end;
479 -- If the type of the allocator expression is an interface type we
480 -- generate a run-time call to displace "this" to reference the
481 -- component containing the pointer to the secondary dispatch table
482 -- or else raise Constraint_Error if the actual object does not
483 -- implement the target interface. This case corresponds to the
484 -- following example:
486 -- function Op (Obj : Iface_1'Class) return access Iface_2'Class is
487 -- begin
488 -- return new Iface_2'Class'(Obj);
489 -- end Op;
491 else
492 Rewrite (N,
493 Unchecked_Convert_To (PtrT,
494 Make_Function_Call (Loc,
495 Name => New_Occurrence_Of (RTE (RE_Displace), Loc),
496 Parameter_Associations => New_List (
497 Unchecked_Convert_To (RTE (RE_Address),
498 Relocate_Node (N)),
500 New_Occurrence_Of
501 (Elists.Node
502 (First_Elmt
503 (Access_Disp_Table (Etype (Base_Type (Dtyp))))),
504 Loc)))));
505 Analyze_And_Resolve (N, PtrT);
506 end if;
507 end if;
508 end Displace_Allocator_Pointer;
510 ---------------------------------
511 -- Expand_Allocator_Expression --
512 ---------------------------------
514 procedure Expand_Allocator_Expression (N : Node_Id) is
515 Loc : constant Source_Ptr := Sloc (N);
516 Exp : constant Node_Id := Expression (Expression (N));
517 PtrT : constant Entity_Id := Etype (N);
518 DesigT : constant Entity_Id := Designated_Type (PtrT);
520 procedure Apply_Accessibility_Check
521 (Ref : Node_Id;
522 Built_In_Place : Boolean := False);
523 -- Ada 2005 (AI-344): For an allocator with a class-wide designated
524 -- type, generate an accessibility check to verify that the level of the
525 -- type of the created object is not deeper than the level of the access
526 -- type. If the type of the qualified expression is class-wide, then
527 -- always generate the check (except in the case where it is known to be
528 -- unnecessary, see comment below). Otherwise, only generate the check
529 -- if the level of the qualified expression type is statically deeper
530 -- than the access type.
532 -- Although the static accessibility will generally have been performed
533 -- as a legality check, it won't have been done in cases where the
534 -- allocator appears in generic body, so a run-time check is needed in
535 -- general. One special case is when the access type is declared in the
536 -- same scope as the class-wide allocator, in which case the check can
537 -- never fail, so it need not be generated.
539 -- As an open issue, there seem to be cases where the static level
540 -- associated with the class-wide object's underlying type is not
541 -- sufficient to perform the proper accessibility check, such as for
542 -- allocators in nested subprograms or accept statements initialized by
543 -- class-wide formals when the actual originates outside at a deeper
544 -- static level. The nested subprogram case might require passing
545 -- accessibility levels along with class-wide parameters, and the task
546 -- case seems to be an actual gap in the language rules that needs to
547 -- be fixed by the ARG. ???
549 -------------------------------
550 -- Apply_Accessibility_Check --
551 -------------------------------
553 procedure Apply_Accessibility_Check
554 (Ref : Node_Id;
555 Built_In_Place : Boolean := False)
557 Pool_Id : constant Entity_Id := Associated_Storage_Pool (PtrT);
558 Cond : Node_Id;
559 Fin_Call : Node_Id;
560 Free_Stmt : Node_Id;
561 Obj_Ref : Node_Id;
562 Stmts : List_Id;
564 begin
565 if Ada_Version >= Ada_2005
566 and then Is_Class_Wide_Type (DesigT)
567 and then Tagged_Type_Expansion
568 and then not Scope_Suppress.Suppress (Accessibility_Check)
569 and then
570 (Type_Access_Level (Etype (Exp)) > Type_Access_Level (PtrT)
571 or else
572 (Is_Class_Wide_Type (Etype (Exp))
573 and then Scope (PtrT) /= Current_Scope))
574 then
575 -- If the allocator was built in place, Ref is already a reference
576 -- to the access object initialized to the result of the allocator
577 -- (see Exp_Ch6.Make_Build_In_Place_Call_In_Allocator). We call
578 -- Remove_Side_Effects for cases where the build-in-place call may
579 -- still be the prefix of the reference (to avoid generating
580 -- duplicate calls). Otherwise, it is the entity associated with
581 -- the object containing the address of the allocated object.
583 if Built_In_Place then
584 Remove_Side_Effects (Ref);
585 Obj_Ref := New_Copy_Tree (Ref);
586 else
587 Obj_Ref := New_Occurrence_Of (Ref, Loc);
588 end if;
590 -- For access to interface types we must generate code to displace
591 -- the pointer to the base of the object since the subsequent code
592 -- references components located in the TSD of the object (which
593 -- is associated with the primary dispatch table --see a-tags.ads)
594 -- and also generates code invoking Free, which requires also a
595 -- reference to the base of the unallocated object.
597 if Is_Interface (DesigT) and then Tagged_Type_Expansion then
598 Obj_Ref :=
599 Unchecked_Convert_To (Etype (Obj_Ref),
600 Make_Function_Call (Loc,
601 Name =>
602 New_Occurrence_Of (RTE (RE_Base_Address), Loc),
603 Parameter_Associations => New_List (
604 Unchecked_Convert_To (RTE (RE_Address),
605 New_Copy_Tree (Obj_Ref)))));
606 end if;
608 -- Step 1: Create the object clean up code
610 Stmts := New_List;
612 -- Deallocate the object if the accessibility check fails. This
613 -- is done only on targets or profiles that support deallocation.
615 -- Free (Obj_Ref);
617 if RTE_Available (RE_Free) then
618 Free_Stmt := Make_Free_Statement (Loc, New_Copy_Tree (Obj_Ref));
619 Set_Storage_Pool (Free_Stmt, Pool_Id);
621 Append_To (Stmts, Free_Stmt);
623 -- The target or profile cannot deallocate objects
625 else
626 Free_Stmt := Empty;
627 end if;
629 -- Finalize the object if applicable. Generate:
631 -- [Deep_]Finalize (Obj_Ref.all);
633 if Needs_Finalization (DesigT)
634 and then not No_Heap_Finalization (PtrT)
635 then
636 Fin_Call :=
637 Make_Final_Call
638 (Obj_Ref =>
639 Make_Explicit_Dereference (Loc, New_Copy (Obj_Ref)),
640 Typ => DesigT);
642 -- Guard against a missing [Deep_]Finalize when the designated
643 -- type was not properly frozen.
645 if No (Fin_Call) then
646 Fin_Call := Make_Null_Statement (Loc);
647 end if;
649 -- When the target or profile supports deallocation, wrap the
650 -- finalization call in a block to ensure proper deallocation
651 -- even if finalization fails. Generate:
653 -- begin
654 -- <Fin_Call>
655 -- exception
656 -- when others =>
657 -- <Free_Stmt>
658 -- raise;
659 -- end;
661 if Present (Free_Stmt) then
662 Fin_Call :=
663 Make_Block_Statement (Loc,
664 Handled_Statement_Sequence =>
665 Make_Handled_Sequence_Of_Statements (Loc,
666 Statements => New_List (Fin_Call),
668 Exception_Handlers => New_List (
669 Make_Exception_Handler (Loc,
670 Exception_Choices => New_List (
671 Make_Others_Choice (Loc)),
672 Statements => New_List (
673 New_Copy_Tree (Free_Stmt),
674 Make_Raise_Statement (Loc))))));
675 end if;
677 Prepend_To (Stmts, Fin_Call);
678 end if;
680 -- Signal the accessibility failure through a Program_Error
682 Append_To (Stmts,
683 Make_Raise_Program_Error (Loc,
684 Condition => New_Occurrence_Of (Standard_True, Loc),
685 Reason => PE_Accessibility_Check_Failed));
687 -- Step 2: Create the accessibility comparison
689 -- Generate:
690 -- Ref'Tag
692 Obj_Ref :=
693 Make_Attribute_Reference (Loc,
694 Prefix => Obj_Ref,
695 Attribute_Name => Name_Tag);
697 -- For tagged types, determine the accessibility level by looking
698 -- at the type specific data of the dispatch table. Generate:
700 -- Type_Specific_Data (Address (Ref'Tag)).Access_Level
702 if Tagged_Type_Expansion then
703 Cond := Build_Get_Access_Level (Loc, Obj_Ref);
705 -- Use a runtime call to determine the accessibility level when
706 -- compiling on virtual machine targets. Generate:
708 -- Get_Access_Level (Ref'Tag)
710 else
711 Cond :=
712 Make_Function_Call (Loc,
713 Name =>
714 New_Occurrence_Of (RTE (RE_Get_Access_Level), Loc),
715 Parameter_Associations => New_List (Obj_Ref));
716 end if;
718 Cond :=
719 Make_Op_Gt (Loc,
720 Left_Opnd => Cond,
721 Right_Opnd =>
722 Make_Integer_Literal (Loc, Type_Access_Level (PtrT)));
724 -- Due to the complexity and side effects of the check, utilize an
725 -- if statement instead of the regular Program_Error circuitry.
727 Insert_Action (N,
728 Make_Implicit_If_Statement (N,
729 Condition => Cond,
730 Then_Statements => Stmts));
731 end if;
732 end Apply_Accessibility_Check;
734 -- Local variables
736 Aggr_In_Place : constant Boolean := Is_Delayed_Aggregate (Exp);
737 Indic : constant Node_Id := Subtype_Mark (Expression (N));
738 T : constant Entity_Id := Entity (Indic);
739 Adj_Call : Node_Id;
740 Node : Node_Id;
741 Tag_Assign : Node_Id;
742 Temp : Entity_Id;
743 Temp_Decl : Node_Id;
745 TagT : Entity_Id := Empty;
746 -- Type used as source for tag assignment
748 TagR : Node_Id := Empty;
749 -- Target reference for tag assignment
751 -- Start of processing for Expand_Allocator_Expression
753 begin
754 -- Handle call to C++ constructor
756 if Is_CPP_Constructor_Call (Exp) then
757 Make_CPP_Constructor_Call_In_Allocator
758 (Allocator => N,
759 Function_Call => Exp);
760 return;
761 end if;
763 -- In the case of an Ada 2012 allocator whose initial value comes from a
764 -- function call, pass "the accessibility level determined by the point
765 -- of call" (AI05-0234) to the function. Conceptually, this belongs in
766 -- Expand_Call but it couldn't be done there (because the Etype of the
767 -- allocator wasn't set then) so we generate the parameter here. See
768 -- the Boolean variable Defer in (a block within) Expand_Call.
770 if Ada_Version >= Ada_2012 and then Nkind (Exp) = N_Function_Call then
771 declare
772 Subp : Entity_Id;
774 begin
775 if Nkind (Name (Exp)) = N_Explicit_Dereference then
776 Subp := Designated_Type (Etype (Prefix (Name (Exp))));
777 else
778 Subp := Entity (Name (Exp));
779 end if;
781 Subp := Ultimate_Alias (Subp);
783 if Present (Extra_Accessibility_Of_Result (Subp)) then
784 Add_Extra_Actual_To_Call
785 (Subprogram_Call => Exp,
786 Extra_Formal => Extra_Accessibility_Of_Result (Subp),
787 Extra_Actual => Dynamic_Accessibility_Level (PtrT));
788 end if;
789 end;
790 end if;
792 -- Case of tagged type or type requiring finalization
794 if Is_Tagged_Type (T) or else Needs_Finalization (T) then
796 -- Ada 2005 (AI-318-02): If the initialization expression is a call
797 -- to a build-in-place function, then access to the allocated object
798 -- must be passed to the function.
800 if Is_Build_In_Place_Function_Call (Exp) then
801 Make_Build_In_Place_Call_In_Allocator (N, Exp);
802 Apply_Accessibility_Check (N, Built_In_Place => True);
803 return;
805 -- Ada 2005 (AI-318-02): Specialization of the previous case for
806 -- expressions containing a build-in-place function call whose
807 -- returned object covers interface types, and Expr has calls to
808 -- Ada.Tags.Displace to displace the pointer to the returned build-
809 -- in-place object to reference the secondary dispatch table of a
810 -- covered interface type.
812 elsif Present (Unqual_BIP_Iface_Function_Call (Exp)) then
813 Make_Build_In_Place_Iface_Call_In_Allocator (N, Exp);
814 Apply_Accessibility_Check (N, Built_In_Place => True);
815 return;
816 end if;
818 -- Actions inserted before:
819 -- Temp : constant ptr_T := new T'(Expression);
820 -- Temp._tag = T'tag; -- when not class-wide
821 -- [Deep_]Adjust (Temp.all);
823 -- We analyze by hand the new internal allocator to avoid any
824 -- recursion and inappropriate call to Initialize.
826 -- We don't want to remove side effects when the expression must be
827 -- built in place. In the case of a build-in-place function call,
828 -- that could lead to a duplication of the call, which was already
829 -- substituted for the allocator.
831 if not Aggr_In_Place then
832 Remove_Side_Effects (Exp);
833 end if;
835 Temp := Make_Temporary (Loc, 'P', N);
837 -- For a class wide allocation generate the following code:
839 -- type Equiv_Record is record ... end record;
840 -- implicit subtype CW is <Class_Wide_Subytpe>;
841 -- temp : PtrT := new CW'(CW!(expr));
843 if Is_Class_Wide_Type (T) then
844 Expand_Subtype_From_Expr (Empty, T, Indic, Exp);
846 -- Ada 2005 (AI-251): If the expression is a class-wide interface
847 -- object we generate code to move up "this" to reference the
848 -- base of the object before allocating the new object.
850 -- Note that Exp'Address is recursively expanded into a call
851 -- to Base_Address (Exp.Tag)
853 if Is_Class_Wide_Type (Etype (Exp))
854 and then Is_Interface (Etype (Exp))
855 and then Tagged_Type_Expansion
856 then
857 Set_Expression
858 (Expression (N),
859 Unchecked_Convert_To (Entity (Indic),
860 Make_Explicit_Dereference (Loc,
861 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
862 Make_Attribute_Reference (Loc,
863 Prefix => Exp,
864 Attribute_Name => Name_Address)))));
865 else
866 Set_Expression
867 (Expression (N),
868 Unchecked_Convert_To (Entity (Indic), Exp));
869 end if;
871 Analyze_And_Resolve (Expression (N), Entity (Indic));
872 end if;
874 -- Processing for allocators returning non-interface types
876 if not Is_Interface (Directly_Designated_Type (PtrT)) then
877 if Aggr_In_Place then
878 Temp_Decl :=
879 Make_Object_Declaration (Loc,
880 Defining_Identifier => Temp,
881 Object_Definition => New_Occurrence_Of (PtrT, Loc),
882 Expression =>
883 Make_Allocator (Loc,
884 Expression =>
885 New_Occurrence_Of (Etype (Exp), Loc)));
887 -- Copy the Comes_From_Source flag for the allocator we just
888 -- built, since logically this allocator is a replacement of
889 -- the original allocator node. This is for proper handling of
890 -- restriction No_Implicit_Heap_Allocations.
892 Set_Comes_From_Source
893 (Expression (Temp_Decl), Comes_From_Source (N));
895 Set_No_Initialization (Expression (Temp_Decl));
896 Insert_Action (N, Temp_Decl);
898 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
899 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
901 else
902 Node := Relocate_Node (N);
903 Set_Analyzed (Node);
905 Temp_Decl :=
906 Make_Object_Declaration (Loc,
907 Defining_Identifier => Temp,
908 Constant_Present => True,
909 Object_Definition => New_Occurrence_Of (PtrT, Loc),
910 Expression => Node);
912 Insert_Action (N, Temp_Decl);
913 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
914 end if;
916 -- Ada 2005 (AI-251): Handle allocators whose designated type is an
917 -- interface type. In this case we use the type of the qualified
918 -- expression to allocate the object.
920 else
921 declare
922 Def_Id : constant Entity_Id := Make_Temporary (Loc, 'T');
923 New_Decl : Node_Id;
925 begin
926 New_Decl :=
927 Make_Full_Type_Declaration (Loc,
928 Defining_Identifier => Def_Id,
929 Type_Definition =>
930 Make_Access_To_Object_Definition (Loc,
931 All_Present => True,
932 Null_Exclusion_Present => False,
933 Constant_Present =>
934 Is_Access_Constant (Etype (N)),
935 Subtype_Indication =>
936 New_Occurrence_Of (Etype (Exp), Loc)));
938 Insert_Action (N, New_Decl);
940 -- Inherit the allocation-related attributes from the original
941 -- access type.
943 Set_Finalization_Master
944 (Def_Id, Finalization_Master (PtrT));
946 Set_Associated_Storage_Pool
947 (Def_Id, Associated_Storage_Pool (PtrT));
949 -- Declare the object using the previous type declaration
951 if Aggr_In_Place then
952 Temp_Decl :=
953 Make_Object_Declaration (Loc,
954 Defining_Identifier => Temp,
955 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
956 Expression =>
957 Make_Allocator (Loc,
958 New_Occurrence_Of (Etype (Exp), Loc)));
960 -- Copy the Comes_From_Source flag for the allocator we just
961 -- built, since logically this allocator is a replacement of
962 -- the original allocator node. This is for proper handling
963 -- of restriction No_Implicit_Heap_Allocations.
965 Set_Comes_From_Source
966 (Expression (Temp_Decl), Comes_From_Source (N));
968 Set_No_Initialization (Expression (Temp_Decl));
969 Insert_Action (N, Temp_Decl);
971 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
972 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
974 else
975 Node := Relocate_Node (N);
976 Set_Analyzed (Node);
978 Temp_Decl :=
979 Make_Object_Declaration (Loc,
980 Defining_Identifier => Temp,
981 Constant_Present => True,
982 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
983 Expression => Node);
985 Insert_Action (N, Temp_Decl);
986 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
987 end if;
989 -- Generate an additional object containing the address of the
990 -- returned object. The type of this second object declaration
991 -- is the correct type required for the common processing that
992 -- is still performed by this subprogram. The displacement of
993 -- this pointer to reference the component associated with the
994 -- interface type will be done at the end of common processing.
996 New_Decl :=
997 Make_Object_Declaration (Loc,
998 Defining_Identifier => Make_Temporary (Loc, 'P'),
999 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1000 Expression =>
1001 Unchecked_Convert_To (PtrT,
1002 New_Occurrence_Of (Temp, Loc)));
1004 Insert_Action (N, New_Decl);
1006 Temp_Decl := New_Decl;
1007 Temp := Defining_Identifier (New_Decl);
1008 end;
1009 end if;
1011 -- Generate the tag assignment
1013 -- Suppress the tag assignment for VM targets because VM tags are
1014 -- represented implicitly in objects.
1016 if not Tagged_Type_Expansion then
1017 null;
1019 -- Ada 2005 (AI-251): Suppress the tag assignment with class-wide
1020 -- interface objects because in this case the tag does not change.
1022 elsif Is_Interface (Directly_Designated_Type (Etype (N))) then
1023 pragma Assert (Is_Class_Wide_Type
1024 (Directly_Designated_Type (Etype (N))));
1025 null;
1027 elsif Is_Tagged_Type (T) and then not Is_Class_Wide_Type (T) then
1028 TagT := T;
1029 TagR := New_Occurrence_Of (Temp, Loc);
1031 elsif Is_Private_Type (T)
1032 and then Is_Tagged_Type (Underlying_Type (T))
1033 then
1034 TagT := Underlying_Type (T);
1035 TagR :=
1036 Unchecked_Convert_To (Underlying_Type (T),
1037 Make_Explicit_Dereference (Loc,
1038 Prefix => New_Occurrence_Of (Temp, Loc)));
1039 end if;
1041 if Present (TagT) then
1042 declare
1043 Full_T : constant Entity_Id := Underlying_Type (TagT);
1045 begin
1046 Tag_Assign :=
1047 Make_Assignment_Statement (Loc,
1048 Name =>
1049 Make_Selected_Component (Loc,
1050 Prefix => TagR,
1051 Selector_Name =>
1052 New_Occurrence_Of
1053 (First_Tag_Component (Full_T), Loc)),
1055 Expression =>
1056 Unchecked_Convert_To (RTE (RE_Tag),
1057 New_Occurrence_Of
1058 (Elists.Node
1059 (First_Elmt (Access_Disp_Table (Full_T))), Loc)));
1060 end;
1062 -- The previous assignment has to be done in any case
1064 Set_Assignment_OK (Name (Tag_Assign));
1065 Insert_Action (N, Tag_Assign);
1066 end if;
1068 -- Generate an Adjust call if the object will be moved. In Ada 2005,
1069 -- the object may be inherently limited, in which case there is no
1070 -- Adjust procedure, and the object is built in place. In Ada 95, the
1071 -- object can be limited but not inherently limited if this allocator
1072 -- came from a return statement (we're allocating the result on the
1073 -- secondary stack). In that case, the object will be moved, so we do
1074 -- want to Adjust. However, if it's a nonlimited build-in-place
1075 -- function call, Adjust is not wanted.
1077 if Needs_Finalization (DesigT)
1078 and then Needs_Finalization (T)
1079 and then not Aggr_In_Place
1080 and then not Is_Limited_View (T)
1081 and then not Alloc_For_BIP_Return (N)
1082 and then not Is_Build_In_Place_Function_Call (Expression (N))
1083 then
1084 -- An unchecked conversion is needed in the classwide case because
1085 -- the designated type can be an ancestor of the subtype mark of
1086 -- the allocator.
1088 Adj_Call :=
1089 Make_Adjust_Call
1090 (Obj_Ref =>
1091 Unchecked_Convert_To (T,
1092 Make_Explicit_Dereference (Loc,
1093 Prefix => New_Occurrence_Of (Temp, Loc))),
1094 Typ => T);
1096 if Present (Adj_Call) then
1097 Insert_Action (N, Adj_Call);
1098 end if;
1099 end if;
1101 -- Note: the accessibility check must be inserted after the call to
1102 -- [Deep_]Adjust to ensure proper completion of the assignment.
1104 Apply_Accessibility_Check (Temp);
1106 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1107 Analyze_And_Resolve (N, PtrT);
1109 -- Ada 2005 (AI-251): Displace the pointer to reference the record
1110 -- component containing the secondary dispatch table of the interface
1111 -- type.
1113 if Is_Interface (Directly_Designated_Type (PtrT)) then
1114 Displace_Allocator_Pointer (N);
1115 end if;
1117 -- Always force the generation of a temporary for aggregates when
1118 -- generating C code, to simplify the work in the code generator.
1120 elsif Aggr_In_Place
1121 or else (Modify_Tree_For_C and then Nkind (Exp) = N_Aggregate)
1122 then
1123 Temp := Make_Temporary (Loc, 'P', N);
1124 Temp_Decl :=
1125 Make_Object_Declaration (Loc,
1126 Defining_Identifier => Temp,
1127 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1128 Expression =>
1129 Make_Allocator (Loc,
1130 Expression => New_Occurrence_Of (Etype (Exp), Loc)));
1132 -- Copy the Comes_From_Source flag for the allocator we just built,
1133 -- since logically this allocator is a replacement of the original
1134 -- allocator node. This is for proper handling of restriction
1135 -- No_Implicit_Heap_Allocations.
1137 Set_Comes_From_Source
1138 (Expression (Temp_Decl), Comes_From_Source (N));
1140 Set_No_Initialization (Expression (Temp_Decl));
1141 Insert_Action (N, Temp_Decl);
1143 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1144 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1146 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1147 Analyze_And_Resolve (N, PtrT);
1149 elsif Is_Access_Type (T) and then Can_Never_Be_Null (T) then
1150 Install_Null_Excluding_Check (Exp);
1152 elsif Is_Access_Type (DesigT)
1153 and then Nkind (Exp) = N_Allocator
1154 and then Nkind (Expression (Exp)) /= N_Qualified_Expression
1155 then
1156 -- Apply constraint to designated subtype indication
1158 Apply_Constraint_Check
1159 (Expression (Exp), Designated_Type (DesigT), No_Sliding => True);
1161 if Nkind (Expression (Exp)) = N_Raise_Constraint_Error then
1163 -- Propagate constraint_error to enclosing allocator
1165 Rewrite (Exp, New_Copy (Expression (Exp)));
1166 end if;
1168 else
1169 Build_Allocate_Deallocate_Proc (N, True);
1171 -- If we have:
1172 -- type A is access T1;
1173 -- X : A := new T2'(...);
1174 -- T1 and T2 can be different subtypes, and we might need to check
1175 -- both constraints. First check against the type of the qualified
1176 -- expression.
1178 Apply_Constraint_Check (Exp, T, No_Sliding => True);
1180 if Do_Range_Check (Exp) then
1181 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1182 end if;
1184 -- A check is also needed in cases where the designated subtype is
1185 -- constrained and differs from the subtype given in the qualified
1186 -- expression. Note that the check on the qualified expression does
1187 -- not allow sliding, but this check does (a relaxation from Ada 83).
1189 if Is_Constrained (DesigT)
1190 and then not Subtypes_Statically_Match (T, DesigT)
1191 then
1192 Apply_Constraint_Check
1193 (Exp, DesigT, No_Sliding => False);
1195 if Do_Range_Check (Exp) then
1196 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1197 end if;
1198 end if;
1200 -- For an access to unconstrained packed array, GIGI needs to see an
1201 -- expression with a constrained subtype in order to compute the
1202 -- proper size for the allocator.
1204 if Is_Array_Type (T)
1205 and then not Is_Constrained (T)
1206 and then Is_Packed (T)
1207 then
1208 declare
1209 ConstrT : constant Entity_Id := Make_Temporary (Loc, 'A');
1210 Internal_Exp : constant Node_Id := Relocate_Node (Exp);
1211 begin
1212 Insert_Action (Exp,
1213 Make_Subtype_Declaration (Loc,
1214 Defining_Identifier => ConstrT,
1215 Subtype_Indication =>
1216 Make_Subtype_From_Expr (Internal_Exp, T)));
1217 Freeze_Itype (ConstrT, Exp);
1218 Rewrite (Exp, OK_Convert_To (ConstrT, Internal_Exp));
1219 end;
1220 end if;
1222 -- Ada 2005 (AI-318-02): If the initialization expression is a call
1223 -- to a build-in-place function, then access to the allocated object
1224 -- must be passed to the function.
1226 if Is_Build_In_Place_Function_Call (Exp) then
1227 Make_Build_In_Place_Call_In_Allocator (N, Exp);
1228 end if;
1229 end if;
1231 exception
1232 when RE_Not_Available =>
1233 return;
1234 end Expand_Allocator_Expression;
1236 -----------------------------
1237 -- Expand_Array_Comparison --
1238 -----------------------------
1240 -- Expansion is only required in the case of array types. For the unpacked
1241 -- case, an appropriate runtime routine is called. For packed cases, and
1242 -- also in some other cases where a runtime routine cannot be called, the
1243 -- form of the expansion is:
1245 -- [body for greater_nn; boolean_expression]
1247 -- The body is built by Make_Array_Comparison_Op, and the form of the
1248 -- Boolean expression depends on the operator involved.
1250 procedure Expand_Array_Comparison (N : Node_Id) is
1251 Loc : constant Source_Ptr := Sloc (N);
1252 Op1 : Node_Id := Left_Opnd (N);
1253 Op2 : Node_Id := Right_Opnd (N);
1254 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
1255 Ctyp : constant Entity_Id := Component_Type (Typ1);
1257 Expr : Node_Id;
1258 Func_Body : Node_Id;
1259 Func_Name : Entity_Id;
1261 Comp : RE_Id;
1263 Byte_Addressable : constant Boolean := System_Storage_Unit = Byte'Size;
1264 -- True for byte addressable target
1266 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean;
1267 -- Returns True if the length of the given operand is known to be less
1268 -- than 4. Returns False if this length is known to be four or greater
1269 -- or is not known at compile time.
1271 ------------------------
1272 -- Length_Less_Than_4 --
1273 ------------------------
1275 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean is
1276 Otyp : constant Entity_Id := Etype (Opnd);
1278 begin
1279 if Ekind (Otyp) = E_String_Literal_Subtype then
1280 return String_Literal_Length (Otyp) < 4;
1282 else
1283 declare
1284 Ityp : constant Entity_Id := Etype (First_Index (Otyp));
1285 Lo : constant Node_Id := Type_Low_Bound (Ityp);
1286 Hi : constant Node_Id := Type_High_Bound (Ityp);
1287 Lov : Uint;
1288 Hiv : Uint;
1290 begin
1291 if Compile_Time_Known_Value (Lo) then
1292 Lov := Expr_Value (Lo);
1293 else
1294 return False;
1295 end if;
1297 if Compile_Time_Known_Value (Hi) then
1298 Hiv := Expr_Value (Hi);
1299 else
1300 return False;
1301 end if;
1303 return Hiv < Lov + 3;
1304 end;
1305 end if;
1306 end Length_Less_Than_4;
1308 -- Start of processing for Expand_Array_Comparison
1310 begin
1311 -- Deal first with unpacked case, where we can call a runtime routine
1312 -- except that we avoid this for targets for which are not addressable
1313 -- by bytes.
1315 if not Is_Bit_Packed_Array (Typ1)
1316 and then Byte_Addressable
1317 then
1318 -- The call we generate is:
1320 -- Compare_Array_xn[_Unaligned]
1321 -- (left'address, right'address, left'length, right'length) <op> 0
1323 -- x = U for unsigned, S for signed
1324 -- n = 8,16,32,64 for component size
1325 -- Add _Unaligned if length < 4 and component size is 8.
1326 -- <op> is the standard comparison operator
1328 if Component_Size (Typ1) = 8 then
1329 if Length_Less_Than_4 (Op1)
1330 or else
1331 Length_Less_Than_4 (Op2)
1332 then
1333 if Is_Unsigned_Type (Ctyp) then
1334 Comp := RE_Compare_Array_U8_Unaligned;
1335 else
1336 Comp := RE_Compare_Array_S8_Unaligned;
1337 end if;
1339 else
1340 if Is_Unsigned_Type (Ctyp) then
1341 Comp := RE_Compare_Array_U8;
1342 else
1343 Comp := RE_Compare_Array_S8;
1344 end if;
1345 end if;
1347 elsif Component_Size (Typ1) = 16 then
1348 if Is_Unsigned_Type (Ctyp) then
1349 Comp := RE_Compare_Array_U16;
1350 else
1351 Comp := RE_Compare_Array_S16;
1352 end if;
1354 elsif Component_Size (Typ1) = 32 then
1355 if Is_Unsigned_Type (Ctyp) then
1356 Comp := RE_Compare_Array_U32;
1357 else
1358 Comp := RE_Compare_Array_S32;
1359 end if;
1361 else pragma Assert (Component_Size (Typ1) = 64);
1362 if Is_Unsigned_Type (Ctyp) then
1363 Comp := RE_Compare_Array_U64;
1364 else
1365 Comp := RE_Compare_Array_S64;
1366 end if;
1367 end if;
1369 if RTE_Available (Comp) then
1371 -- Expand to a call only if the runtime function is available,
1372 -- otherwise fall back to inline code.
1374 Remove_Side_Effects (Op1, Name_Req => True);
1375 Remove_Side_Effects (Op2, Name_Req => True);
1377 Rewrite (Op1,
1378 Make_Function_Call (Sloc (Op1),
1379 Name => New_Occurrence_Of (RTE (Comp), Loc),
1381 Parameter_Associations => New_List (
1382 Make_Attribute_Reference (Loc,
1383 Prefix => Relocate_Node (Op1),
1384 Attribute_Name => Name_Address),
1386 Make_Attribute_Reference (Loc,
1387 Prefix => Relocate_Node (Op2),
1388 Attribute_Name => Name_Address),
1390 Make_Attribute_Reference (Loc,
1391 Prefix => Relocate_Node (Op1),
1392 Attribute_Name => Name_Length),
1394 Make_Attribute_Reference (Loc,
1395 Prefix => Relocate_Node (Op2),
1396 Attribute_Name => Name_Length))));
1398 Rewrite (Op2,
1399 Make_Integer_Literal (Sloc (Op2),
1400 Intval => Uint_0));
1402 Analyze_And_Resolve (Op1, Standard_Integer);
1403 Analyze_And_Resolve (Op2, Standard_Integer);
1404 return;
1405 end if;
1406 end if;
1408 -- Cases where we cannot make runtime call
1410 -- For (a <= b) we convert to not (a > b)
1412 if Chars (N) = Name_Op_Le then
1413 Rewrite (N,
1414 Make_Op_Not (Loc,
1415 Right_Opnd =>
1416 Make_Op_Gt (Loc,
1417 Left_Opnd => Op1,
1418 Right_Opnd => Op2)));
1419 Analyze_And_Resolve (N, Standard_Boolean);
1420 return;
1422 -- For < the Boolean expression is
1423 -- greater__nn (op2, op1)
1425 elsif Chars (N) = Name_Op_Lt then
1426 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1428 -- Switch operands
1430 Op1 := Right_Opnd (N);
1431 Op2 := Left_Opnd (N);
1433 -- For (a >= b) we convert to not (a < b)
1435 elsif Chars (N) = Name_Op_Ge then
1436 Rewrite (N,
1437 Make_Op_Not (Loc,
1438 Right_Opnd =>
1439 Make_Op_Lt (Loc,
1440 Left_Opnd => Op1,
1441 Right_Opnd => Op2)));
1442 Analyze_And_Resolve (N, Standard_Boolean);
1443 return;
1445 -- For > the Boolean expression is
1446 -- greater__nn (op1, op2)
1448 else
1449 pragma Assert (Chars (N) = Name_Op_Gt);
1450 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1451 end if;
1453 Func_Name := Defining_Unit_Name (Specification (Func_Body));
1454 Expr :=
1455 Make_Function_Call (Loc,
1456 Name => New_Occurrence_Of (Func_Name, Loc),
1457 Parameter_Associations => New_List (Op1, Op2));
1459 Insert_Action (N, Func_Body);
1460 Rewrite (N, Expr);
1461 Analyze_And_Resolve (N, Standard_Boolean);
1462 end Expand_Array_Comparison;
1464 ---------------------------
1465 -- Expand_Array_Equality --
1466 ---------------------------
1468 -- Expand an equality function for multi-dimensional arrays. Here is an
1469 -- example of such a function for Nb_Dimension = 2
1471 -- function Enn (A : atyp; B : btyp) return boolean is
1472 -- begin
1473 -- if (A'length (1) = 0 or else A'length (2) = 0)
1474 -- and then
1475 -- (B'length (1) = 0 or else B'length (2) = 0)
1476 -- then
1477 -- return True; -- RM 4.5.2(22)
1478 -- end if;
1480 -- if A'length (1) /= B'length (1)
1481 -- or else
1482 -- A'length (2) /= B'length (2)
1483 -- then
1484 -- return False; -- RM 4.5.2(23)
1485 -- end if;
1487 -- declare
1488 -- A1 : Index_T1 := A'first (1);
1489 -- B1 : Index_T1 := B'first (1);
1490 -- begin
1491 -- loop
1492 -- declare
1493 -- A2 : Index_T2 := A'first (2);
1494 -- B2 : Index_T2 := B'first (2);
1495 -- begin
1496 -- loop
1497 -- if A (A1, A2) /= B (B1, B2) then
1498 -- return False;
1499 -- end if;
1501 -- exit when A2 = A'last (2);
1502 -- A2 := Index_T2'succ (A2);
1503 -- B2 := Index_T2'succ (B2);
1504 -- end loop;
1505 -- end;
1507 -- exit when A1 = A'last (1);
1508 -- A1 := Index_T1'succ (A1);
1509 -- B1 := Index_T1'succ (B1);
1510 -- end loop;
1511 -- end;
1513 -- return true;
1514 -- end Enn;
1516 -- Note on the formal types used (atyp and btyp). If either of the arrays
1517 -- is of a private type, we use the underlying type, and do an unchecked
1518 -- conversion of the actual. If either of the arrays has a bound depending
1519 -- on a discriminant, then we use the base type since otherwise we have an
1520 -- escaped discriminant in the function.
1522 -- If both arrays are constrained and have the same bounds, we can generate
1523 -- a loop with an explicit iteration scheme using a 'Range attribute over
1524 -- the first array.
1526 function Expand_Array_Equality
1527 (Nod : Node_Id;
1528 Lhs : Node_Id;
1529 Rhs : Node_Id;
1530 Bodies : List_Id;
1531 Typ : Entity_Id) return Node_Id
1533 Loc : constant Source_Ptr := Sloc (Nod);
1534 Decls : constant List_Id := New_List;
1535 Index_List1 : constant List_Id := New_List;
1536 Index_List2 : constant List_Id := New_List;
1538 Actuals : List_Id;
1539 Formals : List_Id;
1540 Func_Name : Entity_Id;
1541 Func_Body : Node_Id;
1543 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
1544 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
1546 Ltyp : Entity_Id;
1547 Rtyp : Entity_Id;
1548 -- The parameter types to be used for the formals
1550 function Arr_Attr
1551 (Arr : Entity_Id;
1552 Nam : Name_Id;
1553 Num : Int) return Node_Id;
1554 -- This builds the attribute reference Arr'Nam (Expr)
1556 function Component_Equality (Typ : Entity_Id) return Node_Id;
1557 -- Create one statement to compare corresponding components, designated
1558 -- by a full set of indexes.
1560 function Get_Arg_Type (N : Node_Id) return Entity_Id;
1561 -- Given one of the arguments, computes the appropriate type to be used
1562 -- for that argument in the corresponding function formal
1564 function Handle_One_Dimension
1565 (N : Int;
1566 Index : Node_Id) return Node_Id;
1567 -- This procedure returns the following code
1569 -- declare
1570 -- Bn : Index_T := B'First (N);
1571 -- begin
1572 -- loop
1573 -- xxx
1574 -- exit when An = A'Last (N);
1575 -- An := Index_T'Succ (An)
1576 -- Bn := Index_T'Succ (Bn)
1577 -- end loop;
1578 -- end;
1580 -- If both indexes are constrained and identical, the procedure
1581 -- returns a simpler loop:
1583 -- for An in A'Range (N) loop
1584 -- xxx
1585 -- end loop
1587 -- N is the dimension for which we are generating a loop. Index is the
1588 -- N'th index node, whose Etype is Index_Type_n in the above code. The
1589 -- xxx statement is either the loop or declare for the next dimension
1590 -- or if this is the last dimension the comparison of corresponding
1591 -- components of the arrays.
1593 -- The actual way the code works is to return the comparison of
1594 -- corresponding components for the N+1 call. That's neater.
1596 function Test_Empty_Arrays return Node_Id;
1597 -- This function constructs the test for both arrays being empty
1598 -- (A'length (1) = 0 or else A'length (2) = 0 or else ...)
1599 -- and then
1600 -- (B'length (1) = 0 or else B'length (2) = 0 or else ...)
1602 function Test_Lengths_Correspond return Node_Id;
1603 -- This function constructs the test for arrays having different lengths
1604 -- in at least one index position, in which case the resulting code is:
1606 -- A'length (1) /= B'length (1)
1607 -- or else
1608 -- A'length (2) /= B'length (2)
1609 -- or else
1610 -- ...
1612 --------------
1613 -- Arr_Attr --
1614 --------------
1616 function Arr_Attr
1617 (Arr : Entity_Id;
1618 Nam : Name_Id;
1619 Num : Int) return Node_Id
1621 begin
1622 return
1623 Make_Attribute_Reference (Loc,
1624 Attribute_Name => Nam,
1625 Prefix => New_Occurrence_Of (Arr, Loc),
1626 Expressions => New_List (Make_Integer_Literal (Loc, Num)));
1627 end Arr_Attr;
1629 ------------------------
1630 -- Component_Equality --
1631 ------------------------
1633 function Component_Equality (Typ : Entity_Id) return Node_Id is
1634 Test : Node_Id;
1635 L, R : Node_Id;
1637 begin
1638 -- if a(i1...) /= b(j1...) then return false; end if;
1640 L :=
1641 Make_Indexed_Component (Loc,
1642 Prefix => Make_Identifier (Loc, Chars (A)),
1643 Expressions => Index_List1);
1645 R :=
1646 Make_Indexed_Component (Loc,
1647 Prefix => Make_Identifier (Loc, Chars (B)),
1648 Expressions => Index_List2);
1650 Test := Expand_Composite_Equality
1651 (Nod, Component_Type (Typ), L, R, Decls);
1653 -- If some (sub)component is an unchecked_union, the whole operation
1654 -- will raise program error.
1656 if Nkind (Test) = N_Raise_Program_Error then
1658 -- This node is going to be inserted at a location where a
1659 -- statement is expected: clear its Etype so analysis will set
1660 -- it to the expected Standard_Void_Type.
1662 Set_Etype (Test, Empty);
1663 return Test;
1665 else
1666 return
1667 Make_Implicit_If_Statement (Nod,
1668 Condition => Make_Op_Not (Loc, Right_Opnd => Test),
1669 Then_Statements => New_List (
1670 Make_Simple_Return_Statement (Loc,
1671 Expression => New_Occurrence_Of (Standard_False, Loc))));
1672 end if;
1673 end Component_Equality;
1675 ------------------
1676 -- Get_Arg_Type --
1677 ------------------
1679 function Get_Arg_Type (N : Node_Id) return Entity_Id is
1680 T : Entity_Id;
1681 X : Node_Id;
1683 begin
1684 T := Etype (N);
1686 if No (T) then
1687 return Typ;
1689 else
1690 T := Underlying_Type (T);
1692 X := First_Index (T);
1693 while Present (X) loop
1694 if Denotes_Discriminant (Type_Low_Bound (Etype (X)))
1695 or else
1696 Denotes_Discriminant (Type_High_Bound (Etype (X)))
1697 then
1698 T := Base_Type (T);
1699 exit;
1700 end if;
1702 Next_Index (X);
1703 end loop;
1705 return T;
1706 end if;
1707 end Get_Arg_Type;
1709 --------------------------
1710 -- Handle_One_Dimension --
1711 ---------------------------
1713 function Handle_One_Dimension
1714 (N : Int;
1715 Index : Node_Id) return Node_Id
1717 Need_Separate_Indexes : constant Boolean :=
1718 Ltyp /= Rtyp or else not Is_Constrained (Ltyp);
1719 -- If the index types are identical, and we are working with
1720 -- constrained types, then we can use the same index for both
1721 -- of the arrays.
1723 An : constant Entity_Id := Make_Temporary (Loc, 'A');
1725 Bn : Entity_Id;
1726 Index_T : Entity_Id;
1727 Stm_List : List_Id;
1728 Loop_Stm : Node_Id;
1730 begin
1731 if N > Number_Dimensions (Ltyp) then
1732 return Component_Equality (Ltyp);
1733 end if;
1735 -- Case where we generate a loop
1737 Index_T := Base_Type (Etype (Index));
1739 if Need_Separate_Indexes then
1740 Bn := Make_Temporary (Loc, 'B');
1741 else
1742 Bn := An;
1743 end if;
1745 Append (New_Occurrence_Of (An, Loc), Index_List1);
1746 Append (New_Occurrence_Of (Bn, Loc), Index_List2);
1748 Stm_List := New_List (
1749 Handle_One_Dimension (N + 1, Next_Index (Index)));
1751 if Need_Separate_Indexes then
1753 -- Generate guard for loop, followed by increments of indexes
1755 Append_To (Stm_List,
1756 Make_Exit_Statement (Loc,
1757 Condition =>
1758 Make_Op_Eq (Loc,
1759 Left_Opnd => New_Occurrence_Of (An, Loc),
1760 Right_Opnd => Arr_Attr (A, Name_Last, N))));
1762 Append_To (Stm_List,
1763 Make_Assignment_Statement (Loc,
1764 Name => New_Occurrence_Of (An, Loc),
1765 Expression =>
1766 Make_Attribute_Reference (Loc,
1767 Prefix => New_Occurrence_Of (Index_T, Loc),
1768 Attribute_Name => Name_Succ,
1769 Expressions => New_List (
1770 New_Occurrence_Of (An, Loc)))));
1772 Append_To (Stm_List,
1773 Make_Assignment_Statement (Loc,
1774 Name => New_Occurrence_Of (Bn, Loc),
1775 Expression =>
1776 Make_Attribute_Reference (Loc,
1777 Prefix => New_Occurrence_Of (Index_T, Loc),
1778 Attribute_Name => Name_Succ,
1779 Expressions => New_List (
1780 New_Occurrence_Of (Bn, Loc)))));
1781 end if;
1783 -- If separate indexes, we need a declare block for An and Bn, and a
1784 -- loop without an iteration scheme.
1786 if Need_Separate_Indexes then
1787 Loop_Stm :=
1788 Make_Implicit_Loop_Statement (Nod, Statements => Stm_List);
1790 return
1791 Make_Block_Statement (Loc,
1792 Declarations => New_List (
1793 Make_Object_Declaration (Loc,
1794 Defining_Identifier => An,
1795 Object_Definition => New_Occurrence_Of (Index_T, Loc),
1796 Expression => Arr_Attr (A, Name_First, N)),
1798 Make_Object_Declaration (Loc,
1799 Defining_Identifier => Bn,
1800 Object_Definition => New_Occurrence_Of (Index_T, Loc),
1801 Expression => Arr_Attr (B, Name_First, N))),
1803 Handled_Statement_Sequence =>
1804 Make_Handled_Sequence_Of_Statements (Loc,
1805 Statements => New_List (Loop_Stm)));
1807 -- If no separate indexes, return loop statement with explicit
1808 -- iteration scheme on its own
1810 else
1811 Loop_Stm :=
1812 Make_Implicit_Loop_Statement (Nod,
1813 Statements => Stm_List,
1814 Iteration_Scheme =>
1815 Make_Iteration_Scheme (Loc,
1816 Loop_Parameter_Specification =>
1817 Make_Loop_Parameter_Specification (Loc,
1818 Defining_Identifier => An,
1819 Discrete_Subtype_Definition =>
1820 Arr_Attr (A, Name_Range, N))));
1821 return Loop_Stm;
1822 end if;
1823 end Handle_One_Dimension;
1825 -----------------------
1826 -- Test_Empty_Arrays --
1827 -----------------------
1829 function Test_Empty_Arrays return Node_Id is
1830 Alist : Node_Id;
1831 Blist : Node_Id;
1833 Atest : Node_Id;
1834 Btest : Node_Id;
1836 begin
1837 Alist := Empty;
1838 Blist := Empty;
1839 for J in 1 .. Number_Dimensions (Ltyp) loop
1840 Atest :=
1841 Make_Op_Eq (Loc,
1842 Left_Opnd => Arr_Attr (A, Name_Length, J),
1843 Right_Opnd => Make_Integer_Literal (Loc, 0));
1845 Btest :=
1846 Make_Op_Eq (Loc,
1847 Left_Opnd => Arr_Attr (B, Name_Length, J),
1848 Right_Opnd => Make_Integer_Literal (Loc, 0));
1850 if No (Alist) then
1851 Alist := Atest;
1852 Blist := Btest;
1854 else
1855 Alist :=
1856 Make_Or_Else (Loc,
1857 Left_Opnd => Relocate_Node (Alist),
1858 Right_Opnd => Atest);
1860 Blist :=
1861 Make_Or_Else (Loc,
1862 Left_Opnd => Relocate_Node (Blist),
1863 Right_Opnd => Btest);
1864 end if;
1865 end loop;
1867 return
1868 Make_And_Then (Loc,
1869 Left_Opnd => Alist,
1870 Right_Opnd => Blist);
1871 end Test_Empty_Arrays;
1873 -----------------------------
1874 -- Test_Lengths_Correspond --
1875 -----------------------------
1877 function Test_Lengths_Correspond return Node_Id is
1878 Result : Node_Id;
1879 Rtest : Node_Id;
1881 begin
1882 Result := Empty;
1883 for J in 1 .. Number_Dimensions (Ltyp) loop
1884 Rtest :=
1885 Make_Op_Ne (Loc,
1886 Left_Opnd => Arr_Attr (A, Name_Length, J),
1887 Right_Opnd => Arr_Attr (B, Name_Length, J));
1889 if No (Result) then
1890 Result := Rtest;
1891 else
1892 Result :=
1893 Make_Or_Else (Loc,
1894 Left_Opnd => Relocate_Node (Result),
1895 Right_Opnd => Rtest);
1896 end if;
1897 end loop;
1899 return Result;
1900 end Test_Lengths_Correspond;
1902 -- Start of processing for Expand_Array_Equality
1904 begin
1905 Ltyp := Get_Arg_Type (Lhs);
1906 Rtyp := Get_Arg_Type (Rhs);
1908 -- For now, if the argument types are not the same, go to the base type,
1909 -- since the code assumes that the formals have the same type. This is
1910 -- fixable in future ???
1912 if Ltyp /= Rtyp then
1913 Ltyp := Base_Type (Ltyp);
1914 Rtyp := Base_Type (Rtyp);
1915 pragma Assert (Ltyp = Rtyp);
1916 end if;
1918 -- Build list of formals for function
1920 Formals := New_List (
1921 Make_Parameter_Specification (Loc,
1922 Defining_Identifier => A,
1923 Parameter_Type => New_Occurrence_Of (Ltyp, Loc)),
1925 Make_Parameter_Specification (Loc,
1926 Defining_Identifier => B,
1927 Parameter_Type => New_Occurrence_Of (Rtyp, Loc)));
1929 Func_Name := Make_Temporary (Loc, 'E');
1931 -- Build statement sequence for function
1933 Func_Body :=
1934 Make_Subprogram_Body (Loc,
1935 Specification =>
1936 Make_Function_Specification (Loc,
1937 Defining_Unit_Name => Func_Name,
1938 Parameter_Specifications => Formals,
1939 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
1941 Declarations => Decls,
1943 Handled_Statement_Sequence =>
1944 Make_Handled_Sequence_Of_Statements (Loc,
1945 Statements => New_List (
1947 Make_Implicit_If_Statement (Nod,
1948 Condition => Test_Empty_Arrays,
1949 Then_Statements => New_List (
1950 Make_Simple_Return_Statement (Loc,
1951 Expression =>
1952 New_Occurrence_Of (Standard_True, Loc)))),
1954 Make_Implicit_If_Statement (Nod,
1955 Condition => Test_Lengths_Correspond,
1956 Then_Statements => New_List (
1957 Make_Simple_Return_Statement (Loc,
1958 Expression => New_Occurrence_Of (Standard_False, Loc)))),
1960 Handle_One_Dimension (1, First_Index (Ltyp)),
1962 Make_Simple_Return_Statement (Loc,
1963 Expression => New_Occurrence_Of (Standard_True, Loc)))));
1965 Set_Has_Completion (Func_Name, True);
1966 Set_Is_Inlined (Func_Name);
1968 -- If the array type is distinct from the type of the arguments, it
1969 -- is the full view of a private type. Apply an unchecked conversion
1970 -- to insure that analysis of the call succeeds.
1972 declare
1973 L, R : Node_Id;
1975 begin
1976 L := Lhs;
1977 R := Rhs;
1979 if No (Etype (Lhs))
1980 or else Base_Type (Etype (Lhs)) /= Base_Type (Ltyp)
1981 then
1982 L := OK_Convert_To (Ltyp, Lhs);
1983 end if;
1985 if No (Etype (Rhs))
1986 or else Base_Type (Etype (Rhs)) /= Base_Type (Rtyp)
1987 then
1988 R := OK_Convert_To (Rtyp, Rhs);
1989 end if;
1991 Actuals := New_List (L, R);
1992 end;
1994 Append_To (Bodies, Func_Body);
1996 return
1997 Make_Function_Call (Loc,
1998 Name => New_Occurrence_Of (Func_Name, Loc),
1999 Parameter_Associations => Actuals);
2000 end Expand_Array_Equality;
2002 -----------------------------
2003 -- Expand_Boolean_Operator --
2004 -----------------------------
2006 -- Note that we first get the actual subtypes of the operands, since we
2007 -- always want to deal with types that have bounds.
2009 procedure Expand_Boolean_Operator (N : Node_Id) is
2010 Typ : constant Entity_Id := Etype (N);
2012 begin
2013 -- Special case of bit packed array where both operands are known to be
2014 -- properly aligned. In this case we use an efficient run time routine
2015 -- to carry out the operation (see System.Bit_Ops).
2017 if Is_Bit_Packed_Array (Typ)
2018 and then not Is_Possibly_Unaligned_Object (Left_Opnd (N))
2019 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
2020 then
2021 Expand_Packed_Boolean_Operator (N);
2022 return;
2023 end if;
2025 -- For the normal non-packed case, the general expansion is to build
2026 -- function for carrying out the comparison (use Make_Boolean_Array_Op)
2027 -- and then inserting it into the tree. The original operator node is
2028 -- then rewritten as a call to this function. We also use this in the
2029 -- packed case if either operand is a possibly unaligned object.
2031 declare
2032 Loc : constant Source_Ptr := Sloc (N);
2033 L : constant Node_Id := Relocate_Node (Left_Opnd (N));
2034 R : constant Node_Id := Relocate_Node (Right_Opnd (N));
2035 Func_Body : Node_Id;
2036 Func_Name : Entity_Id;
2038 begin
2039 Convert_To_Actual_Subtype (L);
2040 Convert_To_Actual_Subtype (R);
2041 Ensure_Defined (Etype (L), N);
2042 Ensure_Defined (Etype (R), N);
2043 Apply_Length_Check (R, Etype (L));
2045 if Nkind (N) = N_Op_Xor then
2046 Silly_Boolean_Array_Xor_Test (N, Etype (L));
2047 end if;
2049 if Nkind (Parent (N)) = N_Assignment_Statement
2050 and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
2051 then
2052 Build_Boolean_Array_Proc_Call (Parent (N), L, R);
2054 elsif Nkind (Parent (N)) = N_Op_Not
2055 and then Nkind (N) = N_Op_And
2056 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2057 and then Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
2058 then
2059 return;
2060 else
2062 Func_Body := Make_Boolean_Array_Op (Etype (L), N);
2063 Func_Name := Defining_Unit_Name (Specification (Func_Body));
2064 Insert_Action (N, Func_Body);
2066 -- Now rewrite the expression with a call
2068 Rewrite (N,
2069 Make_Function_Call (Loc,
2070 Name => New_Occurrence_Of (Func_Name, Loc),
2071 Parameter_Associations =>
2072 New_List (
2074 Make_Type_Conversion
2075 (Loc, New_Occurrence_Of (Etype (L), Loc), R))));
2077 Analyze_And_Resolve (N, Typ);
2078 end if;
2079 end;
2080 end Expand_Boolean_Operator;
2082 ------------------------------------------------
2083 -- Expand_Compare_Minimize_Eliminate_Overflow --
2084 ------------------------------------------------
2086 procedure Expand_Compare_Minimize_Eliminate_Overflow (N : Node_Id) is
2087 Loc : constant Source_Ptr := Sloc (N);
2089 Result_Type : constant Entity_Id := Etype (N);
2090 -- Capture result type (could be a derived boolean type)
2092 Llo, Lhi : Uint;
2093 Rlo, Rhi : Uint;
2095 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
2096 -- Entity for Long_Long_Integer'Base
2098 Check : constant Overflow_Mode_Type := Overflow_Check_Mode;
2099 -- Current overflow checking mode
2101 procedure Set_True;
2102 procedure Set_False;
2103 -- These procedures rewrite N with an occurrence of Standard_True or
2104 -- Standard_False, and then makes a call to Warn_On_Known_Condition.
2106 ---------------
2107 -- Set_False --
2108 ---------------
2110 procedure Set_False is
2111 begin
2112 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
2113 Warn_On_Known_Condition (N);
2114 end Set_False;
2116 --------------
2117 -- Set_True --
2118 --------------
2120 procedure Set_True is
2121 begin
2122 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
2123 Warn_On_Known_Condition (N);
2124 end Set_True;
2126 -- Start of processing for Expand_Compare_Minimize_Eliminate_Overflow
2128 begin
2129 -- Nothing to do unless we have a comparison operator with operands
2130 -- that are signed integer types, and we are operating in either
2131 -- MINIMIZED or ELIMINATED overflow checking mode.
2133 if Nkind (N) not in N_Op_Compare
2134 or else Check not in Minimized_Or_Eliminated
2135 or else not Is_Signed_Integer_Type (Etype (Left_Opnd (N)))
2136 then
2137 return;
2138 end if;
2140 -- OK, this is the case we are interested in. First step is to process
2141 -- our operands using the Minimize_Eliminate circuitry which applies
2142 -- this processing to the two operand subtrees.
2144 Minimize_Eliminate_Overflows
2145 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
2146 Minimize_Eliminate_Overflows
2147 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
2149 -- See if the range information decides the result of the comparison.
2150 -- We can only do this if we in fact have full range information (which
2151 -- won't be the case if either operand is bignum at this stage).
2153 if Llo /= No_Uint and then Rlo /= No_Uint then
2154 case N_Op_Compare (Nkind (N)) is
2155 when N_Op_Eq =>
2156 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2157 Set_True;
2158 elsif Llo > Rhi or else Lhi < Rlo then
2159 Set_False;
2160 end if;
2162 when N_Op_Ge =>
2163 if Llo >= Rhi then
2164 Set_True;
2165 elsif Lhi < Rlo then
2166 Set_False;
2167 end if;
2169 when N_Op_Gt =>
2170 if Llo > Rhi then
2171 Set_True;
2172 elsif Lhi <= Rlo then
2173 Set_False;
2174 end if;
2176 when N_Op_Le =>
2177 if Llo > Rhi then
2178 Set_False;
2179 elsif Lhi <= Rlo then
2180 Set_True;
2181 end if;
2183 when N_Op_Lt =>
2184 if Llo >= Rhi then
2185 Set_False;
2186 elsif Lhi < Rlo then
2187 Set_True;
2188 end if;
2190 when N_Op_Ne =>
2191 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2192 Set_False;
2193 elsif Llo > Rhi or else Lhi < Rlo then
2194 Set_True;
2195 end if;
2196 end case;
2198 -- All done if we did the rewrite
2200 if Nkind (N) not in N_Op_Compare then
2201 return;
2202 end if;
2203 end if;
2205 -- Otherwise, time to do the comparison
2207 declare
2208 Ltype : constant Entity_Id := Etype (Left_Opnd (N));
2209 Rtype : constant Entity_Id := Etype (Right_Opnd (N));
2211 begin
2212 -- If the two operands have the same signed integer type we are
2213 -- all set, nothing more to do. This is the case where either
2214 -- both operands were unchanged, or we rewrote both of them to
2215 -- be Long_Long_Integer.
2217 -- Note: Entity for the comparison may be wrong, but it's not worth
2218 -- the effort to change it, since the back end does not use it.
2220 if Is_Signed_Integer_Type (Ltype)
2221 and then Base_Type (Ltype) = Base_Type (Rtype)
2222 then
2223 return;
2225 -- Here if bignums are involved (can only happen in ELIMINATED mode)
2227 elsif Is_RTE (Ltype, RE_Bignum) or else Is_RTE (Rtype, RE_Bignum) then
2228 declare
2229 Left : Node_Id := Left_Opnd (N);
2230 Right : Node_Id := Right_Opnd (N);
2231 -- Bignum references for left and right operands
2233 begin
2234 if not Is_RTE (Ltype, RE_Bignum) then
2235 Left := Convert_To_Bignum (Left);
2236 elsif not Is_RTE (Rtype, RE_Bignum) then
2237 Right := Convert_To_Bignum (Right);
2238 end if;
2240 -- We rewrite our node with:
2242 -- do
2243 -- Bnn : Result_Type;
2244 -- declare
2245 -- M : Mark_Id := SS_Mark;
2246 -- begin
2247 -- Bnn := Big_xx (Left, Right); (xx = EQ, NT etc)
2248 -- SS_Release (M);
2249 -- end;
2250 -- in
2251 -- Bnn
2252 -- end
2254 declare
2255 Blk : constant Node_Id := Make_Bignum_Block (Loc);
2256 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
2257 Ent : RE_Id;
2259 begin
2260 case N_Op_Compare (Nkind (N)) is
2261 when N_Op_Eq => Ent := RE_Big_EQ;
2262 when N_Op_Ge => Ent := RE_Big_GE;
2263 when N_Op_Gt => Ent := RE_Big_GT;
2264 when N_Op_Le => Ent := RE_Big_LE;
2265 when N_Op_Lt => Ent := RE_Big_LT;
2266 when N_Op_Ne => Ent := RE_Big_NE;
2267 end case;
2269 -- Insert assignment to Bnn into the bignum block
2271 Insert_Before
2272 (First (Statements (Handled_Statement_Sequence (Blk))),
2273 Make_Assignment_Statement (Loc,
2274 Name => New_Occurrence_Of (Bnn, Loc),
2275 Expression =>
2276 Make_Function_Call (Loc,
2277 Name =>
2278 New_Occurrence_Of (RTE (Ent), Loc),
2279 Parameter_Associations => New_List (Left, Right))));
2281 -- Now do the rewrite with expression actions
2283 Rewrite (N,
2284 Make_Expression_With_Actions (Loc,
2285 Actions => New_List (
2286 Make_Object_Declaration (Loc,
2287 Defining_Identifier => Bnn,
2288 Object_Definition =>
2289 New_Occurrence_Of (Result_Type, Loc)),
2290 Blk),
2291 Expression => New_Occurrence_Of (Bnn, Loc)));
2292 Analyze_And_Resolve (N, Result_Type);
2293 end;
2294 end;
2296 -- No bignums involved, but types are different, so we must have
2297 -- rewritten one of the operands as a Long_Long_Integer but not
2298 -- the other one.
2300 -- If left operand is Long_Long_Integer, convert right operand
2301 -- and we are done (with a comparison of two Long_Long_Integers).
2303 elsif Ltype = LLIB then
2304 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
2305 Analyze_And_Resolve (Right_Opnd (N), LLIB, Suppress => All_Checks);
2306 return;
2308 -- If right operand is Long_Long_Integer, convert left operand
2309 -- and we are done (with a comparison of two Long_Long_Integers).
2311 -- This is the only remaining possibility
2313 else pragma Assert (Rtype = LLIB);
2314 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
2315 Analyze_And_Resolve (Left_Opnd (N), LLIB, Suppress => All_Checks);
2316 return;
2317 end if;
2318 end;
2319 end Expand_Compare_Minimize_Eliminate_Overflow;
2321 -------------------------------
2322 -- Expand_Composite_Equality --
2323 -------------------------------
2325 -- This function is only called for comparing internal fields of composite
2326 -- types when these fields are themselves composites. This is a special
2327 -- case because it is not possible to respect normal Ada visibility rules.
2329 function Expand_Composite_Equality
2330 (Nod : Node_Id;
2331 Typ : Entity_Id;
2332 Lhs : Node_Id;
2333 Rhs : Node_Id;
2334 Bodies : List_Id) return Node_Id
2336 Loc : constant Source_Ptr := Sloc (Nod);
2337 Full_Type : Entity_Id;
2338 Prim : Elmt_Id;
2339 Eq_Op : Entity_Id;
2341 function Find_Primitive_Eq return Node_Id;
2342 -- AI05-0123: Locate primitive equality for type if it exists, and
2343 -- build the corresponding call. If operation is abstract, replace
2344 -- call with an explicit raise. Return Empty if there is no primitive.
2346 -----------------------
2347 -- Find_Primitive_Eq --
2348 -----------------------
2350 function Find_Primitive_Eq return Node_Id is
2351 Prim_E : Elmt_Id;
2352 Prim : Node_Id;
2354 begin
2355 Prim_E := First_Elmt (Collect_Primitive_Operations (Typ));
2356 while Present (Prim_E) loop
2357 Prim := Node (Prim_E);
2359 -- Locate primitive equality with the right signature
2361 if Chars (Prim) = Name_Op_Eq
2362 and then Etype (First_Formal (Prim)) =
2363 Etype (Next_Formal (First_Formal (Prim)))
2364 and then Etype (Prim) = Standard_Boolean
2365 then
2366 if Is_Abstract_Subprogram (Prim) then
2367 return
2368 Make_Raise_Program_Error (Loc,
2369 Reason => PE_Explicit_Raise);
2371 else
2372 return
2373 Make_Function_Call (Loc,
2374 Name => New_Occurrence_Of (Prim, Loc),
2375 Parameter_Associations => New_List (Lhs, Rhs));
2376 end if;
2377 end if;
2379 Next_Elmt (Prim_E);
2380 end loop;
2382 -- If not found, predefined operation will be used
2384 return Empty;
2385 end Find_Primitive_Eq;
2387 -- Start of processing for Expand_Composite_Equality
2389 begin
2390 if Is_Private_Type (Typ) then
2391 Full_Type := Underlying_Type (Typ);
2392 else
2393 Full_Type := Typ;
2394 end if;
2396 -- If the private type has no completion the context may be the
2397 -- expansion of a composite equality for a composite type with some
2398 -- still incomplete components. The expression will not be analyzed
2399 -- until the enclosing type is completed, at which point this will be
2400 -- properly expanded, unless there is a bona fide completion error.
2402 if No (Full_Type) then
2403 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2404 end if;
2406 Full_Type := Base_Type (Full_Type);
2408 -- When the base type itself is private, use the full view to expand
2409 -- the composite equality.
2411 if Is_Private_Type (Full_Type) then
2412 Full_Type := Underlying_Type (Full_Type);
2413 end if;
2415 -- Case of array types
2417 if Is_Array_Type (Full_Type) then
2419 -- If the operand is an elementary type other than a floating-point
2420 -- type, then we can simply use the built-in block bitwise equality,
2421 -- since the predefined equality operators always apply and bitwise
2422 -- equality is fine for all these cases.
2424 if Is_Elementary_Type (Component_Type (Full_Type))
2425 and then not Is_Floating_Point_Type (Component_Type (Full_Type))
2426 then
2427 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2429 -- For composite component types, and floating-point types, use the
2430 -- expansion. This deals with tagged component types (where we use
2431 -- the applicable equality routine) and floating-point, (where we
2432 -- need to worry about negative zeroes), and also the case of any
2433 -- composite type recursively containing such fields.
2435 else
2436 return Expand_Array_Equality (Nod, Lhs, Rhs, Bodies, Full_Type);
2437 end if;
2439 -- Case of tagged record types
2441 elsif Is_Tagged_Type (Full_Type) then
2443 -- Call the primitive operation "=" of this type
2445 if Is_Class_Wide_Type (Full_Type) then
2446 Full_Type := Root_Type (Full_Type);
2447 end if;
2449 -- If this is derived from an untagged private type completed with a
2450 -- tagged type, it does not have a full view, so we use the primitive
2451 -- operations of the private type. This check should no longer be
2452 -- necessary when these types receive their full views ???
2454 if Is_Private_Type (Typ)
2455 and then not Is_Tagged_Type (Typ)
2456 and then not Is_Controlled (Typ)
2457 and then Is_Derived_Type (Typ)
2458 and then No (Full_View (Typ))
2459 then
2460 Prim := First_Elmt (Collect_Primitive_Operations (Typ));
2461 else
2462 Prim := First_Elmt (Primitive_Operations (Full_Type));
2463 end if;
2465 loop
2466 Eq_Op := Node (Prim);
2467 exit when Chars (Eq_Op) = Name_Op_Eq
2468 and then Etype (First_Formal (Eq_Op)) =
2469 Etype (Next_Formal (First_Formal (Eq_Op)))
2470 and then Base_Type (Etype (Eq_Op)) = Standard_Boolean;
2471 Next_Elmt (Prim);
2472 pragma Assert (Present (Prim));
2473 end loop;
2475 Eq_Op := Node (Prim);
2477 return
2478 Make_Function_Call (Loc,
2479 Name => New_Occurrence_Of (Eq_Op, Loc),
2480 Parameter_Associations =>
2481 New_List
2482 (Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Lhs),
2483 Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Rhs)));
2485 -- Case of untagged record types
2487 elsif Is_Record_Type (Full_Type) then
2488 Eq_Op := TSS (Full_Type, TSS_Composite_Equality);
2490 if Present (Eq_Op) then
2491 if Etype (First_Formal (Eq_Op)) /= Full_Type then
2493 -- Inherited equality from parent type. Convert the actuals to
2494 -- match signature of operation.
2496 declare
2497 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2499 begin
2500 return
2501 Make_Function_Call (Loc,
2502 Name => New_Occurrence_Of (Eq_Op, Loc),
2503 Parameter_Associations => New_List (
2504 OK_Convert_To (T, Lhs),
2505 OK_Convert_To (T, Rhs)));
2506 end;
2508 else
2509 -- Comparison between Unchecked_Union components
2511 if Is_Unchecked_Union (Full_Type) then
2512 declare
2513 Lhs_Type : Node_Id := Full_Type;
2514 Rhs_Type : Node_Id := Full_Type;
2515 Lhs_Discr_Val : Node_Id;
2516 Rhs_Discr_Val : Node_Id;
2518 begin
2519 -- Lhs subtype
2521 if Nkind (Lhs) = N_Selected_Component then
2522 Lhs_Type := Etype (Entity (Selector_Name (Lhs)));
2523 end if;
2525 -- Rhs subtype
2527 if Nkind (Rhs) = N_Selected_Component then
2528 Rhs_Type := Etype (Entity (Selector_Name (Rhs)));
2529 end if;
2531 -- Lhs of the composite equality
2533 if Is_Constrained (Lhs_Type) then
2535 -- Since the enclosing record type can never be an
2536 -- Unchecked_Union (this code is executed for records
2537 -- that do not have variants), we may reference its
2538 -- discriminant(s).
2540 if Nkind (Lhs) = N_Selected_Component
2541 and then Has_Per_Object_Constraint
2542 (Entity (Selector_Name (Lhs)))
2543 then
2544 Lhs_Discr_Val :=
2545 Make_Selected_Component (Loc,
2546 Prefix => Prefix (Lhs),
2547 Selector_Name =>
2548 New_Copy
2549 (Get_Discriminant_Value
2550 (First_Discriminant (Lhs_Type),
2551 Lhs_Type,
2552 Stored_Constraint (Lhs_Type))));
2554 else
2555 Lhs_Discr_Val :=
2556 New_Copy
2557 (Get_Discriminant_Value
2558 (First_Discriminant (Lhs_Type),
2559 Lhs_Type,
2560 Stored_Constraint (Lhs_Type)));
2562 end if;
2563 else
2564 -- It is not possible to infer the discriminant since
2565 -- the subtype is not constrained.
2567 return
2568 Make_Raise_Program_Error (Loc,
2569 Reason => PE_Unchecked_Union_Restriction);
2570 end if;
2572 -- Rhs of the composite equality
2574 if Is_Constrained (Rhs_Type) then
2575 if Nkind (Rhs) = N_Selected_Component
2576 and then Has_Per_Object_Constraint
2577 (Entity (Selector_Name (Rhs)))
2578 then
2579 Rhs_Discr_Val :=
2580 Make_Selected_Component (Loc,
2581 Prefix => Prefix (Rhs),
2582 Selector_Name =>
2583 New_Copy
2584 (Get_Discriminant_Value
2585 (First_Discriminant (Rhs_Type),
2586 Rhs_Type,
2587 Stored_Constraint (Rhs_Type))));
2589 else
2590 Rhs_Discr_Val :=
2591 New_Copy
2592 (Get_Discriminant_Value
2593 (First_Discriminant (Rhs_Type),
2594 Rhs_Type,
2595 Stored_Constraint (Rhs_Type)));
2597 end if;
2598 else
2599 return
2600 Make_Raise_Program_Error (Loc,
2601 Reason => PE_Unchecked_Union_Restriction);
2602 end if;
2604 -- Call the TSS equality function with the inferred
2605 -- discriminant values.
2607 return
2608 Make_Function_Call (Loc,
2609 Name => New_Occurrence_Of (Eq_Op, Loc),
2610 Parameter_Associations => New_List (
2611 Lhs,
2612 Rhs,
2613 Lhs_Discr_Val,
2614 Rhs_Discr_Val));
2615 end;
2617 -- All cases other than comparing Unchecked_Union types
2619 else
2620 declare
2621 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2622 begin
2623 return
2624 Make_Function_Call (Loc,
2625 Name =>
2626 New_Occurrence_Of (Eq_Op, Loc),
2627 Parameter_Associations => New_List (
2628 OK_Convert_To (T, Lhs),
2629 OK_Convert_To (T, Rhs)));
2630 end;
2631 end if;
2632 end if;
2634 -- Equality composes in Ada 2012 for untagged record types. It also
2635 -- composes for bounded strings, because they are part of the
2636 -- predefined environment. We could make it compose for bounded
2637 -- strings by making them tagged, or by making sure all subcomponents
2638 -- are set to the same value, even when not used. Instead, we have
2639 -- this special case in the compiler, because it's more efficient.
2641 elsif Ada_Version >= Ada_2012 or else Is_Bounded_String (Typ) then
2643 -- If no TSS has been created for the type, check whether there is
2644 -- a primitive equality declared for it.
2646 declare
2647 Op : constant Node_Id := Find_Primitive_Eq;
2649 begin
2650 -- Use user-defined primitive if it exists, otherwise use
2651 -- predefined equality.
2653 if Present (Op) then
2654 return Op;
2655 else
2656 return Make_Op_Eq (Loc, Lhs, Rhs);
2657 end if;
2658 end;
2660 else
2661 return Expand_Record_Equality (Nod, Full_Type, Lhs, Rhs, Bodies);
2662 end if;
2664 -- Non-composite types (always use predefined equality)
2666 else
2667 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2668 end if;
2669 end Expand_Composite_Equality;
2671 ------------------------
2672 -- Expand_Concatenate --
2673 ------------------------
2675 procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id) is
2676 Loc : constant Source_Ptr := Sloc (Cnode);
2678 Atyp : constant Entity_Id := Base_Type (Etype (Cnode));
2679 -- Result type of concatenation
2681 Ctyp : constant Entity_Id := Base_Type (Component_Type (Etype (Cnode)));
2682 -- Component type. Elements of this component type can appear as one
2683 -- of the operands of concatenation as well as arrays.
2685 Istyp : constant Entity_Id := Etype (First_Index (Atyp));
2686 -- Index subtype
2688 Ityp : constant Entity_Id := Base_Type (Istyp);
2689 -- Index type. This is the base type of the index subtype, and is used
2690 -- for all computed bounds (which may be out of range of Istyp in the
2691 -- case of null ranges).
2693 Artyp : Entity_Id;
2694 -- This is the type we use to do arithmetic to compute the bounds and
2695 -- lengths of operands. The choice of this type is a little subtle and
2696 -- is discussed in a separate section at the start of the body code.
2698 Concatenation_Error : exception;
2699 -- Raised if concatenation is sure to raise a CE
2701 Result_May_Be_Null : Boolean := True;
2702 -- Reset to False if at least one operand is encountered which is known
2703 -- at compile time to be non-null. Used for handling the special case
2704 -- of setting the high bound to the last operand high bound for a null
2705 -- result, thus ensuring a proper high bound in the super-flat case.
2707 N : constant Nat := List_Length (Opnds);
2708 -- Number of concatenation operands including possibly null operands
2710 NN : Nat := 0;
2711 -- Number of operands excluding any known to be null, except that the
2712 -- last operand is always retained, in case it provides the bounds for
2713 -- a null result.
2715 Opnd : Node_Id := Empty;
2716 -- Current operand being processed in the loop through operands. After
2717 -- this loop is complete, always contains the last operand (which is not
2718 -- the same as Operands (NN), since null operands are skipped).
2720 -- Arrays describing the operands, only the first NN entries of each
2721 -- array are set (NN < N when we exclude known null operands).
2723 Is_Fixed_Length : array (1 .. N) of Boolean;
2724 -- True if length of corresponding operand known at compile time
2726 Operands : array (1 .. N) of Node_Id;
2727 -- Set to the corresponding entry in the Opnds list (but note that null
2728 -- operands are excluded, so not all entries in the list are stored).
2730 Fixed_Length : array (1 .. N) of Uint;
2731 -- Set to length of operand. Entries in this array are set only if the
2732 -- corresponding entry in Is_Fixed_Length is True.
2734 Opnd_Low_Bound : array (1 .. N) of Node_Id;
2735 -- Set to lower bound of operand. Either an integer literal in the case
2736 -- where the bound is known at compile time, else actual lower bound.
2737 -- The operand low bound is of type Ityp.
2739 Var_Length : array (1 .. N) of Entity_Id;
2740 -- Set to an entity of type Natural that contains the length of an
2741 -- operand whose length is not known at compile time. Entries in this
2742 -- array are set only if the corresponding entry in Is_Fixed_Length
2743 -- is False. The entity is of type Artyp.
2745 Aggr_Length : array (0 .. N) of Node_Id;
2746 -- The J'th entry in an expression node that represents the total length
2747 -- of operands 1 through J. It is either an integer literal node, or a
2748 -- reference to a constant entity with the right value, so it is fine
2749 -- to just do a Copy_Node to get an appropriate copy. The extra zero'th
2750 -- entry always is set to zero. The length is of type Artyp.
2752 Low_Bound : Node_Id;
2753 -- A tree node representing the low bound of the result (of type Ityp).
2754 -- This is either an integer literal node, or an identifier reference to
2755 -- a constant entity initialized to the appropriate value.
2757 Last_Opnd_Low_Bound : Node_Id := Empty;
2758 -- A tree node representing the low bound of the last operand. This
2759 -- need only be set if the result could be null. It is used for the
2760 -- special case of setting the right low bound for a null result.
2761 -- This is of type Ityp.
2763 Last_Opnd_High_Bound : Node_Id := Empty;
2764 -- A tree node representing the high bound of the last operand. This
2765 -- need only be set if the result could be null. It is used for the
2766 -- special case of setting the right high bound for a null result.
2767 -- This is of type Ityp.
2769 High_Bound : Node_Id := Empty;
2770 -- A tree node representing the high bound of the result (of type Ityp)
2772 Result : Node_Id;
2773 -- Result of the concatenation (of type Ityp)
2775 Actions : constant List_Id := New_List;
2776 -- Collect actions to be inserted
2778 Known_Non_Null_Operand_Seen : Boolean;
2779 -- Set True during generation of the assignments of operands into
2780 -- result once an operand known to be non-null has been seen.
2782 function Library_Level_Target return Boolean;
2783 -- Return True if the concatenation is within the expression of the
2784 -- declaration of a library-level object.
2786 function Make_Artyp_Literal (Val : Nat) return Node_Id;
2787 -- This function makes an N_Integer_Literal node that is returned in
2788 -- analyzed form with the type set to Artyp. Importantly this literal
2789 -- is not flagged as static, so that if we do computations with it that
2790 -- result in statically detected out of range conditions, we will not
2791 -- generate error messages but instead warning messages.
2793 function To_Artyp (X : Node_Id) return Node_Id;
2794 -- Given a node of type Ityp, returns the corresponding value of type
2795 -- Artyp. For non-enumeration types, this is a plain integer conversion.
2796 -- For enum types, the Pos of the value is returned.
2798 function To_Ityp (X : Node_Id) return Node_Id;
2799 -- The inverse function (uses Val in the case of enumeration types)
2801 --------------------------
2802 -- Library_Level_Target --
2803 --------------------------
2805 function Library_Level_Target return Boolean is
2806 P : Node_Id := Parent (Cnode);
2808 begin
2809 while Present (P) loop
2810 if Nkind (P) = N_Object_Declaration then
2811 return Is_Library_Level_Entity (Defining_Identifier (P));
2813 -- Prevent the search from going too far
2815 elsif Is_Body_Or_Package_Declaration (P) then
2816 return False;
2817 end if;
2819 P := Parent (P);
2820 end loop;
2822 return False;
2823 end Library_Level_Target;
2825 ------------------------
2826 -- Make_Artyp_Literal --
2827 ------------------------
2829 function Make_Artyp_Literal (Val : Nat) return Node_Id is
2830 Result : constant Node_Id := Make_Integer_Literal (Loc, Val);
2831 begin
2832 Set_Etype (Result, Artyp);
2833 Set_Analyzed (Result, True);
2834 Set_Is_Static_Expression (Result, False);
2835 return Result;
2836 end Make_Artyp_Literal;
2838 --------------
2839 -- To_Artyp --
2840 --------------
2842 function To_Artyp (X : Node_Id) return Node_Id is
2843 begin
2844 if Ityp = Base_Type (Artyp) then
2845 return X;
2847 elsif Is_Enumeration_Type (Ityp) then
2848 return
2849 Make_Attribute_Reference (Loc,
2850 Prefix => New_Occurrence_Of (Ityp, Loc),
2851 Attribute_Name => Name_Pos,
2852 Expressions => New_List (X));
2854 else
2855 return Convert_To (Artyp, X);
2856 end if;
2857 end To_Artyp;
2859 -------------
2860 -- To_Ityp --
2861 -------------
2863 function To_Ityp (X : Node_Id) return Node_Id is
2864 begin
2865 if Is_Enumeration_Type (Ityp) then
2866 return
2867 Make_Attribute_Reference (Loc,
2868 Prefix => New_Occurrence_Of (Ityp, Loc),
2869 Attribute_Name => Name_Val,
2870 Expressions => New_List (X));
2872 -- Case where we will do a type conversion
2874 else
2875 if Ityp = Base_Type (Artyp) then
2876 return X;
2877 else
2878 return Convert_To (Ityp, X);
2879 end if;
2880 end if;
2881 end To_Ityp;
2883 -- Local Declarations
2885 Opnd_Typ : Entity_Id;
2886 Ent : Entity_Id;
2887 Len : Uint;
2888 J : Nat;
2889 Clen : Node_Id;
2890 Set : Boolean;
2892 -- Start of processing for Expand_Concatenate
2894 begin
2895 -- Choose an appropriate computational type
2897 -- We will be doing calculations of lengths and bounds in this routine
2898 -- and computing one from the other in some cases, e.g. getting the high
2899 -- bound by adding the length-1 to the low bound.
2901 -- We can't just use the index type, or even its base type for this
2902 -- purpose for two reasons. First it might be an enumeration type which
2903 -- is not suitable for computations of any kind, and second it may
2904 -- simply not have enough range. For example if the index type is
2905 -- -128..+127 then lengths can be up to 256, which is out of range of
2906 -- the type.
2908 -- For enumeration types, we can simply use Standard_Integer, this is
2909 -- sufficient since the actual number of enumeration literals cannot
2910 -- possibly exceed the range of integer (remember we will be doing the
2911 -- arithmetic with POS values, not representation values).
2913 if Is_Enumeration_Type (Ityp) then
2914 Artyp := Standard_Integer;
2916 -- If index type is Positive, we use the standard unsigned type, to give
2917 -- more room on the top of the range, obviating the need for an overflow
2918 -- check when creating the upper bound. This is needed to avoid junk
2919 -- overflow checks in the common case of String types.
2921 -- ??? Disabled for now
2923 -- elsif Istyp = Standard_Positive then
2924 -- Artyp := Standard_Unsigned;
2926 -- For modular types, we use a 32-bit modular type for types whose size
2927 -- is in the range 1-31 bits. For 32-bit unsigned types, we use the
2928 -- identity type, and for larger unsigned types we use 64-bits.
2930 elsif Is_Modular_Integer_Type (Ityp) then
2931 if RM_Size (Ityp) < RM_Size (Standard_Unsigned) then
2932 Artyp := Standard_Unsigned;
2933 elsif RM_Size (Ityp) = RM_Size (Standard_Unsigned) then
2934 Artyp := Ityp;
2935 else
2936 Artyp := RTE (RE_Long_Long_Unsigned);
2937 end if;
2939 -- Similar treatment for signed types
2941 else
2942 if RM_Size (Ityp) < RM_Size (Standard_Integer) then
2943 Artyp := Standard_Integer;
2944 elsif RM_Size (Ityp) = RM_Size (Standard_Integer) then
2945 Artyp := Ityp;
2946 else
2947 Artyp := Standard_Long_Long_Integer;
2948 end if;
2949 end if;
2951 -- Supply dummy entry at start of length array
2953 Aggr_Length (0) := Make_Artyp_Literal (0);
2955 -- Go through operands setting up the above arrays
2957 J := 1;
2958 while J <= N loop
2959 Opnd := Remove_Head (Opnds);
2960 Opnd_Typ := Etype (Opnd);
2962 -- The parent got messed up when we put the operands in a list,
2963 -- so now put back the proper parent for the saved operand, that
2964 -- is to say the concatenation node, to make sure that each operand
2965 -- is seen as a subexpression, e.g. if actions must be inserted.
2967 Set_Parent (Opnd, Cnode);
2969 -- Set will be True when we have setup one entry in the array
2971 Set := False;
2973 -- Singleton element (or character literal) case
2975 if Base_Type (Opnd_Typ) = Ctyp then
2976 NN := NN + 1;
2977 Operands (NN) := Opnd;
2978 Is_Fixed_Length (NN) := True;
2979 Fixed_Length (NN) := Uint_1;
2980 Result_May_Be_Null := False;
2982 -- Set low bound of operand (no need to set Last_Opnd_High_Bound
2983 -- since we know that the result cannot be null).
2985 Opnd_Low_Bound (NN) :=
2986 Make_Attribute_Reference (Loc,
2987 Prefix => New_Occurrence_Of (Istyp, Loc),
2988 Attribute_Name => Name_First);
2990 Set := True;
2992 -- String literal case (can only occur for strings of course)
2994 elsif Nkind (Opnd) = N_String_Literal then
2995 Len := String_Literal_Length (Opnd_Typ);
2997 if Len /= 0 then
2998 Result_May_Be_Null := False;
2999 end if;
3001 -- Capture last operand low and high bound if result could be null
3003 if J = N and then Result_May_Be_Null then
3004 Last_Opnd_Low_Bound :=
3005 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3007 Last_Opnd_High_Bound :=
3008 Make_Op_Subtract (Loc,
3009 Left_Opnd =>
3010 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ)),
3011 Right_Opnd => Make_Integer_Literal (Loc, 1));
3012 end if;
3014 -- Skip null string literal
3016 if J < N and then Len = 0 then
3017 goto Continue;
3018 end if;
3020 NN := NN + 1;
3021 Operands (NN) := Opnd;
3022 Is_Fixed_Length (NN) := True;
3024 -- Set length and bounds
3026 Fixed_Length (NN) := Len;
3028 Opnd_Low_Bound (NN) :=
3029 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3031 Set := True;
3033 -- All other cases
3035 else
3036 -- Check constrained case with known bounds
3038 if Is_Constrained (Opnd_Typ) then
3039 declare
3040 Index : constant Node_Id := First_Index (Opnd_Typ);
3041 Indx_Typ : constant Entity_Id := Etype (Index);
3042 Lo : constant Node_Id := Type_Low_Bound (Indx_Typ);
3043 Hi : constant Node_Id := Type_High_Bound (Indx_Typ);
3045 begin
3046 -- Fixed length constrained array type with known at compile
3047 -- time bounds is last case of fixed length operand.
3049 if Compile_Time_Known_Value (Lo)
3050 and then
3051 Compile_Time_Known_Value (Hi)
3052 then
3053 declare
3054 Loval : constant Uint := Expr_Value (Lo);
3055 Hival : constant Uint := Expr_Value (Hi);
3056 Len : constant Uint :=
3057 UI_Max (Hival - Loval + 1, Uint_0);
3059 begin
3060 if Len > 0 then
3061 Result_May_Be_Null := False;
3062 end if;
3064 -- Capture last operand bounds if result could be null
3066 if J = N and then Result_May_Be_Null then
3067 Last_Opnd_Low_Bound :=
3068 Convert_To (Ityp,
3069 Make_Integer_Literal (Loc, Expr_Value (Lo)));
3071 Last_Opnd_High_Bound :=
3072 Convert_To (Ityp,
3073 Make_Integer_Literal (Loc, Expr_Value (Hi)));
3074 end if;
3076 -- Exclude null length case unless last operand
3078 if J < N and then Len = 0 then
3079 goto Continue;
3080 end if;
3082 NN := NN + 1;
3083 Operands (NN) := Opnd;
3084 Is_Fixed_Length (NN) := True;
3085 Fixed_Length (NN) := Len;
3087 Opnd_Low_Bound (NN) :=
3088 To_Ityp
3089 (Make_Integer_Literal (Loc, Expr_Value (Lo)));
3090 Set := True;
3091 end;
3092 end if;
3093 end;
3094 end if;
3096 -- All cases where the length is not known at compile time, or the
3097 -- special case of an operand which is known to be null but has a
3098 -- lower bound other than 1 or is other than a string type.
3100 if not Set then
3101 NN := NN + 1;
3103 -- Capture operand bounds
3105 Opnd_Low_Bound (NN) :=
3106 Make_Attribute_Reference (Loc,
3107 Prefix =>
3108 Duplicate_Subexpr (Opnd, Name_Req => True),
3109 Attribute_Name => Name_First);
3111 -- Capture last operand bounds if result could be null
3113 if J = N and Result_May_Be_Null then
3114 Last_Opnd_Low_Bound :=
3115 Convert_To (Ityp,
3116 Make_Attribute_Reference (Loc,
3117 Prefix =>
3118 Duplicate_Subexpr (Opnd, Name_Req => True),
3119 Attribute_Name => Name_First));
3121 Last_Opnd_High_Bound :=
3122 Convert_To (Ityp,
3123 Make_Attribute_Reference (Loc,
3124 Prefix =>
3125 Duplicate_Subexpr (Opnd, Name_Req => True),
3126 Attribute_Name => Name_Last));
3127 end if;
3129 -- Capture length of operand in entity
3131 Operands (NN) := Opnd;
3132 Is_Fixed_Length (NN) := False;
3134 Var_Length (NN) := Make_Temporary (Loc, 'L');
3136 Append_To (Actions,
3137 Make_Object_Declaration (Loc,
3138 Defining_Identifier => Var_Length (NN),
3139 Constant_Present => True,
3140 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3141 Expression =>
3142 Make_Attribute_Reference (Loc,
3143 Prefix =>
3144 Duplicate_Subexpr (Opnd, Name_Req => True),
3145 Attribute_Name => Name_Length)));
3146 end if;
3147 end if;
3149 -- Set next entry in aggregate length array
3151 -- For first entry, make either integer literal for fixed length
3152 -- or a reference to the saved length for variable length.
3154 if NN = 1 then
3155 if Is_Fixed_Length (1) then
3156 Aggr_Length (1) := Make_Integer_Literal (Loc, Fixed_Length (1));
3157 else
3158 Aggr_Length (1) := New_Occurrence_Of (Var_Length (1), Loc);
3159 end if;
3161 -- If entry is fixed length and only fixed lengths so far, make
3162 -- appropriate new integer literal adding new length.
3164 elsif Is_Fixed_Length (NN)
3165 and then Nkind (Aggr_Length (NN - 1)) = N_Integer_Literal
3166 then
3167 Aggr_Length (NN) :=
3168 Make_Integer_Literal (Loc,
3169 Intval => Fixed_Length (NN) + Intval (Aggr_Length (NN - 1)));
3171 -- All other cases, construct an addition node for the length and
3172 -- create an entity initialized to this length.
3174 else
3175 Ent := Make_Temporary (Loc, 'L');
3177 if Is_Fixed_Length (NN) then
3178 Clen := Make_Integer_Literal (Loc, Fixed_Length (NN));
3179 else
3180 Clen := New_Occurrence_Of (Var_Length (NN), Loc);
3181 end if;
3183 Append_To (Actions,
3184 Make_Object_Declaration (Loc,
3185 Defining_Identifier => Ent,
3186 Constant_Present => True,
3187 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3188 Expression =>
3189 Make_Op_Add (Loc,
3190 Left_Opnd => New_Copy_Tree (Aggr_Length (NN - 1)),
3191 Right_Opnd => Clen)));
3193 Aggr_Length (NN) := Make_Identifier (Loc, Chars => Chars (Ent));
3194 end if;
3196 <<Continue>>
3197 J := J + 1;
3198 end loop;
3200 -- If we have only skipped null operands, return the last operand
3202 if NN = 0 then
3203 Result := Opnd;
3204 goto Done;
3205 end if;
3207 -- If we have only one non-null operand, return it and we are done.
3208 -- There is one case in which this cannot be done, and that is when
3209 -- the sole operand is of the element type, in which case it must be
3210 -- converted to an array, and the easiest way of doing that is to go
3211 -- through the normal general circuit.
3213 if NN = 1 and then Base_Type (Etype (Operands (1))) /= Ctyp then
3214 Result := Operands (1);
3215 goto Done;
3216 end if;
3218 -- Cases where we have a real concatenation
3220 -- Next step is to find the low bound for the result array that we
3221 -- will allocate. The rules for this are in (RM 4.5.6(5-7)).
3223 -- If the ultimate ancestor of the index subtype is a constrained array
3224 -- definition, then the lower bound is that of the index subtype as
3225 -- specified by (RM 4.5.3(6)).
3227 -- The right test here is to go to the root type, and then the ultimate
3228 -- ancestor is the first subtype of this root type.
3230 if Is_Constrained (First_Subtype (Root_Type (Atyp))) then
3231 Low_Bound :=
3232 Make_Attribute_Reference (Loc,
3233 Prefix =>
3234 New_Occurrence_Of (First_Subtype (Root_Type (Atyp)), Loc),
3235 Attribute_Name => Name_First);
3237 -- If the first operand in the list has known length we know that
3238 -- the lower bound of the result is the lower bound of this operand.
3240 elsif Is_Fixed_Length (1) then
3241 Low_Bound := Opnd_Low_Bound (1);
3243 -- OK, we don't know the lower bound, we have to build a horrible
3244 -- if expression node of the form
3246 -- if Cond1'Length /= 0 then
3247 -- Opnd1 low bound
3248 -- else
3249 -- if Opnd2'Length /= 0 then
3250 -- Opnd2 low bound
3251 -- else
3252 -- ...
3254 -- The nesting ends either when we hit an operand whose length is known
3255 -- at compile time, or on reaching the last operand, whose low bound we
3256 -- take unconditionally whether or not it is null. It's easiest to do
3257 -- this with a recursive procedure:
3259 else
3260 declare
3261 function Get_Known_Bound (J : Nat) return Node_Id;
3262 -- Returns the lower bound determined by operands J .. NN
3264 ---------------------
3265 -- Get_Known_Bound --
3266 ---------------------
3268 function Get_Known_Bound (J : Nat) return Node_Id is
3269 begin
3270 if Is_Fixed_Length (J) or else J = NN then
3271 return New_Copy_Tree (Opnd_Low_Bound (J));
3273 else
3274 return
3275 Make_If_Expression (Loc,
3276 Expressions => New_List (
3278 Make_Op_Ne (Loc,
3279 Left_Opnd =>
3280 New_Occurrence_Of (Var_Length (J), Loc),
3281 Right_Opnd =>
3282 Make_Integer_Literal (Loc, 0)),
3284 New_Copy_Tree (Opnd_Low_Bound (J)),
3285 Get_Known_Bound (J + 1)));
3286 end if;
3287 end Get_Known_Bound;
3289 begin
3290 Ent := Make_Temporary (Loc, 'L');
3292 Append_To (Actions,
3293 Make_Object_Declaration (Loc,
3294 Defining_Identifier => Ent,
3295 Constant_Present => True,
3296 Object_Definition => New_Occurrence_Of (Ityp, Loc),
3297 Expression => Get_Known_Bound (1)));
3299 Low_Bound := New_Occurrence_Of (Ent, Loc);
3300 end;
3301 end if;
3303 -- Now we can safely compute the upper bound, normally
3304 -- Low_Bound + Length - 1.
3306 High_Bound :=
3307 To_Ityp
3308 (Make_Op_Add (Loc,
3309 Left_Opnd => To_Artyp (New_Copy_Tree (Low_Bound)),
3310 Right_Opnd =>
3311 Make_Op_Subtract (Loc,
3312 Left_Opnd => New_Copy_Tree (Aggr_Length (NN)),
3313 Right_Opnd => Make_Artyp_Literal (1))));
3315 -- Note that calculation of the high bound may cause overflow in some
3316 -- very weird cases, so in the general case we need an overflow check on
3317 -- the high bound. We can avoid this for the common case of string types
3318 -- and other types whose index is Positive, since we chose a wider range
3319 -- for the arithmetic type. If checks are suppressed we do not set the
3320 -- flag, and possibly superfluous warnings will be omitted.
3322 if Istyp /= Standard_Positive
3323 and then not Overflow_Checks_Suppressed (Istyp)
3324 then
3325 Activate_Overflow_Check (High_Bound);
3326 end if;
3328 -- Handle the exceptional case where the result is null, in which case
3329 -- case the bounds come from the last operand (so that we get the proper
3330 -- bounds if the last operand is super-flat).
3332 if Result_May_Be_Null then
3333 Low_Bound :=
3334 Make_If_Expression (Loc,
3335 Expressions => New_List (
3336 Make_Op_Eq (Loc,
3337 Left_Opnd => New_Copy_Tree (Aggr_Length (NN)),
3338 Right_Opnd => Make_Artyp_Literal (0)),
3339 Last_Opnd_Low_Bound,
3340 Low_Bound));
3342 High_Bound :=
3343 Make_If_Expression (Loc,
3344 Expressions => New_List (
3345 Make_Op_Eq (Loc,
3346 Left_Opnd => New_Copy_Tree (Aggr_Length (NN)),
3347 Right_Opnd => Make_Artyp_Literal (0)),
3348 Last_Opnd_High_Bound,
3349 High_Bound));
3350 end if;
3352 -- Here is where we insert the saved up actions
3354 Insert_Actions (Cnode, Actions, Suppress => All_Checks);
3356 -- Now we construct an array object with appropriate bounds. We mark
3357 -- the target as internal to prevent useless initialization when
3358 -- Initialize_Scalars is enabled. Also since this is the actual result
3359 -- entity, we make sure we have debug information for the result.
3361 Ent := Make_Temporary (Loc, 'S');
3362 Set_Is_Internal (Ent);
3363 Set_Needs_Debug_Info (Ent);
3365 -- If the bound is statically known to be out of range, we do not want
3366 -- to abort, we want a warning and a runtime constraint error. Note that
3367 -- we have arranged that the result will not be treated as a static
3368 -- constant, so we won't get an illegality during this insertion.
3370 Insert_Action (Cnode,
3371 Make_Object_Declaration (Loc,
3372 Defining_Identifier => Ent,
3373 Object_Definition =>
3374 Make_Subtype_Indication (Loc,
3375 Subtype_Mark => New_Occurrence_Of (Atyp, Loc),
3376 Constraint =>
3377 Make_Index_Or_Discriminant_Constraint (Loc,
3378 Constraints => New_List (
3379 Make_Range (Loc,
3380 Low_Bound => Low_Bound,
3381 High_Bound => High_Bound))))),
3382 Suppress => All_Checks);
3384 -- If the result of the concatenation appears as the initializing
3385 -- expression of an object declaration, we can just rename the
3386 -- result, rather than copying it.
3388 Set_OK_To_Rename (Ent);
3390 -- Catch the static out of range case now
3392 if Raises_Constraint_Error (High_Bound) then
3393 raise Concatenation_Error;
3394 end if;
3396 -- Now we will generate the assignments to do the actual concatenation
3398 -- There is one case in which we will not do this, namely when all the
3399 -- following conditions are met:
3401 -- The result type is Standard.String
3403 -- There are nine or fewer retained (non-null) operands
3405 -- The optimization level is -O0 or the debug flag gnatd.C is set,
3406 -- and the debug flag gnatd.c is not set.
3408 -- The corresponding System.Concat_n.Str_Concat_n routine is
3409 -- available in the run time.
3411 -- If all these conditions are met then we generate a call to the
3412 -- relevant concatenation routine. The purpose of this is to avoid
3413 -- undesirable code bloat at -O0.
3415 -- If the concatenation is within the declaration of a library-level
3416 -- object, we call the built-in concatenation routines to prevent code
3417 -- bloat, regardless of the optimization level. This is space efficient
3418 -- and prevents linking problems when units are compiled with different
3419 -- optimization levels.
3421 if Atyp = Standard_String
3422 and then NN in 2 .. 9
3423 and then (((Optimization_Level = 0 or else Debug_Flag_Dot_CC)
3424 and then not Debug_Flag_Dot_C)
3425 or else Library_Level_Target)
3426 then
3427 declare
3428 RR : constant array (Nat range 2 .. 9) of RE_Id :=
3429 (RE_Str_Concat_2,
3430 RE_Str_Concat_3,
3431 RE_Str_Concat_4,
3432 RE_Str_Concat_5,
3433 RE_Str_Concat_6,
3434 RE_Str_Concat_7,
3435 RE_Str_Concat_8,
3436 RE_Str_Concat_9);
3438 begin
3439 if RTE_Available (RR (NN)) then
3440 declare
3441 Opnds : constant List_Id :=
3442 New_List (New_Occurrence_Of (Ent, Loc));
3444 begin
3445 for J in 1 .. NN loop
3446 if Is_List_Member (Operands (J)) then
3447 Remove (Operands (J));
3448 end if;
3450 if Base_Type (Etype (Operands (J))) = Ctyp then
3451 Append_To (Opnds,
3452 Make_Aggregate (Loc,
3453 Component_Associations => New_List (
3454 Make_Component_Association (Loc,
3455 Choices => New_List (
3456 Make_Integer_Literal (Loc, 1)),
3457 Expression => Operands (J)))));
3459 else
3460 Append_To (Opnds, Operands (J));
3461 end if;
3462 end loop;
3464 Insert_Action (Cnode,
3465 Make_Procedure_Call_Statement (Loc,
3466 Name => New_Occurrence_Of (RTE (RR (NN)), Loc),
3467 Parameter_Associations => Opnds));
3469 Result := New_Occurrence_Of (Ent, Loc);
3470 goto Done;
3471 end;
3472 end if;
3473 end;
3474 end if;
3476 -- Not special case so generate the assignments
3478 Known_Non_Null_Operand_Seen := False;
3480 for J in 1 .. NN loop
3481 declare
3482 Lo : constant Node_Id :=
3483 Make_Op_Add (Loc,
3484 Left_Opnd => To_Artyp (New_Copy_Tree (Low_Bound)),
3485 Right_Opnd => Aggr_Length (J - 1));
3487 Hi : constant Node_Id :=
3488 Make_Op_Add (Loc,
3489 Left_Opnd => To_Artyp (New_Copy_Tree (Low_Bound)),
3490 Right_Opnd =>
3491 Make_Op_Subtract (Loc,
3492 Left_Opnd => Aggr_Length (J),
3493 Right_Opnd => Make_Artyp_Literal (1)));
3495 begin
3496 -- Singleton case, simple assignment
3498 if Base_Type (Etype (Operands (J))) = Ctyp then
3499 Known_Non_Null_Operand_Seen := True;
3500 Insert_Action (Cnode,
3501 Make_Assignment_Statement (Loc,
3502 Name =>
3503 Make_Indexed_Component (Loc,
3504 Prefix => New_Occurrence_Of (Ent, Loc),
3505 Expressions => New_List (To_Ityp (Lo))),
3506 Expression => Operands (J)),
3507 Suppress => All_Checks);
3509 -- Array case, slice assignment, skipped when argument is fixed
3510 -- length and known to be null.
3512 elsif (not Is_Fixed_Length (J)) or else (Fixed_Length (J) > 0) then
3513 declare
3514 Assign : Node_Id :=
3515 Make_Assignment_Statement (Loc,
3516 Name =>
3517 Make_Slice (Loc,
3518 Prefix =>
3519 New_Occurrence_Of (Ent, Loc),
3520 Discrete_Range =>
3521 Make_Range (Loc,
3522 Low_Bound => To_Ityp (Lo),
3523 High_Bound => To_Ityp (Hi))),
3524 Expression => Operands (J));
3525 begin
3526 if Is_Fixed_Length (J) then
3527 Known_Non_Null_Operand_Seen := True;
3529 elsif not Known_Non_Null_Operand_Seen then
3531 -- Here if operand length is not statically known and no
3532 -- operand known to be non-null has been processed yet.
3533 -- If operand length is 0, we do not need to perform the
3534 -- assignment, and we must avoid the evaluation of the
3535 -- high bound of the slice, since it may underflow if the
3536 -- low bound is Ityp'First.
3538 Assign :=
3539 Make_Implicit_If_Statement (Cnode,
3540 Condition =>
3541 Make_Op_Ne (Loc,
3542 Left_Opnd =>
3543 New_Occurrence_Of (Var_Length (J), Loc),
3544 Right_Opnd => Make_Integer_Literal (Loc, 0)),
3545 Then_Statements => New_List (Assign));
3546 end if;
3548 Insert_Action (Cnode, Assign, Suppress => All_Checks);
3549 end;
3550 end if;
3551 end;
3552 end loop;
3554 -- Finally we build the result, which is a reference to the array object
3556 Result := New_Occurrence_Of (Ent, Loc);
3558 <<Done>>
3559 Rewrite (Cnode, Result);
3560 Analyze_And_Resolve (Cnode, Atyp);
3562 exception
3563 when Concatenation_Error =>
3565 -- Kill warning generated for the declaration of the static out of
3566 -- range high bound, and instead generate a Constraint_Error with
3567 -- an appropriate specific message.
3569 Kill_Dead_Code (Declaration_Node (Entity (High_Bound)));
3570 Apply_Compile_Time_Constraint_Error
3571 (N => Cnode,
3572 Msg => "concatenation result upper bound out of range??",
3573 Reason => CE_Range_Check_Failed);
3574 end Expand_Concatenate;
3576 ---------------------------------------------------
3577 -- Expand_Membership_Minimize_Eliminate_Overflow --
3578 ---------------------------------------------------
3580 procedure Expand_Membership_Minimize_Eliminate_Overflow (N : Node_Id) is
3581 pragma Assert (Nkind (N) = N_In);
3582 -- Despite the name, this routine applies only to N_In, not to
3583 -- N_Not_In. The latter is always rewritten as not (X in Y).
3585 Result_Type : constant Entity_Id := Etype (N);
3586 -- Capture result type, may be a derived boolean type
3588 Loc : constant Source_Ptr := Sloc (N);
3589 Lop : constant Node_Id := Left_Opnd (N);
3590 Rop : constant Node_Id := Right_Opnd (N);
3592 -- Note: there are many referencs to Etype (Lop) and Etype (Rop). It
3593 -- is thus tempting to capture these values, but due to the rewrites
3594 -- that occur as a result of overflow checking, these values change
3595 -- as we go along, and it is safe just to always use Etype explicitly.
3597 Restype : constant Entity_Id := Etype (N);
3598 -- Save result type
3600 Lo, Hi : Uint;
3601 -- Bounds in Minimize calls, not used currently
3603 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
3604 -- Entity for Long_Long_Integer'Base (Standard should export this???)
3606 begin
3607 Minimize_Eliminate_Overflows (Lop, Lo, Hi, Top_Level => False);
3609 -- If right operand is a subtype name, and the subtype name has no
3610 -- predicate, then we can just replace the right operand with an
3611 -- explicit range T'First .. T'Last, and use the explicit range code.
3613 if Nkind (Rop) /= N_Range
3614 and then No (Predicate_Function (Etype (Rop)))
3615 then
3616 declare
3617 Rtyp : constant Entity_Id := Etype (Rop);
3618 begin
3619 Rewrite (Rop,
3620 Make_Range (Loc,
3621 Low_Bound =>
3622 Make_Attribute_Reference (Loc,
3623 Attribute_Name => Name_First,
3624 Prefix => New_Occurrence_Of (Rtyp, Loc)),
3625 High_Bound =>
3626 Make_Attribute_Reference (Loc,
3627 Attribute_Name => Name_Last,
3628 Prefix => New_Occurrence_Of (Rtyp, Loc))));
3629 Analyze_And_Resolve (Rop, Rtyp, Suppress => All_Checks);
3630 end;
3631 end if;
3633 -- Here for the explicit range case. Note that the bounds of the range
3634 -- have not been processed for minimized or eliminated checks.
3636 if Nkind (Rop) = N_Range then
3637 Minimize_Eliminate_Overflows
3638 (Low_Bound (Rop), Lo, Hi, Top_Level => False);
3639 Minimize_Eliminate_Overflows
3640 (High_Bound (Rop), Lo, Hi, Top_Level => False);
3642 -- We have A in B .. C, treated as A >= B and then A <= C
3644 -- Bignum case
3646 if Is_RTE (Etype (Lop), RE_Bignum)
3647 or else Is_RTE (Etype (Low_Bound (Rop)), RE_Bignum)
3648 or else Is_RTE (Etype (High_Bound (Rop)), RE_Bignum)
3649 then
3650 declare
3651 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3652 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
3653 L : constant Entity_Id :=
3654 Make_Defining_Identifier (Loc, Name_uL);
3655 Lopnd : constant Node_Id := Convert_To_Bignum (Lop);
3656 Lbound : constant Node_Id :=
3657 Convert_To_Bignum (Low_Bound (Rop));
3658 Hbound : constant Node_Id :=
3659 Convert_To_Bignum (High_Bound (Rop));
3661 -- Now we rewrite the membership test node to look like
3663 -- do
3664 -- Bnn : Result_Type;
3665 -- declare
3666 -- M : Mark_Id := SS_Mark;
3667 -- L : Bignum := Lopnd;
3668 -- begin
3669 -- Bnn := Big_GE (L, Lbound) and then Big_LE (L, Hbound)
3670 -- SS_Release (M);
3671 -- end;
3672 -- in
3673 -- Bnn
3674 -- end
3676 begin
3677 -- Insert declaration of L into declarations of bignum block
3679 Insert_After
3680 (Last (Declarations (Blk)),
3681 Make_Object_Declaration (Loc,
3682 Defining_Identifier => L,
3683 Object_Definition =>
3684 New_Occurrence_Of (RTE (RE_Bignum), Loc),
3685 Expression => Lopnd));
3687 -- Insert assignment to Bnn into expressions of bignum block
3689 Insert_Before
3690 (First (Statements (Handled_Statement_Sequence (Blk))),
3691 Make_Assignment_Statement (Loc,
3692 Name => New_Occurrence_Of (Bnn, Loc),
3693 Expression =>
3694 Make_And_Then (Loc,
3695 Left_Opnd =>
3696 Make_Function_Call (Loc,
3697 Name =>
3698 New_Occurrence_Of (RTE (RE_Big_GE), Loc),
3699 Parameter_Associations => New_List (
3700 New_Occurrence_Of (L, Loc),
3701 Lbound)),
3703 Right_Opnd =>
3704 Make_Function_Call (Loc,
3705 Name =>
3706 New_Occurrence_Of (RTE (RE_Big_LE), Loc),
3707 Parameter_Associations => New_List (
3708 New_Occurrence_Of (L, Loc),
3709 Hbound)))));
3711 -- Now rewrite the node
3713 Rewrite (N,
3714 Make_Expression_With_Actions (Loc,
3715 Actions => New_List (
3716 Make_Object_Declaration (Loc,
3717 Defining_Identifier => Bnn,
3718 Object_Definition =>
3719 New_Occurrence_Of (Result_Type, Loc)),
3720 Blk),
3721 Expression => New_Occurrence_Of (Bnn, Loc)));
3722 Analyze_And_Resolve (N, Result_Type);
3723 return;
3724 end;
3726 -- Here if no bignums around
3728 else
3729 -- Case where types are all the same
3731 if Base_Type (Etype (Lop)) = Base_Type (Etype (Low_Bound (Rop)))
3732 and then
3733 Base_Type (Etype (Lop)) = Base_Type (Etype (High_Bound (Rop)))
3734 then
3735 null;
3737 -- If types are not all the same, it means that we have rewritten
3738 -- at least one of them to be of type Long_Long_Integer, and we
3739 -- will convert the other operands to Long_Long_Integer.
3741 else
3742 Convert_To_And_Rewrite (LLIB, Lop);
3743 Set_Analyzed (Lop, False);
3744 Analyze_And_Resolve (Lop, LLIB);
3746 -- For the right operand, avoid unnecessary recursion into
3747 -- this routine, we know that overflow is not possible.
3749 Convert_To_And_Rewrite (LLIB, Low_Bound (Rop));
3750 Convert_To_And_Rewrite (LLIB, High_Bound (Rop));
3751 Set_Analyzed (Rop, False);
3752 Analyze_And_Resolve (Rop, LLIB, Suppress => Overflow_Check);
3753 end if;
3755 -- Now the three operands are of the same signed integer type,
3756 -- so we can use the normal expansion routine for membership,
3757 -- setting the flag to prevent recursion into this procedure.
3759 Set_No_Minimize_Eliminate (N);
3760 Expand_N_In (N);
3761 end if;
3763 -- Right operand is a subtype name and the subtype has a predicate. We
3764 -- have to make sure the predicate is checked, and for that we need to
3765 -- use the standard N_In circuitry with appropriate types.
3767 else
3768 pragma Assert (Present (Predicate_Function (Etype (Rop))));
3770 -- If types are "right", just call Expand_N_In preventing recursion
3772 if Base_Type (Etype (Lop)) = Base_Type (Etype (Rop)) then
3773 Set_No_Minimize_Eliminate (N);
3774 Expand_N_In (N);
3776 -- Bignum case
3778 elsif Is_RTE (Etype (Lop), RE_Bignum) then
3780 -- For X in T, we want to rewrite our node as
3782 -- do
3783 -- Bnn : Result_Type;
3785 -- declare
3786 -- M : Mark_Id := SS_Mark;
3787 -- Lnn : Long_Long_Integer'Base
3788 -- Nnn : Bignum;
3790 -- begin
3791 -- Nnn := X;
3793 -- if not Bignum_In_LLI_Range (Nnn) then
3794 -- Bnn := False;
3795 -- else
3796 -- Lnn := From_Bignum (Nnn);
3797 -- Bnn :=
3798 -- Lnn in LLIB (T'Base'First) .. LLIB (T'Base'Last)
3799 -- and then T'Base (Lnn) in T;
3800 -- end if;
3802 -- SS_Release (M);
3803 -- end
3804 -- in
3805 -- Bnn
3806 -- end
3808 -- A bit gruesome, but there doesn't seem to be a simpler way
3810 declare
3811 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3812 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
3813 Lnn : constant Entity_Id := Make_Temporary (Loc, 'L', N);
3814 Nnn : constant Entity_Id := Make_Temporary (Loc, 'N', N);
3815 T : constant Entity_Id := Etype (Rop);
3816 TB : constant Entity_Id := Base_Type (T);
3817 Nin : Node_Id;
3819 begin
3820 -- Mark the last membership operation to prevent recursion
3822 Nin :=
3823 Make_In (Loc,
3824 Left_Opnd => Convert_To (TB, New_Occurrence_Of (Lnn, Loc)),
3825 Right_Opnd => New_Occurrence_Of (T, Loc));
3826 Set_No_Minimize_Eliminate (Nin);
3828 -- Now decorate the block
3830 Insert_After
3831 (Last (Declarations (Blk)),
3832 Make_Object_Declaration (Loc,
3833 Defining_Identifier => Lnn,
3834 Object_Definition => New_Occurrence_Of (LLIB, Loc)));
3836 Insert_After
3837 (Last (Declarations (Blk)),
3838 Make_Object_Declaration (Loc,
3839 Defining_Identifier => Nnn,
3840 Object_Definition =>
3841 New_Occurrence_Of (RTE (RE_Bignum), Loc)));
3843 Insert_List_Before
3844 (First (Statements (Handled_Statement_Sequence (Blk))),
3845 New_List (
3846 Make_Assignment_Statement (Loc,
3847 Name => New_Occurrence_Of (Nnn, Loc),
3848 Expression => Relocate_Node (Lop)),
3850 Make_Implicit_If_Statement (N,
3851 Condition =>
3852 Make_Op_Not (Loc,
3853 Right_Opnd =>
3854 Make_Function_Call (Loc,
3855 Name =>
3856 New_Occurrence_Of
3857 (RTE (RE_Bignum_In_LLI_Range), Loc),
3858 Parameter_Associations => New_List (
3859 New_Occurrence_Of (Nnn, Loc)))),
3861 Then_Statements => New_List (
3862 Make_Assignment_Statement (Loc,
3863 Name => New_Occurrence_Of (Bnn, Loc),
3864 Expression =>
3865 New_Occurrence_Of (Standard_False, Loc))),
3867 Else_Statements => New_List (
3868 Make_Assignment_Statement (Loc,
3869 Name => New_Occurrence_Of (Lnn, Loc),
3870 Expression =>
3871 Make_Function_Call (Loc,
3872 Name =>
3873 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
3874 Parameter_Associations => New_List (
3875 New_Occurrence_Of (Nnn, Loc)))),
3877 Make_Assignment_Statement (Loc,
3878 Name => New_Occurrence_Of (Bnn, Loc),
3879 Expression =>
3880 Make_And_Then (Loc,
3881 Left_Opnd =>
3882 Make_In (Loc,
3883 Left_Opnd => New_Occurrence_Of (Lnn, Loc),
3884 Right_Opnd =>
3885 Make_Range (Loc,
3886 Low_Bound =>
3887 Convert_To (LLIB,
3888 Make_Attribute_Reference (Loc,
3889 Attribute_Name => Name_First,
3890 Prefix =>
3891 New_Occurrence_Of (TB, Loc))),
3893 High_Bound =>
3894 Convert_To (LLIB,
3895 Make_Attribute_Reference (Loc,
3896 Attribute_Name => Name_Last,
3897 Prefix =>
3898 New_Occurrence_Of (TB, Loc))))),
3900 Right_Opnd => Nin))))));
3902 -- Now we can do the rewrite
3904 Rewrite (N,
3905 Make_Expression_With_Actions (Loc,
3906 Actions => New_List (
3907 Make_Object_Declaration (Loc,
3908 Defining_Identifier => Bnn,
3909 Object_Definition =>
3910 New_Occurrence_Of (Result_Type, Loc)),
3911 Blk),
3912 Expression => New_Occurrence_Of (Bnn, Loc)));
3913 Analyze_And_Resolve (N, Result_Type);
3914 return;
3915 end;
3917 -- Not bignum case, but types don't match (this means we rewrote the
3918 -- left operand to be Long_Long_Integer).
3920 else
3921 pragma Assert (Base_Type (Etype (Lop)) = LLIB);
3923 -- We rewrite the membership test as (where T is the type with
3924 -- the predicate, i.e. the type of the right operand)
3926 -- Lop in LLIB (T'Base'First) .. LLIB (T'Base'Last)
3927 -- and then T'Base (Lop) in T
3929 declare
3930 T : constant Entity_Id := Etype (Rop);
3931 TB : constant Entity_Id := Base_Type (T);
3932 Nin : Node_Id;
3934 begin
3935 -- The last membership test is marked to prevent recursion
3937 Nin :=
3938 Make_In (Loc,
3939 Left_Opnd => Convert_To (TB, Duplicate_Subexpr (Lop)),
3940 Right_Opnd => New_Occurrence_Of (T, Loc));
3941 Set_No_Minimize_Eliminate (Nin);
3943 -- Now do the rewrite
3945 Rewrite (N,
3946 Make_And_Then (Loc,
3947 Left_Opnd =>
3948 Make_In (Loc,
3949 Left_Opnd => Lop,
3950 Right_Opnd =>
3951 Make_Range (Loc,
3952 Low_Bound =>
3953 Convert_To (LLIB,
3954 Make_Attribute_Reference (Loc,
3955 Attribute_Name => Name_First,
3956 Prefix =>
3957 New_Occurrence_Of (TB, Loc))),
3958 High_Bound =>
3959 Convert_To (LLIB,
3960 Make_Attribute_Reference (Loc,
3961 Attribute_Name => Name_Last,
3962 Prefix =>
3963 New_Occurrence_Of (TB, Loc))))),
3964 Right_Opnd => Nin));
3965 Set_Analyzed (N, False);
3966 Analyze_And_Resolve (N, Restype);
3967 end;
3968 end if;
3969 end if;
3970 end Expand_Membership_Minimize_Eliminate_Overflow;
3972 ---------------------------------
3973 -- Expand_Nonbinary_Modular_Op --
3974 ---------------------------------
3976 procedure Expand_Nonbinary_Modular_Op (N : Node_Id) is
3977 Loc : constant Source_Ptr := Sloc (N);
3978 Typ : constant Entity_Id := Etype (N);
3980 procedure Expand_Modular_Addition;
3981 -- Expand the modular addition, handling the special case of adding a
3982 -- constant.
3984 procedure Expand_Modular_Op;
3985 -- Compute the general rule: (lhs OP rhs) mod Modulus
3987 procedure Expand_Modular_Subtraction;
3988 -- Expand the modular addition, handling the special case of subtracting
3989 -- a constant.
3991 -----------------------------
3992 -- Expand_Modular_Addition --
3993 -----------------------------
3995 procedure Expand_Modular_Addition is
3996 begin
3997 -- If this is not the addition of a constant then compute it using
3998 -- the general rule: (lhs + rhs) mod Modulus
4000 if Nkind (Right_Opnd (N)) /= N_Integer_Literal then
4001 Expand_Modular_Op;
4003 -- If this is an addition of a constant, convert it to a subtraction
4004 -- plus a conditional expression since we can compute it faster than
4005 -- computing the modulus.
4007 -- modMinusRhs = Modulus - rhs
4008 -- if lhs < modMinusRhs then lhs + rhs
4009 -- else lhs - modMinusRhs
4011 else
4012 declare
4013 Mod_Minus_Right : constant Uint :=
4014 Modulus (Typ) - Intval (Right_Opnd (N));
4016 Exprs : constant List_Id := New_List;
4017 Cond_Expr : constant Node_Id := New_Op_Node (N_Op_Lt, Loc);
4018 Then_Expr : constant Node_Id := New_Op_Node (N_Op_Add, Loc);
4019 Else_Expr : constant Node_Id := New_Op_Node (N_Op_Subtract,
4020 Loc);
4021 begin
4022 Set_Left_Opnd (Cond_Expr,
4023 New_Copy_Tree (Left_Opnd (N)));
4024 Set_Right_Opnd (Cond_Expr,
4025 Make_Integer_Literal (Loc, Mod_Minus_Right));
4026 Append_To (Exprs, Cond_Expr);
4028 Set_Left_Opnd (Then_Expr,
4029 Unchecked_Convert_To (Standard_Unsigned,
4030 New_Copy_Tree (Left_Opnd (N))));
4031 Set_Right_Opnd (Then_Expr,
4032 Make_Integer_Literal (Loc, Intval (Right_Opnd (N))));
4033 Append_To (Exprs, Then_Expr);
4035 Set_Left_Opnd (Else_Expr,
4036 Unchecked_Convert_To (Standard_Unsigned,
4037 New_Copy_Tree (Left_Opnd (N))));
4038 Set_Right_Opnd (Else_Expr,
4039 Make_Integer_Literal (Loc, Mod_Minus_Right));
4040 Append_To (Exprs, Else_Expr);
4042 Rewrite (N,
4043 Unchecked_Convert_To (Typ,
4044 Make_If_Expression (Loc, Expressions => Exprs)));
4045 end;
4046 end if;
4047 end Expand_Modular_Addition;
4049 -----------------------
4050 -- Expand_Modular_Op --
4051 -----------------------
4053 procedure Expand_Modular_Op is
4054 Op_Expr : constant Node_Id := New_Op_Node (Nkind (N), Loc);
4055 Mod_Expr : constant Node_Id := New_Op_Node (N_Op_Mod, Loc);
4057 begin
4058 -- Convert nonbinary modular type operands into integer values. Thus
4059 -- we avoid never-ending loops expanding them, and we also ensure
4060 -- the back end never receives nonbinary modular type expressions.
4062 if Nkind_In (Nkind (N), N_Op_And, N_Op_Or) then
4063 Set_Left_Opnd (Op_Expr,
4064 Unchecked_Convert_To (Standard_Unsigned,
4065 New_Copy_Tree (Left_Opnd (N))));
4066 Set_Right_Opnd (Op_Expr,
4067 Unchecked_Convert_To (Standard_Unsigned,
4068 New_Copy_Tree (Right_Opnd (N))));
4069 Set_Left_Opnd (Mod_Expr,
4070 Unchecked_Convert_To (Standard_Integer, Op_Expr));
4072 else
4073 Set_Left_Opnd (Op_Expr,
4074 Unchecked_Convert_To (Standard_Integer,
4075 New_Copy_Tree (Left_Opnd (N))));
4076 Set_Right_Opnd (Op_Expr,
4077 Unchecked_Convert_To (Standard_Integer,
4078 New_Copy_Tree (Right_Opnd (N))));
4080 -- Link this node to the tree to analyze it
4082 -- If the parent node is an expression with actions we link it to
4083 -- N since otherwise Force_Evaluation cannot identify if this node
4084 -- comes from the Expression and rejects generating the temporary.
4086 if Nkind (Parent (N)) = N_Expression_With_Actions then
4087 Set_Parent (Op_Expr, N);
4089 -- Common case
4091 else
4092 Set_Parent (Op_Expr, Parent (N));
4093 end if;
4095 Analyze (Op_Expr);
4097 -- Force generating a temporary because in the expansion of this
4098 -- expression we may generate code that performs this computation
4099 -- several times.
4101 Force_Evaluation (Op_Expr, Mode => Strict);
4103 Set_Left_Opnd (Mod_Expr, Op_Expr);
4104 end if;
4106 Set_Right_Opnd (Mod_Expr,
4107 Make_Integer_Literal (Loc, Modulus (Typ)));
4109 Rewrite (N,
4110 Unchecked_Convert_To (Typ, Mod_Expr));
4111 end Expand_Modular_Op;
4113 --------------------------------
4114 -- Expand_Modular_Subtraction --
4115 --------------------------------
4117 procedure Expand_Modular_Subtraction is
4118 begin
4119 -- If this is not the addition of a constant then compute it using
4120 -- the general rule: (lhs + rhs) mod Modulus
4122 if Nkind (Right_Opnd (N)) /= N_Integer_Literal then
4123 Expand_Modular_Op;
4125 -- If this is an addition of a constant, convert it to a subtraction
4126 -- plus a conditional expression since we can compute it faster than
4127 -- computing the modulus.
4129 -- modMinusRhs = Modulus - rhs
4130 -- if lhs < rhs then lhs + modMinusRhs
4131 -- else lhs - rhs
4133 else
4134 declare
4135 Mod_Minus_Right : constant Uint :=
4136 Modulus (Typ) - Intval (Right_Opnd (N));
4138 Exprs : constant List_Id := New_List;
4139 Cond_Expr : constant Node_Id := New_Op_Node (N_Op_Lt, Loc);
4140 Then_Expr : constant Node_Id := New_Op_Node (N_Op_Add, Loc);
4141 Else_Expr : constant Node_Id := New_Op_Node (N_Op_Subtract,
4142 Loc);
4143 begin
4144 Set_Left_Opnd (Cond_Expr,
4145 New_Copy_Tree (Left_Opnd (N)));
4146 Set_Right_Opnd (Cond_Expr,
4147 Make_Integer_Literal (Loc, Intval (Right_Opnd (N))));
4148 Append_To (Exprs, Cond_Expr);
4150 Set_Left_Opnd (Then_Expr,
4151 Unchecked_Convert_To (Standard_Unsigned,
4152 New_Copy_Tree (Left_Opnd (N))));
4153 Set_Right_Opnd (Then_Expr,
4154 Make_Integer_Literal (Loc, Mod_Minus_Right));
4155 Append_To (Exprs, Then_Expr);
4157 Set_Left_Opnd (Else_Expr,
4158 Unchecked_Convert_To (Standard_Unsigned,
4159 New_Copy_Tree (Left_Opnd (N))));
4160 Set_Right_Opnd (Else_Expr,
4161 Unchecked_Convert_To (Standard_Unsigned,
4162 New_Copy_Tree (Right_Opnd (N))));
4163 Append_To (Exprs, Else_Expr);
4165 Rewrite (N,
4166 Unchecked_Convert_To (Typ,
4167 Make_If_Expression (Loc, Expressions => Exprs)));
4168 end;
4169 end if;
4170 end Expand_Modular_Subtraction;
4172 -- Start of processing for Expand_Nonbinary_Modular_Op
4174 begin
4175 -- No action needed if front-end expansion is not required or if we
4176 -- have a binary modular operand.
4178 if not Expand_Nonbinary_Modular_Ops
4179 or else not Non_Binary_Modulus (Typ)
4180 then
4181 return;
4182 end if;
4184 case Nkind (N) is
4185 when N_Op_Add =>
4186 Expand_Modular_Addition;
4188 when N_Op_Subtract =>
4189 Expand_Modular_Subtraction;
4191 when N_Op_Minus =>
4193 -- Expand -expr into (0 - expr)
4195 Rewrite (N,
4196 Make_Op_Subtract (Loc,
4197 Left_Opnd => Make_Integer_Literal (Loc, 0),
4198 Right_Opnd => Right_Opnd (N)));
4199 Analyze_And_Resolve (N, Typ);
4201 when others =>
4202 Expand_Modular_Op;
4203 end case;
4205 Analyze_And_Resolve (N, Typ);
4206 end Expand_Nonbinary_Modular_Op;
4208 ------------------------
4209 -- Expand_N_Allocator --
4210 ------------------------
4212 procedure Expand_N_Allocator (N : Node_Id) is
4213 Etyp : constant Entity_Id := Etype (Expression (N));
4214 Loc : constant Source_Ptr := Sloc (N);
4215 PtrT : constant Entity_Id := Etype (N);
4217 procedure Rewrite_Coextension (N : Node_Id);
4218 -- Static coextensions have the same lifetime as the entity they
4219 -- constrain. Such occurrences can be rewritten as aliased objects
4220 -- and their unrestricted access used instead of the coextension.
4222 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id;
4223 -- Given a constrained array type E, returns a node representing the
4224 -- code to compute the size in storage elements for the given type.
4225 -- This is done without using the attribute (which malfunctions for
4226 -- large sizes ???)
4228 -------------------------
4229 -- Rewrite_Coextension --
4230 -------------------------
4232 procedure Rewrite_Coextension (N : Node_Id) is
4233 Temp_Id : constant Node_Id := Make_Temporary (Loc, 'C');
4234 Temp_Decl : Node_Id;
4236 begin
4237 -- Generate:
4238 -- Cnn : aliased Etyp;
4240 Temp_Decl :=
4241 Make_Object_Declaration (Loc,
4242 Defining_Identifier => Temp_Id,
4243 Aliased_Present => True,
4244 Object_Definition => New_Occurrence_Of (Etyp, Loc));
4246 if Nkind (Expression (N)) = N_Qualified_Expression then
4247 Set_Expression (Temp_Decl, Expression (Expression (N)));
4248 end if;
4250 Insert_Action (N, Temp_Decl);
4251 Rewrite (N,
4252 Make_Attribute_Reference (Loc,
4253 Prefix => New_Occurrence_Of (Temp_Id, Loc),
4254 Attribute_Name => Name_Unrestricted_Access));
4256 Analyze_And_Resolve (N, PtrT);
4257 end Rewrite_Coextension;
4259 ------------------------------
4260 -- Size_In_Storage_Elements --
4261 ------------------------------
4263 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id is
4264 begin
4265 -- Logically this just returns E'Max_Size_In_Storage_Elements.
4266 -- However, the reason for the existence of this function is
4267 -- to construct a test for sizes too large, which means near the
4268 -- 32-bit limit on a 32-bit machine, and precisely the trouble
4269 -- is that we get overflows when sizes are greater than 2**31.
4271 -- So what we end up doing for array types is to use the expression:
4273 -- number-of-elements * component_type'Max_Size_In_Storage_Elements
4275 -- which avoids this problem. All this is a bit bogus, but it does
4276 -- mean we catch common cases of trying to allocate arrays that
4277 -- are too large, and which in the absence of a check results in
4278 -- undetected chaos ???
4280 -- Note in particular that this is a pessimistic estimate in the
4281 -- case of packed array types, where an array element might occupy
4282 -- just a fraction of a storage element???
4284 declare
4285 Len : Node_Id;
4286 Res : Node_Id;
4287 pragma Warnings (Off, Res);
4289 begin
4290 for J in 1 .. Number_Dimensions (E) loop
4291 Len :=
4292 Make_Attribute_Reference (Loc,
4293 Prefix => New_Occurrence_Of (E, Loc),
4294 Attribute_Name => Name_Length,
4295 Expressions => New_List (Make_Integer_Literal (Loc, J)));
4297 if J = 1 then
4298 Res := Len;
4300 else
4301 Res :=
4302 Make_Op_Multiply (Loc,
4303 Left_Opnd => Res,
4304 Right_Opnd => Len);
4305 end if;
4306 end loop;
4308 return
4309 Make_Op_Multiply (Loc,
4310 Left_Opnd => Len,
4311 Right_Opnd =>
4312 Make_Attribute_Reference (Loc,
4313 Prefix => New_Occurrence_Of (Component_Type (E), Loc),
4314 Attribute_Name => Name_Max_Size_In_Storage_Elements));
4315 end;
4316 end Size_In_Storage_Elements;
4318 -- Local variables
4320 Dtyp : constant Entity_Id := Available_View (Designated_Type (PtrT));
4321 Desig : Entity_Id;
4322 Nod : Node_Id;
4323 Pool : Entity_Id;
4324 Rel_Typ : Entity_Id;
4325 Temp : Entity_Id;
4327 -- Start of processing for Expand_N_Allocator
4329 begin
4330 -- RM E.2.3(22). We enforce that the expected type of an allocator
4331 -- shall not be a remote access-to-class-wide-limited-private type
4333 -- Why is this being done at expansion time, seems clearly wrong ???
4335 Validate_Remote_Access_To_Class_Wide_Type (N);
4337 -- Processing for anonymous access-to-controlled types. These access
4338 -- types receive a special finalization master which appears in the
4339 -- declarations of the enclosing semantic unit. This expansion is done
4340 -- now to ensure that any additional types generated by this routine or
4341 -- Expand_Allocator_Expression inherit the proper type attributes.
4343 if (Ekind (PtrT) = E_Anonymous_Access_Type
4344 or else (Is_Itype (PtrT) and then No (Finalization_Master (PtrT))))
4345 and then Needs_Finalization (Dtyp)
4346 then
4347 -- Detect the allocation of an anonymous controlled object where the
4348 -- type of the context is named. For example:
4350 -- procedure Proc (Ptr : Named_Access_Typ);
4351 -- Proc (new Designated_Typ);
4353 -- Regardless of the anonymous-to-named access type conversion, the
4354 -- lifetime of the object must be associated with the named access
4355 -- type. Use the finalization-related attributes of this type.
4357 if Nkind_In (Parent (N), N_Type_Conversion,
4358 N_Unchecked_Type_Conversion)
4359 and then Ekind_In (Etype (Parent (N)), E_Access_Subtype,
4360 E_Access_Type,
4361 E_General_Access_Type)
4362 then
4363 Rel_Typ := Etype (Parent (N));
4364 else
4365 Rel_Typ := Empty;
4366 end if;
4368 -- Anonymous access-to-controlled types allocate on the global pool.
4369 -- Note that this is a "root type only" attribute.
4371 if No (Associated_Storage_Pool (PtrT)) then
4372 if Present (Rel_Typ) then
4373 Set_Associated_Storage_Pool
4374 (Root_Type (PtrT), Associated_Storage_Pool (Rel_Typ));
4375 else
4376 Set_Associated_Storage_Pool
4377 (Root_Type (PtrT), RTE (RE_Global_Pool_Object));
4378 end if;
4379 end if;
4381 -- The finalization master must be inserted and analyzed as part of
4382 -- the current semantic unit. Note that the master is updated when
4383 -- analysis changes current units. Note that this is a "root type
4384 -- only" attribute.
4386 if Present (Rel_Typ) then
4387 Set_Finalization_Master
4388 (Root_Type (PtrT), Finalization_Master (Rel_Typ));
4389 else
4390 Build_Anonymous_Master (Root_Type (PtrT));
4391 end if;
4392 end if;
4394 -- Set the storage pool and find the appropriate version of Allocate to
4395 -- call. Do not overwrite the storage pool if it is already set, which
4396 -- can happen for build-in-place function returns (see
4397 -- Exp_Ch4.Expand_N_Extended_Return_Statement).
4399 if No (Storage_Pool (N)) then
4400 Pool := Associated_Storage_Pool (Root_Type (PtrT));
4402 if Present (Pool) then
4403 Set_Storage_Pool (N, Pool);
4405 if Is_RTE (Pool, RE_SS_Pool) then
4406 Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
4408 -- In the case of an allocator for a simple storage pool, locate
4409 -- and save a reference to the pool type's Allocate routine.
4411 elsif Present (Get_Rep_Pragma
4412 (Etype (Pool), Name_Simple_Storage_Pool_Type))
4413 then
4414 declare
4415 Pool_Type : constant Entity_Id := Base_Type (Etype (Pool));
4416 Alloc_Op : Entity_Id;
4417 begin
4418 Alloc_Op := Get_Name_Entity_Id (Name_Allocate);
4419 while Present (Alloc_Op) loop
4420 if Scope (Alloc_Op) = Scope (Pool_Type)
4421 and then Present (First_Formal (Alloc_Op))
4422 and then Etype (First_Formal (Alloc_Op)) = Pool_Type
4423 then
4424 Set_Procedure_To_Call (N, Alloc_Op);
4425 exit;
4426 else
4427 Alloc_Op := Homonym (Alloc_Op);
4428 end if;
4429 end loop;
4430 end;
4432 elsif Is_Class_Wide_Type (Etype (Pool)) then
4433 Set_Procedure_To_Call (N, RTE (RE_Allocate_Any));
4435 else
4436 Set_Procedure_To_Call (N,
4437 Find_Prim_Op (Etype (Pool), Name_Allocate));
4438 end if;
4439 end if;
4440 end if;
4442 -- Under certain circumstances we can replace an allocator by an access
4443 -- to statically allocated storage. The conditions, as noted in AARM
4444 -- 3.10 (10c) are as follows:
4446 -- Size and initial value is known at compile time
4447 -- Access type is access-to-constant
4449 -- The allocator is not part of a constraint on a record component,
4450 -- because in that case the inserted actions are delayed until the
4451 -- record declaration is fully analyzed, which is too late for the
4452 -- analysis of the rewritten allocator.
4454 if Is_Access_Constant (PtrT)
4455 and then Nkind (Expression (N)) = N_Qualified_Expression
4456 and then Compile_Time_Known_Value (Expression (Expression (N)))
4457 and then Size_Known_At_Compile_Time
4458 (Etype (Expression (Expression (N))))
4459 and then not Is_Record_Type (Current_Scope)
4460 then
4461 -- Here we can do the optimization. For the allocator
4463 -- new x'(y)
4465 -- We insert an object declaration
4467 -- Tnn : aliased x := y;
4469 -- and replace the allocator by Tnn'Unrestricted_Access. Tnn is
4470 -- marked as requiring static allocation.
4472 Temp := Make_Temporary (Loc, 'T', Expression (Expression (N)));
4473 Desig := Subtype_Mark (Expression (N));
4475 -- If context is constrained, use constrained subtype directly,
4476 -- so that the constant is not labelled as having a nominally
4477 -- unconstrained subtype.
4479 if Entity (Desig) = Base_Type (Dtyp) then
4480 Desig := New_Occurrence_Of (Dtyp, Loc);
4481 end if;
4483 Insert_Action (N,
4484 Make_Object_Declaration (Loc,
4485 Defining_Identifier => Temp,
4486 Aliased_Present => True,
4487 Constant_Present => Is_Access_Constant (PtrT),
4488 Object_Definition => Desig,
4489 Expression => Expression (Expression (N))));
4491 Rewrite (N,
4492 Make_Attribute_Reference (Loc,
4493 Prefix => New_Occurrence_Of (Temp, Loc),
4494 Attribute_Name => Name_Unrestricted_Access));
4496 Analyze_And_Resolve (N, PtrT);
4498 -- We set the variable as statically allocated, since we don't want
4499 -- it going on the stack of the current procedure.
4501 Set_Is_Statically_Allocated (Temp);
4502 return;
4503 end if;
4505 -- Same if the allocator is an access discriminant for a local object:
4506 -- instead of an allocator we create a local value and constrain the
4507 -- enclosing object with the corresponding access attribute.
4509 if Is_Static_Coextension (N) then
4510 Rewrite_Coextension (N);
4511 return;
4512 end if;
4514 -- Check for size too large, we do this because the back end misses
4515 -- proper checks here and can generate rubbish allocation calls when
4516 -- we are near the limit. We only do this for the 32-bit address case
4517 -- since that is from a practical point of view where we see a problem.
4519 if System_Address_Size = 32
4520 and then not Storage_Checks_Suppressed (PtrT)
4521 and then not Storage_Checks_Suppressed (Dtyp)
4522 and then not Storage_Checks_Suppressed (Etyp)
4523 then
4524 -- The check we want to generate should look like
4526 -- if Etyp'Max_Size_In_Storage_Elements > 3.5 gigabytes then
4527 -- raise Storage_Error;
4528 -- end if;
4530 -- where 3.5 gigabytes is a constant large enough to accommodate any
4531 -- reasonable request for. But we can't do it this way because at
4532 -- least at the moment we don't compute this attribute right, and
4533 -- can silently give wrong results when the result gets large. Since
4534 -- this is all about large results, that's bad, so instead we only
4535 -- apply the check for constrained arrays, and manually compute the
4536 -- value of the attribute ???
4538 if Is_Array_Type (Etyp) and then Is_Constrained (Etyp) then
4539 Insert_Action (N,
4540 Make_Raise_Storage_Error (Loc,
4541 Condition =>
4542 Make_Op_Gt (Loc,
4543 Left_Opnd => Size_In_Storage_Elements (Etyp),
4544 Right_Opnd =>
4545 Make_Integer_Literal (Loc, Uint_7 * (Uint_2 ** 29))),
4546 Reason => SE_Object_Too_Large));
4547 end if;
4548 end if;
4550 -- If no storage pool has been specified and we have the restriction
4551 -- No_Standard_Allocators_After_Elaboration is present, then generate
4552 -- a call to Elaboration_Allocators.Check_Standard_Allocator.
4554 if Nkind (N) = N_Allocator
4555 and then No (Storage_Pool (N))
4556 and then Restriction_Active (No_Standard_Allocators_After_Elaboration)
4557 then
4558 Insert_Action (N,
4559 Make_Procedure_Call_Statement (Loc,
4560 Name =>
4561 New_Occurrence_Of (RTE (RE_Check_Standard_Allocator), Loc)));
4562 end if;
4564 -- Handle case of qualified expression (other than optimization above)
4565 -- First apply constraint checks, because the bounds or discriminants
4566 -- in the aggregate might not match the subtype mark in the allocator.
4568 if Nkind (Expression (N)) = N_Qualified_Expression then
4569 declare
4570 Exp : constant Node_Id := Expression (Expression (N));
4571 Typ : constant Entity_Id := Etype (Expression (N));
4573 begin
4574 Apply_Constraint_Check (Exp, Typ);
4575 Apply_Predicate_Check (Exp, Typ);
4576 end;
4578 Expand_Allocator_Expression (N);
4579 return;
4580 end if;
4582 -- If the allocator is for a type which requires initialization, and
4583 -- there is no initial value (i.e. operand is a subtype indication
4584 -- rather than a qualified expression), then we must generate a call to
4585 -- the initialization routine using an expressions action node:
4587 -- [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
4589 -- Here ptr_T is the pointer type for the allocator, and T is the
4590 -- subtype of the allocator. A special case arises if the designated
4591 -- type of the access type is a task or contains tasks. In this case
4592 -- the call to Init (Temp.all ...) is replaced by code that ensures
4593 -- that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
4594 -- for details). In addition, if the type T is a task type, then the
4595 -- first argument to Init must be converted to the task record type.
4597 declare
4598 T : constant Entity_Id := Entity (Expression (N));
4599 Args : List_Id;
4600 Decls : List_Id;
4601 Decl : Node_Id;
4602 Discr : Elmt_Id;
4603 Init : Entity_Id;
4604 Init_Arg1 : Node_Id;
4605 Init_Call : Node_Id;
4606 Temp_Decl : Node_Id;
4607 Temp_Type : Entity_Id;
4609 begin
4610 if No_Initialization (N) then
4612 -- Even though this might be a simple allocation, create a custom
4613 -- Allocate if the context requires it.
4615 if Present (Finalization_Master (PtrT)) then
4616 Build_Allocate_Deallocate_Proc
4617 (N => N,
4618 Is_Allocate => True);
4619 end if;
4621 -- Case of no initialization procedure present
4623 elsif not Has_Non_Null_Base_Init_Proc (T) then
4625 -- Case of simple initialization required
4627 if Needs_Simple_Initialization (T) then
4628 Check_Restriction (No_Default_Initialization, N);
4629 Rewrite (Expression (N),
4630 Make_Qualified_Expression (Loc,
4631 Subtype_Mark => New_Occurrence_Of (T, Loc),
4632 Expression => Get_Simple_Init_Val (T, N)));
4634 Analyze_And_Resolve (Expression (Expression (N)), T);
4635 Analyze_And_Resolve (Expression (N), T);
4636 Set_Paren_Count (Expression (Expression (N)), 1);
4637 Expand_N_Allocator (N);
4639 -- No initialization required
4641 else
4642 Build_Allocate_Deallocate_Proc
4643 (N => N,
4644 Is_Allocate => True);
4645 end if;
4647 -- Case of initialization procedure present, must be called
4649 else
4650 Check_Restriction (No_Default_Initialization, N);
4652 if not Restriction_Active (No_Default_Initialization) then
4653 Init := Base_Init_Proc (T);
4654 Nod := N;
4655 Temp := Make_Temporary (Loc, 'P');
4657 -- Construct argument list for the initialization routine call
4659 Init_Arg1 :=
4660 Make_Explicit_Dereference (Loc,
4661 Prefix =>
4662 New_Occurrence_Of (Temp, Loc));
4664 Set_Assignment_OK (Init_Arg1);
4665 Temp_Type := PtrT;
4667 -- The initialization procedure expects a specific type. if the
4668 -- context is access to class wide, indicate that the object
4669 -- being allocated has the right specific type.
4671 if Is_Class_Wide_Type (Dtyp) then
4672 Init_Arg1 := Unchecked_Convert_To (T, Init_Arg1);
4673 end if;
4675 -- If designated type is a concurrent type or if it is private
4676 -- type whose definition is a concurrent type, the first
4677 -- argument in the Init routine has to be unchecked conversion
4678 -- to the corresponding record type. If the designated type is
4679 -- a derived type, also convert the argument to its root type.
4681 if Is_Concurrent_Type (T) then
4682 Init_Arg1 :=
4683 Unchecked_Convert_To (
4684 Corresponding_Record_Type (T), Init_Arg1);
4686 elsif Is_Private_Type (T)
4687 and then Present (Full_View (T))
4688 and then Is_Concurrent_Type (Full_View (T))
4689 then
4690 Init_Arg1 :=
4691 Unchecked_Convert_To
4692 (Corresponding_Record_Type (Full_View (T)), Init_Arg1);
4694 elsif Etype (First_Formal (Init)) /= Base_Type (T) then
4695 declare
4696 Ftyp : constant Entity_Id := Etype (First_Formal (Init));
4698 begin
4699 Init_Arg1 := OK_Convert_To (Etype (Ftyp), Init_Arg1);
4700 Set_Etype (Init_Arg1, Ftyp);
4701 end;
4702 end if;
4704 Args := New_List (Init_Arg1);
4706 -- For the task case, pass the Master_Id of the access type as
4707 -- the value of the _Master parameter, and _Chain as the value
4708 -- of the _Chain parameter (_Chain will be defined as part of
4709 -- the generated code for the allocator).
4711 -- In Ada 2005, the context may be a function that returns an
4712 -- anonymous access type. In that case the Master_Id has been
4713 -- created when expanding the function declaration.
4715 if Has_Task (T) then
4716 if No (Master_Id (Base_Type (PtrT))) then
4718 -- The designated type was an incomplete type, and the
4719 -- access type did not get expanded. Salvage it now.
4721 if not Restriction_Active (No_Task_Hierarchy) then
4722 if Present (Parent (Base_Type (PtrT))) then
4723 Expand_N_Full_Type_Declaration
4724 (Parent (Base_Type (PtrT)));
4726 -- The only other possibility is an itype. For this
4727 -- case, the master must exist in the context. This is
4728 -- the case when the allocator initializes an access
4729 -- component in an init-proc.
4731 else
4732 pragma Assert (Is_Itype (PtrT));
4733 Build_Master_Renaming (PtrT, N);
4734 end if;
4735 end if;
4736 end if;
4738 -- If the context of the allocator is a declaration or an
4739 -- assignment, we can generate a meaningful image for it,
4740 -- even though subsequent assignments might remove the
4741 -- connection between task and entity. We build this image
4742 -- when the left-hand side is a simple variable, a simple
4743 -- indexed assignment or a simple selected component.
4745 if Nkind (Parent (N)) = N_Assignment_Statement then
4746 declare
4747 Nam : constant Node_Id := Name (Parent (N));
4749 begin
4750 if Is_Entity_Name (Nam) then
4751 Decls :=
4752 Build_Task_Image_Decls
4753 (Loc,
4754 New_Occurrence_Of
4755 (Entity (Nam), Sloc (Nam)), T);
4757 elsif Nkind_In (Nam, N_Indexed_Component,
4758 N_Selected_Component)
4759 and then Is_Entity_Name (Prefix (Nam))
4760 then
4761 Decls :=
4762 Build_Task_Image_Decls
4763 (Loc, Nam, Etype (Prefix (Nam)));
4764 else
4765 Decls := Build_Task_Image_Decls (Loc, T, T);
4766 end if;
4767 end;
4769 elsif Nkind (Parent (N)) = N_Object_Declaration then
4770 Decls :=
4771 Build_Task_Image_Decls
4772 (Loc, Defining_Identifier (Parent (N)), T);
4774 else
4775 Decls := Build_Task_Image_Decls (Loc, T, T);
4776 end if;
4778 if Restriction_Active (No_Task_Hierarchy) then
4779 Append_To (Args,
4780 New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc));
4781 else
4782 Append_To (Args,
4783 New_Occurrence_Of
4784 (Master_Id (Base_Type (Root_Type (PtrT))), Loc));
4785 end if;
4787 Append_To (Args, Make_Identifier (Loc, Name_uChain));
4789 Decl := Last (Decls);
4790 Append_To (Args,
4791 New_Occurrence_Of (Defining_Identifier (Decl), Loc));
4793 -- Has_Task is false, Decls not used
4795 else
4796 Decls := No_List;
4797 end if;
4799 -- Add discriminants if discriminated type
4801 declare
4802 Dis : Boolean := False;
4803 Typ : Entity_Id := Empty;
4805 begin
4806 if Has_Discriminants (T) then
4807 Dis := True;
4808 Typ := T;
4810 -- Type may be a private type with no visible discriminants
4811 -- in which case check full view if in scope, or the
4812 -- underlying_full_view if dealing with a type whose full
4813 -- view may be derived from a private type whose own full
4814 -- view has discriminants.
4816 elsif Is_Private_Type (T) then
4817 if Present (Full_View (T))
4818 and then Has_Discriminants (Full_View (T))
4819 then
4820 Dis := True;
4821 Typ := Full_View (T);
4823 elsif Present (Underlying_Full_View (T))
4824 and then Has_Discriminants (Underlying_Full_View (T))
4825 then
4826 Dis := True;
4827 Typ := Underlying_Full_View (T);
4828 end if;
4829 end if;
4831 if Dis then
4833 -- If the allocated object will be constrained by the
4834 -- default values for discriminants, then build a subtype
4835 -- with those defaults, and change the allocated subtype
4836 -- to that. Note that this happens in fewer cases in Ada
4837 -- 2005 (AI-363).
4839 if not Is_Constrained (Typ)
4840 and then Present (Discriminant_Default_Value
4841 (First_Discriminant (Typ)))
4842 and then (Ada_Version < Ada_2005
4843 or else not
4844 Object_Type_Has_Constrained_Partial_View
4845 (Typ, Current_Scope))
4846 then
4847 Typ := Build_Default_Subtype (Typ, N);
4848 Set_Expression (N, New_Occurrence_Of (Typ, Loc));
4849 end if;
4851 Discr := First_Elmt (Discriminant_Constraint (Typ));
4852 while Present (Discr) loop
4853 Nod := Node (Discr);
4854 Append (New_Copy_Tree (Node (Discr)), Args);
4856 -- AI-416: when the discriminant constraint is an
4857 -- anonymous access type make sure an accessibility
4858 -- check is inserted if necessary (3.10.2(22.q/2))
4860 if Ada_Version >= Ada_2005
4861 and then
4862 Ekind (Etype (Nod)) = E_Anonymous_Access_Type
4863 then
4864 Apply_Accessibility_Check
4865 (Nod, Typ, Insert_Node => Nod);
4866 end if;
4868 Next_Elmt (Discr);
4869 end loop;
4870 end if;
4871 end;
4873 -- We set the allocator as analyzed so that when we analyze
4874 -- the if expression node, we do not get an unwanted recursive
4875 -- expansion of the allocator expression.
4877 Set_Analyzed (N, True);
4878 Nod := Relocate_Node (N);
4880 -- Here is the transformation:
4881 -- input: new Ctrl_Typ
4882 -- output: Temp : constant Ctrl_Typ_Ptr := new Ctrl_Typ;
4883 -- Ctrl_TypIP (Temp.all, ...);
4884 -- [Deep_]Initialize (Temp.all);
4886 -- Here Ctrl_Typ_Ptr is the pointer type for the allocator, and
4887 -- is the subtype of the allocator.
4889 Temp_Decl :=
4890 Make_Object_Declaration (Loc,
4891 Defining_Identifier => Temp,
4892 Constant_Present => True,
4893 Object_Definition => New_Occurrence_Of (Temp_Type, Loc),
4894 Expression => Nod);
4896 Set_Assignment_OK (Temp_Decl);
4897 Insert_Action (N, Temp_Decl, Suppress => All_Checks);
4899 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
4901 -- If the designated type is a task type or contains tasks,
4902 -- create block to activate created tasks, and insert
4903 -- declaration for Task_Image variable ahead of call.
4905 if Has_Task (T) then
4906 declare
4907 L : constant List_Id := New_List;
4908 Blk : Node_Id;
4909 begin
4910 Build_Task_Allocate_Block (L, Nod, Args);
4911 Blk := Last (L);
4912 Insert_List_Before (First (Declarations (Blk)), Decls);
4913 Insert_Actions (N, L);
4914 end;
4916 else
4917 Insert_Action (N,
4918 Make_Procedure_Call_Statement (Loc,
4919 Name => New_Occurrence_Of (Init, Loc),
4920 Parameter_Associations => Args));
4921 end if;
4923 if Needs_Finalization (T) then
4925 -- Generate:
4926 -- [Deep_]Initialize (Init_Arg1);
4928 Init_Call :=
4929 Make_Init_Call
4930 (Obj_Ref => New_Copy_Tree (Init_Arg1),
4931 Typ => T);
4933 -- Guard against a missing [Deep_]Initialize when the
4934 -- designated type was not properly frozen.
4936 if Present (Init_Call) then
4937 Insert_Action (N, Init_Call);
4938 end if;
4939 end if;
4941 Rewrite (N, New_Occurrence_Of (Temp, Loc));
4942 Analyze_And_Resolve (N, PtrT);
4943 end if;
4944 end if;
4945 end;
4947 -- Ada 2005 (AI-251): If the allocator is for a class-wide interface
4948 -- object that has been rewritten as a reference, we displace "this"
4949 -- to reference properly its secondary dispatch table.
4951 if Nkind (N) = N_Identifier and then Is_Interface (Dtyp) then
4952 Displace_Allocator_Pointer (N);
4953 end if;
4955 exception
4956 when RE_Not_Available =>
4957 return;
4958 end Expand_N_Allocator;
4960 -----------------------
4961 -- Expand_N_And_Then --
4962 -----------------------
4964 procedure Expand_N_And_Then (N : Node_Id)
4965 renames Expand_Short_Circuit_Operator;
4967 ------------------------------
4968 -- Expand_N_Case_Expression --
4969 ------------------------------
4971 procedure Expand_N_Case_Expression (N : Node_Id) is
4973 function Is_Copy_Type (Typ : Entity_Id) return Boolean;
4974 -- Return True if we can copy objects of this type when expanding a case
4975 -- expression.
4977 ------------------
4978 -- Is_Copy_Type --
4979 ------------------
4981 function Is_Copy_Type (Typ : Entity_Id) return Boolean is
4982 begin
4983 -- If Minimize_Expression_With_Actions is True, we can afford to copy
4984 -- large objects, as long as they are constrained and not limited.
4986 return
4987 Is_Elementary_Type (Underlying_Type (Typ))
4988 or else
4989 (Minimize_Expression_With_Actions
4990 and then Is_Constrained (Underlying_Type (Typ))
4991 and then not Is_Limited_View (Underlying_Type (Typ)));
4992 end Is_Copy_Type;
4994 -- Local variables
4996 Loc : constant Source_Ptr := Sloc (N);
4997 Par : constant Node_Id := Parent (N);
4998 Typ : constant Entity_Id := Etype (N);
5000 Acts : List_Id;
5001 Alt : Node_Id;
5002 Case_Stmt : Node_Id;
5003 Decl : Node_Id;
5004 Expr : Node_Id;
5005 Target : Entity_Id;
5006 Target_Typ : Entity_Id;
5008 In_Predicate : Boolean := False;
5009 -- Flag set when the case expression appears within a predicate
5011 Optimize_Return_Stmt : Boolean := False;
5012 -- Flag set when the case expression can be optimized in the context of
5013 -- a simple return statement.
5015 -- Start of processing for Expand_N_Case_Expression
5017 begin
5018 -- Check for MINIMIZED/ELIMINATED overflow mode
5020 if Minimized_Eliminated_Overflow_Check (N) then
5021 Apply_Arithmetic_Overflow_Check (N);
5022 return;
5023 end if;
5025 -- If the case expression is a predicate specification, and the type
5026 -- to which it applies has a static predicate aspect, do not expand,
5027 -- because it will be converted to the proper predicate form later.
5029 if Ekind_In (Current_Scope, E_Function, E_Procedure)
5030 and then Is_Predicate_Function (Current_Scope)
5031 then
5032 In_Predicate := True;
5034 if Has_Static_Predicate_Aspect (Etype (First_Entity (Current_Scope)))
5035 then
5036 return;
5037 end if;
5038 end if;
5040 -- When the type of the case expression is elementary, expand
5042 -- (case X is when A => AX, when B => BX ...)
5044 -- into
5046 -- do
5047 -- Target : Typ;
5048 -- case X is
5049 -- when A =>
5050 -- Target := AX;
5051 -- when B =>
5052 -- Target := BX;
5053 -- ...
5054 -- end case;
5055 -- in Target end;
5057 -- In all other cases expand into
5059 -- do
5060 -- type Ptr_Typ is access all Typ;
5061 -- Target : Ptr_Typ;
5062 -- case X is
5063 -- when A =>
5064 -- Target := AX'Unrestricted_Access;
5065 -- when B =>
5066 -- Target := BX'Unrestricted_Access;
5067 -- ...
5068 -- end case;
5069 -- in Target.all end;
5071 -- This approach avoids extra copies of potentially large objects. It
5072 -- also allows handling of values of limited or unconstrained types.
5073 -- Note that we do the copy also for constrained, nonlimited types
5074 -- when minimizing expressions with actions (e.g. when generating C
5075 -- code) since it allows us to do the optimization below in more cases.
5077 -- Small optimization: when the case expression appears in the context
5078 -- of a simple return statement, expand into
5080 -- case X is
5081 -- when A =>
5082 -- return AX;
5083 -- when B =>
5084 -- return BX;
5085 -- ...
5086 -- end case;
5088 Case_Stmt :=
5089 Make_Case_Statement (Loc,
5090 Expression => Expression (N),
5091 Alternatives => New_List);
5093 -- Preserve the original context for which the case statement is being
5094 -- generated. This is needed by the finalization machinery to prevent
5095 -- the premature finalization of controlled objects found within the
5096 -- case statement.
5098 Set_From_Conditional_Expression (Case_Stmt);
5099 Acts := New_List;
5101 -- Scalar/Copy case
5103 if Is_Copy_Type (Typ) then
5104 Target_Typ := Typ;
5106 -- ??? Do not perform the optimization when the return statement is
5107 -- within a predicate function, as this causes spurious errors. Could
5108 -- this be a possible mismatch in handling this case somewhere else
5109 -- in semantic analysis?
5111 Optimize_Return_Stmt :=
5112 Nkind (Par) = N_Simple_Return_Statement and then not In_Predicate;
5114 -- Otherwise create an access type to handle the general case using
5115 -- 'Unrestricted_Access.
5117 -- Generate:
5118 -- type Ptr_Typ is access all Typ;
5120 else
5121 if Generate_C_Code then
5123 -- We cannot ensure that correct C code will be generated if any
5124 -- temporary is created down the line (to e.g. handle checks or
5125 -- capture values) since we might end up with dangling references
5126 -- to local variables, so better be safe and reject the construct.
5128 Error_Msg_N
5129 ("case expression too complex, use case statement instead", N);
5130 end if;
5132 Target_Typ := Make_Temporary (Loc, 'P');
5134 Append_To (Acts,
5135 Make_Full_Type_Declaration (Loc,
5136 Defining_Identifier => Target_Typ,
5137 Type_Definition =>
5138 Make_Access_To_Object_Definition (Loc,
5139 All_Present => True,
5140 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5141 end if;
5143 -- Create the declaration of the target which captures the value of the
5144 -- expression.
5146 -- Generate:
5147 -- Target : [Ptr_]Typ;
5149 if not Optimize_Return_Stmt then
5150 Target := Make_Temporary (Loc, 'T');
5152 Decl :=
5153 Make_Object_Declaration (Loc,
5154 Defining_Identifier => Target,
5155 Object_Definition => New_Occurrence_Of (Target_Typ, Loc));
5156 Set_No_Initialization (Decl);
5158 Append_To (Acts, Decl);
5159 end if;
5161 -- Process the alternatives
5163 Alt := First (Alternatives (N));
5164 while Present (Alt) loop
5165 declare
5166 Alt_Expr : Node_Id := Expression (Alt);
5167 Alt_Loc : constant Source_Ptr := Sloc (Alt_Expr);
5168 Stmts : List_Id;
5170 begin
5171 -- Take the unrestricted access of the expression value for non-
5172 -- scalar types. This approach avoids big copies and covers the
5173 -- limited and unconstrained cases.
5175 -- Generate:
5176 -- AX'Unrestricted_Access
5178 if not Is_Copy_Type (Typ) then
5179 Alt_Expr :=
5180 Make_Attribute_Reference (Alt_Loc,
5181 Prefix => Relocate_Node (Alt_Expr),
5182 Attribute_Name => Name_Unrestricted_Access);
5183 end if;
5185 -- Generate:
5186 -- return AX['Unrestricted_Access];
5188 if Optimize_Return_Stmt then
5189 Stmts := New_List (
5190 Make_Simple_Return_Statement (Alt_Loc,
5191 Expression => Alt_Expr));
5193 -- Generate:
5194 -- Target := AX['Unrestricted_Access];
5196 else
5197 Stmts := New_List (
5198 Make_Assignment_Statement (Alt_Loc,
5199 Name => New_Occurrence_Of (Target, Loc),
5200 Expression => Alt_Expr));
5201 end if;
5203 -- Propagate declarations inserted in the node by Insert_Actions
5204 -- (for example, temporaries generated to remove side effects).
5205 -- These actions must remain attached to the alternative, given
5206 -- that they are generated by the corresponding expression.
5208 if Present (Actions (Alt)) then
5209 Prepend_List (Actions (Alt), Stmts);
5210 end if;
5212 -- Finalize any transient objects on exit from the alternative.
5213 -- This is done only in the return optimization case because
5214 -- otherwise the case expression is converted into an expression
5215 -- with actions which already contains this form of processing.
5217 if Optimize_Return_Stmt then
5218 Process_If_Case_Statements (N, Stmts);
5219 end if;
5221 Append_To
5222 (Alternatives (Case_Stmt),
5223 Make_Case_Statement_Alternative (Sloc (Alt),
5224 Discrete_Choices => Discrete_Choices (Alt),
5225 Statements => Stmts));
5226 end;
5228 Next (Alt);
5229 end loop;
5231 -- Rewrite the parent return statement as a case statement
5233 if Optimize_Return_Stmt then
5234 Rewrite (Par, Case_Stmt);
5235 Analyze (Par);
5237 -- Otherwise convert the case expression into an expression with actions
5239 else
5240 Append_To (Acts, Case_Stmt);
5242 if Is_Copy_Type (Typ) then
5243 Expr := New_Occurrence_Of (Target, Loc);
5245 else
5246 Expr :=
5247 Make_Explicit_Dereference (Loc,
5248 Prefix => New_Occurrence_Of (Target, Loc));
5249 end if;
5251 -- Generate:
5252 -- do
5253 -- ...
5254 -- in Target[.all] end;
5256 Rewrite (N,
5257 Make_Expression_With_Actions (Loc,
5258 Expression => Expr,
5259 Actions => Acts));
5261 Analyze_And_Resolve (N, Typ);
5262 end if;
5263 end Expand_N_Case_Expression;
5265 -----------------------------------
5266 -- Expand_N_Explicit_Dereference --
5267 -----------------------------------
5269 procedure Expand_N_Explicit_Dereference (N : Node_Id) is
5270 begin
5271 -- Insert explicit dereference call for the checked storage pool case
5273 Insert_Dereference_Action (Prefix (N));
5275 -- If the type is an Atomic type for which Atomic_Sync is enabled, then
5276 -- we set the atomic sync flag.
5278 if Is_Atomic (Etype (N))
5279 and then not Atomic_Synchronization_Disabled (Etype (N))
5280 then
5281 Activate_Atomic_Synchronization (N);
5282 end if;
5283 end Expand_N_Explicit_Dereference;
5285 --------------------------------------
5286 -- Expand_N_Expression_With_Actions --
5287 --------------------------------------
5289 procedure Expand_N_Expression_With_Actions (N : Node_Id) is
5290 Acts : constant List_Id := Actions (N);
5292 procedure Force_Boolean_Evaluation (Expr : Node_Id);
5293 -- Force the evaluation of Boolean expression Expr
5295 function Process_Action (Act : Node_Id) return Traverse_Result;
5296 -- Inspect and process a single action of an expression_with_actions for
5297 -- transient objects. If such objects are found, the routine generates
5298 -- code to clean them up when the context of the expression is evaluated
5299 -- or elaborated.
5301 ------------------------------
5302 -- Force_Boolean_Evaluation --
5303 ------------------------------
5305 procedure Force_Boolean_Evaluation (Expr : Node_Id) is
5306 Loc : constant Source_Ptr := Sloc (N);
5307 Flag_Decl : Node_Id;
5308 Flag_Id : Entity_Id;
5310 begin
5311 -- Relocate the expression to the actions list by capturing its value
5312 -- in a Boolean flag. Generate:
5313 -- Flag : constant Boolean := Expr;
5315 Flag_Id := Make_Temporary (Loc, 'F');
5317 Flag_Decl :=
5318 Make_Object_Declaration (Loc,
5319 Defining_Identifier => Flag_Id,
5320 Constant_Present => True,
5321 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
5322 Expression => Relocate_Node (Expr));
5324 Append (Flag_Decl, Acts);
5325 Analyze (Flag_Decl);
5327 -- Replace the expression with a reference to the flag
5329 Rewrite (Expression (N), New_Occurrence_Of (Flag_Id, Loc));
5330 Analyze (Expression (N));
5331 end Force_Boolean_Evaluation;
5333 --------------------
5334 -- Process_Action --
5335 --------------------
5337 function Process_Action (Act : Node_Id) return Traverse_Result is
5338 begin
5339 if Nkind (Act) = N_Object_Declaration
5340 and then Is_Finalizable_Transient (Act, N)
5341 then
5342 Process_Transient_In_Expression (Act, N, Acts);
5343 return Abandon;
5345 -- Avoid processing temporary function results multiple times when
5346 -- dealing with nested expression_with_actions.
5348 elsif Nkind (Act) = N_Expression_With_Actions then
5349 return Abandon;
5351 -- Do not process temporary function results in loops. This is done
5352 -- by Expand_N_Loop_Statement and Build_Finalizer.
5354 elsif Nkind (Act) = N_Loop_Statement then
5355 return Abandon;
5356 end if;
5358 return OK;
5359 end Process_Action;
5361 procedure Process_Single_Action is new Traverse_Proc (Process_Action);
5363 -- Local variables
5365 Act : Node_Id;
5367 -- Start of processing for Expand_N_Expression_With_Actions
5369 begin
5370 -- Do not evaluate the expression when it denotes an entity because the
5371 -- expression_with_actions node will be replaced by the reference.
5373 if Is_Entity_Name (Expression (N)) then
5374 null;
5376 -- Do not evaluate the expression when there are no actions because the
5377 -- expression_with_actions node will be replaced by the expression.
5379 elsif No (Acts) or else Is_Empty_List (Acts) then
5380 null;
5382 -- Force the evaluation of the expression by capturing its value in a
5383 -- temporary. This ensures that aliases of transient objects do not leak
5384 -- to the expression of the expression_with_actions node:
5386 -- do
5387 -- Trans_Id : Ctrl_Typ := ...;
5388 -- Alias : ... := Trans_Id;
5389 -- in ... Alias ... end;
5391 -- In the example above, Trans_Id cannot be finalized at the end of the
5392 -- actions list because this may affect the alias and the final value of
5393 -- the expression_with_actions. Forcing the evaluation encapsulates the
5394 -- reference to the Alias within the actions list:
5396 -- do
5397 -- Trans_Id : Ctrl_Typ := ...;
5398 -- Alias : ... := Trans_Id;
5399 -- Val : constant Boolean := ... Alias ...;
5400 -- <finalize Trans_Id>
5401 -- in Val end;
5403 -- Once this transformation is performed, it is safe to finalize the
5404 -- transient object at the end of the actions list.
5406 -- Note that Force_Evaluation does not remove side effects in operators
5407 -- because it assumes that all operands are evaluated and side effect
5408 -- free. This is not the case when an operand depends implicitly on the
5409 -- transient object through the use of access types.
5411 elsif Is_Boolean_Type (Etype (Expression (N))) then
5412 Force_Boolean_Evaluation (Expression (N));
5414 -- The expression of an expression_with_actions node may not necessarily
5415 -- be Boolean when the node appears in an if expression. In this case do
5416 -- the usual forced evaluation to encapsulate potential aliasing.
5418 else
5419 Force_Evaluation (Expression (N));
5420 end if;
5422 -- Process all transient objects found within the actions of the EWA
5423 -- node.
5425 Act := First (Acts);
5426 while Present (Act) loop
5427 Process_Single_Action (Act);
5428 Next (Act);
5429 end loop;
5431 -- Deal with case where there are no actions. In this case we simply
5432 -- rewrite the node with its expression since we don't need the actions
5433 -- and the specification of this node does not allow a null action list.
5435 -- Note: we use Rewrite instead of Replace, because Codepeer is using
5436 -- the expanded tree and relying on being able to retrieve the original
5437 -- tree in cases like this. This raises a whole lot of issues of whether
5438 -- we have problems elsewhere, which will be addressed in the future???
5440 if Is_Empty_List (Acts) then
5441 Rewrite (N, Relocate_Node (Expression (N)));
5442 end if;
5443 end Expand_N_Expression_With_Actions;
5445 ----------------------------
5446 -- Expand_N_If_Expression --
5447 ----------------------------
5449 -- Deal with limited types and condition actions
5451 procedure Expand_N_If_Expression (N : Node_Id) is
5452 Cond : constant Node_Id := First (Expressions (N));
5453 Loc : constant Source_Ptr := Sloc (N);
5454 Thenx : constant Node_Id := Next (Cond);
5455 Elsex : constant Node_Id := Next (Thenx);
5456 Typ : constant Entity_Id := Etype (N);
5458 Actions : List_Id;
5459 Decl : Node_Id;
5460 Expr : Node_Id;
5461 New_If : Node_Id;
5462 New_N : Node_Id;
5464 begin
5465 -- Check for MINIMIZED/ELIMINATED overflow mode
5467 if Minimized_Eliminated_Overflow_Check (N) then
5468 Apply_Arithmetic_Overflow_Check (N);
5469 return;
5470 end if;
5472 -- Fold at compile time if condition known. We have already folded
5473 -- static if expressions, but it is possible to fold any case in which
5474 -- the condition is known at compile time, even though the result is
5475 -- non-static.
5477 -- Note that we don't do the fold of such cases in Sem_Elab because
5478 -- it can cause infinite loops with the expander adding a conditional
5479 -- expression, and Sem_Elab circuitry removing it repeatedly.
5481 if Compile_Time_Known_Value (Cond) then
5482 declare
5483 function Fold_Known_Value (Cond : Node_Id) return Boolean;
5484 -- Fold at compile time. Assumes condition known. Return True if
5485 -- folding occurred, meaning we're done.
5487 ----------------------
5488 -- Fold_Known_Value --
5489 ----------------------
5491 function Fold_Known_Value (Cond : Node_Id) return Boolean is
5492 begin
5493 if Is_True (Expr_Value (Cond)) then
5494 Expr := Thenx;
5495 Actions := Then_Actions (N);
5496 else
5497 Expr := Elsex;
5498 Actions := Else_Actions (N);
5499 end if;
5501 Remove (Expr);
5503 if Present (Actions) then
5505 -- To minimize the use of Expression_With_Actions, just skip
5506 -- the optimization as it is not critical for correctness.
5508 if Minimize_Expression_With_Actions then
5509 return False;
5510 end if;
5512 Rewrite (N,
5513 Make_Expression_With_Actions (Loc,
5514 Expression => Relocate_Node (Expr),
5515 Actions => Actions));
5516 Analyze_And_Resolve (N, Typ);
5518 else
5519 Rewrite (N, Relocate_Node (Expr));
5520 end if;
5522 -- Note that the result is never static (legitimate cases of
5523 -- static if expressions were folded in Sem_Eval).
5525 Set_Is_Static_Expression (N, False);
5526 return True;
5527 end Fold_Known_Value;
5529 begin
5530 if Fold_Known_Value (Cond) then
5531 return;
5532 end if;
5533 end;
5534 end if;
5536 -- If the type is limited, and the back end does not handle limited
5537 -- types, then we expand as follows to avoid the possibility of
5538 -- improper copying.
5540 -- type Ptr is access all Typ;
5541 -- Cnn : Ptr;
5542 -- if cond then
5543 -- <<then actions>>
5544 -- Cnn := then-expr'Unrestricted_Access;
5545 -- else
5546 -- <<else actions>>
5547 -- Cnn := else-expr'Unrestricted_Access;
5548 -- end if;
5550 -- and replace the if expression by a reference to Cnn.all.
5552 -- This special case can be skipped if the back end handles limited
5553 -- types properly and ensures that no incorrect copies are made.
5555 if Is_By_Reference_Type (Typ)
5556 and then not Back_End_Handles_Limited_Types
5557 then
5558 -- When the "then" or "else" expressions involve controlled function
5559 -- calls, generated temporaries are chained on the corresponding list
5560 -- of actions. These temporaries need to be finalized after the if
5561 -- expression is evaluated.
5563 Process_If_Case_Statements (N, Then_Actions (N));
5564 Process_If_Case_Statements (N, Else_Actions (N));
5566 declare
5567 Cnn : constant Entity_Id := Make_Temporary (Loc, 'C', N);
5568 Ptr_Typ : constant Entity_Id := Make_Temporary (Loc, 'A');
5570 begin
5571 -- Generate:
5572 -- type Ann is access all Typ;
5574 Insert_Action (N,
5575 Make_Full_Type_Declaration (Loc,
5576 Defining_Identifier => Ptr_Typ,
5577 Type_Definition =>
5578 Make_Access_To_Object_Definition (Loc,
5579 All_Present => True,
5580 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5582 -- Generate:
5583 -- Cnn : Ann;
5585 Decl :=
5586 Make_Object_Declaration (Loc,
5587 Defining_Identifier => Cnn,
5588 Object_Definition => New_Occurrence_Of (Ptr_Typ, Loc));
5590 -- Generate:
5591 -- if Cond then
5592 -- Cnn := <Thenx>'Unrestricted_Access;
5593 -- else
5594 -- Cnn := <Elsex>'Unrestricted_Access;
5595 -- end if;
5597 New_If :=
5598 Make_Implicit_If_Statement (N,
5599 Condition => Relocate_Node (Cond),
5600 Then_Statements => New_List (
5601 Make_Assignment_Statement (Sloc (Thenx),
5602 Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
5603 Expression =>
5604 Make_Attribute_Reference (Loc,
5605 Prefix => Relocate_Node (Thenx),
5606 Attribute_Name => Name_Unrestricted_Access))),
5608 Else_Statements => New_List (
5609 Make_Assignment_Statement (Sloc (Elsex),
5610 Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
5611 Expression =>
5612 Make_Attribute_Reference (Loc,
5613 Prefix => Relocate_Node (Elsex),
5614 Attribute_Name => Name_Unrestricted_Access))));
5616 -- Preserve the original context for which the if statement is
5617 -- being generated. This is needed by the finalization machinery
5618 -- to prevent the premature finalization of controlled objects
5619 -- found within the if statement.
5621 Set_From_Conditional_Expression (New_If);
5623 New_N :=
5624 Make_Explicit_Dereference (Loc,
5625 Prefix => New_Occurrence_Of (Cnn, Loc));
5626 end;
5628 -- If the result is an unconstrained array and the if expression is in a
5629 -- context other than the initializing expression of the declaration of
5630 -- an object, then we pull out the if expression as follows:
5632 -- Cnn : constant typ := if-expression
5634 -- and then replace the if expression with an occurrence of Cnn. This
5635 -- avoids the need in the back end to create on-the-fly variable length
5636 -- temporaries (which it cannot do!)
5638 -- Note that the test for being in an object declaration avoids doing an
5639 -- unnecessary expansion, and also avoids infinite recursion.
5641 elsif Is_Array_Type (Typ) and then not Is_Constrained (Typ)
5642 and then (Nkind (Parent (N)) /= N_Object_Declaration
5643 or else Expression (Parent (N)) /= N)
5644 then
5645 declare
5646 Cnn : constant Node_Id := Make_Temporary (Loc, 'C', N);
5648 begin
5649 Insert_Action (N,
5650 Make_Object_Declaration (Loc,
5651 Defining_Identifier => Cnn,
5652 Constant_Present => True,
5653 Object_Definition => New_Occurrence_Of (Typ, Loc),
5654 Expression => Relocate_Node (N),
5655 Has_Init_Expression => True));
5657 Rewrite (N, New_Occurrence_Of (Cnn, Loc));
5658 return;
5659 end;
5661 -- For other types, we only need to expand if there are other actions
5662 -- associated with either branch.
5664 elsif Present (Then_Actions (N)) or else Present (Else_Actions (N)) then
5666 -- We now wrap the actions into the appropriate expression
5668 if Minimize_Expression_With_Actions
5669 and then (Is_Elementary_Type (Underlying_Type (Typ))
5670 or else Is_Constrained (Underlying_Type (Typ)))
5671 then
5672 -- If we can't use N_Expression_With_Actions nodes, then we insert
5673 -- the following sequence of actions (using Insert_Actions):
5675 -- Cnn : typ;
5676 -- if cond then
5677 -- <<then actions>>
5678 -- Cnn := then-expr;
5679 -- else
5680 -- <<else actions>>
5681 -- Cnn := else-expr
5682 -- end if;
5684 -- and replace the if expression by a reference to Cnn
5686 declare
5687 Cnn : constant Node_Id := Make_Temporary (Loc, 'C', N);
5689 begin
5690 Decl :=
5691 Make_Object_Declaration (Loc,
5692 Defining_Identifier => Cnn,
5693 Object_Definition => New_Occurrence_Of (Typ, Loc));
5695 New_If :=
5696 Make_Implicit_If_Statement (N,
5697 Condition => Relocate_Node (Cond),
5699 Then_Statements => New_List (
5700 Make_Assignment_Statement (Sloc (Thenx),
5701 Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
5702 Expression => Relocate_Node (Thenx))),
5704 Else_Statements => New_List (
5705 Make_Assignment_Statement (Sloc (Elsex),
5706 Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
5707 Expression => Relocate_Node (Elsex))));
5709 Set_Assignment_OK (Name (First (Then_Statements (New_If))));
5710 Set_Assignment_OK (Name (First (Else_Statements (New_If))));
5712 New_N := New_Occurrence_Of (Cnn, Loc);
5713 end;
5715 -- Regular path using Expression_With_Actions
5717 else
5718 if Present (Then_Actions (N)) then
5719 Rewrite (Thenx,
5720 Make_Expression_With_Actions (Sloc (Thenx),
5721 Actions => Then_Actions (N),
5722 Expression => Relocate_Node (Thenx)));
5724 Set_Then_Actions (N, No_List);
5725 Analyze_And_Resolve (Thenx, Typ);
5726 end if;
5728 if Present (Else_Actions (N)) then
5729 Rewrite (Elsex,
5730 Make_Expression_With_Actions (Sloc (Elsex),
5731 Actions => Else_Actions (N),
5732 Expression => Relocate_Node (Elsex)));
5734 Set_Else_Actions (N, No_List);
5735 Analyze_And_Resolve (Elsex, Typ);
5736 end if;
5738 return;
5739 end if;
5741 -- If no actions then no expansion needed, gigi will handle it using the
5742 -- same approach as a C conditional expression.
5744 else
5745 return;
5746 end if;
5748 -- Fall through here for either the limited expansion, or the case of
5749 -- inserting actions for nonlimited types. In both these cases, we must
5750 -- move the SLOC of the parent If statement to the newly created one and
5751 -- change it to the SLOC of the expression which, after expansion, will
5752 -- correspond to what is being evaluated.
5754 if Present (Parent (N)) and then Nkind (Parent (N)) = N_If_Statement then
5755 Set_Sloc (New_If, Sloc (Parent (N)));
5756 Set_Sloc (Parent (N), Loc);
5757 end if;
5759 -- Make sure Then_Actions and Else_Actions are appropriately moved
5760 -- to the new if statement.
5762 if Present (Then_Actions (N)) then
5763 Insert_List_Before
5764 (First (Then_Statements (New_If)), Then_Actions (N));
5765 end if;
5767 if Present (Else_Actions (N)) then
5768 Insert_List_Before
5769 (First (Else_Statements (New_If)), Else_Actions (N));
5770 end if;
5772 Insert_Action (N, Decl);
5773 Insert_Action (N, New_If);
5774 Rewrite (N, New_N);
5775 Analyze_And_Resolve (N, Typ);
5776 end Expand_N_If_Expression;
5778 -----------------
5779 -- Expand_N_In --
5780 -----------------
5782 procedure Expand_N_In (N : Node_Id) is
5783 Loc : constant Source_Ptr := Sloc (N);
5784 Restyp : constant Entity_Id := Etype (N);
5785 Lop : constant Node_Id := Left_Opnd (N);
5786 Rop : constant Node_Id := Right_Opnd (N);
5787 Static : constant Boolean := Is_OK_Static_Expression (N);
5789 procedure Substitute_Valid_Check;
5790 -- Replaces node N by Lop'Valid. This is done when we have an explicit
5791 -- test for the left operand being in range of its subtype.
5793 ----------------------------
5794 -- Substitute_Valid_Check --
5795 ----------------------------
5797 procedure Substitute_Valid_Check is
5798 function Is_OK_Object_Reference (Nod : Node_Id) return Boolean;
5799 -- Determine whether arbitrary node Nod denotes a source object that
5800 -- may safely act as prefix of attribute 'Valid.
5802 ----------------------------
5803 -- Is_OK_Object_Reference --
5804 ----------------------------
5806 function Is_OK_Object_Reference (Nod : Node_Id) return Boolean is
5807 Obj_Ref : Node_Id;
5809 begin
5810 -- Inspect the original operand
5812 Obj_Ref := Original_Node (Nod);
5814 -- The object reference must be a source construct, otherwise the
5815 -- codefix suggestion may refer to nonexistent code from a user
5816 -- perspective.
5818 if Comes_From_Source (Obj_Ref) then
5820 -- Recover the actual object reference. There may be more cases
5821 -- to consider???
5823 loop
5824 if Nkind_In (Obj_Ref, N_Type_Conversion,
5825 N_Unchecked_Type_Conversion)
5826 then
5827 Obj_Ref := Expression (Obj_Ref);
5828 else
5829 exit;
5830 end if;
5831 end loop;
5833 return Is_Object_Reference (Obj_Ref);
5834 end if;
5836 return False;
5837 end Is_OK_Object_Reference;
5839 -- Start of processing for Substitute_Valid_Check
5841 begin
5842 Rewrite (N,
5843 Make_Attribute_Reference (Loc,
5844 Prefix => Relocate_Node (Lop),
5845 Attribute_Name => Name_Valid));
5847 Analyze_And_Resolve (N, Restyp);
5849 -- Emit a warning when the left-hand operand of the membership test
5850 -- is a source object, otherwise the use of attribute 'Valid would be
5851 -- illegal. The warning is not given when overflow checking is either
5852 -- MINIMIZED or ELIMINATED, as the danger of optimization has been
5853 -- eliminated above.
5855 if Is_OK_Object_Reference (Lop)
5856 and then Overflow_Check_Mode not in Minimized_Or_Eliminated
5857 then
5858 Error_Msg_N
5859 ("??explicit membership test may be optimized away", N);
5860 Error_Msg_N -- CODEFIX
5861 ("\??use ''Valid attribute instead", N);
5862 end if;
5863 end Substitute_Valid_Check;
5865 -- Local variables
5867 Ltyp : Entity_Id;
5868 Rtyp : Entity_Id;
5870 -- Start of processing for Expand_N_In
5872 begin
5873 -- If set membership case, expand with separate procedure
5875 if Present (Alternatives (N)) then
5876 Expand_Set_Membership (N);
5877 return;
5878 end if;
5880 -- Not set membership, proceed with expansion
5882 Ltyp := Etype (Left_Opnd (N));
5883 Rtyp := Etype (Right_Opnd (N));
5885 -- If MINIMIZED/ELIMINATED overflow mode and type is a signed integer
5886 -- type, then expand with a separate procedure. Note the use of the
5887 -- flag No_Minimize_Eliminate to prevent infinite recursion.
5889 if Overflow_Check_Mode in Minimized_Or_Eliminated
5890 and then Is_Signed_Integer_Type (Ltyp)
5891 and then not No_Minimize_Eliminate (N)
5892 then
5893 Expand_Membership_Minimize_Eliminate_Overflow (N);
5894 return;
5895 end if;
5897 -- Check case of explicit test for an expression in range of its
5898 -- subtype. This is suspicious usage and we replace it with a 'Valid
5899 -- test and give a warning for scalar types.
5901 if Is_Scalar_Type (Ltyp)
5903 -- Only relevant for source comparisons
5905 and then Comes_From_Source (N)
5907 -- In floating-point this is a standard way to check for finite values
5908 -- and using 'Valid would typically be a pessimization.
5910 and then not Is_Floating_Point_Type (Ltyp)
5912 -- Don't give the message unless right operand is a type entity and
5913 -- the type of the left operand matches this type. Note that this
5914 -- eliminates the cases where MINIMIZED/ELIMINATED mode overflow
5915 -- checks have changed the type of the left operand.
5917 and then Nkind (Rop) in N_Has_Entity
5918 and then Ltyp = Entity (Rop)
5920 -- Skip this for predicated types, where such expressions are a
5921 -- reasonable way of testing if something meets the predicate.
5923 and then not Present (Predicate_Function (Ltyp))
5924 then
5925 Substitute_Valid_Check;
5926 return;
5927 end if;
5929 -- Do validity check on operands
5931 if Validity_Checks_On and Validity_Check_Operands then
5932 Ensure_Valid (Left_Opnd (N));
5933 Validity_Check_Range (Right_Opnd (N));
5934 end if;
5936 -- Case of explicit range
5938 if Nkind (Rop) = N_Range then
5939 declare
5940 Lo : constant Node_Id := Low_Bound (Rop);
5941 Hi : constant Node_Id := High_Bound (Rop);
5943 Lo_Orig : constant Node_Id := Original_Node (Lo);
5944 Hi_Orig : constant Node_Id := Original_Node (Hi);
5946 Lcheck : Compare_Result;
5947 Ucheck : Compare_Result;
5949 Warn1 : constant Boolean :=
5950 Constant_Condition_Warnings
5951 and then Comes_From_Source (N)
5952 and then not In_Instance;
5953 -- This must be true for any of the optimization warnings, we
5954 -- clearly want to give them only for source with the flag on. We
5955 -- also skip these warnings in an instance since it may be the
5956 -- case that different instantiations have different ranges.
5958 Warn2 : constant Boolean :=
5959 Warn1
5960 and then Nkind (Original_Node (Rop)) = N_Range
5961 and then Is_Integer_Type (Etype (Lo));
5962 -- For the case where only one bound warning is elided, we also
5963 -- insist on an explicit range and an integer type. The reason is
5964 -- that the use of enumeration ranges including an end point is
5965 -- common, as is the use of a subtype name, one of whose bounds is
5966 -- the same as the type of the expression.
5968 begin
5969 -- If test is explicit x'First .. x'Last, replace by valid check
5971 -- Could use some individual comments for this complex test ???
5973 if Is_Scalar_Type (Ltyp)
5975 -- And left operand is X'First where X matches left operand
5976 -- type (this eliminates cases of type mismatch, including
5977 -- the cases where ELIMINATED/MINIMIZED mode has changed the
5978 -- type of the left operand.
5980 and then Nkind (Lo_Orig) = N_Attribute_Reference
5981 and then Attribute_Name (Lo_Orig) = Name_First
5982 and then Nkind (Prefix (Lo_Orig)) in N_Has_Entity
5983 and then Entity (Prefix (Lo_Orig)) = Ltyp
5985 -- Same tests for right operand
5987 and then Nkind (Hi_Orig) = N_Attribute_Reference
5988 and then Attribute_Name (Hi_Orig) = Name_Last
5989 and then Nkind (Prefix (Hi_Orig)) in N_Has_Entity
5990 and then Entity (Prefix (Hi_Orig)) = Ltyp
5992 -- Relevant only for source cases
5994 and then Comes_From_Source (N)
5995 then
5996 Substitute_Valid_Check;
5997 goto Leave;
5998 end if;
6000 -- If bounds of type are known at compile time, and the end points
6001 -- are known at compile time and identical, this is another case
6002 -- for substituting a valid test. We only do this for discrete
6003 -- types, since it won't arise in practice for float types.
6005 if Comes_From_Source (N)
6006 and then Is_Discrete_Type (Ltyp)
6007 and then Compile_Time_Known_Value (Type_High_Bound (Ltyp))
6008 and then Compile_Time_Known_Value (Type_Low_Bound (Ltyp))
6009 and then Compile_Time_Known_Value (Lo)
6010 and then Compile_Time_Known_Value (Hi)
6011 and then Expr_Value (Type_High_Bound (Ltyp)) = Expr_Value (Hi)
6012 and then Expr_Value (Type_Low_Bound (Ltyp)) = Expr_Value (Lo)
6014 -- Kill warnings in instances, since they may be cases where we
6015 -- have a test in the generic that makes sense with some types
6016 -- and not with other types.
6018 and then not In_Instance
6019 then
6020 Substitute_Valid_Check;
6021 goto Leave;
6022 end if;
6024 -- If we have an explicit range, do a bit of optimization based on
6025 -- range analysis (we may be able to kill one or both checks).
6027 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => False);
6028 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => False);
6030 -- If either check is known to fail, replace result by False since
6031 -- the other check does not matter. Preserve the static flag for
6032 -- legality checks, because we are constant-folding beyond RM 4.9.
6034 if Lcheck = LT or else Ucheck = GT then
6035 if Warn1 then
6036 Error_Msg_N ("?c?range test optimized away", N);
6037 Error_Msg_N ("\?c?value is known to be out of range", N);
6038 end if;
6040 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6041 Analyze_And_Resolve (N, Restyp);
6042 Set_Is_Static_Expression (N, Static);
6043 goto Leave;
6045 -- If both checks are known to succeed, replace result by True,
6046 -- since we know we are in range.
6048 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
6049 if Warn1 then
6050 Error_Msg_N ("?c?range test optimized away", N);
6051 Error_Msg_N ("\?c?value is known to be in range", N);
6052 end if;
6054 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6055 Analyze_And_Resolve (N, Restyp);
6056 Set_Is_Static_Expression (N, Static);
6057 goto Leave;
6059 -- If lower bound check succeeds and upper bound check is not
6060 -- known to succeed or fail, then replace the range check with
6061 -- a comparison against the upper bound.
6063 elsif Lcheck in Compare_GE then
6064 if Warn2 and then not In_Instance then
6065 Error_Msg_N ("??lower bound test optimized away", Lo);
6066 Error_Msg_N ("\??value is known to be in range", Lo);
6067 end if;
6069 Rewrite (N,
6070 Make_Op_Le (Loc,
6071 Left_Opnd => Lop,
6072 Right_Opnd => High_Bound (Rop)));
6073 Analyze_And_Resolve (N, Restyp);
6074 goto Leave;
6076 -- If upper bound check succeeds and lower bound check is not
6077 -- known to succeed or fail, then replace the range check with
6078 -- a comparison against the lower bound.
6080 elsif Ucheck in Compare_LE then
6081 if Warn2 and then not In_Instance then
6082 Error_Msg_N ("??upper bound test optimized away", Hi);
6083 Error_Msg_N ("\??value is known to be in range", Hi);
6084 end if;
6086 Rewrite (N,
6087 Make_Op_Ge (Loc,
6088 Left_Opnd => Lop,
6089 Right_Opnd => Low_Bound (Rop)));
6090 Analyze_And_Resolve (N, Restyp);
6091 goto Leave;
6092 end if;
6094 -- We couldn't optimize away the range check, but there is one
6095 -- more issue. If we are checking constant conditionals, then we
6096 -- see if we can determine the outcome assuming everything is
6097 -- valid, and if so give an appropriate warning.
6099 if Warn1 and then not Assume_No_Invalid_Values then
6100 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => True);
6101 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => True);
6103 -- Result is out of range for valid value
6105 if Lcheck = LT or else Ucheck = GT then
6106 Error_Msg_N
6107 ("?c?value can only be in range if it is invalid", N);
6109 -- Result is in range for valid value
6111 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
6112 Error_Msg_N
6113 ("?c?value can only be out of range if it is invalid", N);
6115 -- Lower bound check succeeds if value is valid
6117 elsif Warn2 and then Lcheck in Compare_GE then
6118 Error_Msg_N
6119 ("?c?lower bound check only fails if it is invalid", Lo);
6121 -- Upper bound check succeeds if value is valid
6123 elsif Warn2 and then Ucheck in Compare_LE then
6124 Error_Msg_N
6125 ("?c?upper bound check only fails for invalid values", Hi);
6126 end if;
6127 end if;
6128 end;
6130 -- For all other cases of an explicit range, nothing to be done
6132 goto Leave;
6134 -- Here right operand is a subtype mark
6136 else
6137 declare
6138 Typ : Entity_Id := Etype (Rop);
6139 Is_Acc : constant Boolean := Is_Access_Type (Typ);
6140 Cond : Node_Id := Empty;
6141 New_N : Node_Id;
6142 Obj : Node_Id := Lop;
6143 SCIL_Node : Node_Id;
6145 begin
6146 Remove_Side_Effects (Obj);
6148 -- For tagged type, do tagged membership operation
6150 if Is_Tagged_Type (Typ) then
6152 -- No expansion will be performed for VM targets, as the VM
6153 -- back ends will handle the membership tests directly.
6155 if Tagged_Type_Expansion then
6156 Tagged_Membership (N, SCIL_Node, New_N);
6157 Rewrite (N, New_N);
6158 Analyze_And_Resolve (N, Restyp, Suppress => All_Checks);
6160 -- Update decoration of relocated node referenced by the
6161 -- SCIL node.
6163 if Generate_SCIL and then Present (SCIL_Node) then
6164 Set_SCIL_Node (N, SCIL_Node);
6165 end if;
6166 end if;
6168 goto Leave;
6170 -- If type is scalar type, rewrite as x in t'First .. t'Last.
6171 -- This reason we do this is that the bounds may have the wrong
6172 -- type if they come from the original type definition. Also this
6173 -- way we get all the processing above for an explicit range.
6175 -- Don't do this for predicated types, since in this case we
6176 -- want to check the predicate.
6178 elsif Is_Scalar_Type (Typ) then
6179 if No (Predicate_Function (Typ)) then
6180 Rewrite (Rop,
6181 Make_Range (Loc,
6182 Low_Bound =>
6183 Make_Attribute_Reference (Loc,
6184 Attribute_Name => Name_First,
6185 Prefix => New_Occurrence_Of (Typ, Loc)),
6187 High_Bound =>
6188 Make_Attribute_Reference (Loc,
6189 Attribute_Name => Name_Last,
6190 Prefix => New_Occurrence_Of (Typ, Loc))));
6191 Analyze_And_Resolve (N, Restyp);
6192 end if;
6194 goto Leave;
6196 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
6197 -- a membership test if the subtype mark denotes a constrained
6198 -- Unchecked_Union subtype and the expression lacks inferable
6199 -- discriminants.
6201 elsif Is_Unchecked_Union (Base_Type (Typ))
6202 and then Is_Constrained (Typ)
6203 and then not Has_Inferable_Discriminants (Lop)
6204 then
6205 Insert_Action (N,
6206 Make_Raise_Program_Error (Loc,
6207 Reason => PE_Unchecked_Union_Restriction));
6209 -- Prevent Gigi from generating incorrect code by rewriting the
6210 -- test as False. What is this undocumented thing about ???
6212 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6213 goto Leave;
6214 end if;
6216 -- Here we have a non-scalar type
6218 if Is_Acc then
6219 Typ := Designated_Type (Typ);
6220 end if;
6222 if not Is_Constrained (Typ) then
6223 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6224 Analyze_And_Resolve (N, Restyp);
6226 -- For the constrained array case, we have to check the subscripts
6227 -- for an exact match if the lengths are non-zero (the lengths
6228 -- must match in any case).
6230 elsif Is_Array_Type (Typ) then
6231 Check_Subscripts : declare
6232 function Build_Attribute_Reference
6233 (E : Node_Id;
6234 Nam : Name_Id;
6235 Dim : Nat) return Node_Id;
6236 -- Build attribute reference E'Nam (Dim)
6238 -------------------------------
6239 -- Build_Attribute_Reference --
6240 -------------------------------
6242 function Build_Attribute_Reference
6243 (E : Node_Id;
6244 Nam : Name_Id;
6245 Dim : Nat) return Node_Id
6247 begin
6248 return
6249 Make_Attribute_Reference (Loc,
6250 Prefix => E,
6251 Attribute_Name => Nam,
6252 Expressions => New_List (
6253 Make_Integer_Literal (Loc, Dim)));
6254 end Build_Attribute_Reference;
6256 -- Start of processing for Check_Subscripts
6258 begin
6259 for J in 1 .. Number_Dimensions (Typ) loop
6260 Evolve_And_Then (Cond,
6261 Make_Op_Eq (Loc,
6262 Left_Opnd =>
6263 Build_Attribute_Reference
6264 (Duplicate_Subexpr_No_Checks (Obj),
6265 Name_First, J),
6266 Right_Opnd =>
6267 Build_Attribute_Reference
6268 (New_Occurrence_Of (Typ, Loc), Name_First, J)));
6270 Evolve_And_Then (Cond,
6271 Make_Op_Eq (Loc,
6272 Left_Opnd =>
6273 Build_Attribute_Reference
6274 (Duplicate_Subexpr_No_Checks (Obj),
6275 Name_Last, J),
6276 Right_Opnd =>
6277 Build_Attribute_Reference
6278 (New_Occurrence_Of (Typ, Loc), Name_Last, J)));
6279 end loop;
6281 if Is_Acc then
6282 Cond :=
6283 Make_Or_Else (Loc,
6284 Left_Opnd =>
6285 Make_Op_Eq (Loc,
6286 Left_Opnd => Obj,
6287 Right_Opnd => Make_Null (Loc)),
6288 Right_Opnd => Cond);
6289 end if;
6291 Rewrite (N, Cond);
6292 Analyze_And_Resolve (N, Restyp);
6293 end Check_Subscripts;
6295 -- These are the cases where constraint checks may be required,
6296 -- e.g. records with possible discriminants
6298 else
6299 -- Expand the test into a series of discriminant comparisons.
6300 -- The expression that is built is the negation of the one that
6301 -- is used for checking discriminant constraints.
6303 Obj := Relocate_Node (Left_Opnd (N));
6305 if Has_Discriminants (Typ) then
6306 Cond := Make_Op_Not (Loc,
6307 Right_Opnd => Build_Discriminant_Checks (Obj, Typ));
6309 if Is_Acc then
6310 Cond := Make_Or_Else (Loc,
6311 Left_Opnd =>
6312 Make_Op_Eq (Loc,
6313 Left_Opnd => Obj,
6314 Right_Opnd => Make_Null (Loc)),
6315 Right_Opnd => Cond);
6316 end if;
6318 else
6319 Cond := New_Occurrence_Of (Standard_True, Loc);
6320 end if;
6322 Rewrite (N, Cond);
6323 Analyze_And_Resolve (N, Restyp);
6324 end if;
6326 -- Ada 2012 (AI05-0149): Handle membership tests applied to an
6327 -- expression of an anonymous access type. This can involve an
6328 -- accessibility test and a tagged type membership test in the
6329 -- case of tagged designated types.
6331 if Ada_Version >= Ada_2012
6332 and then Is_Acc
6333 and then Ekind (Ltyp) = E_Anonymous_Access_Type
6334 then
6335 declare
6336 Expr_Entity : Entity_Id := Empty;
6337 New_N : Node_Id;
6338 Param_Level : Node_Id;
6339 Type_Level : Node_Id;
6341 begin
6342 if Is_Entity_Name (Lop) then
6343 Expr_Entity := Param_Entity (Lop);
6345 if not Present (Expr_Entity) then
6346 Expr_Entity := Entity (Lop);
6347 end if;
6348 end if;
6350 -- If a conversion of the anonymous access value to the
6351 -- tested type would be illegal, then the result is False.
6353 if not Valid_Conversion
6354 (Lop, Rtyp, Lop, Report_Errs => False)
6355 then
6356 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6357 Analyze_And_Resolve (N, Restyp);
6359 -- Apply an accessibility check if the access object has an
6360 -- associated access level and when the level of the type is
6361 -- less deep than the level of the access parameter. This
6362 -- only occur for access parameters and stand-alone objects
6363 -- of an anonymous access type.
6365 else
6366 if Present (Expr_Entity)
6367 and then
6368 Present
6369 (Effective_Extra_Accessibility (Expr_Entity))
6370 and then UI_Gt (Object_Access_Level (Lop),
6371 Type_Access_Level (Rtyp))
6372 then
6373 Param_Level :=
6374 New_Occurrence_Of
6375 (Effective_Extra_Accessibility (Expr_Entity), Loc);
6377 Type_Level :=
6378 Make_Integer_Literal (Loc, Type_Access_Level (Rtyp));
6380 -- Return True only if the accessibility level of the
6381 -- expression entity is not deeper than the level of
6382 -- the tested access type.
6384 Rewrite (N,
6385 Make_And_Then (Loc,
6386 Left_Opnd => Relocate_Node (N),
6387 Right_Opnd => Make_Op_Le (Loc,
6388 Left_Opnd => Param_Level,
6389 Right_Opnd => Type_Level)));
6391 Analyze_And_Resolve (N);
6392 end if;
6394 -- If the designated type is tagged, do tagged membership
6395 -- operation.
6397 -- *** NOTE: we have to check not null before doing the
6398 -- tagged membership test (but maybe that can be done
6399 -- inside Tagged_Membership?).
6401 if Is_Tagged_Type (Typ) then
6402 Rewrite (N,
6403 Make_And_Then (Loc,
6404 Left_Opnd => Relocate_Node (N),
6405 Right_Opnd =>
6406 Make_Op_Ne (Loc,
6407 Left_Opnd => Obj,
6408 Right_Opnd => Make_Null (Loc))));
6410 -- No expansion will be performed for VM targets, as
6411 -- the VM back ends will handle the membership tests
6412 -- directly.
6414 if Tagged_Type_Expansion then
6416 -- Note that we have to pass Original_Node, because
6417 -- the membership test might already have been
6418 -- rewritten by earlier parts of membership test.
6420 Tagged_Membership
6421 (Original_Node (N), SCIL_Node, New_N);
6423 -- Update decoration of relocated node referenced
6424 -- by the SCIL node.
6426 if Generate_SCIL and then Present (SCIL_Node) then
6427 Set_SCIL_Node (New_N, SCIL_Node);
6428 end if;
6430 Rewrite (N,
6431 Make_And_Then (Loc,
6432 Left_Opnd => Relocate_Node (N),
6433 Right_Opnd => New_N));
6435 Analyze_And_Resolve (N, Restyp);
6436 end if;
6437 end if;
6438 end if;
6439 end;
6440 end if;
6441 end;
6442 end if;
6444 -- At this point, we have done the processing required for the basic
6445 -- membership test, but not yet dealt with the predicate.
6447 <<Leave>>
6449 -- If a predicate is present, then we do the predicate test, but we
6450 -- most certainly want to omit this if we are within the predicate
6451 -- function itself, since otherwise we have an infinite recursion.
6452 -- The check should also not be emitted when testing against a range
6453 -- (the check is only done when the right operand is a subtype; see
6454 -- RM12-4.5.2 (28.1/3-30/3)).
6456 Predicate_Check : declare
6457 function In_Range_Check return Boolean;
6458 -- Within an expanded range check that may raise Constraint_Error do
6459 -- not generate a predicate check as well. It is redundant because
6460 -- the context will add an explicit predicate check, and it will
6461 -- raise the wrong exception if it fails.
6463 --------------------
6464 -- In_Range_Check --
6465 --------------------
6467 function In_Range_Check return Boolean is
6468 P : Node_Id;
6469 begin
6470 P := Parent (N);
6471 while Present (P) loop
6472 if Nkind (P) = N_Raise_Constraint_Error then
6473 return True;
6475 elsif Nkind (P) in N_Statement_Other_Than_Procedure_Call
6476 or else Nkind (P) = N_Procedure_Call_Statement
6477 or else Nkind (P) in N_Declaration
6478 then
6479 return False;
6480 end if;
6482 P := Parent (P);
6483 end loop;
6485 return False;
6486 end In_Range_Check;
6488 -- Local variables
6490 PFunc : constant Entity_Id := Predicate_Function (Rtyp);
6491 R_Op : Node_Id;
6493 -- Start of processing for Predicate_Check
6495 begin
6496 if Present (PFunc)
6497 and then Current_Scope /= PFunc
6498 and then Nkind (Rop) /= N_Range
6499 then
6500 if not In_Range_Check then
6501 R_Op := Make_Predicate_Call (Rtyp, Lop, Mem => True);
6502 else
6503 R_Op := New_Occurrence_Of (Standard_True, Loc);
6504 end if;
6506 Rewrite (N,
6507 Make_And_Then (Loc,
6508 Left_Opnd => Relocate_Node (N),
6509 Right_Opnd => R_Op));
6511 -- Analyze new expression, mark left operand as analyzed to
6512 -- avoid infinite recursion adding predicate calls. Similarly,
6513 -- suppress further range checks on the call.
6515 Set_Analyzed (Left_Opnd (N));
6516 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6518 -- All done, skip attempt at compile time determination of result
6520 return;
6521 end if;
6522 end Predicate_Check;
6523 end Expand_N_In;
6525 --------------------------------
6526 -- Expand_N_Indexed_Component --
6527 --------------------------------
6529 procedure Expand_N_Indexed_Component (N : Node_Id) is
6530 Loc : constant Source_Ptr := Sloc (N);
6531 Typ : constant Entity_Id := Etype (N);
6532 P : constant Node_Id := Prefix (N);
6533 T : constant Entity_Id := Etype (P);
6534 Atp : Entity_Id;
6536 begin
6537 -- A special optimization, if we have an indexed component that is
6538 -- selecting from a slice, then we can eliminate the slice, since, for
6539 -- example, x (i .. j)(k) is identical to x(k). The only difference is
6540 -- the range check required by the slice. The range check for the slice
6541 -- itself has already been generated. The range check for the
6542 -- subscripting operation is ensured by converting the subject to
6543 -- the subtype of the slice.
6545 -- This optimization not only generates better code, avoiding slice
6546 -- messing especially in the packed case, but more importantly bypasses
6547 -- some problems in handling this peculiar case, for example, the issue
6548 -- of dealing specially with object renamings.
6550 if Nkind (P) = N_Slice
6552 -- This optimization is disabled for CodePeer because it can transform
6553 -- an index-check constraint_error into a range-check constraint_error
6554 -- and CodePeer cares about that distinction.
6556 and then not CodePeer_Mode
6557 then
6558 Rewrite (N,
6559 Make_Indexed_Component (Loc,
6560 Prefix => Prefix (P),
6561 Expressions => New_List (
6562 Convert_To
6563 (Etype (First_Index (Etype (P))),
6564 First (Expressions (N))))));
6565 Analyze_And_Resolve (N, Typ);
6566 return;
6567 end if;
6569 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
6570 -- function, then additional actuals must be passed.
6572 if Is_Build_In_Place_Function_Call (P) then
6573 Make_Build_In_Place_Call_In_Anonymous_Context (P);
6575 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
6576 -- containing build-in-place function calls whose returned object covers
6577 -- interface types.
6579 elsif Present (Unqual_BIP_Iface_Function_Call (P)) then
6580 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (P);
6581 end if;
6583 -- If the prefix is an access type, then we unconditionally rewrite if
6584 -- as an explicit dereference. This simplifies processing for several
6585 -- cases, including packed array cases and certain cases in which checks
6586 -- must be generated. We used to try to do this only when it was
6587 -- necessary, but it cleans up the code to do it all the time.
6589 if Is_Access_Type (T) then
6590 Insert_Explicit_Dereference (P);
6591 Analyze_And_Resolve (P, Designated_Type (T));
6592 Atp := Designated_Type (T);
6593 else
6594 Atp := T;
6595 end if;
6597 -- Generate index and validity checks
6599 Generate_Index_Checks (N);
6601 if Validity_Checks_On and then Validity_Check_Subscripts then
6602 Apply_Subscript_Validity_Checks (N);
6603 end if;
6605 -- If selecting from an array with atomic components, and atomic sync
6606 -- is not suppressed for this array type, set atomic sync flag.
6608 if (Has_Atomic_Components (Atp)
6609 and then not Atomic_Synchronization_Disabled (Atp))
6610 or else (Is_Atomic (Typ)
6611 and then not Atomic_Synchronization_Disabled (Typ))
6612 or else (Is_Entity_Name (P)
6613 and then Has_Atomic_Components (Entity (P))
6614 and then not Atomic_Synchronization_Disabled (Entity (P)))
6615 then
6616 Activate_Atomic_Synchronization (N);
6617 end if;
6619 -- All done if the prefix is not a packed array implemented specially
6621 if not (Is_Packed (Etype (Prefix (N)))
6622 and then Present (Packed_Array_Impl_Type (Etype (Prefix (N)))))
6623 then
6624 return;
6625 end if;
6627 -- For packed arrays that are not bit-packed (i.e. the case of an array
6628 -- with one or more index types with a non-contiguous enumeration type),
6629 -- we can always use the normal packed element get circuit.
6631 if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
6632 Expand_Packed_Element_Reference (N);
6633 return;
6634 end if;
6636 -- For a reference to a component of a bit packed array, we convert it
6637 -- to a reference to the corresponding Packed_Array_Impl_Type. We only
6638 -- want to do this for simple references, and not for:
6640 -- Left side of assignment, or prefix of left side of assignment, or
6641 -- prefix of the prefix, to handle packed arrays of packed arrays,
6642 -- This case is handled in Exp_Ch5.Expand_N_Assignment_Statement
6644 -- Renaming objects in renaming associations
6645 -- This case is handled when a use of the renamed variable occurs
6647 -- Actual parameters for a procedure call
6648 -- This case is handled in Exp_Ch6.Expand_Actuals
6650 -- The second expression in a 'Read attribute reference
6652 -- The prefix of an address or bit or size attribute reference
6654 -- The following circuit detects these exceptions. Note that we need to
6655 -- deal with implicit dereferences when climbing up the parent chain,
6656 -- with the additional difficulty that the type of parents may have yet
6657 -- to be resolved since prefixes are usually resolved first.
6659 declare
6660 Child : Node_Id := N;
6661 Parnt : Node_Id := Parent (N);
6663 begin
6664 loop
6665 if Nkind (Parnt) = N_Unchecked_Expression then
6666 null;
6668 elsif Nkind_In (Parnt, N_Object_Renaming_Declaration,
6669 N_Procedure_Call_Statement)
6670 or else (Nkind (Parnt) = N_Parameter_Association
6671 and then
6672 Nkind (Parent (Parnt)) = N_Procedure_Call_Statement)
6673 then
6674 return;
6676 elsif Nkind (Parnt) = N_Attribute_Reference
6677 and then Nam_In (Attribute_Name (Parnt), Name_Address,
6678 Name_Bit,
6679 Name_Size)
6680 and then Prefix (Parnt) = Child
6681 then
6682 return;
6684 elsif Nkind (Parnt) = N_Assignment_Statement
6685 and then Name (Parnt) = Child
6686 then
6687 return;
6689 -- If the expression is an index of an indexed component, it must
6690 -- be expanded regardless of context.
6692 elsif Nkind (Parnt) = N_Indexed_Component
6693 and then Child /= Prefix (Parnt)
6694 then
6695 Expand_Packed_Element_Reference (N);
6696 return;
6698 elsif Nkind (Parent (Parnt)) = N_Assignment_Statement
6699 and then Name (Parent (Parnt)) = Parnt
6700 then
6701 return;
6703 elsif Nkind (Parnt) = N_Attribute_Reference
6704 and then Attribute_Name (Parnt) = Name_Read
6705 and then Next (First (Expressions (Parnt))) = Child
6706 then
6707 return;
6709 elsif Nkind (Parnt) = N_Indexed_Component
6710 and then Prefix (Parnt) = Child
6711 then
6712 null;
6714 elsif Nkind (Parnt) = N_Selected_Component
6715 and then Prefix (Parnt) = Child
6716 and then not (Present (Etype (Selector_Name (Parnt)))
6717 and then
6718 Is_Access_Type (Etype (Selector_Name (Parnt))))
6719 then
6720 null;
6722 -- If the parent is a dereference, either implicit or explicit,
6723 -- then the packed reference needs to be expanded.
6725 else
6726 Expand_Packed_Element_Reference (N);
6727 return;
6728 end if;
6730 -- Keep looking up tree for unchecked expression, or if we are the
6731 -- prefix of a possible assignment left side.
6733 Child := Parnt;
6734 Parnt := Parent (Child);
6735 end loop;
6736 end;
6737 end Expand_N_Indexed_Component;
6739 ---------------------
6740 -- Expand_N_Not_In --
6741 ---------------------
6743 -- Replace a not in b by not (a in b) so that the expansions for (a in b)
6744 -- can be done. This avoids needing to duplicate this expansion code.
6746 procedure Expand_N_Not_In (N : Node_Id) is
6747 Loc : constant Source_Ptr := Sloc (N);
6748 Typ : constant Entity_Id := Etype (N);
6749 Cfs : constant Boolean := Comes_From_Source (N);
6751 begin
6752 Rewrite (N,
6753 Make_Op_Not (Loc,
6754 Right_Opnd =>
6755 Make_In (Loc,
6756 Left_Opnd => Left_Opnd (N),
6757 Right_Opnd => Right_Opnd (N))));
6759 -- If this is a set membership, preserve list of alternatives
6761 Set_Alternatives (Right_Opnd (N), Alternatives (Original_Node (N)));
6763 -- We want this to appear as coming from source if original does (see
6764 -- transformations in Expand_N_In).
6766 Set_Comes_From_Source (N, Cfs);
6767 Set_Comes_From_Source (Right_Opnd (N), Cfs);
6769 -- Now analyze transformed node
6771 Analyze_And_Resolve (N, Typ);
6772 end Expand_N_Not_In;
6774 -------------------
6775 -- Expand_N_Null --
6776 -------------------
6778 -- The only replacement required is for the case of a null of a type that
6779 -- is an access to protected subprogram, or a subtype thereof. We represent
6780 -- such access values as a record, and so we must replace the occurrence of
6781 -- null by the equivalent record (with a null address and a null pointer in
6782 -- it), so that the back end creates the proper value.
6784 procedure Expand_N_Null (N : Node_Id) is
6785 Loc : constant Source_Ptr := Sloc (N);
6786 Typ : constant Entity_Id := Base_Type (Etype (N));
6787 Agg : Node_Id;
6789 begin
6790 if Is_Access_Protected_Subprogram_Type (Typ) then
6791 Agg :=
6792 Make_Aggregate (Loc,
6793 Expressions => New_List (
6794 New_Occurrence_Of (RTE (RE_Null_Address), Loc),
6795 Make_Null (Loc)));
6797 Rewrite (N, Agg);
6798 Analyze_And_Resolve (N, Equivalent_Type (Typ));
6800 -- For subsequent semantic analysis, the node must retain its type.
6801 -- Gigi in any case replaces this type by the corresponding record
6802 -- type before processing the node.
6804 Set_Etype (N, Typ);
6805 end if;
6807 exception
6808 when RE_Not_Available =>
6809 return;
6810 end Expand_N_Null;
6812 ---------------------
6813 -- Expand_N_Op_Abs --
6814 ---------------------
6816 procedure Expand_N_Op_Abs (N : Node_Id) is
6817 Loc : constant Source_Ptr := Sloc (N);
6818 Expr : constant Node_Id := Right_Opnd (N);
6820 begin
6821 Unary_Op_Validity_Checks (N);
6823 -- Check for MINIMIZED/ELIMINATED overflow mode
6825 if Minimized_Eliminated_Overflow_Check (N) then
6826 Apply_Arithmetic_Overflow_Check (N);
6827 return;
6828 end if;
6830 -- Deal with software overflow checking
6832 if not Backend_Overflow_Checks_On_Target
6833 and then Is_Signed_Integer_Type (Etype (N))
6834 and then Do_Overflow_Check (N)
6835 then
6836 -- The only case to worry about is when the argument is equal to the
6837 -- largest negative number, so what we do is to insert the check:
6839 -- [constraint_error when Expr = typ'Base'First]
6841 -- with the usual Duplicate_Subexpr use coding for expr
6843 Insert_Action (N,
6844 Make_Raise_Constraint_Error (Loc,
6845 Condition =>
6846 Make_Op_Eq (Loc,
6847 Left_Opnd => Duplicate_Subexpr (Expr),
6848 Right_Opnd =>
6849 Make_Attribute_Reference (Loc,
6850 Prefix =>
6851 New_Occurrence_Of (Base_Type (Etype (Expr)), Loc),
6852 Attribute_Name => Name_First)),
6853 Reason => CE_Overflow_Check_Failed));
6854 end if;
6855 end Expand_N_Op_Abs;
6857 ---------------------
6858 -- Expand_N_Op_Add --
6859 ---------------------
6861 procedure Expand_N_Op_Add (N : Node_Id) is
6862 Typ : constant Entity_Id := Etype (N);
6864 begin
6865 Binary_Op_Validity_Checks (N);
6867 -- Check for MINIMIZED/ELIMINATED overflow mode
6869 if Minimized_Eliminated_Overflow_Check (N) then
6870 Apply_Arithmetic_Overflow_Check (N);
6871 return;
6872 end if;
6874 -- N + 0 = 0 + N = N for integer types
6876 if Is_Integer_Type (Typ) then
6877 if Compile_Time_Known_Value (Right_Opnd (N))
6878 and then Expr_Value (Right_Opnd (N)) = Uint_0
6879 then
6880 Rewrite (N, Left_Opnd (N));
6881 return;
6883 elsif Compile_Time_Known_Value (Left_Opnd (N))
6884 and then Expr_Value (Left_Opnd (N)) = Uint_0
6885 then
6886 Rewrite (N, Right_Opnd (N));
6887 return;
6888 end if;
6889 end if;
6891 -- Arithmetic overflow checks for signed integer/fixed point types
6893 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
6894 Apply_Arithmetic_Overflow_Check (N);
6895 return;
6896 end if;
6898 -- Overflow checks for floating-point if -gnateF mode active
6900 Check_Float_Op_Overflow (N);
6902 Expand_Nonbinary_Modular_Op (N);
6903 end Expand_N_Op_Add;
6905 ---------------------
6906 -- Expand_N_Op_And --
6907 ---------------------
6909 procedure Expand_N_Op_And (N : Node_Id) is
6910 Typ : constant Entity_Id := Etype (N);
6912 begin
6913 Binary_Op_Validity_Checks (N);
6915 if Is_Array_Type (Etype (N)) then
6916 Expand_Boolean_Operator (N);
6918 elsif Is_Boolean_Type (Etype (N)) then
6919 Adjust_Condition (Left_Opnd (N));
6920 Adjust_Condition (Right_Opnd (N));
6921 Set_Etype (N, Standard_Boolean);
6922 Adjust_Result_Type (N, Typ);
6924 elsif Is_Intrinsic_Subprogram (Entity (N)) then
6925 Expand_Intrinsic_Call (N, Entity (N));
6926 end if;
6928 Expand_Nonbinary_Modular_Op (N);
6929 end Expand_N_Op_And;
6931 ------------------------
6932 -- Expand_N_Op_Concat --
6933 ------------------------
6935 procedure Expand_N_Op_Concat (N : Node_Id) is
6936 Opnds : List_Id;
6937 -- List of operands to be concatenated
6939 Cnode : Node_Id;
6940 -- Node which is to be replaced by the result of concatenating the nodes
6941 -- in the list Opnds.
6943 begin
6944 -- Ensure validity of both operands
6946 Binary_Op_Validity_Checks (N);
6948 -- If we are the left operand of a concatenation higher up the tree,
6949 -- then do nothing for now, since we want to deal with a series of
6950 -- concatenations as a unit.
6952 if Nkind (Parent (N)) = N_Op_Concat
6953 and then N = Left_Opnd (Parent (N))
6954 then
6955 return;
6956 end if;
6958 -- We get here with a concatenation whose left operand may be a
6959 -- concatenation itself with a consistent type. We need to process
6960 -- these concatenation operands from left to right, which means
6961 -- from the deepest node in the tree to the highest node.
6963 Cnode := N;
6964 while Nkind (Left_Opnd (Cnode)) = N_Op_Concat loop
6965 Cnode := Left_Opnd (Cnode);
6966 end loop;
6968 -- Now Cnode is the deepest concatenation, and its parents are the
6969 -- concatenation nodes above, so now we process bottom up, doing the
6970 -- operands.
6972 -- The outer loop runs more than once if more than one concatenation
6973 -- type is involved.
6975 Outer : loop
6976 Opnds := New_List (Left_Opnd (Cnode), Right_Opnd (Cnode));
6977 Set_Parent (Opnds, N);
6979 -- The inner loop gathers concatenation operands
6981 Inner : while Cnode /= N
6982 and then Base_Type (Etype (Cnode)) =
6983 Base_Type (Etype (Parent (Cnode)))
6984 loop
6985 Cnode := Parent (Cnode);
6986 Append (Right_Opnd (Cnode), Opnds);
6987 end loop Inner;
6989 -- Note: The following code is a temporary workaround for N731-034
6990 -- and N829-028 and will be kept until the general issue of internal
6991 -- symbol serialization is addressed. The workaround is kept under a
6992 -- debug switch to avoid permiating into the general case.
6994 -- Wrap the node to concatenate into an expression actions node to
6995 -- keep it nicely packaged. This is useful in the case of an assert
6996 -- pragma with a concatenation where we want to be able to delete
6997 -- the concatenation and all its expansion stuff.
6999 if Debug_Flag_Dot_H then
7000 declare
7001 Cnod : constant Node_Id := New_Copy_Tree (Cnode);
7002 Typ : constant Entity_Id := Base_Type (Etype (Cnode));
7004 begin
7005 -- Note: use Rewrite rather than Replace here, so that for
7006 -- example Why_Not_Static can find the original concatenation
7007 -- node OK!
7009 Rewrite (Cnode,
7010 Make_Expression_With_Actions (Sloc (Cnode),
7011 Actions => New_List (Make_Null_Statement (Sloc (Cnode))),
7012 Expression => Cnod));
7014 Expand_Concatenate (Cnod, Opnds);
7015 Analyze_And_Resolve (Cnode, Typ);
7016 end;
7018 -- Default case
7020 else
7021 Expand_Concatenate (Cnode, Opnds);
7022 end if;
7024 exit Outer when Cnode = N;
7025 Cnode := Parent (Cnode);
7026 end loop Outer;
7027 end Expand_N_Op_Concat;
7029 ------------------------
7030 -- Expand_N_Op_Divide --
7031 ------------------------
7033 procedure Expand_N_Op_Divide (N : Node_Id) is
7034 Loc : constant Source_Ptr := Sloc (N);
7035 Lopnd : constant Node_Id := Left_Opnd (N);
7036 Ropnd : constant Node_Id := Right_Opnd (N);
7037 Ltyp : constant Entity_Id := Etype (Lopnd);
7038 Rtyp : constant Entity_Id := Etype (Ropnd);
7039 Typ : Entity_Id := Etype (N);
7040 Rknow : constant Boolean := Is_Integer_Type (Typ)
7041 and then
7042 Compile_Time_Known_Value (Ropnd);
7043 Rval : Uint;
7045 begin
7046 Binary_Op_Validity_Checks (N);
7048 -- Check for MINIMIZED/ELIMINATED overflow mode
7050 if Minimized_Eliminated_Overflow_Check (N) then
7051 Apply_Arithmetic_Overflow_Check (N);
7052 return;
7053 end if;
7055 -- Otherwise proceed with expansion of division
7057 if Rknow then
7058 Rval := Expr_Value (Ropnd);
7059 end if;
7061 -- N / 1 = N for integer types
7063 if Rknow and then Rval = Uint_1 then
7064 Rewrite (N, Lopnd);
7065 return;
7066 end if;
7068 -- Convert x / 2 ** y to Shift_Right (x, y). Note that the fact that
7069 -- Is_Power_Of_2_For_Shift is set means that we know that our left
7070 -- operand is an unsigned integer, as required for this to work.
7072 if Nkind (Ropnd) = N_Op_Expon
7073 and then Is_Power_Of_2_For_Shift (Ropnd)
7075 -- We cannot do this transformation in configurable run time mode if we
7076 -- have 64-bit integers and long shifts are not available.
7078 and then (Esize (Ltyp) <= 32 or else Support_Long_Shifts_On_Target)
7079 then
7080 Rewrite (N,
7081 Make_Op_Shift_Right (Loc,
7082 Left_Opnd => Lopnd,
7083 Right_Opnd =>
7084 Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
7085 Analyze_And_Resolve (N, Typ);
7086 return;
7087 end if;
7089 -- Do required fixup of universal fixed operation
7091 if Typ = Universal_Fixed then
7092 Fixup_Universal_Fixed_Operation (N);
7093 Typ := Etype (N);
7094 end if;
7096 -- Divisions with fixed-point results
7098 if Is_Fixed_Point_Type (Typ) then
7100 -- No special processing if Treat_Fixed_As_Integer is set, since
7101 -- from a semantic point of view such operations are simply integer
7102 -- operations and will be treated that way.
7104 if not Treat_Fixed_As_Integer (N) then
7105 if Is_Integer_Type (Rtyp) then
7106 Expand_Divide_Fixed_By_Integer_Giving_Fixed (N);
7107 else
7108 Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N);
7109 end if;
7110 end if;
7112 -- Deal with divide-by-zero check if back end cannot handle them
7113 -- and the flag is set indicating that we need such a check. Note
7114 -- that we don't need to bother here with the case of mixed-mode
7115 -- (Right operand an integer type), since these will be rewritten
7116 -- with conversions to a divide with a fixed-point right operand.
7118 if Nkind (N) = N_Op_Divide
7119 and then Do_Division_Check (N)
7120 and then not Backend_Divide_Checks_On_Target
7121 and then not Is_Integer_Type (Rtyp)
7122 then
7123 Set_Do_Division_Check (N, False);
7124 Insert_Action (N,
7125 Make_Raise_Constraint_Error (Loc,
7126 Condition =>
7127 Make_Op_Eq (Loc,
7128 Left_Opnd => Duplicate_Subexpr_Move_Checks (Ropnd),
7129 Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
7130 Reason => CE_Divide_By_Zero));
7131 end if;
7133 -- Other cases of division of fixed-point operands. Again we exclude the
7134 -- case where Treat_Fixed_As_Integer is set.
7136 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
7137 and then not Treat_Fixed_As_Integer (N)
7138 then
7139 if Is_Integer_Type (Typ) then
7140 Expand_Divide_Fixed_By_Fixed_Giving_Integer (N);
7141 else
7142 pragma Assert (Is_Floating_Point_Type (Typ));
7143 Expand_Divide_Fixed_By_Fixed_Giving_Float (N);
7144 end if;
7146 -- Mixed-mode operations can appear in a non-static universal context,
7147 -- in which case the integer argument must be converted explicitly.
7149 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
7150 Rewrite (Ropnd,
7151 Convert_To (Universal_Real, Relocate_Node (Ropnd)));
7153 Analyze_And_Resolve (Ropnd, Universal_Real);
7155 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
7156 Rewrite (Lopnd,
7157 Convert_To (Universal_Real, Relocate_Node (Lopnd)));
7159 Analyze_And_Resolve (Lopnd, Universal_Real);
7161 -- Non-fixed point cases, do integer zero divide and overflow checks
7163 elsif Is_Integer_Type (Typ) then
7164 Apply_Divide_Checks (N);
7165 end if;
7167 -- Overflow checks for floating-point if -gnateF mode active
7169 Check_Float_Op_Overflow (N);
7171 Expand_Nonbinary_Modular_Op (N);
7172 end Expand_N_Op_Divide;
7174 --------------------
7175 -- Expand_N_Op_Eq --
7176 --------------------
7178 procedure Expand_N_Op_Eq (N : Node_Id) is
7179 Loc : constant Source_Ptr := Sloc (N);
7180 Typ : constant Entity_Id := Etype (N);
7181 Lhs : constant Node_Id := Left_Opnd (N);
7182 Rhs : constant Node_Id := Right_Opnd (N);
7183 Bodies : constant List_Id := New_List;
7184 A_Typ : constant Entity_Id := Etype (Lhs);
7186 Typl : Entity_Id := A_Typ;
7187 Op_Name : Entity_Id;
7188 Prim : Elmt_Id;
7190 procedure Build_Equality_Call (Eq : Entity_Id);
7191 -- If a constructed equality exists for the type or for its parent,
7192 -- build and analyze call, adding conversions if the operation is
7193 -- inherited.
7195 function Has_Unconstrained_UU_Component (Typ : Node_Id) return Boolean;
7196 -- Determines whether a type has a subcomponent of an unconstrained
7197 -- Unchecked_Union subtype. Typ is a record type.
7199 -------------------------
7200 -- Build_Equality_Call --
7201 -------------------------
7203 procedure Build_Equality_Call (Eq : Entity_Id) is
7204 Op_Type : constant Entity_Id := Etype (First_Formal (Eq));
7205 L_Exp : Node_Id := Relocate_Node (Lhs);
7206 R_Exp : Node_Id := Relocate_Node (Rhs);
7208 begin
7209 -- Adjust operands if necessary to comparison type
7211 if Base_Type (Op_Type) /= Base_Type (A_Typ)
7212 and then not Is_Class_Wide_Type (A_Typ)
7213 then
7214 L_Exp := OK_Convert_To (Op_Type, L_Exp);
7215 R_Exp := OK_Convert_To (Op_Type, R_Exp);
7216 end if;
7218 -- If we have an Unchecked_Union, we need to add the inferred
7219 -- discriminant values as actuals in the function call. At this
7220 -- point, the expansion has determined that both operands have
7221 -- inferable discriminants.
7223 if Is_Unchecked_Union (Op_Type) then
7224 declare
7225 Lhs_Type : constant Node_Id := Etype (L_Exp);
7226 Rhs_Type : constant Node_Id := Etype (R_Exp);
7228 Lhs_Discr_Vals : Elist_Id;
7229 -- List of inferred discriminant values for left operand.
7231 Rhs_Discr_Vals : Elist_Id;
7232 -- List of inferred discriminant values for right operand.
7234 Discr : Entity_Id;
7236 begin
7237 Lhs_Discr_Vals := New_Elmt_List;
7238 Rhs_Discr_Vals := New_Elmt_List;
7240 -- Per-object constrained selected components require special
7241 -- attention. If the enclosing scope of the component is an
7242 -- Unchecked_Union, we cannot reference its discriminants
7243 -- directly. This is why we use the extra parameters of the
7244 -- equality function of the enclosing Unchecked_Union.
7246 -- type UU_Type (Discr : Integer := 0) is
7247 -- . . .
7248 -- end record;
7249 -- pragma Unchecked_Union (UU_Type);
7251 -- 1. Unchecked_Union enclosing record:
7253 -- type Enclosing_UU_Type (Discr : Integer := 0) is record
7254 -- . . .
7255 -- Comp : UU_Type (Discr);
7256 -- . . .
7257 -- end Enclosing_UU_Type;
7258 -- pragma Unchecked_Union (Enclosing_UU_Type);
7260 -- Obj1 : Enclosing_UU_Type;
7261 -- Obj2 : Enclosing_UU_Type (1);
7263 -- [. . .] Obj1 = Obj2 [. . .]
7265 -- Generated code:
7267 -- if not (uu_typeEQ (obj1.comp, obj2.comp, a, b)) then
7269 -- A and B are the formal parameters of the equality function
7270 -- of Enclosing_UU_Type. The function always has two extra
7271 -- formals to capture the inferred discriminant values for
7272 -- each discriminant of the type.
7274 -- 2. Non-Unchecked_Union enclosing record:
7276 -- type
7277 -- Enclosing_Non_UU_Type (Discr : Integer := 0)
7278 -- is record
7279 -- . . .
7280 -- Comp : UU_Type (Discr);
7281 -- . . .
7282 -- end Enclosing_Non_UU_Type;
7284 -- Obj1 : Enclosing_Non_UU_Type;
7285 -- Obj2 : Enclosing_Non_UU_Type (1);
7287 -- ... Obj1 = Obj2 ...
7289 -- Generated code:
7291 -- if not (uu_typeEQ (obj1.comp, obj2.comp,
7292 -- obj1.discr, obj2.discr)) then
7294 -- In this case we can directly reference the discriminants of
7295 -- the enclosing record.
7297 -- Process left operand of equality
7299 if Nkind (Lhs) = N_Selected_Component
7300 and then
7301 Has_Per_Object_Constraint (Entity (Selector_Name (Lhs)))
7302 then
7303 -- If enclosing record is an Unchecked_Union, use formals
7304 -- corresponding to each discriminant. The name of the
7305 -- formal is that of the discriminant, with added suffix,
7306 -- see Exp_Ch3.Build_Record_Equality for details.
7308 if Is_Unchecked_Union (Scope (Entity (Selector_Name (Lhs))))
7309 then
7310 Discr :=
7311 First_Discriminant
7312 (Scope (Entity (Selector_Name (Lhs))));
7313 while Present (Discr) loop
7314 Append_Elmt
7315 (Make_Identifier (Loc,
7316 Chars => New_External_Name (Chars (Discr), 'A')),
7317 To => Lhs_Discr_Vals);
7318 Next_Discriminant (Discr);
7319 end loop;
7321 -- If enclosing record is of a non-Unchecked_Union type, it
7322 -- is possible to reference its discriminants directly.
7324 else
7325 Discr := First_Discriminant (Lhs_Type);
7326 while Present (Discr) loop
7327 Append_Elmt
7328 (Make_Selected_Component (Loc,
7329 Prefix => Prefix (Lhs),
7330 Selector_Name =>
7331 New_Copy
7332 (Get_Discriminant_Value (Discr,
7333 Lhs_Type,
7334 Stored_Constraint (Lhs_Type)))),
7335 To => Lhs_Discr_Vals);
7336 Next_Discriminant (Discr);
7337 end loop;
7338 end if;
7340 -- Otherwise operand is on object with a constrained type.
7341 -- Infer the discriminant values from the constraint.
7343 else
7345 Discr := First_Discriminant (Lhs_Type);
7346 while Present (Discr) loop
7347 Append_Elmt
7348 (New_Copy
7349 (Get_Discriminant_Value (Discr,
7350 Lhs_Type,
7351 Stored_Constraint (Lhs_Type))),
7352 To => Lhs_Discr_Vals);
7353 Next_Discriminant (Discr);
7354 end loop;
7355 end if;
7357 -- Similar processing for right operand of equality
7359 if Nkind (Rhs) = N_Selected_Component
7360 and then
7361 Has_Per_Object_Constraint (Entity (Selector_Name (Rhs)))
7362 then
7363 if Is_Unchecked_Union
7364 (Scope (Entity (Selector_Name (Rhs))))
7365 then
7366 Discr :=
7367 First_Discriminant
7368 (Scope (Entity (Selector_Name (Rhs))));
7369 while Present (Discr) loop
7370 Append_Elmt
7371 (Make_Identifier (Loc,
7372 Chars => New_External_Name (Chars (Discr), 'B')),
7373 To => Rhs_Discr_Vals);
7374 Next_Discriminant (Discr);
7375 end loop;
7377 else
7378 Discr := First_Discriminant (Rhs_Type);
7379 while Present (Discr) loop
7380 Append_Elmt
7381 (Make_Selected_Component (Loc,
7382 Prefix => Prefix (Rhs),
7383 Selector_Name =>
7384 New_Copy (Get_Discriminant_Value
7385 (Discr,
7386 Rhs_Type,
7387 Stored_Constraint (Rhs_Type)))),
7388 To => Rhs_Discr_Vals);
7389 Next_Discriminant (Discr);
7390 end loop;
7391 end if;
7393 else
7394 Discr := First_Discriminant (Rhs_Type);
7395 while Present (Discr) loop
7396 Append_Elmt
7397 (New_Copy (Get_Discriminant_Value
7398 (Discr,
7399 Rhs_Type,
7400 Stored_Constraint (Rhs_Type))),
7401 To => Rhs_Discr_Vals);
7402 Next_Discriminant (Discr);
7403 end loop;
7404 end if;
7406 -- Now merge the list of discriminant values so that values
7407 -- of corresponding discriminants are adjacent.
7409 declare
7410 Params : List_Id;
7411 L_Elmt : Elmt_Id;
7412 R_Elmt : Elmt_Id;
7414 begin
7415 Params := New_List (L_Exp, R_Exp);
7416 L_Elmt := First_Elmt (Lhs_Discr_Vals);
7417 R_Elmt := First_Elmt (Rhs_Discr_Vals);
7418 while Present (L_Elmt) loop
7419 Append_To (Params, Node (L_Elmt));
7420 Append_To (Params, Node (R_Elmt));
7421 Next_Elmt (L_Elmt);
7422 Next_Elmt (R_Elmt);
7423 end loop;
7425 Rewrite (N,
7426 Make_Function_Call (Loc,
7427 Name => New_Occurrence_Of (Eq, Loc),
7428 Parameter_Associations => Params));
7429 end;
7430 end;
7432 -- Normal case, not an unchecked union
7434 else
7435 Rewrite (N,
7436 Make_Function_Call (Loc,
7437 Name => New_Occurrence_Of (Eq, Loc),
7438 Parameter_Associations => New_List (L_Exp, R_Exp)));
7439 end if;
7441 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7442 end Build_Equality_Call;
7444 ------------------------------------
7445 -- Has_Unconstrained_UU_Component --
7446 ------------------------------------
7448 function Has_Unconstrained_UU_Component
7449 (Typ : Node_Id) return Boolean
7451 Tdef : constant Node_Id :=
7452 Type_Definition (Declaration_Node (Base_Type (Typ)));
7453 Clist : Node_Id;
7454 Vpart : Node_Id;
7456 function Component_Is_Unconstrained_UU
7457 (Comp : Node_Id) return Boolean;
7458 -- Determines whether the subtype of the component is an
7459 -- unconstrained Unchecked_Union.
7461 function Variant_Is_Unconstrained_UU
7462 (Variant : Node_Id) return Boolean;
7463 -- Determines whether a component of the variant has an unconstrained
7464 -- Unchecked_Union subtype.
7466 -----------------------------------
7467 -- Component_Is_Unconstrained_UU --
7468 -----------------------------------
7470 function Component_Is_Unconstrained_UU
7471 (Comp : Node_Id) return Boolean
7473 begin
7474 if Nkind (Comp) /= N_Component_Declaration then
7475 return False;
7476 end if;
7478 declare
7479 Sindic : constant Node_Id :=
7480 Subtype_Indication (Component_Definition (Comp));
7482 begin
7483 -- Unconstrained nominal type. In the case of a constraint
7484 -- present, the node kind would have been N_Subtype_Indication.
7486 if Nkind (Sindic) = N_Identifier then
7487 return Is_Unchecked_Union (Base_Type (Etype (Sindic)));
7488 end if;
7490 return False;
7491 end;
7492 end Component_Is_Unconstrained_UU;
7494 ---------------------------------
7495 -- Variant_Is_Unconstrained_UU --
7496 ---------------------------------
7498 function Variant_Is_Unconstrained_UU
7499 (Variant : Node_Id) return Boolean
7501 Clist : constant Node_Id := Component_List (Variant);
7503 begin
7504 if Is_Empty_List (Component_Items (Clist)) then
7505 return False;
7506 end if;
7508 -- We only need to test one component
7510 declare
7511 Comp : Node_Id := First (Component_Items (Clist));
7513 begin
7514 while Present (Comp) loop
7515 if Component_Is_Unconstrained_UU (Comp) then
7516 return True;
7517 end if;
7519 Next (Comp);
7520 end loop;
7521 end;
7523 -- None of the components withing the variant were of
7524 -- unconstrained Unchecked_Union type.
7526 return False;
7527 end Variant_Is_Unconstrained_UU;
7529 -- Start of processing for Has_Unconstrained_UU_Component
7531 begin
7532 if Null_Present (Tdef) then
7533 return False;
7534 end if;
7536 Clist := Component_List (Tdef);
7537 Vpart := Variant_Part (Clist);
7539 -- Inspect available components
7541 if Present (Component_Items (Clist)) then
7542 declare
7543 Comp : Node_Id := First (Component_Items (Clist));
7545 begin
7546 while Present (Comp) loop
7548 -- One component is sufficient
7550 if Component_Is_Unconstrained_UU (Comp) then
7551 return True;
7552 end if;
7554 Next (Comp);
7555 end loop;
7556 end;
7557 end if;
7559 -- Inspect available components withing variants
7561 if Present (Vpart) then
7562 declare
7563 Variant : Node_Id := First (Variants (Vpart));
7565 begin
7566 while Present (Variant) loop
7568 -- One component within a variant is sufficient
7570 if Variant_Is_Unconstrained_UU (Variant) then
7571 return True;
7572 end if;
7574 Next (Variant);
7575 end loop;
7576 end;
7577 end if;
7579 -- Neither the available components, nor the components inside the
7580 -- variant parts were of an unconstrained Unchecked_Union subtype.
7582 return False;
7583 end Has_Unconstrained_UU_Component;
7585 -- Start of processing for Expand_N_Op_Eq
7587 begin
7588 Binary_Op_Validity_Checks (N);
7590 -- Deal with private types
7592 if Ekind (Typl) = E_Private_Type then
7593 Typl := Underlying_Type (Typl);
7594 elsif Ekind (Typl) = E_Private_Subtype then
7595 Typl := Underlying_Type (Base_Type (Typl));
7596 else
7597 null;
7598 end if;
7600 -- It may happen in error situations that the underlying type is not
7601 -- set. The error will be detected later, here we just defend the
7602 -- expander code.
7604 if No (Typl) then
7605 return;
7606 end if;
7608 -- Now get the implementation base type (note that plain Base_Type here
7609 -- might lead us back to the private type, which is not what we want!)
7611 Typl := Implementation_Base_Type (Typl);
7613 -- Equality between variant records results in a call to a routine
7614 -- that has conditional tests of the discriminant value(s), and hence
7615 -- violates the No_Implicit_Conditionals restriction.
7617 if Has_Variant_Part (Typl) then
7618 declare
7619 Msg : Boolean;
7621 begin
7622 Check_Restriction (Msg, No_Implicit_Conditionals, N);
7624 if Msg then
7625 Error_Msg_N
7626 ("\comparison of variant records tests discriminants", N);
7627 return;
7628 end if;
7629 end;
7630 end if;
7632 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7633 -- means we no longer have a comparison operation, we are all done.
7635 Expand_Compare_Minimize_Eliminate_Overflow (N);
7637 if Nkind (N) /= N_Op_Eq then
7638 return;
7639 end if;
7641 -- Boolean types (requiring handling of non-standard case)
7643 if Is_Boolean_Type (Typl) then
7644 Adjust_Condition (Left_Opnd (N));
7645 Adjust_Condition (Right_Opnd (N));
7646 Set_Etype (N, Standard_Boolean);
7647 Adjust_Result_Type (N, Typ);
7649 -- Array types
7651 elsif Is_Array_Type (Typl) then
7653 -- If we are doing full validity checking, and it is possible for the
7654 -- array elements to be invalid then expand out array comparisons to
7655 -- make sure that we check the array elements.
7657 if Validity_Check_Operands
7658 and then not Is_Known_Valid (Component_Type (Typl))
7659 then
7660 declare
7661 Save_Force_Validity_Checks : constant Boolean :=
7662 Force_Validity_Checks;
7663 begin
7664 Force_Validity_Checks := True;
7665 Rewrite (N,
7666 Expand_Array_Equality
7668 Relocate_Node (Lhs),
7669 Relocate_Node (Rhs),
7670 Bodies,
7671 Typl));
7672 Insert_Actions (N, Bodies);
7673 Analyze_And_Resolve (N, Standard_Boolean);
7674 Force_Validity_Checks := Save_Force_Validity_Checks;
7675 end;
7677 -- Packed case where both operands are known aligned
7679 elsif Is_Bit_Packed_Array (Typl)
7680 and then not Is_Possibly_Unaligned_Object (Lhs)
7681 and then not Is_Possibly_Unaligned_Object (Rhs)
7682 then
7683 Expand_Packed_Eq (N);
7685 -- Where the component type is elementary we can use a block bit
7686 -- comparison (if supported on the target) exception in the case
7687 -- of floating-point (negative zero issues require element by
7688 -- element comparison), and atomic/VFA types (where we must be sure
7689 -- to load elements independently) and possibly unaligned arrays.
7691 elsif Is_Elementary_Type (Component_Type (Typl))
7692 and then not Is_Floating_Point_Type (Component_Type (Typl))
7693 and then not Is_Atomic_Or_VFA (Component_Type (Typl))
7694 and then not Is_Possibly_Unaligned_Object (Lhs)
7695 and then not Is_Possibly_Unaligned_Object (Rhs)
7696 and then Support_Composite_Compare_On_Target
7697 then
7698 null;
7700 -- For composite and floating-point cases, expand equality loop to
7701 -- make sure of using proper comparisons for tagged types, and
7702 -- correctly handling the floating-point case.
7704 else
7705 Rewrite (N,
7706 Expand_Array_Equality
7708 Relocate_Node (Lhs),
7709 Relocate_Node (Rhs),
7710 Bodies,
7711 Typl));
7712 Insert_Actions (N, Bodies, Suppress => All_Checks);
7713 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7714 end if;
7716 -- Record Types
7718 elsif Is_Record_Type (Typl) then
7720 -- For tagged types, use the primitive "="
7722 if Is_Tagged_Type (Typl) then
7724 -- No need to do anything else compiling under restriction
7725 -- No_Dispatching_Calls. During the semantic analysis we
7726 -- already notified such violation.
7728 if Restriction_Active (No_Dispatching_Calls) then
7729 return;
7730 end if;
7732 -- If this is derived from an untagged private type completed with
7733 -- a tagged type, it does not have a full view, so we use the
7734 -- primitive operations of the private type. This check should no
7735 -- longer be necessary when these types get their full views???
7737 if Is_Private_Type (A_Typ)
7738 and then not Is_Tagged_Type (A_Typ)
7739 and then Is_Derived_Type (A_Typ)
7740 and then No (Full_View (A_Typ))
7741 then
7742 -- Search for equality operation, checking that the operands
7743 -- have the same type. Note that we must find a matching entry,
7744 -- or something is very wrong.
7746 Prim := First_Elmt (Collect_Primitive_Operations (A_Typ));
7748 while Present (Prim) loop
7749 exit when Chars (Node (Prim)) = Name_Op_Eq
7750 and then Etype (First_Formal (Node (Prim))) =
7751 Etype (Next_Formal (First_Formal (Node (Prim))))
7752 and then
7753 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7755 Next_Elmt (Prim);
7756 end loop;
7758 pragma Assert (Present (Prim));
7759 Op_Name := Node (Prim);
7761 -- Find the type's predefined equality or an overriding
7762 -- user-defined equality. The reason for not simply calling
7763 -- Find_Prim_Op here is that there may be a user-defined
7764 -- overloaded equality op that precedes the equality that we
7765 -- want, so we have to explicitly search (e.g., there could be
7766 -- an equality with two different parameter types).
7768 else
7769 if Is_Class_Wide_Type (Typl) then
7770 Typl := Find_Specific_Type (Typl);
7771 end if;
7773 Prim := First_Elmt (Primitive_Operations (Typl));
7774 while Present (Prim) loop
7775 exit when Chars (Node (Prim)) = Name_Op_Eq
7776 and then Etype (First_Formal (Node (Prim))) =
7777 Etype (Next_Formal (First_Formal (Node (Prim))))
7778 and then
7779 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7781 Next_Elmt (Prim);
7782 end loop;
7784 pragma Assert (Present (Prim));
7785 Op_Name := Node (Prim);
7786 end if;
7788 Build_Equality_Call (Op_Name);
7790 -- Ada 2005 (AI-216): Program_Error is raised when evaluating the
7791 -- predefined equality operator for a type which has a subcomponent
7792 -- of an Unchecked_Union type whose nominal subtype is unconstrained.
7794 elsif Has_Unconstrained_UU_Component (Typl) then
7795 Insert_Action (N,
7796 Make_Raise_Program_Error (Loc,
7797 Reason => PE_Unchecked_Union_Restriction));
7799 -- Prevent Gigi from generating incorrect code by rewriting the
7800 -- equality as a standard False. (is this documented somewhere???)
7802 Rewrite (N,
7803 New_Occurrence_Of (Standard_False, Loc));
7805 elsif Is_Unchecked_Union (Typl) then
7807 -- If we can infer the discriminants of the operands, we make a
7808 -- call to the TSS equality function.
7810 if Has_Inferable_Discriminants (Lhs)
7811 and then
7812 Has_Inferable_Discriminants (Rhs)
7813 then
7814 Build_Equality_Call
7815 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7817 else
7818 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
7819 -- the predefined equality operator for an Unchecked_Union type
7820 -- if either of the operands lack inferable discriminants.
7822 Insert_Action (N,
7823 Make_Raise_Program_Error (Loc,
7824 Reason => PE_Unchecked_Union_Restriction));
7826 -- Emit a warning on source equalities only, otherwise the
7827 -- message may appear out of place due to internal use. The
7828 -- warning is unconditional because it is required by the
7829 -- language.
7831 if Comes_From_Source (N) then
7832 Error_Msg_N
7833 ("Unchecked_Union discriminants cannot be determined??",
7835 Error_Msg_N
7836 ("\Program_Error will be raised for equality operation??",
7838 end if;
7840 -- Prevent Gigi from generating incorrect code by rewriting
7841 -- the equality as a standard False (documented where???).
7843 Rewrite (N,
7844 New_Occurrence_Of (Standard_False, Loc));
7845 end if;
7847 -- If a type support function is present (for complex cases), use it
7849 elsif Present (TSS (Root_Type (Typl), TSS_Composite_Equality)) then
7850 Build_Equality_Call
7851 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7853 -- When comparing two Bounded_Strings, use the primitive equality of
7854 -- the root Super_String type.
7856 elsif Is_Bounded_String (Typl) then
7857 Prim :=
7858 First_Elmt (Collect_Primitive_Operations (Root_Type (Typl)));
7860 while Present (Prim) loop
7861 exit when Chars (Node (Prim)) = Name_Op_Eq
7862 and then Etype (First_Formal (Node (Prim))) =
7863 Etype (Next_Formal (First_Formal (Node (Prim))))
7864 and then Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7866 Next_Elmt (Prim);
7867 end loop;
7869 -- A Super_String type should always have a primitive equality
7871 pragma Assert (Present (Prim));
7872 Build_Equality_Call (Node (Prim));
7874 -- Otherwise expand the component by component equality. Note that
7875 -- we never use block-bit comparisons for records, because of the
7876 -- problems with gaps. The back end will often be able to recombine
7877 -- the separate comparisons that we generate here.
7879 else
7880 Remove_Side_Effects (Lhs);
7881 Remove_Side_Effects (Rhs);
7882 Rewrite (N,
7883 Expand_Record_Equality (N, Typl, Lhs, Rhs, Bodies));
7885 Insert_Actions (N, Bodies, Suppress => All_Checks);
7886 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7887 end if;
7888 end if;
7890 -- Test if result is known at compile time
7892 Rewrite_Comparison (N);
7894 -- Special optimization of length comparison
7896 Optimize_Length_Comparison (N);
7898 -- One more special case: if we have a comparison of X'Result = expr
7899 -- in floating-point, then if not already there, change expr to be
7900 -- f'Machine (expr) to eliminate surprise from extra precision.
7902 if Is_Floating_Point_Type (Typl)
7903 and then Nkind (Original_Node (Lhs)) = N_Attribute_Reference
7904 and then Attribute_Name (Original_Node (Lhs)) = Name_Result
7905 then
7906 -- Stick in the Typ'Machine call if not already there
7908 if Nkind (Rhs) /= N_Attribute_Reference
7909 or else Attribute_Name (Rhs) /= Name_Machine
7910 then
7911 Rewrite (Rhs,
7912 Make_Attribute_Reference (Loc,
7913 Prefix => New_Occurrence_Of (Typl, Loc),
7914 Attribute_Name => Name_Machine,
7915 Expressions => New_List (Relocate_Node (Rhs))));
7916 Analyze_And_Resolve (Rhs, Typl);
7917 end if;
7918 end if;
7919 end Expand_N_Op_Eq;
7921 -----------------------
7922 -- Expand_N_Op_Expon --
7923 -----------------------
7925 procedure Expand_N_Op_Expon (N : Node_Id) is
7926 Loc : constant Source_Ptr := Sloc (N);
7927 Ovflo : constant Boolean := Do_Overflow_Check (N);
7928 Typ : constant Entity_Id := Etype (N);
7929 Rtyp : constant Entity_Id := Root_Type (Typ);
7931 Bastyp : Entity_Id;
7933 function Wrap_MA (Exp : Node_Id) return Node_Id;
7934 -- Given an expression Exp, if the root type is Float or Long_Float,
7935 -- then wrap the expression in a call of Bastyp'Machine, to stop any
7936 -- extra precision. This is done to ensure that X**A = X**B when A is
7937 -- a static constant and B is a variable with the same value. For any
7938 -- other type, the node Exp is returned unchanged.
7940 -------------
7941 -- Wrap_MA --
7942 -------------
7944 function Wrap_MA (Exp : Node_Id) return Node_Id is
7945 Loc : constant Source_Ptr := Sloc (Exp);
7947 begin
7948 if Rtyp = Standard_Float or else Rtyp = Standard_Long_Float then
7949 return
7950 Make_Attribute_Reference (Loc,
7951 Attribute_Name => Name_Machine,
7952 Prefix => New_Occurrence_Of (Bastyp, Loc),
7953 Expressions => New_List (Relocate_Node (Exp)));
7954 else
7955 return Exp;
7956 end if;
7957 end Wrap_MA;
7959 -- Local variables
7961 Base : Node_Id;
7962 Ent : Entity_Id;
7963 Etyp : Entity_Id;
7964 Exp : Node_Id;
7965 Exptyp : Entity_Id;
7966 Expv : Uint;
7967 Rent : RE_Id;
7968 Temp : Node_Id;
7969 Xnode : Node_Id;
7971 -- Start of processing for Expand_N_Op_Expon
7973 begin
7974 Binary_Op_Validity_Checks (N);
7976 -- CodePeer wants to see the unexpanded N_Op_Expon node
7978 if CodePeer_Mode then
7979 return;
7980 end if;
7982 -- Relocation of left and right operands must be done after performing
7983 -- the validity checks since the generation of validation checks may
7984 -- remove side effects.
7986 Base := Relocate_Node (Left_Opnd (N));
7987 Bastyp := Etype (Base);
7988 Exp := Relocate_Node (Right_Opnd (N));
7989 Exptyp := Etype (Exp);
7991 -- If either operand is of a private type, then we have the use of an
7992 -- intrinsic operator, and we get rid of the privateness, by using root
7993 -- types of underlying types for the actual operation. Otherwise the
7994 -- private types will cause trouble if we expand multiplications or
7995 -- shifts etc. We also do this transformation if the result type is
7996 -- different from the base type.
7998 if Is_Private_Type (Etype (Base))
7999 or else Is_Private_Type (Typ)
8000 or else Is_Private_Type (Exptyp)
8001 or else Rtyp /= Root_Type (Bastyp)
8002 then
8003 declare
8004 Bt : constant Entity_Id := Root_Type (Underlying_Type (Bastyp));
8005 Et : constant Entity_Id := Root_Type (Underlying_Type (Exptyp));
8006 begin
8007 Rewrite (N,
8008 Unchecked_Convert_To (Typ,
8009 Make_Op_Expon (Loc,
8010 Left_Opnd => Unchecked_Convert_To (Bt, Base),
8011 Right_Opnd => Unchecked_Convert_To (Et, Exp))));
8012 Analyze_And_Resolve (N, Typ);
8013 return;
8014 end;
8015 end if;
8017 -- Check for MINIMIZED/ELIMINATED overflow mode
8019 if Minimized_Eliminated_Overflow_Check (N) then
8020 Apply_Arithmetic_Overflow_Check (N);
8021 return;
8022 end if;
8024 -- Test for case of known right argument where we can replace the
8025 -- exponentiation by an equivalent expression using multiplication.
8027 -- Note: use CRT_Safe version of Compile_Time_Known_Value because in
8028 -- configurable run-time mode, we may not have the exponentiation
8029 -- routine available, and we don't want the legality of the program
8030 -- to depend on how clever the compiler is in knowing values.
8032 if CRT_Safe_Compile_Time_Known_Value (Exp) then
8033 Expv := Expr_Value (Exp);
8035 -- We only fold small non-negative exponents. You might think we
8036 -- could fold small negative exponents for the real case, but we
8037 -- can't because we are required to raise Constraint_Error for
8038 -- the case of 0.0 ** (negative) even if Machine_Overflows = False.
8039 -- See ACVC test C4A012B, and it is not worth generating the test.
8041 -- For small negative exponents, we return the reciprocal of
8042 -- the folding of the exponentiation for the opposite (positive)
8043 -- exponent, as required by Ada RM 4.5.6(11/3).
8045 if abs Expv <= 4 then
8047 -- X ** 0 = 1 (or 1.0)
8049 if Expv = 0 then
8051 -- Call Remove_Side_Effects to ensure that any side effects
8052 -- in the ignored left operand (in particular function calls
8053 -- to user defined functions) are properly executed.
8055 Remove_Side_Effects (Base);
8057 if Ekind (Typ) in Integer_Kind then
8058 Xnode := Make_Integer_Literal (Loc, Intval => 1);
8059 else
8060 Xnode := Make_Real_Literal (Loc, Ureal_1);
8061 end if;
8063 -- X ** 1 = X
8065 elsif Expv = 1 then
8066 Xnode := Base;
8068 -- X ** 2 = X * X
8070 elsif Expv = 2 then
8071 Xnode :=
8072 Wrap_MA (
8073 Make_Op_Multiply (Loc,
8074 Left_Opnd => Duplicate_Subexpr (Base),
8075 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8077 -- X ** 3 = X * X * X
8079 elsif Expv = 3 then
8080 Xnode :=
8081 Wrap_MA (
8082 Make_Op_Multiply (Loc,
8083 Left_Opnd =>
8084 Make_Op_Multiply (Loc,
8085 Left_Opnd => Duplicate_Subexpr (Base),
8086 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)),
8087 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8089 -- X ** 4 ->
8091 -- do
8092 -- En : constant base'type := base * base;
8093 -- in
8094 -- En * En
8096 elsif Expv = 4 then
8097 Temp := Make_Temporary (Loc, 'E', Base);
8099 Xnode :=
8100 Make_Expression_With_Actions (Loc,
8101 Actions => New_List (
8102 Make_Object_Declaration (Loc,
8103 Defining_Identifier => Temp,
8104 Constant_Present => True,
8105 Object_Definition => New_Occurrence_Of (Typ, Loc),
8106 Expression =>
8107 Wrap_MA (
8108 Make_Op_Multiply (Loc,
8109 Left_Opnd =>
8110 Duplicate_Subexpr (Base),
8111 Right_Opnd =>
8112 Duplicate_Subexpr_No_Checks (Base))))),
8114 Expression =>
8115 Wrap_MA (
8116 Make_Op_Multiply (Loc,
8117 Left_Opnd => New_Occurrence_Of (Temp, Loc),
8118 Right_Opnd => New_Occurrence_Of (Temp, Loc))));
8120 -- X ** N = 1.0 / X ** (-N)
8121 -- N in -4 .. -1
8123 else
8124 pragma Assert
8125 (Expv = -1 or Expv = -2 or Expv = -3 or Expv = -4);
8127 Xnode :=
8128 Make_Op_Divide (Loc,
8129 Left_Opnd =>
8130 Make_Float_Literal (Loc,
8131 Radix => Uint_1,
8132 Significand => Uint_1,
8133 Exponent => Uint_0),
8134 Right_Opnd =>
8135 Make_Op_Expon (Loc,
8136 Left_Opnd => Duplicate_Subexpr (Base),
8137 Right_Opnd =>
8138 Make_Integer_Literal (Loc,
8139 Intval => -Expv)));
8140 end if;
8142 Rewrite (N, Xnode);
8143 Analyze_And_Resolve (N, Typ);
8144 return;
8145 end if;
8146 end if;
8148 -- Deal with optimizing 2 ** expression to shift where possible
8150 -- Note: we used to check that Exptyp was an unsigned type. But that is
8151 -- an unnecessary check, since if Exp is negative, we have a run-time
8152 -- error that is either caught (so we get the right result) or we have
8153 -- suppressed the check, in which case the code is erroneous anyway.
8155 if Is_Integer_Type (Rtyp)
8157 -- The base value must be "safe compile-time known", and exactly 2
8159 and then Nkind (Base) = N_Integer_Literal
8160 and then CRT_Safe_Compile_Time_Known_Value (Base)
8161 and then Expr_Value (Base) = Uint_2
8163 -- We only handle cases where the right type is a integer
8165 and then Is_Integer_Type (Root_Type (Exptyp))
8166 and then Esize (Root_Type (Exptyp)) <= Esize (Standard_Integer)
8168 -- This transformation is not applicable for a modular type with a
8169 -- nonbinary modulus because we do not handle modular reduction in
8170 -- a correct manner if we attempt this transformation in this case.
8172 and then not Non_Binary_Modulus (Typ)
8173 then
8174 -- Handle the cases where our parent is a division or multiplication
8175 -- specially. In these cases we can convert to using a shift at the
8176 -- parent level if we are not doing overflow checking, since it is
8177 -- too tricky to combine the overflow check at the parent level.
8179 if not Ovflo
8180 and then Nkind_In (Parent (N), N_Op_Divide, N_Op_Multiply)
8181 then
8182 declare
8183 P : constant Node_Id := Parent (N);
8184 L : constant Node_Id := Left_Opnd (P);
8185 R : constant Node_Id := Right_Opnd (P);
8187 begin
8188 if (Nkind (P) = N_Op_Multiply
8189 and then
8190 ((Is_Integer_Type (Etype (L)) and then R = N)
8191 or else
8192 (Is_Integer_Type (Etype (R)) and then L = N))
8193 and then not Do_Overflow_Check (P))
8195 or else
8196 (Nkind (P) = N_Op_Divide
8197 and then Is_Integer_Type (Etype (L))
8198 and then Is_Unsigned_Type (Etype (L))
8199 and then R = N
8200 and then not Do_Overflow_Check (P))
8201 then
8202 Set_Is_Power_Of_2_For_Shift (N);
8203 return;
8204 end if;
8205 end;
8207 -- Here we just have 2 ** N on its own, so we can convert this to a
8208 -- shift node. We are prepared to deal with overflow here, and we
8209 -- also have to handle proper modular reduction for binary modular.
8211 else
8212 declare
8213 OK : Boolean;
8214 Lo : Uint;
8215 Hi : Uint;
8217 MaxS : Uint;
8218 -- Maximum shift count with no overflow
8220 TestS : Boolean;
8221 -- Set True if we must test the shift count
8223 Test_Gt : Node_Id;
8224 -- Node for test against TestS
8226 begin
8227 -- Compute maximum shift based on the underlying size. For a
8228 -- modular type this is one less than the size.
8230 if Is_Modular_Integer_Type (Typ) then
8232 -- For modular integer types, this is the size of the value
8233 -- being shifted minus one. Any larger values will cause
8234 -- modular reduction to a result of zero. Note that we do
8235 -- want the RM_Size here (e.g. mod 2 ** 7, we want a result
8236 -- of 6, since 2**7 should be reduced to zero).
8238 MaxS := RM_Size (Rtyp) - 1;
8240 -- For signed integer types, we use the size of the value
8241 -- being shifted minus 2. Larger values cause overflow.
8243 else
8244 MaxS := Esize (Rtyp) - 2;
8245 end if;
8247 -- Determine range to see if it can be larger than MaxS
8249 Determine_Range
8250 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
8251 TestS := (not OK) or else Hi > MaxS;
8253 -- Signed integer case
8255 if Is_Signed_Integer_Type (Typ) then
8257 -- Generate overflow check if overflow is active. Note that
8258 -- we can simply ignore the possibility of overflow if the
8259 -- flag is not set (means that overflow cannot happen or
8260 -- that overflow checks are suppressed).
8262 if Ovflo and TestS then
8263 Insert_Action (N,
8264 Make_Raise_Constraint_Error (Loc,
8265 Condition =>
8266 Make_Op_Gt (Loc,
8267 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8268 Right_Opnd => Make_Integer_Literal (Loc, MaxS)),
8269 Reason => CE_Overflow_Check_Failed));
8270 end if;
8272 -- Now rewrite node as Shift_Left (1, right-operand)
8274 Rewrite (N,
8275 Make_Op_Shift_Left (Loc,
8276 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8277 Right_Opnd => Right_Opnd (N)));
8279 -- Modular integer case
8281 else pragma Assert (Is_Modular_Integer_Type (Typ));
8283 -- If shift count can be greater than MaxS, we need to wrap
8284 -- the shift in a test that will reduce the result value to
8285 -- zero if this shift count is exceeded.
8287 if TestS then
8289 -- Note: build node for the comparison first, before we
8290 -- reuse the Right_Opnd, so that we have proper parents
8291 -- in place for the Duplicate_Subexpr call.
8293 Test_Gt :=
8294 Make_Op_Gt (Loc,
8295 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8296 Right_Opnd => Make_Integer_Literal (Loc, MaxS));
8298 Rewrite (N,
8299 Make_If_Expression (Loc,
8300 Expressions => New_List (
8301 Test_Gt,
8302 Make_Integer_Literal (Loc, Uint_0),
8303 Make_Op_Shift_Left (Loc,
8304 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8305 Right_Opnd => Right_Opnd (N)))));
8307 -- If we know shift count cannot be greater than MaxS, then
8308 -- it is safe to just rewrite as a shift with no test.
8310 else
8311 Rewrite (N,
8312 Make_Op_Shift_Left (Loc,
8313 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8314 Right_Opnd => Right_Opnd (N)));
8315 end if;
8316 end if;
8318 Analyze_And_Resolve (N, Typ);
8319 return;
8320 end;
8321 end if;
8322 end if;
8324 -- Fall through if exponentiation must be done using a runtime routine
8326 -- First deal with modular case
8328 if Is_Modular_Integer_Type (Rtyp) then
8330 -- Nonbinary modular case, we call the special exponentiation
8331 -- routine for the nonbinary case, converting the argument to
8332 -- Long_Long_Integer and passing the modulus value. Then the
8333 -- result is converted back to the base type.
8335 if Non_Binary_Modulus (Rtyp) then
8336 Rewrite (N,
8337 Convert_To (Typ,
8338 Make_Function_Call (Loc,
8339 Name =>
8340 New_Occurrence_Of (RTE (RE_Exp_Modular), Loc),
8341 Parameter_Associations => New_List (
8342 Convert_To (RTE (RE_Unsigned), Base),
8343 Make_Integer_Literal (Loc, Modulus (Rtyp)),
8344 Exp))));
8346 -- Binary modular case, in this case, we call one of two routines,
8347 -- either the unsigned integer case, or the unsigned long long
8348 -- integer case, with a final "and" operation to do the required mod.
8350 else
8351 if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
8352 Ent := RTE (RE_Exp_Unsigned);
8353 else
8354 Ent := RTE (RE_Exp_Long_Long_Unsigned);
8355 end if;
8357 Rewrite (N,
8358 Convert_To (Typ,
8359 Make_Op_And (Loc,
8360 Left_Opnd =>
8361 Make_Function_Call (Loc,
8362 Name => New_Occurrence_Of (Ent, Loc),
8363 Parameter_Associations => New_List (
8364 Convert_To (Etype (First_Formal (Ent)), Base),
8365 Exp)),
8366 Right_Opnd =>
8367 Make_Integer_Literal (Loc, Modulus (Rtyp) - 1))));
8369 end if;
8371 -- Common exit point for modular type case
8373 Analyze_And_Resolve (N, Typ);
8374 return;
8376 -- Signed integer cases, done using either Integer or Long_Long_Integer.
8377 -- It is not worth having routines for Short_[Short_]Integer, since for
8378 -- most machines it would not help, and it would generate more code that
8379 -- might need certification when a certified run time is required.
8381 -- In the integer cases, we have two routines, one for when overflow
8382 -- checks are required, and one when they are not required, since there
8383 -- is a real gain in omitting checks on many machines.
8385 elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
8386 or else (Rtyp = Base_Type (Standard_Long_Integer)
8387 and then
8388 Esize (Standard_Long_Integer) > Esize (Standard_Integer))
8389 or else Rtyp = Universal_Integer
8390 then
8391 Etyp := Standard_Long_Long_Integer;
8393 if Ovflo then
8394 Rent := RE_Exp_Long_Long_Integer;
8395 else
8396 Rent := RE_Exn_Long_Long_Integer;
8397 end if;
8399 elsif Is_Signed_Integer_Type (Rtyp) then
8400 Etyp := Standard_Integer;
8402 if Ovflo then
8403 Rent := RE_Exp_Integer;
8404 else
8405 Rent := RE_Exn_Integer;
8406 end if;
8408 -- Floating-point cases. We do not need separate routines for the
8409 -- overflow case here, since in the case of floating-point, we generate
8410 -- infinities anyway as a rule (either that or we automatically trap
8411 -- overflow), and if there is an infinity generated and a range check
8412 -- is required, the check will fail anyway.
8414 -- Historical note: we used to convert everything to Long_Long_Float
8415 -- and call a single common routine, but this had the undesirable effect
8416 -- of giving different results for small static exponent values and the
8417 -- same dynamic values.
8419 else
8420 pragma Assert (Is_Floating_Point_Type (Rtyp));
8422 if Rtyp = Standard_Float then
8423 Etyp := Standard_Float;
8424 Rent := RE_Exn_Float;
8426 elsif Rtyp = Standard_Long_Float then
8427 Etyp := Standard_Long_Float;
8428 Rent := RE_Exn_Long_Float;
8430 else
8431 Etyp := Standard_Long_Long_Float;
8432 Rent := RE_Exn_Long_Long_Float;
8433 end if;
8434 end if;
8436 -- Common processing for integer cases and floating-point cases.
8437 -- If we are in the right type, we can call runtime routine directly
8439 if Typ = Etyp
8440 and then Rtyp /= Universal_Integer
8441 and then Rtyp /= Universal_Real
8442 then
8443 Rewrite (N,
8444 Wrap_MA (
8445 Make_Function_Call (Loc,
8446 Name => New_Occurrence_Of (RTE (Rent), Loc),
8447 Parameter_Associations => New_List (Base, Exp))));
8449 -- Otherwise we have to introduce conversions (conversions are also
8450 -- required in the universal cases, since the runtime routine is
8451 -- typed using one of the standard types).
8453 else
8454 Rewrite (N,
8455 Convert_To (Typ,
8456 Make_Function_Call (Loc,
8457 Name => New_Occurrence_Of (RTE (Rent), Loc),
8458 Parameter_Associations => New_List (
8459 Convert_To (Etyp, Base),
8460 Exp))));
8461 end if;
8463 Analyze_And_Resolve (N, Typ);
8464 return;
8466 exception
8467 when RE_Not_Available =>
8468 return;
8469 end Expand_N_Op_Expon;
8471 --------------------
8472 -- Expand_N_Op_Ge --
8473 --------------------
8475 procedure Expand_N_Op_Ge (N : Node_Id) is
8476 Typ : constant Entity_Id := Etype (N);
8477 Op1 : constant Node_Id := Left_Opnd (N);
8478 Op2 : constant Node_Id := Right_Opnd (N);
8479 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8481 begin
8482 Binary_Op_Validity_Checks (N);
8484 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8485 -- means we no longer have a comparison operation, we are all done.
8487 Expand_Compare_Minimize_Eliminate_Overflow (N);
8489 if Nkind (N) /= N_Op_Ge then
8490 return;
8491 end if;
8493 -- Array type case
8495 if Is_Array_Type (Typ1) then
8496 Expand_Array_Comparison (N);
8497 return;
8498 end if;
8500 -- Deal with boolean operands
8502 if Is_Boolean_Type (Typ1) then
8503 Adjust_Condition (Op1);
8504 Adjust_Condition (Op2);
8505 Set_Etype (N, Standard_Boolean);
8506 Adjust_Result_Type (N, Typ);
8507 end if;
8509 Rewrite_Comparison (N);
8511 Optimize_Length_Comparison (N);
8512 end Expand_N_Op_Ge;
8514 --------------------
8515 -- Expand_N_Op_Gt --
8516 --------------------
8518 procedure Expand_N_Op_Gt (N : Node_Id) is
8519 Typ : constant Entity_Id := Etype (N);
8520 Op1 : constant Node_Id := Left_Opnd (N);
8521 Op2 : constant Node_Id := Right_Opnd (N);
8522 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8524 begin
8525 Binary_Op_Validity_Checks (N);
8527 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8528 -- means we no longer have a comparison operation, we are all done.
8530 Expand_Compare_Minimize_Eliminate_Overflow (N);
8532 if Nkind (N) /= N_Op_Gt then
8533 return;
8534 end if;
8536 -- Deal with array type operands
8538 if Is_Array_Type (Typ1) then
8539 Expand_Array_Comparison (N);
8540 return;
8541 end if;
8543 -- Deal with boolean type operands
8545 if Is_Boolean_Type (Typ1) then
8546 Adjust_Condition (Op1);
8547 Adjust_Condition (Op2);
8548 Set_Etype (N, Standard_Boolean);
8549 Adjust_Result_Type (N, Typ);
8550 end if;
8552 Rewrite_Comparison (N);
8554 Optimize_Length_Comparison (N);
8555 end Expand_N_Op_Gt;
8557 --------------------
8558 -- Expand_N_Op_Le --
8559 --------------------
8561 procedure Expand_N_Op_Le (N : Node_Id) is
8562 Typ : constant Entity_Id := Etype (N);
8563 Op1 : constant Node_Id := Left_Opnd (N);
8564 Op2 : constant Node_Id := Right_Opnd (N);
8565 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8567 begin
8568 Binary_Op_Validity_Checks (N);
8570 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8571 -- means we no longer have a comparison operation, we are all done.
8573 Expand_Compare_Minimize_Eliminate_Overflow (N);
8575 if Nkind (N) /= N_Op_Le then
8576 return;
8577 end if;
8579 -- Deal with array type operands
8581 if Is_Array_Type (Typ1) then
8582 Expand_Array_Comparison (N);
8583 return;
8584 end if;
8586 -- Deal with Boolean type operands
8588 if Is_Boolean_Type (Typ1) then
8589 Adjust_Condition (Op1);
8590 Adjust_Condition (Op2);
8591 Set_Etype (N, Standard_Boolean);
8592 Adjust_Result_Type (N, Typ);
8593 end if;
8595 Rewrite_Comparison (N);
8597 Optimize_Length_Comparison (N);
8598 end Expand_N_Op_Le;
8600 --------------------
8601 -- Expand_N_Op_Lt --
8602 --------------------
8604 procedure Expand_N_Op_Lt (N : Node_Id) is
8605 Typ : constant Entity_Id := Etype (N);
8606 Op1 : constant Node_Id := Left_Opnd (N);
8607 Op2 : constant Node_Id := Right_Opnd (N);
8608 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8610 begin
8611 Binary_Op_Validity_Checks (N);
8613 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8614 -- means we no longer have a comparison operation, we are all done.
8616 Expand_Compare_Minimize_Eliminate_Overflow (N);
8618 if Nkind (N) /= N_Op_Lt then
8619 return;
8620 end if;
8622 -- Deal with array type operands
8624 if Is_Array_Type (Typ1) then
8625 Expand_Array_Comparison (N);
8626 return;
8627 end if;
8629 -- Deal with Boolean type operands
8631 if Is_Boolean_Type (Typ1) then
8632 Adjust_Condition (Op1);
8633 Adjust_Condition (Op2);
8634 Set_Etype (N, Standard_Boolean);
8635 Adjust_Result_Type (N, Typ);
8636 end if;
8638 Rewrite_Comparison (N);
8640 Optimize_Length_Comparison (N);
8641 end Expand_N_Op_Lt;
8643 -----------------------
8644 -- Expand_N_Op_Minus --
8645 -----------------------
8647 procedure Expand_N_Op_Minus (N : Node_Id) is
8648 Loc : constant Source_Ptr := Sloc (N);
8649 Typ : constant Entity_Id := Etype (N);
8651 begin
8652 Unary_Op_Validity_Checks (N);
8654 -- Check for MINIMIZED/ELIMINATED overflow mode
8656 if Minimized_Eliminated_Overflow_Check (N) then
8657 Apply_Arithmetic_Overflow_Check (N);
8658 return;
8659 end if;
8661 if not Backend_Overflow_Checks_On_Target
8662 and then Is_Signed_Integer_Type (Etype (N))
8663 and then Do_Overflow_Check (N)
8664 then
8665 -- Software overflow checking expands -expr into (0 - expr)
8667 Rewrite (N,
8668 Make_Op_Subtract (Loc,
8669 Left_Opnd => Make_Integer_Literal (Loc, 0),
8670 Right_Opnd => Right_Opnd (N)));
8672 Analyze_And_Resolve (N, Typ);
8673 end if;
8675 Expand_Nonbinary_Modular_Op (N);
8676 end Expand_N_Op_Minus;
8678 ---------------------
8679 -- Expand_N_Op_Mod --
8680 ---------------------
8682 procedure Expand_N_Op_Mod (N : Node_Id) is
8683 Loc : constant Source_Ptr := Sloc (N);
8684 Typ : constant Entity_Id := Etype (N);
8685 DDC : constant Boolean := Do_Division_Check (N);
8687 Left : Node_Id;
8688 Right : Node_Id;
8690 LLB : Uint;
8691 Llo : Uint;
8692 Lhi : Uint;
8693 LOK : Boolean;
8694 Rlo : Uint;
8695 Rhi : Uint;
8696 ROK : Boolean;
8698 pragma Warnings (Off, Lhi);
8700 begin
8701 Binary_Op_Validity_Checks (N);
8703 -- Check for MINIMIZED/ELIMINATED overflow mode
8705 if Minimized_Eliminated_Overflow_Check (N) then
8706 Apply_Arithmetic_Overflow_Check (N);
8707 return;
8708 end if;
8710 if Is_Integer_Type (Etype (N)) then
8711 Apply_Divide_Checks (N);
8713 -- All done if we don't have a MOD any more, which can happen as a
8714 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
8716 if Nkind (N) /= N_Op_Mod then
8717 return;
8718 end if;
8719 end if;
8721 -- Proceed with expansion of mod operator
8723 Left := Left_Opnd (N);
8724 Right := Right_Opnd (N);
8726 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
8727 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
8729 -- Convert mod to rem if operands are both known to be non-negative, or
8730 -- both known to be non-positive (these are the cases in which rem and
8731 -- mod are the same, see (RM 4.5.5(28-30)). We do this since it is quite
8732 -- likely that this will improve the quality of code, (the operation now
8733 -- corresponds to the hardware remainder), and it does not seem likely
8734 -- that it could be harmful. It also avoids some cases of the elaborate
8735 -- expansion in Modify_Tree_For_C mode below (since Ada rem = C %).
8737 if (LOK and ROK)
8738 and then ((Llo >= 0 and then Rlo >= 0)
8739 or else
8740 (Lhi <= 0 and then Rhi <= 0))
8741 then
8742 Rewrite (N,
8743 Make_Op_Rem (Sloc (N),
8744 Left_Opnd => Left_Opnd (N),
8745 Right_Opnd => Right_Opnd (N)));
8747 -- Instead of reanalyzing the node we do the analysis manually. This
8748 -- avoids anomalies when the replacement is done in an instance and
8749 -- is epsilon more efficient.
8751 Set_Entity (N, Standard_Entity (S_Op_Rem));
8752 Set_Etype (N, Typ);
8753 Set_Do_Division_Check (N, DDC);
8754 Expand_N_Op_Rem (N);
8755 Set_Analyzed (N);
8756 return;
8758 -- Otherwise, normal mod processing
8760 else
8761 -- Apply optimization x mod 1 = 0. We don't really need that with
8762 -- gcc, but it is useful with other back ends and is certainly
8763 -- harmless.
8765 if Is_Integer_Type (Etype (N))
8766 and then Compile_Time_Known_Value (Right)
8767 and then Expr_Value (Right) = Uint_1
8768 then
8769 -- Call Remove_Side_Effects to ensure that any side effects in
8770 -- the ignored left operand (in particular function calls to
8771 -- user defined functions) are properly executed.
8773 Remove_Side_Effects (Left);
8775 Rewrite (N, Make_Integer_Literal (Loc, 0));
8776 Analyze_And_Resolve (N, Typ);
8777 return;
8778 end if;
8780 -- If we still have a mod operator and we are in Modify_Tree_For_C
8781 -- mode, and we have a signed integer type, then here is where we do
8782 -- the rewrite in terms of Rem. Note this rewrite bypasses the need
8783 -- for the special handling of the annoying case of largest negative
8784 -- number mod minus one.
8786 if Nkind (N) = N_Op_Mod
8787 and then Is_Signed_Integer_Type (Typ)
8788 and then Modify_Tree_For_C
8789 then
8790 -- In the general case, we expand A mod B as
8792 -- Tnn : constant typ := A rem B;
8793 -- ..
8794 -- (if (A >= 0) = (B >= 0) then Tnn
8795 -- elsif Tnn = 0 then 0
8796 -- else Tnn + B)
8798 -- The comparison can be written simply as A >= 0 if we know that
8799 -- B >= 0 which is a very common case.
8801 -- An important optimization is when B is known at compile time
8802 -- to be 2**K for some constant. In this case we can simply AND
8803 -- the left operand with the bit string 2**K-1 (i.e. K 1-bits)
8804 -- and that works for both the positive and negative cases.
8806 declare
8807 P2 : constant Nat := Power_Of_Two (Right);
8809 begin
8810 if P2 /= 0 then
8811 Rewrite (N,
8812 Unchecked_Convert_To (Typ,
8813 Make_Op_And (Loc,
8814 Left_Opnd =>
8815 Unchecked_Convert_To
8816 (Corresponding_Unsigned_Type (Typ), Left),
8817 Right_Opnd =>
8818 Make_Integer_Literal (Loc, 2 ** P2 - 1))));
8819 Analyze_And_Resolve (N, Typ);
8820 return;
8821 end if;
8822 end;
8824 -- Here for the full rewrite
8826 declare
8827 Tnn : constant Entity_Id := Make_Temporary (Sloc (N), 'T', N);
8828 Cmp : Node_Id;
8830 begin
8831 Cmp :=
8832 Make_Op_Ge (Loc,
8833 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
8834 Right_Opnd => Make_Integer_Literal (Loc, 0));
8836 if not LOK or else Rlo < 0 then
8837 Cmp :=
8838 Make_Op_Eq (Loc,
8839 Left_Opnd => Cmp,
8840 Right_Opnd =>
8841 Make_Op_Ge (Loc,
8842 Left_Opnd => Duplicate_Subexpr_No_Checks (Right),
8843 Right_Opnd => Make_Integer_Literal (Loc, 0)));
8844 end if;
8846 Insert_Action (N,
8847 Make_Object_Declaration (Loc,
8848 Defining_Identifier => Tnn,
8849 Constant_Present => True,
8850 Object_Definition => New_Occurrence_Of (Typ, Loc),
8851 Expression =>
8852 Make_Op_Rem (Loc,
8853 Left_Opnd => Left,
8854 Right_Opnd => Right)));
8856 Rewrite (N,
8857 Make_If_Expression (Loc,
8858 Expressions => New_List (
8859 Cmp,
8860 New_Occurrence_Of (Tnn, Loc),
8861 Make_If_Expression (Loc,
8862 Is_Elsif => True,
8863 Expressions => New_List (
8864 Make_Op_Eq (Loc,
8865 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8866 Right_Opnd => Make_Integer_Literal (Loc, 0)),
8867 Make_Integer_Literal (Loc, 0),
8868 Make_Op_Add (Loc,
8869 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8870 Right_Opnd =>
8871 Duplicate_Subexpr_No_Checks (Right)))))));
8873 Analyze_And_Resolve (N, Typ);
8874 return;
8875 end;
8876 end if;
8878 -- Deal with annoying case of largest negative number mod minus one.
8879 -- Gigi may not handle this case correctly, because on some targets,
8880 -- the mod value is computed using a divide instruction which gives
8881 -- an overflow trap for this case.
8883 -- It would be a bit more efficient to figure out which targets
8884 -- this is really needed for, but in practice it is reasonable
8885 -- to do the following special check in all cases, since it means
8886 -- we get a clearer message, and also the overhead is minimal given
8887 -- that division is expensive in any case.
8889 -- In fact the check is quite easy, if the right operand is -1, then
8890 -- the mod value is always 0, and we can just ignore the left operand
8891 -- completely in this case.
8893 -- This only applies if we still have a mod operator. Skip if we
8894 -- have already rewritten this (e.g. in the case of eliminated
8895 -- overflow checks which have driven us into bignum mode).
8897 if Nkind (N) = N_Op_Mod then
8899 -- The operand type may be private (e.g. in the expansion of an
8900 -- intrinsic operation) so we must use the underlying type to get
8901 -- the bounds, and convert the literals explicitly.
8903 LLB :=
8904 Expr_Value
8905 (Type_Low_Bound (Base_Type (Underlying_Type (Etype (Left)))));
8907 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
8908 and then ((not LOK) or else (Llo = LLB))
8909 then
8910 Rewrite (N,
8911 Make_If_Expression (Loc,
8912 Expressions => New_List (
8913 Make_Op_Eq (Loc,
8914 Left_Opnd => Duplicate_Subexpr (Right),
8915 Right_Opnd =>
8916 Unchecked_Convert_To (Typ,
8917 Make_Integer_Literal (Loc, -1))),
8918 Unchecked_Convert_To (Typ,
8919 Make_Integer_Literal (Loc, Uint_0)),
8920 Relocate_Node (N))));
8922 Set_Analyzed (Next (Next (First (Expressions (N)))));
8923 Analyze_And_Resolve (N, Typ);
8924 end if;
8925 end if;
8926 end if;
8927 end Expand_N_Op_Mod;
8929 --------------------------
8930 -- Expand_N_Op_Multiply --
8931 --------------------------
8933 procedure Expand_N_Op_Multiply (N : Node_Id) is
8934 Loc : constant Source_Ptr := Sloc (N);
8935 Lop : constant Node_Id := Left_Opnd (N);
8936 Rop : constant Node_Id := Right_Opnd (N);
8938 Lp2 : constant Boolean :=
8939 Nkind (Lop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Lop);
8940 Rp2 : constant Boolean :=
8941 Nkind (Rop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Rop);
8943 Ltyp : constant Entity_Id := Etype (Lop);
8944 Rtyp : constant Entity_Id := Etype (Rop);
8945 Typ : Entity_Id := Etype (N);
8947 begin
8948 Binary_Op_Validity_Checks (N);
8950 -- Check for MINIMIZED/ELIMINATED overflow mode
8952 if Minimized_Eliminated_Overflow_Check (N) then
8953 Apply_Arithmetic_Overflow_Check (N);
8954 return;
8955 end if;
8957 -- Special optimizations for integer types
8959 if Is_Integer_Type (Typ) then
8961 -- N * 0 = 0 for integer types
8963 if Compile_Time_Known_Value (Rop)
8964 and then Expr_Value (Rop) = Uint_0
8965 then
8966 -- Call Remove_Side_Effects to ensure that any side effects in
8967 -- the ignored left operand (in particular function calls to
8968 -- user defined functions) are properly executed.
8970 Remove_Side_Effects (Lop);
8972 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
8973 Analyze_And_Resolve (N, Typ);
8974 return;
8975 end if;
8977 -- Similar handling for 0 * N = 0
8979 if Compile_Time_Known_Value (Lop)
8980 and then Expr_Value (Lop) = Uint_0
8981 then
8982 Remove_Side_Effects (Rop);
8983 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
8984 Analyze_And_Resolve (N, Typ);
8985 return;
8986 end if;
8988 -- N * 1 = 1 * N = N for integer types
8990 -- This optimisation is not done if we are going to
8991 -- rewrite the product 1 * 2 ** N to a shift.
8993 if Compile_Time_Known_Value (Rop)
8994 and then Expr_Value (Rop) = Uint_1
8995 and then not Lp2
8996 then
8997 Rewrite (N, Lop);
8998 return;
9000 elsif Compile_Time_Known_Value (Lop)
9001 and then Expr_Value (Lop) = Uint_1
9002 and then not Rp2
9003 then
9004 Rewrite (N, Rop);
9005 return;
9006 end if;
9007 end if;
9009 -- Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
9010 -- Is_Power_Of_2_For_Shift is set means that we know that our left
9011 -- operand is an integer, as required for this to work.
9013 if Rp2 then
9014 if Lp2 then
9016 -- Convert 2 ** A * 2 ** B into 2 ** (A + B)
9018 Rewrite (N,
9019 Make_Op_Expon (Loc,
9020 Left_Opnd => Make_Integer_Literal (Loc, 2),
9021 Right_Opnd =>
9022 Make_Op_Add (Loc,
9023 Left_Opnd => Right_Opnd (Lop),
9024 Right_Opnd => Right_Opnd (Rop))));
9025 Analyze_And_Resolve (N, Typ);
9026 return;
9028 else
9029 -- If the result is modular, perform the reduction of the result
9030 -- appropriately.
9032 if Is_Modular_Integer_Type (Typ)
9033 and then not Non_Binary_Modulus (Typ)
9034 then
9035 Rewrite (N,
9036 Make_Op_And (Loc,
9037 Left_Opnd =>
9038 Make_Op_Shift_Left (Loc,
9039 Left_Opnd => Lop,
9040 Right_Opnd =>
9041 Convert_To (Standard_Natural, Right_Opnd (Rop))),
9042 Right_Opnd =>
9043 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9045 else
9046 Rewrite (N,
9047 Make_Op_Shift_Left (Loc,
9048 Left_Opnd => Lop,
9049 Right_Opnd =>
9050 Convert_To (Standard_Natural, Right_Opnd (Rop))));
9051 end if;
9053 Analyze_And_Resolve (N, Typ);
9054 return;
9055 end if;
9057 -- Same processing for the operands the other way round
9059 elsif Lp2 then
9060 if Is_Modular_Integer_Type (Typ)
9061 and then not Non_Binary_Modulus (Typ)
9062 then
9063 Rewrite (N,
9064 Make_Op_And (Loc,
9065 Left_Opnd =>
9066 Make_Op_Shift_Left (Loc,
9067 Left_Opnd => Rop,
9068 Right_Opnd =>
9069 Convert_To (Standard_Natural, Right_Opnd (Lop))),
9070 Right_Opnd =>
9071 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9073 else
9074 Rewrite (N,
9075 Make_Op_Shift_Left (Loc,
9076 Left_Opnd => Rop,
9077 Right_Opnd =>
9078 Convert_To (Standard_Natural, Right_Opnd (Lop))));
9079 end if;
9081 Analyze_And_Resolve (N, Typ);
9082 return;
9083 end if;
9085 -- Do required fixup of universal fixed operation
9087 if Typ = Universal_Fixed then
9088 Fixup_Universal_Fixed_Operation (N);
9089 Typ := Etype (N);
9090 end if;
9092 -- Multiplications with fixed-point results
9094 if Is_Fixed_Point_Type (Typ) then
9096 -- No special processing if Treat_Fixed_As_Integer is set, since from
9097 -- a semantic point of view such operations are simply integer
9098 -- operations and will be treated that way.
9100 if not Treat_Fixed_As_Integer (N) then
9102 -- Case of fixed * integer => fixed
9104 if Is_Integer_Type (Rtyp) then
9105 Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N);
9107 -- Case of integer * fixed => fixed
9109 elsif Is_Integer_Type (Ltyp) then
9110 Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N);
9112 -- Case of fixed * fixed => fixed
9114 else
9115 Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N);
9116 end if;
9117 end if;
9119 -- Other cases of multiplication of fixed-point operands. Again we
9120 -- exclude the cases where Treat_Fixed_As_Integer flag is set.
9122 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
9123 and then not Treat_Fixed_As_Integer (N)
9124 then
9125 if Is_Integer_Type (Typ) then
9126 Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N);
9127 else
9128 pragma Assert (Is_Floating_Point_Type (Typ));
9129 Expand_Multiply_Fixed_By_Fixed_Giving_Float (N);
9130 end if;
9132 -- Mixed-mode operations can appear in a non-static universal context,
9133 -- in which case the integer argument must be converted explicitly.
9135 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
9136 Rewrite (Rop, Convert_To (Universal_Real, Relocate_Node (Rop)));
9137 Analyze_And_Resolve (Rop, Universal_Real);
9139 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
9140 Rewrite (Lop, Convert_To (Universal_Real, Relocate_Node (Lop)));
9141 Analyze_And_Resolve (Lop, Universal_Real);
9143 -- Non-fixed point cases, check software overflow checking required
9145 elsif Is_Signed_Integer_Type (Etype (N)) then
9146 Apply_Arithmetic_Overflow_Check (N);
9147 end if;
9149 -- Overflow checks for floating-point if -gnateF mode active
9151 Check_Float_Op_Overflow (N);
9153 Expand_Nonbinary_Modular_Op (N);
9154 end Expand_N_Op_Multiply;
9156 --------------------
9157 -- Expand_N_Op_Ne --
9158 --------------------
9160 procedure Expand_N_Op_Ne (N : Node_Id) is
9161 Typ : constant Entity_Id := Etype (Left_Opnd (N));
9163 begin
9164 -- Case of elementary type with standard operator
9166 if Is_Elementary_Type (Typ)
9167 and then Sloc (Entity (N)) = Standard_Location
9168 then
9169 Binary_Op_Validity_Checks (N);
9171 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if
9172 -- means we no longer have a /= operation, we are all done.
9174 Expand_Compare_Minimize_Eliminate_Overflow (N);
9176 if Nkind (N) /= N_Op_Ne then
9177 return;
9178 end if;
9180 -- Boolean types (requiring handling of non-standard case)
9182 if Is_Boolean_Type (Typ) then
9183 Adjust_Condition (Left_Opnd (N));
9184 Adjust_Condition (Right_Opnd (N));
9185 Set_Etype (N, Standard_Boolean);
9186 Adjust_Result_Type (N, Typ);
9187 end if;
9189 Rewrite_Comparison (N);
9191 -- For all cases other than elementary types, we rewrite node as the
9192 -- negation of an equality operation, and reanalyze. The equality to be
9193 -- used is defined in the same scope and has the same signature. This
9194 -- signature must be set explicitly since in an instance it may not have
9195 -- the same visibility as in the generic unit. This avoids duplicating
9196 -- or factoring the complex code for record/array equality tests etc.
9198 -- This case is also used for the minimal expansion performed in
9199 -- GNATprove mode.
9201 else
9202 declare
9203 Loc : constant Source_Ptr := Sloc (N);
9204 Neg : Node_Id;
9205 Ne : constant Entity_Id := Entity (N);
9207 begin
9208 Binary_Op_Validity_Checks (N);
9210 Neg :=
9211 Make_Op_Not (Loc,
9212 Right_Opnd =>
9213 Make_Op_Eq (Loc,
9214 Left_Opnd => Left_Opnd (N),
9215 Right_Opnd => Right_Opnd (N)));
9217 -- The level of parentheses is useless in GNATprove mode, and
9218 -- bumping its level here leads to wrong columns being used in
9219 -- check messages, hence skip it in this mode.
9221 if not GNATprove_Mode then
9222 Set_Paren_Count (Right_Opnd (Neg), 1);
9223 end if;
9225 if Scope (Ne) /= Standard_Standard then
9226 Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
9227 end if;
9229 -- For navigation purposes, we want to treat the inequality as an
9230 -- implicit reference to the corresponding equality. Preserve the
9231 -- Comes_From_ source flag to generate proper Xref entries.
9233 Preserve_Comes_From_Source (Neg, N);
9234 Preserve_Comes_From_Source (Right_Opnd (Neg), N);
9235 Rewrite (N, Neg);
9236 Analyze_And_Resolve (N, Standard_Boolean);
9237 end;
9238 end if;
9240 -- No need for optimization in GNATprove mode, where we would rather see
9241 -- the original source expression.
9243 if not GNATprove_Mode then
9244 Optimize_Length_Comparison (N);
9245 end if;
9246 end Expand_N_Op_Ne;
9248 ---------------------
9249 -- Expand_N_Op_Not --
9250 ---------------------
9252 -- If the argument is other than a Boolean array type, there is no special
9253 -- expansion required, except for dealing with validity checks, and non-
9254 -- standard boolean representations.
9256 -- For the packed array case, we call the special routine in Exp_Pakd,
9257 -- except that if the component size is greater than one, we use the
9258 -- standard routine generating a gruesome loop (it is so peculiar to have
9259 -- packed arrays with non-standard Boolean representations anyway, so it
9260 -- does not matter that we do not handle this case efficiently).
9262 -- For the unpacked array case (and for the special packed case where we
9263 -- have non standard Booleans, as discussed above), we generate and insert
9264 -- into the tree the following function definition:
9266 -- function Nnnn (A : arr) is
9267 -- B : arr;
9268 -- begin
9269 -- for J in a'range loop
9270 -- B (J) := not A (J);
9271 -- end loop;
9272 -- return B;
9273 -- end Nnnn;
9275 -- Here arr is the actual subtype of the parameter (and hence always
9276 -- constrained). Then we replace the not with a call to this function.
9278 procedure Expand_N_Op_Not (N : Node_Id) is
9279 Loc : constant Source_Ptr := Sloc (N);
9280 Typ : constant Entity_Id := Etype (N);
9281 Opnd : Node_Id;
9282 Arr : Entity_Id;
9283 A : Entity_Id;
9284 B : Entity_Id;
9285 J : Entity_Id;
9286 A_J : Node_Id;
9287 B_J : Node_Id;
9289 Func_Name : Entity_Id;
9290 Loop_Statement : Node_Id;
9292 begin
9293 Unary_Op_Validity_Checks (N);
9295 -- For boolean operand, deal with non-standard booleans
9297 if Is_Boolean_Type (Typ) then
9298 Adjust_Condition (Right_Opnd (N));
9299 Set_Etype (N, Standard_Boolean);
9300 Adjust_Result_Type (N, Typ);
9301 return;
9302 end if;
9304 -- Only array types need any other processing
9306 if not Is_Array_Type (Typ) then
9307 return;
9308 end if;
9310 -- Case of array operand. If bit packed with a component size of 1,
9311 -- handle it in Exp_Pakd if the operand is known to be aligned.
9313 if Is_Bit_Packed_Array (Typ)
9314 and then Component_Size (Typ) = 1
9315 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
9316 then
9317 Expand_Packed_Not (N);
9318 return;
9319 end if;
9321 -- Case of array operand which is not bit-packed. If the context is
9322 -- a safe assignment, call in-place operation, If context is a larger
9323 -- boolean expression in the context of a safe assignment, expansion is
9324 -- done by enclosing operation.
9326 Opnd := Relocate_Node (Right_Opnd (N));
9327 Convert_To_Actual_Subtype (Opnd);
9328 Arr := Etype (Opnd);
9329 Ensure_Defined (Arr, N);
9330 Silly_Boolean_Array_Not_Test (N, Arr);
9332 if Nkind (Parent (N)) = N_Assignment_Statement then
9333 if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
9334 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9335 return;
9337 -- Special case the negation of a binary operation
9339 elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
9340 and then Safe_In_Place_Array_Op
9341 (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
9342 then
9343 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9344 return;
9345 end if;
9347 elsif Nkind (Parent (N)) in N_Binary_Op
9348 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
9349 then
9350 declare
9351 Op1 : constant Node_Id := Left_Opnd (Parent (N));
9352 Op2 : constant Node_Id := Right_Opnd (Parent (N));
9353 Lhs : constant Node_Id := Name (Parent (Parent (N)));
9355 begin
9356 if Safe_In_Place_Array_Op (Lhs, Op1, Op2) then
9358 -- (not A) op (not B) can be reduced to a single call
9360 if N = Op1 and then Nkind (Op2) = N_Op_Not then
9361 return;
9363 elsif N = Op2 and then Nkind (Op1) = N_Op_Not then
9364 return;
9366 -- A xor (not B) can also be special-cased
9368 elsif N = Op2 and then Nkind (Parent (N)) = N_Op_Xor then
9369 return;
9370 end if;
9371 end if;
9372 end;
9373 end if;
9375 A := Make_Defining_Identifier (Loc, Name_uA);
9376 B := Make_Defining_Identifier (Loc, Name_uB);
9377 J := Make_Defining_Identifier (Loc, Name_uJ);
9379 A_J :=
9380 Make_Indexed_Component (Loc,
9381 Prefix => New_Occurrence_Of (A, Loc),
9382 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9384 B_J :=
9385 Make_Indexed_Component (Loc,
9386 Prefix => New_Occurrence_Of (B, Loc),
9387 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9389 Loop_Statement :=
9390 Make_Implicit_Loop_Statement (N,
9391 Identifier => Empty,
9393 Iteration_Scheme =>
9394 Make_Iteration_Scheme (Loc,
9395 Loop_Parameter_Specification =>
9396 Make_Loop_Parameter_Specification (Loc,
9397 Defining_Identifier => J,
9398 Discrete_Subtype_Definition =>
9399 Make_Attribute_Reference (Loc,
9400 Prefix => Make_Identifier (Loc, Chars (A)),
9401 Attribute_Name => Name_Range))),
9403 Statements => New_List (
9404 Make_Assignment_Statement (Loc,
9405 Name => B_J,
9406 Expression => Make_Op_Not (Loc, A_J))));
9408 Func_Name := Make_Temporary (Loc, 'N');
9409 Set_Is_Inlined (Func_Name);
9411 Insert_Action (N,
9412 Make_Subprogram_Body (Loc,
9413 Specification =>
9414 Make_Function_Specification (Loc,
9415 Defining_Unit_Name => Func_Name,
9416 Parameter_Specifications => New_List (
9417 Make_Parameter_Specification (Loc,
9418 Defining_Identifier => A,
9419 Parameter_Type => New_Occurrence_Of (Typ, Loc))),
9420 Result_Definition => New_Occurrence_Of (Typ, Loc)),
9422 Declarations => New_List (
9423 Make_Object_Declaration (Loc,
9424 Defining_Identifier => B,
9425 Object_Definition => New_Occurrence_Of (Arr, Loc))),
9427 Handled_Statement_Sequence =>
9428 Make_Handled_Sequence_Of_Statements (Loc,
9429 Statements => New_List (
9430 Loop_Statement,
9431 Make_Simple_Return_Statement (Loc,
9432 Expression => Make_Identifier (Loc, Chars (B)))))));
9434 Rewrite (N,
9435 Make_Function_Call (Loc,
9436 Name => New_Occurrence_Of (Func_Name, Loc),
9437 Parameter_Associations => New_List (Opnd)));
9439 Analyze_And_Resolve (N, Typ);
9440 end Expand_N_Op_Not;
9442 --------------------
9443 -- Expand_N_Op_Or --
9444 --------------------
9446 procedure Expand_N_Op_Or (N : Node_Id) is
9447 Typ : constant Entity_Id := Etype (N);
9449 begin
9450 Binary_Op_Validity_Checks (N);
9452 if Is_Array_Type (Etype (N)) then
9453 Expand_Boolean_Operator (N);
9455 elsif Is_Boolean_Type (Etype (N)) then
9456 Adjust_Condition (Left_Opnd (N));
9457 Adjust_Condition (Right_Opnd (N));
9458 Set_Etype (N, Standard_Boolean);
9459 Adjust_Result_Type (N, Typ);
9461 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9462 Expand_Intrinsic_Call (N, Entity (N));
9463 end if;
9465 Expand_Nonbinary_Modular_Op (N);
9466 end Expand_N_Op_Or;
9468 ----------------------
9469 -- Expand_N_Op_Plus --
9470 ----------------------
9472 procedure Expand_N_Op_Plus (N : Node_Id) is
9473 begin
9474 Unary_Op_Validity_Checks (N);
9476 -- Check for MINIMIZED/ELIMINATED overflow mode
9478 if Minimized_Eliminated_Overflow_Check (N) then
9479 Apply_Arithmetic_Overflow_Check (N);
9480 return;
9481 end if;
9482 end Expand_N_Op_Plus;
9484 ---------------------
9485 -- Expand_N_Op_Rem --
9486 ---------------------
9488 procedure Expand_N_Op_Rem (N : Node_Id) is
9489 Loc : constant Source_Ptr := Sloc (N);
9490 Typ : constant Entity_Id := Etype (N);
9492 Left : Node_Id;
9493 Right : Node_Id;
9495 Lo : Uint;
9496 Hi : Uint;
9497 OK : Boolean;
9499 Lneg : Boolean;
9500 Rneg : Boolean;
9501 -- Set if corresponding operand can be negative
9503 pragma Unreferenced (Hi);
9505 begin
9506 Binary_Op_Validity_Checks (N);
9508 -- Check for MINIMIZED/ELIMINATED overflow mode
9510 if Minimized_Eliminated_Overflow_Check (N) then
9511 Apply_Arithmetic_Overflow_Check (N);
9512 return;
9513 end if;
9515 if Is_Integer_Type (Etype (N)) then
9516 Apply_Divide_Checks (N);
9518 -- All done if we don't have a REM any more, which can happen as a
9519 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
9521 if Nkind (N) /= N_Op_Rem then
9522 return;
9523 end if;
9524 end if;
9526 -- Proceed with expansion of REM
9528 Left := Left_Opnd (N);
9529 Right := Right_Opnd (N);
9531 -- Apply optimization x rem 1 = 0. We don't really need that with gcc,
9532 -- but it is useful with other back ends, and is certainly harmless.
9534 if Is_Integer_Type (Etype (N))
9535 and then Compile_Time_Known_Value (Right)
9536 and then Expr_Value (Right) = Uint_1
9537 then
9538 -- Call Remove_Side_Effects to ensure that any side effects in the
9539 -- ignored left operand (in particular function calls to user defined
9540 -- functions) are properly executed.
9542 Remove_Side_Effects (Left);
9544 Rewrite (N, Make_Integer_Literal (Loc, 0));
9545 Analyze_And_Resolve (N, Typ);
9546 return;
9547 end if;
9549 -- Deal with annoying case of largest negative number remainder minus
9550 -- one. Gigi may not handle this case correctly, because on some
9551 -- targets, the mod value is computed using a divide instruction
9552 -- which gives an overflow trap for this case.
9554 -- It would be a bit more efficient to figure out which targets this
9555 -- is really needed for, but in practice it is reasonable to do the
9556 -- following special check in all cases, since it means we get a clearer
9557 -- message, and also the overhead is minimal given that division is
9558 -- expensive in any case.
9560 -- In fact the check is quite easy, if the right operand is -1, then
9561 -- the remainder is always 0, and we can just ignore the left operand
9562 -- completely in this case.
9564 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9565 Lneg := (not OK) or else Lo < 0;
9567 Determine_Range (Left, OK, Lo, Hi, Assume_Valid => True);
9568 Rneg := (not OK) or else Lo < 0;
9570 -- We won't mess with trying to find out if the left operand can really
9571 -- be the largest negative number (that's a pain in the case of private
9572 -- types and this is really marginal). We will just assume that we need
9573 -- the test if the left operand can be negative at all.
9575 if Lneg and Rneg then
9576 Rewrite (N,
9577 Make_If_Expression (Loc,
9578 Expressions => New_List (
9579 Make_Op_Eq (Loc,
9580 Left_Opnd => Duplicate_Subexpr (Right),
9581 Right_Opnd =>
9582 Unchecked_Convert_To (Typ, Make_Integer_Literal (Loc, -1))),
9584 Unchecked_Convert_To (Typ,
9585 Make_Integer_Literal (Loc, Uint_0)),
9587 Relocate_Node (N))));
9589 Set_Analyzed (Next (Next (First (Expressions (N)))));
9590 Analyze_And_Resolve (N, Typ);
9591 end if;
9592 end Expand_N_Op_Rem;
9594 -----------------------------
9595 -- Expand_N_Op_Rotate_Left --
9596 -----------------------------
9598 procedure Expand_N_Op_Rotate_Left (N : Node_Id) is
9599 begin
9600 Binary_Op_Validity_Checks (N);
9602 -- If we are in Modify_Tree_For_C mode, there is no rotate left in C,
9603 -- so we rewrite in terms of logical shifts
9605 -- Shift_Left (Num, Bits) or Shift_Right (num, Esize - Bits)
9607 -- where Bits is the shift count mod Esize (the mod operation here
9608 -- deals with ludicrous large shift counts, which are apparently OK).
9610 -- What about nonbinary modulus ???
9612 declare
9613 Loc : constant Source_Ptr := Sloc (N);
9614 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9615 Typ : constant Entity_Id := Etype (N);
9617 begin
9618 if Modify_Tree_For_C then
9619 Rewrite (Right_Opnd (N),
9620 Make_Op_Rem (Loc,
9621 Left_Opnd => Relocate_Node (Right_Opnd (N)),
9622 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
9624 Analyze_And_Resolve (Right_Opnd (N), Rtp);
9626 Rewrite (N,
9627 Make_Op_Or (Loc,
9628 Left_Opnd =>
9629 Make_Op_Shift_Left (Loc,
9630 Left_Opnd => Left_Opnd (N),
9631 Right_Opnd => Right_Opnd (N)),
9633 Right_Opnd =>
9634 Make_Op_Shift_Right (Loc,
9635 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9636 Right_Opnd =>
9637 Make_Op_Subtract (Loc,
9638 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9639 Right_Opnd =>
9640 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9642 Analyze_And_Resolve (N, Typ);
9643 end if;
9644 end;
9645 end Expand_N_Op_Rotate_Left;
9647 ------------------------------
9648 -- Expand_N_Op_Rotate_Right --
9649 ------------------------------
9651 procedure Expand_N_Op_Rotate_Right (N : Node_Id) is
9652 begin
9653 Binary_Op_Validity_Checks (N);
9655 -- If we are in Modify_Tree_For_C mode, there is no rotate right in C,
9656 -- so we rewrite in terms of logical shifts
9658 -- Shift_Right (Num, Bits) or Shift_Left (num, Esize - Bits)
9660 -- where Bits is the shift count mod Esize (the mod operation here
9661 -- deals with ludicrous large shift counts, which are apparently OK).
9663 -- What about nonbinary modulus ???
9665 declare
9666 Loc : constant Source_Ptr := Sloc (N);
9667 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9668 Typ : constant Entity_Id := Etype (N);
9670 begin
9671 Rewrite (Right_Opnd (N),
9672 Make_Op_Rem (Loc,
9673 Left_Opnd => Relocate_Node (Right_Opnd (N)),
9674 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
9676 Analyze_And_Resolve (Right_Opnd (N), Rtp);
9678 if Modify_Tree_For_C then
9679 Rewrite (N,
9680 Make_Op_Or (Loc,
9681 Left_Opnd =>
9682 Make_Op_Shift_Right (Loc,
9683 Left_Opnd => Left_Opnd (N),
9684 Right_Opnd => Right_Opnd (N)),
9686 Right_Opnd =>
9687 Make_Op_Shift_Left (Loc,
9688 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9689 Right_Opnd =>
9690 Make_Op_Subtract (Loc,
9691 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9692 Right_Opnd =>
9693 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9695 Analyze_And_Resolve (N, Typ);
9696 end if;
9697 end;
9698 end Expand_N_Op_Rotate_Right;
9700 ----------------------------
9701 -- Expand_N_Op_Shift_Left --
9702 ----------------------------
9704 -- Note: nothing in this routine depends on left as opposed to right shifts
9705 -- so we share the routine for expanding shift right operations.
9707 procedure Expand_N_Op_Shift_Left (N : Node_Id) is
9708 begin
9709 Binary_Op_Validity_Checks (N);
9711 -- If we are in Modify_Tree_For_C mode, then ensure that the right
9712 -- operand is not greater than the word size (since that would not
9713 -- be defined properly by the corresponding C shift operator).
9715 if Modify_Tree_For_C then
9716 declare
9717 Right : constant Node_Id := Right_Opnd (N);
9718 Loc : constant Source_Ptr := Sloc (Right);
9719 Typ : constant Entity_Id := Etype (N);
9720 Siz : constant Uint := Esize (Typ);
9721 Orig : Node_Id;
9722 OK : Boolean;
9723 Lo : Uint;
9724 Hi : Uint;
9726 begin
9727 if Compile_Time_Known_Value (Right) then
9728 if Expr_Value (Right) >= Siz then
9729 Rewrite (N, Make_Integer_Literal (Loc, 0));
9730 Analyze_And_Resolve (N, Typ);
9731 end if;
9733 -- Not compile time known, find range
9735 else
9736 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9738 -- Nothing to do if known to be OK range, otherwise expand
9740 if not OK or else Hi >= Siz then
9742 -- Prevent recursion on copy of shift node
9744 Orig := Relocate_Node (N);
9745 Set_Analyzed (Orig);
9747 -- Now do the rewrite
9749 Rewrite (N,
9750 Make_If_Expression (Loc,
9751 Expressions => New_List (
9752 Make_Op_Ge (Loc,
9753 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
9754 Right_Opnd => Make_Integer_Literal (Loc, Siz)),
9755 Make_Integer_Literal (Loc, 0),
9756 Orig)));
9757 Analyze_And_Resolve (N, Typ);
9758 end if;
9759 end if;
9760 end;
9761 end if;
9762 end Expand_N_Op_Shift_Left;
9764 -----------------------------
9765 -- Expand_N_Op_Shift_Right --
9766 -----------------------------
9768 procedure Expand_N_Op_Shift_Right (N : Node_Id) is
9769 begin
9770 -- Share shift left circuit
9772 Expand_N_Op_Shift_Left (N);
9773 end Expand_N_Op_Shift_Right;
9775 ----------------------------------------
9776 -- Expand_N_Op_Shift_Right_Arithmetic --
9777 ----------------------------------------
9779 procedure Expand_N_Op_Shift_Right_Arithmetic (N : Node_Id) is
9780 begin
9781 Binary_Op_Validity_Checks (N);
9783 -- If we are in Modify_Tree_For_C mode, there is no shift right
9784 -- arithmetic in C, so we rewrite in terms of logical shifts.
9786 -- Shift_Right (Num, Bits) or
9787 -- (if Num >= Sign
9788 -- then not (Shift_Right (Mask, bits))
9789 -- else 0)
9791 -- Here Mask is all 1 bits (2**size - 1), and Sign is 2**(size - 1)
9793 -- Note: in almost all C compilers it would work to just shift a
9794 -- signed integer right, but it's undefined and we cannot rely on it.
9796 -- Note: the above works fine for shift counts greater than or equal
9797 -- to the word size, since in this case (not (Shift_Right (Mask, bits)))
9798 -- generates all 1'bits.
9800 -- What about nonbinary modulus ???
9802 declare
9803 Loc : constant Source_Ptr := Sloc (N);
9804 Typ : constant Entity_Id := Etype (N);
9805 Sign : constant Uint := 2 ** (Esize (Typ) - 1);
9806 Mask : constant Uint := (2 ** Esize (Typ)) - 1;
9807 Left : constant Node_Id := Left_Opnd (N);
9808 Right : constant Node_Id := Right_Opnd (N);
9809 Maskx : Node_Id;
9811 begin
9812 if Modify_Tree_For_C then
9814 -- Here if not (Shift_Right (Mask, bits)) can be computed at
9815 -- compile time as a single constant.
9817 if Compile_Time_Known_Value (Right) then
9818 declare
9819 Val : constant Uint := Expr_Value (Right);
9821 begin
9822 if Val >= Esize (Typ) then
9823 Maskx := Make_Integer_Literal (Loc, Mask);
9825 else
9826 Maskx :=
9827 Make_Integer_Literal (Loc,
9828 Intval => Mask - (Mask / (2 ** Expr_Value (Right))));
9829 end if;
9830 end;
9832 else
9833 Maskx :=
9834 Make_Op_Not (Loc,
9835 Right_Opnd =>
9836 Make_Op_Shift_Right (Loc,
9837 Left_Opnd => Make_Integer_Literal (Loc, Mask),
9838 Right_Opnd => Duplicate_Subexpr_No_Checks (Right)));
9839 end if;
9841 -- Now do the rewrite
9843 Rewrite (N,
9844 Make_Op_Or (Loc,
9845 Left_Opnd =>
9846 Make_Op_Shift_Right (Loc,
9847 Left_Opnd => Left,
9848 Right_Opnd => Right),
9849 Right_Opnd =>
9850 Make_If_Expression (Loc,
9851 Expressions => New_List (
9852 Make_Op_Ge (Loc,
9853 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
9854 Right_Opnd => Make_Integer_Literal (Loc, Sign)),
9855 Maskx,
9856 Make_Integer_Literal (Loc, 0)))));
9857 Analyze_And_Resolve (N, Typ);
9858 end if;
9859 end;
9860 end Expand_N_Op_Shift_Right_Arithmetic;
9862 --------------------------
9863 -- Expand_N_Op_Subtract --
9864 --------------------------
9866 procedure Expand_N_Op_Subtract (N : Node_Id) is
9867 Typ : constant Entity_Id := Etype (N);
9869 begin
9870 Binary_Op_Validity_Checks (N);
9872 -- Check for MINIMIZED/ELIMINATED overflow mode
9874 if Minimized_Eliminated_Overflow_Check (N) then
9875 Apply_Arithmetic_Overflow_Check (N);
9876 return;
9877 end if;
9879 -- N - 0 = N for integer types
9881 if Is_Integer_Type (Typ)
9882 and then Compile_Time_Known_Value (Right_Opnd (N))
9883 and then Expr_Value (Right_Opnd (N)) = 0
9884 then
9885 Rewrite (N, Left_Opnd (N));
9886 return;
9887 end if;
9889 -- Arithmetic overflow checks for signed integer/fixed point types
9891 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
9892 Apply_Arithmetic_Overflow_Check (N);
9893 end if;
9895 -- Overflow checks for floating-point if -gnateF mode active
9897 Check_Float_Op_Overflow (N);
9899 Expand_Nonbinary_Modular_Op (N);
9900 end Expand_N_Op_Subtract;
9902 ---------------------
9903 -- Expand_N_Op_Xor --
9904 ---------------------
9906 procedure Expand_N_Op_Xor (N : Node_Id) is
9907 Typ : constant Entity_Id := Etype (N);
9909 begin
9910 Binary_Op_Validity_Checks (N);
9912 if Is_Array_Type (Etype (N)) then
9913 Expand_Boolean_Operator (N);
9915 elsif Is_Boolean_Type (Etype (N)) then
9916 Adjust_Condition (Left_Opnd (N));
9917 Adjust_Condition (Right_Opnd (N));
9918 Set_Etype (N, Standard_Boolean);
9919 Adjust_Result_Type (N, Typ);
9921 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9922 Expand_Intrinsic_Call (N, Entity (N));
9923 end if;
9924 end Expand_N_Op_Xor;
9926 ----------------------
9927 -- Expand_N_Or_Else --
9928 ----------------------
9930 procedure Expand_N_Or_Else (N : Node_Id)
9931 renames Expand_Short_Circuit_Operator;
9933 -----------------------------------
9934 -- Expand_N_Qualified_Expression --
9935 -----------------------------------
9937 procedure Expand_N_Qualified_Expression (N : Node_Id) is
9938 Operand : constant Node_Id := Expression (N);
9939 Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
9941 begin
9942 -- Do validity check if validity checking operands
9944 if Validity_Checks_On and Validity_Check_Operands then
9945 Ensure_Valid (Operand);
9946 end if;
9948 -- Apply possible constraint check
9950 Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
9952 if Do_Range_Check (Operand) then
9953 Set_Do_Range_Check (Operand, False);
9954 Generate_Range_Check (Operand, Target_Type, CE_Range_Check_Failed);
9955 end if;
9956 end Expand_N_Qualified_Expression;
9958 ------------------------------------
9959 -- Expand_N_Quantified_Expression --
9960 ------------------------------------
9962 -- We expand:
9964 -- for all X in range => Cond
9966 -- into:
9968 -- T := True;
9969 -- for X in range loop
9970 -- if not Cond then
9971 -- T := False;
9972 -- exit;
9973 -- end if;
9974 -- end loop;
9976 -- Similarly, an existentially quantified expression:
9978 -- for some X in range => Cond
9980 -- becomes:
9982 -- T := False;
9983 -- for X in range loop
9984 -- if Cond then
9985 -- T := True;
9986 -- exit;
9987 -- end if;
9988 -- end loop;
9990 -- In both cases, the iteration may be over a container in which case it is
9991 -- given by an iterator specification, not a loop parameter specification.
9993 procedure Expand_N_Quantified_Expression (N : Node_Id) is
9994 Actions : constant List_Id := New_List;
9995 For_All : constant Boolean := All_Present (N);
9996 Iter_Spec : constant Node_Id := Iterator_Specification (N);
9997 Loc : constant Source_Ptr := Sloc (N);
9998 Loop_Spec : constant Node_Id := Loop_Parameter_Specification (N);
9999 Cond : Node_Id;
10000 Flag : Entity_Id;
10001 Scheme : Node_Id;
10002 Stmts : List_Id;
10004 begin
10005 -- Create the declaration of the flag which tracks the status of the
10006 -- quantified expression. Generate:
10008 -- Flag : Boolean := (True | False);
10010 Flag := Make_Temporary (Loc, 'T', N);
10012 Append_To (Actions,
10013 Make_Object_Declaration (Loc,
10014 Defining_Identifier => Flag,
10015 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
10016 Expression =>
10017 New_Occurrence_Of (Boolean_Literals (For_All), Loc)));
10019 -- Construct the circuitry which tracks the status of the quantified
10020 -- expression. Generate:
10022 -- if [not] Cond then
10023 -- Flag := (False | True);
10024 -- exit;
10025 -- end if;
10027 Cond := Relocate_Node (Condition (N));
10029 if For_All then
10030 Cond := Make_Op_Not (Loc, Cond);
10031 end if;
10033 Stmts := New_List (
10034 Make_Implicit_If_Statement (N,
10035 Condition => Cond,
10036 Then_Statements => New_List (
10037 Make_Assignment_Statement (Loc,
10038 Name => New_Occurrence_Of (Flag, Loc),
10039 Expression =>
10040 New_Occurrence_Of (Boolean_Literals (not For_All), Loc)),
10041 Make_Exit_Statement (Loc))));
10043 -- Build the loop equivalent of the quantified expression
10045 if Present (Iter_Spec) then
10046 Scheme :=
10047 Make_Iteration_Scheme (Loc,
10048 Iterator_Specification => Iter_Spec);
10049 else
10050 Scheme :=
10051 Make_Iteration_Scheme (Loc,
10052 Loop_Parameter_Specification => Loop_Spec);
10053 end if;
10055 Append_To (Actions,
10056 Make_Loop_Statement (Loc,
10057 Iteration_Scheme => Scheme,
10058 Statements => Stmts,
10059 End_Label => Empty));
10061 -- Transform the quantified expression
10063 Rewrite (N,
10064 Make_Expression_With_Actions (Loc,
10065 Expression => New_Occurrence_Of (Flag, Loc),
10066 Actions => Actions));
10067 Analyze_And_Resolve (N, Standard_Boolean);
10068 end Expand_N_Quantified_Expression;
10070 ---------------------------------
10071 -- Expand_N_Selected_Component --
10072 ---------------------------------
10074 procedure Expand_N_Selected_Component (N : Node_Id) is
10075 Loc : constant Source_Ptr := Sloc (N);
10076 Par : constant Node_Id := Parent (N);
10077 P : constant Node_Id := Prefix (N);
10078 S : constant Node_Id := Selector_Name (N);
10079 Ptyp : Entity_Id := Underlying_Type (Etype (P));
10080 Disc : Entity_Id;
10081 New_N : Node_Id;
10082 Dcon : Elmt_Id;
10083 Dval : Node_Id;
10085 function In_Left_Hand_Side (Comp : Node_Id) return Boolean;
10086 -- Gigi needs a temporary for prefixes that depend on a discriminant,
10087 -- unless the context of an assignment can provide size information.
10088 -- Don't we have a general routine that does this???
10090 function Is_Subtype_Declaration return Boolean;
10091 -- The replacement of a discriminant reference by its value is required
10092 -- if this is part of the initialization of an temporary generated by a
10093 -- change of representation. This shows up as the construction of a
10094 -- discriminant constraint for a subtype declared at the same point as
10095 -- the entity in the prefix of the selected component. We recognize this
10096 -- case when the context of the reference is:
10097 -- subtype ST is T(Obj.D);
10098 -- where the entity for Obj comes from source, and ST has the same sloc.
10100 -----------------------
10101 -- In_Left_Hand_Side --
10102 -----------------------
10104 function In_Left_Hand_Side (Comp : Node_Id) return Boolean is
10105 begin
10106 return (Nkind (Parent (Comp)) = N_Assignment_Statement
10107 and then Comp = Name (Parent (Comp)))
10108 or else (Present (Parent (Comp))
10109 and then Nkind (Parent (Comp)) in N_Subexpr
10110 and then In_Left_Hand_Side (Parent (Comp)));
10111 end In_Left_Hand_Side;
10113 -----------------------------
10114 -- Is_Subtype_Declaration --
10115 -----------------------------
10117 function Is_Subtype_Declaration return Boolean is
10118 Par : constant Node_Id := Parent (N);
10119 begin
10120 return
10121 Nkind (Par) = N_Index_Or_Discriminant_Constraint
10122 and then Nkind (Parent (Parent (Par))) = N_Subtype_Declaration
10123 and then Comes_From_Source (Entity (Prefix (N)))
10124 and then Sloc (Par) = Sloc (Entity (Prefix (N)));
10125 end Is_Subtype_Declaration;
10127 -- Start of processing for Expand_N_Selected_Component
10129 begin
10130 -- Insert explicit dereference if required
10132 if Is_Access_Type (Ptyp) then
10134 -- First set prefix type to proper access type, in case it currently
10135 -- has a private (non-access) view of this type.
10137 Set_Etype (P, Ptyp);
10139 Insert_Explicit_Dereference (P);
10140 Analyze_And_Resolve (P, Designated_Type (Ptyp));
10142 if Ekind (Etype (P)) = E_Private_Subtype
10143 and then Is_For_Access_Subtype (Etype (P))
10144 then
10145 Set_Etype (P, Base_Type (Etype (P)));
10146 end if;
10148 Ptyp := Etype (P);
10149 end if;
10151 -- Deal with discriminant check required
10153 if Do_Discriminant_Check (N) then
10154 if Present (Discriminant_Checking_Func
10155 (Original_Record_Component (Entity (S))))
10156 then
10157 -- Present the discriminant checking function to the backend, so
10158 -- that it can inline the call to the function.
10160 Add_Inlined_Body
10161 (Discriminant_Checking_Func
10162 (Original_Record_Component (Entity (S))),
10165 -- Now reset the flag and generate the call
10167 Set_Do_Discriminant_Check (N, False);
10168 Generate_Discriminant_Check (N);
10170 -- In the case of Unchecked_Union, no discriminant checking is
10171 -- actually performed.
10173 else
10174 Set_Do_Discriminant_Check (N, False);
10175 end if;
10176 end if;
10178 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10179 -- function, then additional actuals must be passed.
10181 if Is_Build_In_Place_Function_Call (P) then
10182 Make_Build_In_Place_Call_In_Anonymous_Context (P);
10184 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
10185 -- containing build-in-place function calls whose returned object covers
10186 -- interface types.
10188 elsif Present (Unqual_BIP_Iface_Function_Call (P)) then
10189 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (P);
10190 end if;
10192 -- Gigi cannot handle unchecked conversions that are the prefix of a
10193 -- selected component with discriminants. This must be checked during
10194 -- expansion, because during analysis the type of the selector is not
10195 -- known at the point the prefix is analyzed. If the conversion is the
10196 -- target of an assignment, then we cannot force the evaluation.
10198 if Nkind (Prefix (N)) = N_Unchecked_Type_Conversion
10199 and then Has_Discriminants (Etype (N))
10200 and then not In_Left_Hand_Side (N)
10201 then
10202 Force_Evaluation (Prefix (N));
10203 end if;
10205 -- Remaining processing applies only if selector is a discriminant
10207 if Ekind (Entity (Selector_Name (N))) = E_Discriminant then
10209 -- If the selector is a discriminant of a constrained record type,
10210 -- we may be able to rewrite the expression with the actual value
10211 -- of the discriminant, a useful optimization in some cases.
10213 if Is_Record_Type (Ptyp)
10214 and then Has_Discriminants (Ptyp)
10215 and then Is_Constrained (Ptyp)
10216 then
10217 -- Do this optimization for discrete types only, and not for
10218 -- access types (access discriminants get us into trouble).
10220 if not Is_Discrete_Type (Etype (N)) then
10221 null;
10223 -- Don't do this on the left-hand side of an assignment statement.
10224 -- Normally one would think that references like this would not
10225 -- occur, but they do in generated code, and mean that we really
10226 -- do want to assign the discriminant.
10228 elsif Nkind (Par) = N_Assignment_Statement
10229 and then Name (Par) = N
10230 then
10231 null;
10233 -- Don't do this optimization for the prefix of an attribute or
10234 -- the name of an object renaming declaration since these are
10235 -- contexts where we do not want the value anyway.
10237 elsif (Nkind (Par) = N_Attribute_Reference
10238 and then Prefix (Par) = N)
10239 or else Is_Renamed_Object (N)
10240 then
10241 null;
10243 -- Don't do this optimization if we are within the code for a
10244 -- discriminant check, since the whole point of such a check may
10245 -- be to verify the condition on which the code below depends.
10247 elsif Is_In_Discriminant_Check (N) then
10248 null;
10250 -- Green light to see if we can do the optimization. There is
10251 -- still one condition that inhibits the optimization below but
10252 -- now is the time to check the particular discriminant.
10254 else
10255 -- Loop through discriminants to find the matching discriminant
10256 -- constraint to see if we can copy it.
10258 Disc := First_Discriminant (Ptyp);
10259 Dcon := First_Elmt (Discriminant_Constraint (Ptyp));
10260 Discr_Loop : while Present (Dcon) loop
10261 Dval := Node (Dcon);
10263 -- Check if this is the matching discriminant and if the
10264 -- discriminant value is simple enough to make sense to
10265 -- copy. We don't want to copy complex expressions, and
10266 -- indeed to do so can cause trouble (before we put in
10267 -- this guard, a discriminant expression containing an
10268 -- AND THEN was copied, causing problems for coverage
10269 -- analysis tools).
10271 -- However, if the reference is part of the initialization
10272 -- code generated for an object declaration, we must use
10273 -- the discriminant value from the subtype constraint,
10274 -- because the selected component may be a reference to the
10275 -- object being initialized, whose discriminant is not yet
10276 -- set. This only happens in complex cases involving changes
10277 -- or representation.
10279 if Disc = Entity (Selector_Name (N))
10280 and then (Is_Entity_Name (Dval)
10281 or else Compile_Time_Known_Value (Dval)
10282 or else Is_Subtype_Declaration)
10283 then
10284 -- Here we have the matching discriminant. Check for
10285 -- the case of a discriminant of a component that is
10286 -- constrained by an outer discriminant, which cannot
10287 -- be optimized away.
10289 if Denotes_Discriminant
10290 (Dval, Check_Concurrent => True)
10291 then
10292 exit Discr_Loop;
10294 elsif Nkind (Original_Node (Dval)) = N_Selected_Component
10295 and then
10296 Denotes_Discriminant
10297 (Selector_Name (Original_Node (Dval)), True)
10298 then
10299 exit Discr_Loop;
10301 -- Do not retrieve value if constraint is not static. It
10302 -- is generally not useful, and the constraint may be a
10303 -- rewritten outer discriminant in which case it is in
10304 -- fact incorrect.
10306 elsif Is_Entity_Name (Dval)
10307 and then
10308 Nkind (Parent (Entity (Dval))) = N_Object_Declaration
10309 and then Present (Expression (Parent (Entity (Dval))))
10310 and then not
10311 Is_OK_Static_Expression
10312 (Expression (Parent (Entity (Dval))))
10313 then
10314 exit Discr_Loop;
10316 -- In the context of a case statement, the expression may
10317 -- have the base type of the discriminant, and we need to
10318 -- preserve the constraint to avoid spurious errors on
10319 -- missing cases.
10321 elsif Nkind (Parent (N)) = N_Case_Statement
10322 and then Etype (Dval) /= Etype (Disc)
10323 then
10324 Rewrite (N,
10325 Make_Qualified_Expression (Loc,
10326 Subtype_Mark =>
10327 New_Occurrence_Of (Etype (Disc), Loc),
10328 Expression =>
10329 New_Copy_Tree (Dval)));
10330 Analyze_And_Resolve (N, Etype (Disc));
10332 -- In case that comes out as a static expression,
10333 -- reset it (a selected component is never static).
10335 Set_Is_Static_Expression (N, False);
10336 return;
10338 -- Otherwise we can just copy the constraint, but the
10339 -- result is certainly not static. In some cases the
10340 -- discriminant constraint has been analyzed in the
10341 -- context of the original subtype indication, but for
10342 -- itypes the constraint might not have been analyzed
10343 -- yet, and this must be done now.
10345 else
10346 Rewrite (N, New_Copy_Tree (Dval));
10347 Analyze_And_Resolve (N);
10348 Set_Is_Static_Expression (N, False);
10349 return;
10350 end if;
10351 end if;
10353 Next_Elmt (Dcon);
10354 Next_Discriminant (Disc);
10355 end loop Discr_Loop;
10357 -- Note: the above loop should always find a matching
10358 -- discriminant, but if it does not, we just missed an
10359 -- optimization due to some glitch (perhaps a previous
10360 -- error), so ignore.
10362 end if;
10363 end if;
10365 -- The only remaining processing is in the case of a discriminant of
10366 -- a concurrent object, where we rewrite the prefix to denote the
10367 -- corresponding record type. If the type is derived and has renamed
10368 -- discriminants, use corresponding discriminant, which is the one
10369 -- that appears in the corresponding record.
10371 if not Is_Concurrent_Type (Ptyp) then
10372 return;
10373 end if;
10375 Disc := Entity (Selector_Name (N));
10377 if Is_Derived_Type (Ptyp)
10378 and then Present (Corresponding_Discriminant (Disc))
10379 then
10380 Disc := Corresponding_Discriminant (Disc);
10381 end if;
10383 New_N :=
10384 Make_Selected_Component (Loc,
10385 Prefix =>
10386 Unchecked_Convert_To (Corresponding_Record_Type (Ptyp),
10387 New_Copy_Tree (P)),
10388 Selector_Name => Make_Identifier (Loc, Chars (Disc)));
10390 Rewrite (N, New_N);
10391 Analyze (N);
10392 end if;
10394 -- Set Atomic_Sync_Required if necessary for atomic component
10396 if Nkind (N) = N_Selected_Component then
10397 declare
10398 E : constant Entity_Id := Entity (Selector_Name (N));
10399 Set : Boolean;
10401 begin
10402 -- If component is atomic, but type is not, setting depends on
10403 -- disable/enable state for the component.
10405 if Is_Atomic (E) and then not Is_Atomic (Etype (E)) then
10406 Set := not Atomic_Synchronization_Disabled (E);
10408 -- If component is not atomic, but its type is atomic, setting
10409 -- depends on disable/enable state for the type.
10411 elsif not Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10412 Set := not Atomic_Synchronization_Disabled (Etype (E));
10414 -- If both component and type are atomic, we disable if either
10415 -- component or its type have sync disabled.
10417 elsif Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10418 Set := (not Atomic_Synchronization_Disabled (E))
10419 and then
10420 (not Atomic_Synchronization_Disabled (Etype (E)));
10422 else
10423 Set := False;
10424 end if;
10426 -- Set flag if required
10428 if Set then
10429 Activate_Atomic_Synchronization (N);
10430 end if;
10431 end;
10432 end if;
10433 end Expand_N_Selected_Component;
10435 --------------------
10436 -- Expand_N_Slice --
10437 --------------------
10439 procedure Expand_N_Slice (N : Node_Id) is
10440 Loc : constant Source_Ptr := Sloc (N);
10441 Typ : constant Entity_Id := Etype (N);
10443 function Is_Procedure_Actual (N : Node_Id) return Boolean;
10444 -- Check whether the argument is an actual for a procedure call, in
10445 -- which case the expansion of a bit-packed slice is deferred until the
10446 -- call itself is expanded. The reason this is required is that we might
10447 -- have an IN OUT or OUT parameter, and the copy out is essential, and
10448 -- that copy out would be missed if we created a temporary here in
10449 -- Expand_N_Slice. Note that we don't bother to test specifically for an
10450 -- IN OUT or OUT mode parameter, since it is a bit tricky to do, and it
10451 -- is harmless to defer expansion in the IN case, since the call
10452 -- processing will still generate the appropriate copy in operation,
10453 -- which will take care of the slice.
10455 procedure Make_Temporary_For_Slice;
10456 -- Create a named variable for the value of the slice, in cases where
10457 -- the back end cannot handle it properly, e.g. when packed types or
10458 -- unaligned slices are involved.
10460 -------------------------
10461 -- Is_Procedure_Actual --
10462 -------------------------
10464 function Is_Procedure_Actual (N : Node_Id) return Boolean is
10465 Par : Node_Id := Parent (N);
10467 begin
10468 loop
10469 -- If our parent is a procedure call we can return
10471 if Nkind (Par) = N_Procedure_Call_Statement then
10472 return True;
10474 -- If our parent is a type conversion, keep climbing the tree,
10475 -- since a type conversion can be a procedure actual. Also keep
10476 -- climbing if parameter association or a qualified expression,
10477 -- since these are additional cases that do can appear on
10478 -- procedure actuals.
10480 elsif Nkind_In (Par, N_Type_Conversion,
10481 N_Parameter_Association,
10482 N_Qualified_Expression)
10483 then
10484 Par := Parent (Par);
10486 -- Any other case is not what we are looking for
10488 else
10489 return False;
10490 end if;
10491 end loop;
10492 end Is_Procedure_Actual;
10494 ------------------------------
10495 -- Make_Temporary_For_Slice --
10496 ------------------------------
10498 procedure Make_Temporary_For_Slice is
10499 Ent : constant Entity_Id := Make_Temporary (Loc, 'T', N);
10500 Decl : Node_Id;
10502 begin
10503 Decl :=
10504 Make_Object_Declaration (Loc,
10505 Defining_Identifier => Ent,
10506 Object_Definition => New_Occurrence_Of (Typ, Loc));
10508 Set_No_Initialization (Decl);
10510 Insert_Actions (N, New_List (
10511 Decl,
10512 Make_Assignment_Statement (Loc,
10513 Name => New_Occurrence_Of (Ent, Loc),
10514 Expression => Relocate_Node (N))));
10516 Rewrite (N, New_Occurrence_Of (Ent, Loc));
10517 Analyze_And_Resolve (N, Typ);
10518 end Make_Temporary_For_Slice;
10520 -- Local variables
10522 Pref : constant Node_Id := Prefix (N);
10523 Pref_Typ : Entity_Id := Etype (Pref);
10525 -- Start of processing for Expand_N_Slice
10527 begin
10528 -- Special handling for access types
10530 if Is_Access_Type (Pref_Typ) then
10531 Pref_Typ := Designated_Type (Pref_Typ);
10533 Rewrite (Pref,
10534 Make_Explicit_Dereference (Sloc (N),
10535 Prefix => Relocate_Node (Pref)));
10537 Analyze_And_Resolve (Pref, Pref_Typ);
10538 end if;
10540 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10541 -- function, then additional actuals must be passed.
10543 if Is_Build_In_Place_Function_Call (Pref) then
10544 Make_Build_In_Place_Call_In_Anonymous_Context (Pref);
10546 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
10547 -- containing build-in-place function calls whose returned object covers
10548 -- interface types.
10550 elsif Present (Unqual_BIP_Iface_Function_Call (Pref)) then
10551 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (Pref);
10552 end if;
10554 -- The remaining case to be handled is packed slices. We can leave
10555 -- packed slices as they are in the following situations:
10557 -- 1. Right or left side of an assignment (we can handle this
10558 -- situation correctly in the assignment statement expansion).
10560 -- 2. Prefix of indexed component (the slide is optimized away in this
10561 -- case, see the start of Expand_N_Slice.)
10563 -- 3. Object renaming declaration, since we want the name of the
10564 -- slice, not the value.
10566 -- 4. Argument to procedure call, since copy-in/copy-out handling may
10567 -- be required, and this is handled in the expansion of call
10568 -- itself.
10570 -- 5. Prefix of an address attribute (this is an error which is caught
10571 -- elsewhere, and the expansion would interfere with generating the
10572 -- error message).
10574 if not Is_Packed (Typ) then
10576 -- Apply transformation for actuals of a function call, where
10577 -- Expand_Actuals is not used.
10579 if Nkind (Parent (N)) = N_Function_Call
10580 and then Is_Possibly_Unaligned_Slice (N)
10581 then
10582 Make_Temporary_For_Slice;
10583 end if;
10585 elsif Nkind (Parent (N)) = N_Assignment_Statement
10586 or else (Nkind (Parent (Parent (N))) = N_Assignment_Statement
10587 and then Parent (N) = Name (Parent (Parent (N))))
10588 then
10589 return;
10591 elsif Nkind (Parent (N)) = N_Indexed_Component
10592 or else Is_Renamed_Object (N)
10593 or else Is_Procedure_Actual (N)
10594 then
10595 return;
10597 elsif Nkind (Parent (N)) = N_Attribute_Reference
10598 and then Attribute_Name (Parent (N)) = Name_Address
10599 then
10600 return;
10602 else
10603 Make_Temporary_For_Slice;
10604 end if;
10605 end Expand_N_Slice;
10607 ------------------------------
10608 -- Expand_N_Type_Conversion --
10609 ------------------------------
10611 procedure Expand_N_Type_Conversion (N : Node_Id) is
10612 Loc : constant Source_Ptr := Sloc (N);
10613 Operand : constant Node_Id := Expression (N);
10614 Target_Type : constant Entity_Id := Etype (N);
10615 Operand_Type : Entity_Id := Etype (Operand);
10617 procedure Handle_Changed_Representation;
10618 -- This is called in the case of record and array type conversions to
10619 -- see if there is a change of representation to be handled. Change of
10620 -- representation is actually handled at the assignment statement level,
10621 -- and what this procedure does is rewrite node N conversion as an
10622 -- assignment to temporary. If there is no change of representation,
10623 -- then the conversion node is unchanged.
10625 procedure Raise_Accessibility_Error;
10626 -- Called when we know that an accessibility check will fail. Rewrites
10627 -- node N to an appropriate raise statement and outputs warning msgs.
10628 -- The Etype of the raise node is set to Target_Type. Note that in this
10629 -- case the rest of the processing should be skipped (i.e. the call to
10630 -- this procedure will be followed by "goto Done").
10632 procedure Real_Range_Check;
10633 -- Handles generation of range check for real target value
10635 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean;
10636 -- True iff Present (Effective_Extra_Accessibility (Id)) successfully
10637 -- evaluates to True.
10639 -----------------------------------
10640 -- Handle_Changed_Representation --
10641 -----------------------------------
10643 procedure Handle_Changed_Representation is
10644 Temp : Entity_Id;
10645 Decl : Node_Id;
10646 Odef : Node_Id;
10647 N_Ix : Node_Id;
10648 Cons : List_Id;
10650 begin
10651 -- Nothing else to do if no change of representation
10653 if Same_Representation (Operand_Type, Target_Type) then
10654 return;
10656 -- The real change of representation work is done by the assignment
10657 -- statement processing. So if this type conversion is appearing as
10658 -- the expression of an assignment statement, nothing needs to be
10659 -- done to the conversion.
10661 elsif Nkind (Parent (N)) = N_Assignment_Statement then
10662 return;
10664 -- Otherwise we need to generate a temporary variable, and do the
10665 -- change of representation assignment into that temporary variable.
10666 -- The conversion is then replaced by a reference to this variable.
10668 else
10669 Cons := No_List;
10671 -- If type is unconstrained we have to add a constraint, copied
10672 -- from the actual value of the left-hand side.
10674 if not Is_Constrained (Target_Type) then
10675 if Has_Discriminants (Operand_Type) then
10677 -- A change of representation can only apply to untagged
10678 -- types. We need to build the constraint that applies to
10679 -- the target type, using the constraints of the operand.
10680 -- The analysis is complicated if there are both inherited
10681 -- discriminants and constrained discriminants.
10682 -- We iterate over the discriminants of the target, and
10683 -- find the discriminant of the same name:
10685 -- a) If there is a corresponding discriminant in the object
10686 -- then the value is a selected component of the operand.
10688 -- b) Otherwise the value of a constrained discriminant is
10689 -- found in the stored constraint of the operand.
10691 declare
10692 Stored : constant Elist_Id :=
10693 Stored_Constraint (Operand_Type);
10695 Elmt : Elmt_Id;
10697 Disc_O : Entity_Id;
10698 -- Discriminant of the operand type. Its value in the
10699 -- object is captured in a selected component.
10701 Disc_S : Entity_Id;
10702 -- Stored discriminant of the operand. If present, it
10703 -- corresponds to a constrained discriminant of the
10704 -- parent type.
10706 Disc_T : Entity_Id;
10707 -- Discriminant of the target type
10709 begin
10710 Disc_T := First_Discriminant (Target_Type);
10711 Disc_O := First_Discriminant (Operand_Type);
10712 Disc_S := First_Stored_Discriminant (Operand_Type);
10714 if Present (Stored) then
10715 Elmt := First_Elmt (Stored);
10716 else
10717 Elmt := No_Elmt; -- init to avoid warning
10718 end if;
10720 Cons := New_List;
10721 while Present (Disc_T) loop
10722 if Present (Disc_O)
10723 and then Chars (Disc_T) = Chars (Disc_O)
10724 then
10725 Append_To (Cons,
10726 Make_Selected_Component (Loc,
10727 Prefix =>
10728 Duplicate_Subexpr_Move_Checks (Operand),
10729 Selector_Name =>
10730 Make_Identifier (Loc, Chars (Disc_O))));
10731 Next_Discriminant (Disc_O);
10733 elsif Present (Disc_S) then
10734 Append_To (Cons, New_Copy_Tree (Node (Elmt)));
10735 Next_Elmt (Elmt);
10736 end if;
10738 Next_Discriminant (Disc_T);
10739 end loop;
10740 end;
10742 elsif Is_Array_Type (Operand_Type) then
10743 N_Ix := First_Index (Target_Type);
10744 Cons := New_List;
10746 for J in 1 .. Number_Dimensions (Operand_Type) loop
10748 -- We convert the bounds explicitly. We use an unchecked
10749 -- conversion because bounds checks are done elsewhere.
10751 Append_To (Cons,
10752 Make_Range (Loc,
10753 Low_Bound =>
10754 Unchecked_Convert_To (Etype (N_Ix),
10755 Make_Attribute_Reference (Loc,
10756 Prefix =>
10757 Duplicate_Subexpr_No_Checks
10758 (Operand, Name_Req => True),
10759 Attribute_Name => Name_First,
10760 Expressions => New_List (
10761 Make_Integer_Literal (Loc, J)))),
10763 High_Bound =>
10764 Unchecked_Convert_To (Etype (N_Ix),
10765 Make_Attribute_Reference (Loc,
10766 Prefix =>
10767 Duplicate_Subexpr_No_Checks
10768 (Operand, Name_Req => True),
10769 Attribute_Name => Name_Last,
10770 Expressions => New_List (
10771 Make_Integer_Literal (Loc, J))))));
10773 Next_Index (N_Ix);
10774 end loop;
10775 end if;
10776 end if;
10778 Odef := New_Occurrence_Of (Target_Type, Loc);
10780 if Present (Cons) then
10781 Odef :=
10782 Make_Subtype_Indication (Loc,
10783 Subtype_Mark => Odef,
10784 Constraint =>
10785 Make_Index_Or_Discriminant_Constraint (Loc,
10786 Constraints => Cons));
10787 end if;
10789 Temp := Make_Temporary (Loc, 'C');
10790 Decl :=
10791 Make_Object_Declaration (Loc,
10792 Defining_Identifier => Temp,
10793 Object_Definition => Odef);
10795 Set_No_Initialization (Decl, True);
10797 -- Insert required actions. It is essential to suppress checks
10798 -- since we have suppressed default initialization, which means
10799 -- that the variable we create may have no discriminants.
10801 Insert_Actions (N,
10802 New_List (
10803 Decl,
10804 Make_Assignment_Statement (Loc,
10805 Name => New_Occurrence_Of (Temp, Loc),
10806 Expression => Relocate_Node (N))),
10807 Suppress => All_Checks);
10809 Rewrite (N, New_Occurrence_Of (Temp, Loc));
10810 return;
10811 end if;
10812 end Handle_Changed_Representation;
10814 -------------------------------
10815 -- Raise_Accessibility_Error --
10816 -------------------------------
10818 procedure Raise_Accessibility_Error is
10819 begin
10820 Error_Msg_Warn := SPARK_Mode /= On;
10821 Rewrite (N,
10822 Make_Raise_Program_Error (Sloc (N),
10823 Reason => PE_Accessibility_Check_Failed));
10824 Set_Etype (N, Target_Type);
10826 Error_Msg_N ("<<accessibility check failure", N);
10827 Error_Msg_NE ("\<<& [", N, Standard_Program_Error);
10828 end Raise_Accessibility_Error;
10830 ----------------------
10831 -- Real_Range_Check --
10832 ----------------------
10834 -- Case of conversions to floating-point or fixed-point. If range checks
10835 -- are enabled and the target type has a range constraint, we convert:
10837 -- typ (x)
10839 -- to
10841 -- Tnn : typ'Base := typ'Base (x);
10842 -- [constraint_error when Tnn < typ'First or else Tnn > typ'Last]
10843 -- Tnn
10845 -- This is necessary when there is a conversion of integer to float or
10846 -- to fixed-point to ensure that the correct checks are made. It is not
10847 -- necessary for float to float where it is enough to simply set the
10848 -- Do_Range_Check flag.
10850 procedure Real_Range_Check is
10851 Btyp : constant Entity_Id := Base_Type (Target_Type);
10852 Lo : constant Node_Id := Type_Low_Bound (Target_Type);
10853 Hi : constant Node_Id := Type_High_Bound (Target_Type);
10854 Xtyp : constant Entity_Id := Etype (Operand);
10855 Conv : Node_Id;
10856 Tnn : Entity_Id;
10858 begin
10859 -- Nothing to do if conversion was rewritten
10861 if Nkind (N) /= N_Type_Conversion then
10862 return;
10863 end if;
10865 -- Nothing to do if range checks suppressed, or target has the same
10866 -- range as the base type (or is the base type).
10868 if Range_Checks_Suppressed (Target_Type)
10869 or else (Lo = Type_Low_Bound (Btyp)
10870 and then
10871 Hi = Type_High_Bound (Btyp))
10872 then
10873 return;
10874 end if;
10876 -- Nothing to do if expression is an entity on which checks have been
10877 -- suppressed.
10879 if Is_Entity_Name (Operand)
10880 and then Range_Checks_Suppressed (Entity (Operand))
10881 then
10882 return;
10883 end if;
10885 -- Nothing to do if bounds are all static and we can tell that the
10886 -- expression is within the bounds of the target. Note that if the
10887 -- operand is of an unconstrained floating-point type, then we do
10888 -- not trust it to be in range (might be infinite)
10890 declare
10891 S_Lo : constant Node_Id := Type_Low_Bound (Xtyp);
10892 S_Hi : constant Node_Id := Type_High_Bound (Xtyp);
10894 begin
10895 if (not Is_Floating_Point_Type (Xtyp)
10896 or else Is_Constrained (Xtyp))
10897 and then Compile_Time_Known_Value (S_Lo)
10898 and then Compile_Time_Known_Value (S_Hi)
10899 and then Compile_Time_Known_Value (Hi)
10900 and then Compile_Time_Known_Value (Lo)
10901 then
10902 declare
10903 D_Lov : constant Ureal := Expr_Value_R (Lo);
10904 D_Hiv : constant Ureal := Expr_Value_R (Hi);
10905 S_Lov : Ureal;
10906 S_Hiv : Ureal;
10908 begin
10909 if Is_Real_Type (Xtyp) then
10910 S_Lov := Expr_Value_R (S_Lo);
10911 S_Hiv := Expr_Value_R (S_Hi);
10912 else
10913 S_Lov := UR_From_Uint (Expr_Value (S_Lo));
10914 S_Hiv := UR_From_Uint (Expr_Value (S_Hi));
10915 end if;
10917 if D_Hiv > D_Lov
10918 and then S_Lov >= D_Lov
10919 and then S_Hiv <= D_Hiv
10920 then
10921 -- Unset the range check flag on the current value of
10922 -- Expression (N), since the captured Operand may have
10923 -- been rewritten (such as for the case of a conversion
10924 -- to a fixed-point type).
10926 Set_Do_Range_Check (Expression (N), False);
10928 return;
10929 end if;
10930 end;
10931 end if;
10932 end;
10934 -- For float to float conversions, we are done
10936 if Is_Floating_Point_Type (Xtyp)
10937 and then
10938 Is_Floating_Point_Type (Btyp)
10939 then
10940 return;
10941 end if;
10943 -- Otherwise rewrite the conversion as described above
10945 Conv := Relocate_Node (N);
10946 Rewrite (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
10947 Set_Etype (Conv, Btyp);
10949 -- Enable overflow except for case of integer to float conversions,
10950 -- where it is never required, since we can never have overflow in
10951 -- this case.
10953 if not Is_Integer_Type (Etype (Operand)) then
10954 Enable_Overflow_Check (Conv);
10955 end if;
10957 Tnn := Make_Temporary (Loc, 'T', Conv);
10959 Insert_Actions (N, New_List (
10960 Make_Object_Declaration (Loc,
10961 Defining_Identifier => Tnn,
10962 Object_Definition => New_Occurrence_Of (Btyp, Loc),
10963 Constant_Present => True,
10964 Expression => Conv),
10966 Make_Raise_Constraint_Error (Loc,
10967 Condition =>
10968 Make_Or_Else (Loc,
10969 Left_Opnd =>
10970 Make_Op_Lt (Loc,
10971 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
10972 Right_Opnd =>
10973 Make_Attribute_Reference (Loc,
10974 Attribute_Name => Name_First,
10975 Prefix =>
10976 New_Occurrence_Of (Target_Type, Loc))),
10978 Right_Opnd =>
10979 Make_Op_Gt (Loc,
10980 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
10981 Right_Opnd =>
10982 Make_Attribute_Reference (Loc,
10983 Attribute_Name => Name_Last,
10984 Prefix =>
10985 New_Occurrence_Of (Target_Type, Loc)))),
10986 Reason => CE_Range_Check_Failed)));
10988 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
10989 Analyze_And_Resolve (N, Btyp);
10990 end Real_Range_Check;
10992 -----------------------------
10993 -- Has_Extra_Accessibility --
10994 -----------------------------
10996 -- Returns true for a formal of an anonymous access type or for
10997 -- an Ada 2012-style stand-alone object of an anonymous access type.
10999 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean is
11000 begin
11001 if Is_Formal (Id) or else Ekind_In (Id, E_Constant, E_Variable) then
11002 return Present (Effective_Extra_Accessibility (Id));
11003 else
11004 return False;
11005 end if;
11006 end Has_Extra_Accessibility;
11008 -- Start of processing for Expand_N_Type_Conversion
11010 begin
11011 -- First remove check marks put by the semantic analysis on the type
11012 -- conversion between array types. We need these checks, and they will
11013 -- be generated by this expansion routine, but we do not depend on these
11014 -- flags being set, and since we do intend to expand the checks in the
11015 -- front end, we don't want them on the tree passed to the back end.
11017 if Is_Array_Type (Target_Type) then
11018 if Is_Constrained (Target_Type) then
11019 Set_Do_Length_Check (N, False);
11020 else
11021 Set_Do_Range_Check (Operand, False);
11022 end if;
11023 end if;
11025 -- Nothing at all to do if conversion is to the identical type so remove
11026 -- the conversion completely, it is useless, except that it may carry
11027 -- an Assignment_OK attribute, which must be propagated to the operand.
11029 if Operand_Type = Target_Type then
11030 if Assignment_OK (N) then
11031 Set_Assignment_OK (Operand);
11032 end if;
11034 Rewrite (N, Relocate_Node (Operand));
11035 goto Done;
11036 end if;
11038 -- Nothing to do if this is the second argument of read. This is a
11039 -- "backwards" conversion that will be handled by the specialized code
11040 -- in attribute processing.
11042 if Nkind (Parent (N)) = N_Attribute_Reference
11043 and then Attribute_Name (Parent (N)) = Name_Read
11044 and then Next (First (Expressions (Parent (N)))) = N
11045 then
11046 goto Done;
11047 end if;
11049 -- Check for case of converting to a type that has an invariant
11050 -- associated with it. This requires an invariant check. We insert
11051 -- a call:
11053 -- invariant_check (typ (expr))
11055 -- in the code, after removing side effects from the expression.
11056 -- This is clearer than replacing the conversion into an expression
11057 -- with actions, because the context may impose additional actions
11058 -- (tag checks, membership tests, etc.) that conflict with this
11059 -- rewriting (used previously).
11061 -- Note: the Comes_From_Source check, and then the resetting of this
11062 -- flag prevents what would otherwise be an infinite recursion.
11064 if Has_Invariants (Target_Type)
11065 and then Present (Invariant_Procedure (Target_Type))
11066 and then Comes_From_Source (N)
11067 then
11068 Set_Comes_From_Source (N, False);
11069 Remove_Side_Effects (N);
11070 Insert_Action (N, Make_Invariant_Call (Duplicate_Subexpr (N)));
11071 goto Done;
11072 end if;
11074 -- Here if we may need to expand conversion
11076 -- If the operand of the type conversion is an arithmetic operation on
11077 -- signed integers, and the based type of the signed integer type in
11078 -- question is smaller than Standard.Integer, we promote both of the
11079 -- operands to type Integer.
11081 -- For example, if we have
11083 -- target-type (opnd1 + opnd2)
11085 -- and opnd1 and opnd2 are of type short integer, then we rewrite
11086 -- this as:
11088 -- target-type (integer(opnd1) + integer(opnd2))
11090 -- We do this because we are always allowed to compute in a larger type
11091 -- if we do the right thing with the result, and in this case we are
11092 -- going to do a conversion which will do an appropriate check to make
11093 -- sure that things are in range of the target type in any case. This
11094 -- avoids some unnecessary intermediate overflows.
11096 -- We might consider a similar transformation in the case where the
11097 -- target is a real type or a 64-bit integer type, and the operand
11098 -- is an arithmetic operation using a 32-bit integer type. However,
11099 -- we do not bother with this case, because it could cause significant
11100 -- inefficiencies on 32-bit machines. On a 64-bit machine it would be
11101 -- much cheaper, but we don't want different behavior on 32-bit and
11102 -- 64-bit machines. Note that the exclusion of the 64-bit case also
11103 -- handles the configurable run-time cases where 64-bit arithmetic
11104 -- may simply be unavailable.
11106 -- Note: this circuit is partially redundant with respect to the circuit
11107 -- in Checks.Apply_Arithmetic_Overflow_Check, but we catch more cases in
11108 -- the processing here. Also we still need the Checks circuit, since we
11109 -- have to be sure not to generate junk overflow checks in the first
11110 -- place, since it would be trick to remove them here.
11112 if Integer_Promotion_Possible (N) then
11114 -- All conditions met, go ahead with transformation
11116 declare
11117 Opnd : Node_Id;
11118 L, R : Node_Id;
11120 begin
11121 R :=
11122 Make_Type_Conversion (Loc,
11123 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11124 Expression => Relocate_Node (Right_Opnd (Operand)));
11126 Opnd := New_Op_Node (Nkind (Operand), Loc);
11127 Set_Right_Opnd (Opnd, R);
11129 if Nkind (Operand) in N_Binary_Op then
11130 L :=
11131 Make_Type_Conversion (Loc,
11132 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11133 Expression => Relocate_Node (Left_Opnd (Operand)));
11135 Set_Left_Opnd (Opnd, L);
11136 end if;
11138 Rewrite (N,
11139 Make_Type_Conversion (Loc,
11140 Subtype_Mark => Relocate_Node (Subtype_Mark (N)),
11141 Expression => Opnd));
11143 Analyze_And_Resolve (N, Target_Type);
11144 goto Done;
11145 end;
11146 end if;
11148 -- Do validity check if validity checking operands
11150 if Validity_Checks_On and Validity_Check_Operands then
11151 Ensure_Valid (Operand);
11152 end if;
11154 -- Special case of converting from non-standard boolean type
11156 if Is_Boolean_Type (Operand_Type)
11157 and then (Nonzero_Is_True (Operand_Type))
11158 then
11159 Adjust_Condition (Operand);
11160 Set_Etype (Operand, Standard_Boolean);
11161 Operand_Type := Standard_Boolean;
11162 end if;
11164 -- Case of converting to an access type
11166 if Is_Access_Type (Target_Type) then
11168 -- If this type conversion was internally generated by the front end
11169 -- to displace the pointer to the object to reference an interface
11170 -- type and the original node was an Unrestricted_Access attribute,
11171 -- then skip applying accessibility checks (because, according to the
11172 -- GNAT Reference Manual, this attribute is similar to 'Access except
11173 -- that all accessibility and aliased view checks are omitted).
11175 if not Comes_From_Source (N)
11176 and then Is_Interface (Designated_Type (Target_Type))
11177 and then Nkind (Original_Node (N)) = N_Attribute_Reference
11178 and then Attribute_Name (Original_Node (N)) =
11179 Name_Unrestricted_Access
11180 then
11181 null;
11183 -- Apply an accessibility check when the conversion operand is an
11184 -- access parameter (or a renaming thereof), unless conversion was
11185 -- expanded from an Unchecked_ or Unrestricted_Access attribute,
11186 -- or for the actual of a class-wide interface parameter. Note that
11187 -- other checks may still need to be applied below (such as tagged
11188 -- type checks).
11190 elsif Is_Entity_Name (Operand)
11191 and then Has_Extra_Accessibility (Entity (Operand))
11192 and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
11193 and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
11194 or else Attribute_Name (Original_Node (N)) = Name_Access)
11195 then
11196 if not Comes_From_Source (N)
11197 and then Nkind_In (Parent (N), N_Function_Call,
11198 N_Procedure_Call_Statement)
11199 and then Is_Interface (Designated_Type (Target_Type))
11200 and then Is_Class_Wide_Type (Designated_Type (Target_Type))
11201 then
11202 null;
11204 else
11205 Apply_Accessibility_Check
11206 (Operand, Target_Type, Insert_Node => Operand);
11207 end if;
11209 -- If the level of the operand type is statically deeper than the
11210 -- level of the target type, then force Program_Error. Note that this
11211 -- can only occur for cases where the attribute is within the body of
11212 -- an instantiation, otherwise the conversion will already have been
11213 -- rejected as illegal.
11215 -- Note: warnings are issued by the analyzer for the instance cases
11217 elsif In_Instance_Body
11219 -- The case where the target type is an anonymous access type of
11220 -- a discriminant is excluded, because the level of such a type
11221 -- depends on the context and currently the level returned for such
11222 -- types is zero, resulting in warnings about about check failures
11223 -- in certain legal cases involving class-wide interfaces as the
11224 -- designated type (some cases, such as return statements, are
11225 -- checked at run time, but not clear if these are handled right
11226 -- in general, see 3.10.2(12/2-12.5/3) ???).
11228 and then
11229 not (Ekind (Target_Type) = E_Anonymous_Access_Type
11230 and then Present (Associated_Node_For_Itype (Target_Type))
11231 and then Nkind (Associated_Node_For_Itype (Target_Type)) =
11232 N_Discriminant_Specification)
11233 and then
11234 Type_Access_Level (Operand_Type) > Type_Access_Level (Target_Type)
11235 then
11236 Raise_Accessibility_Error;
11237 goto Done;
11239 -- When the operand is a selected access discriminant the check needs
11240 -- to be made against the level of the object denoted by the prefix
11241 -- of the selected name. Force Program_Error for this case as well
11242 -- (this accessibility violation can only happen if within the body
11243 -- of an instantiation).
11245 elsif In_Instance_Body
11246 and then Ekind (Operand_Type) = E_Anonymous_Access_Type
11247 and then Nkind (Operand) = N_Selected_Component
11248 and then Ekind (Entity (Selector_Name (Operand))) = E_Discriminant
11249 and then Object_Access_Level (Operand) >
11250 Type_Access_Level (Target_Type)
11251 then
11252 Raise_Accessibility_Error;
11253 goto Done;
11254 end if;
11255 end if;
11257 -- Case of conversions of tagged types and access to tagged types
11259 -- When needed, that is to say when the expression is class-wide, Add
11260 -- runtime a tag check for (strict) downward conversion by using the
11261 -- membership test, generating:
11263 -- [constraint_error when Operand not in Target_Type'Class]
11265 -- or in the access type case
11267 -- [constraint_error
11268 -- when Operand /= null
11269 -- and then Operand.all not in
11270 -- Designated_Type (Target_Type)'Class]
11272 if (Is_Access_Type (Target_Type)
11273 and then Is_Tagged_Type (Designated_Type (Target_Type)))
11274 or else Is_Tagged_Type (Target_Type)
11275 then
11276 -- Do not do any expansion in the access type case if the parent is a
11277 -- renaming, since this is an error situation which will be caught by
11278 -- Sem_Ch8, and the expansion can interfere with this error check.
11280 if Is_Access_Type (Target_Type) and then Is_Renamed_Object (N) then
11281 goto Done;
11282 end if;
11284 -- Otherwise, proceed with processing tagged conversion
11286 Tagged_Conversion : declare
11287 Actual_Op_Typ : Entity_Id;
11288 Actual_Targ_Typ : Entity_Id;
11289 Make_Conversion : Boolean := False;
11290 Root_Op_Typ : Entity_Id;
11292 procedure Make_Tag_Check (Targ_Typ : Entity_Id);
11293 -- Create a membership check to test whether Operand is a member
11294 -- of Targ_Typ. If the original Target_Type is an access, include
11295 -- a test for null value. The check is inserted at N.
11297 --------------------
11298 -- Make_Tag_Check --
11299 --------------------
11301 procedure Make_Tag_Check (Targ_Typ : Entity_Id) is
11302 Cond : Node_Id;
11304 begin
11305 -- Generate:
11306 -- [Constraint_Error
11307 -- when Operand /= null
11308 -- and then Operand.all not in Targ_Typ]
11310 if Is_Access_Type (Target_Type) then
11311 Cond :=
11312 Make_And_Then (Loc,
11313 Left_Opnd =>
11314 Make_Op_Ne (Loc,
11315 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11316 Right_Opnd => Make_Null (Loc)),
11318 Right_Opnd =>
11319 Make_Not_In (Loc,
11320 Left_Opnd =>
11321 Make_Explicit_Dereference (Loc,
11322 Prefix => Duplicate_Subexpr_No_Checks (Operand)),
11323 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc)));
11325 -- Generate:
11326 -- [Constraint_Error when Operand not in Targ_Typ]
11328 else
11329 Cond :=
11330 Make_Not_In (Loc,
11331 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11332 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc));
11333 end if;
11335 Insert_Action (N,
11336 Make_Raise_Constraint_Error (Loc,
11337 Condition => Cond,
11338 Reason => CE_Tag_Check_Failed),
11339 Suppress => All_Checks);
11340 end Make_Tag_Check;
11342 -- Start of processing for Tagged_Conversion
11344 begin
11345 -- Handle entities from the limited view
11347 if Is_Access_Type (Operand_Type) then
11348 Actual_Op_Typ :=
11349 Available_View (Designated_Type (Operand_Type));
11350 else
11351 Actual_Op_Typ := Operand_Type;
11352 end if;
11354 if Is_Access_Type (Target_Type) then
11355 Actual_Targ_Typ :=
11356 Available_View (Designated_Type (Target_Type));
11357 else
11358 Actual_Targ_Typ := Target_Type;
11359 end if;
11361 Root_Op_Typ := Root_Type (Actual_Op_Typ);
11363 -- Ada 2005 (AI-251): Handle interface type conversion
11365 if Is_Interface (Actual_Op_Typ)
11366 or else
11367 Is_Interface (Actual_Targ_Typ)
11368 then
11369 Expand_Interface_Conversion (N);
11370 goto Done;
11371 end if;
11373 if not Tag_Checks_Suppressed (Actual_Targ_Typ) then
11375 -- Create a runtime tag check for a downward class-wide type
11376 -- conversion.
11378 if Is_Class_Wide_Type (Actual_Op_Typ)
11379 and then Actual_Op_Typ /= Actual_Targ_Typ
11380 and then Root_Op_Typ /= Actual_Targ_Typ
11381 and then Is_Ancestor (Root_Op_Typ, Actual_Targ_Typ,
11382 Use_Full_View => True)
11383 then
11384 Make_Tag_Check (Class_Wide_Type (Actual_Targ_Typ));
11385 Make_Conversion := True;
11386 end if;
11388 -- AI05-0073: If the result subtype of the function is defined
11389 -- by an access_definition designating a specific tagged type
11390 -- T, a check is made that the result value is null or the tag
11391 -- of the object designated by the result value identifies T.
11392 -- Constraint_Error is raised if this check fails.
11394 if Nkind (Parent (N)) = N_Simple_Return_Statement then
11395 declare
11396 Func : Entity_Id;
11397 Func_Typ : Entity_Id;
11399 begin
11400 -- Climb scope stack looking for the enclosing function
11402 Func := Current_Scope;
11403 while Present (Func)
11404 and then Ekind (Func) /= E_Function
11405 loop
11406 Func := Scope (Func);
11407 end loop;
11409 -- The function's return subtype must be defined using
11410 -- an access definition.
11412 if Nkind (Result_Definition (Parent (Func))) =
11413 N_Access_Definition
11414 then
11415 Func_Typ := Directly_Designated_Type (Etype (Func));
11417 -- The return subtype denotes a specific tagged type,
11418 -- in other words, a non class-wide type.
11420 if Is_Tagged_Type (Func_Typ)
11421 and then not Is_Class_Wide_Type (Func_Typ)
11422 then
11423 Make_Tag_Check (Actual_Targ_Typ);
11424 Make_Conversion := True;
11425 end if;
11426 end if;
11427 end;
11428 end if;
11430 -- We have generated a tag check for either a class-wide type
11431 -- conversion or for AI05-0073.
11433 if Make_Conversion then
11434 declare
11435 Conv : Node_Id;
11436 begin
11437 Conv :=
11438 Make_Unchecked_Type_Conversion (Loc,
11439 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
11440 Expression => Relocate_Node (Expression (N)));
11441 Rewrite (N, Conv);
11442 Analyze_And_Resolve (N, Target_Type);
11443 end;
11444 end if;
11445 end if;
11446 end Tagged_Conversion;
11448 -- Case of other access type conversions
11450 elsif Is_Access_Type (Target_Type) then
11451 Apply_Constraint_Check (Operand, Target_Type);
11453 -- Case of conversions from a fixed-point type
11455 -- These conversions require special expansion and processing, found in
11456 -- the Exp_Fixd package. We ignore cases where Conversion_OK is set,
11457 -- since from a semantic point of view, these are simple integer
11458 -- conversions, which do not need further processing.
11460 elsif Is_Fixed_Point_Type (Operand_Type)
11461 and then not Conversion_OK (N)
11462 then
11463 -- We should never see universal fixed at this case, since the
11464 -- expansion of the constituent divide or multiply should have
11465 -- eliminated the explicit mention of universal fixed.
11467 pragma Assert (Operand_Type /= Universal_Fixed);
11469 -- Check for special case of the conversion to universal real that
11470 -- occurs as a result of the use of a round attribute. In this case,
11471 -- the real type for the conversion is taken from the target type of
11472 -- the Round attribute and the result must be marked as rounded.
11474 if Target_Type = Universal_Real
11475 and then Nkind (Parent (N)) = N_Attribute_Reference
11476 and then Attribute_Name (Parent (N)) = Name_Round
11477 then
11478 Set_Rounded_Result (N);
11479 Set_Etype (N, Etype (Parent (N)));
11480 end if;
11482 -- Otherwise do correct fixed-conversion, but skip these if the
11483 -- Conversion_OK flag is set, because from a semantic point of view
11484 -- these are simple integer conversions needing no further processing
11485 -- (the backend will simply treat them as integers).
11487 if not Conversion_OK (N) then
11488 if Is_Fixed_Point_Type (Etype (N)) then
11489 Expand_Convert_Fixed_To_Fixed (N);
11490 Real_Range_Check;
11492 elsif Is_Integer_Type (Etype (N)) then
11493 Expand_Convert_Fixed_To_Integer (N);
11495 else
11496 pragma Assert (Is_Floating_Point_Type (Etype (N)));
11497 Expand_Convert_Fixed_To_Float (N);
11498 Real_Range_Check;
11499 end if;
11500 end if;
11502 -- Case of conversions to a fixed-point type
11504 -- These conversions require special expansion and processing, found in
11505 -- the Exp_Fixd package. Again, ignore cases where Conversion_OK is set,
11506 -- since from a semantic point of view, these are simple integer
11507 -- conversions, which do not need further processing.
11509 elsif Is_Fixed_Point_Type (Target_Type)
11510 and then not Conversion_OK (N)
11511 then
11512 if Is_Integer_Type (Operand_Type) then
11513 Expand_Convert_Integer_To_Fixed (N);
11514 Real_Range_Check;
11515 else
11516 pragma Assert (Is_Floating_Point_Type (Operand_Type));
11517 Expand_Convert_Float_To_Fixed (N);
11518 Real_Range_Check;
11519 end if;
11521 -- Case of float-to-integer conversions
11523 -- We also handle float-to-fixed conversions with Conversion_OK set
11524 -- since semantically the fixed-point target is treated as though it
11525 -- were an integer in such cases.
11527 elsif Is_Floating_Point_Type (Operand_Type)
11528 and then
11529 (Is_Integer_Type (Target_Type)
11530 or else
11531 (Is_Fixed_Point_Type (Target_Type) and then Conversion_OK (N)))
11532 then
11533 -- One more check here, gcc is still not able to do conversions of
11534 -- this type with proper overflow checking, and so gigi is doing an
11535 -- approximation of what is required by doing floating-point compares
11536 -- with the end-point. But that can lose precision in some cases, and
11537 -- give a wrong result. Converting the operand to Universal_Real is
11538 -- helpful, but still does not catch all cases with 64-bit integers
11539 -- on targets with only 64-bit floats.
11541 -- The above comment seems obsoleted by Apply_Float_Conversion_Check
11542 -- Can this code be removed ???
11544 if Do_Range_Check (Operand) then
11545 Rewrite (Operand,
11546 Make_Type_Conversion (Loc,
11547 Subtype_Mark =>
11548 New_Occurrence_Of (Universal_Real, Loc),
11549 Expression =>
11550 Relocate_Node (Operand)));
11552 Set_Etype (Operand, Universal_Real);
11553 Enable_Range_Check (Operand);
11554 Set_Do_Range_Check (Expression (Operand), False);
11555 end if;
11557 -- Case of array conversions
11559 -- Expansion of array conversions, add required length/range checks but
11560 -- only do this if there is no change of representation. For handling of
11561 -- this case, see Handle_Changed_Representation.
11563 elsif Is_Array_Type (Target_Type) then
11564 if Is_Constrained (Target_Type) then
11565 Apply_Length_Check (Operand, Target_Type);
11566 else
11567 Apply_Range_Check (Operand, Target_Type);
11568 end if;
11570 Handle_Changed_Representation;
11572 -- Case of conversions of discriminated types
11574 -- Add required discriminant checks if target is constrained. Again this
11575 -- change is skipped if we have a change of representation.
11577 elsif Has_Discriminants (Target_Type)
11578 and then Is_Constrained (Target_Type)
11579 then
11580 Apply_Discriminant_Check (Operand, Target_Type);
11581 Handle_Changed_Representation;
11583 -- Case of all other record conversions. The only processing required
11584 -- is to check for a change of representation requiring the special
11585 -- assignment processing.
11587 elsif Is_Record_Type (Target_Type) then
11589 -- Ada 2005 (AI-216): Program_Error is raised when converting from
11590 -- a derived Unchecked_Union type to an unconstrained type that is
11591 -- not Unchecked_Union if the operand lacks inferable discriminants.
11593 if Is_Derived_Type (Operand_Type)
11594 and then Is_Unchecked_Union (Base_Type (Operand_Type))
11595 and then not Is_Constrained (Target_Type)
11596 and then not Is_Unchecked_Union (Base_Type (Target_Type))
11597 and then not Has_Inferable_Discriminants (Operand)
11598 then
11599 -- To prevent Gigi from generating illegal code, we generate a
11600 -- Program_Error node, but we give it the target type of the
11601 -- conversion (is this requirement documented somewhere ???)
11603 declare
11604 PE : constant Node_Id := Make_Raise_Program_Error (Loc,
11605 Reason => PE_Unchecked_Union_Restriction);
11607 begin
11608 Set_Etype (PE, Target_Type);
11609 Rewrite (N, PE);
11611 end;
11612 else
11613 Handle_Changed_Representation;
11614 end if;
11616 -- Case of conversions of enumeration types
11618 elsif Is_Enumeration_Type (Target_Type) then
11620 -- Special processing is required if there is a change of
11621 -- representation (from enumeration representation clauses).
11623 if not Same_Representation (Target_Type, Operand_Type) then
11625 -- Convert: x(y) to x'val (ytyp'val (y))
11627 Rewrite (N,
11628 Make_Attribute_Reference (Loc,
11629 Prefix => New_Occurrence_Of (Target_Type, Loc),
11630 Attribute_Name => Name_Val,
11631 Expressions => New_List (
11632 Make_Attribute_Reference (Loc,
11633 Prefix => New_Occurrence_Of (Operand_Type, Loc),
11634 Attribute_Name => Name_Pos,
11635 Expressions => New_List (Operand)))));
11637 Analyze_And_Resolve (N, Target_Type);
11638 end if;
11640 -- Case of conversions to floating-point
11642 elsif Is_Floating_Point_Type (Target_Type) then
11643 Real_Range_Check;
11644 end if;
11646 -- At this stage, either the conversion node has been transformed into
11647 -- some other equivalent expression, or left as a conversion that can be
11648 -- handled by Gigi, in the following cases:
11650 -- Conversions with no change of representation or type
11652 -- Numeric conversions involving integer, floating- and fixed-point
11653 -- values. Fixed-point values are allowed only if Conversion_OK is
11654 -- set, i.e. if the fixed-point values are to be treated as integers.
11656 -- No other conversions should be passed to Gigi
11658 -- Check: are these rules stated in sinfo??? if so, why restate here???
11660 -- The only remaining step is to generate a range check if we still have
11661 -- a type conversion at this stage and Do_Range_Check is set. For now we
11662 -- do this only for conversions of discrete types and for float-to-float
11663 -- conversions.
11665 if Nkind (N) = N_Type_Conversion then
11667 -- For now we only support floating-point cases where both source
11668 -- and target are floating-point types. Conversions where the source
11669 -- and target involve integer or fixed-point types are still TBD,
11670 -- though not clear whether those can even happen at this point, due
11671 -- to transformations above. ???
11673 if Is_Floating_Point_Type (Etype (N))
11674 and then Is_Floating_Point_Type (Etype (Expression (N)))
11675 then
11676 if Do_Range_Check (Expression (N))
11677 and then Is_Floating_Point_Type (Target_Type)
11678 then
11679 Generate_Range_Check
11680 (Expression (N), Target_Type, CE_Range_Check_Failed);
11681 end if;
11683 -- Discrete-to-discrete conversions
11685 elsif Is_Discrete_Type (Etype (N)) then
11686 declare
11687 Expr : constant Node_Id := Expression (N);
11688 Ftyp : Entity_Id;
11689 Ityp : Entity_Id;
11691 begin
11692 if Do_Range_Check (Expr)
11693 and then Is_Discrete_Type (Etype (Expr))
11694 then
11695 Set_Do_Range_Check (Expr, False);
11697 -- Before we do a range check, we have to deal with treating
11698 -- a fixed-point operand as an integer. The way we do this
11699 -- is simply to do an unchecked conversion to an appropriate
11700 -- integer type large enough to hold the result.
11702 -- This code is not active yet, because we are only dealing
11703 -- with discrete types so far ???
11705 if Nkind (Expr) in N_Has_Treat_Fixed_As_Integer
11706 and then Treat_Fixed_As_Integer (Expr)
11707 then
11708 Ftyp := Base_Type (Etype (Expr));
11710 if Esize (Ftyp) >= Esize (Standard_Integer) then
11711 Ityp := Standard_Long_Long_Integer;
11712 else
11713 Ityp := Standard_Integer;
11714 end if;
11716 Rewrite (Expr, Unchecked_Convert_To (Ityp, Expr));
11717 end if;
11719 -- Reset overflow flag, since the range check will include
11720 -- dealing with possible overflow, and generate the check.
11721 -- If Address is either a source type or target type,
11722 -- suppress range check to avoid typing anomalies when
11723 -- it is a visible integer type.
11725 Set_Do_Overflow_Check (N, False);
11727 if not Is_Descendant_Of_Address (Etype (Expr))
11728 and then not Is_Descendant_Of_Address (Target_Type)
11729 then
11730 Generate_Range_Check
11731 (Expr, Target_Type, CE_Range_Check_Failed);
11732 end if;
11733 end if;
11734 end;
11735 end if;
11736 end if;
11738 -- Here at end of processing
11740 <<Done>>
11741 -- Apply predicate check if required. Note that we can't just call
11742 -- Apply_Predicate_Check here, because the type looks right after
11743 -- the conversion and it would omit the check. The Comes_From_Source
11744 -- guard is necessary to prevent infinite recursions when we generate
11745 -- internal conversions for the purpose of checking predicates.
11747 if Present (Predicate_Function (Target_Type))
11748 and then not Predicates_Ignored (Target_Type)
11749 and then Target_Type /= Operand_Type
11750 and then Comes_From_Source (N)
11751 then
11752 declare
11753 New_Expr : constant Node_Id := Duplicate_Subexpr (N);
11755 begin
11756 -- Avoid infinite recursion on the subsequent expansion of
11757 -- of the copy of the original type conversion.
11759 Set_Comes_From_Source (New_Expr, False);
11760 Insert_Action (N, Make_Predicate_Check (Target_Type, New_Expr));
11761 end;
11762 end if;
11763 end Expand_N_Type_Conversion;
11765 -----------------------------------
11766 -- Expand_N_Unchecked_Expression --
11767 -----------------------------------
11769 -- Remove the unchecked expression node from the tree. Its job was simply
11770 -- to make sure that its constituent expression was handled with checks
11771 -- off, and now that that is done, we can remove it from the tree, and
11772 -- indeed must, since Gigi does not expect to see these nodes.
11774 procedure Expand_N_Unchecked_Expression (N : Node_Id) is
11775 Exp : constant Node_Id := Expression (N);
11776 begin
11777 Set_Assignment_OK (Exp, Assignment_OK (N) or else Assignment_OK (Exp));
11778 Rewrite (N, Exp);
11779 end Expand_N_Unchecked_Expression;
11781 ----------------------------------------
11782 -- Expand_N_Unchecked_Type_Conversion --
11783 ----------------------------------------
11785 -- If this cannot be handled by Gigi and we haven't already made a
11786 -- temporary for it, do it now.
11788 procedure Expand_N_Unchecked_Type_Conversion (N : Node_Id) is
11789 Target_Type : constant Entity_Id := Etype (N);
11790 Operand : constant Node_Id := Expression (N);
11791 Operand_Type : constant Entity_Id := Etype (Operand);
11793 begin
11794 -- Nothing at all to do if conversion is to the identical type so remove
11795 -- the conversion completely, it is useless, except that it may carry
11796 -- an Assignment_OK indication which must be propagated to the operand.
11798 if Operand_Type = Target_Type then
11800 -- Code duplicates Expand_N_Unchecked_Expression above, factor???
11802 if Assignment_OK (N) then
11803 Set_Assignment_OK (Operand);
11804 end if;
11806 Rewrite (N, Relocate_Node (Operand));
11807 return;
11808 end if;
11810 -- If we have a conversion of a compile time known value to a target
11811 -- type and the value is in range of the target type, then we can simply
11812 -- replace the construct by an integer literal of the correct type. We
11813 -- only apply this to integer types being converted. Possibly it may
11814 -- apply in other cases, but it is too much trouble to worry about.
11816 -- Note that we do not do this transformation if the Kill_Range_Check
11817 -- flag is set, since then the value may be outside the expected range.
11818 -- This happens in the Normalize_Scalars case.
11820 -- We also skip this if either the target or operand type is biased
11821 -- because in this case, the unchecked conversion is supposed to
11822 -- preserve the bit pattern, not the integer value.
11824 if Is_Integer_Type (Target_Type)
11825 and then not Has_Biased_Representation (Target_Type)
11826 and then Is_Integer_Type (Operand_Type)
11827 and then not Has_Biased_Representation (Operand_Type)
11828 and then Compile_Time_Known_Value (Operand)
11829 and then not Kill_Range_Check (N)
11830 then
11831 declare
11832 Val : constant Uint := Expr_Value (Operand);
11834 begin
11835 if Compile_Time_Known_Value (Type_Low_Bound (Target_Type))
11836 and then
11837 Compile_Time_Known_Value (Type_High_Bound (Target_Type))
11838 and then
11839 Val >= Expr_Value (Type_Low_Bound (Target_Type))
11840 and then
11841 Val <= Expr_Value (Type_High_Bound (Target_Type))
11842 then
11843 Rewrite (N, Make_Integer_Literal (Sloc (N), Val));
11845 -- If Address is the target type, just set the type to avoid a
11846 -- spurious type error on the literal when Address is a visible
11847 -- integer type.
11849 if Is_Descendant_Of_Address (Target_Type) then
11850 Set_Etype (N, Target_Type);
11851 else
11852 Analyze_And_Resolve (N, Target_Type);
11853 end if;
11855 return;
11856 end if;
11857 end;
11858 end if;
11860 -- Nothing to do if conversion is safe
11862 if Safe_Unchecked_Type_Conversion (N) then
11863 return;
11864 end if;
11866 -- Otherwise force evaluation unless Assignment_OK flag is set (this
11867 -- flag indicates ??? More comments needed here)
11869 if Assignment_OK (N) then
11870 null;
11871 else
11872 Force_Evaluation (N);
11873 end if;
11874 end Expand_N_Unchecked_Type_Conversion;
11876 ----------------------------
11877 -- Expand_Record_Equality --
11878 ----------------------------
11880 -- For non-variant records, Equality is expanded when needed into:
11882 -- and then Lhs.Discr1 = Rhs.Discr1
11883 -- and then ...
11884 -- and then Lhs.Discrn = Rhs.Discrn
11885 -- and then Lhs.Cmp1 = Rhs.Cmp1
11886 -- and then ...
11887 -- and then Lhs.Cmpn = Rhs.Cmpn
11889 -- The expression is folded by the back end for adjacent fields. This
11890 -- function is called for tagged record in only one occasion: for imple-
11891 -- menting predefined primitive equality (see Predefined_Primitives_Bodies)
11892 -- otherwise the primitive "=" is used directly.
11894 function Expand_Record_Equality
11895 (Nod : Node_Id;
11896 Typ : Entity_Id;
11897 Lhs : Node_Id;
11898 Rhs : Node_Id;
11899 Bodies : List_Id) return Node_Id
11901 Loc : constant Source_Ptr := Sloc (Nod);
11903 Result : Node_Id;
11904 C : Entity_Id;
11906 First_Time : Boolean := True;
11908 function Element_To_Compare (C : Entity_Id) return Entity_Id;
11909 -- Return the next discriminant or component to compare, starting with
11910 -- C, skipping inherited components.
11912 ------------------------
11913 -- Element_To_Compare --
11914 ------------------------
11916 function Element_To_Compare (C : Entity_Id) return Entity_Id is
11917 Comp : Entity_Id;
11919 begin
11920 Comp := C;
11921 loop
11922 -- Exit loop when the next element to be compared is found, or
11923 -- there is no more such element.
11925 exit when No (Comp);
11927 exit when Ekind_In (Comp, E_Discriminant, E_Component)
11928 and then not (
11930 -- Skip inherited components
11932 -- Note: for a tagged type, we always generate the "=" primitive
11933 -- for the base type (not on the first subtype), so the test for
11934 -- Comp /= Original_Record_Component (Comp) is True for
11935 -- inherited components only.
11937 (Is_Tagged_Type (Typ)
11938 and then Comp /= Original_Record_Component (Comp))
11940 -- Skip _Tag
11942 or else Chars (Comp) = Name_uTag
11944 -- Skip interface elements (secondary tags???)
11946 or else Is_Interface (Etype (Comp)));
11948 Next_Entity (Comp);
11949 end loop;
11951 return Comp;
11952 end Element_To_Compare;
11954 -- Start of processing for Expand_Record_Equality
11956 begin
11957 -- Generates the following code: (assuming that Typ has one Discr and
11958 -- component C2 is also a record)
11960 -- True
11961 -- and then Lhs.Discr1 = Rhs.Discr1
11962 -- and then Lhs.C1 = Rhs.C1
11963 -- and then Lhs.C2.C1=Rhs.C2.C1 and then ... Lhs.C2.Cn=Rhs.C2.Cn
11964 -- and then ...
11965 -- and then Lhs.Cmpn = Rhs.Cmpn
11967 Result := New_Occurrence_Of (Standard_True, Loc);
11968 C := Element_To_Compare (First_Entity (Typ));
11969 while Present (C) loop
11970 declare
11971 New_Lhs : Node_Id;
11972 New_Rhs : Node_Id;
11973 Check : Node_Id;
11975 begin
11976 if First_Time then
11977 First_Time := False;
11978 New_Lhs := Lhs;
11979 New_Rhs := Rhs;
11980 else
11981 New_Lhs := New_Copy_Tree (Lhs);
11982 New_Rhs := New_Copy_Tree (Rhs);
11983 end if;
11985 Check :=
11986 Expand_Composite_Equality (Nod, Etype (C),
11987 Lhs =>
11988 Make_Selected_Component (Loc,
11989 Prefix => New_Lhs,
11990 Selector_Name => New_Occurrence_Of (C, Loc)),
11991 Rhs =>
11992 Make_Selected_Component (Loc,
11993 Prefix => New_Rhs,
11994 Selector_Name => New_Occurrence_Of (C, Loc)),
11995 Bodies => Bodies);
11997 -- If some (sub)component is an unchecked_union, the whole
11998 -- operation will raise program error.
12000 if Nkind (Check) = N_Raise_Program_Error then
12001 Result := Check;
12002 Set_Etype (Result, Standard_Boolean);
12003 exit;
12004 else
12005 Result :=
12006 Make_And_Then (Loc,
12007 Left_Opnd => Result,
12008 Right_Opnd => Check);
12009 end if;
12010 end;
12012 C := Element_To_Compare (Next_Entity (C));
12013 end loop;
12015 return Result;
12016 end Expand_Record_Equality;
12018 ---------------------------
12019 -- Expand_Set_Membership --
12020 ---------------------------
12022 procedure Expand_Set_Membership (N : Node_Id) is
12023 Lop : constant Node_Id := Left_Opnd (N);
12024 Alt : Node_Id;
12025 Res : Node_Id;
12027 function Make_Cond (Alt : Node_Id) return Node_Id;
12028 -- If the alternative is a subtype mark, create a simple membership
12029 -- test. Otherwise create an equality test for it.
12031 ---------------
12032 -- Make_Cond --
12033 ---------------
12035 function Make_Cond (Alt : Node_Id) return Node_Id is
12036 Cond : Node_Id;
12037 L : constant Node_Id := New_Copy (Lop);
12038 R : constant Node_Id := Relocate_Node (Alt);
12040 begin
12041 if (Is_Entity_Name (Alt) and then Is_Type (Entity (Alt)))
12042 or else Nkind (Alt) = N_Range
12043 then
12044 Cond :=
12045 Make_In (Sloc (Alt),
12046 Left_Opnd => L,
12047 Right_Opnd => R);
12048 else
12049 Cond :=
12050 Make_Op_Eq (Sloc (Alt),
12051 Left_Opnd => L,
12052 Right_Opnd => R);
12053 end if;
12055 return Cond;
12056 end Make_Cond;
12058 -- Start of processing for Expand_Set_Membership
12060 begin
12061 Remove_Side_Effects (Lop);
12063 Alt := Last (Alternatives (N));
12064 Res := Make_Cond (Alt);
12066 Prev (Alt);
12067 while Present (Alt) loop
12068 Res :=
12069 Make_Or_Else (Sloc (Alt),
12070 Left_Opnd => Make_Cond (Alt),
12071 Right_Opnd => Res);
12072 Prev (Alt);
12073 end loop;
12075 Rewrite (N, Res);
12076 Analyze_And_Resolve (N, Standard_Boolean);
12077 end Expand_Set_Membership;
12079 -----------------------------------
12080 -- Expand_Short_Circuit_Operator --
12081 -----------------------------------
12083 -- Deal with special expansion if actions are present for the right operand
12084 -- and deal with optimizing case of arguments being True or False. We also
12085 -- deal with the special case of non-standard boolean values.
12087 procedure Expand_Short_Circuit_Operator (N : Node_Id) is
12088 Loc : constant Source_Ptr := Sloc (N);
12089 Typ : constant Entity_Id := Etype (N);
12090 Left : constant Node_Id := Left_Opnd (N);
12091 Right : constant Node_Id := Right_Opnd (N);
12092 LocR : constant Source_Ptr := Sloc (Right);
12093 Actlist : List_Id;
12095 Shortcut_Value : constant Boolean := Nkind (N) = N_Or_Else;
12096 Shortcut_Ent : constant Entity_Id := Boolean_Literals (Shortcut_Value);
12097 -- If Left = Shortcut_Value then Right need not be evaluated
12099 function Make_Test_Expr (Opnd : Node_Id) return Node_Id;
12100 -- For Opnd a boolean expression, return a Boolean expression equivalent
12101 -- to Opnd /= Shortcut_Value.
12103 --------------------
12104 -- Make_Test_Expr --
12105 --------------------
12107 function Make_Test_Expr (Opnd : Node_Id) return Node_Id is
12108 begin
12109 if Shortcut_Value then
12110 return Make_Op_Not (Sloc (Opnd), Opnd);
12111 else
12112 return Opnd;
12113 end if;
12114 end Make_Test_Expr;
12116 -- Local variables
12118 Op_Var : Entity_Id;
12119 -- Entity for a temporary variable holding the value of the operator,
12120 -- used for expansion in the case where actions are present.
12122 -- Start of processing for Expand_Short_Circuit_Operator
12124 begin
12125 -- Deal with non-standard booleans
12127 if Is_Boolean_Type (Typ) then
12128 Adjust_Condition (Left);
12129 Adjust_Condition (Right);
12130 Set_Etype (N, Standard_Boolean);
12131 end if;
12133 -- Check for cases where left argument is known to be True or False
12135 if Compile_Time_Known_Value (Left) then
12137 -- Mark SCO for left condition as compile time known
12139 if Generate_SCO and then Comes_From_Source (Left) then
12140 Set_SCO_Condition (Left, Expr_Value_E (Left) = Standard_True);
12141 end if;
12143 -- Rewrite True AND THEN Right / False OR ELSE Right to Right.
12144 -- Any actions associated with Right will be executed unconditionally
12145 -- and can thus be inserted into the tree unconditionally.
12147 if Expr_Value_E (Left) /= Shortcut_Ent then
12148 if Present (Actions (N)) then
12149 Insert_Actions (N, Actions (N));
12150 end if;
12152 Rewrite (N, Right);
12154 -- Rewrite False AND THEN Right / True OR ELSE Right to Left.
12155 -- In this case we can forget the actions associated with Right,
12156 -- since they will never be executed.
12158 else
12159 Kill_Dead_Code (Right);
12160 Kill_Dead_Code (Actions (N));
12161 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12162 end if;
12164 Adjust_Result_Type (N, Typ);
12165 return;
12166 end if;
12168 -- If Actions are present for the right operand, we have to do some
12169 -- special processing. We can't just let these actions filter back into
12170 -- code preceding the short circuit (which is what would have happened
12171 -- if we had not trapped them in the short-circuit form), since they
12172 -- must only be executed if the right operand of the short circuit is
12173 -- executed and not otherwise.
12175 if Present (Actions (N)) then
12176 Actlist := Actions (N);
12178 -- The old approach is to expand:
12180 -- left AND THEN right
12182 -- into
12184 -- C : Boolean := False;
12185 -- IF left THEN
12186 -- Actions;
12187 -- IF right THEN
12188 -- C := True;
12189 -- END IF;
12190 -- END IF;
12192 -- and finally rewrite the operator into a reference to C. Similarly
12193 -- for left OR ELSE right, with negated values. Note that this
12194 -- rewrite causes some difficulties for coverage analysis because
12195 -- of the introduction of the new variable C, which obscures the
12196 -- structure of the test.
12198 -- We use this "old approach" if Minimize_Expression_With_Actions
12199 -- is True.
12201 if Minimize_Expression_With_Actions then
12202 Op_Var := Make_Temporary (Loc, 'C', Related_Node => N);
12204 Insert_Action (N,
12205 Make_Object_Declaration (Loc,
12206 Defining_Identifier => Op_Var,
12207 Object_Definition =>
12208 New_Occurrence_Of (Standard_Boolean, Loc),
12209 Expression =>
12210 New_Occurrence_Of (Shortcut_Ent, Loc)));
12212 Append_To (Actlist,
12213 Make_Implicit_If_Statement (Right,
12214 Condition => Make_Test_Expr (Right),
12215 Then_Statements => New_List (
12216 Make_Assignment_Statement (LocR,
12217 Name => New_Occurrence_Of (Op_Var, LocR),
12218 Expression =>
12219 New_Occurrence_Of
12220 (Boolean_Literals (not Shortcut_Value), LocR)))));
12222 Insert_Action (N,
12223 Make_Implicit_If_Statement (Left,
12224 Condition => Make_Test_Expr (Left),
12225 Then_Statements => Actlist));
12227 Rewrite (N, New_Occurrence_Of (Op_Var, Loc));
12228 Analyze_And_Resolve (N, Standard_Boolean);
12230 -- The new approach (the default) is to use an
12231 -- Expression_With_Actions node for the right operand of the
12232 -- short-circuit form. Note that this solves the traceability
12233 -- problems for coverage analysis.
12235 else
12236 Rewrite (Right,
12237 Make_Expression_With_Actions (LocR,
12238 Expression => Relocate_Node (Right),
12239 Actions => Actlist));
12241 Set_Actions (N, No_List);
12242 Analyze_And_Resolve (Right, Standard_Boolean);
12243 end if;
12245 Adjust_Result_Type (N, Typ);
12246 return;
12247 end if;
12249 -- No actions present, check for cases of right argument True/False
12251 if Compile_Time_Known_Value (Right) then
12253 -- Mark SCO for left condition as compile time known
12255 if Generate_SCO and then Comes_From_Source (Right) then
12256 Set_SCO_Condition (Right, Expr_Value_E (Right) = Standard_True);
12257 end if;
12259 -- Change (Left and then True), (Left or else False) to Left. Note
12260 -- that we know there are no actions associated with the right
12261 -- operand, since we just checked for this case above.
12263 if Expr_Value_E (Right) /= Shortcut_Ent then
12264 Rewrite (N, Left);
12266 -- Change (Left and then False), (Left or else True) to Right,
12267 -- making sure to preserve any side effects associated with the Left
12268 -- operand.
12270 else
12271 Remove_Side_Effects (Left);
12272 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12273 end if;
12274 end if;
12276 Adjust_Result_Type (N, Typ);
12277 end Expand_Short_Circuit_Operator;
12279 -------------------------------------
12280 -- Fixup_Universal_Fixed_Operation --
12281 -------------------------------------
12283 procedure Fixup_Universal_Fixed_Operation (N : Node_Id) is
12284 Conv : constant Node_Id := Parent (N);
12286 begin
12287 -- We must have a type conversion immediately above us
12289 pragma Assert (Nkind (Conv) = N_Type_Conversion);
12291 -- Normally the type conversion gives our target type. The exception
12292 -- occurs in the case of the Round attribute, where the conversion
12293 -- will be to universal real, and our real type comes from the Round
12294 -- attribute (as well as an indication that we must round the result)
12296 if Nkind (Parent (Conv)) = N_Attribute_Reference
12297 and then Attribute_Name (Parent (Conv)) = Name_Round
12298 then
12299 Set_Etype (N, Etype (Parent (Conv)));
12300 Set_Rounded_Result (N);
12302 -- Normal case where type comes from conversion above us
12304 else
12305 Set_Etype (N, Etype (Conv));
12306 end if;
12307 end Fixup_Universal_Fixed_Operation;
12309 ---------------------------------
12310 -- Has_Inferable_Discriminants --
12311 ---------------------------------
12313 function Has_Inferable_Discriminants (N : Node_Id) return Boolean is
12315 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean;
12316 -- Determines whether the left-most prefix of a selected component is a
12317 -- formal parameter in a subprogram. Assumes N is a selected component.
12319 --------------------------------
12320 -- Prefix_Is_Formal_Parameter --
12321 --------------------------------
12323 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean is
12324 Sel_Comp : Node_Id;
12326 begin
12327 -- Move to the left-most prefix by climbing up the tree
12329 Sel_Comp := N;
12330 while Present (Parent (Sel_Comp))
12331 and then Nkind (Parent (Sel_Comp)) = N_Selected_Component
12332 loop
12333 Sel_Comp := Parent (Sel_Comp);
12334 end loop;
12336 return Ekind (Entity (Prefix (Sel_Comp))) in Formal_Kind;
12337 end Prefix_Is_Formal_Parameter;
12339 -- Start of processing for Has_Inferable_Discriminants
12341 begin
12342 -- For selected components, the subtype of the selector must be a
12343 -- constrained Unchecked_Union. If the component is subject to a
12344 -- per-object constraint, then the enclosing object must have inferable
12345 -- discriminants.
12347 if Nkind (N) = N_Selected_Component then
12348 if Has_Per_Object_Constraint (Entity (Selector_Name (N))) then
12350 -- A small hack. If we have a per-object constrained selected
12351 -- component of a formal parameter, return True since we do not
12352 -- know the actual parameter association yet.
12354 if Prefix_Is_Formal_Parameter (N) then
12355 return True;
12357 -- Otherwise, check the enclosing object and the selector
12359 else
12360 return Has_Inferable_Discriminants (Prefix (N))
12361 and then Has_Inferable_Discriminants (Selector_Name (N));
12362 end if;
12364 -- The call to Has_Inferable_Discriminants will determine whether
12365 -- the selector has a constrained Unchecked_Union nominal type.
12367 else
12368 return Has_Inferable_Discriminants (Selector_Name (N));
12369 end if;
12371 -- A qualified expression has inferable discriminants if its subtype
12372 -- mark is a constrained Unchecked_Union subtype.
12374 elsif Nkind (N) = N_Qualified_Expression then
12375 return Is_Unchecked_Union (Etype (Subtype_Mark (N)))
12376 and then Is_Constrained (Etype (Subtype_Mark (N)));
12378 -- For all other names, it is sufficient to have a constrained
12379 -- Unchecked_Union nominal subtype.
12381 else
12382 return Is_Unchecked_Union (Base_Type (Etype (N)))
12383 and then Is_Constrained (Etype (N));
12384 end if;
12385 end Has_Inferable_Discriminants;
12387 -------------------------------
12388 -- Insert_Dereference_Action --
12389 -------------------------------
12391 procedure Insert_Dereference_Action (N : Node_Id) is
12392 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean;
12393 -- Return true if type of P is derived from Checked_Pool;
12395 -----------------------------
12396 -- Is_Checked_Storage_Pool --
12397 -----------------------------
12399 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean is
12400 T : Entity_Id;
12402 begin
12403 if No (P) then
12404 return False;
12405 end if;
12407 T := Etype (P);
12408 while T /= Etype (T) loop
12409 if Is_RTE (T, RE_Checked_Pool) then
12410 return True;
12411 else
12412 T := Etype (T);
12413 end if;
12414 end loop;
12416 return False;
12417 end Is_Checked_Storage_Pool;
12419 -- Local variables
12421 Context : constant Node_Id := Parent (N);
12422 Ptr_Typ : constant Entity_Id := Etype (N);
12423 Desig_Typ : constant Entity_Id :=
12424 Available_View (Designated_Type (Ptr_Typ));
12425 Loc : constant Source_Ptr := Sloc (N);
12426 Pool : constant Entity_Id := Associated_Storage_Pool (Ptr_Typ);
12428 Addr : Entity_Id;
12429 Alig : Entity_Id;
12430 Deref : Node_Id;
12431 Size : Entity_Id;
12432 Size_Bits : Node_Id;
12433 Stmt : Node_Id;
12435 -- Start of processing for Insert_Dereference_Action
12437 begin
12438 pragma Assert (Nkind (Context) = N_Explicit_Dereference);
12440 -- Do not re-expand a dereference which has already been processed by
12441 -- this routine.
12443 if Has_Dereference_Action (Context) then
12444 return;
12446 -- Do not perform this type of expansion for internally-generated
12447 -- dereferences.
12449 elsif not Comes_From_Source (Original_Node (Context)) then
12450 return;
12452 -- A dereference action is only applicable to objects which have been
12453 -- allocated on a checked pool.
12455 elsif not Is_Checked_Storage_Pool (Pool) then
12456 return;
12457 end if;
12459 -- Extract the address of the dereferenced object. Generate:
12461 -- Addr : System.Address := <N>'Pool_Address;
12463 Addr := Make_Temporary (Loc, 'P');
12465 Insert_Action (N,
12466 Make_Object_Declaration (Loc,
12467 Defining_Identifier => Addr,
12468 Object_Definition =>
12469 New_Occurrence_Of (RTE (RE_Address), Loc),
12470 Expression =>
12471 Make_Attribute_Reference (Loc,
12472 Prefix => Duplicate_Subexpr_Move_Checks (N),
12473 Attribute_Name => Name_Pool_Address)));
12475 -- Calculate the size of the dereferenced object. Generate:
12477 -- Size : Storage_Count := <N>.all'Size / Storage_Unit;
12479 Deref :=
12480 Make_Explicit_Dereference (Loc,
12481 Prefix => Duplicate_Subexpr_Move_Checks (N));
12482 Set_Has_Dereference_Action (Deref);
12484 Size_Bits :=
12485 Make_Attribute_Reference (Loc,
12486 Prefix => Deref,
12487 Attribute_Name => Name_Size);
12489 -- Special case of an unconstrained array: need to add descriptor size
12491 if Is_Array_Type (Desig_Typ)
12492 and then not Is_Constrained (First_Subtype (Desig_Typ))
12493 then
12494 Size_Bits :=
12495 Make_Op_Add (Loc,
12496 Left_Opnd =>
12497 Make_Attribute_Reference (Loc,
12498 Prefix =>
12499 New_Occurrence_Of (First_Subtype (Desig_Typ), Loc),
12500 Attribute_Name => Name_Descriptor_Size),
12501 Right_Opnd => Size_Bits);
12502 end if;
12504 Size := Make_Temporary (Loc, 'S');
12505 Insert_Action (N,
12506 Make_Object_Declaration (Loc,
12507 Defining_Identifier => Size,
12508 Object_Definition =>
12509 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12510 Expression =>
12511 Make_Op_Divide (Loc,
12512 Left_Opnd => Size_Bits,
12513 Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit))));
12515 -- Calculate the alignment of the dereferenced object. Generate:
12516 -- Alig : constant Storage_Count := <N>.all'Alignment;
12518 Deref :=
12519 Make_Explicit_Dereference (Loc,
12520 Prefix => Duplicate_Subexpr_Move_Checks (N));
12521 Set_Has_Dereference_Action (Deref);
12523 Alig := Make_Temporary (Loc, 'A');
12524 Insert_Action (N,
12525 Make_Object_Declaration (Loc,
12526 Defining_Identifier => Alig,
12527 Object_Definition =>
12528 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12529 Expression =>
12530 Make_Attribute_Reference (Loc,
12531 Prefix => Deref,
12532 Attribute_Name => Name_Alignment)));
12534 -- A dereference of a controlled object requires special processing. The
12535 -- finalization machinery requests additional space from the underlying
12536 -- pool to allocate and hide two pointers. As a result, a checked pool
12537 -- may mark the wrong memory as valid. Since checked pools do not have
12538 -- knowledge of hidden pointers, we have to bring the two pointers back
12539 -- in view in order to restore the original state of the object.
12541 -- The address manipulation is not performed for access types that are
12542 -- subject to pragma No_Heap_Finalization because the two pointers do
12543 -- not exist in the first place.
12545 if No_Heap_Finalization (Ptr_Typ) then
12546 null;
12548 elsif Needs_Finalization (Desig_Typ) then
12550 -- Adjust the address and size of the dereferenced object. Generate:
12551 -- Adjust_Controlled_Dereference (Addr, Size, Alig);
12553 Stmt :=
12554 Make_Procedure_Call_Statement (Loc,
12555 Name =>
12556 New_Occurrence_Of (RTE (RE_Adjust_Controlled_Dereference), Loc),
12557 Parameter_Associations => New_List (
12558 New_Occurrence_Of (Addr, Loc),
12559 New_Occurrence_Of (Size, Loc),
12560 New_Occurrence_Of (Alig, Loc)));
12562 -- Class-wide types complicate things because we cannot determine
12563 -- statically whether the actual object is truly controlled. We must
12564 -- generate a runtime check to detect this property. Generate:
12566 -- if Needs_Finalization (<N>.all'Tag) then
12567 -- <Stmt>;
12568 -- end if;
12570 if Is_Class_Wide_Type (Desig_Typ) then
12571 Deref :=
12572 Make_Explicit_Dereference (Loc,
12573 Prefix => Duplicate_Subexpr_Move_Checks (N));
12574 Set_Has_Dereference_Action (Deref);
12576 Stmt :=
12577 Make_Implicit_If_Statement (N,
12578 Condition =>
12579 Make_Function_Call (Loc,
12580 Name =>
12581 New_Occurrence_Of (RTE (RE_Needs_Finalization), Loc),
12582 Parameter_Associations => New_List (
12583 Make_Attribute_Reference (Loc,
12584 Prefix => Deref,
12585 Attribute_Name => Name_Tag))),
12586 Then_Statements => New_List (Stmt));
12587 end if;
12589 Insert_Action (N, Stmt);
12590 end if;
12592 -- Generate:
12593 -- Dereference (Pool, Addr, Size, Alig);
12595 Insert_Action (N,
12596 Make_Procedure_Call_Statement (Loc,
12597 Name =>
12598 New_Occurrence_Of
12599 (Find_Prim_Op (Etype (Pool), Name_Dereference), Loc),
12600 Parameter_Associations => New_List (
12601 New_Occurrence_Of (Pool, Loc),
12602 New_Occurrence_Of (Addr, Loc),
12603 New_Occurrence_Of (Size, Loc),
12604 New_Occurrence_Of (Alig, Loc))));
12606 -- Mark the explicit dereference as processed to avoid potential
12607 -- infinite expansion.
12609 Set_Has_Dereference_Action (Context);
12611 exception
12612 when RE_Not_Available =>
12613 return;
12614 end Insert_Dereference_Action;
12616 --------------------------------
12617 -- Integer_Promotion_Possible --
12618 --------------------------------
12620 function Integer_Promotion_Possible (N : Node_Id) return Boolean is
12621 Operand : constant Node_Id := Expression (N);
12622 Operand_Type : constant Entity_Id := Etype (Operand);
12623 Root_Operand_Type : constant Entity_Id := Root_Type (Operand_Type);
12625 begin
12626 pragma Assert (Nkind (N) = N_Type_Conversion);
12628 return
12630 -- We only do the transformation for source constructs. We assume
12631 -- that the expander knows what it is doing when it generates code.
12633 Comes_From_Source (N)
12635 -- If the operand type is Short_Integer or Short_Short_Integer,
12636 -- then we will promote to Integer, which is available on all
12637 -- targets, and is sufficient to ensure no intermediate overflow.
12638 -- Furthermore it is likely to be as efficient or more efficient
12639 -- than using the smaller type for the computation so we do this
12640 -- unconditionally.
12642 and then
12643 (Root_Operand_Type = Base_Type (Standard_Short_Integer)
12644 or else
12645 Root_Operand_Type = Base_Type (Standard_Short_Short_Integer))
12647 -- Test for interesting operation, which includes addition,
12648 -- division, exponentiation, multiplication, subtraction, absolute
12649 -- value and unary negation. Unary "+" is omitted since it is a
12650 -- no-op and thus can't overflow.
12652 and then Nkind_In (Operand, N_Op_Abs,
12653 N_Op_Add,
12654 N_Op_Divide,
12655 N_Op_Expon,
12656 N_Op_Minus,
12657 N_Op_Multiply,
12658 N_Op_Subtract);
12659 end Integer_Promotion_Possible;
12661 ------------------------------
12662 -- Make_Array_Comparison_Op --
12663 ------------------------------
12665 -- This is a hand-coded expansion of the following generic function:
12667 -- generic
12668 -- type elem is (<>);
12669 -- type index is (<>);
12670 -- type a is array (index range <>) of elem;
12672 -- function Gnnn (X : a; Y: a) return boolean is
12673 -- J : index := Y'first;
12675 -- begin
12676 -- if X'length = 0 then
12677 -- return false;
12679 -- elsif Y'length = 0 then
12680 -- return true;
12682 -- else
12683 -- for I in X'range loop
12684 -- if X (I) = Y (J) then
12685 -- if J = Y'last then
12686 -- exit;
12687 -- else
12688 -- J := index'succ (J);
12689 -- end if;
12691 -- else
12692 -- return X (I) > Y (J);
12693 -- end if;
12694 -- end loop;
12696 -- return X'length > Y'length;
12697 -- end if;
12698 -- end Gnnn;
12700 -- Note that since we are essentially doing this expansion by hand, we
12701 -- do not need to generate an actual or formal generic part, just the
12702 -- instantiated function itself.
12704 -- Perhaps we could have the actual generic available in the run-time,
12705 -- obtained by rtsfind, and actually expand a real instantiation ???
12707 function Make_Array_Comparison_Op
12708 (Typ : Entity_Id;
12709 Nod : Node_Id) return Node_Id
12711 Loc : constant Source_Ptr := Sloc (Nod);
12713 X : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uX);
12714 Y : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uY);
12715 I : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uI);
12716 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
12718 Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
12720 Loop_Statement : Node_Id;
12721 Loop_Body : Node_Id;
12722 If_Stat : Node_Id;
12723 Inner_If : Node_Id;
12724 Final_Expr : Node_Id;
12725 Func_Body : Node_Id;
12726 Func_Name : Entity_Id;
12727 Formals : List_Id;
12728 Length1 : Node_Id;
12729 Length2 : Node_Id;
12731 begin
12732 -- if J = Y'last then
12733 -- exit;
12734 -- else
12735 -- J := index'succ (J);
12736 -- end if;
12738 Inner_If :=
12739 Make_Implicit_If_Statement (Nod,
12740 Condition =>
12741 Make_Op_Eq (Loc,
12742 Left_Opnd => New_Occurrence_Of (J, Loc),
12743 Right_Opnd =>
12744 Make_Attribute_Reference (Loc,
12745 Prefix => New_Occurrence_Of (Y, Loc),
12746 Attribute_Name => Name_Last)),
12748 Then_Statements => New_List (
12749 Make_Exit_Statement (Loc)),
12751 Else_Statements =>
12752 New_List (
12753 Make_Assignment_Statement (Loc,
12754 Name => New_Occurrence_Of (J, Loc),
12755 Expression =>
12756 Make_Attribute_Reference (Loc,
12757 Prefix => New_Occurrence_Of (Index, Loc),
12758 Attribute_Name => Name_Succ,
12759 Expressions => New_List (New_Occurrence_Of (J, Loc))))));
12761 -- if X (I) = Y (J) then
12762 -- if ... end if;
12763 -- else
12764 -- return X (I) > Y (J);
12765 -- end if;
12767 Loop_Body :=
12768 Make_Implicit_If_Statement (Nod,
12769 Condition =>
12770 Make_Op_Eq (Loc,
12771 Left_Opnd =>
12772 Make_Indexed_Component (Loc,
12773 Prefix => New_Occurrence_Of (X, Loc),
12774 Expressions => New_List (New_Occurrence_Of (I, Loc))),
12776 Right_Opnd =>
12777 Make_Indexed_Component (Loc,
12778 Prefix => New_Occurrence_Of (Y, Loc),
12779 Expressions => New_List (New_Occurrence_Of (J, Loc)))),
12781 Then_Statements => New_List (Inner_If),
12783 Else_Statements => New_List (
12784 Make_Simple_Return_Statement (Loc,
12785 Expression =>
12786 Make_Op_Gt (Loc,
12787 Left_Opnd =>
12788 Make_Indexed_Component (Loc,
12789 Prefix => New_Occurrence_Of (X, Loc),
12790 Expressions => New_List (New_Occurrence_Of (I, Loc))),
12792 Right_Opnd =>
12793 Make_Indexed_Component (Loc,
12794 Prefix => New_Occurrence_Of (Y, Loc),
12795 Expressions => New_List (
12796 New_Occurrence_Of (J, Loc)))))));
12798 -- for I in X'range loop
12799 -- if ... end if;
12800 -- end loop;
12802 Loop_Statement :=
12803 Make_Implicit_Loop_Statement (Nod,
12804 Identifier => Empty,
12806 Iteration_Scheme =>
12807 Make_Iteration_Scheme (Loc,
12808 Loop_Parameter_Specification =>
12809 Make_Loop_Parameter_Specification (Loc,
12810 Defining_Identifier => I,
12811 Discrete_Subtype_Definition =>
12812 Make_Attribute_Reference (Loc,
12813 Prefix => New_Occurrence_Of (X, Loc),
12814 Attribute_Name => Name_Range))),
12816 Statements => New_List (Loop_Body));
12818 -- if X'length = 0 then
12819 -- return false;
12820 -- elsif Y'length = 0 then
12821 -- return true;
12822 -- else
12823 -- for ... loop ... end loop;
12824 -- return X'length > Y'length;
12825 -- end if;
12827 Length1 :=
12828 Make_Attribute_Reference (Loc,
12829 Prefix => New_Occurrence_Of (X, Loc),
12830 Attribute_Name => Name_Length);
12832 Length2 :=
12833 Make_Attribute_Reference (Loc,
12834 Prefix => New_Occurrence_Of (Y, Loc),
12835 Attribute_Name => Name_Length);
12837 Final_Expr :=
12838 Make_Op_Gt (Loc,
12839 Left_Opnd => Length1,
12840 Right_Opnd => Length2);
12842 If_Stat :=
12843 Make_Implicit_If_Statement (Nod,
12844 Condition =>
12845 Make_Op_Eq (Loc,
12846 Left_Opnd =>
12847 Make_Attribute_Reference (Loc,
12848 Prefix => New_Occurrence_Of (X, Loc),
12849 Attribute_Name => Name_Length),
12850 Right_Opnd =>
12851 Make_Integer_Literal (Loc, 0)),
12853 Then_Statements =>
12854 New_List (
12855 Make_Simple_Return_Statement (Loc,
12856 Expression => New_Occurrence_Of (Standard_False, Loc))),
12858 Elsif_Parts => New_List (
12859 Make_Elsif_Part (Loc,
12860 Condition =>
12861 Make_Op_Eq (Loc,
12862 Left_Opnd =>
12863 Make_Attribute_Reference (Loc,
12864 Prefix => New_Occurrence_Of (Y, Loc),
12865 Attribute_Name => Name_Length),
12866 Right_Opnd =>
12867 Make_Integer_Literal (Loc, 0)),
12869 Then_Statements =>
12870 New_List (
12871 Make_Simple_Return_Statement (Loc,
12872 Expression => New_Occurrence_Of (Standard_True, Loc))))),
12874 Else_Statements => New_List (
12875 Loop_Statement,
12876 Make_Simple_Return_Statement (Loc,
12877 Expression => Final_Expr)));
12879 -- (X : a; Y: a)
12881 Formals := New_List (
12882 Make_Parameter_Specification (Loc,
12883 Defining_Identifier => X,
12884 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
12886 Make_Parameter_Specification (Loc,
12887 Defining_Identifier => Y,
12888 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
12890 -- function Gnnn (...) return boolean is
12891 -- J : index := Y'first;
12892 -- begin
12893 -- if ... end if;
12894 -- end Gnnn;
12896 Func_Name := Make_Temporary (Loc, 'G');
12898 Func_Body :=
12899 Make_Subprogram_Body (Loc,
12900 Specification =>
12901 Make_Function_Specification (Loc,
12902 Defining_Unit_Name => Func_Name,
12903 Parameter_Specifications => Formals,
12904 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
12906 Declarations => New_List (
12907 Make_Object_Declaration (Loc,
12908 Defining_Identifier => J,
12909 Object_Definition => New_Occurrence_Of (Index, Loc),
12910 Expression =>
12911 Make_Attribute_Reference (Loc,
12912 Prefix => New_Occurrence_Of (Y, Loc),
12913 Attribute_Name => Name_First))),
12915 Handled_Statement_Sequence =>
12916 Make_Handled_Sequence_Of_Statements (Loc,
12917 Statements => New_List (If_Stat)));
12919 return Func_Body;
12920 end Make_Array_Comparison_Op;
12922 ---------------------------
12923 -- Make_Boolean_Array_Op --
12924 ---------------------------
12926 -- For logical operations on boolean arrays, expand in line the following,
12927 -- replacing 'and' with 'or' or 'xor' where needed:
12929 -- function Annn (A : typ; B: typ) return typ is
12930 -- C : typ;
12931 -- begin
12932 -- for J in A'range loop
12933 -- C (J) := A (J) op B (J);
12934 -- end loop;
12935 -- return C;
12936 -- end Annn;
12938 -- Here typ is the boolean array type
12940 function Make_Boolean_Array_Op
12941 (Typ : Entity_Id;
12942 N : Node_Id) return Node_Id
12944 Loc : constant Source_Ptr := Sloc (N);
12946 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
12947 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
12948 C : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uC);
12949 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
12951 A_J : Node_Id;
12952 B_J : Node_Id;
12953 C_J : Node_Id;
12954 Op : Node_Id;
12956 Formals : List_Id;
12957 Func_Name : Entity_Id;
12958 Func_Body : Node_Id;
12959 Loop_Statement : Node_Id;
12961 begin
12962 A_J :=
12963 Make_Indexed_Component (Loc,
12964 Prefix => New_Occurrence_Of (A, Loc),
12965 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12967 B_J :=
12968 Make_Indexed_Component (Loc,
12969 Prefix => New_Occurrence_Of (B, Loc),
12970 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12972 C_J :=
12973 Make_Indexed_Component (Loc,
12974 Prefix => New_Occurrence_Of (C, Loc),
12975 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12977 if Nkind (N) = N_Op_And then
12978 Op :=
12979 Make_Op_And (Loc,
12980 Left_Opnd => A_J,
12981 Right_Opnd => B_J);
12983 elsif Nkind (N) = N_Op_Or then
12984 Op :=
12985 Make_Op_Or (Loc,
12986 Left_Opnd => A_J,
12987 Right_Opnd => B_J);
12989 else
12990 Op :=
12991 Make_Op_Xor (Loc,
12992 Left_Opnd => A_J,
12993 Right_Opnd => B_J);
12994 end if;
12996 Loop_Statement :=
12997 Make_Implicit_Loop_Statement (N,
12998 Identifier => Empty,
13000 Iteration_Scheme =>
13001 Make_Iteration_Scheme (Loc,
13002 Loop_Parameter_Specification =>
13003 Make_Loop_Parameter_Specification (Loc,
13004 Defining_Identifier => J,
13005 Discrete_Subtype_Definition =>
13006 Make_Attribute_Reference (Loc,
13007 Prefix => New_Occurrence_Of (A, Loc),
13008 Attribute_Name => Name_Range))),
13010 Statements => New_List (
13011 Make_Assignment_Statement (Loc,
13012 Name => C_J,
13013 Expression => Op)));
13015 Formals := New_List (
13016 Make_Parameter_Specification (Loc,
13017 Defining_Identifier => A,
13018 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
13020 Make_Parameter_Specification (Loc,
13021 Defining_Identifier => B,
13022 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
13024 Func_Name := Make_Temporary (Loc, 'A');
13025 Set_Is_Inlined (Func_Name);
13027 Func_Body :=
13028 Make_Subprogram_Body (Loc,
13029 Specification =>
13030 Make_Function_Specification (Loc,
13031 Defining_Unit_Name => Func_Name,
13032 Parameter_Specifications => Formals,
13033 Result_Definition => New_Occurrence_Of (Typ, Loc)),
13035 Declarations => New_List (
13036 Make_Object_Declaration (Loc,
13037 Defining_Identifier => C,
13038 Object_Definition => New_Occurrence_Of (Typ, Loc))),
13040 Handled_Statement_Sequence =>
13041 Make_Handled_Sequence_Of_Statements (Loc,
13042 Statements => New_List (
13043 Loop_Statement,
13044 Make_Simple_Return_Statement (Loc,
13045 Expression => New_Occurrence_Of (C, Loc)))));
13047 return Func_Body;
13048 end Make_Boolean_Array_Op;
13050 -----------------------------------------
13051 -- Minimized_Eliminated_Overflow_Check --
13052 -----------------------------------------
13054 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean is
13055 begin
13056 return
13057 Is_Signed_Integer_Type (Etype (N))
13058 and then Overflow_Check_Mode in Minimized_Or_Eliminated;
13059 end Minimized_Eliminated_Overflow_Check;
13061 --------------------------------
13062 -- Optimize_Length_Comparison --
13063 --------------------------------
13065 procedure Optimize_Length_Comparison (N : Node_Id) is
13066 Loc : constant Source_Ptr := Sloc (N);
13067 Typ : constant Entity_Id := Etype (N);
13068 Result : Node_Id;
13070 Left : Node_Id;
13071 Right : Node_Id;
13072 -- First and Last attribute reference nodes, which end up as left and
13073 -- right operands of the optimized result.
13075 Is_Zero : Boolean;
13076 -- True for comparison operand of zero
13078 Comp : Node_Id;
13079 -- Comparison operand, set only if Is_Zero is false
13081 Ent : Entity_Id := Empty;
13082 -- Entity whose length is being compared
13084 Index : Node_Id := Empty;
13085 -- Integer_Literal node for length attribute expression, or Empty
13086 -- if there is no such expression present.
13088 Ityp : Entity_Id;
13089 -- Type of array index to which 'Length is applied
13091 Op : Node_Kind := Nkind (N);
13092 -- Kind of comparison operator, gets flipped if operands backwards
13094 function Is_Optimizable (N : Node_Id) return Boolean;
13095 -- Tests N to see if it is an optimizable comparison value (defined as
13096 -- constant zero or one, or something else where the value is known to
13097 -- be positive and in the range of 32-bits, and where the corresponding
13098 -- Length value is also known to be 32-bits. If result is true, sets
13099 -- Is_Zero, Ityp, and Comp accordingly.
13101 function Is_Entity_Length (N : Node_Id) return Boolean;
13102 -- Tests if N is a length attribute applied to a simple entity. If so,
13103 -- returns True, and sets Ent to the entity, and Index to the integer
13104 -- literal provided as an attribute expression, or to Empty if none.
13105 -- Also returns True if the expression is a generated type conversion
13106 -- whose expression is of the desired form. This latter case arises
13107 -- when Apply_Universal_Integer_Attribute_Check installs a conversion
13108 -- to check for being in range, which is not needed in this context.
13109 -- Returns False if neither condition holds.
13111 function Prepare_64 (N : Node_Id) return Node_Id;
13112 -- Given a discrete expression, returns a Long_Long_Integer typed
13113 -- expression representing the underlying value of the expression.
13114 -- This is done with an unchecked conversion to the result type. We
13115 -- use unchecked conversion to handle the enumeration type case.
13117 ----------------------
13118 -- Is_Entity_Length --
13119 ----------------------
13121 function Is_Entity_Length (N : Node_Id) return Boolean is
13122 begin
13123 if Nkind (N) = N_Attribute_Reference
13124 and then Attribute_Name (N) = Name_Length
13125 and then Is_Entity_Name (Prefix (N))
13126 then
13127 Ent := Entity (Prefix (N));
13129 if Present (Expressions (N)) then
13130 Index := First (Expressions (N));
13131 else
13132 Index := Empty;
13133 end if;
13135 return True;
13137 elsif Nkind (N) = N_Type_Conversion
13138 and then not Comes_From_Source (N)
13139 then
13140 return Is_Entity_Length (Expression (N));
13142 else
13143 return False;
13144 end if;
13145 end Is_Entity_Length;
13147 --------------------
13148 -- Is_Optimizable --
13149 --------------------
13151 function Is_Optimizable (N : Node_Id) return Boolean is
13152 Val : Uint;
13153 OK : Boolean;
13154 Lo : Uint;
13155 Hi : Uint;
13156 Indx : Node_Id;
13158 begin
13159 if Compile_Time_Known_Value (N) then
13160 Val := Expr_Value (N);
13162 if Val = Uint_0 then
13163 Is_Zero := True;
13164 Comp := Empty;
13165 return True;
13167 elsif Val = Uint_1 then
13168 Is_Zero := False;
13169 Comp := Empty;
13170 return True;
13171 end if;
13172 end if;
13174 -- Here we have to make sure of being within 32-bits
13176 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
13178 if not OK
13179 or else Lo < Uint_1
13180 or else Hi > UI_From_Int (Int'Last)
13181 then
13182 return False;
13183 end if;
13185 -- Comparison value was within range, so now we must check the index
13186 -- value to make sure it is also within 32-bits.
13188 Indx := First_Index (Etype (Ent));
13190 if Present (Index) then
13191 for J in 2 .. UI_To_Int (Intval (Index)) loop
13192 Next_Index (Indx);
13193 end loop;
13194 end if;
13196 Ityp := Etype (Indx);
13198 if Esize (Ityp) > 32 then
13199 return False;
13200 end if;
13202 Is_Zero := False;
13203 Comp := N;
13204 return True;
13205 end Is_Optimizable;
13207 ----------------
13208 -- Prepare_64 --
13209 ----------------
13211 function Prepare_64 (N : Node_Id) return Node_Id is
13212 begin
13213 return Unchecked_Convert_To (Standard_Long_Long_Integer, N);
13214 end Prepare_64;
13216 -- Start of processing for Optimize_Length_Comparison
13218 begin
13219 -- Nothing to do if not a comparison
13221 if Op not in N_Op_Compare then
13222 return;
13223 end if;
13225 -- Nothing to do if special -gnatd.P debug flag set.
13227 if Debug_Flag_Dot_PP then
13228 return;
13229 end if;
13231 -- Ent'Length op 0/1
13233 if Is_Entity_Length (Left_Opnd (N))
13234 and then Is_Optimizable (Right_Opnd (N))
13235 then
13236 null;
13238 -- 0/1 op Ent'Length
13240 elsif Is_Entity_Length (Right_Opnd (N))
13241 and then Is_Optimizable (Left_Opnd (N))
13242 then
13243 -- Flip comparison to opposite sense
13245 case Op is
13246 when N_Op_Lt => Op := N_Op_Gt;
13247 when N_Op_Le => Op := N_Op_Ge;
13248 when N_Op_Gt => Op := N_Op_Lt;
13249 when N_Op_Ge => Op := N_Op_Le;
13250 when others => null;
13251 end case;
13253 -- Else optimization not possible
13255 else
13256 return;
13257 end if;
13259 -- Fall through if we will do the optimization
13261 -- Cases to handle:
13263 -- X'Length = 0 => X'First > X'Last
13264 -- X'Length = 1 => X'First = X'Last
13265 -- X'Length = n => X'First + (n - 1) = X'Last
13267 -- X'Length /= 0 => X'First <= X'Last
13268 -- X'Length /= 1 => X'First /= X'Last
13269 -- X'Length /= n => X'First + (n - 1) /= X'Last
13271 -- X'Length >= 0 => always true, warn
13272 -- X'Length >= 1 => X'First <= X'Last
13273 -- X'Length >= n => X'First + (n - 1) <= X'Last
13275 -- X'Length > 0 => X'First <= X'Last
13276 -- X'Length > 1 => X'First < X'Last
13277 -- X'Length > n => X'First + (n - 1) < X'Last
13279 -- X'Length <= 0 => X'First > X'Last (warn, could be =)
13280 -- X'Length <= 1 => X'First >= X'Last
13281 -- X'Length <= n => X'First + (n - 1) >= X'Last
13283 -- X'Length < 0 => always false (warn)
13284 -- X'Length < 1 => X'First > X'Last
13285 -- X'Length < n => X'First + (n - 1) > X'Last
13287 -- Note: for the cases of n (not constant 0,1), we require that the
13288 -- corresponding index type be integer or shorter (i.e. not 64-bit),
13289 -- and the same for the comparison value. Then we do the comparison
13290 -- using 64-bit arithmetic (actually long long integer), so that we
13291 -- cannot have overflow intefering with the result.
13293 -- First deal with warning cases
13295 if Is_Zero then
13296 case Op is
13298 -- X'Length >= 0
13300 when N_Op_Ge =>
13301 Rewrite (N,
13302 Convert_To (Typ, New_Occurrence_Of (Standard_True, Loc)));
13303 Analyze_And_Resolve (N, Typ);
13304 Warn_On_Known_Condition (N);
13305 return;
13307 -- X'Length < 0
13309 when N_Op_Lt =>
13310 Rewrite (N,
13311 Convert_To (Typ, New_Occurrence_Of (Standard_False, Loc)));
13312 Analyze_And_Resolve (N, Typ);
13313 Warn_On_Known_Condition (N);
13314 return;
13316 when N_Op_Le =>
13317 if Constant_Condition_Warnings
13318 and then Comes_From_Source (Original_Node (N))
13319 then
13320 Error_Msg_N ("could replace by ""'=""?c?", N);
13321 end if;
13323 Op := N_Op_Eq;
13325 when others =>
13326 null;
13327 end case;
13328 end if;
13330 -- Build the First reference we will use
13332 Left :=
13333 Make_Attribute_Reference (Loc,
13334 Prefix => New_Occurrence_Of (Ent, Loc),
13335 Attribute_Name => Name_First);
13337 if Present (Index) then
13338 Set_Expressions (Left, New_List (New_Copy (Index)));
13339 end if;
13341 -- If general value case, then do the addition of (n - 1), and
13342 -- also add the needed conversions to type Long_Long_Integer.
13344 if Present (Comp) then
13345 Left :=
13346 Make_Op_Add (Loc,
13347 Left_Opnd => Prepare_64 (Left),
13348 Right_Opnd =>
13349 Make_Op_Subtract (Loc,
13350 Left_Opnd => Prepare_64 (Comp),
13351 Right_Opnd => Make_Integer_Literal (Loc, 1)));
13352 end if;
13354 -- Build the Last reference we will use
13356 Right :=
13357 Make_Attribute_Reference (Loc,
13358 Prefix => New_Occurrence_Of (Ent, Loc),
13359 Attribute_Name => Name_Last);
13361 if Present (Index) then
13362 Set_Expressions (Right, New_List (New_Copy (Index)));
13363 end if;
13365 -- If general operand, convert Last reference to Long_Long_Integer
13367 if Present (Comp) then
13368 Right := Prepare_64 (Right);
13369 end if;
13371 -- Check for cases to optimize
13373 -- X'Length = 0 => X'First > X'Last
13374 -- X'Length < 1 => X'First > X'Last
13375 -- X'Length < n => X'First + (n - 1) > X'Last
13377 if (Is_Zero and then Op = N_Op_Eq)
13378 or else (not Is_Zero and then Op = N_Op_Lt)
13379 then
13380 Result :=
13381 Make_Op_Gt (Loc,
13382 Left_Opnd => Left,
13383 Right_Opnd => Right);
13385 -- X'Length = 1 => X'First = X'Last
13386 -- X'Length = n => X'First + (n - 1) = X'Last
13388 elsif not Is_Zero and then Op = N_Op_Eq then
13389 Result :=
13390 Make_Op_Eq (Loc,
13391 Left_Opnd => Left,
13392 Right_Opnd => Right);
13394 -- X'Length /= 0 => X'First <= X'Last
13395 -- X'Length > 0 => X'First <= X'Last
13397 elsif Is_Zero and (Op = N_Op_Ne or else Op = N_Op_Gt) then
13398 Result :=
13399 Make_Op_Le (Loc,
13400 Left_Opnd => Left,
13401 Right_Opnd => Right);
13403 -- X'Length /= 1 => X'First /= X'Last
13404 -- X'Length /= n => X'First + (n - 1) /= X'Last
13406 elsif not Is_Zero and then Op = N_Op_Ne then
13407 Result :=
13408 Make_Op_Ne (Loc,
13409 Left_Opnd => Left,
13410 Right_Opnd => Right);
13412 -- X'Length >= 1 => X'First <= X'Last
13413 -- X'Length >= n => X'First + (n - 1) <= X'Last
13415 elsif not Is_Zero and then Op = N_Op_Ge then
13416 Result :=
13417 Make_Op_Le (Loc,
13418 Left_Opnd => Left,
13419 Right_Opnd => Right);
13421 -- X'Length > 1 => X'First < X'Last
13422 -- X'Length > n => X'First + (n = 1) < X'Last
13424 elsif not Is_Zero and then Op = N_Op_Gt then
13425 Result :=
13426 Make_Op_Lt (Loc,
13427 Left_Opnd => Left,
13428 Right_Opnd => Right);
13430 -- X'Length <= 1 => X'First >= X'Last
13431 -- X'Length <= n => X'First + (n - 1) >= X'Last
13433 elsif not Is_Zero and then Op = N_Op_Le then
13434 Result :=
13435 Make_Op_Ge (Loc,
13436 Left_Opnd => Left,
13437 Right_Opnd => Right);
13439 -- Should not happen at this stage
13441 else
13442 raise Program_Error;
13443 end if;
13445 -- Rewrite and finish up
13447 Rewrite (N, Result);
13448 Analyze_And_Resolve (N, Typ);
13449 return;
13450 end Optimize_Length_Comparison;
13452 --------------------------------
13453 -- Process_If_Case_Statements --
13454 --------------------------------
13456 procedure Process_If_Case_Statements (N : Node_Id; Stmts : List_Id) is
13457 Decl : Node_Id;
13459 begin
13460 Decl := First (Stmts);
13461 while Present (Decl) loop
13462 if Nkind (Decl) = N_Object_Declaration
13463 and then Is_Finalizable_Transient (Decl, N)
13464 then
13465 Process_Transient_In_Expression (Decl, N, Stmts);
13466 end if;
13468 Next (Decl);
13469 end loop;
13470 end Process_If_Case_Statements;
13472 -------------------------------------
13473 -- Process_Transient_In_Expression --
13474 -------------------------------------
13476 procedure Process_Transient_In_Expression
13477 (Obj_Decl : Node_Id;
13478 Expr : Node_Id;
13479 Stmts : List_Id)
13481 Loc : constant Source_Ptr := Sloc (Obj_Decl);
13482 Obj_Id : constant Entity_Id := Defining_Identifier (Obj_Decl);
13484 Hook_Context : constant Node_Id := Find_Hook_Context (Expr);
13485 -- The node on which to insert the hook as an action. This is usually
13486 -- the innermost enclosing non-transient construct.
13488 Fin_Call : Node_Id;
13489 Hook_Assign : Node_Id;
13490 Hook_Clear : Node_Id;
13491 Hook_Decl : Node_Id;
13492 Hook_Insert : Node_Id;
13493 Ptr_Decl : Node_Id;
13495 Fin_Context : Node_Id;
13496 -- The node after which to insert the finalization actions of the
13497 -- transient object.
13499 begin
13500 pragma Assert (Nkind_In (Expr, N_Case_Expression,
13501 N_Expression_With_Actions,
13502 N_If_Expression));
13504 -- When the context is a Boolean evaluation, all three nodes capture the
13505 -- result of their computation in a local temporary:
13507 -- do
13508 -- Trans_Id : Ctrl_Typ := ...;
13509 -- Result : constant Boolean := ... Trans_Id ...;
13510 -- <finalize Trans_Id>
13511 -- in Result end;
13513 -- As a result, the finalization of any transient objects can safely
13514 -- take place after the result capture.
13516 -- ??? could this be extended to elementary types?
13518 if Is_Boolean_Type (Etype (Expr)) then
13519 Fin_Context := Last (Stmts);
13521 -- Otherwise the immediate context may not be safe enough to carry
13522 -- out transient object finalization due to aliasing and nesting of
13523 -- constructs. Insert calls to [Deep_]Finalize after the innermost
13524 -- enclosing non-transient construct.
13526 else
13527 Fin_Context := Hook_Context;
13528 end if;
13530 -- Mark the transient object as successfully processed to avoid double
13531 -- finalization.
13533 Set_Is_Finalized_Transient (Obj_Id);
13535 -- Construct all the pieces necessary to hook and finalize a transient
13536 -- object.
13538 Build_Transient_Object_Statements
13539 (Obj_Decl => Obj_Decl,
13540 Fin_Call => Fin_Call,
13541 Hook_Assign => Hook_Assign,
13542 Hook_Clear => Hook_Clear,
13543 Hook_Decl => Hook_Decl,
13544 Ptr_Decl => Ptr_Decl,
13545 Finalize_Obj => False);
13547 -- Add the access type which provides a reference to the transient
13548 -- object. Generate:
13550 -- type Ptr_Typ is access all Desig_Typ;
13552 Insert_Action (Hook_Context, Ptr_Decl);
13554 -- Add the temporary which acts as a hook to the transient object.
13555 -- Generate:
13557 -- Hook : Ptr_Id := null;
13559 Insert_Action (Hook_Context, Hook_Decl);
13561 -- When the transient object is initialized by an aggregate, the hook
13562 -- must capture the object after the last aggregate assignment takes
13563 -- place. Only then is the object considered initialized. Generate:
13565 -- Hook := Ptr_Typ (Obj_Id);
13566 -- <or>
13567 -- Hook := Obj_Id'Unrestricted_Access;
13569 if Ekind_In (Obj_Id, E_Constant, E_Variable)
13570 and then Present (Last_Aggregate_Assignment (Obj_Id))
13571 then
13572 Hook_Insert := Last_Aggregate_Assignment (Obj_Id);
13574 -- Otherwise the hook seizes the related object immediately
13576 else
13577 Hook_Insert := Obj_Decl;
13578 end if;
13580 Insert_After_And_Analyze (Hook_Insert, Hook_Assign);
13582 -- When the node is part of a return statement, there is no need to
13583 -- insert a finalization call, as the general finalization mechanism
13584 -- (see Build_Finalizer) would take care of the transient object on
13585 -- subprogram exit. Note that it would also be impossible to insert the
13586 -- finalization code after the return statement as this will render it
13587 -- unreachable.
13589 if Nkind (Fin_Context) = N_Simple_Return_Statement then
13590 null;
13592 -- Finalize the hook after the context has been evaluated. Generate:
13594 -- if Hook /= null then
13595 -- [Deep_]Finalize (Hook.all);
13596 -- Hook := null;
13597 -- end if;
13599 else
13600 Insert_Action_After (Fin_Context,
13601 Make_Implicit_If_Statement (Obj_Decl,
13602 Condition =>
13603 Make_Op_Ne (Loc,
13604 Left_Opnd =>
13605 New_Occurrence_Of (Defining_Entity (Hook_Decl), Loc),
13606 Right_Opnd => Make_Null (Loc)),
13608 Then_Statements => New_List (
13609 Fin_Call,
13610 Hook_Clear)));
13611 end if;
13612 end Process_Transient_In_Expression;
13614 ------------------------
13615 -- Rewrite_Comparison --
13616 ------------------------
13618 procedure Rewrite_Comparison (N : Node_Id) is
13619 Typ : constant Entity_Id := Etype (N);
13621 False_Result : Boolean;
13622 True_Result : Boolean;
13624 begin
13625 if Nkind (N) = N_Type_Conversion then
13626 Rewrite_Comparison (Expression (N));
13627 return;
13629 elsif Nkind (N) not in N_Op_Compare then
13630 return;
13631 end if;
13633 -- Determine the potential outcome of the comparison assuming that the
13634 -- operands are valid and emit a warning when the comparison evaluates
13635 -- to True or False only in the presence of invalid values.
13637 Warn_On_Constant_Valid_Condition (N);
13639 -- Determine the potential outcome of the comparison assuming that the
13640 -- operands are not valid.
13642 Test_Comparison
13643 (Op => N,
13644 Assume_Valid => False,
13645 True_Result => True_Result,
13646 False_Result => False_Result);
13648 -- The outcome is a decisive False or True, rewrite the operator
13650 if False_Result or True_Result then
13651 Rewrite (N,
13652 Convert_To (Typ,
13653 New_Occurrence_Of (Boolean_Literals (True_Result), Sloc (N))));
13655 Analyze_And_Resolve (N, Typ);
13656 Warn_On_Known_Condition (N);
13657 end if;
13658 end Rewrite_Comparison;
13660 ----------------------------
13661 -- Safe_In_Place_Array_Op --
13662 ----------------------------
13664 function Safe_In_Place_Array_Op
13665 (Lhs : Node_Id;
13666 Op1 : Node_Id;
13667 Op2 : Node_Id) return Boolean
13669 Target : Entity_Id;
13671 function Is_Safe_Operand (Op : Node_Id) return Boolean;
13672 -- Operand is safe if it cannot overlap part of the target of the
13673 -- operation. If the operand and the target are identical, the operand
13674 -- is safe. The operand can be empty in the case of negation.
13676 function Is_Unaliased (N : Node_Id) return Boolean;
13677 -- Check that N is a stand-alone entity
13679 ------------------
13680 -- Is_Unaliased --
13681 ------------------
13683 function Is_Unaliased (N : Node_Id) return Boolean is
13684 begin
13685 return
13686 Is_Entity_Name (N)
13687 and then No (Address_Clause (Entity (N)))
13688 and then No (Renamed_Object (Entity (N)));
13689 end Is_Unaliased;
13691 ---------------------
13692 -- Is_Safe_Operand --
13693 ---------------------
13695 function Is_Safe_Operand (Op : Node_Id) return Boolean is
13696 begin
13697 if No (Op) then
13698 return True;
13700 elsif Is_Entity_Name (Op) then
13701 return Is_Unaliased (Op);
13703 elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
13704 return Is_Unaliased (Prefix (Op));
13706 elsif Nkind (Op) = N_Slice then
13707 return
13708 Is_Unaliased (Prefix (Op))
13709 and then Entity (Prefix (Op)) /= Target;
13711 elsif Nkind (Op) = N_Op_Not then
13712 return Is_Safe_Operand (Right_Opnd (Op));
13714 else
13715 return False;
13716 end if;
13717 end Is_Safe_Operand;
13719 -- Start of processing for Safe_In_Place_Array_Op
13721 begin
13722 -- Skip this processing if the component size is different from system
13723 -- storage unit (since at least for NOT this would cause problems).
13725 if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
13726 return False;
13728 -- Cannot do in place stuff if non-standard Boolean representation
13730 elsif Has_Non_Standard_Rep (Component_Type (Etype (Lhs))) then
13731 return False;
13733 elsif not Is_Unaliased (Lhs) then
13734 return False;
13736 else
13737 Target := Entity (Lhs);
13738 return Is_Safe_Operand (Op1) and then Is_Safe_Operand (Op2);
13739 end if;
13740 end Safe_In_Place_Array_Op;
13742 -----------------------
13743 -- Tagged_Membership --
13744 -----------------------
13746 -- There are two different cases to consider depending on whether the right
13747 -- operand is a class-wide type or not. If not we just compare the actual
13748 -- tag of the left expr to the target type tag:
13750 -- Left_Expr.Tag = Right_Type'Tag;
13752 -- If it is a class-wide type we use the RT function CW_Membership which is
13753 -- usually implemented by looking in the ancestor tables contained in the
13754 -- dispatch table pointed by Left_Expr.Tag for Typ'Tag
13756 -- Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
13757 -- function IW_Membership which is usually implemented by looking in the
13758 -- table of abstract interface types plus the ancestor table contained in
13759 -- the dispatch table pointed by Left_Expr.Tag for Typ'Tag
13761 procedure Tagged_Membership
13762 (N : Node_Id;
13763 SCIL_Node : out Node_Id;
13764 Result : out Node_Id)
13766 Left : constant Node_Id := Left_Opnd (N);
13767 Right : constant Node_Id := Right_Opnd (N);
13768 Loc : constant Source_Ptr := Sloc (N);
13770 Full_R_Typ : Entity_Id;
13771 Left_Type : Entity_Id;
13772 New_Node : Node_Id;
13773 Right_Type : Entity_Id;
13774 Obj_Tag : Node_Id;
13776 begin
13777 SCIL_Node := Empty;
13779 -- Handle entities from the limited view
13781 Left_Type := Available_View (Etype (Left));
13782 Right_Type := Available_View (Etype (Right));
13784 -- In the case where the type is an access type, the test is applied
13785 -- using the designated types (needed in Ada 2012 for implicit anonymous
13786 -- access conversions, for AI05-0149).
13788 if Is_Access_Type (Right_Type) then
13789 Left_Type := Designated_Type (Left_Type);
13790 Right_Type := Designated_Type (Right_Type);
13791 end if;
13793 if Is_Class_Wide_Type (Left_Type) then
13794 Left_Type := Root_Type (Left_Type);
13795 end if;
13797 if Is_Class_Wide_Type (Right_Type) then
13798 Full_R_Typ := Underlying_Type (Root_Type (Right_Type));
13799 else
13800 Full_R_Typ := Underlying_Type (Right_Type);
13801 end if;
13803 Obj_Tag :=
13804 Make_Selected_Component (Loc,
13805 Prefix => Relocate_Node (Left),
13806 Selector_Name =>
13807 New_Occurrence_Of (First_Tag_Component (Left_Type), Loc));
13809 if Is_Class_Wide_Type (Right_Type) then
13811 -- No need to issue a run-time check if we statically know that the
13812 -- result of this membership test is always true. For example,
13813 -- considering the following declarations:
13815 -- type Iface is interface;
13816 -- type T is tagged null record;
13817 -- type DT is new T and Iface with null record;
13819 -- Obj1 : T;
13820 -- Obj2 : DT;
13822 -- These membership tests are always true:
13824 -- Obj1 in T'Class
13825 -- Obj2 in T'Class;
13826 -- Obj2 in Iface'Class;
13828 -- We do not need to handle cases where the membership is illegal.
13829 -- For example:
13831 -- Obj1 in DT'Class; -- Compile time error
13832 -- Obj1 in Iface'Class; -- Compile time error
13834 if not Is_Class_Wide_Type (Left_Type)
13835 and then (Is_Ancestor (Etype (Right_Type), Left_Type,
13836 Use_Full_View => True)
13837 or else (Is_Interface (Etype (Right_Type))
13838 and then Interface_Present_In_Ancestor
13839 (Typ => Left_Type,
13840 Iface => Etype (Right_Type))))
13841 then
13842 Result := New_Occurrence_Of (Standard_True, Loc);
13843 return;
13844 end if;
13846 -- Ada 2005 (AI-251): Class-wide applied to interfaces
13848 if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
13850 -- Support to: "Iface_CW_Typ in Typ'Class"
13852 or else Is_Interface (Left_Type)
13853 then
13854 -- Issue error if IW_Membership operation not available in a
13855 -- configurable run time setting.
13857 if not RTE_Available (RE_IW_Membership) then
13858 Error_Msg_CRT
13859 ("dynamic membership test on interface types", N);
13860 Result := Empty;
13861 return;
13862 end if;
13864 Result :=
13865 Make_Function_Call (Loc,
13866 Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
13867 Parameter_Associations => New_List (
13868 Make_Attribute_Reference (Loc,
13869 Prefix => Obj_Tag,
13870 Attribute_Name => Name_Address),
13871 New_Occurrence_Of (
13872 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))),
13873 Loc)));
13875 -- Ada 95: Normal case
13877 else
13878 Build_CW_Membership (Loc,
13879 Obj_Tag_Node => Obj_Tag,
13880 Typ_Tag_Node =>
13881 New_Occurrence_Of (
13882 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc),
13883 Related_Nod => N,
13884 New_Node => New_Node);
13886 -- Generate the SCIL node for this class-wide membership test.
13887 -- Done here because the previous call to Build_CW_Membership
13888 -- relocates Obj_Tag.
13890 if Generate_SCIL then
13891 SCIL_Node := Make_SCIL_Membership_Test (Sloc (N));
13892 Set_SCIL_Entity (SCIL_Node, Etype (Right_Type));
13893 Set_SCIL_Tag_Value (SCIL_Node, Obj_Tag);
13894 end if;
13896 Result := New_Node;
13897 end if;
13899 -- Right_Type is not a class-wide type
13901 else
13902 -- No need to check the tag of the object if Right_Typ is abstract
13904 if Is_Abstract_Type (Right_Type) then
13905 Result := New_Occurrence_Of (Standard_False, Loc);
13907 else
13908 Result :=
13909 Make_Op_Eq (Loc,
13910 Left_Opnd => Obj_Tag,
13911 Right_Opnd =>
13912 New_Occurrence_Of
13913 (Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc));
13914 end if;
13915 end if;
13916 end Tagged_Membership;
13918 ------------------------------
13919 -- Unary_Op_Validity_Checks --
13920 ------------------------------
13922 procedure Unary_Op_Validity_Checks (N : Node_Id) is
13923 begin
13924 if Validity_Checks_On and Validity_Check_Operands then
13925 Ensure_Valid (Right_Opnd (N));
13926 end if;
13927 end Unary_Op_Validity_Checks;
13929 end Exp_Ch4;