PR rtl-optimization/82913
[official-gcc.git] / gcc / ada / exp_ch4.adb
blob88303c66861cead8050dd0cd8575c793fbf26b84
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 we are not generating C code for a nonbinary
4176 -- modular operand.
4178 if not Modify_Tree_For_C
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 -- When generating C code, convert nonbinary modular additions into code
6903 -- that relies on the front-end expansion of operator Mod.
6905 if Modify_Tree_For_C then
6906 Expand_Nonbinary_Modular_Op (N);
6907 end if;
6908 end Expand_N_Op_Add;
6910 ---------------------
6911 -- Expand_N_Op_And --
6912 ---------------------
6914 procedure Expand_N_Op_And (N : Node_Id) is
6915 Typ : constant Entity_Id := Etype (N);
6917 begin
6918 Binary_Op_Validity_Checks (N);
6920 if Is_Array_Type (Etype (N)) then
6921 Expand_Boolean_Operator (N);
6923 elsif Is_Boolean_Type (Etype (N)) then
6924 Adjust_Condition (Left_Opnd (N));
6925 Adjust_Condition (Right_Opnd (N));
6926 Set_Etype (N, Standard_Boolean);
6927 Adjust_Result_Type (N, Typ);
6929 elsif Is_Intrinsic_Subprogram (Entity (N)) then
6930 Expand_Intrinsic_Call (N, Entity (N));
6931 end if;
6933 -- When generating C code, convert nonbinary modular operators into code
6934 -- that relies on the front-end expansion of operator Mod.
6936 if Modify_Tree_For_C then
6937 Expand_Nonbinary_Modular_Op (N);
6938 end if;
6939 end Expand_N_Op_And;
6941 ------------------------
6942 -- Expand_N_Op_Concat --
6943 ------------------------
6945 procedure Expand_N_Op_Concat (N : Node_Id) is
6946 Opnds : List_Id;
6947 -- List of operands to be concatenated
6949 Cnode : Node_Id;
6950 -- Node which is to be replaced by the result of concatenating the nodes
6951 -- in the list Opnds.
6953 begin
6954 -- Ensure validity of both operands
6956 Binary_Op_Validity_Checks (N);
6958 -- If we are the left operand of a concatenation higher up the tree,
6959 -- then do nothing for now, since we want to deal with a series of
6960 -- concatenations as a unit.
6962 if Nkind (Parent (N)) = N_Op_Concat
6963 and then N = Left_Opnd (Parent (N))
6964 then
6965 return;
6966 end if;
6968 -- We get here with a concatenation whose left operand may be a
6969 -- concatenation itself with a consistent type. We need to process
6970 -- these concatenation operands from left to right, which means
6971 -- from the deepest node in the tree to the highest node.
6973 Cnode := N;
6974 while Nkind (Left_Opnd (Cnode)) = N_Op_Concat loop
6975 Cnode := Left_Opnd (Cnode);
6976 end loop;
6978 -- Now Cnode is the deepest concatenation, and its parents are the
6979 -- concatenation nodes above, so now we process bottom up, doing the
6980 -- operands.
6982 -- The outer loop runs more than once if more than one concatenation
6983 -- type is involved.
6985 Outer : loop
6986 Opnds := New_List (Left_Opnd (Cnode), Right_Opnd (Cnode));
6987 Set_Parent (Opnds, N);
6989 -- The inner loop gathers concatenation operands
6991 Inner : while Cnode /= N
6992 and then Base_Type (Etype (Cnode)) =
6993 Base_Type (Etype (Parent (Cnode)))
6994 loop
6995 Cnode := Parent (Cnode);
6996 Append (Right_Opnd (Cnode), Opnds);
6997 end loop Inner;
6999 -- Note: The following code is a temporary workaround for N731-034
7000 -- and N829-028 and will be kept until the general issue of internal
7001 -- symbol serialization is addressed. The workaround is kept under a
7002 -- debug switch to avoid permiating into the general case.
7004 -- Wrap the node to concatenate into an expression actions node to
7005 -- keep it nicely packaged. This is useful in the case of an assert
7006 -- pragma with a concatenation where we want to be able to delete
7007 -- the concatenation and all its expansion stuff.
7009 if Debug_Flag_Dot_H then
7010 declare
7011 Cnod : constant Node_Id := New_Copy_Tree (Cnode);
7012 Typ : constant Entity_Id := Base_Type (Etype (Cnode));
7014 begin
7015 -- Note: use Rewrite rather than Replace here, so that for
7016 -- example Why_Not_Static can find the original concatenation
7017 -- node OK!
7019 Rewrite (Cnode,
7020 Make_Expression_With_Actions (Sloc (Cnode),
7021 Actions => New_List (Make_Null_Statement (Sloc (Cnode))),
7022 Expression => Cnod));
7024 Expand_Concatenate (Cnod, Opnds);
7025 Analyze_And_Resolve (Cnode, Typ);
7026 end;
7028 -- Default case
7030 else
7031 Expand_Concatenate (Cnode, Opnds);
7032 end if;
7034 exit Outer when Cnode = N;
7035 Cnode := Parent (Cnode);
7036 end loop Outer;
7037 end Expand_N_Op_Concat;
7039 ------------------------
7040 -- Expand_N_Op_Divide --
7041 ------------------------
7043 procedure Expand_N_Op_Divide (N : Node_Id) is
7044 Loc : constant Source_Ptr := Sloc (N);
7045 Lopnd : constant Node_Id := Left_Opnd (N);
7046 Ropnd : constant Node_Id := Right_Opnd (N);
7047 Ltyp : constant Entity_Id := Etype (Lopnd);
7048 Rtyp : constant Entity_Id := Etype (Ropnd);
7049 Typ : Entity_Id := Etype (N);
7050 Rknow : constant Boolean := Is_Integer_Type (Typ)
7051 and then
7052 Compile_Time_Known_Value (Ropnd);
7053 Rval : Uint;
7055 begin
7056 Binary_Op_Validity_Checks (N);
7058 -- Check for MINIMIZED/ELIMINATED overflow mode
7060 if Minimized_Eliminated_Overflow_Check (N) then
7061 Apply_Arithmetic_Overflow_Check (N);
7062 return;
7063 end if;
7065 -- Otherwise proceed with expansion of division
7067 if Rknow then
7068 Rval := Expr_Value (Ropnd);
7069 end if;
7071 -- N / 1 = N for integer types
7073 if Rknow and then Rval = Uint_1 then
7074 Rewrite (N, Lopnd);
7075 return;
7076 end if;
7078 -- Convert x / 2 ** y to Shift_Right (x, y). Note that the fact that
7079 -- Is_Power_Of_2_For_Shift is set means that we know that our left
7080 -- operand is an unsigned integer, as required for this to work.
7082 if Nkind (Ropnd) = N_Op_Expon
7083 and then Is_Power_Of_2_For_Shift (Ropnd)
7085 -- We cannot do this transformation in configurable run time mode if we
7086 -- have 64-bit integers and long shifts are not available.
7088 and then (Esize (Ltyp) <= 32 or else Support_Long_Shifts_On_Target)
7089 then
7090 Rewrite (N,
7091 Make_Op_Shift_Right (Loc,
7092 Left_Opnd => Lopnd,
7093 Right_Opnd =>
7094 Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
7095 Analyze_And_Resolve (N, Typ);
7096 return;
7097 end if;
7099 -- Do required fixup of universal fixed operation
7101 if Typ = Universal_Fixed then
7102 Fixup_Universal_Fixed_Operation (N);
7103 Typ := Etype (N);
7104 end if;
7106 -- Divisions with fixed-point results
7108 if Is_Fixed_Point_Type (Typ) then
7110 -- No special processing if Treat_Fixed_As_Integer is set, since
7111 -- from a semantic point of view such operations are simply integer
7112 -- operations and will be treated that way.
7114 if not Treat_Fixed_As_Integer (N) then
7115 if Is_Integer_Type (Rtyp) then
7116 Expand_Divide_Fixed_By_Integer_Giving_Fixed (N);
7117 else
7118 Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N);
7119 end if;
7120 end if;
7122 -- Deal with divide-by-zero check if back end cannot handle them
7123 -- and the flag is set indicating that we need such a check. Note
7124 -- that we don't need to bother here with the case of mixed-mode
7125 -- (Right operand an integer type), since these will be rewritten
7126 -- with conversions to a divide with a fixed-point right operand.
7128 if Nkind (N) = N_Op_Divide
7129 and then Do_Division_Check (N)
7130 and then not Backend_Divide_Checks_On_Target
7131 and then not Is_Integer_Type (Rtyp)
7132 then
7133 Set_Do_Division_Check (N, False);
7134 Insert_Action (N,
7135 Make_Raise_Constraint_Error (Loc,
7136 Condition =>
7137 Make_Op_Eq (Loc,
7138 Left_Opnd => Duplicate_Subexpr_Move_Checks (Ropnd),
7139 Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
7140 Reason => CE_Divide_By_Zero));
7141 end if;
7143 -- Other cases of division of fixed-point operands. Again we exclude the
7144 -- case where Treat_Fixed_As_Integer is set.
7146 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
7147 and then not Treat_Fixed_As_Integer (N)
7148 then
7149 if Is_Integer_Type (Typ) then
7150 Expand_Divide_Fixed_By_Fixed_Giving_Integer (N);
7151 else
7152 pragma Assert (Is_Floating_Point_Type (Typ));
7153 Expand_Divide_Fixed_By_Fixed_Giving_Float (N);
7154 end if;
7156 -- Mixed-mode operations can appear in a non-static universal context,
7157 -- in which case the integer argument must be converted explicitly.
7159 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
7160 Rewrite (Ropnd,
7161 Convert_To (Universal_Real, Relocate_Node (Ropnd)));
7163 Analyze_And_Resolve (Ropnd, Universal_Real);
7165 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
7166 Rewrite (Lopnd,
7167 Convert_To (Universal_Real, Relocate_Node (Lopnd)));
7169 Analyze_And_Resolve (Lopnd, Universal_Real);
7171 -- Non-fixed point cases, do integer zero divide and overflow checks
7173 elsif Is_Integer_Type (Typ) then
7174 Apply_Divide_Checks (N);
7175 end if;
7177 -- Overflow checks for floating-point if -gnateF mode active
7179 Check_Float_Op_Overflow (N);
7181 -- When generating C code, convert nonbinary modular divisions into code
7182 -- that relies on the front-end expansion of operator Mod.
7184 if Modify_Tree_For_C then
7185 Expand_Nonbinary_Modular_Op (N);
7186 end if;
7187 end Expand_N_Op_Divide;
7189 --------------------
7190 -- Expand_N_Op_Eq --
7191 --------------------
7193 procedure Expand_N_Op_Eq (N : Node_Id) is
7194 Loc : constant Source_Ptr := Sloc (N);
7195 Typ : constant Entity_Id := Etype (N);
7196 Lhs : constant Node_Id := Left_Opnd (N);
7197 Rhs : constant Node_Id := Right_Opnd (N);
7198 Bodies : constant List_Id := New_List;
7199 A_Typ : constant Entity_Id := Etype (Lhs);
7201 Typl : Entity_Id := A_Typ;
7202 Op_Name : Entity_Id;
7203 Prim : Elmt_Id;
7205 procedure Build_Equality_Call (Eq : Entity_Id);
7206 -- If a constructed equality exists for the type or for its parent,
7207 -- build and analyze call, adding conversions if the operation is
7208 -- inherited.
7210 function Has_Unconstrained_UU_Component (Typ : Node_Id) return Boolean;
7211 -- Determines whether a type has a subcomponent of an unconstrained
7212 -- Unchecked_Union subtype. Typ is a record type.
7214 -------------------------
7215 -- Build_Equality_Call --
7216 -------------------------
7218 procedure Build_Equality_Call (Eq : Entity_Id) is
7219 Op_Type : constant Entity_Id := Etype (First_Formal (Eq));
7220 L_Exp : Node_Id := Relocate_Node (Lhs);
7221 R_Exp : Node_Id := Relocate_Node (Rhs);
7223 begin
7224 -- Adjust operands if necessary to comparison type
7226 if Base_Type (Op_Type) /= Base_Type (A_Typ)
7227 and then not Is_Class_Wide_Type (A_Typ)
7228 then
7229 L_Exp := OK_Convert_To (Op_Type, L_Exp);
7230 R_Exp := OK_Convert_To (Op_Type, R_Exp);
7231 end if;
7233 -- If we have an Unchecked_Union, we need to add the inferred
7234 -- discriminant values as actuals in the function call. At this
7235 -- point, the expansion has determined that both operands have
7236 -- inferable discriminants.
7238 if Is_Unchecked_Union (Op_Type) then
7239 declare
7240 Lhs_Type : constant Node_Id := Etype (L_Exp);
7241 Rhs_Type : constant Node_Id := Etype (R_Exp);
7243 Lhs_Discr_Vals : Elist_Id;
7244 -- List of inferred discriminant values for left operand.
7246 Rhs_Discr_Vals : Elist_Id;
7247 -- List of inferred discriminant values for right operand.
7249 Discr : Entity_Id;
7251 begin
7252 Lhs_Discr_Vals := New_Elmt_List;
7253 Rhs_Discr_Vals := New_Elmt_List;
7255 -- Per-object constrained selected components require special
7256 -- attention. If the enclosing scope of the component is an
7257 -- Unchecked_Union, we cannot reference its discriminants
7258 -- directly. This is why we use the extra parameters of the
7259 -- equality function of the enclosing Unchecked_Union.
7261 -- type UU_Type (Discr : Integer := 0) is
7262 -- . . .
7263 -- end record;
7264 -- pragma Unchecked_Union (UU_Type);
7266 -- 1. Unchecked_Union enclosing record:
7268 -- type Enclosing_UU_Type (Discr : Integer := 0) is record
7269 -- . . .
7270 -- Comp : UU_Type (Discr);
7271 -- . . .
7272 -- end Enclosing_UU_Type;
7273 -- pragma Unchecked_Union (Enclosing_UU_Type);
7275 -- Obj1 : Enclosing_UU_Type;
7276 -- Obj2 : Enclosing_UU_Type (1);
7278 -- [. . .] Obj1 = Obj2 [. . .]
7280 -- Generated code:
7282 -- if not (uu_typeEQ (obj1.comp, obj2.comp, a, b)) then
7284 -- A and B are the formal parameters of the equality function
7285 -- of Enclosing_UU_Type. The function always has two extra
7286 -- formals to capture the inferred discriminant values for
7287 -- each discriminant of the type.
7289 -- 2. Non-Unchecked_Union enclosing record:
7291 -- type
7292 -- Enclosing_Non_UU_Type (Discr : Integer := 0)
7293 -- is record
7294 -- . . .
7295 -- Comp : UU_Type (Discr);
7296 -- . . .
7297 -- end Enclosing_Non_UU_Type;
7299 -- Obj1 : Enclosing_Non_UU_Type;
7300 -- Obj2 : Enclosing_Non_UU_Type (1);
7302 -- ... Obj1 = Obj2 ...
7304 -- Generated code:
7306 -- if not (uu_typeEQ (obj1.comp, obj2.comp,
7307 -- obj1.discr, obj2.discr)) then
7309 -- In this case we can directly reference the discriminants of
7310 -- the enclosing record.
7312 -- Process left operand of equality
7314 if Nkind (Lhs) = N_Selected_Component
7315 and then
7316 Has_Per_Object_Constraint (Entity (Selector_Name (Lhs)))
7317 then
7318 -- If enclosing record is an Unchecked_Union, use formals
7319 -- corresponding to each discriminant. The name of the
7320 -- formal is that of the discriminant, with added suffix,
7321 -- see Exp_Ch3.Build_Record_Equality for details.
7323 if Is_Unchecked_Union (Scope (Entity (Selector_Name (Lhs))))
7324 then
7325 Discr :=
7326 First_Discriminant
7327 (Scope (Entity (Selector_Name (Lhs))));
7328 while Present (Discr) loop
7329 Append_Elmt
7330 (Make_Identifier (Loc,
7331 Chars => New_External_Name (Chars (Discr), 'A')),
7332 To => Lhs_Discr_Vals);
7333 Next_Discriminant (Discr);
7334 end loop;
7336 -- If enclosing record is of a non-Unchecked_Union type, it
7337 -- is possible to reference its discriminants directly.
7339 else
7340 Discr := First_Discriminant (Lhs_Type);
7341 while Present (Discr) loop
7342 Append_Elmt
7343 (Make_Selected_Component (Loc,
7344 Prefix => Prefix (Lhs),
7345 Selector_Name =>
7346 New_Copy
7347 (Get_Discriminant_Value (Discr,
7348 Lhs_Type,
7349 Stored_Constraint (Lhs_Type)))),
7350 To => Lhs_Discr_Vals);
7351 Next_Discriminant (Discr);
7352 end loop;
7353 end if;
7355 -- Otherwise operand is on object with a constrained type.
7356 -- Infer the discriminant values from the constraint.
7358 else
7360 Discr := First_Discriminant (Lhs_Type);
7361 while Present (Discr) loop
7362 Append_Elmt
7363 (New_Copy
7364 (Get_Discriminant_Value (Discr,
7365 Lhs_Type,
7366 Stored_Constraint (Lhs_Type))),
7367 To => Lhs_Discr_Vals);
7368 Next_Discriminant (Discr);
7369 end loop;
7370 end if;
7372 -- Similar processing for right operand of equality
7374 if Nkind (Rhs) = N_Selected_Component
7375 and then
7376 Has_Per_Object_Constraint (Entity (Selector_Name (Rhs)))
7377 then
7378 if Is_Unchecked_Union
7379 (Scope (Entity (Selector_Name (Rhs))))
7380 then
7381 Discr :=
7382 First_Discriminant
7383 (Scope (Entity (Selector_Name (Rhs))));
7384 while Present (Discr) loop
7385 Append_Elmt
7386 (Make_Identifier (Loc,
7387 Chars => New_External_Name (Chars (Discr), 'B')),
7388 To => Rhs_Discr_Vals);
7389 Next_Discriminant (Discr);
7390 end loop;
7392 else
7393 Discr := First_Discriminant (Rhs_Type);
7394 while Present (Discr) loop
7395 Append_Elmt
7396 (Make_Selected_Component (Loc,
7397 Prefix => Prefix (Rhs),
7398 Selector_Name =>
7399 New_Copy (Get_Discriminant_Value
7400 (Discr,
7401 Rhs_Type,
7402 Stored_Constraint (Rhs_Type)))),
7403 To => Rhs_Discr_Vals);
7404 Next_Discriminant (Discr);
7405 end loop;
7406 end if;
7408 else
7409 Discr := First_Discriminant (Rhs_Type);
7410 while Present (Discr) loop
7411 Append_Elmt
7412 (New_Copy (Get_Discriminant_Value
7413 (Discr,
7414 Rhs_Type,
7415 Stored_Constraint (Rhs_Type))),
7416 To => Rhs_Discr_Vals);
7417 Next_Discriminant (Discr);
7418 end loop;
7419 end if;
7421 -- Now merge the list of discriminant values so that values
7422 -- of corresponding discriminants are adjacent.
7424 declare
7425 Params : List_Id;
7426 L_Elmt : Elmt_Id;
7427 R_Elmt : Elmt_Id;
7429 begin
7430 Params := New_List (L_Exp, R_Exp);
7431 L_Elmt := First_Elmt (Lhs_Discr_Vals);
7432 R_Elmt := First_Elmt (Rhs_Discr_Vals);
7433 while Present (L_Elmt) loop
7434 Append_To (Params, Node (L_Elmt));
7435 Append_To (Params, Node (R_Elmt));
7436 Next_Elmt (L_Elmt);
7437 Next_Elmt (R_Elmt);
7438 end loop;
7440 Rewrite (N,
7441 Make_Function_Call (Loc,
7442 Name => New_Occurrence_Of (Eq, Loc),
7443 Parameter_Associations => Params));
7444 end;
7445 end;
7447 -- Normal case, not an unchecked union
7449 else
7450 Rewrite (N,
7451 Make_Function_Call (Loc,
7452 Name => New_Occurrence_Of (Eq, Loc),
7453 Parameter_Associations => New_List (L_Exp, R_Exp)));
7454 end if;
7456 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7457 end Build_Equality_Call;
7459 ------------------------------------
7460 -- Has_Unconstrained_UU_Component --
7461 ------------------------------------
7463 function Has_Unconstrained_UU_Component
7464 (Typ : Node_Id) return Boolean
7466 Tdef : constant Node_Id :=
7467 Type_Definition (Declaration_Node (Base_Type (Typ)));
7468 Clist : Node_Id;
7469 Vpart : Node_Id;
7471 function Component_Is_Unconstrained_UU
7472 (Comp : Node_Id) return Boolean;
7473 -- Determines whether the subtype of the component is an
7474 -- unconstrained Unchecked_Union.
7476 function Variant_Is_Unconstrained_UU
7477 (Variant : Node_Id) return Boolean;
7478 -- Determines whether a component of the variant has an unconstrained
7479 -- Unchecked_Union subtype.
7481 -----------------------------------
7482 -- Component_Is_Unconstrained_UU --
7483 -----------------------------------
7485 function Component_Is_Unconstrained_UU
7486 (Comp : Node_Id) return Boolean
7488 begin
7489 if Nkind (Comp) /= N_Component_Declaration then
7490 return False;
7491 end if;
7493 declare
7494 Sindic : constant Node_Id :=
7495 Subtype_Indication (Component_Definition (Comp));
7497 begin
7498 -- Unconstrained nominal type. In the case of a constraint
7499 -- present, the node kind would have been N_Subtype_Indication.
7501 if Nkind (Sindic) = N_Identifier then
7502 return Is_Unchecked_Union (Base_Type (Etype (Sindic)));
7503 end if;
7505 return False;
7506 end;
7507 end Component_Is_Unconstrained_UU;
7509 ---------------------------------
7510 -- Variant_Is_Unconstrained_UU --
7511 ---------------------------------
7513 function Variant_Is_Unconstrained_UU
7514 (Variant : Node_Id) return Boolean
7516 Clist : constant Node_Id := Component_List (Variant);
7518 begin
7519 if Is_Empty_List (Component_Items (Clist)) then
7520 return False;
7521 end if;
7523 -- We only need to test one component
7525 declare
7526 Comp : Node_Id := First (Component_Items (Clist));
7528 begin
7529 while Present (Comp) loop
7530 if Component_Is_Unconstrained_UU (Comp) then
7531 return True;
7532 end if;
7534 Next (Comp);
7535 end loop;
7536 end;
7538 -- None of the components withing the variant were of
7539 -- unconstrained Unchecked_Union type.
7541 return False;
7542 end Variant_Is_Unconstrained_UU;
7544 -- Start of processing for Has_Unconstrained_UU_Component
7546 begin
7547 if Null_Present (Tdef) then
7548 return False;
7549 end if;
7551 Clist := Component_List (Tdef);
7552 Vpart := Variant_Part (Clist);
7554 -- Inspect available components
7556 if Present (Component_Items (Clist)) then
7557 declare
7558 Comp : Node_Id := First (Component_Items (Clist));
7560 begin
7561 while Present (Comp) loop
7563 -- One component is sufficient
7565 if Component_Is_Unconstrained_UU (Comp) then
7566 return True;
7567 end if;
7569 Next (Comp);
7570 end loop;
7571 end;
7572 end if;
7574 -- Inspect available components withing variants
7576 if Present (Vpart) then
7577 declare
7578 Variant : Node_Id := First (Variants (Vpart));
7580 begin
7581 while Present (Variant) loop
7583 -- One component within a variant is sufficient
7585 if Variant_Is_Unconstrained_UU (Variant) then
7586 return True;
7587 end if;
7589 Next (Variant);
7590 end loop;
7591 end;
7592 end if;
7594 -- Neither the available components, nor the components inside the
7595 -- variant parts were of an unconstrained Unchecked_Union subtype.
7597 return False;
7598 end Has_Unconstrained_UU_Component;
7600 -- Start of processing for Expand_N_Op_Eq
7602 begin
7603 Binary_Op_Validity_Checks (N);
7605 -- Deal with private types
7607 if Ekind (Typl) = E_Private_Type then
7608 Typl := Underlying_Type (Typl);
7609 elsif Ekind (Typl) = E_Private_Subtype then
7610 Typl := Underlying_Type (Base_Type (Typl));
7611 else
7612 null;
7613 end if;
7615 -- It may happen in error situations that the underlying type is not
7616 -- set. The error will be detected later, here we just defend the
7617 -- expander code.
7619 if No (Typl) then
7620 return;
7621 end if;
7623 -- Now get the implementation base type (note that plain Base_Type here
7624 -- might lead us back to the private type, which is not what we want!)
7626 Typl := Implementation_Base_Type (Typl);
7628 -- Equality between variant records results in a call to a routine
7629 -- that has conditional tests of the discriminant value(s), and hence
7630 -- violates the No_Implicit_Conditionals restriction.
7632 if Has_Variant_Part (Typl) then
7633 declare
7634 Msg : Boolean;
7636 begin
7637 Check_Restriction (Msg, No_Implicit_Conditionals, N);
7639 if Msg then
7640 Error_Msg_N
7641 ("\comparison of variant records tests discriminants", N);
7642 return;
7643 end if;
7644 end;
7645 end if;
7647 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7648 -- means we no longer have a comparison operation, we are all done.
7650 Expand_Compare_Minimize_Eliminate_Overflow (N);
7652 if Nkind (N) /= N_Op_Eq then
7653 return;
7654 end if;
7656 -- Boolean types (requiring handling of non-standard case)
7658 if Is_Boolean_Type (Typl) then
7659 Adjust_Condition (Left_Opnd (N));
7660 Adjust_Condition (Right_Opnd (N));
7661 Set_Etype (N, Standard_Boolean);
7662 Adjust_Result_Type (N, Typ);
7664 -- Array types
7666 elsif Is_Array_Type (Typl) then
7668 -- If we are doing full validity checking, and it is possible for the
7669 -- array elements to be invalid then expand out array comparisons to
7670 -- make sure that we check the array elements.
7672 if Validity_Check_Operands
7673 and then not Is_Known_Valid (Component_Type (Typl))
7674 then
7675 declare
7676 Save_Force_Validity_Checks : constant Boolean :=
7677 Force_Validity_Checks;
7678 begin
7679 Force_Validity_Checks := True;
7680 Rewrite (N,
7681 Expand_Array_Equality
7683 Relocate_Node (Lhs),
7684 Relocate_Node (Rhs),
7685 Bodies,
7686 Typl));
7687 Insert_Actions (N, Bodies);
7688 Analyze_And_Resolve (N, Standard_Boolean);
7689 Force_Validity_Checks := Save_Force_Validity_Checks;
7690 end;
7692 -- Packed case where both operands are known aligned
7694 elsif Is_Bit_Packed_Array (Typl)
7695 and then not Is_Possibly_Unaligned_Object (Lhs)
7696 and then not Is_Possibly_Unaligned_Object (Rhs)
7697 then
7698 Expand_Packed_Eq (N);
7700 -- Where the component type is elementary we can use a block bit
7701 -- comparison (if supported on the target) exception in the case
7702 -- of floating-point (negative zero issues require element by
7703 -- element comparison), and atomic/VFA types (where we must be sure
7704 -- to load elements independently) and possibly unaligned arrays.
7706 elsif Is_Elementary_Type (Component_Type (Typl))
7707 and then not Is_Floating_Point_Type (Component_Type (Typl))
7708 and then not Is_Atomic_Or_VFA (Component_Type (Typl))
7709 and then not Is_Possibly_Unaligned_Object (Lhs)
7710 and then not Is_Possibly_Unaligned_Object (Rhs)
7711 and then Support_Composite_Compare_On_Target
7712 then
7713 null;
7715 -- For composite and floating-point cases, expand equality loop to
7716 -- make sure of using proper comparisons for tagged types, and
7717 -- correctly handling the floating-point case.
7719 else
7720 Rewrite (N,
7721 Expand_Array_Equality
7723 Relocate_Node (Lhs),
7724 Relocate_Node (Rhs),
7725 Bodies,
7726 Typl));
7727 Insert_Actions (N, Bodies, Suppress => All_Checks);
7728 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7729 end if;
7731 -- Record Types
7733 elsif Is_Record_Type (Typl) then
7735 -- For tagged types, use the primitive "="
7737 if Is_Tagged_Type (Typl) then
7739 -- No need to do anything else compiling under restriction
7740 -- No_Dispatching_Calls. During the semantic analysis we
7741 -- already notified such violation.
7743 if Restriction_Active (No_Dispatching_Calls) then
7744 return;
7745 end if;
7747 -- If this is derived from an untagged private type completed with
7748 -- a tagged type, it does not have a full view, so we use the
7749 -- primitive operations of the private type. This check should no
7750 -- longer be necessary when these types get their full views???
7752 if Is_Private_Type (A_Typ)
7753 and then not Is_Tagged_Type (A_Typ)
7754 and then Is_Derived_Type (A_Typ)
7755 and then No (Full_View (A_Typ))
7756 then
7757 -- Search for equality operation, checking that the operands
7758 -- have the same type. Note that we must find a matching entry,
7759 -- or something is very wrong.
7761 Prim := First_Elmt (Collect_Primitive_Operations (A_Typ));
7763 while Present (Prim) loop
7764 exit when Chars (Node (Prim)) = Name_Op_Eq
7765 and then Etype (First_Formal (Node (Prim))) =
7766 Etype (Next_Formal (First_Formal (Node (Prim))))
7767 and then
7768 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7770 Next_Elmt (Prim);
7771 end loop;
7773 pragma Assert (Present (Prim));
7774 Op_Name := Node (Prim);
7776 -- Find the type's predefined equality or an overriding
7777 -- user-defined equality. The reason for not simply calling
7778 -- Find_Prim_Op here is that there may be a user-defined
7779 -- overloaded equality op that precedes the equality that we
7780 -- want, so we have to explicitly search (e.g., there could be
7781 -- an equality with two different parameter types).
7783 else
7784 if Is_Class_Wide_Type (Typl) then
7785 Typl := Find_Specific_Type (Typl);
7786 end if;
7788 Prim := First_Elmt (Primitive_Operations (Typl));
7789 while Present (Prim) loop
7790 exit when Chars (Node (Prim)) = Name_Op_Eq
7791 and then Etype (First_Formal (Node (Prim))) =
7792 Etype (Next_Formal (First_Formal (Node (Prim))))
7793 and then
7794 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7796 Next_Elmt (Prim);
7797 end loop;
7799 pragma Assert (Present (Prim));
7800 Op_Name := Node (Prim);
7801 end if;
7803 Build_Equality_Call (Op_Name);
7805 -- Ada 2005 (AI-216): Program_Error is raised when evaluating the
7806 -- predefined equality operator for a type which has a subcomponent
7807 -- of an Unchecked_Union type whose nominal subtype is unconstrained.
7809 elsif Has_Unconstrained_UU_Component (Typl) then
7810 Insert_Action (N,
7811 Make_Raise_Program_Error (Loc,
7812 Reason => PE_Unchecked_Union_Restriction));
7814 -- Prevent Gigi from generating incorrect code by rewriting the
7815 -- equality as a standard False. (is this documented somewhere???)
7817 Rewrite (N,
7818 New_Occurrence_Of (Standard_False, Loc));
7820 elsif Is_Unchecked_Union (Typl) then
7822 -- If we can infer the discriminants of the operands, we make a
7823 -- call to the TSS equality function.
7825 if Has_Inferable_Discriminants (Lhs)
7826 and then
7827 Has_Inferable_Discriminants (Rhs)
7828 then
7829 Build_Equality_Call
7830 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7832 else
7833 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
7834 -- the predefined equality operator for an Unchecked_Union type
7835 -- if either of the operands lack inferable discriminants.
7837 Insert_Action (N,
7838 Make_Raise_Program_Error (Loc,
7839 Reason => PE_Unchecked_Union_Restriction));
7841 -- Emit a warning on source equalities only, otherwise the
7842 -- message may appear out of place due to internal use. The
7843 -- warning is unconditional because it is required by the
7844 -- language.
7846 if Comes_From_Source (N) then
7847 Error_Msg_N
7848 ("Unchecked_Union discriminants cannot be determined??",
7850 Error_Msg_N
7851 ("\Program_Error will be raised for equality operation??",
7853 end if;
7855 -- Prevent Gigi from generating incorrect code by rewriting
7856 -- the equality as a standard False (documented where???).
7858 Rewrite (N,
7859 New_Occurrence_Of (Standard_False, Loc));
7860 end if;
7862 -- If a type support function is present (for complex cases), use it
7864 elsif Present (TSS (Root_Type (Typl), TSS_Composite_Equality)) then
7865 Build_Equality_Call
7866 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7868 -- When comparing two Bounded_Strings, use the primitive equality of
7869 -- the root Super_String type.
7871 elsif Is_Bounded_String (Typl) then
7872 Prim :=
7873 First_Elmt (Collect_Primitive_Operations (Root_Type (Typl)));
7875 while Present (Prim) loop
7876 exit when Chars (Node (Prim)) = Name_Op_Eq
7877 and then Etype (First_Formal (Node (Prim))) =
7878 Etype (Next_Formal (First_Formal (Node (Prim))))
7879 and then Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7881 Next_Elmt (Prim);
7882 end loop;
7884 -- A Super_String type should always have a primitive equality
7886 pragma Assert (Present (Prim));
7887 Build_Equality_Call (Node (Prim));
7889 -- Otherwise expand the component by component equality. Note that
7890 -- we never use block-bit comparisons for records, because of the
7891 -- problems with gaps. The back end will often be able to recombine
7892 -- the separate comparisons that we generate here.
7894 else
7895 Remove_Side_Effects (Lhs);
7896 Remove_Side_Effects (Rhs);
7897 Rewrite (N,
7898 Expand_Record_Equality (N, Typl, Lhs, Rhs, Bodies));
7900 Insert_Actions (N, Bodies, Suppress => All_Checks);
7901 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7902 end if;
7903 end if;
7905 -- Test if result is known at compile time
7907 Rewrite_Comparison (N);
7909 -- Special optimization of length comparison
7911 Optimize_Length_Comparison (N);
7913 -- One more special case: if we have a comparison of X'Result = expr
7914 -- in floating-point, then if not already there, change expr to be
7915 -- f'Machine (expr) to eliminate surprise from extra precision.
7917 if Is_Floating_Point_Type (Typl)
7918 and then Nkind (Original_Node (Lhs)) = N_Attribute_Reference
7919 and then Attribute_Name (Original_Node (Lhs)) = Name_Result
7920 then
7921 -- Stick in the Typ'Machine call if not already there
7923 if Nkind (Rhs) /= N_Attribute_Reference
7924 or else Attribute_Name (Rhs) /= Name_Machine
7925 then
7926 Rewrite (Rhs,
7927 Make_Attribute_Reference (Loc,
7928 Prefix => New_Occurrence_Of (Typl, Loc),
7929 Attribute_Name => Name_Machine,
7930 Expressions => New_List (Relocate_Node (Rhs))));
7931 Analyze_And_Resolve (Rhs, Typl);
7932 end if;
7933 end if;
7934 end Expand_N_Op_Eq;
7936 -----------------------
7937 -- Expand_N_Op_Expon --
7938 -----------------------
7940 procedure Expand_N_Op_Expon (N : Node_Id) is
7941 Loc : constant Source_Ptr := Sloc (N);
7942 Ovflo : constant Boolean := Do_Overflow_Check (N);
7943 Typ : constant Entity_Id := Etype (N);
7944 Rtyp : constant Entity_Id := Root_Type (Typ);
7946 Bastyp : Entity_Id;
7948 function Wrap_MA (Exp : Node_Id) return Node_Id;
7949 -- Given an expression Exp, if the root type is Float or Long_Float,
7950 -- then wrap the expression in a call of Bastyp'Machine, to stop any
7951 -- extra precision. This is done to ensure that X**A = X**B when A is
7952 -- a static constant and B is a variable with the same value. For any
7953 -- other type, the node Exp is returned unchanged.
7955 -------------
7956 -- Wrap_MA --
7957 -------------
7959 function Wrap_MA (Exp : Node_Id) return Node_Id is
7960 Loc : constant Source_Ptr := Sloc (Exp);
7962 begin
7963 if Rtyp = Standard_Float or else Rtyp = Standard_Long_Float then
7964 return
7965 Make_Attribute_Reference (Loc,
7966 Attribute_Name => Name_Machine,
7967 Prefix => New_Occurrence_Of (Bastyp, Loc),
7968 Expressions => New_List (Relocate_Node (Exp)));
7969 else
7970 return Exp;
7971 end if;
7972 end Wrap_MA;
7974 -- Local variables
7976 Base : Node_Id;
7977 Ent : Entity_Id;
7978 Etyp : Entity_Id;
7979 Exp : Node_Id;
7980 Exptyp : Entity_Id;
7981 Expv : Uint;
7982 Rent : RE_Id;
7983 Temp : Node_Id;
7984 Xnode : Node_Id;
7986 -- Start of processing for Expand_N_Op_Expon
7988 begin
7989 Binary_Op_Validity_Checks (N);
7991 -- CodePeer wants to see the unexpanded N_Op_Expon node
7993 if CodePeer_Mode then
7994 return;
7995 end if;
7997 -- Relocation of left and right operands must be done after performing
7998 -- the validity checks since the generation of validation checks may
7999 -- remove side effects.
8001 Base := Relocate_Node (Left_Opnd (N));
8002 Bastyp := Etype (Base);
8003 Exp := Relocate_Node (Right_Opnd (N));
8004 Exptyp := Etype (Exp);
8006 -- If either operand is of a private type, then we have the use of an
8007 -- intrinsic operator, and we get rid of the privateness, by using root
8008 -- types of underlying types for the actual operation. Otherwise the
8009 -- private types will cause trouble if we expand multiplications or
8010 -- shifts etc. We also do this transformation if the result type is
8011 -- different from the base type.
8013 if Is_Private_Type (Etype (Base))
8014 or else Is_Private_Type (Typ)
8015 or else Is_Private_Type (Exptyp)
8016 or else Rtyp /= Root_Type (Bastyp)
8017 then
8018 declare
8019 Bt : constant Entity_Id := Root_Type (Underlying_Type (Bastyp));
8020 Et : constant Entity_Id := Root_Type (Underlying_Type (Exptyp));
8021 begin
8022 Rewrite (N,
8023 Unchecked_Convert_To (Typ,
8024 Make_Op_Expon (Loc,
8025 Left_Opnd => Unchecked_Convert_To (Bt, Base),
8026 Right_Opnd => Unchecked_Convert_To (Et, Exp))));
8027 Analyze_And_Resolve (N, Typ);
8028 return;
8029 end;
8030 end if;
8032 -- Check for MINIMIZED/ELIMINATED overflow mode
8034 if Minimized_Eliminated_Overflow_Check (N) then
8035 Apply_Arithmetic_Overflow_Check (N);
8036 return;
8037 end if;
8039 -- Test for case of known right argument where we can replace the
8040 -- exponentiation by an equivalent expression using multiplication.
8042 -- Note: use CRT_Safe version of Compile_Time_Known_Value because in
8043 -- configurable run-time mode, we may not have the exponentiation
8044 -- routine available, and we don't want the legality of the program
8045 -- to depend on how clever the compiler is in knowing values.
8047 if CRT_Safe_Compile_Time_Known_Value (Exp) then
8048 Expv := Expr_Value (Exp);
8050 -- We only fold small non-negative exponents. You might think we
8051 -- could fold small negative exponents for the real case, but we
8052 -- can't because we are required to raise Constraint_Error for
8053 -- the case of 0.0 ** (negative) even if Machine_Overflows = False.
8054 -- See ACVC test C4A012B, and it is not worth generating the test.
8056 -- For small negative exponents, we return the reciprocal of
8057 -- the folding of the exponentiation for the opposite (positive)
8058 -- exponent, as required by Ada RM 4.5.6(11/3).
8060 if abs Expv <= 4 then
8062 -- X ** 0 = 1 (or 1.0)
8064 if Expv = 0 then
8066 -- Call Remove_Side_Effects to ensure that any side effects
8067 -- in the ignored left operand (in particular function calls
8068 -- to user defined functions) are properly executed.
8070 Remove_Side_Effects (Base);
8072 if Ekind (Typ) in Integer_Kind then
8073 Xnode := Make_Integer_Literal (Loc, Intval => 1);
8074 else
8075 Xnode := Make_Real_Literal (Loc, Ureal_1);
8076 end if;
8078 -- X ** 1 = X
8080 elsif Expv = 1 then
8081 Xnode := Base;
8083 -- X ** 2 = X * X
8085 elsif Expv = 2 then
8086 Xnode :=
8087 Wrap_MA (
8088 Make_Op_Multiply (Loc,
8089 Left_Opnd => Duplicate_Subexpr (Base),
8090 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8092 -- X ** 3 = X * X * X
8094 elsif Expv = 3 then
8095 Xnode :=
8096 Wrap_MA (
8097 Make_Op_Multiply (Loc,
8098 Left_Opnd =>
8099 Make_Op_Multiply (Loc,
8100 Left_Opnd => Duplicate_Subexpr (Base),
8101 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)),
8102 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8104 -- X ** 4 ->
8106 -- do
8107 -- En : constant base'type := base * base;
8108 -- in
8109 -- En * En
8111 elsif Expv = 4 then
8112 Temp := Make_Temporary (Loc, 'E', Base);
8114 Xnode :=
8115 Make_Expression_With_Actions (Loc,
8116 Actions => New_List (
8117 Make_Object_Declaration (Loc,
8118 Defining_Identifier => Temp,
8119 Constant_Present => True,
8120 Object_Definition => New_Occurrence_Of (Typ, Loc),
8121 Expression =>
8122 Wrap_MA (
8123 Make_Op_Multiply (Loc,
8124 Left_Opnd =>
8125 Duplicate_Subexpr (Base),
8126 Right_Opnd =>
8127 Duplicate_Subexpr_No_Checks (Base))))),
8129 Expression =>
8130 Wrap_MA (
8131 Make_Op_Multiply (Loc,
8132 Left_Opnd => New_Occurrence_Of (Temp, Loc),
8133 Right_Opnd => New_Occurrence_Of (Temp, Loc))));
8135 -- X ** N = 1.0 / X ** (-N)
8136 -- N in -4 .. -1
8138 else
8139 pragma Assert
8140 (Expv = -1 or Expv = -2 or Expv = -3 or Expv = -4);
8142 Xnode :=
8143 Make_Op_Divide (Loc,
8144 Left_Opnd =>
8145 Make_Float_Literal (Loc,
8146 Radix => Uint_1,
8147 Significand => Uint_1,
8148 Exponent => Uint_0),
8149 Right_Opnd =>
8150 Make_Op_Expon (Loc,
8151 Left_Opnd => Duplicate_Subexpr (Base),
8152 Right_Opnd =>
8153 Make_Integer_Literal (Loc,
8154 Intval => -Expv)));
8155 end if;
8157 Rewrite (N, Xnode);
8158 Analyze_And_Resolve (N, Typ);
8159 return;
8160 end if;
8161 end if;
8163 -- Deal with optimizing 2 ** expression to shift where possible
8165 -- Note: we used to check that Exptyp was an unsigned type. But that is
8166 -- an unnecessary check, since if Exp is negative, we have a run-time
8167 -- error that is either caught (so we get the right result) or we have
8168 -- suppressed the check, in which case the code is erroneous anyway.
8170 if Is_Integer_Type (Rtyp)
8172 -- The base value must be "safe compile-time known", and exactly 2
8174 and then Nkind (Base) = N_Integer_Literal
8175 and then CRT_Safe_Compile_Time_Known_Value (Base)
8176 and then Expr_Value (Base) = Uint_2
8178 -- We only handle cases where the right type is a integer
8180 and then Is_Integer_Type (Root_Type (Exptyp))
8181 and then Esize (Root_Type (Exptyp)) <= Esize (Standard_Integer)
8183 -- This transformation is not applicable for a modular type with a
8184 -- nonbinary modulus because we do not handle modular reduction in
8185 -- a correct manner if we attempt this transformation in this case.
8187 and then not Non_Binary_Modulus (Typ)
8188 then
8189 -- Handle the cases where our parent is a division or multiplication
8190 -- specially. In these cases we can convert to using a shift at the
8191 -- parent level if we are not doing overflow checking, since it is
8192 -- too tricky to combine the overflow check at the parent level.
8194 if not Ovflo
8195 and then Nkind_In (Parent (N), N_Op_Divide, N_Op_Multiply)
8196 then
8197 declare
8198 P : constant Node_Id := Parent (N);
8199 L : constant Node_Id := Left_Opnd (P);
8200 R : constant Node_Id := Right_Opnd (P);
8202 begin
8203 if (Nkind (P) = N_Op_Multiply
8204 and then
8205 ((Is_Integer_Type (Etype (L)) and then R = N)
8206 or else
8207 (Is_Integer_Type (Etype (R)) and then L = N))
8208 and then not Do_Overflow_Check (P))
8210 or else
8211 (Nkind (P) = N_Op_Divide
8212 and then Is_Integer_Type (Etype (L))
8213 and then Is_Unsigned_Type (Etype (L))
8214 and then R = N
8215 and then not Do_Overflow_Check (P))
8216 then
8217 Set_Is_Power_Of_2_For_Shift (N);
8218 return;
8219 end if;
8220 end;
8222 -- Here we just have 2 ** N on its own, so we can convert this to a
8223 -- shift node. We are prepared to deal with overflow here, and we
8224 -- also have to handle proper modular reduction for binary modular.
8226 else
8227 declare
8228 OK : Boolean;
8229 Lo : Uint;
8230 Hi : Uint;
8232 MaxS : Uint;
8233 -- Maximum shift count with no overflow
8235 TestS : Boolean;
8236 -- Set True if we must test the shift count
8238 Test_Gt : Node_Id;
8239 -- Node for test against TestS
8241 begin
8242 -- Compute maximum shift based on the underlying size. For a
8243 -- modular type this is one less than the size.
8245 if Is_Modular_Integer_Type (Typ) then
8247 -- For modular integer types, this is the size of the value
8248 -- being shifted minus one. Any larger values will cause
8249 -- modular reduction to a result of zero. Note that we do
8250 -- want the RM_Size here (e.g. mod 2 ** 7, we want a result
8251 -- of 6, since 2**7 should be reduced to zero).
8253 MaxS := RM_Size (Rtyp) - 1;
8255 -- For signed integer types, we use the size of the value
8256 -- being shifted minus 2. Larger values cause overflow.
8258 else
8259 MaxS := Esize (Rtyp) - 2;
8260 end if;
8262 -- Determine range to see if it can be larger than MaxS
8264 Determine_Range
8265 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
8266 TestS := (not OK) or else Hi > MaxS;
8268 -- Signed integer case
8270 if Is_Signed_Integer_Type (Typ) then
8272 -- Generate overflow check if overflow is active. Note that
8273 -- we can simply ignore the possibility of overflow if the
8274 -- flag is not set (means that overflow cannot happen or
8275 -- that overflow checks are suppressed).
8277 if Ovflo and TestS then
8278 Insert_Action (N,
8279 Make_Raise_Constraint_Error (Loc,
8280 Condition =>
8281 Make_Op_Gt (Loc,
8282 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8283 Right_Opnd => Make_Integer_Literal (Loc, MaxS)),
8284 Reason => CE_Overflow_Check_Failed));
8285 end if;
8287 -- Now rewrite node as Shift_Left (1, right-operand)
8289 Rewrite (N,
8290 Make_Op_Shift_Left (Loc,
8291 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8292 Right_Opnd => Right_Opnd (N)));
8294 -- Modular integer case
8296 else pragma Assert (Is_Modular_Integer_Type (Typ));
8298 -- If shift count can be greater than MaxS, we need to wrap
8299 -- the shift in a test that will reduce the result value to
8300 -- zero if this shift count is exceeded.
8302 if TestS then
8304 -- Note: build node for the comparison first, before we
8305 -- reuse the Right_Opnd, so that we have proper parents
8306 -- in place for the Duplicate_Subexpr call.
8308 Test_Gt :=
8309 Make_Op_Gt (Loc,
8310 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8311 Right_Opnd => Make_Integer_Literal (Loc, MaxS));
8313 Rewrite (N,
8314 Make_If_Expression (Loc,
8315 Expressions => New_List (
8316 Test_Gt,
8317 Make_Integer_Literal (Loc, Uint_0),
8318 Make_Op_Shift_Left (Loc,
8319 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8320 Right_Opnd => Right_Opnd (N)))));
8322 -- If we know shift count cannot be greater than MaxS, then
8323 -- it is safe to just rewrite as a shift with no test.
8325 else
8326 Rewrite (N,
8327 Make_Op_Shift_Left (Loc,
8328 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8329 Right_Opnd => Right_Opnd (N)));
8330 end if;
8331 end if;
8333 Analyze_And_Resolve (N, Typ);
8334 return;
8335 end;
8336 end if;
8337 end if;
8339 -- Fall through if exponentiation must be done using a runtime routine
8341 -- First deal with modular case
8343 if Is_Modular_Integer_Type (Rtyp) then
8345 -- Nonbinary modular case, we call the special exponentiation
8346 -- routine for the nonbinary case, converting the argument to
8347 -- Long_Long_Integer and passing the modulus value. Then the
8348 -- result is converted back to the base type.
8350 if Non_Binary_Modulus (Rtyp) then
8351 Rewrite (N,
8352 Convert_To (Typ,
8353 Make_Function_Call (Loc,
8354 Name =>
8355 New_Occurrence_Of (RTE (RE_Exp_Modular), Loc),
8356 Parameter_Associations => New_List (
8357 Convert_To (RTE (RE_Unsigned), Base),
8358 Make_Integer_Literal (Loc, Modulus (Rtyp)),
8359 Exp))));
8361 -- Binary modular case, in this case, we call one of two routines,
8362 -- either the unsigned integer case, or the unsigned long long
8363 -- integer case, with a final "and" operation to do the required mod.
8365 else
8366 if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
8367 Ent := RTE (RE_Exp_Unsigned);
8368 else
8369 Ent := RTE (RE_Exp_Long_Long_Unsigned);
8370 end if;
8372 Rewrite (N,
8373 Convert_To (Typ,
8374 Make_Op_And (Loc,
8375 Left_Opnd =>
8376 Make_Function_Call (Loc,
8377 Name => New_Occurrence_Of (Ent, Loc),
8378 Parameter_Associations => New_List (
8379 Convert_To (Etype (First_Formal (Ent)), Base),
8380 Exp)),
8381 Right_Opnd =>
8382 Make_Integer_Literal (Loc, Modulus (Rtyp) - 1))));
8384 end if;
8386 -- Common exit point for modular type case
8388 Analyze_And_Resolve (N, Typ);
8389 return;
8391 -- Signed integer cases, done using either Integer or Long_Long_Integer.
8392 -- It is not worth having routines for Short_[Short_]Integer, since for
8393 -- most machines it would not help, and it would generate more code that
8394 -- might need certification when a certified run time is required.
8396 -- In the integer cases, we have two routines, one for when overflow
8397 -- checks are required, and one when they are not required, since there
8398 -- is a real gain in omitting checks on many machines.
8400 elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
8401 or else (Rtyp = Base_Type (Standard_Long_Integer)
8402 and then
8403 Esize (Standard_Long_Integer) > Esize (Standard_Integer))
8404 or else Rtyp = Universal_Integer
8405 then
8406 Etyp := Standard_Long_Long_Integer;
8408 if Ovflo then
8409 Rent := RE_Exp_Long_Long_Integer;
8410 else
8411 Rent := RE_Exn_Long_Long_Integer;
8412 end if;
8414 elsif Is_Signed_Integer_Type (Rtyp) then
8415 Etyp := Standard_Integer;
8417 if Ovflo then
8418 Rent := RE_Exp_Integer;
8419 else
8420 Rent := RE_Exn_Integer;
8421 end if;
8423 -- Floating-point cases. We do not need separate routines for the
8424 -- overflow case here, since in the case of floating-point, we generate
8425 -- infinities anyway as a rule (either that or we automatically trap
8426 -- overflow), and if there is an infinity generated and a range check
8427 -- is required, the check will fail anyway.
8429 -- Historical note: we used to convert everything to Long_Long_Float
8430 -- and call a single common routine, but this had the undesirable effect
8431 -- of giving different results for small static exponent values and the
8432 -- same dynamic values.
8434 else
8435 pragma Assert (Is_Floating_Point_Type (Rtyp));
8437 if Rtyp = Standard_Float then
8438 Etyp := Standard_Float;
8439 Rent := RE_Exn_Float;
8441 elsif Rtyp = Standard_Long_Float then
8442 Etyp := Standard_Long_Float;
8443 Rent := RE_Exn_Long_Float;
8445 else
8446 Etyp := Standard_Long_Long_Float;
8447 Rent := RE_Exn_Long_Long_Float;
8448 end if;
8449 end if;
8451 -- Common processing for integer cases and floating-point cases.
8452 -- If we are in the right type, we can call runtime routine directly
8454 if Typ = Etyp
8455 and then Rtyp /= Universal_Integer
8456 and then Rtyp /= Universal_Real
8457 then
8458 Rewrite (N,
8459 Wrap_MA (
8460 Make_Function_Call (Loc,
8461 Name => New_Occurrence_Of (RTE (Rent), Loc),
8462 Parameter_Associations => New_List (Base, Exp))));
8464 -- Otherwise we have to introduce conversions (conversions are also
8465 -- required in the universal cases, since the runtime routine is
8466 -- typed using one of the standard types).
8468 else
8469 Rewrite (N,
8470 Convert_To (Typ,
8471 Make_Function_Call (Loc,
8472 Name => New_Occurrence_Of (RTE (Rent), Loc),
8473 Parameter_Associations => New_List (
8474 Convert_To (Etyp, Base),
8475 Exp))));
8476 end if;
8478 Analyze_And_Resolve (N, Typ);
8479 return;
8481 exception
8482 when RE_Not_Available =>
8483 return;
8484 end Expand_N_Op_Expon;
8486 --------------------
8487 -- Expand_N_Op_Ge --
8488 --------------------
8490 procedure Expand_N_Op_Ge (N : Node_Id) is
8491 Typ : constant Entity_Id := Etype (N);
8492 Op1 : constant Node_Id := Left_Opnd (N);
8493 Op2 : constant Node_Id := Right_Opnd (N);
8494 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8496 begin
8497 Binary_Op_Validity_Checks (N);
8499 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8500 -- means we no longer have a comparison operation, we are all done.
8502 Expand_Compare_Minimize_Eliminate_Overflow (N);
8504 if Nkind (N) /= N_Op_Ge then
8505 return;
8506 end if;
8508 -- Array type case
8510 if Is_Array_Type (Typ1) then
8511 Expand_Array_Comparison (N);
8512 return;
8513 end if;
8515 -- Deal with boolean operands
8517 if Is_Boolean_Type (Typ1) then
8518 Adjust_Condition (Op1);
8519 Adjust_Condition (Op2);
8520 Set_Etype (N, Standard_Boolean);
8521 Adjust_Result_Type (N, Typ);
8522 end if;
8524 Rewrite_Comparison (N);
8526 Optimize_Length_Comparison (N);
8527 end Expand_N_Op_Ge;
8529 --------------------
8530 -- Expand_N_Op_Gt --
8531 --------------------
8533 procedure Expand_N_Op_Gt (N : Node_Id) is
8534 Typ : constant Entity_Id := Etype (N);
8535 Op1 : constant Node_Id := Left_Opnd (N);
8536 Op2 : constant Node_Id := Right_Opnd (N);
8537 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8539 begin
8540 Binary_Op_Validity_Checks (N);
8542 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8543 -- means we no longer have a comparison operation, we are all done.
8545 Expand_Compare_Minimize_Eliminate_Overflow (N);
8547 if Nkind (N) /= N_Op_Gt then
8548 return;
8549 end if;
8551 -- Deal with array type operands
8553 if Is_Array_Type (Typ1) then
8554 Expand_Array_Comparison (N);
8555 return;
8556 end if;
8558 -- Deal with boolean type operands
8560 if Is_Boolean_Type (Typ1) then
8561 Adjust_Condition (Op1);
8562 Adjust_Condition (Op2);
8563 Set_Etype (N, Standard_Boolean);
8564 Adjust_Result_Type (N, Typ);
8565 end if;
8567 Rewrite_Comparison (N);
8569 Optimize_Length_Comparison (N);
8570 end Expand_N_Op_Gt;
8572 --------------------
8573 -- Expand_N_Op_Le --
8574 --------------------
8576 procedure Expand_N_Op_Le (N : Node_Id) is
8577 Typ : constant Entity_Id := Etype (N);
8578 Op1 : constant Node_Id := Left_Opnd (N);
8579 Op2 : constant Node_Id := Right_Opnd (N);
8580 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8582 begin
8583 Binary_Op_Validity_Checks (N);
8585 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8586 -- means we no longer have a comparison operation, we are all done.
8588 Expand_Compare_Minimize_Eliminate_Overflow (N);
8590 if Nkind (N) /= N_Op_Le then
8591 return;
8592 end if;
8594 -- Deal with array type operands
8596 if Is_Array_Type (Typ1) then
8597 Expand_Array_Comparison (N);
8598 return;
8599 end if;
8601 -- Deal with Boolean type operands
8603 if Is_Boolean_Type (Typ1) then
8604 Adjust_Condition (Op1);
8605 Adjust_Condition (Op2);
8606 Set_Etype (N, Standard_Boolean);
8607 Adjust_Result_Type (N, Typ);
8608 end if;
8610 Rewrite_Comparison (N);
8612 Optimize_Length_Comparison (N);
8613 end Expand_N_Op_Le;
8615 --------------------
8616 -- Expand_N_Op_Lt --
8617 --------------------
8619 procedure Expand_N_Op_Lt (N : Node_Id) is
8620 Typ : constant Entity_Id := Etype (N);
8621 Op1 : constant Node_Id := Left_Opnd (N);
8622 Op2 : constant Node_Id := Right_Opnd (N);
8623 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8625 begin
8626 Binary_Op_Validity_Checks (N);
8628 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8629 -- means we no longer have a comparison operation, we are all done.
8631 Expand_Compare_Minimize_Eliminate_Overflow (N);
8633 if Nkind (N) /= N_Op_Lt then
8634 return;
8635 end if;
8637 -- Deal with array type operands
8639 if Is_Array_Type (Typ1) then
8640 Expand_Array_Comparison (N);
8641 return;
8642 end if;
8644 -- Deal with Boolean type operands
8646 if Is_Boolean_Type (Typ1) then
8647 Adjust_Condition (Op1);
8648 Adjust_Condition (Op2);
8649 Set_Etype (N, Standard_Boolean);
8650 Adjust_Result_Type (N, Typ);
8651 end if;
8653 Rewrite_Comparison (N);
8655 Optimize_Length_Comparison (N);
8656 end Expand_N_Op_Lt;
8658 -----------------------
8659 -- Expand_N_Op_Minus --
8660 -----------------------
8662 procedure Expand_N_Op_Minus (N : Node_Id) is
8663 Loc : constant Source_Ptr := Sloc (N);
8664 Typ : constant Entity_Id := Etype (N);
8666 begin
8667 Unary_Op_Validity_Checks (N);
8669 -- Check for MINIMIZED/ELIMINATED overflow mode
8671 if Minimized_Eliminated_Overflow_Check (N) then
8672 Apply_Arithmetic_Overflow_Check (N);
8673 return;
8674 end if;
8676 if not Backend_Overflow_Checks_On_Target
8677 and then Is_Signed_Integer_Type (Etype (N))
8678 and then Do_Overflow_Check (N)
8679 then
8680 -- Software overflow checking expands -expr into (0 - expr)
8682 Rewrite (N,
8683 Make_Op_Subtract (Loc,
8684 Left_Opnd => Make_Integer_Literal (Loc, 0),
8685 Right_Opnd => Right_Opnd (N)));
8687 Analyze_And_Resolve (N, Typ);
8688 end if;
8690 -- When generating C code, convert nonbinary modular minus into code
8691 -- that relies on the front-end expansion of operator Mod.
8693 if Modify_Tree_For_C then
8694 Expand_Nonbinary_Modular_Op (N);
8695 end if;
8696 end Expand_N_Op_Minus;
8698 ---------------------
8699 -- Expand_N_Op_Mod --
8700 ---------------------
8702 procedure Expand_N_Op_Mod (N : Node_Id) is
8703 Loc : constant Source_Ptr := Sloc (N);
8704 Typ : constant Entity_Id := Etype (N);
8705 DDC : constant Boolean := Do_Division_Check (N);
8707 Left : Node_Id;
8708 Right : Node_Id;
8710 LLB : Uint;
8711 Llo : Uint;
8712 Lhi : Uint;
8713 LOK : Boolean;
8714 Rlo : Uint;
8715 Rhi : Uint;
8716 ROK : Boolean;
8718 pragma Warnings (Off, Lhi);
8720 begin
8721 Binary_Op_Validity_Checks (N);
8723 -- Check for MINIMIZED/ELIMINATED overflow mode
8725 if Minimized_Eliminated_Overflow_Check (N) then
8726 Apply_Arithmetic_Overflow_Check (N);
8727 return;
8728 end if;
8730 if Is_Integer_Type (Etype (N)) then
8731 Apply_Divide_Checks (N);
8733 -- All done if we don't have a MOD any more, which can happen as a
8734 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
8736 if Nkind (N) /= N_Op_Mod then
8737 return;
8738 end if;
8739 end if;
8741 -- Proceed with expansion of mod operator
8743 Left := Left_Opnd (N);
8744 Right := Right_Opnd (N);
8746 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
8747 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
8749 -- Convert mod to rem if operands are both known to be non-negative, or
8750 -- both known to be non-positive (these are the cases in which rem and
8751 -- mod are the same, see (RM 4.5.5(28-30)). We do this since it is quite
8752 -- likely that this will improve the quality of code, (the operation now
8753 -- corresponds to the hardware remainder), and it does not seem likely
8754 -- that it could be harmful. It also avoids some cases of the elaborate
8755 -- expansion in Modify_Tree_For_C mode below (since Ada rem = C %).
8757 if (LOK and ROK)
8758 and then ((Llo >= 0 and then Rlo >= 0)
8759 or else
8760 (Lhi <= 0 and then Rhi <= 0))
8761 then
8762 Rewrite (N,
8763 Make_Op_Rem (Sloc (N),
8764 Left_Opnd => Left_Opnd (N),
8765 Right_Opnd => Right_Opnd (N)));
8767 -- Instead of reanalyzing the node we do the analysis manually. This
8768 -- avoids anomalies when the replacement is done in an instance and
8769 -- is epsilon more efficient.
8771 Set_Entity (N, Standard_Entity (S_Op_Rem));
8772 Set_Etype (N, Typ);
8773 Set_Do_Division_Check (N, DDC);
8774 Expand_N_Op_Rem (N);
8775 Set_Analyzed (N);
8776 return;
8778 -- Otherwise, normal mod processing
8780 else
8781 -- Apply optimization x mod 1 = 0. We don't really need that with
8782 -- gcc, but it is useful with other back ends and is certainly
8783 -- harmless.
8785 if Is_Integer_Type (Etype (N))
8786 and then Compile_Time_Known_Value (Right)
8787 and then Expr_Value (Right) = Uint_1
8788 then
8789 -- Call Remove_Side_Effects to ensure that any side effects in
8790 -- the ignored left operand (in particular function calls to
8791 -- user defined functions) are properly executed.
8793 Remove_Side_Effects (Left);
8795 Rewrite (N, Make_Integer_Literal (Loc, 0));
8796 Analyze_And_Resolve (N, Typ);
8797 return;
8798 end if;
8800 -- If we still have a mod operator and we are in Modify_Tree_For_C
8801 -- mode, and we have a signed integer type, then here is where we do
8802 -- the rewrite in terms of Rem. Note this rewrite bypasses the need
8803 -- for the special handling of the annoying case of largest negative
8804 -- number mod minus one.
8806 if Nkind (N) = N_Op_Mod
8807 and then Is_Signed_Integer_Type (Typ)
8808 and then Modify_Tree_For_C
8809 then
8810 -- In the general case, we expand A mod B as
8812 -- Tnn : constant typ := A rem B;
8813 -- ..
8814 -- (if (A >= 0) = (B >= 0) then Tnn
8815 -- elsif Tnn = 0 then 0
8816 -- else Tnn + B)
8818 -- The comparison can be written simply as A >= 0 if we know that
8819 -- B >= 0 which is a very common case.
8821 -- An important optimization is when B is known at compile time
8822 -- to be 2**K for some constant. In this case we can simply AND
8823 -- the left operand with the bit string 2**K-1 (i.e. K 1-bits)
8824 -- and that works for both the positive and negative cases.
8826 declare
8827 P2 : constant Nat := Power_Of_Two (Right);
8829 begin
8830 if P2 /= 0 then
8831 Rewrite (N,
8832 Unchecked_Convert_To (Typ,
8833 Make_Op_And (Loc,
8834 Left_Opnd =>
8835 Unchecked_Convert_To
8836 (Corresponding_Unsigned_Type (Typ), Left),
8837 Right_Opnd =>
8838 Make_Integer_Literal (Loc, 2 ** P2 - 1))));
8839 Analyze_And_Resolve (N, Typ);
8840 return;
8841 end if;
8842 end;
8844 -- Here for the full rewrite
8846 declare
8847 Tnn : constant Entity_Id := Make_Temporary (Sloc (N), 'T', N);
8848 Cmp : Node_Id;
8850 begin
8851 Cmp :=
8852 Make_Op_Ge (Loc,
8853 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
8854 Right_Opnd => Make_Integer_Literal (Loc, 0));
8856 if not LOK or else Rlo < 0 then
8857 Cmp :=
8858 Make_Op_Eq (Loc,
8859 Left_Opnd => Cmp,
8860 Right_Opnd =>
8861 Make_Op_Ge (Loc,
8862 Left_Opnd => Duplicate_Subexpr_No_Checks (Right),
8863 Right_Opnd => Make_Integer_Literal (Loc, 0)));
8864 end if;
8866 Insert_Action (N,
8867 Make_Object_Declaration (Loc,
8868 Defining_Identifier => Tnn,
8869 Constant_Present => True,
8870 Object_Definition => New_Occurrence_Of (Typ, Loc),
8871 Expression =>
8872 Make_Op_Rem (Loc,
8873 Left_Opnd => Left,
8874 Right_Opnd => Right)));
8876 Rewrite (N,
8877 Make_If_Expression (Loc,
8878 Expressions => New_List (
8879 Cmp,
8880 New_Occurrence_Of (Tnn, Loc),
8881 Make_If_Expression (Loc,
8882 Is_Elsif => True,
8883 Expressions => New_List (
8884 Make_Op_Eq (Loc,
8885 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8886 Right_Opnd => Make_Integer_Literal (Loc, 0)),
8887 Make_Integer_Literal (Loc, 0),
8888 Make_Op_Add (Loc,
8889 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8890 Right_Opnd =>
8891 Duplicate_Subexpr_No_Checks (Right)))))));
8893 Analyze_And_Resolve (N, Typ);
8894 return;
8895 end;
8896 end if;
8898 -- Deal with annoying case of largest negative number mod minus one.
8899 -- Gigi may not handle this case correctly, because on some targets,
8900 -- the mod value is computed using a divide instruction which gives
8901 -- an overflow trap for this case.
8903 -- It would be a bit more efficient to figure out which targets
8904 -- this is really needed for, but in practice it is reasonable
8905 -- to do the following special check in all cases, since it means
8906 -- we get a clearer message, and also the overhead is minimal given
8907 -- that division is expensive in any case.
8909 -- In fact the check is quite easy, if the right operand is -1, then
8910 -- the mod value is always 0, and we can just ignore the left operand
8911 -- completely in this case.
8913 -- This only applies if we still have a mod operator. Skip if we
8914 -- have already rewritten this (e.g. in the case of eliminated
8915 -- overflow checks which have driven us into bignum mode).
8917 if Nkind (N) = N_Op_Mod then
8919 -- The operand type may be private (e.g. in the expansion of an
8920 -- intrinsic operation) so we must use the underlying type to get
8921 -- the bounds, and convert the literals explicitly.
8923 LLB :=
8924 Expr_Value
8925 (Type_Low_Bound (Base_Type (Underlying_Type (Etype (Left)))));
8927 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
8928 and then ((not LOK) or else (Llo = LLB))
8929 then
8930 Rewrite (N,
8931 Make_If_Expression (Loc,
8932 Expressions => New_List (
8933 Make_Op_Eq (Loc,
8934 Left_Opnd => Duplicate_Subexpr (Right),
8935 Right_Opnd =>
8936 Unchecked_Convert_To (Typ,
8937 Make_Integer_Literal (Loc, -1))),
8938 Unchecked_Convert_To (Typ,
8939 Make_Integer_Literal (Loc, Uint_0)),
8940 Relocate_Node (N))));
8942 Set_Analyzed (Next (Next (First (Expressions (N)))));
8943 Analyze_And_Resolve (N, Typ);
8944 end if;
8945 end if;
8946 end if;
8947 end Expand_N_Op_Mod;
8949 --------------------------
8950 -- Expand_N_Op_Multiply --
8951 --------------------------
8953 procedure Expand_N_Op_Multiply (N : Node_Id) is
8954 Loc : constant Source_Ptr := Sloc (N);
8955 Lop : constant Node_Id := Left_Opnd (N);
8956 Rop : constant Node_Id := Right_Opnd (N);
8958 Lp2 : constant Boolean :=
8959 Nkind (Lop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Lop);
8960 Rp2 : constant Boolean :=
8961 Nkind (Rop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Rop);
8963 Ltyp : constant Entity_Id := Etype (Lop);
8964 Rtyp : constant Entity_Id := Etype (Rop);
8965 Typ : Entity_Id := Etype (N);
8967 begin
8968 Binary_Op_Validity_Checks (N);
8970 -- Check for MINIMIZED/ELIMINATED overflow mode
8972 if Minimized_Eliminated_Overflow_Check (N) then
8973 Apply_Arithmetic_Overflow_Check (N);
8974 return;
8975 end if;
8977 -- Special optimizations for integer types
8979 if Is_Integer_Type (Typ) then
8981 -- N * 0 = 0 for integer types
8983 if Compile_Time_Known_Value (Rop)
8984 and then Expr_Value (Rop) = Uint_0
8985 then
8986 -- Call Remove_Side_Effects to ensure that any side effects in
8987 -- the ignored left operand (in particular function calls to
8988 -- user defined functions) are properly executed.
8990 Remove_Side_Effects (Lop);
8992 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
8993 Analyze_And_Resolve (N, Typ);
8994 return;
8995 end if;
8997 -- Similar handling for 0 * N = 0
8999 if Compile_Time_Known_Value (Lop)
9000 and then Expr_Value (Lop) = Uint_0
9001 then
9002 Remove_Side_Effects (Rop);
9003 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
9004 Analyze_And_Resolve (N, Typ);
9005 return;
9006 end if;
9008 -- N * 1 = 1 * N = N for integer types
9010 -- This optimisation is not done if we are going to
9011 -- rewrite the product 1 * 2 ** N to a shift.
9013 if Compile_Time_Known_Value (Rop)
9014 and then Expr_Value (Rop) = Uint_1
9015 and then not Lp2
9016 then
9017 Rewrite (N, Lop);
9018 return;
9020 elsif Compile_Time_Known_Value (Lop)
9021 and then Expr_Value (Lop) = Uint_1
9022 and then not Rp2
9023 then
9024 Rewrite (N, Rop);
9025 return;
9026 end if;
9027 end if;
9029 -- Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
9030 -- Is_Power_Of_2_For_Shift is set means that we know that our left
9031 -- operand is an integer, as required for this to work.
9033 if Rp2 then
9034 if Lp2 then
9036 -- Convert 2 ** A * 2 ** B into 2 ** (A + B)
9038 Rewrite (N,
9039 Make_Op_Expon (Loc,
9040 Left_Opnd => Make_Integer_Literal (Loc, 2),
9041 Right_Opnd =>
9042 Make_Op_Add (Loc,
9043 Left_Opnd => Right_Opnd (Lop),
9044 Right_Opnd => Right_Opnd (Rop))));
9045 Analyze_And_Resolve (N, Typ);
9046 return;
9048 else
9049 -- If the result is modular, perform the reduction of the result
9050 -- appropriately.
9052 if Is_Modular_Integer_Type (Typ)
9053 and then not Non_Binary_Modulus (Typ)
9054 then
9055 Rewrite (N,
9056 Make_Op_And (Loc,
9057 Left_Opnd =>
9058 Make_Op_Shift_Left (Loc,
9059 Left_Opnd => Lop,
9060 Right_Opnd =>
9061 Convert_To (Standard_Natural, Right_Opnd (Rop))),
9062 Right_Opnd =>
9063 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9065 else
9066 Rewrite (N,
9067 Make_Op_Shift_Left (Loc,
9068 Left_Opnd => Lop,
9069 Right_Opnd =>
9070 Convert_To (Standard_Natural, Right_Opnd (Rop))));
9071 end if;
9073 Analyze_And_Resolve (N, Typ);
9074 return;
9075 end if;
9077 -- Same processing for the operands the other way round
9079 elsif Lp2 then
9080 if Is_Modular_Integer_Type (Typ)
9081 and then not Non_Binary_Modulus (Typ)
9082 then
9083 Rewrite (N,
9084 Make_Op_And (Loc,
9085 Left_Opnd =>
9086 Make_Op_Shift_Left (Loc,
9087 Left_Opnd => Rop,
9088 Right_Opnd =>
9089 Convert_To (Standard_Natural, Right_Opnd (Lop))),
9090 Right_Opnd =>
9091 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9093 else
9094 Rewrite (N,
9095 Make_Op_Shift_Left (Loc,
9096 Left_Opnd => Rop,
9097 Right_Opnd =>
9098 Convert_To (Standard_Natural, Right_Opnd (Lop))));
9099 end if;
9101 Analyze_And_Resolve (N, Typ);
9102 return;
9103 end if;
9105 -- Do required fixup of universal fixed operation
9107 if Typ = Universal_Fixed then
9108 Fixup_Universal_Fixed_Operation (N);
9109 Typ := Etype (N);
9110 end if;
9112 -- Multiplications with fixed-point results
9114 if Is_Fixed_Point_Type (Typ) then
9116 -- No special processing if Treat_Fixed_As_Integer is set, since from
9117 -- a semantic point of view such operations are simply integer
9118 -- operations and will be treated that way.
9120 if not Treat_Fixed_As_Integer (N) then
9122 -- Case of fixed * integer => fixed
9124 if Is_Integer_Type (Rtyp) then
9125 Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N);
9127 -- Case of integer * fixed => fixed
9129 elsif Is_Integer_Type (Ltyp) then
9130 Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N);
9132 -- Case of fixed * fixed => fixed
9134 else
9135 Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N);
9136 end if;
9137 end if;
9139 -- Other cases of multiplication of fixed-point operands. Again we
9140 -- exclude the cases where Treat_Fixed_As_Integer flag is set.
9142 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
9143 and then not Treat_Fixed_As_Integer (N)
9144 then
9145 if Is_Integer_Type (Typ) then
9146 Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N);
9147 else
9148 pragma Assert (Is_Floating_Point_Type (Typ));
9149 Expand_Multiply_Fixed_By_Fixed_Giving_Float (N);
9150 end if;
9152 -- Mixed-mode operations can appear in a non-static universal context,
9153 -- in which case the integer argument must be converted explicitly.
9155 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
9156 Rewrite (Rop, Convert_To (Universal_Real, Relocate_Node (Rop)));
9157 Analyze_And_Resolve (Rop, Universal_Real);
9159 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
9160 Rewrite (Lop, Convert_To (Universal_Real, Relocate_Node (Lop)));
9161 Analyze_And_Resolve (Lop, Universal_Real);
9163 -- Non-fixed point cases, check software overflow checking required
9165 elsif Is_Signed_Integer_Type (Etype (N)) then
9166 Apply_Arithmetic_Overflow_Check (N);
9167 end if;
9169 -- Overflow checks for floating-point if -gnateF mode active
9171 Check_Float_Op_Overflow (N);
9173 -- When generating C code, convert nonbinary modular multiplications
9174 -- into code that relies on the front-end expansion of operator Mod.
9176 if Modify_Tree_For_C then
9177 Expand_Nonbinary_Modular_Op (N);
9178 end if;
9179 end Expand_N_Op_Multiply;
9181 --------------------
9182 -- Expand_N_Op_Ne --
9183 --------------------
9185 procedure Expand_N_Op_Ne (N : Node_Id) is
9186 Typ : constant Entity_Id := Etype (Left_Opnd (N));
9188 begin
9189 -- Case of elementary type with standard operator
9191 if Is_Elementary_Type (Typ)
9192 and then Sloc (Entity (N)) = Standard_Location
9193 then
9194 Binary_Op_Validity_Checks (N);
9196 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if
9197 -- means we no longer have a /= operation, we are all done.
9199 Expand_Compare_Minimize_Eliminate_Overflow (N);
9201 if Nkind (N) /= N_Op_Ne then
9202 return;
9203 end if;
9205 -- Boolean types (requiring handling of non-standard case)
9207 if Is_Boolean_Type (Typ) then
9208 Adjust_Condition (Left_Opnd (N));
9209 Adjust_Condition (Right_Opnd (N));
9210 Set_Etype (N, Standard_Boolean);
9211 Adjust_Result_Type (N, Typ);
9212 end if;
9214 Rewrite_Comparison (N);
9216 -- For all cases other than elementary types, we rewrite node as the
9217 -- negation of an equality operation, and reanalyze. The equality to be
9218 -- used is defined in the same scope and has the same signature. This
9219 -- signature must be set explicitly since in an instance it may not have
9220 -- the same visibility as in the generic unit. This avoids duplicating
9221 -- or factoring the complex code for record/array equality tests etc.
9223 -- This case is also used for the minimal expansion performed in
9224 -- GNATprove mode.
9226 else
9227 declare
9228 Loc : constant Source_Ptr := Sloc (N);
9229 Neg : Node_Id;
9230 Ne : constant Entity_Id := Entity (N);
9232 begin
9233 Binary_Op_Validity_Checks (N);
9235 Neg :=
9236 Make_Op_Not (Loc,
9237 Right_Opnd =>
9238 Make_Op_Eq (Loc,
9239 Left_Opnd => Left_Opnd (N),
9240 Right_Opnd => Right_Opnd (N)));
9242 -- The level of parentheses is useless in GNATprove mode, and
9243 -- bumping its level here leads to wrong columns being used in
9244 -- check messages, hence skip it in this mode.
9246 if not GNATprove_Mode then
9247 Set_Paren_Count (Right_Opnd (Neg), 1);
9248 end if;
9250 if Scope (Ne) /= Standard_Standard then
9251 Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
9252 end if;
9254 -- For navigation purposes, we want to treat the inequality as an
9255 -- implicit reference to the corresponding equality. Preserve the
9256 -- Comes_From_ source flag to generate proper Xref entries.
9258 Preserve_Comes_From_Source (Neg, N);
9259 Preserve_Comes_From_Source (Right_Opnd (Neg), N);
9260 Rewrite (N, Neg);
9261 Analyze_And_Resolve (N, Standard_Boolean);
9262 end;
9263 end if;
9265 -- No need for optimization in GNATprove mode, where we would rather see
9266 -- the original source expression.
9268 if not GNATprove_Mode then
9269 Optimize_Length_Comparison (N);
9270 end if;
9271 end Expand_N_Op_Ne;
9273 ---------------------
9274 -- Expand_N_Op_Not --
9275 ---------------------
9277 -- If the argument is other than a Boolean array type, there is no special
9278 -- expansion required, except for dealing with validity checks, and non-
9279 -- standard boolean representations.
9281 -- For the packed array case, we call the special routine in Exp_Pakd,
9282 -- except that if the component size is greater than one, we use the
9283 -- standard routine generating a gruesome loop (it is so peculiar to have
9284 -- packed arrays with non-standard Boolean representations anyway, so it
9285 -- does not matter that we do not handle this case efficiently).
9287 -- For the unpacked array case (and for the special packed case where we
9288 -- have non standard Booleans, as discussed above), we generate and insert
9289 -- into the tree the following function definition:
9291 -- function Nnnn (A : arr) is
9292 -- B : arr;
9293 -- begin
9294 -- for J in a'range loop
9295 -- B (J) := not A (J);
9296 -- end loop;
9297 -- return B;
9298 -- end Nnnn;
9300 -- Here arr is the actual subtype of the parameter (and hence always
9301 -- constrained). Then we replace the not with a call to this function.
9303 procedure Expand_N_Op_Not (N : Node_Id) is
9304 Loc : constant Source_Ptr := Sloc (N);
9305 Typ : constant Entity_Id := Etype (N);
9306 Opnd : Node_Id;
9307 Arr : Entity_Id;
9308 A : Entity_Id;
9309 B : Entity_Id;
9310 J : Entity_Id;
9311 A_J : Node_Id;
9312 B_J : Node_Id;
9314 Func_Name : Entity_Id;
9315 Loop_Statement : Node_Id;
9317 begin
9318 Unary_Op_Validity_Checks (N);
9320 -- For boolean operand, deal with non-standard booleans
9322 if Is_Boolean_Type (Typ) then
9323 Adjust_Condition (Right_Opnd (N));
9324 Set_Etype (N, Standard_Boolean);
9325 Adjust_Result_Type (N, Typ);
9326 return;
9327 end if;
9329 -- Only array types need any other processing
9331 if not Is_Array_Type (Typ) then
9332 return;
9333 end if;
9335 -- Case of array operand. If bit packed with a component size of 1,
9336 -- handle it in Exp_Pakd if the operand is known to be aligned.
9338 if Is_Bit_Packed_Array (Typ)
9339 and then Component_Size (Typ) = 1
9340 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
9341 then
9342 Expand_Packed_Not (N);
9343 return;
9344 end if;
9346 -- Case of array operand which is not bit-packed. If the context is
9347 -- a safe assignment, call in-place operation, If context is a larger
9348 -- boolean expression in the context of a safe assignment, expansion is
9349 -- done by enclosing operation.
9351 Opnd := Relocate_Node (Right_Opnd (N));
9352 Convert_To_Actual_Subtype (Opnd);
9353 Arr := Etype (Opnd);
9354 Ensure_Defined (Arr, N);
9355 Silly_Boolean_Array_Not_Test (N, Arr);
9357 if Nkind (Parent (N)) = N_Assignment_Statement then
9358 if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
9359 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9360 return;
9362 -- Special case the negation of a binary operation
9364 elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
9365 and then Safe_In_Place_Array_Op
9366 (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
9367 then
9368 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9369 return;
9370 end if;
9372 elsif Nkind (Parent (N)) in N_Binary_Op
9373 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
9374 then
9375 declare
9376 Op1 : constant Node_Id := Left_Opnd (Parent (N));
9377 Op2 : constant Node_Id := Right_Opnd (Parent (N));
9378 Lhs : constant Node_Id := Name (Parent (Parent (N)));
9380 begin
9381 if Safe_In_Place_Array_Op (Lhs, Op1, Op2) then
9383 -- (not A) op (not B) can be reduced to a single call
9385 if N = Op1 and then Nkind (Op2) = N_Op_Not then
9386 return;
9388 elsif N = Op2 and then Nkind (Op1) = N_Op_Not then
9389 return;
9391 -- A xor (not B) can also be special-cased
9393 elsif N = Op2 and then Nkind (Parent (N)) = N_Op_Xor then
9394 return;
9395 end if;
9396 end if;
9397 end;
9398 end if;
9400 A := Make_Defining_Identifier (Loc, Name_uA);
9401 B := Make_Defining_Identifier (Loc, Name_uB);
9402 J := Make_Defining_Identifier (Loc, Name_uJ);
9404 A_J :=
9405 Make_Indexed_Component (Loc,
9406 Prefix => New_Occurrence_Of (A, Loc),
9407 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9409 B_J :=
9410 Make_Indexed_Component (Loc,
9411 Prefix => New_Occurrence_Of (B, Loc),
9412 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9414 Loop_Statement :=
9415 Make_Implicit_Loop_Statement (N,
9416 Identifier => Empty,
9418 Iteration_Scheme =>
9419 Make_Iteration_Scheme (Loc,
9420 Loop_Parameter_Specification =>
9421 Make_Loop_Parameter_Specification (Loc,
9422 Defining_Identifier => J,
9423 Discrete_Subtype_Definition =>
9424 Make_Attribute_Reference (Loc,
9425 Prefix => Make_Identifier (Loc, Chars (A)),
9426 Attribute_Name => Name_Range))),
9428 Statements => New_List (
9429 Make_Assignment_Statement (Loc,
9430 Name => B_J,
9431 Expression => Make_Op_Not (Loc, A_J))));
9433 Func_Name := Make_Temporary (Loc, 'N');
9434 Set_Is_Inlined (Func_Name);
9436 Insert_Action (N,
9437 Make_Subprogram_Body (Loc,
9438 Specification =>
9439 Make_Function_Specification (Loc,
9440 Defining_Unit_Name => Func_Name,
9441 Parameter_Specifications => New_List (
9442 Make_Parameter_Specification (Loc,
9443 Defining_Identifier => A,
9444 Parameter_Type => New_Occurrence_Of (Typ, Loc))),
9445 Result_Definition => New_Occurrence_Of (Typ, Loc)),
9447 Declarations => New_List (
9448 Make_Object_Declaration (Loc,
9449 Defining_Identifier => B,
9450 Object_Definition => New_Occurrence_Of (Arr, Loc))),
9452 Handled_Statement_Sequence =>
9453 Make_Handled_Sequence_Of_Statements (Loc,
9454 Statements => New_List (
9455 Loop_Statement,
9456 Make_Simple_Return_Statement (Loc,
9457 Expression => Make_Identifier (Loc, Chars (B)))))));
9459 Rewrite (N,
9460 Make_Function_Call (Loc,
9461 Name => New_Occurrence_Of (Func_Name, Loc),
9462 Parameter_Associations => New_List (Opnd)));
9464 Analyze_And_Resolve (N, Typ);
9465 end Expand_N_Op_Not;
9467 --------------------
9468 -- Expand_N_Op_Or --
9469 --------------------
9471 procedure Expand_N_Op_Or (N : Node_Id) is
9472 Typ : constant Entity_Id := Etype (N);
9474 begin
9475 Binary_Op_Validity_Checks (N);
9477 if Is_Array_Type (Etype (N)) then
9478 Expand_Boolean_Operator (N);
9480 elsif Is_Boolean_Type (Etype (N)) then
9481 Adjust_Condition (Left_Opnd (N));
9482 Adjust_Condition (Right_Opnd (N));
9483 Set_Etype (N, Standard_Boolean);
9484 Adjust_Result_Type (N, Typ);
9486 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9487 Expand_Intrinsic_Call (N, Entity (N));
9488 end if;
9490 -- When generating C code, convert nonbinary modular operators into code
9491 -- that relies on the front-end expansion of operator Mod.
9493 if Modify_Tree_For_C then
9494 Expand_Nonbinary_Modular_Op (N);
9495 end if;
9496 end Expand_N_Op_Or;
9498 ----------------------
9499 -- Expand_N_Op_Plus --
9500 ----------------------
9502 procedure Expand_N_Op_Plus (N : Node_Id) is
9503 begin
9504 Unary_Op_Validity_Checks (N);
9506 -- Check for MINIMIZED/ELIMINATED overflow mode
9508 if Minimized_Eliminated_Overflow_Check (N) then
9509 Apply_Arithmetic_Overflow_Check (N);
9510 return;
9511 end if;
9512 end Expand_N_Op_Plus;
9514 ---------------------
9515 -- Expand_N_Op_Rem --
9516 ---------------------
9518 procedure Expand_N_Op_Rem (N : Node_Id) is
9519 Loc : constant Source_Ptr := Sloc (N);
9520 Typ : constant Entity_Id := Etype (N);
9522 Left : Node_Id;
9523 Right : Node_Id;
9525 Lo : Uint;
9526 Hi : Uint;
9527 OK : Boolean;
9529 Lneg : Boolean;
9530 Rneg : Boolean;
9531 -- Set if corresponding operand can be negative
9533 pragma Unreferenced (Hi);
9535 begin
9536 Binary_Op_Validity_Checks (N);
9538 -- Check for MINIMIZED/ELIMINATED overflow mode
9540 if Minimized_Eliminated_Overflow_Check (N) then
9541 Apply_Arithmetic_Overflow_Check (N);
9542 return;
9543 end if;
9545 if Is_Integer_Type (Etype (N)) then
9546 Apply_Divide_Checks (N);
9548 -- All done if we don't have a REM any more, which can happen as a
9549 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
9551 if Nkind (N) /= N_Op_Rem then
9552 return;
9553 end if;
9554 end if;
9556 -- Proceed with expansion of REM
9558 Left := Left_Opnd (N);
9559 Right := Right_Opnd (N);
9561 -- Apply optimization x rem 1 = 0. We don't really need that with gcc,
9562 -- but it is useful with other back ends, and is certainly harmless.
9564 if Is_Integer_Type (Etype (N))
9565 and then Compile_Time_Known_Value (Right)
9566 and then Expr_Value (Right) = Uint_1
9567 then
9568 -- Call Remove_Side_Effects to ensure that any side effects in the
9569 -- ignored left operand (in particular function calls to user defined
9570 -- functions) are properly executed.
9572 Remove_Side_Effects (Left);
9574 Rewrite (N, Make_Integer_Literal (Loc, 0));
9575 Analyze_And_Resolve (N, Typ);
9576 return;
9577 end if;
9579 -- Deal with annoying case of largest negative number remainder minus
9580 -- one. Gigi may not handle this case correctly, because on some
9581 -- targets, the mod value is computed using a divide instruction
9582 -- which gives an overflow trap for this case.
9584 -- It would be a bit more efficient to figure out which targets this
9585 -- is really needed for, but in practice it is reasonable to do the
9586 -- following special check in all cases, since it means we get a clearer
9587 -- message, and also the overhead is minimal given that division is
9588 -- expensive in any case.
9590 -- In fact the check is quite easy, if the right operand is -1, then
9591 -- the remainder is always 0, and we can just ignore the left operand
9592 -- completely in this case.
9594 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9595 Lneg := (not OK) or else Lo < 0;
9597 Determine_Range (Left, OK, Lo, Hi, Assume_Valid => True);
9598 Rneg := (not OK) or else Lo < 0;
9600 -- We won't mess with trying to find out if the left operand can really
9601 -- be the largest negative number (that's a pain in the case of private
9602 -- types and this is really marginal). We will just assume that we need
9603 -- the test if the left operand can be negative at all.
9605 if Lneg and Rneg then
9606 Rewrite (N,
9607 Make_If_Expression (Loc,
9608 Expressions => New_List (
9609 Make_Op_Eq (Loc,
9610 Left_Opnd => Duplicate_Subexpr (Right),
9611 Right_Opnd =>
9612 Unchecked_Convert_To (Typ, Make_Integer_Literal (Loc, -1))),
9614 Unchecked_Convert_To (Typ,
9615 Make_Integer_Literal (Loc, Uint_0)),
9617 Relocate_Node (N))));
9619 Set_Analyzed (Next (Next (First (Expressions (N)))));
9620 Analyze_And_Resolve (N, Typ);
9621 end if;
9622 end Expand_N_Op_Rem;
9624 -----------------------------
9625 -- Expand_N_Op_Rotate_Left --
9626 -----------------------------
9628 procedure Expand_N_Op_Rotate_Left (N : Node_Id) is
9629 begin
9630 Binary_Op_Validity_Checks (N);
9632 -- If we are in Modify_Tree_For_C mode, there is no rotate left in C,
9633 -- so we rewrite in terms of logical shifts
9635 -- Shift_Left (Num, Bits) or Shift_Right (num, Esize - Bits)
9637 -- where Bits is the shift count mod Esize (the mod operation here
9638 -- deals with ludicrous large shift counts, which are apparently OK).
9640 -- What about nonbinary modulus ???
9642 declare
9643 Loc : constant Source_Ptr := Sloc (N);
9644 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9645 Typ : constant Entity_Id := Etype (N);
9647 begin
9648 if Modify_Tree_For_C then
9649 Rewrite (Right_Opnd (N),
9650 Make_Op_Rem (Loc,
9651 Left_Opnd => Relocate_Node (Right_Opnd (N)),
9652 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
9654 Analyze_And_Resolve (Right_Opnd (N), Rtp);
9656 Rewrite (N,
9657 Make_Op_Or (Loc,
9658 Left_Opnd =>
9659 Make_Op_Shift_Left (Loc,
9660 Left_Opnd => Left_Opnd (N),
9661 Right_Opnd => Right_Opnd (N)),
9663 Right_Opnd =>
9664 Make_Op_Shift_Right (Loc,
9665 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9666 Right_Opnd =>
9667 Make_Op_Subtract (Loc,
9668 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9669 Right_Opnd =>
9670 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9672 Analyze_And_Resolve (N, Typ);
9673 end if;
9674 end;
9675 end Expand_N_Op_Rotate_Left;
9677 ------------------------------
9678 -- Expand_N_Op_Rotate_Right --
9679 ------------------------------
9681 procedure Expand_N_Op_Rotate_Right (N : Node_Id) is
9682 begin
9683 Binary_Op_Validity_Checks (N);
9685 -- If we are in Modify_Tree_For_C mode, there is no rotate right in C,
9686 -- so we rewrite in terms of logical shifts
9688 -- Shift_Right (Num, Bits) or Shift_Left (num, Esize - Bits)
9690 -- where Bits is the shift count mod Esize (the mod operation here
9691 -- deals with ludicrous large shift counts, which are apparently OK).
9693 -- What about nonbinary modulus ???
9695 declare
9696 Loc : constant Source_Ptr := Sloc (N);
9697 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9698 Typ : constant Entity_Id := Etype (N);
9700 begin
9701 Rewrite (Right_Opnd (N),
9702 Make_Op_Rem (Loc,
9703 Left_Opnd => Relocate_Node (Right_Opnd (N)),
9704 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
9706 Analyze_And_Resolve (Right_Opnd (N), Rtp);
9708 if Modify_Tree_For_C then
9709 Rewrite (N,
9710 Make_Op_Or (Loc,
9711 Left_Opnd =>
9712 Make_Op_Shift_Right (Loc,
9713 Left_Opnd => Left_Opnd (N),
9714 Right_Opnd => Right_Opnd (N)),
9716 Right_Opnd =>
9717 Make_Op_Shift_Left (Loc,
9718 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9719 Right_Opnd =>
9720 Make_Op_Subtract (Loc,
9721 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9722 Right_Opnd =>
9723 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9725 Analyze_And_Resolve (N, Typ);
9726 end if;
9727 end;
9728 end Expand_N_Op_Rotate_Right;
9730 ----------------------------
9731 -- Expand_N_Op_Shift_Left --
9732 ----------------------------
9734 -- Note: nothing in this routine depends on left as opposed to right shifts
9735 -- so we share the routine for expanding shift right operations.
9737 procedure Expand_N_Op_Shift_Left (N : Node_Id) is
9738 begin
9739 Binary_Op_Validity_Checks (N);
9741 -- If we are in Modify_Tree_For_C mode, then ensure that the right
9742 -- operand is not greater than the word size (since that would not
9743 -- be defined properly by the corresponding C shift operator).
9745 if Modify_Tree_For_C then
9746 declare
9747 Right : constant Node_Id := Right_Opnd (N);
9748 Loc : constant Source_Ptr := Sloc (Right);
9749 Typ : constant Entity_Id := Etype (N);
9750 Siz : constant Uint := Esize (Typ);
9751 Orig : Node_Id;
9752 OK : Boolean;
9753 Lo : Uint;
9754 Hi : Uint;
9756 begin
9757 if Compile_Time_Known_Value (Right) then
9758 if Expr_Value (Right) >= Siz then
9759 Rewrite (N, Make_Integer_Literal (Loc, 0));
9760 Analyze_And_Resolve (N, Typ);
9761 end if;
9763 -- Not compile time known, find range
9765 else
9766 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9768 -- Nothing to do if known to be OK range, otherwise expand
9770 if not OK or else Hi >= Siz then
9772 -- Prevent recursion on copy of shift node
9774 Orig := Relocate_Node (N);
9775 Set_Analyzed (Orig);
9777 -- Now do the rewrite
9779 Rewrite (N,
9780 Make_If_Expression (Loc,
9781 Expressions => New_List (
9782 Make_Op_Ge (Loc,
9783 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
9784 Right_Opnd => Make_Integer_Literal (Loc, Siz)),
9785 Make_Integer_Literal (Loc, 0),
9786 Orig)));
9787 Analyze_And_Resolve (N, Typ);
9788 end if;
9789 end if;
9790 end;
9791 end if;
9792 end Expand_N_Op_Shift_Left;
9794 -----------------------------
9795 -- Expand_N_Op_Shift_Right --
9796 -----------------------------
9798 procedure Expand_N_Op_Shift_Right (N : Node_Id) is
9799 begin
9800 -- Share shift left circuit
9802 Expand_N_Op_Shift_Left (N);
9803 end Expand_N_Op_Shift_Right;
9805 ----------------------------------------
9806 -- Expand_N_Op_Shift_Right_Arithmetic --
9807 ----------------------------------------
9809 procedure Expand_N_Op_Shift_Right_Arithmetic (N : Node_Id) is
9810 begin
9811 Binary_Op_Validity_Checks (N);
9813 -- If we are in Modify_Tree_For_C mode, there is no shift right
9814 -- arithmetic in C, so we rewrite in terms of logical shifts.
9816 -- Shift_Right (Num, Bits) or
9817 -- (if Num >= Sign
9818 -- then not (Shift_Right (Mask, bits))
9819 -- else 0)
9821 -- Here Mask is all 1 bits (2**size - 1), and Sign is 2**(size - 1)
9823 -- Note: in almost all C compilers it would work to just shift a
9824 -- signed integer right, but it's undefined and we cannot rely on it.
9826 -- Note: the above works fine for shift counts greater than or equal
9827 -- to the word size, since in this case (not (Shift_Right (Mask, bits)))
9828 -- generates all 1'bits.
9830 -- What about nonbinary modulus ???
9832 declare
9833 Loc : constant Source_Ptr := Sloc (N);
9834 Typ : constant Entity_Id := Etype (N);
9835 Sign : constant Uint := 2 ** (Esize (Typ) - 1);
9836 Mask : constant Uint := (2 ** Esize (Typ)) - 1;
9837 Left : constant Node_Id := Left_Opnd (N);
9838 Right : constant Node_Id := Right_Opnd (N);
9839 Maskx : Node_Id;
9841 begin
9842 if Modify_Tree_For_C then
9844 -- Here if not (Shift_Right (Mask, bits)) can be computed at
9845 -- compile time as a single constant.
9847 if Compile_Time_Known_Value (Right) then
9848 declare
9849 Val : constant Uint := Expr_Value (Right);
9851 begin
9852 if Val >= Esize (Typ) then
9853 Maskx := Make_Integer_Literal (Loc, Mask);
9855 else
9856 Maskx :=
9857 Make_Integer_Literal (Loc,
9858 Intval => Mask - (Mask / (2 ** Expr_Value (Right))));
9859 end if;
9860 end;
9862 else
9863 Maskx :=
9864 Make_Op_Not (Loc,
9865 Right_Opnd =>
9866 Make_Op_Shift_Right (Loc,
9867 Left_Opnd => Make_Integer_Literal (Loc, Mask),
9868 Right_Opnd => Duplicate_Subexpr_No_Checks (Right)));
9869 end if;
9871 -- Now do the rewrite
9873 Rewrite (N,
9874 Make_Op_Or (Loc,
9875 Left_Opnd =>
9876 Make_Op_Shift_Right (Loc,
9877 Left_Opnd => Left,
9878 Right_Opnd => Right),
9879 Right_Opnd =>
9880 Make_If_Expression (Loc,
9881 Expressions => New_List (
9882 Make_Op_Ge (Loc,
9883 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
9884 Right_Opnd => Make_Integer_Literal (Loc, Sign)),
9885 Maskx,
9886 Make_Integer_Literal (Loc, 0)))));
9887 Analyze_And_Resolve (N, Typ);
9888 end if;
9889 end;
9890 end Expand_N_Op_Shift_Right_Arithmetic;
9892 --------------------------
9893 -- Expand_N_Op_Subtract --
9894 --------------------------
9896 procedure Expand_N_Op_Subtract (N : Node_Id) is
9897 Typ : constant Entity_Id := Etype (N);
9899 begin
9900 Binary_Op_Validity_Checks (N);
9902 -- Check for MINIMIZED/ELIMINATED overflow mode
9904 if Minimized_Eliminated_Overflow_Check (N) then
9905 Apply_Arithmetic_Overflow_Check (N);
9906 return;
9907 end if;
9909 -- N - 0 = N for integer types
9911 if Is_Integer_Type (Typ)
9912 and then Compile_Time_Known_Value (Right_Opnd (N))
9913 and then Expr_Value (Right_Opnd (N)) = 0
9914 then
9915 Rewrite (N, Left_Opnd (N));
9916 return;
9917 end if;
9919 -- Arithmetic overflow checks for signed integer/fixed point types
9921 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
9922 Apply_Arithmetic_Overflow_Check (N);
9923 end if;
9925 -- Overflow checks for floating-point if -gnateF mode active
9927 Check_Float_Op_Overflow (N);
9929 -- When generating C code, convert nonbinary modular subtractions into
9930 -- code that relies on the front-end expansion of operator Mod.
9932 if Modify_Tree_For_C then
9933 Expand_Nonbinary_Modular_Op (N);
9934 end if;
9935 end Expand_N_Op_Subtract;
9937 ---------------------
9938 -- Expand_N_Op_Xor --
9939 ---------------------
9941 procedure Expand_N_Op_Xor (N : Node_Id) is
9942 Typ : constant Entity_Id := Etype (N);
9944 begin
9945 Binary_Op_Validity_Checks (N);
9947 if Is_Array_Type (Etype (N)) then
9948 Expand_Boolean_Operator (N);
9950 elsif Is_Boolean_Type (Etype (N)) then
9951 Adjust_Condition (Left_Opnd (N));
9952 Adjust_Condition (Right_Opnd (N));
9953 Set_Etype (N, Standard_Boolean);
9954 Adjust_Result_Type (N, Typ);
9956 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9957 Expand_Intrinsic_Call (N, Entity (N));
9959 end if;
9960 end Expand_N_Op_Xor;
9962 ----------------------
9963 -- Expand_N_Or_Else --
9964 ----------------------
9966 procedure Expand_N_Or_Else (N : Node_Id)
9967 renames Expand_Short_Circuit_Operator;
9969 -----------------------------------
9970 -- Expand_N_Qualified_Expression --
9971 -----------------------------------
9973 procedure Expand_N_Qualified_Expression (N : Node_Id) is
9974 Operand : constant Node_Id := Expression (N);
9975 Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
9977 begin
9978 -- Do validity check if validity checking operands
9980 if Validity_Checks_On and Validity_Check_Operands then
9981 Ensure_Valid (Operand);
9982 end if;
9984 -- Apply possible constraint check
9986 Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
9988 if Do_Range_Check (Operand) then
9989 Set_Do_Range_Check (Operand, False);
9990 Generate_Range_Check (Operand, Target_Type, CE_Range_Check_Failed);
9991 end if;
9992 end Expand_N_Qualified_Expression;
9994 ------------------------------------
9995 -- Expand_N_Quantified_Expression --
9996 ------------------------------------
9998 -- We expand:
10000 -- for all X in range => Cond
10002 -- into:
10004 -- T := True;
10005 -- for X in range loop
10006 -- if not Cond then
10007 -- T := False;
10008 -- exit;
10009 -- end if;
10010 -- end loop;
10012 -- Similarly, an existentially quantified expression:
10014 -- for some X in range => Cond
10016 -- becomes:
10018 -- T := False;
10019 -- for X in range loop
10020 -- if Cond then
10021 -- T := True;
10022 -- exit;
10023 -- end if;
10024 -- end loop;
10026 -- In both cases, the iteration may be over a container in which case it is
10027 -- given by an iterator specification, not a loop parameter specification.
10029 procedure Expand_N_Quantified_Expression (N : Node_Id) is
10030 Actions : constant List_Id := New_List;
10031 For_All : constant Boolean := All_Present (N);
10032 Iter_Spec : constant Node_Id := Iterator_Specification (N);
10033 Loc : constant Source_Ptr := Sloc (N);
10034 Loop_Spec : constant Node_Id := Loop_Parameter_Specification (N);
10035 Cond : Node_Id;
10036 Flag : Entity_Id;
10037 Scheme : Node_Id;
10038 Stmts : List_Id;
10040 begin
10041 -- Create the declaration of the flag which tracks the status of the
10042 -- quantified expression. Generate:
10044 -- Flag : Boolean := (True | False);
10046 Flag := Make_Temporary (Loc, 'T', N);
10048 Append_To (Actions,
10049 Make_Object_Declaration (Loc,
10050 Defining_Identifier => Flag,
10051 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
10052 Expression =>
10053 New_Occurrence_Of (Boolean_Literals (For_All), Loc)));
10055 -- Construct the circuitry which tracks the status of the quantified
10056 -- expression. Generate:
10058 -- if [not] Cond then
10059 -- Flag := (False | True);
10060 -- exit;
10061 -- end if;
10063 Cond := Relocate_Node (Condition (N));
10065 if For_All then
10066 Cond := Make_Op_Not (Loc, Cond);
10067 end if;
10069 Stmts := New_List (
10070 Make_Implicit_If_Statement (N,
10071 Condition => Cond,
10072 Then_Statements => New_List (
10073 Make_Assignment_Statement (Loc,
10074 Name => New_Occurrence_Of (Flag, Loc),
10075 Expression =>
10076 New_Occurrence_Of (Boolean_Literals (not For_All), Loc)),
10077 Make_Exit_Statement (Loc))));
10079 -- Build the loop equivalent of the quantified expression
10081 if Present (Iter_Spec) then
10082 Scheme :=
10083 Make_Iteration_Scheme (Loc,
10084 Iterator_Specification => Iter_Spec);
10085 else
10086 Scheme :=
10087 Make_Iteration_Scheme (Loc,
10088 Loop_Parameter_Specification => Loop_Spec);
10089 end if;
10091 Append_To (Actions,
10092 Make_Loop_Statement (Loc,
10093 Iteration_Scheme => Scheme,
10094 Statements => Stmts,
10095 End_Label => Empty));
10097 -- Transform the quantified expression
10099 Rewrite (N,
10100 Make_Expression_With_Actions (Loc,
10101 Expression => New_Occurrence_Of (Flag, Loc),
10102 Actions => Actions));
10103 Analyze_And_Resolve (N, Standard_Boolean);
10104 end Expand_N_Quantified_Expression;
10106 ---------------------------------
10107 -- Expand_N_Selected_Component --
10108 ---------------------------------
10110 procedure Expand_N_Selected_Component (N : Node_Id) is
10111 Loc : constant Source_Ptr := Sloc (N);
10112 Par : constant Node_Id := Parent (N);
10113 P : constant Node_Id := Prefix (N);
10114 S : constant Node_Id := Selector_Name (N);
10115 Ptyp : Entity_Id := Underlying_Type (Etype (P));
10116 Disc : Entity_Id;
10117 New_N : Node_Id;
10118 Dcon : Elmt_Id;
10119 Dval : Node_Id;
10121 function In_Left_Hand_Side (Comp : Node_Id) return Boolean;
10122 -- Gigi needs a temporary for prefixes that depend on a discriminant,
10123 -- unless the context of an assignment can provide size information.
10124 -- Don't we have a general routine that does this???
10126 function Is_Subtype_Declaration return Boolean;
10127 -- The replacement of a discriminant reference by its value is required
10128 -- if this is part of the initialization of an temporary generated by a
10129 -- change of representation. This shows up as the construction of a
10130 -- discriminant constraint for a subtype declared at the same point as
10131 -- the entity in the prefix of the selected component. We recognize this
10132 -- case when the context of the reference is:
10133 -- subtype ST is T(Obj.D);
10134 -- where the entity for Obj comes from source, and ST has the same sloc.
10136 -----------------------
10137 -- In_Left_Hand_Side --
10138 -----------------------
10140 function In_Left_Hand_Side (Comp : Node_Id) return Boolean is
10141 begin
10142 return (Nkind (Parent (Comp)) = N_Assignment_Statement
10143 and then Comp = Name (Parent (Comp)))
10144 or else (Present (Parent (Comp))
10145 and then Nkind (Parent (Comp)) in N_Subexpr
10146 and then In_Left_Hand_Side (Parent (Comp)));
10147 end In_Left_Hand_Side;
10149 -----------------------------
10150 -- Is_Subtype_Declaration --
10151 -----------------------------
10153 function Is_Subtype_Declaration return Boolean is
10154 Par : constant Node_Id := Parent (N);
10155 begin
10156 return
10157 Nkind (Par) = N_Index_Or_Discriminant_Constraint
10158 and then Nkind (Parent (Parent (Par))) = N_Subtype_Declaration
10159 and then Comes_From_Source (Entity (Prefix (N)))
10160 and then Sloc (Par) = Sloc (Entity (Prefix (N)));
10161 end Is_Subtype_Declaration;
10163 -- Start of processing for Expand_N_Selected_Component
10165 begin
10166 -- Insert explicit dereference if required
10168 if Is_Access_Type (Ptyp) then
10170 -- First set prefix type to proper access type, in case it currently
10171 -- has a private (non-access) view of this type.
10173 Set_Etype (P, Ptyp);
10175 Insert_Explicit_Dereference (P);
10176 Analyze_And_Resolve (P, Designated_Type (Ptyp));
10178 if Ekind (Etype (P)) = E_Private_Subtype
10179 and then Is_For_Access_Subtype (Etype (P))
10180 then
10181 Set_Etype (P, Base_Type (Etype (P)));
10182 end if;
10184 Ptyp := Etype (P);
10185 end if;
10187 -- Deal with discriminant check required
10189 if Do_Discriminant_Check (N) then
10190 if Present (Discriminant_Checking_Func
10191 (Original_Record_Component (Entity (S))))
10192 then
10193 -- Present the discriminant checking function to the backend, so
10194 -- that it can inline the call to the function.
10196 Add_Inlined_Body
10197 (Discriminant_Checking_Func
10198 (Original_Record_Component (Entity (S))),
10201 -- Now reset the flag and generate the call
10203 Set_Do_Discriminant_Check (N, False);
10204 Generate_Discriminant_Check (N);
10206 -- In the case of Unchecked_Union, no discriminant checking is
10207 -- actually performed.
10209 else
10210 Set_Do_Discriminant_Check (N, False);
10211 end if;
10212 end if;
10214 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10215 -- function, then additional actuals must be passed.
10217 if Is_Build_In_Place_Function_Call (P) then
10218 Make_Build_In_Place_Call_In_Anonymous_Context (P);
10220 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
10221 -- containing build-in-place function calls whose returned object covers
10222 -- interface types.
10224 elsif Present (Unqual_BIP_Iface_Function_Call (P)) then
10225 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (P);
10226 end if;
10228 -- Gigi cannot handle unchecked conversions that are the prefix of a
10229 -- selected component with discriminants. This must be checked during
10230 -- expansion, because during analysis the type of the selector is not
10231 -- known at the point the prefix is analyzed. If the conversion is the
10232 -- target of an assignment, then we cannot force the evaluation.
10234 if Nkind (Prefix (N)) = N_Unchecked_Type_Conversion
10235 and then Has_Discriminants (Etype (N))
10236 and then not In_Left_Hand_Side (N)
10237 then
10238 Force_Evaluation (Prefix (N));
10239 end if;
10241 -- Remaining processing applies only if selector is a discriminant
10243 if Ekind (Entity (Selector_Name (N))) = E_Discriminant then
10245 -- If the selector is a discriminant of a constrained record type,
10246 -- we may be able to rewrite the expression with the actual value
10247 -- of the discriminant, a useful optimization in some cases.
10249 if Is_Record_Type (Ptyp)
10250 and then Has_Discriminants (Ptyp)
10251 and then Is_Constrained (Ptyp)
10252 then
10253 -- Do this optimization for discrete types only, and not for
10254 -- access types (access discriminants get us into trouble).
10256 if not Is_Discrete_Type (Etype (N)) then
10257 null;
10259 -- Don't do this on the left-hand side of an assignment statement.
10260 -- Normally one would think that references like this would not
10261 -- occur, but they do in generated code, and mean that we really
10262 -- do want to assign the discriminant.
10264 elsif Nkind (Par) = N_Assignment_Statement
10265 and then Name (Par) = N
10266 then
10267 null;
10269 -- Don't do this optimization for the prefix of an attribute or
10270 -- the name of an object renaming declaration since these are
10271 -- contexts where we do not want the value anyway.
10273 elsif (Nkind (Par) = N_Attribute_Reference
10274 and then Prefix (Par) = N)
10275 or else Is_Renamed_Object (N)
10276 then
10277 null;
10279 -- Don't do this optimization if we are within the code for a
10280 -- discriminant check, since the whole point of such a check may
10281 -- be to verify the condition on which the code below depends.
10283 elsif Is_In_Discriminant_Check (N) then
10284 null;
10286 -- Green light to see if we can do the optimization. There is
10287 -- still one condition that inhibits the optimization below but
10288 -- now is the time to check the particular discriminant.
10290 else
10291 -- Loop through discriminants to find the matching discriminant
10292 -- constraint to see if we can copy it.
10294 Disc := First_Discriminant (Ptyp);
10295 Dcon := First_Elmt (Discriminant_Constraint (Ptyp));
10296 Discr_Loop : while Present (Dcon) loop
10297 Dval := Node (Dcon);
10299 -- Check if this is the matching discriminant and if the
10300 -- discriminant value is simple enough to make sense to
10301 -- copy. We don't want to copy complex expressions, and
10302 -- indeed to do so can cause trouble (before we put in
10303 -- this guard, a discriminant expression containing an
10304 -- AND THEN was copied, causing problems for coverage
10305 -- analysis tools).
10307 -- However, if the reference is part of the initialization
10308 -- code generated for an object declaration, we must use
10309 -- the discriminant value from the subtype constraint,
10310 -- because the selected component may be a reference to the
10311 -- object being initialized, whose discriminant is not yet
10312 -- set. This only happens in complex cases involving changes
10313 -- or representation.
10315 if Disc = Entity (Selector_Name (N))
10316 and then (Is_Entity_Name (Dval)
10317 or else Compile_Time_Known_Value (Dval)
10318 or else Is_Subtype_Declaration)
10319 then
10320 -- Here we have the matching discriminant. Check for
10321 -- the case of a discriminant of a component that is
10322 -- constrained by an outer discriminant, which cannot
10323 -- be optimized away.
10325 if Denotes_Discriminant
10326 (Dval, Check_Concurrent => True)
10327 then
10328 exit Discr_Loop;
10330 elsif Nkind (Original_Node (Dval)) = N_Selected_Component
10331 and then
10332 Denotes_Discriminant
10333 (Selector_Name (Original_Node (Dval)), True)
10334 then
10335 exit Discr_Loop;
10337 -- Do not retrieve value if constraint is not static. It
10338 -- is generally not useful, and the constraint may be a
10339 -- rewritten outer discriminant in which case it is in
10340 -- fact incorrect.
10342 elsif Is_Entity_Name (Dval)
10343 and then
10344 Nkind (Parent (Entity (Dval))) = N_Object_Declaration
10345 and then Present (Expression (Parent (Entity (Dval))))
10346 and then not
10347 Is_OK_Static_Expression
10348 (Expression (Parent (Entity (Dval))))
10349 then
10350 exit Discr_Loop;
10352 -- In the context of a case statement, the expression may
10353 -- have the base type of the discriminant, and we need to
10354 -- preserve the constraint to avoid spurious errors on
10355 -- missing cases.
10357 elsif Nkind (Parent (N)) = N_Case_Statement
10358 and then Etype (Dval) /= Etype (Disc)
10359 then
10360 Rewrite (N,
10361 Make_Qualified_Expression (Loc,
10362 Subtype_Mark =>
10363 New_Occurrence_Of (Etype (Disc), Loc),
10364 Expression =>
10365 New_Copy_Tree (Dval)));
10366 Analyze_And_Resolve (N, Etype (Disc));
10368 -- In case that comes out as a static expression,
10369 -- reset it (a selected component is never static).
10371 Set_Is_Static_Expression (N, False);
10372 return;
10374 -- Otherwise we can just copy the constraint, but the
10375 -- result is certainly not static. In some cases the
10376 -- discriminant constraint has been analyzed in the
10377 -- context of the original subtype indication, but for
10378 -- itypes the constraint might not have been analyzed
10379 -- yet, and this must be done now.
10381 else
10382 Rewrite (N, New_Copy_Tree (Dval));
10383 Analyze_And_Resolve (N);
10384 Set_Is_Static_Expression (N, False);
10385 return;
10386 end if;
10387 end if;
10389 Next_Elmt (Dcon);
10390 Next_Discriminant (Disc);
10391 end loop Discr_Loop;
10393 -- Note: the above loop should always find a matching
10394 -- discriminant, but if it does not, we just missed an
10395 -- optimization due to some glitch (perhaps a previous
10396 -- error), so ignore.
10398 end if;
10399 end if;
10401 -- The only remaining processing is in the case of a discriminant of
10402 -- a concurrent object, where we rewrite the prefix to denote the
10403 -- corresponding record type. If the type is derived and has renamed
10404 -- discriminants, use corresponding discriminant, which is the one
10405 -- that appears in the corresponding record.
10407 if not Is_Concurrent_Type (Ptyp) then
10408 return;
10409 end if;
10411 Disc := Entity (Selector_Name (N));
10413 if Is_Derived_Type (Ptyp)
10414 and then Present (Corresponding_Discriminant (Disc))
10415 then
10416 Disc := Corresponding_Discriminant (Disc);
10417 end if;
10419 New_N :=
10420 Make_Selected_Component (Loc,
10421 Prefix =>
10422 Unchecked_Convert_To (Corresponding_Record_Type (Ptyp),
10423 New_Copy_Tree (P)),
10424 Selector_Name => Make_Identifier (Loc, Chars (Disc)));
10426 Rewrite (N, New_N);
10427 Analyze (N);
10428 end if;
10430 -- Set Atomic_Sync_Required if necessary for atomic component
10432 if Nkind (N) = N_Selected_Component then
10433 declare
10434 E : constant Entity_Id := Entity (Selector_Name (N));
10435 Set : Boolean;
10437 begin
10438 -- If component is atomic, but type is not, setting depends on
10439 -- disable/enable state for the component.
10441 if Is_Atomic (E) and then not Is_Atomic (Etype (E)) then
10442 Set := not Atomic_Synchronization_Disabled (E);
10444 -- If component is not atomic, but its type is atomic, setting
10445 -- depends on disable/enable state for the type.
10447 elsif not Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10448 Set := not Atomic_Synchronization_Disabled (Etype (E));
10450 -- If both component and type are atomic, we disable if either
10451 -- component or its type have sync disabled.
10453 elsif Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10454 Set := (not Atomic_Synchronization_Disabled (E))
10455 and then
10456 (not Atomic_Synchronization_Disabled (Etype (E)));
10458 else
10459 Set := False;
10460 end if;
10462 -- Set flag if required
10464 if Set then
10465 Activate_Atomic_Synchronization (N);
10466 end if;
10467 end;
10468 end if;
10469 end Expand_N_Selected_Component;
10471 --------------------
10472 -- Expand_N_Slice --
10473 --------------------
10475 procedure Expand_N_Slice (N : Node_Id) is
10476 Loc : constant Source_Ptr := Sloc (N);
10477 Typ : constant Entity_Id := Etype (N);
10479 function Is_Procedure_Actual (N : Node_Id) return Boolean;
10480 -- Check whether the argument is an actual for a procedure call, in
10481 -- which case the expansion of a bit-packed slice is deferred until the
10482 -- call itself is expanded. The reason this is required is that we might
10483 -- have an IN OUT or OUT parameter, and the copy out is essential, and
10484 -- that copy out would be missed if we created a temporary here in
10485 -- Expand_N_Slice. Note that we don't bother to test specifically for an
10486 -- IN OUT or OUT mode parameter, since it is a bit tricky to do, and it
10487 -- is harmless to defer expansion in the IN case, since the call
10488 -- processing will still generate the appropriate copy in operation,
10489 -- which will take care of the slice.
10491 procedure Make_Temporary_For_Slice;
10492 -- Create a named variable for the value of the slice, in cases where
10493 -- the back end cannot handle it properly, e.g. when packed types or
10494 -- unaligned slices are involved.
10496 -------------------------
10497 -- Is_Procedure_Actual --
10498 -------------------------
10500 function Is_Procedure_Actual (N : Node_Id) return Boolean is
10501 Par : Node_Id := Parent (N);
10503 begin
10504 loop
10505 -- If our parent is a procedure call we can return
10507 if Nkind (Par) = N_Procedure_Call_Statement then
10508 return True;
10510 -- If our parent is a type conversion, keep climbing the tree,
10511 -- since a type conversion can be a procedure actual. Also keep
10512 -- climbing if parameter association or a qualified expression,
10513 -- since these are additional cases that do can appear on
10514 -- procedure actuals.
10516 elsif Nkind_In (Par, N_Type_Conversion,
10517 N_Parameter_Association,
10518 N_Qualified_Expression)
10519 then
10520 Par := Parent (Par);
10522 -- Any other case is not what we are looking for
10524 else
10525 return False;
10526 end if;
10527 end loop;
10528 end Is_Procedure_Actual;
10530 ------------------------------
10531 -- Make_Temporary_For_Slice --
10532 ------------------------------
10534 procedure Make_Temporary_For_Slice is
10535 Ent : constant Entity_Id := Make_Temporary (Loc, 'T', N);
10536 Decl : Node_Id;
10538 begin
10539 Decl :=
10540 Make_Object_Declaration (Loc,
10541 Defining_Identifier => Ent,
10542 Object_Definition => New_Occurrence_Of (Typ, Loc));
10544 Set_No_Initialization (Decl);
10546 Insert_Actions (N, New_List (
10547 Decl,
10548 Make_Assignment_Statement (Loc,
10549 Name => New_Occurrence_Of (Ent, Loc),
10550 Expression => Relocate_Node (N))));
10552 Rewrite (N, New_Occurrence_Of (Ent, Loc));
10553 Analyze_And_Resolve (N, Typ);
10554 end Make_Temporary_For_Slice;
10556 -- Local variables
10558 Pref : constant Node_Id := Prefix (N);
10559 Pref_Typ : Entity_Id := Etype (Pref);
10561 -- Start of processing for Expand_N_Slice
10563 begin
10564 -- Special handling for access types
10566 if Is_Access_Type (Pref_Typ) then
10567 Pref_Typ := Designated_Type (Pref_Typ);
10569 Rewrite (Pref,
10570 Make_Explicit_Dereference (Sloc (N),
10571 Prefix => Relocate_Node (Pref)));
10573 Analyze_And_Resolve (Pref, Pref_Typ);
10574 end if;
10576 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10577 -- function, then additional actuals must be passed.
10579 if Is_Build_In_Place_Function_Call (Pref) then
10580 Make_Build_In_Place_Call_In_Anonymous_Context (Pref);
10582 -- Ada 2005 (AI-318-02): Specialization of the previous case for prefix
10583 -- containing build-in-place function calls whose returned object covers
10584 -- interface types.
10586 elsif Present (Unqual_BIP_Iface_Function_Call (Pref)) then
10587 Make_Build_In_Place_Iface_Call_In_Anonymous_Context (Pref);
10588 end if;
10590 -- The remaining case to be handled is packed slices. We can leave
10591 -- packed slices as they are in the following situations:
10593 -- 1. Right or left side of an assignment (we can handle this
10594 -- situation correctly in the assignment statement expansion).
10596 -- 2. Prefix of indexed component (the slide is optimized away in this
10597 -- case, see the start of Expand_N_Slice.)
10599 -- 3. Object renaming declaration, since we want the name of the
10600 -- slice, not the value.
10602 -- 4. Argument to procedure call, since copy-in/copy-out handling may
10603 -- be required, and this is handled in the expansion of call
10604 -- itself.
10606 -- 5. Prefix of an address attribute (this is an error which is caught
10607 -- elsewhere, and the expansion would interfere with generating the
10608 -- error message).
10610 if not Is_Packed (Typ) then
10612 -- Apply transformation for actuals of a function call, where
10613 -- Expand_Actuals is not used.
10615 if Nkind (Parent (N)) = N_Function_Call
10616 and then Is_Possibly_Unaligned_Slice (N)
10617 then
10618 Make_Temporary_For_Slice;
10619 end if;
10621 elsif Nkind (Parent (N)) = N_Assignment_Statement
10622 or else (Nkind (Parent (Parent (N))) = N_Assignment_Statement
10623 and then Parent (N) = Name (Parent (Parent (N))))
10624 then
10625 return;
10627 elsif Nkind (Parent (N)) = N_Indexed_Component
10628 or else Is_Renamed_Object (N)
10629 or else Is_Procedure_Actual (N)
10630 then
10631 return;
10633 elsif Nkind (Parent (N)) = N_Attribute_Reference
10634 and then Attribute_Name (Parent (N)) = Name_Address
10635 then
10636 return;
10638 else
10639 Make_Temporary_For_Slice;
10640 end if;
10641 end Expand_N_Slice;
10643 ------------------------------
10644 -- Expand_N_Type_Conversion --
10645 ------------------------------
10647 procedure Expand_N_Type_Conversion (N : Node_Id) is
10648 Loc : constant Source_Ptr := Sloc (N);
10649 Operand : constant Node_Id := Expression (N);
10650 Target_Type : constant Entity_Id := Etype (N);
10651 Operand_Type : Entity_Id := Etype (Operand);
10653 procedure Handle_Changed_Representation;
10654 -- This is called in the case of record and array type conversions to
10655 -- see if there is a change of representation to be handled. Change of
10656 -- representation is actually handled at the assignment statement level,
10657 -- and what this procedure does is rewrite node N conversion as an
10658 -- assignment to temporary. If there is no change of representation,
10659 -- then the conversion node is unchanged.
10661 procedure Raise_Accessibility_Error;
10662 -- Called when we know that an accessibility check will fail. Rewrites
10663 -- node N to an appropriate raise statement and outputs warning msgs.
10664 -- The Etype of the raise node is set to Target_Type. Note that in this
10665 -- case the rest of the processing should be skipped (i.e. the call to
10666 -- this procedure will be followed by "goto Done").
10668 procedure Real_Range_Check;
10669 -- Handles generation of range check for real target value
10671 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean;
10672 -- True iff Present (Effective_Extra_Accessibility (Id)) successfully
10673 -- evaluates to True.
10675 -----------------------------------
10676 -- Handle_Changed_Representation --
10677 -----------------------------------
10679 procedure Handle_Changed_Representation is
10680 Temp : Entity_Id;
10681 Decl : Node_Id;
10682 Odef : Node_Id;
10683 N_Ix : Node_Id;
10684 Cons : List_Id;
10686 begin
10687 -- Nothing else to do if no change of representation
10689 if Same_Representation (Operand_Type, Target_Type) then
10690 return;
10692 -- The real change of representation work is done by the assignment
10693 -- statement processing. So if this type conversion is appearing as
10694 -- the expression of an assignment statement, nothing needs to be
10695 -- done to the conversion.
10697 elsif Nkind (Parent (N)) = N_Assignment_Statement then
10698 return;
10700 -- Otherwise we need to generate a temporary variable, and do the
10701 -- change of representation assignment into that temporary variable.
10702 -- The conversion is then replaced by a reference to this variable.
10704 else
10705 Cons := No_List;
10707 -- If type is unconstrained we have to add a constraint, copied
10708 -- from the actual value of the left-hand side.
10710 if not Is_Constrained (Target_Type) then
10711 if Has_Discriminants (Operand_Type) then
10713 -- A change of representation can only apply to untagged
10714 -- types. We need to build the constraint that applies to
10715 -- the target type, using the constraints of the operand.
10716 -- The analysis is complicated if there are both inherited
10717 -- discriminants and constrained discriminants.
10718 -- We iterate over the discriminants of the target, and
10719 -- find the discriminant of the same name:
10721 -- a) If there is a corresponding discriminant in the object
10722 -- then the value is a selected component of the operand.
10724 -- b) Otherwise the value of a constrained discriminant is
10725 -- found in the stored constraint of the operand.
10727 declare
10728 Stored : constant Elist_Id :=
10729 Stored_Constraint (Operand_Type);
10731 Elmt : Elmt_Id;
10733 Disc_O : Entity_Id;
10734 -- Discriminant of the operand type. Its value in the
10735 -- object is captured in a selected component.
10737 Disc_S : Entity_Id;
10738 -- Stored discriminant of the operand. If present, it
10739 -- corresponds to a constrained discriminant of the
10740 -- parent type.
10742 Disc_T : Entity_Id;
10743 -- Discriminant of the target type
10745 begin
10746 Disc_T := First_Discriminant (Target_Type);
10747 Disc_O := First_Discriminant (Operand_Type);
10748 Disc_S := First_Stored_Discriminant (Operand_Type);
10750 if Present (Stored) then
10751 Elmt := First_Elmt (Stored);
10752 else
10753 Elmt := No_Elmt; -- init to avoid warning
10754 end if;
10756 Cons := New_List;
10757 while Present (Disc_T) loop
10758 if Present (Disc_O)
10759 and then Chars (Disc_T) = Chars (Disc_O)
10760 then
10761 Append_To (Cons,
10762 Make_Selected_Component (Loc,
10763 Prefix =>
10764 Duplicate_Subexpr_Move_Checks (Operand),
10765 Selector_Name =>
10766 Make_Identifier (Loc, Chars (Disc_O))));
10767 Next_Discriminant (Disc_O);
10769 elsif Present (Disc_S) then
10770 Append_To (Cons, New_Copy_Tree (Node (Elmt)));
10771 Next_Elmt (Elmt);
10772 end if;
10774 Next_Discriminant (Disc_T);
10775 end loop;
10776 end;
10778 elsif Is_Array_Type (Operand_Type) then
10779 N_Ix := First_Index (Target_Type);
10780 Cons := New_List;
10782 for J in 1 .. Number_Dimensions (Operand_Type) loop
10784 -- We convert the bounds explicitly. We use an unchecked
10785 -- conversion because bounds checks are done elsewhere.
10787 Append_To (Cons,
10788 Make_Range (Loc,
10789 Low_Bound =>
10790 Unchecked_Convert_To (Etype (N_Ix),
10791 Make_Attribute_Reference (Loc,
10792 Prefix =>
10793 Duplicate_Subexpr_No_Checks
10794 (Operand, Name_Req => True),
10795 Attribute_Name => Name_First,
10796 Expressions => New_List (
10797 Make_Integer_Literal (Loc, J)))),
10799 High_Bound =>
10800 Unchecked_Convert_To (Etype (N_Ix),
10801 Make_Attribute_Reference (Loc,
10802 Prefix =>
10803 Duplicate_Subexpr_No_Checks
10804 (Operand, Name_Req => True),
10805 Attribute_Name => Name_Last,
10806 Expressions => New_List (
10807 Make_Integer_Literal (Loc, J))))));
10809 Next_Index (N_Ix);
10810 end loop;
10811 end if;
10812 end if;
10814 Odef := New_Occurrence_Of (Target_Type, Loc);
10816 if Present (Cons) then
10817 Odef :=
10818 Make_Subtype_Indication (Loc,
10819 Subtype_Mark => Odef,
10820 Constraint =>
10821 Make_Index_Or_Discriminant_Constraint (Loc,
10822 Constraints => Cons));
10823 end if;
10825 Temp := Make_Temporary (Loc, 'C');
10826 Decl :=
10827 Make_Object_Declaration (Loc,
10828 Defining_Identifier => Temp,
10829 Object_Definition => Odef);
10831 Set_No_Initialization (Decl, True);
10833 -- Insert required actions. It is essential to suppress checks
10834 -- since we have suppressed default initialization, which means
10835 -- that the variable we create may have no discriminants.
10837 Insert_Actions (N,
10838 New_List (
10839 Decl,
10840 Make_Assignment_Statement (Loc,
10841 Name => New_Occurrence_Of (Temp, Loc),
10842 Expression => Relocate_Node (N))),
10843 Suppress => All_Checks);
10845 Rewrite (N, New_Occurrence_Of (Temp, Loc));
10846 return;
10847 end if;
10848 end Handle_Changed_Representation;
10850 -------------------------------
10851 -- Raise_Accessibility_Error --
10852 -------------------------------
10854 procedure Raise_Accessibility_Error is
10855 begin
10856 Error_Msg_Warn := SPARK_Mode /= On;
10857 Rewrite (N,
10858 Make_Raise_Program_Error (Sloc (N),
10859 Reason => PE_Accessibility_Check_Failed));
10860 Set_Etype (N, Target_Type);
10862 Error_Msg_N ("<<accessibility check failure", N);
10863 Error_Msg_NE ("\<<& [", N, Standard_Program_Error);
10864 end Raise_Accessibility_Error;
10866 ----------------------
10867 -- Real_Range_Check --
10868 ----------------------
10870 -- Case of conversions to floating-point or fixed-point. If range checks
10871 -- are enabled and the target type has a range constraint, we convert:
10873 -- typ (x)
10875 -- to
10877 -- Tnn : typ'Base := typ'Base (x);
10878 -- [constraint_error when Tnn < typ'First or else Tnn > typ'Last]
10879 -- Tnn
10881 -- This is necessary when there is a conversion of integer to float or
10882 -- to fixed-point to ensure that the correct checks are made. It is not
10883 -- necessary for float to float where it is enough to simply set the
10884 -- Do_Range_Check flag.
10886 procedure Real_Range_Check is
10887 Btyp : constant Entity_Id := Base_Type (Target_Type);
10888 Lo : constant Node_Id := Type_Low_Bound (Target_Type);
10889 Hi : constant Node_Id := Type_High_Bound (Target_Type);
10890 Xtyp : constant Entity_Id := Etype (Operand);
10891 Conv : Node_Id;
10892 Tnn : Entity_Id;
10894 begin
10895 -- Nothing to do if conversion was rewritten
10897 if Nkind (N) /= N_Type_Conversion then
10898 return;
10899 end if;
10901 -- Nothing to do if range checks suppressed, or target has the same
10902 -- range as the base type (or is the base type).
10904 if Range_Checks_Suppressed (Target_Type)
10905 or else (Lo = Type_Low_Bound (Btyp)
10906 and then
10907 Hi = Type_High_Bound (Btyp))
10908 then
10909 return;
10910 end if;
10912 -- Nothing to do if expression is an entity on which checks have been
10913 -- suppressed.
10915 if Is_Entity_Name (Operand)
10916 and then Range_Checks_Suppressed (Entity (Operand))
10917 then
10918 return;
10919 end if;
10921 -- Nothing to do if bounds are all static and we can tell that the
10922 -- expression is within the bounds of the target. Note that if the
10923 -- operand is of an unconstrained floating-point type, then we do
10924 -- not trust it to be in range (might be infinite)
10926 declare
10927 S_Lo : constant Node_Id := Type_Low_Bound (Xtyp);
10928 S_Hi : constant Node_Id := Type_High_Bound (Xtyp);
10930 begin
10931 if (not Is_Floating_Point_Type (Xtyp)
10932 or else Is_Constrained (Xtyp))
10933 and then Compile_Time_Known_Value (S_Lo)
10934 and then Compile_Time_Known_Value (S_Hi)
10935 and then Compile_Time_Known_Value (Hi)
10936 and then Compile_Time_Known_Value (Lo)
10937 then
10938 declare
10939 D_Lov : constant Ureal := Expr_Value_R (Lo);
10940 D_Hiv : constant Ureal := Expr_Value_R (Hi);
10941 S_Lov : Ureal;
10942 S_Hiv : Ureal;
10944 begin
10945 if Is_Real_Type (Xtyp) then
10946 S_Lov := Expr_Value_R (S_Lo);
10947 S_Hiv := Expr_Value_R (S_Hi);
10948 else
10949 S_Lov := UR_From_Uint (Expr_Value (S_Lo));
10950 S_Hiv := UR_From_Uint (Expr_Value (S_Hi));
10951 end if;
10953 if D_Hiv > D_Lov
10954 and then S_Lov >= D_Lov
10955 and then S_Hiv <= D_Hiv
10956 then
10957 -- Unset the range check flag on the current value of
10958 -- Expression (N), since the captured Operand may have
10959 -- been rewritten (such as for the case of a conversion
10960 -- to a fixed-point type).
10962 Set_Do_Range_Check (Expression (N), False);
10964 return;
10965 end if;
10966 end;
10967 end if;
10968 end;
10970 -- For float to float conversions, we are done
10972 if Is_Floating_Point_Type (Xtyp)
10973 and then
10974 Is_Floating_Point_Type (Btyp)
10975 then
10976 return;
10977 end if;
10979 -- Otherwise rewrite the conversion as described above
10981 Conv := Relocate_Node (N);
10982 Rewrite (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
10983 Set_Etype (Conv, Btyp);
10985 -- Enable overflow except for case of integer to float conversions,
10986 -- where it is never required, since we can never have overflow in
10987 -- this case.
10989 if not Is_Integer_Type (Etype (Operand)) then
10990 Enable_Overflow_Check (Conv);
10991 end if;
10993 Tnn := Make_Temporary (Loc, 'T', Conv);
10995 Insert_Actions (N, New_List (
10996 Make_Object_Declaration (Loc,
10997 Defining_Identifier => Tnn,
10998 Object_Definition => New_Occurrence_Of (Btyp, Loc),
10999 Constant_Present => True,
11000 Expression => Conv),
11002 Make_Raise_Constraint_Error (Loc,
11003 Condition =>
11004 Make_Or_Else (Loc,
11005 Left_Opnd =>
11006 Make_Op_Lt (Loc,
11007 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
11008 Right_Opnd =>
11009 Make_Attribute_Reference (Loc,
11010 Attribute_Name => Name_First,
11011 Prefix =>
11012 New_Occurrence_Of (Target_Type, Loc))),
11014 Right_Opnd =>
11015 Make_Op_Gt (Loc,
11016 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
11017 Right_Opnd =>
11018 Make_Attribute_Reference (Loc,
11019 Attribute_Name => Name_Last,
11020 Prefix =>
11021 New_Occurrence_Of (Target_Type, Loc)))),
11022 Reason => CE_Range_Check_Failed)));
11024 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
11025 Analyze_And_Resolve (N, Btyp);
11026 end Real_Range_Check;
11028 -----------------------------
11029 -- Has_Extra_Accessibility --
11030 -----------------------------
11032 -- Returns true for a formal of an anonymous access type or for
11033 -- an Ada 2012-style stand-alone object of an anonymous access type.
11035 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean is
11036 begin
11037 if Is_Formal (Id) or else Ekind_In (Id, E_Constant, E_Variable) then
11038 return Present (Effective_Extra_Accessibility (Id));
11039 else
11040 return False;
11041 end if;
11042 end Has_Extra_Accessibility;
11044 -- Start of processing for Expand_N_Type_Conversion
11046 begin
11047 -- First remove check marks put by the semantic analysis on the type
11048 -- conversion between array types. We need these checks, and they will
11049 -- be generated by this expansion routine, but we do not depend on these
11050 -- flags being set, and since we do intend to expand the checks in the
11051 -- front end, we don't want them on the tree passed to the back end.
11053 if Is_Array_Type (Target_Type) then
11054 if Is_Constrained (Target_Type) then
11055 Set_Do_Length_Check (N, False);
11056 else
11057 Set_Do_Range_Check (Operand, False);
11058 end if;
11059 end if;
11061 -- Nothing at all to do if conversion is to the identical type so remove
11062 -- the conversion completely, it is useless, except that it may carry
11063 -- an Assignment_OK attribute, which must be propagated to the operand.
11065 if Operand_Type = Target_Type then
11066 if Assignment_OK (N) then
11067 Set_Assignment_OK (Operand);
11068 end if;
11070 Rewrite (N, Relocate_Node (Operand));
11071 goto Done;
11072 end if;
11074 -- Nothing to do if this is the second argument of read. This is a
11075 -- "backwards" conversion that will be handled by the specialized code
11076 -- in attribute processing.
11078 if Nkind (Parent (N)) = N_Attribute_Reference
11079 and then Attribute_Name (Parent (N)) = Name_Read
11080 and then Next (First (Expressions (Parent (N)))) = N
11081 then
11082 goto Done;
11083 end if;
11085 -- Check for case of converting to a type that has an invariant
11086 -- associated with it. This requires an invariant check. We insert
11087 -- a call:
11089 -- invariant_check (typ (expr))
11091 -- in the code, after removing side effects from the expression.
11092 -- This is clearer than replacing the conversion into an expression
11093 -- with actions, because the context may impose additional actions
11094 -- (tag checks, membership tests, etc.) that conflict with this
11095 -- rewriting (used previously).
11097 -- Note: the Comes_From_Source check, and then the resetting of this
11098 -- flag prevents what would otherwise be an infinite recursion.
11100 if Has_Invariants (Target_Type)
11101 and then Present (Invariant_Procedure (Target_Type))
11102 and then Comes_From_Source (N)
11103 then
11104 Set_Comes_From_Source (N, False);
11105 Remove_Side_Effects (N);
11106 Insert_Action (N, Make_Invariant_Call (Duplicate_Subexpr (N)));
11107 goto Done;
11108 end if;
11110 -- Here if we may need to expand conversion
11112 -- If the operand of the type conversion is an arithmetic operation on
11113 -- signed integers, and the based type of the signed integer type in
11114 -- question is smaller than Standard.Integer, we promote both of the
11115 -- operands to type Integer.
11117 -- For example, if we have
11119 -- target-type (opnd1 + opnd2)
11121 -- and opnd1 and opnd2 are of type short integer, then we rewrite
11122 -- this as:
11124 -- target-type (integer(opnd1) + integer(opnd2))
11126 -- We do this because we are always allowed to compute in a larger type
11127 -- if we do the right thing with the result, and in this case we are
11128 -- going to do a conversion which will do an appropriate check to make
11129 -- sure that things are in range of the target type in any case. This
11130 -- avoids some unnecessary intermediate overflows.
11132 -- We might consider a similar transformation in the case where the
11133 -- target is a real type or a 64-bit integer type, and the operand
11134 -- is an arithmetic operation using a 32-bit integer type. However,
11135 -- we do not bother with this case, because it could cause significant
11136 -- inefficiencies on 32-bit machines. On a 64-bit machine it would be
11137 -- much cheaper, but we don't want different behavior on 32-bit and
11138 -- 64-bit machines. Note that the exclusion of the 64-bit case also
11139 -- handles the configurable run-time cases where 64-bit arithmetic
11140 -- may simply be unavailable.
11142 -- Note: this circuit is partially redundant with respect to the circuit
11143 -- in Checks.Apply_Arithmetic_Overflow_Check, but we catch more cases in
11144 -- the processing here. Also we still need the Checks circuit, since we
11145 -- have to be sure not to generate junk overflow checks in the first
11146 -- place, since it would be trick to remove them here.
11148 if Integer_Promotion_Possible (N) then
11150 -- All conditions met, go ahead with transformation
11152 declare
11153 Opnd : Node_Id;
11154 L, R : Node_Id;
11156 begin
11157 R :=
11158 Make_Type_Conversion (Loc,
11159 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11160 Expression => Relocate_Node (Right_Opnd (Operand)));
11162 Opnd := New_Op_Node (Nkind (Operand), Loc);
11163 Set_Right_Opnd (Opnd, R);
11165 if Nkind (Operand) in N_Binary_Op then
11166 L :=
11167 Make_Type_Conversion (Loc,
11168 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11169 Expression => Relocate_Node (Left_Opnd (Operand)));
11171 Set_Left_Opnd (Opnd, L);
11172 end if;
11174 Rewrite (N,
11175 Make_Type_Conversion (Loc,
11176 Subtype_Mark => Relocate_Node (Subtype_Mark (N)),
11177 Expression => Opnd));
11179 Analyze_And_Resolve (N, Target_Type);
11180 goto Done;
11181 end;
11182 end if;
11184 -- Do validity check if validity checking operands
11186 if Validity_Checks_On and Validity_Check_Operands then
11187 Ensure_Valid (Operand);
11188 end if;
11190 -- Special case of converting from non-standard boolean type
11192 if Is_Boolean_Type (Operand_Type)
11193 and then (Nonzero_Is_True (Operand_Type))
11194 then
11195 Adjust_Condition (Operand);
11196 Set_Etype (Operand, Standard_Boolean);
11197 Operand_Type := Standard_Boolean;
11198 end if;
11200 -- Case of converting to an access type
11202 if Is_Access_Type (Target_Type) then
11204 -- If this type conversion was internally generated by the front end
11205 -- to displace the pointer to the object to reference an interface
11206 -- type and the original node was an Unrestricted_Access attribute,
11207 -- then skip applying accessibility checks (because, according to the
11208 -- GNAT Reference Manual, this attribute is similar to 'Access except
11209 -- that all accessibility and aliased view checks are omitted).
11211 if not Comes_From_Source (N)
11212 and then Is_Interface (Designated_Type (Target_Type))
11213 and then Nkind (Original_Node (N)) = N_Attribute_Reference
11214 and then Attribute_Name (Original_Node (N)) =
11215 Name_Unrestricted_Access
11216 then
11217 null;
11219 -- Apply an accessibility check when the conversion operand is an
11220 -- access parameter (or a renaming thereof), unless conversion was
11221 -- expanded from an Unchecked_ or Unrestricted_Access attribute,
11222 -- or for the actual of a class-wide interface parameter. Note that
11223 -- other checks may still need to be applied below (such as tagged
11224 -- type checks).
11226 elsif Is_Entity_Name (Operand)
11227 and then Has_Extra_Accessibility (Entity (Operand))
11228 and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
11229 and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
11230 or else Attribute_Name (Original_Node (N)) = Name_Access)
11231 then
11232 if not Comes_From_Source (N)
11233 and then Nkind_In (Parent (N), N_Function_Call,
11234 N_Procedure_Call_Statement)
11235 and then Is_Interface (Designated_Type (Target_Type))
11236 and then Is_Class_Wide_Type (Designated_Type (Target_Type))
11237 then
11238 null;
11240 else
11241 Apply_Accessibility_Check
11242 (Operand, Target_Type, Insert_Node => Operand);
11243 end if;
11245 -- If the level of the operand type is statically deeper than the
11246 -- level of the target type, then force Program_Error. Note that this
11247 -- can only occur for cases where the attribute is within the body of
11248 -- an instantiation, otherwise the conversion will already have been
11249 -- rejected as illegal.
11251 -- Note: warnings are issued by the analyzer for the instance cases
11253 elsif In_Instance_Body
11255 -- The case where the target type is an anonymous access type of
11256 -- a discriminant is excluded, because the level of such a type
11257 -- depends on the context and currently the level returned for such
11258 -- types is zero, resulting in warnings about about check failures
11259 -- in certain legal cases involving class-wide interfaces as the
11260 -- designated type (some cases, such as return statements, are
11261 -- checked at run time, but not clear if these are handled right
11262 -- in general, see 3.10.2(12/2-12.5/3) ???).
11264 and then
11265 not (Ekind (Target_Type) = E_Anonymous_Access_Type
11266 and then Present (Associated_Node_For_Itype (Target_Type))
11267 and then Nkind (Associated_Node_For_Itype (Target_Type)) =
11268 N_Discriminant_Specification)
11269 and then
11270 Type_Access_Level (Operand_Type) > Type_Access_Level (Target_Type)
11271 then
11272 Raise_Accessibility_Error;
11273 goto Done;
11275 -- When the operand is a selected access discriminant the check needs
11276 -- to be made against the level of the object denoted by the prefix
11277 -- of the selected name. Force Program_Error for this case as well
11278 -- (this accessibility violation can only happen if within the body
11279 -- of an instantiation).
11281 elsif In_Instance_Body
11282 and then Ekind (Operand_Type) = E_Anonymous_Access_Type
11283 and then Nkind (Operand) = N_Selected_Component
11284 and then Ekind (Entity (Selector_Name (Operand))) = E_Discriminant
11285 and then Object_Access_Level (Operand) >
11286 Type_Access_Level (Target_Type)
11287 then
11288 Raise_Accessibility_Error;
11289 goto Done;
11290 end if;
11291 end if;
11293 -- Case of conversions of tagged types and access to tagged types
11295 -- When needed, that is to say when the expression is class-wide, Add
11296 -- runtime a tag check for (strict) downward conversion by using the
11297 -- membership test, generating:
11299 -- [constraint_error when Operand not in Target_Type'Class]
11301 -- or in the access type case
11303 -- [constraint_error
11304 -- when Operand /= null
11305 -- and then Operand.all not in
11306 -- Designated_Type (Target_Type)'Class]
11308 if (Is_Access_Type (Target_Type)
11309 and then Is_Tagged_Type (Designated_Type (Target_Type)))
11310 or else Is_Tagged_Type (Target_Type)
11311 then
11312 -- Do not do any expansion in the access type case if the parent is a
11313 -- renaming, since this is an error situation which will be caught by
11314 -- Sem_Ch8, and the expansion can interfere with this error check.
11316 if Is_Access_Type (Target_Type) and then Is_Renamed_Object (N) then
11317 goto Done;
11318 end if;
11320 -- Otherwise, proceed with processing tagged conversion
11322 Tagged_Conversion : declare
11323 Actual_Op_Typ : Entity_Id;
11324 Actual_Targ_Typ : Entity_Id;
11325 Make_Conversion : Boolean := False;
11326 Root_Op_Typ : Entity_Id;
11328 procedure Make_Tag_Check (Targ_Typ : Entity_Id);
11329 -- Create a membership check to test whether Operand is a member
11330 -- of Targ_Typ. If the original Target_Type is an access, include
11331 -- a test for null value. The check is inserted at N.
11333 --------------------
11334 -- Make_Tag_Check --
11335 --------------------
11337 procedure Make_Tag_Check (Targ_Typ : Entity_Id) is
11338 Cond : Node_Id;
11340 begin
11341 -- Generate:
11342 -- [Constraint_Error
11343 -- when Operand /= null
11344 -- and then Operand.all not in Targ_Typ]
11346 if Is_Access_Type (Target_Type) then
11347 Cond :=
11348 Make_And_Then (Loc,
11349 Left_Opnd =>
11350 Make_Op_Ne (Loc,
11351 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11352 Right_Opnd => Make_Null (Loc)),
11354 Right_Opnd =>
11355 Make_Not_In (Loc,
11356 Left_Opnd =>
11357 Make_Explicit_Dereference (Loc,
11358 Prefix => Duplicate_Subexpr_No_Checks (Operand)),
11359 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc)));
11361 -- Generate:
11362 -- [Constraint_Error when Operand not in Targ_Typ]
11364 else
11365 Cond :=
11366 Make_Not_In (Loc,
11367 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11368 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc));
11369 end if;
11371 Insert_Action (N,
11372 Make_Raise_Constraint_Error (Loc,
11373 Condition => Cond,
11374 Reason => CE_Tag_Check_Failed),
11375 Suppress => All_Checks);
11376 end Make_Tag_Check;
11378 -- Start of processing for Tagged_Conversion
11380 begin
11381 -- Handle entities from the limited view
11383 if Is_Access_Type (Operand_Type) then
11384 Actual_Op_Typ :=
11385 Available_View (Designated_Type (Operand_Type));
11386 else
11387 Actual_Op_Typ := Operand_Type;
11388 end if;
11390 if Is_Access_Type (Target_Type) then
11391 Actual_Targ_Typ :=
11392 Available_View (Designated_Type (Target_Type));
11393 else
11394 Actual_Targ_Typ := Target_Type;
11395 end if;
11397 Root_Op_Typ := Root_Type (Actual_Op_Typ);
11399 -- Ada 2005 (AI-251): Handle interface type conversion
11401 if Is_Interface (Actual_Op_Typ)
11402 or else
11403 Is_Interface (Actual_Targ_Typ)
11404 then
11405 Expand_Interface_Conversion (N);
11406 goto Done;
11407 end if;
11409 if not Tag_Checks_Suppressed (Actual_Targ_Typ) then
11411 -- Create a runtime tag check for a downward class-wide type
11412 -- conversion.
11414 if Is_Class_Wide_Type (Actual_Op_Typ)
11415 and then Actual_Op_Typ /= Actual_Targ_Typ
11416 and then Root_Op_Typ /= Actual_Targ_Typ
11417 and then Is_Ancestor (Root_Op_Typ, Actual_Targ_Typ,
11418 Use_Full_View => True)
11419 then
11420 Make_Tag_Check (Class_Wide_Type (Actual_Targ_Typ));
11421 Make_Conversion := True;
11422 end if;
11424 -- AI05-0073: If the result subtype of the function is defined
11425 -- by an access_definition designating a specific tagged type
11426 -- T, a check is made that the result value is null or the tag
11427 -- of the object designated by the result value identifies T.
11428 -- Constraint_Error is raised if this check fails.
11430 if Nkind (Parent (N)) = N_Simple_Return_Statement then
11431 declare
11432 Func : Entity_Id;
11433 Func_Typ : Entity_Id;
11435 begin
11436 -- Climb scope stack looking for the enclosing function
11438 Func := Current_Scope;
11439 while Present (Func)
11440 and then Ekind (Func) /= E_Function
11441 loop
11442 Func := Scope (Func);
11443 end loop;
11445 -- The function's return subtype must be defined using
11446 -- an access definition.
11448 if Nkind (Result_Definition (Parent (Func))) =
11449 N_Access_Definition
11450 then
11451 Func_Typ := Directly_Designated_Type (Etype (Func));
11453 -- The return subtype denotes a specific tagged type,
11454 -- in other words, a non class-wide type.
11456 if Is_Tagged_Type (Func_Typ)
11457 and then not Is_Class_Wide_Type (Func_Typ)
11458 then
11459 Make_Tag_Check (Actual_Targ_Typ);
11460 Make_Conversion := True;
11461 end if;
11462 end if;
11463 end;
11464 end if;
11466 -- We have generated a tag check for either a class-wide type
11467 -- conversion or for AI05-0073.
11469 if Make_Conversion then
11470 declare
11471 Conv : Node_Id;
11472 begin
11473 Conv :=
11474 Make_Unchecked_Type_Conversion (Loc,
11475 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
11476 Expression => Relocate_Node (Expression (N)));
11477 Rewrite (N, Conv);
11478 Analyze_And_Resolve (N, Target_Type);
11479 end;
11480 end if;
11481 end if;
11482 end Tagged_Conversion;
11484 -- Case of other access type conversions
11486 elsif Is_Access_Type (Target_Type) then
11487 Apply_Constraint_Check (Operand, Target_Type);
11489 -- Case of conversions from a fixed-point type
11491 -- These conversions require special expansion and processing, found in
11492 -- the Exp_Fixd package. We ignore cases where Conversion_OK is set,
11493 -- since from a semantic point of view, these are simple integer
11494 -- conversions, which do not need further processing.
11496 elsif Is_Fixed_Point_Type (Operand_Type)
11497 and then not Conversion_OK (N)
11498 then
11499 -- We should never see universal fixed at this case, since the
11500 -- expansion of the constituent divide or multiply should have
11501 -- eliminated the explicit mention of universal fixed.
11503 pragma Assert (Operand_Type /= Universal_Fixed);
11505 -- Check for special case of the conversion to universal real that
11506 -- occurs as a result of the use of a round attribute. In this case,
11507 -- the real type for the conversion is taken from the target type of
11508 -- the Round attribute and the result must be marked as rounded.
11510 if Target_Type = Universal_Real
11511 and then Nkind (Parent (N)) = N_Attribute_Reference
11512 and then Attribute_Name (Parent (N)) = Name_Round
11513 then
11514 Set_Rounded_Result (N);
11515 Set_Etype (N, Etype (Parent (N)));
11516 end if;
11518 -- Otherwise do correct fixed-conversion, but skip these if the
11519 -- Conversion_OK flag is set, because from a semantic point of view
11520 -- these are simple integer conversions needing no further processing
11521 -- (the backend will simply treat them as integers).
11523 if not Conversion_OK (N) then
11524 if Is_Fixed_Point_Type (Etype (N)) then
11525 Expand_Convert_Fixed_To_Fixed (N);
11526 Real_Range_Check;
11528 elsif Is_Integer_Type (Etype (N)) then
11529 Expand_Convert_Fixed_To_Integer (N);
11531 else
11532 pragma Assert (Is_Floating_Point_Type (Etype (N)));
11533 Expand_Convert_Fixed_To_Float (N);
11534 Real_Range_Check;
11535 end if;
11536 end if;
11538 -- Case of conversions to a fixed-point type
11540 -- These conversions require special expansion and processing, found in
11541 -- the Exp_Fixd package. Again, ignore cases where Conversion_OK is set,
11542 -- since from a semantic point of view, these are simple integer
11543 -- conversions, which do not need further processing.
11545 elsif Is_Fixed_Point_Type (Target_Type)
11546 and then not Conversion_OK (N)
11547 then
11548 if Is_Integer_Type (Operand_Type) then
11549 Expand_Convert_Integer_To_Fixed (N);
11550 Real_Range_Check;
11551 else
11552 pragma Assert (Is_Floating_Point_Type (Operand_Type));
11553 Expand_Convert_Float_To_Fixed (N);
11554 Real_Range_Check;
11555 end if;
11557 -- Case of float-to-integer conversions
11559 -- We also handle float-to-fixed conversions with Conversion_OK set
11560 -- since semantically the fixed-point target is treated as though it
11561 -- were an integer in such cases.
11563 elsif Is_Floating_Point_Type (Operand_Type)
11564 and then
11565 (Is_Integer_Type (Target_Type)
11566 or else
11567 (Is_Fixed_Point_Type (Target_Type) and then Conversion_OK (N)))
11568 then
11569 -- One more check here, gcc is still not able to do conversions of
11570 -- this type with proper overflow checking, and so gigi is doing an
11571 -- approximation of what is required by doing floating-point compares
11572 -- with the end-point. But that can lose precision in some cases, and
11573 -- give a wrong result. Converting the operand to Universal_Real is
11574 -- helpful, but still does not catch all cases with 64-bit integers
11575 -- on targets with only 64-bit floats.
11577 -- The above comment seems obsoleted by Apply_Float_Conversion_Check
11578 -- Can this code be removed ???
11580 if Do_Range_Check (Operand) then
11581 Rewrite (Operand,
11582 Make_Type_Conversion (Loc,
11583 Subtype_Mark =>
11584 New_Occurrence_Of (Universal_Real, Loc),
11585 Expression =>
11586 Relocate_Node (Operand)));
11588 Set_Etype (Operand, Universal_Real);
11589 Enable_Range_Check (Operand);
11590 Set_Do_Range_Check (Expression (Operand), False);
11591 end if;
11593 -- Case of array conversions
11595 -- Expansion of array conversions, add required length/range checks but
11596 -- only do this if there is no change of representation. For handling of
11597 -- this case, see Handle_Changed_Representation.
11599 elsif Is_Array_Type (Target_Type) then
11600 if Is_Constrained (Target_Type) then
11601 Apply_Length_Check (Operand, Target_Type);
11602 else
11603 Apply_Range_Check (Operand, Target_Type);
11604 end if;
11606 Handle_Changed_Representation;
11608 -- Case of conversions of discriminated types
11610 -- Add required discriminant checks if target is constrained. Again this
11611 -- change is skipped if we have a change of representation.
11613 elsif Has_Discriminants (Target_Type)
11614 and then Is_Constrained (Target_Type)
11615 then
11616 Apply_Discriminant_Check (Operand, Target_Type);
11617 Handle_Changed_Representation;
11619 -- Case of all other record conversions. The only processing required
11620 -- is to check for a change of representation requiring the special
11621 -- assignment processing.
11623 elsif Is_Record_Type (Target_Type) then
11625 -- Ada 2005 (AI-216): Program_Error is raised when converting from
11626 -- a derived Unchecked_Union type to an unconstrained type that is
11627 -- not Unchecked_Union if the operand lacks inferable discriminants.
11629 if Is_Derived_Type (Operand_Type)
11630 and then Is_Unchecked_Union (Base_Type (Operand_Type))
11631 and then not Is_Constrained (Target_Type)
11632 and then not Is_Unchecked_Union (Base_Type (Target_Type))
11633 and then not Has_Inferable_Discriminants (Operand)
11634 then
11635 -- To prevent Gigi from generating illegal code, we generate a
11636 -- Program_Error node, but we give it the target type of the
11637 -- conversion (is this requirement documented somewhere ???)
11639 declare
11640 PE : constant Node_Id := Make_Raise_Program_Error (Loc,
11641 Reason => PE_Unchecked_Union_Restriction);
11643 begin
11644 Set_Etype (PE, Target_Type);
11645 Rewrite (N, PE);
11647 end;
11648 else
11649 Handle_Changed_Representation;
11650 end if;
11652 -- Case of conversions of enumeration types
11654 elsif Is_Enumeration_Type (Target_Type) then
11656 -- Special processing is required if there is a change of
11657 -- representation (from enumeration representation clauses).
11659 if not Same_Representation (Target_Type, Operand_Type) then
11661 -- Convert: x(y) to x'val (ytyp'val (y))
11663 Rewrite (N,
11664 Make_Attribute_Reference (Loc,
11665 Prefix => New_Occurrence_Of (Target_Type, Loc),
11666 Attribute_Name => Name_Val,
11667 Expressions => New_List (
11668 Make_Attribute_Reference (Loc,
11669 Prefix => New_Occurrence_Of (Operand_Type, Loc),
11670 Attribute_Name => Name_Pos,
11671 Expressions => New_List (Operand)))));
11673 Analyze_And_Resolve (N, Target_Type);
11674 end if;
11676 -- Case of conversions to floating-point
11678 elsif Is_Floating_Point_Type (Target_Type) then
11679 Real_Range_Check;
11680 end if;
11682 -- At this stage, either the conversion node has been transformed into
11683 -- some other equivalent expression, or left as a conversion that can be
11684 -- handled by Gigi, in the following cases:
11686 -- Conversions with no change of representation or type
11688 -- Numeric conversions involving integer, floating- and fixed-point
11689 -- values. Fixed-point values are allowed only if Conversion_OK is
11690 -- set, i.e. if the fixed-point values are to be treated as integers.
11692 -- No other conversions should be passed to Gigi
11694 -- Check: are these rules stated in sinfo??? if so, why restate here???
11696 -- The only remaining step is to generate a range check if we still have
11697 -- a type conversion at this stage and Do_Range_Check is set. For now we
11698 -- do this only for conversions of discrete types and for float-to-float
11699 -- conversions.
11701 if Nkind (N) = N_Type_Conversion then
11703 -- For now we only support floating-point cases where both source
11704 -- and target are floating-point types. Conversions where the source
11705 -- and target involve integer or fixed-point types are still TBD,
11706 -- though not clear whether those can even happen at this point, due
11707 -- to transformations above. ???
11709 if Is_Floating_Point_Type (Etype (N))
11710 and then Is_Floating_Point_Type (Etype (Expression (N)))
11711 then
11712 if Do_Range_Check (Expression (N))
11713 and then Is_Floating_Point_Type (Target_Type)
11714 then
11715 Generate_Range_Check
11716 (Expression (N), Target_Type, CE_Range_Check_Failed);
11717 end if;
11719 -- Discrete-to-discrete conversions
11721 elsif Is_Discrete_Type (Etype (N)) then
11722 declare
11723 Expr : constant Node_Id := Expression (N);
11724 Ftyp : Entity_Id;
11725 Ityp : Entity_Id;
11727 begin
11728 if Do_Range_Check (Expr)
11729 and then Is_Discrete_Type (Etype (Expr))
11730 then
11731 Set_Do_Range_Check (Expr, False);
11733 -- Before we do a range check, we have to deal with treating
11734 -- a fixed-point operand as an integer. The way we do this
11735 -- is simply to do an unchecked conversion to an appropriate
11736 -- integer type large enough to hold the result.
11738 -- This code is not active yet, because we are only dealing
11739 -- with discrete types so far ???
11741 if Nkind (Expr) in N_Has_Treat_Fixed_As_Integer
11742 and then Treat_Fixed_As_Integer (Expr)
11743 then
11744 Ftyp := Base_Type (Etype (Expr));
11746 if Esize (Ftyp) >= Esize (Standard_Integer) then
11747 Ityp := Standard_Long_Long_Integer;
11748 else
11749 Ityp := Standard_Integer;
11750 end if;
11752 Rewrite (Expr, Unchecked_Convert_To (Ityp, Expr));
11753 end if;
11755 -- Reset overflow flag, since the range check will include
11756 -- dealing with possible overflow, and generate the check.
11757 -- If Address is either a source type or target type,
11758 -- suppress range check to avoid typing anomalies when
11759 -- it is a visible integer type.
11761 Set_Do_Overflow_Check (N, False);
11763 if not Is_Descendant_Of_Address (Etype (Expr))
11764 and then not Is_Descendant_Of_Address (Target_Type)
11765 then
11766 Generate_Range_Check
11767 (Expr, Target_Type, CE_Range_Check_Failed);
11768 end if;
11769 end if;
11770 end;
11771 end if;
11772 end if;
11774 -- Here at end of processing
11776 <<Done>>
11777 -- Apply predicate check if required. Note that we can't just call
11778 -- Apply_Predicate_Check here, because the type looks right after
11779 -- the conversion and it would omit the check. The Comes_From_Source
11780 -- guard is necessary to prevent infinite recursions when we generate
11781 -- internal conversions for the purpose of checking predicates.
11783 if Present (Predicate_Function (Target_Type))
11784 and then not Predicates_Ignored (Target_Type)
11785 and then Target_Type /= Operand_Type
11786 and then Comes_From_Source (N)
11787 then
11788 declare
11789 New_Expr : constant Node_Id := Duplicate_Subexpr (N);
11791 begin
11792 -- Avoid infinite recursion on the subsequent expansion of
11793 -- of the copy of the original type conversion.
11795 Set_Comes_From_Source (New_Expr, False);
11796 Insert_Action (N, Make_Predicate_Check (Target_Type, New_Expr));
11797 end;
11798 end if;
11799 end Expand_N_Type_Conversion;
11801 -----------------------------------
11802 -- Expand_N_Unchecked_Expression --
11803 -----------------------------------
11805 -- Remove the unchecked expression node from the tree. Its job was simply
11806 -- to make sure that its constituent expression was handled with checks
11807 -- off, and now that that is done, we can remove it from the tree, and
11808 -- indeed must, since Gigi does not expect to see these nodes.
11810 procedure Expand_N_Unchecked_Expression (N : Node_Id) is
11811 Exp : constant Node_Id := Expression (N);
11812 begin
11813 Set_Assignment_OK (Exp, Assignment_OK (N) or else Assignment_OK (Exp));
11814 Rewrite (N, Exp);
11815 end Expand_N_Unchecked_Expression;
11817 ----------------------------------------
11818 -- Expand_N_Unchecked_Type_Conversion --
11819 ----------------------------------------
11821 -- If this cannot be handled by Gigi and we haven't already made a
11822 -- temporary for it, do it now.
11824 procedure Expand_N_Unchecked_Type_Conversion (N : Node_Id) is
11825 Target_Type : constant Entity_Id := Etype (N);
11826 Operand : constant Node_Id := Expression (N);
11827 Operand_Type : constant Entity_Id := Etype (Operand);
11829 begin
11830 -- Nothing at all to do if conversion is to the identical type so remove
11831 -- the conversion completely, it is useless, except that it may carry
11832 -- an Assignment_OK indication which must be propagated to the operand.
11834 if Operand_Type = Target_Type then
11836 -- Code duplicates Expand_N_Unchecked_Expression above, factor???
11838 if Assignment_OK (N) then
11839 Set_Assignment_OK (Operand);
11840 end if;
11842 Rewrite (N, Relocate_Node (Operand));
11843 return;
11844 end if;
11846 -- If we have a conversion of a compile time known value to a target
11847 -- type and the value is in range of the target type, then we can simply
11848 -- replace the construct by an integer literal of the correct type. We
11849 -- only apply this to integer types being converted. Possibly it may
11850 -- apply in other cases, but it is too much trouble to worry about.
11852 -- Note that we do not do this transformation if the Kill_Range_Check
11853 -- flag is set, since then the value may be outside the expected range.
11854 -- This happens in the Normalize_Scalars case.
11856 -- We also skip this if either the target or operand type is biased
11857 -- because in this case, the unchecked conversion is supposed to
11858 -- preserve the bit pattern, not the integer value.
11860 if Is_Integer_Type (Target_Type)
11861 and then not Has_Biased_Representation (Target_Type)
11862 and then Is_Integer_Type (Operand_Type)
11863 and then not Has_Biased_Representation (Operand_Type)
11864 and then Compile_Time_Known_Value (Operand)
11865 and then not Kill_Range_Check (N)
11866 then
11867 declare
11868 Val : constant Uint := Expr_Value (Operand);
11870 begin
11871 if Compile_Time_Known_Value (Type_Low_Bound (Target_Type))
11872 and then
11873 Compile_Time_Known_Value (Type_High_Bound (Target_Type))
11874 and then
11875 Val >= Expr_Value (Type_Low_Bound (Target_Type))
11876 and then
11877 Val <= Expr_Value (Type_High_Bound (Target_Type))
11878 then
11879 Rewrite (N, Make_Integer_Literal (Sloc (N), Val));
11881 -- If Address is the target type, just set the type to avoid a
11882 -- spurious type error on the literal when Address is a visible
11883 -- integer type.
11885 if Is_Descendant_Of_Address (Target_Type) then
11886 Set_Etype (N, Target_Type);
11887 else
11888 Analyze_And_Resolve (N, Target_Type);
11889 end if;
11891 return;
11892 end if;
11893 end;
11894 end if;
11896 -- Nothing to do if conversion is safe
11898 if Safe_Unchecked_Type_Conversion (N) then
11899 return;
11900 end if;
11902 -- Otherwise force evaluation unless Assignment_OK flag is set (this
11903 -- flag indicates ??? More comments needed here)
11905 if Assignment_OK (N) then
11906 null;
11907 else
11908 Force_Evaluation (N);
11909 end if;
11910 end Expand_N_Unchecked_Type_Conversion;
11912 ----------------------------
11913 -- Expand_Record_Equality --
11914 ----------------------------
11916 -- For non-variant records, Equality is expanded when needed into:
11918 -- and then Lhs.Discr1 = Rhs.Discr1
11919 -- and then ...
11920 -- and then Lhs.Discrn = Rhs.Discrn
11921 -- and then Lhs.Cmp1 = Rhs.Cmp1
11922 -- and then ...
11923 -- and then Lhs.Cmpn = Rhs.Cmpn
11925 -- The expression is folded by the back end for adjacent fields. This
11926 -- function is called for tagged record in only one occasion: for imple-
11927 -- menting predefined primitive equality (see Predefined_Primitives_Bodies)
11928 -- otherwise the primitive "=" is used directly.
11930 function Expand_Record_Equality
11931 (Nod : Node_Id;
11932 Typ : Entity_Id;
11933 Lhs : Node_Id;
11934 Rhs : Node_Id;
11935 Bodies : List_Id) return Node_Id
11937 Loc : constant Source_Ptr := Sloc (Nod);
11939 Result : Node_Id;
11940 C : Entity_Id;
11942 First_Time : Boolean := True;
11944 function Element_To_Compare (C : Entity_Id) return Entity_Id;
11945 -- Return the next discriminant or component to compare, starting with
11946 -- C, skipping inherited components.
11948 ------------------------
11949 -- Element_To_Compare --
11950 ------------------------
11952 function Element_To_Compare (C : Entity_Id) return Entity_Id is
11953 Comp : Entity_Id;
11955 begin
11956 Comp := C;
11957 loop
11958 -- Exit loop when the next element to be compared is found, or
11959 -- there is no more such element.
11961 exit when No (Comp);
11963 exit when Ekind_In (Comp, E_Discriminant, E_Component)
11964 and then not (
11966 -- Skip inherited components
11968 -- Note: for a tagged type, we always generate the "=" primitive
11969 -- for the base type (not on the first subtype), so the test for
11970 -- Comp /= Original_Record_Component (Comp) is True for
11971 -- inherited components only.
11973 (Is_Tagged_Type (Typ)
11974 and then Comp /= Original_Record_Component (Comp))
11976 -- Skip _Tag
11978 or else Chars (Comp) = Name_uTag
11980 -- Skip interface elements (secondary tags???)
11982 or else Is_Interface (Etype (Comp)));
11984 Next_Entity (Comp);
11985 end loop;
11987 return Comp;
11988 end Element_To_Compare;
11990 -- Start of processing for Expand_Record_Equality
11992 begin
11993 -- Generates the following code: (assuming that Typ has one Discr and
11994 -- component C2 is also a record)
11996 -- True
11997 -- and then Lhs.Discr1 = Rhs.Discr1
11998 -- and then Lhs.C1 = Rhs.C1
11999 -- and then Lhs.C2.C1=Rhs.C2.C1 and then ... Lhs.C2.Cn=Rhs.C2.Cn
12000 -- and then ...
12001 -- and then Lhs.Cmpn = Rhs.Cmpn
12003 Result := New_Occurrence_Of (Standard_True, Loc);
12004 C := Element_To_Compare (First_Entity (Typ));
12005 while Present (C) loop
12006 declare
12007 New_Lhs : Node_Id;
12008 New_Rhs : Node_Id;
12009 Check : Node_Id;
12011 begin
12012 if First_Time then
12013 First_Time := False;
12014 New_Lhs := Lhs;
12015 New_Rhs := Rhs;
12016 else
12017 New_Lhs := New_Copy_Tree (Lhs);
12018 New_Rhs := New_Copy_Tree (Rhs);
12019 end if;
12021 Check :=
12022 Expand_Composite_Equality (Nod, Etype (C),
12023 Lhs =>
12024 Make_Selected_Component (Loc,
12025 Prefix => New_Lhs,
12026 Selector_Name => New_Occurrence_Of (C, Loc)),
12027 Rhs =>
12028 Make_Selected_Component (Loc,
12029 Prefix => New_Rhs,
12030 Selector_Name => New_Occurrence_Of (C, Loc)),
12031 Bodies => Bodies);
12033 -- If some (sub)component is an unchecked_union, the whole
12034 -- operation will raise program error.
12036 if Nkind (Check) = N_Raise_Program_Error then
12037 Result := Check;
12038 Set_Etype (Result, Standard_Boolean);
12039 exit;
12040 else
12041 Result :=
12042 Make_And_Then (Loc,
12043 Left_Opnd => Result,
12044 Right_Opnd => Check);
12045 end if;
12046 end;
12048 C := Element_To_Compare (Next_Entity (C));
12049 end loop;
12051 return Result;
12052 end Expand_Record_Equality;
12054 ---------------------------
12055 -- Expand_Set_Membership --
12056 ---------------------------
12058 procedure Expand_Set_Membership (N : Node_Id) is
12059 Lop : constant Node_Id := Left_Opnd (N);
12060 Alt : Node_Id;
12061 Res : Node_Id;
12063 function Make_Cond (Alt : Node_Id) return Node_Id;
12064 -- If the alternative is a subtype mark, create a simple membership
12065 -- test. Otherwise create an equality test for it.
12067 ---------------
12068 -- Make_Cond --
12069 ---------------
12071 function Make_Cond (Alt : Node_Id) return Node_Id is
12072 Cond : Node_Id;
12073 L : constant Node_Id := New_Copy (Lop);
12074 R : constant Node_Id := Relocate_Node (Alt);
12076 begin
12077 if (Is_Entity_Name (Alt) and then Is_Type (Entity (Alt)))
12078 or else Nkind (Alt) = N_Range
12079 then
12080 Cond :=
12081 Make_In (Sloc (Alt),
12082 Left_Opnd => L,
12083 Right_Opnd => R);
12084 else
12085 Cond :=
12086 Make_Op_Eq (Sloc (Alt),
12087 Left_Opnd => L,
12088 Right_Opnd => R);
12089 end if;
12091 return Cond;
12092 end Make_Cond;
12094 -- Start of processing for Expand_Set_Membership
12096 begin
12097 Remove_Side_Effects (Lop);
12099 Alt := Last (Alternatives (N));
12100 Res := Make_Cond (Alt);
12102 Prev (Alt);
12103 while Present (Alt) loop
12104 Res :=
12105 Make_Or_Else (Sloc (Alt),
12106 Left_Opnd => Make_Cond (Alt),
12107 Right_Opnd => Res);
12108 Prev (Alt);
12109 end loop;
12111 Rewrite (N, Res);
12112 Analyze_And_Resolve (N, Standard_Boolean);
12113 end Expand_Set_Membership;
12115 -----------------------------------
12116 -- Expand_Short_Circuit_Operator --
12117 -----------------------------------
12119 -- Deal with special expansion if actions are present for the right operand
12120 -- and deal with optimizing case of arguments being True or False. We also
12121 -- deal with the special case of non-standard boolean values.
12123 procedure Expand_Short_Circuit_Operator (N : Node_Id) is
12124 Loc : constant Source_Ptr := Sloc (N);
12125 Typ : constant Entity_Id := Etype (N);
12126 Left : constant Node_Id := Left_Opnd (N);
12127 Right : constant Node_Id := Right_Opnd (N);
12128 LocR : constant Source_Ptr := Sloc (Right);
12129 Actlist : List_Id;
12131 Shortcut_Value : constant Boolean := Nkind (N) = N_Or_Else;
12132 Shortcut_Ent : constant Entity_Id := Boolean_Literals (Shortcut_Value);
12133 -- If Left = Shortcut_Value then Right need not be evaluated
12135 function Make_Test_Expr (Opnd : Node_Id) return Node_Id;
12136 -- For Opnd a boolean expression, return a Boolean expression equivalent
12137 -- to Opnd /= Shortcut_Value.
12139 --------------------
12140 -- Make_Test_Expr --
12141 --------------------
12143 function Make_Test_Expr (Opnd : Node_Id) return Node_Id is
12144 begin
12145 if Shortcut_Value then
12146 return Make_Op_Not (Sloc (Opnd), Opnd);
12147 else
12148 return Opnd;
12149 end if;
12150 end Make_Test_Expr;
12152 -- Local variables
12154 Op_Var : Entity_Id;
12155 -- Entity for a temporary variable holding the value of the operator,
12156 -- used for expansion in the case where actions are present.
12158 -- Start of processing for Expand_Short_Circuit_Operator
12160 begin
12161 -- Deal with non-standard booleans
12163 if Is_Boolean_Type (Typ) then
12164 Adjust_Condition (Left);
12165 Adjust_Condition (Right);
12166 Set_Etype (N, Standard_Boolean);
12167 end if;
12169 -- Check for cases where left argument is known to be True or False
12171 if Compile_Time_Known_Value (Left) then
12173 -- Mark SCO for left condition as compile time known
12175 if Generate_SCO and then Comes_From_Source (Left) then
12176 Set_SCO_Condition (Left, Expr_Value_E (Left) = Standard_True);
12177 end if;
12179 -- Rewrite True AND THEN Right / False OR ELSE Right to Right.
12180 -- Any actions associated with Right will be executed unconditionally
12181 -- and can thus be inserted into the tree unconditionally.
12183 if Expr_Value_E (Left) /= Shortcut_Ent then
12184 if Present (Actions (N)) then
12185 Insert_Actions (N, Actions (N));
12186 end if;
12188 Rewrite (N, Right);
12190 -- Rewrite False AND THEN Right / True OR ELSE Right to Left.
12191 -- In this case we can forget the actions associated with Right,
12192 -- since they will never be executed.
12194 else
12195 Kill_Dead_Code (Right);
12196 Kill_Dead_Code (Actions (N));
12197 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12198 end if;
12200 Adjust_Result_Type (N, Typ);
12201 return;
12202 end if;
12204 -- If Actions are present for the right operand, we have to do some
12205 -- special processing. We can't just let these actions filter back into
12206 -- code preceding the short circuit (which is what would have happened
12207 -- if we had not trapped them in the short-circuit form), since they
12208 -- must only be executed if the right operand of the short circuit is
12209 -- executed and not otherwise.
12211 if Present (Actions (N)) then
12212 Actlist := Actions (N);
12214 -- The old approach is to expand:
12216 -- left AND THEN right
12218 -- into
12220 -- C : Boolean := False;
12221 -- IF left THEN
12222 -- Actions;
12223 -- IF right THEN
12224 -- C := True;
12225 -- END IF;
12226 -- END IF;
12228 -- and finally rewrite the operator into a reference to C. Similarly
12229 -- for left OR ELSE right, with negated values. Note that this
12230 -- rewrite causes some difficulties for coverage analysis because
12231 -- of the introduction of the new variable C, which obscures the
12232 -- structure of the test.
12234 -- We use this "old approach" if Minimize_Expression_With_Actions
12235 -- is True.
12237 if Minimize_Expression_With_Actions then
12238 Op_Var := Make_Temporary (Loc, 'C', Related_Node => N);
12240 Insert_Action (N,
12241 Make_Object_Declaration (Loc,
12242 Defining_Identifier => Op_Var,
12243 Object_Definition =>
12244 New_Occurrence_Of (Standard_Boolean, Loc),
12245 Expression =>
12246 New_Occurrence_Of (Shortcut_Ent, Loc)));
12248 Append_To (Actlist,
12249 Make_Implicit_If_Statement (Right,
12250 Condition => Make_Test_Expr (Right),
12251 Then_Statements => New_List (
12252 Make_Assignment_Statement (LocR,
12253 Name => New_Occurrence_Of (Op_Var, LocR),
12254 Expression =>
12255 New_Occurrence_Of
12256 (Boolean_Literals (not Shortcut_Value), LocR)))));
12258 Insert_Action (N,
12259 Make_Implicit_If_Statement (Left,
12260 Condition => Make_Test_Expr (Left),
12261 Then_Statements => Actlist));
12263 Rewrite (N, New_Occurrence_Of (Op_Var, Loc));
12264 Analyze_And_Resolve (N, Standard_Boolean);
12266 -- The new approach (the default) is to use an
12267 -- Expression_With_Actions node for the right operand of the
12268 -- short-circuit form. Note that this solves the traceability
12269 -- problems for coverage analysis.
12271 else
12272 Rewrite (Right,
12273 Make_Expression_With_Actions (LocR,
12274 Expression => Relocate_Node (Right),
12275 Actions => Actlist));
12277 Set_Actions (N, No_List);
12278 Analyze_And_Resolve (Right, Standard_Boolean);
12279 end if;
12281 Adjust_Result_Type (N, Typ);
12282 return;
12283 end if;
12285 -- No actions present, check for cases of right argument True/False
12287 if Compile_Time_Known_Value (Right) then
12289 -- Mark SCO for left condition as compile time known
12291 if Generate_SCO and then Comes_From_Source (Right) then
12292 Set_SCO_Condition (Right, Expr_Value_E (Right) = Standard_True);
12293 end if;
12295 -- Change (Left and then True), (Left or else False) to Left. Note
12296 -- that we know there are no actions associated with the right
12297 -- operand, since we just checked for this case above.
12299 if Expr_Value_E (Right) /= Shortcut_Ent then
12300 Rewrite (N, Left);
12302 -- Change (Left and then False), (Left or else True) to Right,
12303 -- making sure to preserve any side effects associated with the Left
12304 -- operand.
12306 else
12307 Remove_Side_Effects (Left);
12308 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12309 end if;
12310 end if;
12312 Adjust_Result_Type (N, Typ);
12313 end Expand_Short_Circuit_Operator;
12315 -------------------------------------
12316 -- Fixup_Universal_Fixed_Operation --
12317 -------------------------------------
12319 procedure Fixup_Universal_Fixed_Operation (N : Node_Id) is
12320 Conv : constant Node_Id := Parent (N);
12322 begin
12323 -- We must have a type conversion immediately above us
12325 pragma Assert (Nkind (Conv) = N_Type_Conversion);
12327 -- Normally the type conversion gives our target type. The exception
12328 -- occurs in the case of the Round attribute, where the conversion
12329 -- will be to universal real, and our real type comes from the Round
12330 -- attribute (as well as an indication that we must round the result)
12332 if Nkind (Parent (Conv)) = N_Attribute_Reference
12333 and then Attribute_Name (Parent (Conv)) = Name_Round
12334 then
12335 Set_Etype (N, Etype (Parent (Conv)));
12336 Set_Rounded_Result (N);
12338 -- Normal case where type comes from conversion above us
12340 else
12341 Set_Etype (N, Etype (Conv));
12342 end if;
12343 end Fixup_Universal_Fixed_Operation;
12345 ---------------------------------
12346 -- Has_Inferable_Discriminants --
12347 ---------------------------------
12349 function Has_Inferable_Discriminants (N : Node_Id) return Boolean is
12351 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean;
12352 -- Determines whether the left-most prefix of a selected component is a
12353 -- formal parameter in a subprogram. Assumes N is a selected component.
12355 --------------------------------
12356 -- Prefix_Is_Formal_Parameter --
12357 --------------------------------
12359 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean is
12360 Sel_Comp : Node_Id;
12362 begin
12363 -- Move to the left-most prefix by climbing up the tree
12365 Sel_Comp := N;
12366 while Present (Parent (Sel_Comp))
12367 and then Nkind (Parent (Sel_Comp)) = N_Selected_Component
12368 loop
12369 Sel_Comp := Parent (Sel_Comp);
12370 end loop;
12372 return Ekind (Entity (Prefix (Sel_Comp))) in Formal_Kind;
12373 end Prefix_Is_Formal_Parameter;
12375 -- Start of processing for Has_Inferable_Discriminants
12377 begin
12378 -- For selected components, the subtype of the selector must be a
12379 -- constrained Unchecked_Union. If the component is subject to a
12380 -- per-object constraint, then the enclosing object must have inferable
12381 -- discriminants.
12383 if Nkind (N) = N_Selected_Component then
12384 if Has_Per_Object_Constraint (Entity (Selector_Name (N))) then
12386 -- A small hack. If we have a per-object constrained selected
12387 -- component of a formal parameter, return True since we do not
12388 -- know the actual parameter association yet.
12390 if Prefix_Is_Formal_Parameter (N) then
12391 return True;
12393 -- Otherwise, check the enclosing object and the selector
12395 else
12396 return Has_Inferable_Discriminants (Prefix (N))
12397 and then Has_Inferable_Discriminants (Selector_Name (N));
12398 end if;
12400 -- The call to Has_Inferable_Discriminants will determine whether
12401 -- the selector has a constrained Unchecked_Union nominal type.
12403 else
12404 return Has_Inferable_Discriminants (Selector_Name (N));
12405 end if;
12407 -- A qualified expression has inferable discriminants if its subtype
12408 -- mark is a constrained Unchecked_Union subtype.
12410 elsif Nkind (N) = N_Qualified_Expression then
12411 return Is_Unchecked_Union (Etype (Subtype_Mark (N)))
12412 and then Is_Constrained (Etype (Subtype_Mark (N)));
12414 -- For all other names, it is sufficient to have a constrained
12415 -- Unchecked_Union nominal subtype.
12417 else
12418 return Is_Unchecked_Union (Base_Type (Etype (N)))
12419 and then Is_Constrained (Etype (N));
12420 end if;
12421 end Has_Inferable_Discriminants;
12423 -------------------------------
12424 -- Insert_Dereference_Action --
12425 -------------------------------
12427 procedure Insert_Dereference_Action (N : Node_Id) is
12428 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean;
12429 -- Return true if type of P is derived from Checked_Pool;
12431 -----------------------------
12432 -- Is_Checked_Storage_Pool --
12433 -----------------------------
12435 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean is
12436 T : Entity_Id;
12438 begin
12439 if No (P) then
12440 return False;
12441 end if;
12443 T := Etype (P);
12444 while T /= Etype (T) loop
12445 if Is_RTE (T, RE_Checked_Pool) then
12446 return True;
12447 else
12448 T := Etype (T);
12449 end if;
12450 end loop;
12452 return False;
12453 end Is_Checked_Storage_Pool;
12455 -- Local variables
12457 Context : constant Node_Id := Parent (N);
12458 Ptr_Typ : constant Entity_Id := Etype (N);
12459 Desig_Typ : constant Entity_Id :=
12460 Available_View (Designated_Type (Ptr_Typ));
12461 Loc : constant Source_Ptr := Sloc (N);
12462 Pool : constant Entity_Id := Associated_Storage_Pool (Ptr_Typ);
12464 Addr : Entity_Id;
12465 Alig : Entity_Id;
12466 Deref : Node_Id;
12467 Size : Entity_Id;
12468 Size_Bits : Node_Id;
12469 Stmt : Node_Id;
12471 -- Start of processing for Insert_Dereference_Action
12473 begin
12474 pragma Assert (Nkind (Context) = N_Explicit_Dereference);
12476 -- Do not re-expand a dereference which has already been processed by
12477 -- this routine.
12479 if Has_Dereference_Action (Context) then
12480 return;
12482 -- Do not perform this type of expansion for internally-generated
12483 -- dereferences.
12485 elsif not Comes_From_Source (Original_Node (Context)) then
12486 return;
12488 -- A dereference action is only applicable to objects which have been
12489 -- allocated on a checked pool.
12491 elsif not Is_Checked_Storage_Pool (Pool) then
12492 return;
12493 end if;
12495 -- Extract the address of the dereferenced object. Generate:
12497 -- Addr : System.Address := <N>'Pool_Address;
12499 Addr := Make_Temporary (Loc, 'P');
12501 Insert_Action (N,
12502 Make_Object_Declaration (Loc,
12503 Defining_Identifier => Addr,
12504 Object_Definition =>
12505 New_Occurrence_Of (RTE (RE_Address), Loc),
12506 Expression =>
12507 Make_Attribute_Reference (Loc,
12508 Prefix => Duplicate_Subexpr_Move_Checks (N),
12509 Attribute_Name => Name_Pool_Address)));
12511 -- Calculate the size of the dereferenced object. Generate:
12513 -- Size : Storage_Count := <N>.all'Size / Storage_Unit;
12515 Deref :=
12516 Make_Explicit_Dereference (Loc,
12517 Prefix => Duplicate_Subexpr_Move_Checks (N));
12518 Set_Has_Dereference_Action (Deref);
12520 Size_Bits :=
12521 Make_Attribute_Reference (Loc,
12522 Prefix => Deref,
12523 Attribute_Name => Name_Size);
12525 -- Special case of an unconstrained array: need to add descriptor size
12527 if Is_Array_Type (Desig_Typ)
12528 and then not Is_Constrained (First_Subtype (Desig_Typ))
12529 then
12530 Size_Bits :=
12531 Make_Op_Add (Loc,
12532 Left_Opnd =>
12533 Make_Attribute_Reference (Loc,
12534 Prefix =>
12535 New_Occurrence_Of (First_Subtype (Desig_Typ), Loc),
12536 Attribute_Name => Name_Descriptor_Size),
12537 Right_Opnd => Size_Bits);
12538 end if;
12540 Size := Make_Temporary (Loc, 'S');
12541 Insert_Action (N,
12542 Make_Object_Declaration (Loc,
12543 Defining_Identifier => Size,
12544 Object_Definition =>
12545 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12546 Expression =>
12547 Make_Op_Divide (Loc,
12548 Left_Opnd => Size_Bits,
12549 Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit))));
12551 -- Calculate the alignment of the dereferenced object. Generate:
12552 -- Alig : constant Storage_Count := <N>.all'Alignment;
12554 Deref :=
12555 Make_Explicit_Dereference (Loc,
12556 Prefix => Duplicate_Subexpr_Move_Checks (N));
12557 Set_Has_Dereference_Action (Deref);
12559 Alig := Make_Temporary (Loc, 'A');
12560 Insert_Action (N,
12561 Make_Object_Declaration (Loc,
12562 Defining_Identifier => Alig,
12563 Object_Definition =>
12564 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12565 Expression =>
12566 Make_Attribute_Reference (Loc,
12567 Prefix => Deref,
12568 Attribute_Name => Name_Alignment)));
12570 -- A dereference of a controlled object requires special processing. The
12571 -- finalization machinery requests additional space from the underlying
12572 -- pool to allocate and hide two pointers. As a result, a checked pool
12573 -- may mark the wrong memory as valid. Since checked pools do not have
12574 -- knowledge of hidden pointers, we have to bring the two pointers back
12575 -- in view in order to restore the original state of the object.
12577 -- The address manipulation is not performed for access types that are
12578 -- subject to pragma No_Heap_Finalization because the two pointers do
12579 -- not exist in the first place.
12581 if No_Heap_Finalization (Ptr_Typ) then
12582 null;
12584 elsif Needs_Finalization (Desig_Typ) then
12586 -- Adjust the address and size of the dereferenced object. Generate:
12587 -- Adjust_Controlled_Dereference (Addr, Size, Alig);
12589 Stmt :=
12590 Make_Procedure_Call_Statement (Loc,
12591 Name =>
12592 New_Occurrence_Of (RTE (RE_Adjust_Controlled_Dereference), Loc),
12593 Parameter_Associations => New_List (
12594 New_Occurrence_Of (Addr, Loc),
12595 New_Occurrence_Of (Size, Loc),
12596 New_Occurrence_Of (Alig, Loc)));
12598 -- Class-wide types complicate things because we cannot determine
12599 -- statically whether the actual object is truly controlled. We must
12600 -- generate a runtime check to detect this property. Generate:
12602 -- if Needs_Finalization (<N>.all'Tag) then
12603 -- <Stmt>;
12604 -- end if;
12606 if Is_Class_Wide_Type (Desig_Typ) then
12607 Deref :=
12608 Make_Explicit_Dereference (Loc,
12609 Prefix => Duplicate_Subexpr_Move_Checks (N));
12610 Set_Has_Dereference_Action (Deref);
12612 Stmt :=
12613 Make_Implicit_If_Statement (N,
12614 Condition =>
12615 Make_Function_Call (Loc,
12616 Name =>
12617 New_Occurrence_Of (RTE (RE_Needs_Finalization), Loc),
12618 Parameter_Associations => New_List (
12619 Make_Attribute_Reference (Loc,
12620 Prefix => Deref,
12621 Attribute_Name => Name_Tag))),
12622 Then_Statements => New_List (Stmt));
12623 end if;
12625 Insert_Action (N, Stmt);
12626 end if;
12628 -- Generate:
12629 -- Dereference (Pool, Addr, Size, Alig);
12631 Insert_Action (N,
12632 Make_Procedure_Call_Statement (Loc,
12633 Name =>
12634 New_Occurrence_Of
12635 (Find_Prim_Op (Etype (Pool), Name_Dereference), Loc),
12636 Parameter_Associations => New_List (
12637 New_Occurrence_Of (Pool, Loc),
12638 New_Occurrence_Of (Addr, Loc),
12639 New_Occurrence_Of (Size, Loc),
12640 New_Occurrence_Of (Alig, Loc))));
12642 -- Mark the explicit dereference as processed to avoid potential
12643 -- infinite expansion.
12645 Set_Has_Dereference_Action (Context);
12647 exception
12648 when RE_Not_Available =>
12649 return;
12650 end Insert_Dereference_Action;
12652 --------------------------------
12653 -- Integer_Promotion_Possible --
12654 --------------------------------
12656 function Integer_Promotion_Possible (N : Node_Id) return Boolean is
12657 Operand : constant Node_Id := Expression (N);
12658 Operand_Type : constant Entity_Id := Etype (Operand);
12659 Root_Operand_Type : constant Entity_Id := Root_Type (Operand_Type);
12661 begin
12662 pragma Assert (Nkind (N) = N_Type_Conversion);
12664 return
12666 -- We only do the transformation for source constructs. We assume
12667 -- that the expander knows what it is doing when it generates code.
12669 Comes_From_Source (N)
12671 -- If the operand type is Short_Integer or Short_Short_Integer,
12672 -- then we will promote to Integer, which is available on all
12673 -- targets, and is sufficient to ensure no intermediate overflow.
12674 -- Furthermore it is likely to be as efficient or more efficient
12675 -- than using the smaller type for the computation so we do this
12676 -- unconditionally.
12678 and then
12679 (Root_Operand_Type = Base_Type (Standard_Short_Integer)
12680 or else
12681 Root_Operand_Type = Base_Type (Standard_Short_Short_Integer))
12683 -- Test for interesting operation, which includes addition,
12684 -- division, exponentiation, multiplication, subtraction, absolute
12685 -- value and unary negation. Unary "+" is omitted since it is a
12686 -- no-op and thus can't overflow.
12688 and then Nkind_In (Operand, N_Op_Abs,
12689 N_Op_Add,
12690 N_Op_Divide,
12691 N_Op_Expon,
12692 N_Op_Minus,
12693 N_Op_Multiply,
12694 N_Op_Subtract);
12695 end Integer_Promotion_Possible;
12697 ------------------------------
12698 -- Make_Array_Comparison_Op --
12699 ------------------------------
12701 -- This is a hand-coded expansion of the following generic function:
12703 -- generic
12704 -- type elem is (<>);
12705 -- type index is (<>);
12706 -- type a is array (index range <>) of elem;
12708 -- function Gnnn (X : a; Y: a) return boolean is
12709 -- J : index := Y'first;
12711 -- begin
12712 -- if X'length = 0 then
12713 -- return false;
12715 -- elsif Y'length = 0 then
12716 -- return true;
12718 -- else
12719 -- for I in X'range loop
12720 -- if X (I) = Y (J) then
12721 -- if J = Y'last then
12722 -- exit;
12723 -- else
12724 -- J := index'succ (J);
12725 -- end if;
12727 -- else
12728 -- return X (I) > Y (J);
12729 -- end if;
12730 -- end loop;
12732 -- return X'length > Y'length;
12733 -- end if;
12734 -- end Gnnn;
12736 -- Note that since we are essentially doing this expansion by hand, we
12737 -- do not need to generate an actual or formal generic part, just the
12738 -- instantiated function itself.
12740 -- Perhaps we could have the actual generic available in the run-time,
12741 -- obtained by rtsfind, and actually expand a real instantiation ???
12743 function Make_Array_Comparison_Op
12744 (Typ : Entity_Id;
12745 Nod : Node_Id) return Node_Id
12747 Loc : constant Source_Ptr := Sloc (Nod);
12749 X : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uX);
12750 Y : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uY);
12751 I : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uI);
12752 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
12754 Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
12756 Loop_Statement : Node_Id;
12757 Loop_Body : Node_Id;
12758 If_Stat : Node_Id;
12759 Inner_If : Node_Id;
12760 Final_Expr : Node_Id;
12761 Func_Body : Node_Id;
12762 Func_Name : Entity_Id;
12763 Formals : List_Id;
12764 Length1 : Node_Id;
12765 Length2 : Node_Id;
12767 begin
12768 -- if J = Y'last then
12769 -- exit;
12770 -- else
12771 -- J := index'succ (J);
12772 -- end if;
12774 Inner_If :=
12775 Make_Implicit_If_Statement (Nod,
12776 Condition =>
12777 Make_Op_Eq (Loc,
12778 Left_Opnd => New_Occurrence_Of (J, Loc),
12779 Right_Opnd =>
12780 Make_Attribute_Reference (Loc,
12781 Prefix => New_Occurrence_Of (Y, Loc),
12782 Attribute_Name => Name_Last)),
12784 Then_Statements => New_List (
12785 Make_Exit_Statement (Loc)),
12787 Else_Statements =>
12788 New_List (
12789 Make_Assignment_Statement (Loc,
12790 Name => New_Occurrence_Of (J, Loc),
12791 Expression =>
12792 Make_Attribute_Reference (Loc,
12793 Prefix => New_Occurrence_Of (Index, Loc),
12794 Attribute_Name => Name_Succ,
12795 Expressions => New_List (New_Occurrence_Of (J, Loc))))));
12797 -- if X (I) = Y (J) then
12798 -- if ... end if;
12799 -- else
12800 -- return X (I) > Y (J);
12801 -- end if;
12803 Loop_Body :=
12804 Make_Implicit_If_Statement (Nod,
12805 Condition =>
12806 Make_Op_Eq (Loc,
12807 Left_Opnd =>
12808 Make_Indexed_Component (Loc,
12809 Prefix => New_Occurrence_Of (X, Loc),
12810 Expressions => New_List (New_Occurrence_Of (I, Loc))),
12812 Right_Opnd =>
12813 Make_Indexed_Component (Loc,
12814 Prefix => New_Occurrence_Of (Y, Loc),
12815 Expressions => New_List (New_Occurrence_Of (J, Loc)))),
12817 Then_Statements => New_List (Inner_If),
12819 Else_Statements => New_List (
12820 Make_Simple_Return_Statement (Loc,
12821 Expression =>
12822 Make_Op_Gt (Loc,
12823 Left_Opnd =>
12824 Make_Indexed_Component (Loc,
12825 Prefix => New_Occurrence_Of (X, Loc),
12826 Expressions => New_List (New_Occurrence_Of (I, Loc))),
12828 Right_Opnd =>
12829 Make_Indexed_Component (Loc,
12830 Prefix => New_Occurrence_Of (Y, Loc),
12831 Expressions => New_List (
12832 New_Occurrence_Of (J, Loc)))))));
12834 -- for I in X'range loop
12835 -- if ... end if;
12836 -- end loop;
12838 Loop_Statement :=
12839 Make_Implicit_Loop_Statement (Nod,
12840 Identifier => Empty,
12842 Iteration_Scheme =>
12843 Make_Iteration_Scheme (Loc,
12844 Loop_Parameter_Specification =>
12845 Make_Loop_Parameter_Specification (Loc,
12846 Defining_Identifier => I,
12847 Discrete_Subtype_Definition =>
12848 Make_Attribute_Reference (Loc,
12849 Prefix => New_Occurrence_Of (X, Loc),
12850 Attribute_Name => Name_Range))),
12852 Statements => New_List (Loop_Body));
12854 -- if X'length = 0 then
12855 -- return false;
12856 -- elsif Y'length = 0 then
12857 -- return true;
12858 -- else
12859 -- for ... loop ... end loop;
12860 -- return X'length > Y'length;
12861 -- end if;
12863 Length1 :=
12864 Make_Attribute_Reference (Loc,
12865 Prefix => New_Occurrence_Of (X, Loc),
12866 Attribute_Name => Name_Length);
12868 Length2 :=
12869 Make_Attribute_Reference (Loc,
12870 Prefix => New_Occurrence_Of (Y, Loc),
12871 Attribute_Name => Name_Length);
12873 Final_Expr :=
12874 Make_Op_Gt (Loc,
12875 Left_Opnd => Length1,
12876 Right_Opnd => Length2);
12878 If_Stat :=
12879 Make_Implicit_If_Statement (Nod,
12880 Condition =>
12881 Make_Op_Eq (Loc,
12882 Left_Opnd =>
12883 Make_Attribute_Reference (Loc,
12884 Prefix => New_Occurrence_Of (X, Loc),
12885 Attribute_Name => Name_Length),
12886 Right_Opnd =>
12887 Make_Integer_Literal (Loc, 0)),
12889 Then_Statements =>
12890 New_List (
12891 Make_Simple_Return_Statement (Loc,
12892 Expression => New_Occurrence_Of (Standard_False, Loc))),
12894 Elsif_Parts => New_List (
12895 Make_Elsif_Part (Loc,
12896 Condition =>
12897 Make_Op_Eq (Loc,
12898 Left_Opnd =>
12899 Make_Attribute_Reference (Loc,
12900 Prefix => New_Occurrence_Of (Y, Loc),
12901 Attribute_Name => Name_Length),
12902 Right_Opnd =>
12903 Make_Integer_Literal (Loc, 0)),
12905 Then_Statements =>
12906 New_List (
12907 Make_Simple_Return_Statement (Loc,
12908 Expression => New_Occurrence_Of (Standard_True, Loc))))),
12910 Else_Statements => New_List (
12911 Loop_Statement,
12912 Make_Simple_Return_Statement (Loc,
12913 Expression => Final_Expr)));
12915 -- (X : a; Y: a)
12917 Formals := New_List (
12918 Make_Parameter_Specification (Loc,
12919 Defining_Identifier => X,
12920 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
12922 Make_Parameter_Specification (Loc,
12923 Defining_Identifier => Y,
12924 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
12926 -- function Gnnn (...) return boolean is
12927 -- J : index := Y'first;
12928 -- begin
12929 -- if ... end if;
12930 -- end Gnnn;
12932 Func_Name := Make_Temporary (Loc, 'G');
12934 Func_Body :=
12935 Make_Subprogram_Body (Loc,
12936 Specification =>
12937 Make_Function_Specification (Loc,
12938 Defining_Unit_Name => Func_Name,
12939 Parameter_Specifications => Formals,
12940 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
12942 Declarations => New_List (
12943 Make_Object_Declaration (Loc,
12944 Defining_Identifier => J,
12945 Object_Definition => New_Occurrence_Of (Index, Loc),
12946 Expression =>
12947 Make_Attribute_Reference (Loc,
12948 Prefix => New_Occurrence_Of (Y, Loc),
12949 Attribute_Name => Name_First))),
12951 Handled_Statement_Sequence =>
12952 Make_Handled_Sequence_Of_Statements (Loc,
12953 Statements => New_List (If_Stat)));
12955 return Func_Body;
12956 end Make_Array_Comparison_Op;
12958 ---------------------------
12959 -- Make_Boolean_Array_Op --
12960 ---------------------------
12962 -- For logical operations on boolean arrays, expand in line the following,
12963 -- replacing 'and' with 'or' or 'xor' where needed:
12965 -- function Annn (A : typ; B: typ) return typ is
12966 -- C : typ;
12967 -- begin
12968 -- for J in A'range loop
12969 -- C (J) := A (J) op B (J);
12970 -- end loop;
12971 -- return C;
12972 -- end Annn;
12974 -- Here typ is the boolean array type
12976 function Make_Boolean_Array_Op
12977 (Typ : Entity_Id;
12978 N : Node_Id) return Node_Id
12980 Loc : constant Source_Ptr := Sloc (N);
12982 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
12983 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
12984 C : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uC);
12985 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
12987 A_J : Node_Id;
12988 B_J : Node_Id;
12989 C_J : Node_Id;
12990 Op : Node_Id;
12992 Formals : List_Id;
12993 Func_Name : Entity_Id;
12994 Func_Body : Node_Id;
12995 Loop_Statement : Node_Id;
12997 begin
12998 A_J :=
12999 Make_Indexed_Component (Loc,
13000 Prefix => New_Occurrence_Of (A, Loc),
13001 Expressions => New_List (New_Occurrence_Of (J, Loc)));
13003 B_J :=
13004 Make_Indexed_Component (Loc,
13005 Prefix => New_Occurrence_Of (B, Loc),
13006 Expressions => New_List (New_Occurrence_Of (J, Loc)));
13008 C_J :=
13009 Make_Indexed_Component (Loc,
13010 Prefix => New_Occurrence_Of (C, Loc),
13011 Expressions => New_List (New_Occurrence_Of (J, Loc)));
13013 if Nkind (N) = N_Op_And then
13014 Op :=
13015 Make_Op_And (Loc,
13016 Left_Opnd => A_J,
13017 Right_Opnd => B_J);
13019 elsif Nkind (N) = N_Op_Or then
13020 Op :=
13021 Make_Op_Or (Loc,
13022 Left_Opnd => A_J,
13023 Right_Opnd => B_J);
13025 else
13026 Op :=
13027 Make_Op_Xor (Loc,
13028 Left_Opnd => A_J,
13029 Right_Opnd => B_J);
13030 end if;
13032 Loop_Statement :=
13033 Make_Implicit_Loop_Statement (N,
13034 Identifier => Empty,
13036 Iteration_Scheme =>
13037 Make_Iteration_Scheme (Loc,
13038 Loop_Parameter_Specification =>
13039 Make_Loop_Parameter_Specification (Loc,
13040 Defining_Identifier => J,
13041 Discrete_Subtype_Definition =>
13042 Make_Attribute_Reference (Loc,
13043 Prefix => New_Occurrence_Of (A, Loc),
13044 Attribute_Name => Name_Range))),
13046 Statements => New_List (
13047 Make_Assignment_Statement (Loc,
13048 Name => C_J,
13049 Expression => Op)));
13051 Formals := New_List (
13052 Make_Parameter_Specification (Loc,
13053 Defining_Identifier => A,
13054 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
13056 Make_Parameter_Specification (Loc,
13057 Defining_Identifier => B,
13058 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
13060 Func_Name := Make_Temporary (Loc, 'A');
13061 Set_Is_Inlined (Func_Name);
13063 Func_Body :=
13064 Make_Subprogram_Body (Loc,
13065 Specification =>
13066 Make_Function_Specification (Loc,
13067 Defining_Unit_Name => Func_Name,
13068 Parameter_Specifications => Formals,
13069 Result_Definition => New_Occurrence_Of (Typ, Loc)),
13071 Declarations => New_List (
13072 Make_Object_Declaration (Loc,
13073 Defining_Identifier => C,
13074 Object_Definition => New_Occurrence_Of (Typ, Loc))),
13076 Handled_Statement_Sequence =>
13077 Make_Handled_Sequence_Of_Statements (Loc,
13078 Statements => New_List (
13079 Loop_Statement,
13080 Make_Simple_Return_Statement (Loc,
13081 Expression => New_Occurrence_Of (C, Loc)))));
13083 return Func_Body;
13084 end Make_Boolean_Array_Op;
13086 -----------------------------------------
13087 -- Minimized_Eliminated_Overflow_Check --
13088 -----------------------------------------
13090 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean is
13091 begin
13092 return
13093 Is_Signed_Integer_Type (Etype (N))
13094 and then Overflow_Check_Mode in Minimized_Or_Eliminated;
13095 end Minimized_Eliminated_Overflow_Check;
13097 --------------------------------
13098 -- Optimize_Length_Comparison --
13099 --------------------------------
13101 procedure Optimize_Length_Comparison (N : Node_Id) is
13102 Loc : constant Source_Ptr := Sloc (N);
13103 Typ : constant Entity_Id := Etype (N);
13104 Result : Node_Id;
13106 Left : Node_Id;
13107 Right : Node_Id;
13108 -- First and Last attribute reference nodes, which end up as left and
13109 -- right operands of the optimized result.
13111 Is_Zero : Boolean;
13112 -- True for comparison operand of zero
13114 Comp : Node_Id;
13115 -- Comparison operand, set only if Is_Zero is false
13117 Ent : Entity_Id := Empty;
13118 -- Entity whose length is being compared
13120 Index : Node_Id := Empty;
13121 -- Integer_Literal node for length attribute expression, or Empty
13122 -- if there is no such expression present.
13124 Ityp : Entity_Id;
13125 -- Type of array index to which 'Length is applied
13127 Op : Node_Kind := Nkind (N);
13128 -- Kind of comparison operator, gets flipped if operands backwards
13130 function Is_Optimizable (N : Node_Id) return Boolean;
13131 -- Tests N to see if it is an optimizable comparison value (defined as
13132 -- constant zero or one, or something else where the value is known to
13133 -- be positive and in the range of 32-bits, and where the corresponding
13134 -- Length value is also known to be 32-bits. If result is true, sets
13135 -- Is_Zero, Ityp, and Comp accordingly.
13137 function Is_Entity_Length (N : Node_Id) return Boolean;
13138 -- Tests if N is a length attribute applied to a simple entity. If so,
13139 -- returns True, and sets Ent to the entity, and Index to the integer
13140 -- literal provided as an attribute expression, or to Empty if none.
13141 -- Also returns True if the expression is a generated type conversion
13142 -- whose expression is of the desired form. This latter case arises
13143 -- when Apply_Universal_Integer_Attribute_Check installs a conversion
13144 -- to check for being in range, which is not needed in this context.
13145 -- Returns False if neither condition holds.
13147 function Prepare_64 (N : Node_Id) return Node_Id;
13148 -- Given a discrete expression, returns a Long_Long_Integer typed
13149 -- expression representing the underlying value of the expression.
13150 -- This is done with an unchecked conversion to the result type. We
13151 -- use unchecked conversion to handle the enumeration type case.
13153 ----------------------
13154 -- Is_Entity_Length --
13155 ----------------------
13157 function Is_Entity_Length (N : Node_Id) return Boolean is
13158 begin
13159 if Nkind (N) = N_Attribute_Reference
13160 and then Attribute_Name (N) = Name_Length
13161 and then Is_Entity_Name (Prefix (N))
13162 then
13163 Ent := Entity (Prefix (N));
13165 if Present (Expressions (N)) then
13166 Index := First (Expressions (N));
13167 else
13168 Index := Empty;
13169 end if;
13171 return True;
13173 elsif Nkind (N) = N_Type_Conversion
13174 and then not Comes_From_Source (N)
13175 then
13176 return Is_Entity_Length (Expression (N));
13178 else
13179 return False;
13180 end if;
13181 end Is_Entity_Length;
13183 --------------------
13184 -- Is_Optimizable --
13185 --------------------
13187 function Is_Optimizable (N : Node_Id) return Boolean is
13188 Val : Uint;
13189 OK : Boolean;
13190 Lo : Uint;
13191 Hi : Uint;
13192 Indx : Node_Id;
13194 begin
13195 if Compile_Time_Known_Value (N) then
13196 Val := Expr_Value (N);
13198 if Val = Uint_0 then
13199 Is_Zero := True;
13200 Comp := Empty;
13201 return True;
13203 elsif Val = Uint_1 then
13204 Is_Zero := False;
13205 Comp := Empty;
13206 return True;
13207 end if;
13208 end if;
13210 -- Here we have to make sure of being within 32-bits
13212 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
13214 if not OK
13215 or else Lo < Uint_1
13216 or else Hi > UI_From_Int (Int'Last)
13217 then
13218 return False;
13219 end if;
13221 -- Comparison value was within range, so now we must check the index
13222 -- value to make sure it is also within 32-bits.
13224 Indx := First_Index (Etype (Ent));
13226 if Present (Index) then
13227 for J in 2 .. UI_To_Int (Intval (Index)) loop
13228 Next_Index (Indx);
13229 end loop;
13230 end if;
13232 Ityp := Etype (Indx);
13234 if Esize (Ityp) > 32 then
13235 return False;
13236 end if;
13238 Is_Zero := False;
13239 Comp := N;
13240 return True;
13241 end Is_Optimizable;
13243 ----------------
13244 -- Prepare_64 --
13245 ----------------
13247 function Prepare_64 (N : Node_Id) return Node_Id is
13248 begin
13249 return Unchecked_Convert_To (Standard_Long_Long_Integer, N);
13250 end Prepare_64;
13252 -- Start of processing for Optimize_Length_Comparison
13254 begin
13255 -- Nothing to do if not a comparison
13257 if Op not in N_Op_Compare then
13258 return;
13259 end if;
13261 -- Nothing to do if special -gnatd.P debug flag set.
13263 if Debug_Flag_Dot_PP then
13264 return;
13265 end if;
13267 -- Ent'Length op 0/1
13269 if Is_Entity_Length (Left_Opnd (N))
13270 and then Is_Optimizable (Right_Opnd (N))
13271 then
13272 null;
13274 -- 0/1 op Ent'Length
13276 elsif Is_Entity_Length (Right_Opnd (N))
13277 and then Is_Optimizable (Left_Opnd (N))
13278 then
13279 -- Flip comparison to opposite sense
13281 case Op is
13282 when N_Op_Lt => Op := N_Op_Gt;
13283 when N_Op_Le => Op := N_Op_Ge;
13284 when N_Op_Gt => Op := N_Op_Lt;
13285 when N_Op_Ge => Op := N_Op_Le;
13286 when others => null;
13287 end case;
13289 -- Else optimization not possible
13291 else
13292 return;
13293 end if;
13295 -- Fall through if we will do the optimization
13297 -- Cases to handle:
13299 -- X'Length = 0 => X'First > X'Last
13300 -- X'Length = 1 => X'First = X'Last
13301 -- X'Length = n => X'First + (n - 1) = X'Last
13303 -- X'Length /= 0 => X'First <= X'Last
13304 -- X'Length /= 1 => X'First /= X'Last
13305 -- X'Length /= n => X'First + (n - 1) /= X'Last
13307 -- X'Length >= 0 => always true, warn
13308 -- X'Length >= 1 => X'First <= X'Last
13309 -- X'Length >= n => X'First + (n - 1) <= X'Last
13311 -- X'Length > 0 => X'First <= X'Last
13312 -- X'Length > 1 => X'First < X'Last
13313 -- X'Length > n => X'First + (n - 1) < X'Last
13315 -- X'Length <= 0 => X'First > X'Last (warn, could be =)
13316 -- X'Length <= 1 => X'First >= X'Last
13317 -- X'Length <= n => X'First + (n - 1) >= X'Last
13319 -- X'Length < 0 => always false (warn)
13320 -- X'Length < 1 => X'First > X'Last
13321 -- X'Length < n => X'First + (n - 1) > X'Last
13323 -- Note: for the cases of n (not constant 0,1), we require that the
13324 -- corresponding index type be integer or shorter (i.e. not 64-bit),
13325 -- and the same for the comparison value. Then we do the comparison
13326 -- using 64-bit arithmetic (actually long long integer), so that we
13327 -- cannot have overflow intefering with the result.
13329 -- First deal with warning cases
13331 if Is_Zero then
13332 case Op is
13334 -- X'Length >= 0
13336 when N_Op_Ge =>
13337 Rewrite (N,
13338 Convert_To (Typ, New_Occurrence_Of (Standard_True, Loc)));
13339 Analyze_And_Resolve (N, Typ);
13340 Warn_On_Known_Condition (N);
13341 return;
13343 -- X'Length < 0
13345 when N_Op_Lt =>
13346 Rewrite (N,
13347 Convert_To (Typ, New_Occurrence_Of (Standard_False, Loc)));
13348 Analyze_And_Resolve (N, Typ);
13349 Warn_On_Known_Condition (N);
13350 return;
13352 when N_Op_Le =>
13353 if Constant_Condition_Warnings
13354 and then Comes_From_Source (Original_Node (N))
13355 then
13356 Error_Msg_N ("could replace by ""'=""?c?", N);
13357 end if;
13359 Op := N_Op_Eq;
13361 when others =>
13362 null;
13363 end case;
13364 end if;
13366 -- Build the First reference we will use
13368 Left :=
13369 Make_Attribute_Reference (Loc,
13370 Prefix => New_Occurrence_Of (Ent, Loc),
13371 Attribute_Name => Name_First);
13373 if Present (Index) then
13374 Set_Expressions (Left, New_List (New_Copy (Index)));
13375 end if;
13377 -- If general value case, then do the addition of (n - 1), and
13378 -- also add the needed conversions to type Long_Long_Integer.
13380 if Present (Comp) then
13381 Left :=
13382 Make_Op_Add (Loc,
13383 Left_Opnd => Prepare_64 (Left),
13384 Right_Opnd =>
13385 Make_Op_Subtract (Loc,
13386 Left_Opnd => Prepare_64 (Comp),
13387 Right_Opnd => Make_Integer_Literal (Loc, 1)));
13388 end if;
13390 -- Build the Last reference we will use
13392 Right :=
13393 Make_Attribute_Reference (Loc,
13394 Prefix => New_Occurrence_Of (Ent, Loc),
13395 Attribute_Name => Name_Last);
13397 if Present (Index) then
13398 Set_Expressions (Right, New_List (New_Copy (Index)));
13399 end if;
13401 -- If general operand, convert Last reference to Long_Long_Integer
13403 if Present (Comp) then
13404 Right := Prepare_64 (Right);
13405 end if;
13407 -- Check for cases to optimize
13409 -- X'Length = 0 => X'First > X'Last
13410 -- X'Length < 1 => X'First > X'Last
13411 -- X'Length < n => X'First + (n - 1) > X'Last
13413 if (Is_Zero and then Op = N_Op_Eq)
13414 or else (not Is_Zero and then Op = N_Op_Lt)
13415 then
13416 Result :=
13417 Make_Op_Gt (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_Eq then
13425 Result :=
13426 Make_Op_Eq (Loc,
13427 Left_Opnd => Left,
13428 Right_Opnd => Right);
13430 -- X'Length /= 0 => X'First <= X'Last
13431 -- X'Length > 0 => X'First <= X'Last
13433 elsif Is_Zero and (Op = N_Op_Ne or else Op = N_Op_Gt) then
13434 Result :=
13435 Make_Op_Le (Loc,
13436 Left_Opnd => Left,
13437 Right_Opnd => Right);
13439 -- X'Length /= 1 => X'First /= X'Last
13440 -- X'Length /= n => X'First + (n - 1) /= X'Last
13442 elsif not Is_Zero and then Op = N_Op_Ne then
13443 Result :=
13444 Make_Op_Ne (Loc,
13445 Left_Opnd => Left,
13446 Right_Opnd => Right);
13448 -- X'Length >= 1 => X'First <= X'Last
13449 -- X'Length >= n => X'First + (n - 1) <= X'Last
13451 elsif not Is_Zero and then Op = N_Op_Ge then
13452 Result :=
13453 Make_Op_Le (Loc,
13454 Left_Opnd => Left,
13455 Right_Opnd => Right);
13457 -- X'Length > 1 => X'First < X'Last
13458 -- X'Length > n => X'First + (n = 1) < X'Last
13460 elsif not Is_Zero and then Op = N_Op_Gt then
13461 Result :=
13462 Make_Op_Lt (Loc,
13463 Left_Opnd => Left,
13464 Right_Opnd => Right);
13466 -- X'Length <= 1 => X'First >= X'Last
13467 -- X'Length <= n => X'First + (n - 1) >= X'Last
13469 elsif not Is_Zero and then Op = N_Op_Le then
13470 Result :=
13471 Make_Op_Ge (Loc,
13472 Left_Opnd => Left,
13473 Right_Opnd => Right);
13475 -- Should not happen at this stage
13477 else
13478 raise Program_Error;
13479 end if;
13481 -- Rewrite and finish up
13483 Rewrite (N, Result);
13484 Analyze_And_Resolve (N, Typ);
13485 return;
13486 end Optimize_Length_Comparison;
13488 --------------------------------
13489 -- Process_If_Case_Statements --
13490 --------------------------------
13492 procedure Process_If_Case_Statements (N : Node_Id; Stmts : List_Id) is
13493 Decl : Node_Id;
13495 begin
13496 Decl := First (Stmts);
13497 while Present (Decl) loop
13498 if Nkind (Decl) = N_Object_Declaration
13499 and then Is_Finalizable_Transient (Decl, N)
13500 then
13501 Process_Transient_In_Expression (Decl, N, Stmts);
13502 end if;
13504 Next (Decl);
13505 end loop;
13506 end Process_If_Case_Statements;
13508 -------------------------------------
13509 -- Process_Transient_In_Expression --
13510 -------------------------------------
13512 procedure Process_Transient_In_Expression
13513 (Obj_Decl : Node_Id;
13514 Expr : Node_Id;
13515 Stmts : List_Id)
13517 Loc : constant Source_Ptr := Sloc (Obj_Decl);
13518 Obj_Id : constant Entity_Id := Defining_Identifier (Obj_Decl);
13520 Hook_Context : constant Node_Id := Find_Hook_Context (Expr);
13521 -- The node on which to insert the hook as an action. This is usually
13522 -- the innermost enclosing non-transient construct.
13524 Fin_Call : Node_Id;
13525 Hook_Assign : Node_Id;
13526 Hook_Clear : Node_Id;
13527 Hook_Decl : Node_Id;
13528 Hook_Insert : Node_Id;
13529 Ptr_Decl : Node_Id;
13531 Fin_Context : Node_Id;
13532 -- The node after which to insert the finalization actions of the
13533 -- transient object.
13535 begin
13536 pragma Assert (Nkind_In (Expr, N_Case_Expression,
13537 N_Expression_With_Actions,
13538 N_If_Expression));
13540 -- When the context is a Boolean evaluation, all three nodes capture the
13541 -- result of their computation in a local temporary:
13543 -- do
13544 -- Trans_Id : Ctrl_Typ := ...;
13545 -- Result : constant Boolean := ... Trans_Id ...;
13546 -- <finalize Trans_Id>
13547 -- in Result end;
13549 -- As a result, the finalization of any transient objects can safely
13550 -- take place after the result capture.
13552 -- ??? could this be extended to elementary types?
13554 if Is_Boolean_Type (Etype (Expr)) then
13555 Fin_Context := Last (Stmts);
13557 -- Otherwise the immediate context may not be safe enough to carry
13558 -- out transient object finalization due to aliasing and nesting of
13559 -- constructs. Insert calls to [Deep_]Finalize after the innermost
13560 -- enclosing non-transient construct.
13562 else
13563 Fin_Context := Hook_Context;
13564 end if;
13566 -- Mark the transient object as successfully processed to avoid double
13567 -- finalization.
13569 Set_Is_Finalized_Transient (Obj_Id);
13571 -- Construct all the pieces necessary to hook and finalize a transient
13572 -- object.
13574 Build_Transient_Object_Statements
13575 (Obj_Decl => Obj_Decl,
13576 Fin_Call => Fin_Call,
13577 Hook_Assign => Hook_Assign,
13578 Hook_Clear => Hook_Clear,
13579 Hook_Decl => Hook_Decl,
13580 Ptr_Decl => Ptr_Decl,
13581 Finalize_Obj => False);
13583 -- Add the access type which provides a reference to the transient
13584 -- object. Generate:
13586 -- type Ptr_Typ is access all Desig_Typ;
13588 Insert_Action (Hook_Context, Ptr_Decl);
13590 -- Add the temporary which acts as a hook to the transient object.
13591 -- Generate:
13593 -- Hook : Ptr_Id := null;
13595 Insert_Action (Hook_Context, Hook_Decl);
13597 -- When the transient object is initialized by an aggregate, the hook
13598 -- must capture the object after the last aggregate assignment takes
13599 -- place. Only then is the object considered initialized. Generate:
13601 -- Hook := Ptr_Typ (Obj_Id);
13602 -- <or>
13603 -- Hook := Obj_Id'Unrestricted_Access;
13605 if Ekind_In (Obj_Id, E_Constant, E_Variable)
13606 and then Present (Last_Aggregate_Assignment (Obj_Id))
13607 then
13608 Hook_Insert := Last_Aggregate_Assignment (Obj_Id);
13610 -- Otherwise the hook seizes the related object immediately
13612 else
13613 Hook_Insert := Obj_Decl;
13614 end if;
13616 Insert_After_And_Analyze (Hook_Insert, Hook_Assign);
13618 -- When the node is part of a return statement, there is no need to
13619 -- insert a finalization call, as the general finalization mechanism
13620 -- (see Build_Finalizer) would take care of the transient object on
13621 -- subprogram exit. Note that it would also be impossible to insert the
13622 -- finalization code after the return statement as this will render it
13623 -- unreachable.
13625 if Nkind (Fin_Context) = N_Simple_Return_Statement then
13626 null;
13628 -- Finalize the hook after the context has been evaluated. Generate:
13630 -- if Hook /= null then
13631 -- [Deep_]Finalize (Hook.all);
13632 -- Hook := null;
13633 -- end if;
13635 else
13636 Insert_Action_After (Fin_Context,
13637 Make_Implicit_If_Statement (Obj_Decl,
13638 Condition =>
13639 Make_Op_Ne (Loc,
13640 Left_Opnd =>
13641 New_Occurrence_Of (Defining_Entity (Hook_Decl), Loc),
13642 Right_Opnd => Make_Null (Loc)),
13644 Then_Statements => New_List (
13645 Fin_Call,
13646 Hook_Clear)));
13647 end if;
13648 end Process_Transient_In_Expression;
13650 ------------------------
13651 -- Rewrite_Comparison --
13652 ------------------------
13654 procedure Rewrite_Comparison (N : Node_Id) is
13655 Typ : constant Entity_Id := Etype (N);
13657 False_Result : Boolean;
13658 True_Result : Boolean;
13660 begin
13661 if Nkind (N) = N_Type_Conversion then
13662 Rewrite_Comparison (Expression (N));
13663 return;
13665 elsif Nkind (N) not in N_Op_Compare then
13666 return;
13667 end if;
13669 -- Determine the potential outcome of the comparison assuming that the
13670 -- operands are valid and emit a warning when the comparison evaluates
13671 -- to True or False only in the presence of invalid values.
13673 Warn_On_Constant_Valid_Condition (N);
13675 -- Determine the potential outcome of the comparison assuming that the
13676 -- operands are not valid.
13678 Test_Comparison
13679 (Op => N,
13680 Assume_Valid => False,
13681 True_Result => True_Result,
13682 False_Result => False_Result);
13684 -- The outcome is a decisive False or True, rewrite the operator
13686 if False_Result or True_Result then
13687 Rewrite (N,
13688 Convert_To (Typ,
13689 New_Occurrence_Of (Boolean_Literals (True_Result), Sloc (N))));
13691 Analyze_And_Resolve (N, Typ);
13692 Warn_On_Known_Condition (N);
13693 end if;
13694 end Rewrite_Comparison;
13696 ----------------------------
13697 -- Safe_In_Place_Array_Op --
13698 ----------------------------
13700 function Safe_In_Place_Array_Op
13701 (Lhs : Node_Id;
13702 Op1 : Node_Id;
13703 Op2 : Node_Id) return Boolean
13705 Target : Entity_Id;
13707 function Is_Safe_Operand (Op : Node_Id) return Boolean;
13708 -- Operand is safe if it cannot overlap part of the target of the
13709 -- operation. If the operand and the target are identical, the operand
13710 -- is safe. The operand can be empty in the case of negation.
13712 function Is_Unaliased (N : Node_Id) return Boolean;
13713 -- Check that N is a stand-alone entity
13715 ------------------
13716 -- Is_Unaliased --
13717 ------------------
13719 function Is_Unaliased (N : Node_Id) return Boolean is
13720 begin
13721 return
13722 Is_Entity_Name (N)
13723 and then No (Address_Clause (Entity (N)))
13724 and then No (Renamed_Object (Entity (N)));
13725 end Is_Unaliased;
13727 ---------------------
13728 -- Is_Safe_Operand --
13729 ---------------------
13731 function Is_Safe_Operand (Op : Node_Id) return Boolean is
13732 begin
13733 if No (Op) then
13734 return True;
13736 elsif Is_Entity_Name (Op) then
13737 return Is_Unaliased (Op);
13739 elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
13740 return Is_Unaliased (Prefix (Op));
13742 elsif Nkind (Op) = N_Slice then
13743 return
13744 Is_Unaliased (Prefix (Op))
13745 and then Entity (Prefix (Op)) /= Target;
13747 elsif Nkind (Op) = N_Op_Not then
13748 return Is_Safe_Operand (Right_Opnd (Op));
13750 else
13751 return False;
13752 end if;
13753 end Is_Safe_Operand;
13755 -- Start of processing for Safe_In_Place_Array_Op
13757 begin
13758 -- Skip this processing if the component size is different from system
13759 -- storage unit (since at least for NOT this would cause problems).
13761 if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
13762 return False;
13764 -- Cannot do in place stuff if non-standard Boolean representation
13766 elsif Has_Non_Standard_Rep (Component_Type (Etype (Lhs))) then
13767 return False;
13769 elsif not Is_Unaliased (Lhs) then
13770 return False;
13772 else
13773 Target := Entity (Lhs);
13774 return Is_Safe_Operand (Op1) and then Is_Safe_Operand (Op2);
13775 end if;
13776 end Safe_In_Place_Array_Op;
13778 -----------------------
13779 -- Tagged_Membership --
13780 -----------------------
13782 -- There are two different cases to consider depending on whether the right
13783 -- operand is a class-wide type or not. If not we just compare the actual
13784 -- tag of the left expr to the target type tag:
13786 -- Left_Expr.Tag = Right_Type'Tag;
13788 -- If it is a class-wide type we use the RT function CW_Membership which is
13789 -- usually implemented by looking in the ancestor tables contained in the
13790 -- dispatch table pointed by Left_Expr.Tag for Typ'Tag
13792 -- Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
13793 -- function IW_Membership which is usually implemented by looking in the
13794 -- table of abstract interface types plus the ancestor table contained in
13795 -- the dispatch table pointed by Left_Expr.Tag for Typ'Tag
13797 procedure Tagged_Membership
13798 (N : Node_Id;
13799 SCIL_Node : out Node_Id;
13800 Result : out Node_Id)
13802 Left : constant Node_Id := Left_Opnd (N);
13803 Right : constant Node_Id := Right_Opnd (N);
13804 Loc : constant Source_Ptr := Sloc (N);
13806 Full_R_Typ : Entity_Id;
13807 Left_Type : Entity_Id;
13808 New_Node : Node_Id;
13809 Right_Type : Entity_Id;
13810 Obj_Tag : Node_Id;
13812 begin
13813 SCIL_Node := Empty;
13815 -- Handle entities from the limited view
13817 Left_Type := Available_View (Etype (Left));
13818 Right_Type := Available_View (Etype (Right));
13820 -- In the case where the type is an access type, the test is applied
13821 -- using the designated types (needed in Ada 2012 for implicit anonymous
13822 -- access conversions, for AI05-0149).
13824 if Is_Access_Type (Right_Type) then
13825 Left_Type := Designated_Type (Left_Type);
13826 Right_Type := Designated_Type (Right_Type);
13827 end if;
13829 if Is_Class_Wide_Type (Left_Type) then
13830 Left_Type := Root_Type (Left_Type);
13831 end if;
13833 if Is_Class_Wide_Type (Right_Type) then
13834 Full_R_Typ := Underlying_Type (Root_Type (Right_Type));
13835 else
13836 Full_R_Typ := Underlying_Type (Right_Type);
13837 end if;
13839 Obj_Tag :=
13840 Make_Selected_Component (Loc,
13841 Prefix => Relocate_Node (Left),
13842 Selector_Name =>
13843 New_Occurrence_Of (First_Tag_Component (Left_Type), Loc));
13845 if Is_Class_Wide_Type (Right_Type) then
13847 -- No need to issue a run-time check if we statically know that the
13848 -- result of this membership test is always true. For example,
13849 -- considering the following declarations:
13851 -- type Iface is interface;
13852 -- type T is tagged null record;
13853 -- type DT is new T and Iface with null record;
13855 -- Obj1 : T;
13856 -- Obj2 : DT;
13858 -- These membership tests are always true:
13860 -- Obj1 in T'Class
13861 -- Obj2 in T'Class;
13862 -- Obj2 in Iface'Class;
13864 -- We do not need to handle cases where the membership is illegal.
13865 -- For example:
13867 -- Obj1 in DT'Class; -- Compile time error
13868 -- Obj1 in Iface'Class; -- Compile time error
13870 if not Is_Class_Wide_Type (Left_Type)
13871 and then (Is_Ancestor (Etype (Right_Type), Left_Type,
13872 Use_Full_View => True)
13873 or else (Is_Interface (Etype (Right_Type))
13874 and then Interface_Present_In_Ancestor
13875 (Typ => Left_Type,
13876 Iface => Etype (Right_Type))))
13877 then
13878 Result := New_Occurrence_Of (Standard_True, Loc);
13879 return;
13880 end if;
13882 -- Ada 2005 (AI-251): Class-wide applied to interfaces
13884 if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
13886 -- Support to: "Iface_CW_Typ in Typ'Class"
13888 or else Is_Interface (Left_Type)
13889 then
13890 -- Issue error if IW_Membership operation not available in a
13891 -- configurable run time setting.
13893 if not RTE_Available (RE_IW_Membership) then
13894 Error_Msg_CRT
13895 ("dynamic membership test on interface types", N);
13896 Result := Empty;
13897 return;
13898 end if;
13900 Result :=
13901 Make_Function_Call (Loc,
13902 Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
13903 Parameter_Associations => New_List (
13904 Make_Attribute_Reference (Loc,
13905 Prefix => Obj_Tag,
13906 Attribute_Name => Name_Address),
13907 New_Occurrence_Of (
13908 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))),
13909 Loc)));
13911 -- Ada 95: Normal case
13913 else
13914 Build_CW_Membership (Loc,
13915 Obj_Tag_Node => Obj_Tag,
13916 Typ_Tag_Node =>
13917 New_Occurrence_Of (
13918 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc),
13919 Related_Nod => N,
13920 New_Node => New_Node);
13922 -- Generate the SCIL node for this class-wide membership test.
13923 -- Done here because the previous call to Build_CW_Membership
13924 -- relocates Obj_Tag.
13926 if Generate_SCIL then
13927 SCIL_Node := Make_SCIL_Membership_Test (Sloc (N));
13928 Set_SCIL_Entity (SCIL_Node, Etype (Right_Type));
13929 Set_SCIL_Tag_Value (SCIL_Node, Obj_Tag);
13930 end if;
13932 Result := New_Node;
13933 end if;
13935 -- Right_Type is not a class-wide type
13937 else
13938 -- No need to check the tag of the object if Right_Typ is abstract
13940 if Is_Abstract_Type (Right_Type) then
13941 Result := New_Occurrence_Of (Standard_False, Loc);
13943 else
13944 Result :=
13945 Make_Op_Eq (Loc,
13946 Left_Opnd => Obj_Tag,
13947 Right_Opnd =>
13948 New_Occurrence_Of
13949 (Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc));
13950 end if;
13951 end if;
13952 end Tagged_Membership;
13954 ------------------------------
13955 -- Unary_Op_Validity_Checks --
13956 ------------------------------
13958 procedure Unary_Op_Validity_Checks (N : Node_Id) is
13959 begin
13960 if Validity_Checks_On and Validity_Check_Operands then
13961 Ensure_Valid (Right_Opnd (N));
13962 end if;
13963 end Unary_Op_Validity_Checks;
13965 end Exp_Ch4;