[gcc]
[official-gcc.git] / gcc / ada / exp_ch4.adb
blobcc797a01a61cb2251656999dce597f22abef9156
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_Non_Binary_Modular_Op (N : Node_Id);
132 -- Generating C code convert non-binary modular arithmetic operations into
133 -- code that relies on the frontend expansion of operator Mod. No expansion
134 -- is performed if N is not a non-binary 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) then
634 Fin_Call :=
635 Make_Final_Call
636 (Obj_Ref =>
637 Make_Explicit_Dereference (Loc, New_Copy (Obj_Ref)),
638 Typ => DesigT);
640 -- Guard against a missing [Deep_]Finalize when the designated
641 -- type was not properly frozen.
643 if No (Fin_Call) then
644 Fin_Call := Make_Null_Statement (Loc);
645 end if;
647 -- When the target or profile supports deallocation, wrap the
648 -- finalization call in a block to ensure proper deallocation
649 -- even if finalization fails. Generate:
651 -- begin
652 -- <Fin_Call>
653 -- exception
654 -- when others =>
655 -- <Free_Stmt>
656 -- raise;
657 -- end;
659 if Present (Free_Stmt) then
660 Fin_Call :=
661 Make_Block_Statement (Loc,
662 Handled_Statement_Sequence =>
663 Make_Handled_Sequence_Of_Statements (Loc,
664 Statements => New_List (Fin_Call),
666 Exception_Handlers => New_List (
667 Make_Exception_Handler (Loc,
668 Exception_Choices => New_List (
669 Make_Others_Choice (Loc)),
670 Statements => New_List (
671 New_Copy_Tree (Free_Stmt),
672 Make_Raise_Statement (Loc))))));
673 end if;
675 Prepend_To (Stmts, Fin_Call);
676 end if;
678 -- Signal the accessibility failure through a Program_Error
680 Append_To (Stmts,
681 Make_Raise_Program_Error (Loc,
682 Condition => New_Occurrence_Of (Standard_True, Loc),
683 Reason => PE_Accessibility_Check_Failed));
685 -- Step 2: Create the accessibility comparison
687 -- Generate:
688 -- Ref'Tag
690 Obj_Ref :=
691 Make_Attribute_Reference (Loc,
692 Prefix => Obj_Ref,
693 Attribute_Name => Name_Tag);
695 -- For tagged types, determine the accessibility level by looking
696 -- at the type specific data of the dispatch table. Generate:
698 -- Type_Specific_Data (Address (Ref'Tag)).Access_Level
700 if Tagged_Type_Expansion then
701 Cond := Build_Get_Access_Level (Loc, Obj_Ref);
703 -- Use a runtime call to determine the accessibility level when
704 -- compiling on virtual machine targets. Generate:
706 -- Get_Access_Level (Ref'Tag)
708 else
709 Cond :=
710 Make_Function_Call (Loc,
711 Name =>
712 New_Occurrence_Of (RTE (RE_Get_Access_Level), Loc),
713 Parameter_Associations => New_List (Obj_Ref));
714 end if;
716 Cond :=
717 Make_Op_Gt (Loc,
718 Left_Opnd => Cond,
719 Right_Opnd =>
720 Make_Integer_Literal (Loc, Type_Access_Level (PtrT)));
722 -- Due to the complexity and side effects of the check, utilize an
723 -- if statement instead of the regular Program_Error circuitry.
725 Insert_Action (N,
726 Make_Implicit_If_Statement (N,
727 Condition => Cond,
728 Then_Statements => Stmts));
729 end if;
730 end Apply_Accessibility_Check;
732 -- Local variables
734 Aggr_In_Place : constant Boolean := Is_Delayed_Aggregate (Exp);
735 Indic : constant Node_Id := Subtype_Mark (Expression (N));
736 T : constant Entity_Id := Entity (Indic);
737 Adj_Call : Node_Id;
738 Node : Node_Id;
739 Tag_Assign : Node_Id;
740 Temp : Entity_Id;
741 Temp_Decl : Node_Id;
743 TagT : Entity_Id := Empty;
744 -- Type used as source for tag assignment
746 TagR : Node_Id := Empty;
747 -- Target reference for tag assignment
749 -- Start of processing for Expand_Allocator_Expression
751 begin
752 -- Handle call to C++ constructor
754 if Is_CPP_Constructor_Call (Exp) then
755 Make_CPP_Constructor_Call_In_Allocator
756 (Allocator => N,
757 Function_Call => Exp);
758 return;
759 end if;
761 -- In the case of an Ada 2012 allocator whose initial value comes from a
762 -- function call, pass "the accessibility level determined by the point
763 -- of call" (AI05-0234) to the function. Conceptually, this belongs in
764 -- Expand_Call but it couldn't be done there (because the Etype of the
765 -- allocator wasn't set then) so we generate the parameter here. See
766 -- the Boolean variable Defer in (a block within) Expand_Call.
768 if Ada_Version >= Ada_2012 and then Nkind (Exp) = N_Function_Call then
769 declare
770 Subp : Entity_Id;
772 begin
773 if Nkind (Name (Exp)) = N_Explicit_Dereference then
774 Subp := Designated_Type (Etype (Prefix (Name (Exp))));
775 else
776 Subp := Entity (Name (Exp));
777 end if;
779 Subp := Ultimate_Alias (Subp);
781 if Present (Extra_Accessibility_Of_Result (Subp)) then
782 Add_Extra_Actual_To_Call
783 (Subprogram_Call => Exp,
784 Extra_Formal => Extra_Accessibility_Of_Result (Subp),
785 Extra_Actual => Dynamic_Accessibility_Level (PtrT));
786 end if;
787 end;
788 end if;
790 -- Case of tagged type or type requiring finalization
792 if Is_Tagged_Type (T) or else Needs_Finalization (T) then
794 -- Ada 2005 (AI-318-02): If the initialization expression is a call
795 -- to a build-in-place function, then access to the allocated object
796 -- must be passed to the function. Currently we limit such functions
797 -- to those with constrained limited result subtypes, but eventually
798 -- we plan to expand the allowed forms of functions that are treated
799 -- as build-in-place.
801 if Ada_Version >= Ada_2005
802 and then Is_Build_In_Place_Function_Call (Exp)
803 then
804 Make_Build_In_Place_Call_In_Allocator (N, Exp);
805 Apply_Accessibility_Check (N, Built_In_Place => True);
806 return;
807 end if;
809 -- Actions inserted before:
810 -- Temp : constant ptr_T := new T'(Expression);
811 -- Temp._tag = T'tag; -- when not class-wide
812 -- [Deep_]Adjust (Temp.all);
814 -- We analyze by hand the new internal allocator to avoid any
815 -- recursion and inappropriate call to Initialize.
817 -- We don't want to remove side effects when the expression must be
818 -- built in place. In the case of a build-in-place function call,
819 -- that could lead to a duplication of the call, which was already
820 -- substituted for the allocator.
822 if not Aggr_In_Place then
823 Remove_Side_Effects (Exp);
824 end if;
826 Temp := Make_Temporary (Loc, 'P', N);
828 -- For a class wide allocation generate the following code:
830 -- type Equiv_Record is record ... end record;
831 -- implicit subtype CW is <Class_Wide_Subytpe>;
832 -- temp : PtrT := new CW'(CW!(expr));
834 if Is_Class_Wide_Type (T) then
835 Expand_Subtype_From_Expr (Empty, T, Indic, Exp);
837 -- Ada 2005 (AI-251): If the expression is a class-wide interface
838 -- object we generate code to move up "this" to reference the
839 -- base of the object before allocating the new object.
841 -- Note that Exp'Address is recursively expanded into a call
842 -- to Base_Address (Exp.Tag)
844 if Is_Class_Wide_Type (Etype (Exp))
845 and then Is_Interface (Etype (Exp))
846 and then Tagged_Type_Expansion
847 then
848 Set_Expression
849 (Expression (N),
850 Unchecked_Convert_To (Entity (Indic),
851 Make_Explicit_Dereference (Loc,
852 Unchecked_Convert_To (RTE (RE_Tag_Ptr),
853 Make_Attribute_Reference (Loc,
854 Prefix => Exp,
855 Attribute_Name => Name_Address)))));
856 else
857 Set_Expression
858 (Expression (N),
859 Unchecked_Convert_To (Entity (Indic), Exp));
860 end if;
862 Analyze_And_Resolve (Expression (N), Entity (Indic));
863 end if;
865 -- Processing for allocators returning non-interface types
867 if not Is_Interface (Directly_Designated_Type (PtrT)) then
868 if Aggr_In_Place then
869 Temp_Decl :=
870 Make_Object_Declaration (Loc,
871 Defining_Identifier => Temp,
872 Object_Definition => New_Occurrence_Of (PtrT, Loc),
873 Expression =>
874 Make_Allocator (Loc,
875 Expression =>
876 New_Occurrence_Of (Etype (Exp), Loc)));
878 -- Copy the Comes_From_Source flag for the allocator we just
879 -- built, since logically this allocator is a replacement of
880 -- the original allocator node. This is for proper handling of
881 -- restriction No_Implicit_Heap_Allocations.
883 Set_Comes_From_Source
884 (Expression (Temp_Decl), Comes_From_Source (N));
886 Set_No_Initialization (Expression (Temp_Decl));
887 Insert_Action (N, Temp_Decl);
889 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
890 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
892 else
893 Node := Relocate_Node (N);
894 Set_Analyzed (Node);
896 Temp_Decl :=
897 Make_Object_Declaration (Loc,
898 Defining_Identifier => Temp,
899 Constant_Present => True,
900 Object_Definition => New_Occurrence_Of (PtrT, Loc),
901 Expression => Node);
903 Insert_Action (N, Temp_Decl);
904 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
905 end if;
907 -- Ada 2005 (AI-251): Handle allocators whose designated type is an
908 -- interface type. In this case we use the type of the qualified
909 -- expression to allocate the object.
911 else
912 declare
913 Def_Id : constant Entity_Id := Make_Temporary (Loc, 'T');
914 New_Decl : Node_Id;
916 begin
917 New_Decl :=
918 Make_Full_Type_Declaration (Loc,
919 Defining_Identifier => Def_Id,
920 Type_Definition =>
921 Make_Access_To_Object_Definition (Loc,
922 All_Present => True,
923 Null_Exclusion_Present => False,
924 Constant_Present =>
925 Is_Access_Constant (Etype (N)),
926 Subtype_Indication =>
927 New_Occurrence_Of (Etype (Exp), Loc)));
929 Insert_Action (N, New_Decl);
931 -- Inherit the allocation-related attributes from the original
932 -- access type.
934 Set_Finalization_Master
935 (Def_Id, Finalization_Master (PtrT));
937 Set_Associated_Storage_Pool
938 (Def_Id, Associated_Storage_Pool (PtrT));
940 -- Declare the object using the previous type declaration
942 if Aggr_In_Place then
943 Temp_Decl :=
944 Make_Object_Declaration (Loc,
945 Defining_Identifier => Temp,
946 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
947 Expression =>
948 Make_Allocator (Loc,
949 New_Occurrence_Of (Etype (Exp), Loc)));
951 -- Copy the Comes_From_Source flag for the allocator we just
952 -- built, since logically this allocator is a replacement of
953 -- the original allocator node. This is for proper handling
954 -- of restriction No_Implicit_Heap_Allocations.
956 Set_Comes_From_Source
957 (Expression (Temp_Decl), Comes_From_Source (N));
959 Set_No_Initialization (Expression (Temp_Decl));
960 Insert_Action (N, Temp_Decl);
962 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
963 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
965 else
966 Node := Relocate_Node (N);
967 Set_Analyzed (Node);
969 Temp_Decl :=
970 Make_Object_Declaration (Loc,
971 Defining_Identifier => Temp,
972 Constant_Present => True,
973 Object_Definition => New_Occurrence_Of (Def_Id, Loc),
974 Expression => Node);
976 Insert_Action (N, Temp_Decl);
977 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
978 end if;
980 -- Generate an additional object containing the address of the
981 -- returned object. The type of this second object declaration
982 -- is the correct type required for the common processing that
983 -- is still performed by this subprogram. The displacement of
984 -- this pointer to reference the component associated with the
985 -- interface type will be done at the end of common processing.
987 New_Decl :=
988 Make_Object_Declaration (Loc,
989 Defining_Identifier => Make_Temporary (Loc, 'P'),
990 Object_Definition => New_Occurrence_Of (PtrT, Loc),
991 Expression =>
992 Unchecked_Convert_To (PtrT,
993 New_Occurrence_Of (Temp, Loc)));
995 Insert_Action (N, New_Decl);
997 Temp_Decl := New_Decl;
998 Temp := Defining_Identifier (New_Decl);
999 end;
1000 end if;
1002 -- Generate the tag assignment
1004 -- Suppress the tag assignment for VM targets because VM tags are
1005 -- represented implicitly in objects.
1007 if not Tagged_Type_Expansion then
1008 null;
1010 -- Ada 2005 (AI-251): Suppress the tag assignment with class-wide
1011 -- interface objects because in this case the tag does not change.
1013 elsif Is_Interface (Directly_Designated_Type (Etype (N))) then
1014 pragma Assert (Is_Class_Wide_Type
1015 (Directly_Designated_Type (Etype (N))));
1016 null;
1018 elsif Is_Tagged_Type (T) and then not Is_Class_Wide_Type (T) then
1019 TagT := T;
1020 TagR := New_Occurrence_Of (Temp, Loc);
1022 elsif Is_Private_Type (T)
1023 and then Is_Tagged_Type (Underlying_Type (T))
1024 then
1025 TagT := Underlying_Type (T);
1026 TagR :=
1027 Unchecked_Convert_To (Underlying_Type (T),
1028 Make_Explicit_Dereference (Loc,
1029 Prefix => New_Occurrence_Of (Temp, Loc)));
1030 end if;
1032 if Present (TagT) then
1033 declare
1034 Full_T : constant Entity_Id := Underlying_Type (TagT);
1036 begin
1037 Tag_Assign :=
1038 Make_Assignment_Statement (Loc,
1039 Name =>
1040 Make_Selected_Component (Loc,
1041 Prefix => TagR,
1042 Selector_Name =>
1043 New_Occurrence_Of
1044 (First_Tag_Component (Full_T), Loc)),
1046 Expression =>
1047 Unchecked_Convert_To (RTE (RE_Tag),
1048 New_Occurrence_Of
1049 (Elists.Node
1050 (First_Elmt (Access_Disp_Table (Full_T))), Loc)));
1051 end;
1053 -- The previous assignment has to be done in any case
1055 Set_Assignment_OK (Name (Tag_Assign));
1056 Insert_Action (N, Tag_Assign);
1057 end if;
1059 -- Generate an Adjust call if the object will be moved. In Ada 2005,
1060 -- the object may be inherently limited, in which case there is no
1061 -- Adjust procedure, and the object is built in place. In Ada 95, the
1062 -- object can be limited but not inherently limited if this allocator
1063 -- came from a return statement (we're allocating the result on the
1064 -- secondary stack). In that case, the object will be moved, so we do
1065 -- want to Adjust.
1067 if Needs_Finalization (DesigT)
1068 and then Needs_Finalization (T)
1069 and then not Aggr_In_Place
1070 and then not Is_Limited_View (T)
1071 then
1072 -- An unchecked conversion is needed in the classwide case because
1073 -- the designated type can be an ancestor of the subtype mark of
1074 -- the allocator.
1076 Adj_Call :=
1077 Make_Adjust_Call
1078 (Obj_Ref =>
1079 Unchecked_Convert_To (T,
1080 Make_Explicit_Dereference (Loc,
1081 Prefix => New_Occurrence_Of (Temp, Loc))),
1082 Typ => T);
1084 if Present (Adj_Call) then
1085 Insert_Action (N, Adj_Call);
1086 end if;
1087 end if;
1089 -- Note: the accessibility check must be inserted after the call to
1090 -- [Deep_]Adjust to ensure proper completion of the assignment.
1092 Apply_Accessibility_Check (Temp);
1094 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1095 Analyze_And_Resolve (N, PtrT);
1097 -- Ada 2005 (AI-251): Displace the pointer to reference the record
1098 -- component containing the secondary dispatch table of the interface
1099 -- type.
1101 if Is_Interface (Directly_Designated_Type (PtrT)) then
1102 Displace_Allocator_Pointer (N);
1103 end if;
1105 -- Always force the generation of a temporary for aggregates when
1106 -- generating C code, to simplify the work in the code generator.
1108 elsif Aggr_In_Place
1109 or else (Modify_Tree_For_C and then Nkind (Exp) = N_Aggregate)
1110 then
1111 Temp := Make_Temporary (Loc, 'P', N);
1112 Temp_Decl :=
1113 Make_Object_Declaration (Loc,
1114 Defining_Identifier => Temp,
1115 Object_Definition => New_Occurrence_Of (PtrT, Loc),
1116 Expression =>
1117 Make_Allocator (Loc,
1118 Expression => New_Occurrence_Of (Etype (Exp), Loc)));
1120 -- Copy the Comes_From_Source flag for the allocator we just built,
1121 -- since logically this allocator is a replacement of the original
1122 -- allocator node. This is for proper handling of restriction
1123 -- No_Implicit_Heap_Allocations.
1125 Set_Comes_From_Source
1126 (Expression (Temp_Decl), Comes_From_Source (N));
1128 Set_No_Initialization (Expression (Temp_Decl));
1129 Insert_Action (N, Temp_Decl);
1131 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
1132 Convert_Aggr_In_Allocator (N, Temp_Decl, Exp);
1134 Rewrite (N, New_Occurrence_Of (Temp, Loc));
1135 Analyze_And_Resolve (N, PtrT);
1137 elsif Is_Access_Type (T) and then Can_Never_Be_Null (T) then
1138 Install_Null_Excluding_Check (Exp);
1140 elsif Is_Access_Type (DesigT)
1141 and then Nkind (Exp) = N_Allocator
1142 and then Nkind (Expression (Exp)) /= N_Qualified_Expression
1143 then
1144 -- Apply constraint to designated subtype indication
1146 Apply_Constraint_Check
1147 (Expression (Exp), Designated_Type (DesigT), No_Sliding => True);
1149 if Nkind (Expression (Exp)) = N_Raise_Constraint_Error then
1151 -- Propagate constraint_error to enclosing allocator
1153 Rewrite (Exp, New_Copy (Expression (Exp)));
1154 end if;
1156 else
1157 Build_Allocate_Deallocate_Proc (N, True);
1159 -- If we have:
1160 -- type A is access T1;
1161 -- X : A := new T2'(...);
1162 -- T1 and T2 can be different subtypes, and we might need to check
1163 -- both constraints. First check against the type of the qualified
1164 -- expression.
1166 Apply_Constraint_Check (Exp, T, No_Sliding => True);
1168 if Do_Range_Check (Exp) then
1169 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1170 end if;
1172 -- A check is also needed in cases where the designated subtype is
1173 -- constrained and differs from the subtype given in the qualified
1174 -- expression. Note that the check on the qualified expression does
1175 -- not allow sliding, but this check does (a relaxation from Ada 83).
1177 if Is_Constrained (DesigT)
1178 and then not Subtypes_Statically_Match (T, DesigT)
1179 then
1180 Apply_Constraint_Check
1181 (Exp, DesigT, No_Sliding => False);
1183 if Do_Range_Check (Exp) then
1184 Generate_Range_Check (Exp, DesigT, CE_Range_Check_Failed);
1185 end if;
1186 end if;
1188 -- For an access to unconstrained packed array, GIGI needs to see an
1189 -- expression with a constrained subtype in order to compute the
1190 -- proper size for the allocator.
1192 if Is_Array_Type (T)
1193 and then not Is_Constrained (T)
1194 and then Is_Packed (T)
1195 then
1196 declare
1197 ConstrT : constant Entity_Id := Make_Temporary (Loc, 'A');
1198 Internal_Exp : constant Node_Id := Relocate_Node (Exp);
1199 begin
1200 Insert_Action (Exp,
1201 Make_Subtype_Declaration (Loc,
1202 Defining_Identifier => ConstrT,
1203 Subtype_Indication =>
1204 Make_Subtype_From_Expr (Internal_Exp, T)));
1205 Freeze_Itype (ConstrT, Exp);
1206 Rewrite (Exp, OK_Convert_To (ConstrT, Internal_Exp));
1207 end;
1208 end if;
1210 -- Ada 2005 (AI-318-02): If the initialization expression is a call
1211 -- to a build-in-place function, then access to the allocated object
1212 -- must be passed to the function. Currently we limit such functions
1213 -- to those with constrained limited result subtypes, but eventually
1214 -- we plan to expand the allowed forms of functions that are treated
1215 -- as build-in-place.
1217 if Ada_Version >= Ada_2005
1218 and then Is_Build_In_Place_Function_Call (Exp)
1219 then
1220 Make_Build_In_Place_Call_In_Allocator (N, Exp);
1221 end if;
1222 end if;
1224 exception
1225 when RE_Not_Available =>
1226 return;
1227 end Expand_Allocator_Expression;
1229 -----------------------------
1230 -- Expand_Array_Comparison --
1231 -----------------------------
1233 -- Expansion is only required in the case of array types. For the unpacked
1234 -- case, an appropriate runtime routine is called. For packed cases, and
1235 -- also in some other cases where a runtime routine cannot be called, the
1236 -- form of the expansion is:
1238 -- [body for greater_nn; boolean_expression]
1240 -- The body is built by Make_Array_Comparison_Op, and the form of the
1241 -- Boolean expression depends on the operator involved.
1243 procedure Expand_Array_Comparison (N : Node_Id) is
1244 Loc : constant Source_Ptr := Sloc (N);
1245 Op1 : Node_Id := Left_Opnd (N);
1246 Op2 : Node_Id := Right_Opnd (N);
1247 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
1248 Ctyp : constant Entity_Id := Component_Type (Typ1);
1250 Expr : Node_Id;
1251 Func_Body : Node_Id;
1252 Func_Name : Entity_Id;
1254 Comp : RE_Id;
1256 Byte_Addressable : constant Boolean := System_Storage_Unit = Byte'Size;
1257 -- True for byte addressable target
1259 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean;
1260 -- Returns True if the length of the given operand is known to be less
1261 -- than 4. Returns False if this length is known to be four or greater
1262 -- or is not known at compile time.
1264 ------------------------
1265 -- Length_Less_Than_4 --
1266 ------------------------
1268 function Length_Less_Than_4 (Opnd : Node_Id) return Boolean is
1269 Otyp : constant Entity_Id := Etype (Opnd);
1271 begin
1272 if Ekind (Otyp) = E_String_Literal_Subtype then
1273 return String_Literal_Length (Otyp) < 4;
1275 else
1276 declare
1277 Ityp : constant Entity_Id := Etype (First_Index (Otyp));
1278 Lo : constant Node_Id := Type_Low_Bound (Ityp);
1279 Hi : constant Node_Id := Type_High_Bound (Ityp);
1280 Lov : Uint;
1281 Hiv : Uint;
1283 begin
1284 if Compile_Time_Known_Value (Lo) then
1285 Lov := Expr_Value (Lo);
1286 else
1287 return False;
1288 end if;
1290 if Compile_Time_Known_Value (Hi) then
1291 Hiv := Expr_Value (Hi);
1292 else
1293 return False;
1294 end if;
1296 return Hiv < Lov + 3;
1297 end;
1298 end if;
1299 end Length_Less_Than_4;
1301 -- Start of processing for Expand_Array_Comparison
1303 begin
1304 -- Deal first with unpacked case, where we can call a runtime routine
1305 -- except that we avoid this for targets for which are not addressable
1306 -- by bytes.
1308 if not Is_Bit_Packed_Array (Typ1)
1309 and then Byte_Addressable
1310 then
1311 -- The call we generate is:
1313 -- Compare_Array_xn[_Unaligned]
1314 -- (left'address, right'address, left'length, right'length) <op> 0
1316 -- x = U for unsigned, S for signed
1317 -- n = 8,16,32,64 for component size
1318 -- Add _Unaligned if length < 4 and component size is 8.
1319 -- <op> is the standard comparison operator
1321 if Component_Size (Typ1) = 8 then
1322 if Length_Less_Than_4 (Op1)
1323 or else
1324 Length_Less_Than_4 (Op2)
1325 then
1326 if Is_Unsigned_Type (Ctyp) then
1327 Comp := RE_Compare_Array_U8_Unaligned;
1328 else
1329 Comp := RE_Compare_Array_S8_Unaligned;
1330 end if;
1332 else
1333 if Is_Unsigned_Type (Ctyp) then
1334 Comp := RE_Compare_Array_U8;
1335 else
1336 Comp := RE_Compare_Array_S8;
1337 end if;
1338 end if;
1340 elsif Component_Size (Typ1) = 16 then
1341 if Is_Unsigned_Type (Ctyp) then
1342 Comp := RE_Compare_Array_U16;
1343 else
1344 Comp := RE_Compare_Array_S16;
1345 end if;
1347 elsif Component_Size (Typ1) = 32 then
1348 if Is_Unsigned_Type (Ctyp) then
1349 Comp := RE_Compare_Array_U32;
1350 else
1351 Comp := RE_Compare_Array_S32;
1352 end if;
1354 else pragma Assert (Component_Size (Typ1) = 64);
1355 if Is_Unsigned_Type (Ctyp) then
1356 Comp := RE_Compare_Array_U64;
1357 else
1358 Comp := RE_Compare_Array_S64;
1359 end if;
1360 end if;
1362 if RTE_Available (Comp) then
1364 -- Expand to a call only if the runtime function is available,
1365 -- otherwise fall back to inline code.
1367 Remove_Side_Effects (Op1, Name_Req => True);
1368 Remove_Side_Effects (Op2, Name_Req => True);
1370 Rewrite (Op1,
1371 Make_Function_Call (Sloc (Op1),
1372 Name => New_Occurrence_Of (RTE (Comp), Loc),
1374 Parameter_Associations => New_List (
1375 Make_Attribute_Reference (Loc,
1376 Prefix => Relocate_Node (Op1),
1377 Attribute_Name => Name_Address),
1379 Make_Attribute_Reference (Loc,
1380 Prefix => Relocate_Node (Op2),
1381 Attribute_Name => Name_Address),
1383 Make_Attribute_Reference (Loc,
1384 Prefix => Relocate_Node (Op1),
1385 Attribute_Name => Name_Length),
1387 Make_Attribute_Reference (Loc,
1388 Prefix => Relocate_Node (Op2),
1389 Attribute_Name => Name_Length))));
1391 Rewrite (Op2,
1392 Make_Integer_Literal (Sloc (Op2),
1393 Intval => Uint_0));
1395 Analyze_And_Resolve (Op1, Standard_Integer);
1396 Analyze_And_Resolve (Op2, Standard_Integer);
1397 return;
1398 end if;
1399 end if;
1401 -- Cases where we cannot make runtime call
1403 -- For (a <= b) we convert to not (a > b)
1405 if Chars (N) = Name_Op_Le then
1406 Rewrite (N,
1407 Make_Op_Not (Loc,
1408 Right_Opnd =>
1409 Make_Op_Gt (Loc,
1410 Left_Opnd => Op1,
1411 Right_Opnd => Op2)));
1412 Analyze_And_Resolve (N, Standard_Boolean);
1413 return;
1415 -- For < the Boolean expression is
1416 -- greater__nn (op2, op1)
1418 elsif Chars (N) = Name_Op_Lt then
1419 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1421 -- Switch operands
1423 Op1 := Right_Opnd (N);
1424 Op2 := Left_Opnd (N);
1426 -- For (a >= b) we convert to not (a < b)
1428 elsif Chars (N) = Name_Op_Ge then
1429 Rewrite (N,
1430 Make_Op_Not (Loc,
1431 Right_Opnd =>
1432 Make_Op_Lt (Loc,
1433 Left_Opnd => Op1,
1434 Right_Opnd => Op2)));
1435 Analyze_And_Resolve (N, Standard_Boolean);
1436 return;
1438 -- For > the Boolean expression is
1439 -- greater__nn (op1, op2)
1441 else
1442 pragma Assert (Chars (N) = Name_Op_Gt);
1443 Func_Body := Make_Array_Comparison_Op (Typ1, N);
1444 end if;
1446 Func_Name := Defining_Unit_Name (Specification (Func_Body));
1447 Expr :=
1448 Make_Function_Call (Loc,
1449 Name => New_Occurrence_Of (Func_Name, Loc),
1450 Parameter_Associations => New_List (Op1, Op2));
1452 Insert_Action (N, Func_Body);
1453 Rewrite (N, Expr);
1454 Analyze_And_Resolve (N, Standard_Boolean);
1455 end Expand_Array_Comparison;
1457 ---------------------------
1458 -- Expand_Array_Equality --
1459 ---------------------------
1461 -- Expand an equality function for multi-dimensional arrays. Here is an
1462 -- example of such a function for Nb_Dimension = 2
1464 -- function Enn (A : atyp; B : btyp) return boolean is
1465 -- begin
1466 -- if (A'length (1) = 0 or else A'length (2) = 0)
1467 -- and then
1468 -- (B'length (1) = 0 or else B'length (2) = 0)
1469 -- then
1470 -- return True; -- RM 4.5.2(22)
1471 -- end if;
1473 -- if A'length (1) /= B'length (1)
1474 -- or else
1475 -- A'length (2) /= B'length (2)
1476 -- then
1477 -- return False; -- RM 4.5.2(23)
1478 -- end if;
1480 -- declare
1481 -- A1 : Index_T1 := A'first (1);
1482 -- B1 : Index_T1 := B'first (1);
1483 -- begin
1484 -- loop
1485 -- declare
1486 -- A2 : Index_T2 := A'first (2);
1487 -- B2 : Index_T2 := B'first (2);
1488 -- begin
1489 -- loop
1490 -- if A (A1, A2) /= B (B1, B2) then
1491 -- return False;
1492 -- end if;
1494 -- exit when A2 = A'last (2);
1495 -- A2 := Index_T2'succ (A2);
1496 -- B2 := Index_T2'succ (B2);
1497 -- end loop;
1498 -- end;
1500 -- exit when A1 = A'last (1);
1501 -- A1 := Index_T1'succ (A1);
1502 -- B1 := Index_T1'succ (B1);
1503 -- end loop;
1504 -- end;
1506 -- return true;
1507 -- end Enn;
1509 -- Note on the formal types used (atyp and btyp). If either of the arrays
1510 -- is of a private type, we use the underlying type, and do an unchecked
1511 -- conversion of the actual. If either of the arrays has a bound depending
1512 -- on a discriminant, then we use the base type since otherwise we have an
1513 -- escaped discriminant in the function.
1515 -- If both arrays are constrained and have the same bounds, we can generate
1516 -- a loop with an explicit iteration scheme using a 'Range attribute over
1517 -- the first array.
1519 function Expand_Array_Equality
1520 (Nod : Node_Id;
1521 Lhs : Node_Id;
1522 Rhs : Node_Id;
1523 Bodies : List_Id;
1524 Typ : Entity_Id) return Node_Id
1526 Loc : constant Source_Ptr := Sloc (Nod);
1527 Decls : constant List_Id := New_List;
1528 Index_List1 : constant List_Id := New_List;
1529 Index_List2 : constant List_Id := New_List;
1531 Actuals : List_Id;
1532 Formals : List_Id;
1533 Func_Name : Entity_Id;
1534 Func_Body : Node_Id;
1536 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
1537 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
1539 Ltyp : Entity_Id;
1540 Rtyp : Entity_Id;
1541 -- The parameter types to be used for the formals
1543 function Arr_Attr
1544 (Arr : Entity_Id;
1545 Nam : Name_Id;
1546 Num : Int) return Node_Id;
1547 -- This builds the attribute reference Arr'Nam (Expr)
1549 function Component_Equality (Typ : Entity_Id) return Node_Id;
1550 -- Create one statement to compare corresponding components, designated
1551 -- by a full set of indexes.
1553 function Get_Arg_Type (N : Node_Id) return Entity_Id;
1554 -- Given one of the arguments, computes the appropriate type to be used
1555 -- for that argument in the corresponding function formal
1557 function Handle_One_Dimension
1558 (N : Int;
1559 Index : Node_Id) return Node_Id;
1560 -- This procedure returns the following code
1562 -- declare
1563 -- Bn : Index_T := B'First (N);
1564 -- begin
1565 -- loop
1566 -- xxx
1567 -- exit when An = A'Last (N);
1568 -- An := Index_T'Succ (An)
1569 -- Bn := Index_T'Succ (Bn)
1570 -- end loop;
1571 -- end;
1573 -- If both indexes are constrained and identical, the procedure
1574 -- returns a simpler loop:
1576 -- for An in A'Range (N) loop
1577 -- xxx
1578 -- end loop
1580 -- N is the dimension for which we are generating a loop. Index is the
1581 -- N'th index node, whose Etype is Index_Type_n in the above code. The
1582 -- xxx statement is either the loop or declare for the next dimension
1583 -- or if this is the last dimension the comparison of corresponding
1584 -- components of the arrays.
1586 -- The actual way the code works is to return the comparison of
1587 -- corresponding components for the N+1 call. That's neater.
1589 function Test_Empty_Arrays return Node_Id;
1590 -- This function constructs the test for both arrays being empty
1591 -- (A'length (1) = 0 or else A'length (2) = 0 or else ...)
1592 -- and then
1593 -- (B'length (1) = 0 or else B'length (2) = 0 or else ...)
1595 function Test_Lengths_Correspond return Node_Id;
1596 -- This function constructs the test for arrays having different lengths
1597 -- in at least one index position, in which case the resulting code is:
1599 -- A'length (1) /= B'length (1)
1600 -- or else
1601 -- A'length (2) /= B'length (2)
1602 -- or else
1603 -- ...
1605 --------------
1606 -- Arr_Attr --
1607 --------------
1609 function Arr_Attr
1610 (Arr : Entity_Id;
1611 Nam : Name_Id;
1612 Num : Int) return Node_Id
1614 begin
1615 return
1616 Make_Attribute_Reference (Loc,
1617 Attribute_Name => Nam,
1618 Prefix => New_Occurrence_Of (Arr, Loc),
1619 Expressions => New_List (Make_Integer_Literal (Loc, Num)));
1620 end Arr_Attr;
1622 ------------------------
1623 -- Component_Equality --
1624 ------------------------
1626 function Component_Equality (Typ : Entity_Id) return Node_Id is
1627 Test : Node_Id;
1628 L, R : Node_Id;
1630 begin
1631 -- if a(i1...) /= b(j1...) then return false; end if;
1633 L :=
1634 Make_Indexed_Component (Loc,
1635 Prefix => Make_Identifier (Loc, Chars (A)),
1636 Expressions => Index_List1);
1638 R :=
1639 Make_Indexed_Component (Loc,
1640 Prefix => Make_Identifier (Loc, Chars (B)),
1641 Expressions => Index_List2);
1643 Test := Expand_Composite_Equality
1644 (Nod, Component_Type (Typ), L, R, Decls);
1646 -- If some (sub)component is an unchecked_union, the whole operation
1647 -- will raise program error.
1649 if Nkind (Test) = N_Raise_Program_Error then
1651 -- This node is going to be inserted at a location where a
1652 -- statement is expected: clear its Etype so analysis will set
1653 -- it to the expected Standard_Void_Type.
1655 Set_Etype (Test, Empty);
1656 return Test;
1658 else
1659 return
1660 Make_Implicit_If_Statement (Nod,
1661 Condition => Make_Op_Not (Loc, Right_Opnd => Test),
1662 Then_Statements => New_List (
1663 Make_Simple_Return_Statement (Loc,
1664 Expression => New_Occurrence_Of (Standard_False, Loc))));
1665 end if;
1666 end Component_Equality;
1668 ------------------
1669 -- Get_Arg_Type --
1670 ------------------
1672 function Get_Arg_Type (N : Node_Id) return Entity_Id is
1673 T : Entity_Id;
1674 X : Node_Id;
1676 begin
1677 T := Etype (N);
1679 if No (T) then
1680 return Typ;
1682 else
1683 T := Underlying_Type (T);
1685 X := First_Index (T);
1686 while Present (X) loop
1687 if Denotes_Discriminant (Type_Low_Bound (Etype (X)))
1688 or else
1689 Denotes_Discriminant (Type_High_Bound (Etype (X)))
1690 then
1691 T := Base_Type (T);
1692 exit;
1693 end if;
1695 Next_Index (X);
1696 end loop;
1698 return T;
1699 end if;
1700 end Get_Arg_Type;
1702 --------------------------
1703 -- Handle_One_Dimension --
1704 ---------------------------
1706 function Handle_One_Dimension
1707 (N : Int;
1708 Index : Node_Id) return Node_Id
1710 Need_Separate_Indexes : constant Boolean :=
1711 Ltyp /= Rtyp or else not Is_Constrained (Ltyp);
1712 -- If the index types are identical, and we are working with
1713 -- constrained types, then we can use the same index for both
1714 -- of the arrays.
1716 An : constant Entity_Id := Make_Temporary (Loc, 'A');
1718 Bn : Entity_Id;
1719 Index_T : Entity_Id;
1720 Stm_List : List_Id;
1721 Loop_Stm : Node_Id;
1723 begin
1724 if N > Number_Dimensions (Ltyp) then
1725 return Component_Equality (Ltyp);
1726 end if;
1728 -- Case where we generate a loop
1730 Index_T := Base_Type (Etype (Index));
1732 if Need_Separate_Indexes then
1733 Bn := Make_Temporary (Loc, 'B');
1734 else
1735 Bn := An;
1736 end if;
1738 Append (New_Occurrence_Of (An, Loc), Index_List1);
1739 Append (New_Occurrence_Of (Bn, Loc), Index_List2);
1741 Stm_List := New_List (
1742 Handle_One_Dimension (N + 1, Next_Index (Index)));
1744 if Need_Separate_Indexes then
1746 -- Generate guard for loop, followed by increments of indexes
1748 Append_To (Stm_List,
1749 Make_Exit_Statement (Loc,
1750 Condition =>
1751 Make_Op_Eq (Loc,
1752 Left_Opnd => New_Occurrence_Of (An, Loc),
1753 Right_Opnd => Arr_Attr (A, Name_Last, N))));
1755 Append_To (Stm_List,
1756 Make_Assignment_Statement (Loc,
1757 Name => New_Occurrence_Of (An, Loc),
1758 Expression =>
1759 Make_Attribute_Reference (Loc,
1760 Prefix => New_Occurrence_Of (Index_T, Loc),
1761 Attribute_Name => Name_Succ,
1762 Expressions => New_List (
1763 New_Occurrence_Of (An, Loc)))));
1765 Append_To (Stm_List,
1766 Make_Assignment_Statement (Loc,
1767 Name => New_Occurrence_Of (Bn, Loc),
1768 Expression =>
1769 Make_Attribute_Reference (Loc,
1770 Prefix => New_Occurrence_Of (Index_T, Loc),
1771 Attribute_Name => Name_Succ,
1772 Expressions => New_List (
1773 New_Occurrence_Of (Bn, Loc)))));
1774 end if;
1776 -- If separate indexes, we need a declare block for An and Bn, and a
1777 -- loop without an iteration scheme.
1779 if Need_Separate_Indexes then
1780 Loop_Stm :=
1781 Make_Implicit_Loop_Statement (Nod, Statements => Stm_List);
1783 return
1784 Make_Block_Statement (Loc,
1785 Declarations => New_List (
1786 Make_Object_Declaration (Loc,
1787 Defining_Identifier => An,
1788 Object_Definition => New_Occurrence_Of (Index_T, Loc),
1789 Expression => Arr_Attr (A, Name_First, N)),
1791 Make_Object_Declaration (Loc,
1792 Defining_Identifier => Bn,
1793 Object_Definition => New_Occurrence_Of (Index_T, Loc),
1794 Expression => Arr_Attr (B, Name_First, N))),
1796 Handled_Statement_Sequence =>
1797 Make_Handled_Sequence_Of_Statements (Loc,
1798 Statements => New_List (Loop_Stm)));
1800 -- If no separate indexes, return loop statement with explicit
1801 -- iteration scheme on its own
1803 else
1804 Loop_Stm :=
1805 Make_Implicit_Loop_Statement (Nod,
1806 Statements => Stm_List,
1807 Iteration_Scheme =>
1808 Make_Iteration_Scheme (Loc,
1809 Loop_Parameter_Specification =>
1810 Make_Loop_Parameter_Specification (Loc,
1811 Defining_Identifier => An,
1812 Discrete_Subtype_Definition =>
1813 Arr_Attr (A, Name_Range, N))));
1814 return Loop_Stm;
1815 end if;
1816 end Handle_One_Dimension;
1818 -----------------------
1819 -- Test_Empty_Arrays --
1820 -----------------------
1822 function Test_Empty_Arrays return Node_Id is
1823 Alist : Node_Id;
1824 Blist : Node_Id;
1826 Atest : Node_Id;
1827 Btest : Node_Id;
1829 begin
1830 Alist := Empty;
1831 Blist := Empty;
1832 for J in 1 .. Number_Dimensions (Ltyp) loop
1833 Atest :=
1834 Make_Op_Eq (Loc,
1835 Left_Opnd => Arr_Attr (A, Name_Length, J),
1836 Right_Opnd => Make_Integer_Literal (Loc, 0));
1838 Btest :=
1839 Make_Op_Eq (Loc,
1840 Left_Opnd => Arr_Attr (B, Name_Length, J),
1841 Right_Opnd => Make_Integer_Literal (Loc, 0));
1843 if No (Alist) then
1844 Alist := Atest;
1845 Blist := Btest;
1847 else
1848 Alist :=
1849 Make_Or_Else (Loc,
1850 Left_Opnd => Relocate_Node (Alist),
1851 Right_Opnd => Atest);
1853 Blist :=
1854 Make_Or_Else (Loc,
1855 Left_Opnd => Relocate_Node (Blist),
1856 Right_Opnd => Btest);
1857 end if;
1858 end loop;
1860 return
1861 Make_And_Then (Loc,
1862 Left_Opnd => Alist,
1863 Right_Opnd => Blist);
1864 end Test_Empty_Arrays;
1866 -----------------------------
1867 -- Test_Lengths_Correspond --
1868 -----------------------------
1870 function Test_Lengths_Correspond return Node_Id is
1871 Result : Node_Id;
1872 Rtest : Node_Id;
1874 begin
1875 Result := Empty;
1876 for J in 1 .. Number_Dimensions (Ltyp) loop
1877 Rtest :=
1878 Make_Op_Ne (Loc,
1879 Left_Opnd => Arr_Attr (A, Name_Length, J),
1880 Right_Opnd => Arr_Attr (B, Name_Length, J));
1882 if No (Result) then
1883 Result := Rtest;
1884 else
1885 Result :=
1886 Make_Or_Else (Loc,
1887 Left_Opnd => Relocate_Node (Result),
1888 Right_Opnd => Rtest);
1889 end if;
1890 end loop;
1892 return Result;
1893 end Test_Lengths_Correspond;
1895 -- Start of processing for Expand_Array_Equality
1897 begin
1898 Ltyp := Get_Arg_Type (Lhs);
1899 Rtyp := Get_Arg_Type (Rhs);
1901 -- For now, if the argument types are not the same, go to the base type,
1902 -- since the code assumes that the formals have the same type. This is
1903 -- fixable in future ???
1905 if Ltyp /= Rtyp then
1906 Ltyp := Base_Type (Ltyp);
1907 Rtyp := Base_Type (Rtyp);
1908 pragma Assert (Ltyp = Rtyp);
1909 end if;
1911 -- Build list of formals for function
1913 Formals := New_List (
1914 Make_Parameter_Specification (Loc,
1915 Defining_Identifier => A,
1916 Parameter_Type => New_Occurrence_Of (Ltyp, Loc)),
1918 Make_Parameter_Specification (Loc,
1919 Defining_Identifier => B,
1920 Parameter_Type => New_Occurrence_Of (Rtyp, Loc)));
1922 Func_Name := Make_Temporary (Loc, 'E');
1924 -- Build statement sequence for function
1926 Func_Body :=
1927 Make_Subprogram_Body (Loc,
1928 Specification =>
1929 Make_Function_Specification (Loc,
1930 Defining_Unit_Name => Func_Name,
1931 Parameter_Specifications => Formals,
1932 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
1934 Declarations => Decls,
1936 Handled_Statement_Sequence =>
1937 Make_Handled_Sequence_Of_Statements (Loc,
1938 Statements => New_List (
1940 Make_Implicit_If_Statement (Nod,
1941 Condition => Test_Empty_Arrays,
1942 Then_Statements => New_List (
1943 Make_Simple_Return_Statement (Loc,
1944 Expression =>
1945 New_Occurrence_Of (Standard_True, Loc)))),
1947 Make_Implicit_If_Statement (Nod,
1948 Condition => Test_Lengths_Correspond,
1949 Then_Statements => New_List (
1950 Make_Simple_Return_Statement (Loc,
1951 Expression => New_Occurrence_Of (Standard_False, Loc)))),
1953 Handle_One_Dimension (1, First_Index (Ltyp)),
1955 Make_Simple_Return_Statement (Loc,
1956 Expression => New_Occurrence_Of (Standard_True, Loc)))));
1958 Set_Has_Completion (Func_Name, True);
1959 Set_Is_Inlined (Func_Name);
1961 -- If the array type is distinct from the type of the arguments, it
1962 -- is the full view of a private type. Apply an unchecked conversion
1963 -- to insure that analysis of the call succeeds.
1965 declare
1966 L, R : Node_Id;
1968 begin
1969 L := Lhs;
1970 R := Rhs;
1972 if No (Etype (Lhs))
1973 or else Base_Type (Etype (Lhs)) /= Base_Type (Ltyp)
1974 then
1975 L := OK_Convert_To (Ltyp, Lhs);
1976 end if;
1978 if No (Etype (Rhs))
1979 or else Base_Type (Etype (Rhs)) /= Base_Type (Rtyp)
1980 then
1981 R := OK_Convert_To (Rtyp, Rhs);
1982 end if;
1984 Actuals := New_List (L, R);
1985 end;
1987 Append_To (Bodies, Func_Body);
1989 return
1990 Make_Function_Call (Loc,
1991 Name => New_Occurrence_Of (Func_Name, Loc),
1992 Parameter_Associations => Actuals);
1993 end Expand_Array_Equality;
1995 -----------------------------
1996 -- Expand_Boolean_Operator --
1997 -----------------------------
1999 -- Note that we first get the actual subtypes of the operands, since we
2000 -- always want to deal with types that have bounds.
2002 procedure Expand_Boolean_Operator (N : Node_Id) is
2003 Typ : constant Entity_Id := Etype (N);
2005 begin
2006 -- Special case of bit packed array where both operands are known to be
2007 -- properly aligned. In this case we use an efficient run time routine
2008 -- to carry out the operation (see System.Bit_Ops).
2010 if Is_Bit_Packed_Array (Typ)
2011 and then not Is_Possibly_Unaligned_Object (Left_Opnd (N))
2012 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
2013 then
2014 Expand_Packed_Boolean_Operator (N);
2015 return;
2016 end if;
2018 -- For the normal non-packed case, the general expansion is to build
2019 -- function for carrying out the comparison (use Make_Boolean_Array_Op)
2020 -- and then inserting it into the tree. The original operator node is
2021 -- then rewritten as a call to this function. We also use this in the
2022 -- packed case if either operand is a possibly unaligned object.
2024 declare
2025 Loc : constant Source_Ptr := Sloc (N);
2026 L : constant Node_Id := Relocate_Node (Left_Opnd (N));
2027 R : constant Node_Id := Relocate_Node (Right_Opnd (N));
2028 Func_Body : Node_Id;
2029 Func_Name : Entity_Id;
2031 begin
2032 Convert_To_Actual_Subtype (L);
2033 Convert_To_Actual_Subtype (R);
2034 Ensure_Defined (Etype (L), N);
2035 Ensure_Defined (Etype (R), N);
2036 Apply_Length_Check (R, Etype (L));
2038 if Nkind (N) = N_Op_Xor then
2039 Silly_Boolean_Array_Xor_Test (N, Etype (L));
2040 end if;
2042 if Nkind (Parent (N)) = N_Assignment_Statement
2043 and then Safe_In_Place_Array_Op (Name (Parent (N)), L, R)
2044 then
2045 Build_Boolean_Array_Proc_Call (Parent (N), L, R);
2047 elsif Nkind (Parent (N)) = N_Op_Not
2048 and then Nkind (N) = N_Op_And
2049 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
2050 and then Safe_In_Place_Array_Op (Name (Parent (Parent (N))), L, R)
2051 then
2052 return;
2053 else
2055 Func_Body := Make_Boolean_Array_Op (Etype (L), N);
2056 Func_Name := Defining_Unit_Name (Specification (Func_Body));
2057 Insert_Action (N, Func_Body);
2059 -- Now rewrite the expression with a call
2061 Rewrite (N,
2062 Make_Function_Call (Loc,
2063 Name => New_Occurrence_Of (Func_Name, Loc),
2064 Parameter_Associations =>
2065 New_List (
2067 Make_Type_Conversion
2068 (Loc, New_Occurrence_Of (Etype (L), Loc), R))));
2070 Analyze_And_Resolve (N, Typ);
2071 end if;
2072 end;
2073 end Expand_Boolean_Operator;
2075 ------------------------------------------------
2076 -- Expand_Compare_Minimize_Eliminate_Overflow --
2077 ------------------------------------------------
2079 procedure Expand_Compare_Minimize_Eliminate_Overflow (N : Node_Id) is
2080 Loc : constant Source_Ptr := Sloc (N);
2082 Result_Type : constant Entity_Id := Etype (N);
2083 -- Capture result type (could be a derived boolean type)
2085 Llo, Lhi : Uint;
2086 Rlo, Rhi : Uint;
2088 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
2089 -- Entity for Long_Long_Integer'Base
2091 Check : constant Overflow_Mode_Type := Overflow_Check_Mode;
2092 -- Current overflow checking mode
2094 procedure Set_True;
2095 procedure Set_False;
2096 -- These procedures rewrite N with an occurrence of Standard_True or
2097 -- Standard_False, and then makes a call to Warn_On_Known_Condition.
2099 ---------------
2100 -- Set_False --
2101 ---------------
2103 procedure Set_False is
2104 begin
2105 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
2106 Warn_On_Known_Condition (N);
2107 end Set_False;
2109 --------------
2110 -- Set_True --
2111 --------------
2113 procedure Set_True is
2114 begin
2115 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
2116 Warn_On_Known_Condition (N);
2117 end Set_True;
2119 -- Start of processing for Expand_Compare_Minimize_Eliminate_Overflow
2121 begin
2122 -- Nothing to do unless we have a comparison operator with operands
2123 -- that are signed integer types, and we are operating in either
2124 -- MINIMIZED or ELIMINATED overflow checking mode.
2126 if Nkind (N) not in N_Op_Compare
2127 or else Check not in Minimized_Or_Eliminated
2128 or else not Is_Signed_Integer_Type (Etype (Left_Opnd (N)))
2129 then
2130 return;
2131 end if;
2133 -- OK, this is the case we are interested in. First step is to process
2134 -- our operands using the Minimize_Eliminate circuitry which applies
2135 -- this processing to the two operand subtrees.
2137 Minimize_Eliminate_Overflows
2138 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
2139 Minimize_Eliminate_Overflows
2140 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
2142 -- See if the range information decides the result of the comparison.
2143 -- We can only do this if we in fact have full range information (which
2144 -- won't be the case if either operand is bignum at this stage).
2146 if Llo /= No_Uint and then Rlo /= No_Uint then
2147 case N_Op_Compare (Nkind (N)) is
2148 when N_Op_Eq =>
2149 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2150 Set_True;
2151 elsif Llo > Rhi or else Lhi < Rlo then
2152 Set_False;
2153 end if;
2155 when N_Op_Ge =>
2156 if Llo >= Rhi then
2157 Set_True;
2158 elsif Lhi < Rlo then
2159 Set_False;
2160 end if;
2162 when N_Op_Gt =>
2163 if Llo > Rhi then
2164 Set_True;
2165 elsif Lhi <= Rlo then
2166 Set_False;
2167 end if;
2169 when N_Op_Le =>
2170 if Llo > Rhi then
2171 Set_False;
2172 elsif Lhi <= Rlo then
2173 Set_True;
2174 end if;
2176 when N_Op_Lt =>
2177 if Llo >= Rhi then
2178 Set_False;
2179 elsif Lhi < Rlo then
2180 Set_True;
2181 end if;
2183 when N_Op_Ne =>
2184 if Llo = Lhi and then Rlo = Rhi and then Llo = Rlo then
2185 Set_False;
2186 elsif Llo > Rhi or else Lhi < Rlo then
2187 Set_True;
2188 end if;
2189 end case;
2191 -- All done if we did the rewrite
2193 if Nkind (N) not in N_Op_Compare then
2194 return;
2195 end if;
2196 end if;
2198 -- Otherwise, time to do the comparison
2200 declare
2201 Ltype : constant Entity_Id := Etype (Left_Opnd (N));
2202 Rtype : constant Entity_Id := Etype (Right_Opnd (N));
2204 begin
2205 -- If the two operands have the same signed integer type we are
2206 -- all set, nothing more to do. This is the case where either
2207 -- both operands were unchanged, or we rewrote both of them to
2208 -- be Long_Long_Integer.
2210 -- Note: Entity for the comparison may be wrong, but it's not worth
2211 -- the effort to change it, since the back end does not use it.
2213 if Is_Signed_Integer_Type (Ltype)
2214 and then Base_Type (Ltype) = Base_Type (Rtype)
2215 then
2216 return;
2218 -- Here if bignums are involved (can only happen in ELIMINATED mode)
2220 elsif Is_RTE (Ltype, RE_Bignum) or else Is_RTE (Rtype, RE_Bignum) then
2221 declare
2222 Left : Node_Id := Left_Opnd (N);
2223 Right : Node_Id := Right_Opnd (N);
2224 -- Bignum references for left and right operands
2226 begin
2227 if not Is_RTE (Ltype, RE_Bignum) then
2228 Left := Convert_To_Bignum (Left);
2229 elsif not Is_RTE (Rtype, RE_Bignum) then
2230 Right := Convert_To_Bignum (Right);
2231 end if;
2233 -- We rewrite our node with:
2235 -- do
2236 -- Bnn : Result_Type;
2237 -- declare
2238 -- M : Mark_Id := SS_Mark;
2239 -- begin
2240 -- Bnn := Big_xx (Left, Right); (xx = EQ, NT etc)
2241 -- SS_Release (M);
2242 -- end;
2243 -- in
2244 -- Bnn
2245 -- end
2247 declare
2248 Blk : constant Node_Id := Make_Bignum_Block (Loc);
2249 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
2250 Ent : RE_Id;
2252 begin
2253 case N_Op_Compare (Nkind (N)) is
2254 when N_Op_Eq => Ent := RE_Big_EQ;
2255 when N_Op_Ge => Ent := RE_Big_GE;
2256 when N_Op_Gt => Ent := RE_Big_GT;
2257 when N_Op_Le => Ent := RE_Big_LE;
2258 when N_Op_Lt => Ent := RE_Big_LT;
2259 when N_Op_Ne => Ent := RE_Big_NE;
2260 end case;
2262 -- Insert assignment to Bnn into the bignum block
2264 Insert_Before
2265 (First (Statements (Handled_Statement_Sequence (Blk))),
2266 Make_Assignment_Statement (Loc,
2267 Name => New_Occurrence_Of (Bnn, Loc),
2268 Expression =>
2269 Make_Function_Call (Loc,
2270 Name =>
2271 New_Occurrence_Of (RTE (Ent), Loc),
2272 Parameter_Associations => New_List (Left, Right))));
2274 -- Now do the rewrite with expression actions
2276 Rewrite (N,
2277 Make_Expression_With_Actions (Loc,
2278 Actions => New_List (
2279 Make_Object_Declaration (Loc,
2280 Defining_Identifier => Bnn,
2281 Object_Definition =>
2282 New_Occurrence_Of (Result_Type, Loc)),
2283 Blk),
2284 Expression => New_Occurrence_Of (Bnn, Loc)));
2285 Analyze_And_Resolve (N, Result_Type);
2286 end;
2287 end;
2289 -- No bignums involved, but types are different, so we must have
2290 -- rewritten one of the operands as a Long_Long_Integer but not
2291 -- the other one.
2293 -- If left operand is Long_Long_Integer, convert right operand
2294 -- and we are done (with a comparison of two Long_Long_Integers).
2296 elsif Ltype = LLIB then
2297 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
2298 Analyze_And_Resolve (Right_Opnd (N), LLIB, Suppress => All_Checks);
2299 return;
2301 -- If right operand is Long_Long_Integer, convert left operand
2302 -- and we are done (with a comparison of two Long_Long_Integers).
2304 -- This is the only remaining possibility
2306 else pragma Assert (Rtype = LLIB);
2307 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
2308 Analyze_And_Resolve (Left_Opnd (N), LLIB, Suppress => All_Checks);
2309 return;
2310 end if;
2311 end;
2312 end Expand_Compare_Minimize_Eliminate_Overflow;
2314 -------------------------------
2315 -- Expand_Composite_Equality --
2316 -------------------------------
2318 -- This function is only called for comparing internal fields of composite
2319 -- types when these fields are themselves composites. This is a special
2320 -- case because it is not possible to respect normal Ada visibility rules.
2322 function Expand_Composite_Equality
2323 (Nod : Node_Id;
2324 Typ : Entity_Id;
2325 Lhs : Node_Id;
2326 Rhs : Node_Id;
2327 Bodies : List_Id) return Node_Id
2329 Loc : constant Source_Ptr := Sloc (Nod);
2330 Full_Type : Entity_Id;
2331 Prim : Elmt_Id;
2332 Eq_Op : Entity_Id;
2334 function Find_Primitive_Eq return Node_Id;
2335 -- AI05-0123: Locate primitive equality for type if it exists, and
2336 -- build the corresponding call. If operation is abstract, replace
2337 -- call with an explicit raise. Return Empty if there is no primitive.
2339 -----------------------
2340 -- Find_Primitive_Eq --
2341 -----------------------
2343 function Find_Primitive_Eq return Node_Id is
2344 Prim_E : Elmt_Id;
2345 Prim : Node_Id;
2347 begin
2348 Prim_E := First_Elmt (Collect_Primitive_Operations (Typ));
2349 while Present (Prim_E) loop
2350 Prim := Node (Prim_E);
2352 -- Locate primitive equality with the right signature
2354 if Chars (Prim) = Name_Op_Eq
2355 and then Etype (First_Formal (Prim)) =
2356 Etype (Next_Formal (First_Formal (Prim)))
2357 and then Etype (Prim) = Standard_Boolean
2358 then
2359 if Is_Abstract_Subprogram (Prim) then
2360 return
2361 Make_Raise_Program_Error (Loc,
2362 Reason => PE_Explicit_Raise);
2364 else
2365 return
2366 Make_Function_Call (Loc,
2367 Name => New_Occurrence_Of (Prim, Loc),
2368 Parameter_Associations => New_List (Lhs, Rhs));
2369 end if;
2370 end if;
2372 Next_Elmt (Prim_E);
2373 end loop;
2375 -- If not found, predefined operation will be used
2377 return Empty;
2378 end Find_Primitive_Eq;
2380 -- Start of processing for Expand_Composite_Equality
2382 begin
2383 if Is_Private_Type (Typ) then
2384 Full_Type := Underlying_Type (Typ);
2385 else
2386 Full_Type := Typ;
2387 end if;
2389 -- If the private type has no completion the context may be the
2390 -- expansion of a composite equality for a composite type with some
2391 -- still incomplete components. The expression will not be analyzed
2392 -- until the enclosing type is completed, at which point this will be
2393 -- properly expanded, unless there is a bona fide completion error.
2395 if No (Full_Type) then
2396 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2397 end if;
2399 Full_Type := Base_Type (Full_Type);
2401 -- When the base type itself is private, use the full view to expand
2402 -- the composite equality.
2404 if Is_Private_Type (Full_Type) then
2405 Full_Type := Underlying_Type (Full_Type);
2406 end if;
2408 -- Case of array types
2410 if Is_Array_Type (Full_Type) then
2412 -- If the operand is an elementary type other than a floating-point
2413 -- type, then we can simply use the built-in block bitwise equality,
2414 -- since the predefined equality operators always apply and bitwise
2415 -- equality is fine for all these cases.
2417 if Is_Elementary_Type (Component_Type (Full_Type))
2418 and then not Is_Floating_Point_Type (Component_Type (Full_Type))
2419 then
2420 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2422 -- For composite component types, and floating-point types, use the
2423 -- expansion. This deals with tagged component types (where we use
2424 -- the applicable equality routine) and floating-point, (where we
2425 -- need to worry about negative zeroes), and also the case of any
2426 -- composite type recursively containing such fields.
2428 else
2429 return Expand_Array_Equality (Nod, Lhs, Rhs, Bodies, Full_Type);
2430 end if;
2432 -- Case of tagged record types
2434 elsif Is_Tagged_Type (Full_Type) then
2436 -- Call the primitive operation "=" of this type
2438 if Is_Class_Wide_Type (Full_Type) then
2439 Full_Type := Root_Type (Full_Type);
2440 end if;
2442 -- If this is derived from an untagged private type completed with a
2443 -- tagged type, it does not have a full view, so we use the primitive
2444 -- operations of the private type. This check should no longer be
2445 -- necessary when these types receive their full views ???
2447 if Is_Private_Type (Typ)
2448 and then not Is_Tagged_Type (Typ)
2449 and then not Is_Controlled (Typ)
2450 and then Is_Derived_Type (Typ)
2451 and then No (Full_View (Typ))
2452 then
2453 Prim := First_Elmt (Collect_Primitive_Operations (Typ));
2454 else
2455 Prim := First_Elmt (Primitive_Operations (Full_Type));
2456 end if;
2458 loop
2459 Eq_Op := Node (Prim);
2460 exit when Chars (Eq_Op) = Name_Op_Eq
2461 and then Etype (First_Formal (Eq_Op)) =
2462 Etype (Next_Formal (First_Formal (Eq_Op)))
2463 and then Base_Type (Etype (Eq_Op)) = Standard_Boolean;
2464 Next_Elmt (Prim);
2465 pragma Assert (Present (Prim));
2466 end loop;
2468 Eq_Op := Node (Prim);
2470 return
2471 Make_Function_Call (Loc,
2472 Name => New_Occurrence_Of (Eq_Op, Loc),
2473 Parameter_Associations =>
2474 New_List
2475 (Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Lhs),
2476 Unchecked_Convert_To (Etype (First_Formal (Eq_Op)), Rhs)));
2478 -- Case of untagged record types
2480 elsif Is_Record_Type (Full_Type) then
2481 Eq_Op := TSS (Full_Type, TSS_Composite_Equality);
2483 if Present (Eq_Op) then
2484 if Etype (First_Formal (Eq_Op)) /= Full_Type then
2486 -- Inherited equality from parent type. Convert the actuals to
2487 -- match signature of operation.
2489 declare
2490 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2492 begin
2493 return
2494 Make_Function_Call (Loc,
2495 Name => New_Occurrence_Of (Eq_Op, Loc),
2496 Parameter_Associations => New_List (
2497 OK_Convert_To (T, Lhs),
2498 OK_Convert_To (T, Rhs)));
2499 end;
2501 else
2502 -- Comparison between Unchecked_Union components
2504 if Is_Unchecked_Union (Full_Type) then
2505 declare
2506 Lhs_Type : Node_Id := Full_Type;
2507 Rhs_Type : Node_Id := Full_Type;
2508 Lhs_Discr_Val : Node_Id;
2509 Rhs_Discr_Val : Node_Id;
2511 begin
2512 -- Lhs subtype
2514 if Nkind (Lhs) = N_Selected_Component then
2515 Lhs_Type := Etype (Entity (Selector_Name (Lhs)));
2516 end if;
2518 -- Rhs subtype
2520 if Nkind (Rhs) = N_Selected_Component then
2521 Rhs_Type := Etype (Entity (Selector_Name (Rhs)));
2522 end if;
2524 -- Lhs of the composite equality
2526 if Is_Constrained (Lhs_Type) then
2528 -- Since the enclosing record type can never be an
2529 -- Unchecked_Union (this code is executed for records
2530 -- that do not have variants), we may reference its
2531 -- discriminant(s).
2533 if Nkind (Lhs) = N_Selected_Component
2534 and then Has_Per_Object_Constraint
2535 (Entity (Selector_Name (Lhs)))
2536 then
2537 Lhs_Discr_Val :=
2538 Make_Selected_Component (Loc,
2539 Prefix => Prefix (Lhs),
2540 Selector_Name =>
2541 New_Copy
2542 (Get_Discriminant_Value
2543 (First_Discriminant (Lhs_Type),
2544 Lhs_Type,
2545 Stored_Constraint (Lhs_Type))));
2547 else
2548 Lhs_Discr_Val :=
2549 New_Copy
2550 (Get_Discriminant_Value
2551 (First_Discriminant (Lhs_Type),
2552 Lhs_Type,
2553 Stored_Constraint (Lhs_Type)));
2555 end if;
2556 else
2557 -- It is not possible to infer the discriminant since
2558 -- the subtype is not constrained.
2560 return
2561 Make_Raise_Program_Error (Loc,
2562 Reason => PE_Unchecked_Union_Restriction);
2563 end if;
2565 -- Rhs of the composite equality
2567 if Is_Constrained (Rhs_Type) then
2568 if Nkind (Rhs) = N_Selected_Component
2569 and then Has_Per_Object_Constraint
2570 (Entity (Selector_Name (Rhs)))
2571 then
2572 Rhs_Discr_Val :=
2573 Make_Selected_Component (Loc,
2574 Prefix => Prefix (Rhs),
2575 Selector_Name =>
2576 New_Copy
2577 (Get_Discriminant_Value
2578 (First_Discriminant (Rhs_Type),
2579 Rhs_Type,
2580 Stored_Constraint (Rhs_Type))));
2582 else
2583 Rhs_Discr_Val :=
2584 New_Copy
2585 (Get_Discriminant_Value
2586 (First_Discriminant (Rhs_Type),
2587 Rhs_Type,
2588 Stored_Constraint (Rhs_Type)));
2590 end if;
2591 else
2592 return
2593 Make_Raise_Program_Error (Loc,
2594 Reason => PE_Unchecked_Union_Restriction);
2595 end if;
2597 -- Call the TSS equality function with the inferred
2598 -- discriminant values.
2600 return
2601 Make_Function_Call (Loc,
2602 Name => New_Occurrence_Of (Eq_Op, Loc),
2603 Parameter_Associations => New_List (
2604 Lhs,
2605 Rhs,
2606 Lhs_Discr_Val,
2607 Rhs_Discr_Val));
2608 end;
2610 -- All cases other than comparing Unchecked_Union types
2612 else
2613 declare
2614 T : constant Entity_Id := Etype (First_Formal (Eq_Op));
2615 begin
2616 return
2617 Make_Function_Call (Loc,
2618 Name =>
2619 New_Occurrence_Of (Eq_Op, Loc),
2620 Parameter_Associations => New_List (
2621 OK_Convert_To (T, Lhs),
2622 OK_Convert_To (T, Rhs)));
2623 end;
2624 end if;
2625 end if;
2627 -- Equality composes in Ada 2012 for untagged record types. It also
2628 -- composes for bounded strings, because they are part of the
2629 -- predefined environment. We could make it compose for bounded
2630 -- strings by making them tagged, or by making sure all subcomponents
2631 -- are set to the same value, even when not used. Instead, we have
2632 -- this special case in the compiler, because it's more efficient.
2634 elsif Ada_Version >= Ada_2012 or else Is_Bounded_String (Typ) then
2636 -- If no TSS has been created for the type, check whether there is
2637 -- a primitive equality declared for it.
2639 declare
2640 Op : constant Node_Id := Find_Primitive_Eq;
2642 begin
2643 -- Use user-defined primitive if it exists, otherwise use
2644 -- predefined equality.
2646 if Present (Op) then
2647 return Op;
2648 else
2649 return Make_Op_Eq (Loc, Lhs, Rhs);
2650 end if;
2651 end;
2653 else
2654 return Expand_Record_Equality (Nod, Full_Type, Lhs, Rhs, Bodies);
2655 end if;
2657 -- Non-composite types (always use predefined equality)
2659 else
2660 return Make_Op_Eq (Loc, Left_Opnd => Lhs, Right_Opnd => Rhs);
2661 end if;
2662 end Expand_Composite_Equality;
2664 ------------------------
2665 -- Expand_Concatenate --
2666 ------------------------
2668 procedure Expand_Concatenate (Cnode : Node_Id; Opnds : List_Id) is
2669 Loc : constant Source_Ptr := Sloc (Cnode);
2671 Atyp : constant Entity_Id := Base_Type (Etype (Cnode));
2672 -- Result type of concatenation
2674 Ctyp : constant Entity_Id := Base_Type (Component_Type (Etype (Cnode)));
2675 -- Component type. Elements of this component type can appear as one
2676 -- of the operands of concatenation as well as arrays.
2678 Istyp : constant Entity_Id := Etype (First_Index (Atyp));
2679 -- Index subtype
2681 Ityp : constant Entity_Id := Base_Type (Istyp);
2682 -- Index type. This is the base type of the index subtype, and is used
2683 -- for all computed bounds (which may be out of range of Istyp in the
2684 -- case of null ranges).
2686 Artyp : Entity_Id;
2687 -- This is the type we use to do arithmetic to compute the bounds and
2688 -- lengths of operands. The choice of this type is a little subtle and
2689 -- is discussed in a separate section at the start of the body code.
2691 Concatenation_Error : exception;
2692 -- Raised if concatenation is sure to raise a CE
2694 Result_May_Be_Null : Boolean := True;
2695 -- Reset to False if at least one operand is encountered which is known
2696 -- at compile time to be non-null. Used for handling the special case
2697 -- of setting the high bound to the last operand high bound for a null
2698 -- result, thus ensuring a proper high bound in the super-flat case.
2700 N : constant Nat := List_Length (Opnds);
2701 -- Number of concatenation operands including possibly null operands
2703 NN : Nat := 0;
2704 -- Number of operands excluding any known to be null, except that the
2705 -- last operand is always retained, in case it provides the bounds for
2706 -- a null result.
2708 Opnd : Node_Id := Empty;
2709 -- Current operand being processed in the loop through operands. After
2710 -- this loop is complete, always contains the last operand (which is not
2711 -- the same as Operands (NN), since null operands are skipped).
2713 -- Arrays describing the operands, only the first NN entries of each
2714 -- array are set (NN < N when we exclude known null operands).
2716 Is_Fixed_Length : array (1 .. N) of Boolean;
2717 -- True if length of corresponding operand known at compile time
2719 Operands : array (1 .. N) of Node_Id;
2720 -- Set to the corresponding entry in the Opnds list (but note that null
2721 -- operands are excluded, so not all entries in the list are stored).
2723 Fixed_Length : array (1 .. N) of Uint;
2724 -- Set to length of operand. Entries in this array are set only if the
2725 -- corresponding entry in Is_Fixed_Length is True.
2727 Opnd_Low_Bound : array (1 .. N) of Node_Id;
2728 -- Set to lower bound of operand. Either an integer literal in the case
2729 -- where the bound is known at compile time, else actual lower bound.
2730 -- The operand low bound is of type Ityp.
2732 Var_Length : array (1 .. N) of Entity_Id;
2733 -- Set to an entity of type Natural that contains the length of an
2734 -- operand whose length is not known at compile time. Entries in this
2735 -- array are set only if the corresponding entry in Is_Fixed_Length
2736 -- is False. The entity is of type Artyp.
2738 Aggr_Length : array (0 .. N) of Node_Id;
2739 -- The J'th entry in an expression node that represents the total length
2740 -- of operands 1 through J. It is either an integer literal node, or a
2741 -- reference to a constant entity with the right value, so it is fine
2742 -- to just do a Copy_Node to get an appropriate copy. The extra zero'th
2743 -- entry always is set to zero. The length is of type Artyp.
2745 Low_Bound : Node_Id;
2746 -- A tree node representing the low bound of the result (of type Ityp).
2747 -- This is either an integer literal node, or an identifier reference to
2748 -- a constant entity initialized to the appropriate value.
2750 Last_Opnd_Low_Bound : Node_Id := Empty;
2751 -- A tree node representing the low bound of the last operand. This
2752 -- need only be set if the result could be null. It is used for the
2753 -- special case of setting the right low bound for a null result.
2754 -- This is of type Ityp.
2756 Last_Opnd_High_Bound : Node_Id := Empty;
2757 -- A tree node representing the high bound of the last operand. This
2758 -- need only be set if the result could be null. It is used for the
2759 -- special case of setting the right high bound for a null result.
2760 -- This is of type Ityp.
2762 High_Bound : Node_Id;
2763 -- A tree node representing the high bound of the result (of type Ityp)
2765 Result : Node_Id;
2766 -- Result of the concatenation (of type Ityp)
2768 Actions : constant List_Id := New_List;
2769 -- Collect actions to be inserted
2771 Known_Non_Null_Operand_Seen : Boolean;
2772 -- Set True during generation of the assignments of operands into
2773 -- result once an operand known to be non-null has been seen.
2775 function Library_Level_Target return Boolean;
2776 -- Return True if the concatenation is within the expression of the
2777 -- declaration of a library-level object.
2779 function Make_Artyp_Literal (Val : Nat) return Node_Id;
2780 -- This function makes an N_Integer_Literal node that is returned in
2781 -- analyzed form with the type set to Artyp. Importantly this literal
2782 -- is not flagged as static, so that if we do computations with it that
2783 -- result in statically detected out of range conditions, we will not
2784 -- generate error messages but instead warning messages.
2786 function To_Artyp (X : Node_Id) return Node_Id;
2787 -- Given a node of type Ityp, returns the corresponding value of type
2788 -- Artyp. For non-enumeration types, this is a plain integer conversion.
2789 -- For enum types, the Pos of the value is returned.
2791 function To_Ityp (X : Node_Id) return Node_Id;
2792 -- The inverse function (uses Val in the case of enumeration types)
2794 --------------------------
2795 -- Library_Level_Target --
2796 --------------------------
2798 function Library_Level_Target return Boolean is
2799 P : Node_Id := Parent (Cnode);
2801 begin
2802 while Present (P) loop
2803 if Nkind (P) = N_Object_Declaration then
2804 return Is_Library_Level_Entity (Defining_Identifier (P));
2806 -- Prevent the search from going too far
2808 elsif Is_Body_Or_Package_Declaration (P) then
2809 return False;
2810 end if;
2812 P := Parent (P);
2813 end loop;
2815 return False;
2816 end Library_Level_Target;
2818 ------------------------
2819 -- Make_Artyp_Literal --
2820 ------------------------
2822 function Make_Artyp_Literal (Val : Nat) return Node_Id is
2823 Result : constant Node_Id := Make_Integer_Literal (Loc, Val);
2824 begin
2825 Set_Etype (Result, Artyp);
2826 Set_Analyzed (Result, True);
2827 Set_Is_Static_Expression (Result, False);
2828 return Result;
2829 end Make_Artyp_Literal;
2831 --------------
2832 -- To_Artyp --
2833 --------------
2835 function To_Artyp (X : Node_Id) return Node_Id is
2836 begin
2837 if Ityp = Base_Type (Artyp) then
2838 return X;
2840 elsif Is_Enumeration_Type (Ityp) then
2841 return
2842 Make_Attribute_Reference (Loc,
2843 Prefix => New_Occurrence_Of (Ityp, Loc),
2844 Attribute_Name => Name_Pos,
2845 Expressions => New_List (X));
2847 else
2848 return Convert_To (Artyp, X);
2849 end if;
2850 end To_Artyp;
2852 -------------
2853 -- To_Ityp --
2854 -------------
2856 function To_Ityp (X : Node_Id) return Node_Id is
2857 begin
2858 if Is_Enumeration_Type (Ityp) then
2859 return
2860 Make_Attribute_Reference (Loc,
2861 Prefix => New_Occurrence_Of (Ityp, Loc),
2862 Attribute_Name => Name_Val,
2863 Expressions => New_List (X));
2865 -- Case where we will do a type conversion
2867 else
2868 if Ityp = Base_Type (Artyp) then
2869 return X;
2870 else
2871 return Convert_To (Ityp, X);
2872 end if;
2873 end if;
2874 end To_Ityp;
2876 -- Local Declarations
2878 Opnd_Typ : Entity_Id;
2879 Ent : Entity_Id;
2880 Len : Uint;
2881 J : Nat;
2882 Clen : Node_Id;
2883 Set : Boolean;
2885 -- Start of processing for Expand_Concatenate
2887 begin
2888 -- Choose an appropriate computational type
2890 -- We will be doing calculations of lengths and bounds in this routine
2891 -- and computing one from the other in some cases, e.g. getting the high
2892 -- bound by adding the length-1 to the low bound.
2894 -- We can't just use the index type, or even its base type for this
2895 -- purpose for two reasons. First it might be an enumeration type which
2896 -- is not suitable for computations of any kind, and second it may
2897 -- simply not have enough range. For example if the index type is
2898 -- -128..+127 then lengths can be up to 256, which is out of range of
2899 -- the type.
2901 -- For enumeration types, we can simply use Standard_Integer, this is
2902 -- sufficient since the actual number of enumeration literals cannot
2903 -- possibly exceed the range of integer (remember we will be doing the
2904 -- arithmetic with POS values, not representation values).
2906 if Is_Enumeration_Type (Ityp) then
2907 Artyp := Standard_Integer;
2909 -- If index type is Positive, we use the standard unsigned type, to give
2910 -- more room on the top of the range, obviating the need for an overflow
2911 -- check when creating the upper bound. This is needed to avoid junk
2912 -- overflow checks in the common case of String types.
2914 -- ??? Disabled for now
2916 -- elsif Istyp = Standard_Positive then
2917 -- Artyp := Standard_Unsigned;
2919 -- For modular types, we use a 32-bit modular type for types whose size
2920 -- is in the range 1-31 bits. For 32-bit unsigned types, we use the
2921 -- identity type, and for larger unsigned types we use 64-bits.
2923 elsif Is_Modular_Integer_Type (Ityp) then
2924 if RM_Size (Ityp) < RM_Size (Standard_Unsigned) then
2925 Artyp := Standard_Unsigned;
2926 elsif RM_Size (Ityp) = RM_Size (Standard_Unsigned) then
2927 Artyp := Ityp;
2928 else
2929 Artyp := RTE (RE_Long_Long_Unsigned);
2930 end if;
2932 -- Similar treatment for signed types
2934 else
2935 if RM_Size (Ityp) < RM_Size (Standard_Integer) then
2936 Artyp := Standard_Integer;
2937 elsif RM_Size (Ityp) = RM_Size (Standard_Integer) then
2938 Artyp := Ityp;
2939 else
2940 Artyp := Standard_Long_Long_Integer;
2941 end if;
2942 end if;
2944 -- Supply dummy entry at start of length array
2946 Aggr_Length (0) := Make_Artyp_Literal (0);
2948 -- Go through operands setting up the above arrays
2950 J := 1;
2951 while J <= N loop
2952 Opnd := Remove_Head (Opnds);
2953 Opnd_Typ := Etype (Opnd);
2955 -- The parent got messed up when we put the operands in a list,
2956 -- so now put back the proper parent for the saved operand, that
2957 -- is to say the concatenation node, to make sure that each operand
2958 -- is seen as a subexpression, e.g. if actions must be inserted.
2960 Set_Parent (Opnd, Cnode);
2962 -- Set will be True when we have setup one entry in the array
2964 Set := False;
2966 -- Singleton element (or character literal) case
2968 if Base_Type (Opnd_Typ) = Ctyp then
2969 NN := NN + 1;
2970 Operands (NN) := Opnd;
2971 Is_Fixed_Length (NN) := True;
2972 Fixed_Length (NN) := Uint_1;
2973 Result_May_Be_Null := False;
2975 -- Set low bound of operand (no need to set Last_Opnd_High_Bound
2976 -- since we know that the result cannot be null).
2978 Opnd_Low_Bound (NN) :=
2979 Make_Attribute_Reference (Loc,
2980 Prefix => New_Occurrence_Of (Istyp, Loc),
2981 Attribute_Name => Name_First);
2983 Set := True;
2985 -- String literal case (can only occur for strings of course)
2987 elsif Nkind (Opnd) = N_String_Literal then
2988 Len := String_Literal_Length (Opnd_Typ);
2990 if Len /= 0 then
2991 Result_May_Be_Null := False;
2992 end if;
2994 -- Capture last operand low and high bound if result could be null
2996 if J = N and then Result_May_Be_Null then
2997 Last_Opnd_Low_Bound :=
2998 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3000 Last_Opnd_High_Bound :=
3001 Make_Op_Subtract (Loc,
3002 Left_Opnd =>
3003 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ)),
3004 Right_Opnd => Make_Integer_Literal (Loc, 1));
3005 end if;
3007 -- Skip null string literal
3009 if J < N and then Len = 0 then
3010 goto Continue;
3011 end if;
3013 NN := NN + 1;
3014 Operands (NN) := Opnd;
3015 Is_Fixed_Length (NN) := True;
3017 -- Set length and bounds
3019 Fixed_Length (NN) := Len;
3021 Opnd_Low_Bound (NN) :=
3022 New_Copy_Tree (String_Literal_Low_Bound (Opnd_Typ));
3024 Set := True;
3026 -- All other cases
3028 else
3029 -- Check constrained case with known bounds
3031 if Is_Constrained (Opnd_Typ) then
3032 declare
3033 Index : constant Node_Id := First_Index (Opnd_Typ);
3034 Indx_Typ : constant Entity_Id := Etype (Index);
3035 Lo : constant Node_Id := Type_Low_Bound (Indx_Typ);
3036 Hi : constant Node_Id := Type_High_Bound (Indx_Typ);
3038 begin
3039 -- Fixed length constrained array type with known at compile
3040 -- time bounds is last case of fixed length operand.
3042 if Compile_Time_Known_Value (Lo)
3043 and then
3044 Compile_Time_Known_Value (Hi)
3045 then
3046 declare
3047 Loval : constant Uint := Expr_Value (Lo);
3048 Hival : constant Uint := Expr_Value (Hi);
3049 Len : constant Uint :=
3050 UI_Max (Hival - Loval + 1, Uint_0);
3052 begin
3053 if Len > 0 then
3054 Result_May_Be_Null := False;
3055 end if;
3057 -- Capture last operand bounds if result could be null
3059 if J = N and then Result_May_Be_Null then
3060 Last_Opnd_Low_Bound :=
3061 Convert_To (Ityp,
3062 Make_Integer_Literal (Loc, Expr_Value (Lo)));
3064 Last_Opnd_High_Bound :=
3065 Convert_To (Ityp,
3066 Make_Integer_Literal (Loc, Expr_Value (Hi)));
3067 end if;
3069 -- Exclude null length case unless last operand
3071 if J < N and then Len = 0 then
3072 goto Continue;
3073 end if;
3075 NN := NN + 1;
3076 Operands (NN) := Opnd;
3077 Is_Fixed_Length (NN) := True;
3078 Fixed_Length (NN) := Len;
3080 Opnd_Low_Bound (NN) :=
3081 To_Ityp
3082 (Make_Integer_Literal (Loc, Expr_Value (Lo)));
3083 Set := True;
3084 end;
3085 end if;
3086 end;
3087 end if;
3089 -- All cases where the length is not known at compile time, or the
3090 -- special case of an operand which is known to be null but has a
3091 -- lower bound other than 1 or is other than a string type.
3093 if not Set then
3094 NN := NN + 1;
3096 -- Capture operand bounds
3098 Opnd_Low_Bound (NN) :=
3099 Make_Attribute_Reference (Loc,
3100 Prefix =>
3101 Duplicate_Subexpr (Opnd, Name_Req => True),
3102 Attribute_Name => Name_First);
3104 -- Capture last operand bounds if result could be null
3106 if J = N and Result_May_Be_Null then
3107 Last_Opnd_Low_Bound :=
3108 Convert_To (Ityp,
3109 Make_Attribute_Reference (Loc,
3110 Prefix =>
3111 Duplicate_Subexpr (Opnd, Name_Req => True),
3112 Attribute_Name => Name_First));
3114 Last_Opnd_High_Bound :=
3115 Convert_To (Ityp,
3116 Make_Attribute_Reference (Loc,
3117 Prefix =>
3118 Duplicate_Subexpr (Opnd, Name_Req => True),
3119 Attribute_Name => Name_Last));
3120 end if;
3122 -- Capture length of operand in entity
3124 Operands (NN) := Opnd;
3125 Is_Fixed_Length (NN) := False;
3127 Var_Length (NN) := Make_Temporary (Loc, 'L');
3129 Append_To (Actions,
3130 Make_Object_Declaration (Loc,
3131 Defining_Identifier => Var_Length (NN),
3132 Constant_Present => True,
3133 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3134 Expression =>
3135 Make_Attribute_Reference (Loc,
3136 Prefix =>
3137 Duplicate_Subexpr (Opnd, Name_Req => True),
3138 Attribute_Name => Name_Length)));
3139 end if;
3140 end if;
3142 -- Set next entry in aggregate length array
3144 -- For first entry, make either integer literal for fixed length
3145 -- or a reference to the saved length for variable length.
3147 if NN = 1 then
3148 if Is_Fixed_Length (1) then
3149 Aggr_Length (1) := Make_Integer_Literal (Loc, Fixed_Length (1));
3150 else
3151 Aggr_Length (1) := New_Occurrence_Of (Var_Length (1), Loc);
3152 end if;
3154 -- If entry is fixed length and only fixed lengths so far, make
3155 -- appropriate new integer literal adding new length.
3157 elsif Is_Fixed_Length (NN)
3158 and then Nkind (Aggr_Length (NN - 1)) = N_Integer_Literal
3159 then
3160 Aggr_Length (NN) :=
3161 Make_Integer_Literal (Loc,
3162 Intval => Fixed_Length (NN) + Intval (Aggr_Length (NN - 1)));
3164 -- All other cases, construct an addition node for the length and
3165 -- create an entity initialized to this length.
3167 else
3168 Ent := Make_Temporary (Loc, 'L');
3170 if Is_Fixed_Length (NN) then
3171 Clen := Make_Integer_Literal (Loc, Fixed_Length (NN));
3172 else
3173 Clen := New_Occurrence_Of (Var_Length (NN), Loc);
3174 end if;
3176 Append_To (Actions,
3177 Make_Object_Declaration (Loc,
3178 Defining_Identifier => Ent,
3179 Constant_Present => True,
3180 Object_Definition => New_Occurrence_Of (Artyp, Loc),
3181 Expression =>
3182 Make_Op_Add (Loc,
3183 Left_Opnd => New_Copy (Aggr_Length (NN - 1)),
3184 Right_Opnd => Clen)));
3186 Aggr_Length (NN) := Make_Identifier (Loc, Chars => Chars (Ent));
3187 end if;
3189 <<Continue>>
3190 J := J + 1;
3191 end loop;
3193 -- If we have only skipped null operands, return the last operand
3195 if NN = 0 then
3196 Result := Opnd;
3197 goto Done;
3198 end if;
3200 -- If we have only one non-null operand, return it and we are done.
3201 -- There is one case in which this cannot be done, and that is when
3202 -- the sole operand is of the element type, in which case it must be
3203 -- converted to an array, and the easiest way of doing that is to go
3204 -- through the normal general circuit.
3206 if NN = 1 and then Base_Type (Etype (Operands (1))) /= Ctyp then
3207 Result := Operands (1);
3208 goto Done;
3209 end if;
3211 -- Cases where we have a real concatenation
3213 -- Next step is to find the low bound for the result array that we
3214 -- will allocate. The rules for this are in (RM 4.5.6(5-7)).
3216 -- If the ultimate ancestor of the index subtype is a constrained array
3217 -- definition, then the lower bound is that of the index subtype as
3218 -- specified by (RM 4.5.3(6)).
3220 -- The right test here is to go to the root type, and then the ultimate
3221 -- ancestor is the first subtype of this root type.
3223 if Is_Constrained (First_Subtype (Root_Type (Atyp))) then
3224 Low_Bound :=
3225 Make_Attribute_Reference (Loc,
3226 Prefix =>
3227 New_Occurrence_Of (First_Subtype (Root_Type (Atyp)), Loc),
3228 Attribute_Name => Name_First);
3230 -- If the first operand in the list has known length we know that
3231 -- the lower bound of the result is the lower bound of this operand.
3233 elsif Is_Fixed_Length (1) then
3234 Low_Bound := Opnd_Low_Bound (1);
3236 -- OK, we don't know the lower bound, we have to build a horrible
3237 -- if expression node of the form
3239 -- if Cond1'Length /= 0 then
3240 -- Opnd1 low bound
3241 -- else
3242 -- if Opnd2'Length /= 0 then
3243 -- Opnd2 low bound
3244 -- else
3245 -- ...
3247 -- The nesting ends either when we hit an operand whose length is known
3248 -- at compile time, or on reaching the last operand, whose low bound we
3249 -- take unconditionally whether or not it is null. It's easiest to do
3250 -- this with a recursive procedure:
3252 else
3253 declare
3254 function Get_Known_Bound (J : Nat) return Node_Id;
3255 -- Returns the lower bound determined by operands J .. NN
3257 ---------------------
3258 -- Get_Known_Bound --
3259 ---------------------
3261 function Get_Known_Bound (J : Nat) return Node_Id is
3262 begin
3263 if Is_Fixed_Length (J) or else J = NN then
3264 return New_Copy (Opnd_Low_Bound (J));
3266 else
3267 return
3268 Make_If_Expression (Loc,
3269 Expressions => New_List (
3271 Make_Op_Ne (Loc,
3272 Left_Opnd =>
3273 New_Occurrence_Of (Var_Length (J), Loc),
3274 Right_Opnd =>
3275 Make_Integer_Literal (Loc, 0)),
3277 New_Copy (Opnd_Low_Bound (J)),
3278 Get_Known_Bound (J + 1)));
3279 end if;
3280 end Get_Known_Bound;
3282 begin
3283 Ent := Make_Temporary (Loc, 'L');
3285 Append_To (Actions,
3286 Make_Object_Declaration (Loc,
3287 Defining_Identifier => Ent,
3288 Constant_Present => True,
3289 Object_Definition => New_Occurrence_Of (Ityp, Loc),
3290 Expression => Get_Known_Bound (1)));
3292 Low_Bound := New_Occurrence_Of (Ent, Loc);
3293 end;
3294 end if;
3296 -- Now we can safely compute the upper bound, normally
3297 -- Low_Bound + Length - 1.
3299 High_Bound :=
3300 To_Ityp
3301 (Make_Op_Add (Loc,
3302 Left_Opnd => To_Artyp (New_Copy (Low_Bound)),
3303 Right_Opnd =>
3304 Make_Op_Subtract (Loc,
3305 Left_Opnd => New_Copy (Aggr_Length (NN)),
3306 Right_Opnd => Make_Artyp_Literal (1))));
3308 -- Note that calculation of the high bound may cause overflow in some
3309 -- very weird cases, so in the general case we need an overflow check on
3310 -- the high bound. We can avoid this for the common case of string types
3311 -- and other types whose index is Positive, since we chose a wider range
3312 -- for the arithmetic type. If checks are suppressed we do not set the
3313 -- flag, and possibly superfluous warnings will be omitted.
3315 if Istyp /= Standard_Positive
3316 and then not Overflow_Checks_Suppressed (Istyp)
3317 then
3318 Activate_Overflow_Check (High_Bound);
3319 end if;
3321 -- Handle the exceptional case where the result is null, in which case
3322 -- case the bounds come from the last operand (so that we get the proper
3323 -- bounds if the last operand is super-flat).
3325 if Result_May_Be_Null then
3326 Low_Bound :=
3327 Make_If_Expression (Loc,
3328 Expressions => New_List (
3329 Make_Op_Eq (Loc,
3330 Left_Opnd => New_Copy (Aggr_Length (NN)),
3331 Right_Opnd => Make_Artyp_Literal (0)),
3332 Last_Opnd_Low_Bound,
3333 Low_Bound));
3335 High_Bound :=
3336 Make_If_Expression (Loc,
3337 Expressions => New_List (
3338 Make_Op_Eq (Loc,
3339 Left_Opnd => New_Copy (Aggr_Length (NN)),
3340 Right_Opnd => Make_Artyp_Literal (0)),
3341 Last_Opnd_High_Bound,
3342 High_Bound));
3343 end if;
3345 -- Here is where we insert the saved up actions
3347 Insert_Actions (Cnode, Actions, Suppress => All_Checks);
3349 -- Now we construct an array object with appropriate bounds. We mark
3350 -- the target as internal to prevent useless initialization when
3351 -- Initialize_Scalars is enabled. Also since this is the actual result
3352 -- entity, we make sure we have debug information for the result.
3354 Ent := Make_Temporary (Loc, 'S');
3355 Set_Is_Internal (Ent);
3356 Set_Needs_Debug_Info (Ent);
3358 -- If the bound is statically known to be out of range, we do not want
3359 -- to abort, we want a warning and a runtime constraint error. Note that
3360 -- we have arranged that the result will not be treated as a static
3361 -- constant, so we won't get an illegality during this insertion.
3363 Insert_Action (Cnode,
3364 Make_Object_Declaration (Loc,
3365 Defining_Identifier => Ent,
3366 Object_Definition =>
3367 Make_Subtype_Indication (Loc,
3368 Subtype_Mark => New_Occurrence_Of (Atyp, Loc),
3369 Constraint =>
3370 Make_Index_Or_Discriminant_Constraint (Loc,
3371 Constraints => New_List (
3372 Make_Range (Loc,
3373 Low_Bound => Low_Bound,
3374 High_Bound => High_Bound))))),
3375 Suppress => All_Checks);
3377 -- If the result of the concatenation appears as the initializing
3378 -- expression of an object declaration, we can just rename the
3379 -- result, rather than copying it.
3381 Set_OK_To_Rename (Ent);
3383 -- Catch the static out of range case now
3385 if Raises_Constraint_Error (High_Bound) then
3386 raise Concatenation_Error;
3387 end if;
3389 -- Now we will generate the assignments to do the actual concatenation
3391 -- There is one case in which we will not do this, namely when all the
3392 -- following conditions are met:
3394 -- The result type is Standard.String
3396 -- There are nine or fewer retained (non-null) operands
3398 -- The optimization level is -O0 or the debug flag gnatd.C is set,
3399 -- and the debug flag gnatd.c is not set.
3401 -- The corresponding System.Concat_n.Str_Concat_n routine is
3402 -- available in the run time.
3404 -- If all these conditions are met then we generate a call to the
3405 -- relevant concatenation routine. The purpose of this is to avoid
3406 -- undesirable code bloat at -O0.
3408 -- If the concatenation is within the declaration of a library-level
3409 -- object, we call the built-in concatenation routines to prevent code
3410 -- bloat, regardless of the optimization level. This is space efficient
3411 -- and prevents linking problems when units are compiled with different
3412 -- optimization levels.
3414 if Atyp = Standard_String
3415 and then NN in 2 .. 9
3416 and then (((Optimization_Level = 0 or else Debug_Flag_Dot_CC)
3417 and then not Debug_Flag_Dot_C)
3418 or else Library_Level_Target)
3419 then
3420 declare
3421 RR : constant array (Nat range 2 .. 9) of RE_Id :=
3422 (RE_Str_Concat_2,
3423 RE_Str_Concat_3,
3424 RE_Str_Concat_4,
3425 RE_Str_Concat_5,
3426 RE_Str_Concat_6,
3427 RE_Str_Concat_7,
3428 RE_Str_Concat_8,
3429 RE_Str_Concat_9);
3431 begin
3432 if RTE_Available (RR (NN)) then
3433 declare
3434 Opnds : constant List_Id :=
3435 New_List (New_Occurrence_Of (Ent, Loc));
3437 begin
3438 for J in 1 .. NN loop
3439 if Is_List_Member (Operands (J)) then
3440 Remove (Operands (J));
3441 end if;
3443 if Base_Type (Etype (Operands (J))) = Ctyp then
3444 Append_To (Opnds,
3445 Make_Aggregate (Loc,
3446 Component_Associations => New_List (
3447 Make_Component_Association (Loc,
3448 Choices => New_List (
3449 Make_Integer_Literal (Loc, 1)),
3450 Expression => Operands (J)))));
3452 else
3453 Append_To (Opnds, Operands (J));
3454 end if;
3455 end loop;
3457 Insert_Action (Cnode,
3458 Make_Procedure_Call_Statement (Loc,
3459 Name => New_Occurrence_Of (RTE (RR (NN)), Loc),
3460 Parameter_Associations => Opnds));
3462 Result := New_Occurrence_Of (Ent, Loc);
3463 goto Done;
3464 end;
3465 end if;
3466 end;
3467 end if;
3469 -- Not special case so generate the assignments
3471 Known_Non_Null_Operand_Seen := False;
3473 for J in 1 .. NN loop
3474 declare
3475 Lo : constant Node_Id :=
3476 Make_Op_Add (Loc,
3477 Left_Opnd => To_Artyp (New_Copy (Low_Bound)),
3478 Right_Opnd => Aggr_Length (J - 1));
3480 Hi : constant Node_Id :=
3481 Make_Op_Add (Loc,
3482 Left_Opnd => To_Artyp (New_Copy (Low_Bound)),
3483 Right_Opnd =>
3484 Make_Op_Subtract (Loc,
3485 Left_Opnd => Aggr_Length (J),
3486 Right_Opnd => Make_Artyp_Literal (1)));
3488 begin
3489 -- Singleton case, simple assignment
3491 if Base_Type (Etype (Operands (J))) = Ctyp then
3492 Known_Non_Null_Operand_Seen := True;
3493 Insert_Action (Cnode,
3494 Make_Assignment_Statement (Loc,
3495 Name =>
3496 Make_Indexed_Component (Loc,
3497 Prefix => New_Occurrence_Of (Ent, Loc),
3498 Expressions => New_List (To_Ityp (Lo))),
3499 Expression => Operands (J)),
3500 Suppress => All_Checks);
3502 -- Array case, slice assignment, skipped when argument is fixed
3503 -- length and known to be null.
3505 elsif (not Is_Fixed_Length (J)) or else (Fixed_Length (J) > 0) then
3506 declare
3507 Assign : Node_Id :=
3508 Make_Assignment_Statement (Loc,
3509 Name =>
3510 Make_Slice (Loc,
3511 Prefix =>
3512 New_Occurrence_Of (Ent, Loc),
3513 Discrete_Range =>
3514 Make_Range (Loc,
3515 Low_Bound => To_Ityp (Lo),
3516 High_Bound => To_Ityp (Hi))),
3517 Expression => Operands (J));
3518 begin
3519 if Is_Fixed_Length (J) then
3520 Known_Non_Null_Operand_Seen := True;
3522 elsif not Known_Non_Null_Operand_Seen then
3524 -- Here if operand length is not statically known and no
3525 -- operand known to be non-null has been processed yet.
3526 -- If operand length is 0, we do not need to perform the
3527 -- assignment, and we must avoid the evaluation of the
3528 -- high bound of the slice, since it may underflow if the
3529 -- low bound is Ityp'First.
3531 Assign :=
3532 Make_Implicit_If_Statement (Cnode,
3533 Condition =>
3534 Make_Op_Ne (Loc,
3535 Left_Opnd =>
3536 New_Occurrence_Of (Var_Length (J), Loc),
3537 Right_Opnd => Make_Integer_Literal (Loc, 0)),
3538 Then_Statements => New_List (Assign));
3539 end if;
3541 Insert_Action (Cnode, Assign, Suppress => All_Checks);
3542 end;
3543 end if;
3544 end;
3545 end loop;
3547 -- Finally we build the result, which is a reference to the array object
3549 Result := New_Occurrence_Of (Ent, Loc);
3551 <<Done>>
3552 Rewrite (Cnode, Result);
3553 Analyze_And_Resolve (Cnode, Atyp);
3555 exception
3556 when Concatenation_Error =>
3558 -- Kill warning generated for the declaration of the static out of
3559 -- range high bound, and instead generate a Constraint_Error with
3560 -- an appropriate specific message.
3562 Kill_Dead_Code (Declaration_Node (Entity (High_Bound)));
3563 Apply_Compile_Time_Constraint_Error
3564 (N => Cnode,
3565 Msg => "concatenation result upper bound out of range??",
3566 Reason => CE_Range_Check_Failed);
3567 end Expand_Concatenate;
3569 ---------------------------------------------------
3570 -- Expand_Membership_Minimize_Eliminate_Overflow --
3571 ---------------------------------------------------
3573 procedure Expand_Membership_Minimize_Eliminate_Overflow (N : Node_Id) is
3574 pragma Assert (Nkind (N) = N_In);
3575 -- Despite the name, this routine applies only to N_In, not to
3576 -- N_Not_In. The latter is always rewritten as not (X in Y).
3578 Result_Type : constant Entity_Id := Etype (N);
3579 -- Capture result type, may be a derived boolean type
3581 Loc : constant Source_Ptr := Sloc (N);
3582 Lop : constant Node_Id := Left_Opnd (N);
3583 Rop : constant Node_Id := Right_Opnd (N);
3585 -- Note: there are many referencs to Etype (Lop) and Etype (Rop). It
3586 -- is thus tempting to capture these values, but due to the rewrites
3587 -- that occur as a result of overflow checking, these values change
3588 -- as we go along, and it is safe just to always use Etype explicitly.
3590 Restype : constant Entity_Id := Etype (N);
3591 -- Save result type
3593 Lo, Hi : Uint;
3594 -- Bounds in Minimize calls, not used currently
3596 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
3597 -- Entity for Long_Long_Integer'Base (Standard should export this???)
3599 begin
3600 Minimize_Eliminate_Overflows (Lop, Lo, Hi, Top_Level => False);
3602 -- If right operand is a subtype name, and the subtype name has no
3603 -- predicate, then we can just replace the right operand with an
3604 -- explicit range T'First .. T'Last, and use the explicit range code.
3606 if Nkind (Rop) /= N_Range
3607 and then No (Predicate_Function (Etype (Rop)))
3608 then
3609 declare
3610 Rtyp : constant Entity_Id := Etype (Rop);
3611 begin
3612 Rewrite (Rop,
3613 Make_Range (Loc,
3614 Low_Bound =>
3615 Make_Attribute_Reference (Loc,
3616 Attribute_Name => Name_First,
3617 Prefix => New_Occurrence_Of (Rtyp, Loc)),
3618 High_Bound =>
3619 Make_Attribute_Reference (Loc,
3620 Attribute_Name => Name_Last,
3621 Prefix => New_Occurrence_Of (Rtyp, Loc))));
3622 Analyze_And_Resolve (Rop, Rtyp, Suppress => All_Checks);
3623 end;
3624 end if;
3626 -- Here for the explicit range case. Note that the bounds of the range
3627 -- have not been processed for minimized or eliminated checks.
3629 if Nkind (Rop) = N_Range then
3630 Minimize_Eliminate_Overflows
3631 (Low_Bound (Rop), Lo, Hi, Top_Level => False);
3632 Minimize_Eliminate_Overflows
3633 (High_Bound (Rop), Lo, Hi, Top_Level => False);
3635 -- We have A in B .. C, treated as A >= B and then A <= C
3637 -- Bignum case
3639 if Is_RTE (Etype (Lop), RE_Bignum)
3640 or else Is_RTE (Etype (Low_Bound (Rop)), RE_Bignum)
3641 or else Is_RTE (Etype (High_Bound (Rop)), RE_Bignum)
3642 then
3643 declare
3644 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3645 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
3646 L : constant Entity_Id :=
3647 Make_Defining_Identifier (Loc, Name_uL);
3648 Lopnd : constant Node_Id := Convert_To_Bignum (Lop);
3649 Lbound : constant Node_Id :=
3650 Convert_To_Bignum (Low_Bound (Rop));
3651 Hbound : constant Node_Id :=
3652 Convert_To_Bignum (High_Bound (Rop));
3654 -- Now we rewrite the membership test node to look like
3656 -- do
3657 -- Bnn : Result_Type;
3658 -- declare
3659 -- M : Mark_Id := SS_Mark;
3660 -- L : Bignum := Lopnd;
3661 -- begin
3662 -- Bnn := Big_GE (L, Lbound) and then Big_LE (L, Hbound)
3663 -- SS_Release (M);
3664 -- end;
3665 -- in
3666 -- Bnn
3667 -- end
3669 begin
3670 -- Insert declaration of L into declarations of bignum block
3672 Insert_After
3673 (Last (Declarations (Blk)),
3674 Make_Object_Declaration (Loc,
3675 Defining_Identifier => L,
3676 Object_Definition =>
3677 New_Occurrence_Of (RTE (RE_Bignum), Loc),
3678 Expression => Lopnd));
3680 -- Insert assignment to Bnn into expressions of bignum block
3682 Insert_Before
3683 (First (Statements (Handled_Statement_Sequence (Blk))),
3684 Make_Assignment_Statement (Loc,
3685 Name => New_Occurrence_Of (Bnn, Loc),
3686 Expression =>
3687 Make_And_Then (Loc,
3688 Left_Opnd =>
3689 Make_Function_Call (Loc,
3690 Name =>
3691 New_Occurrence_Of (RTE (RE_Big_GE), Loc),
3692 Parameter_Associations => New_List (
3693 New_Occurrence_Of (L, Loc),
3694 Lbound)),
3696 Right_Opnd =>
3697 Make_Function_Call (Loc,
3698 Name =>
3699 New_Occurrence_Of (RTE (RE_Big_LE), Loc),
3700 Parameter_Associations => New_List (
3701 New_Occurrence_Of (L, Loc),
3702 Hbound)))));
3704 -- Now rewrite the node
3706 Rewrite (N,
3707 Make_Expression_With_Actions (Loc,
3708 Actions => New_List (
3709 Make_Object_Declaration (Loc,
3710 Defining_Identifier => Bnn,
3711 Object_Definition =>
3712 New_Occurrence_Of (Result_Type, Loc)),
3713 Blk),
3714 Expression => New_Occurrence_Of (Bnn, Loc)));
3715 Analyze_And_Resolve (N, Result_Type);
3716 return;
3717 end;
3719 -- Here if no bignums around
3721 else
3722 -- Case where types are all the same
3724 if Base_Type (Etype (Lop)) = Base_Type (Etype (Low_Bound (Rop)))
3725 and then
3726 Base_Type (Etype (Lop)) = Base_Type (Etype (High_Bound (Rop)))
3727 then
3728 null;
3730 -- If types are not all the same, it means that we have rewritten
3731 -- at least one of them to be of type Long_Long_Integer, and we
3732 -- will convert the other operands to Long_Long_Integer.
3734 else
3735 Convert_To_And_Rewrite (LLIB, Lop);
3736 Set_Analyzed (Lop, False);
3737 Analyze_And_Resolve (Lop, LLIB);
3739 -- For the right operand, avoid unnecessary recursion into
3740 -- this routine, we know that overflow is not possible.
3742 Convert_To_And_Rewrite (LLIB, Low_Bound (Rop));
3743 Convert_To_And_Rewrite (LLIB, High_Bound (Rop));
3744 Set_Analyzed (Rop, False);
3745 Analyze_And_Resolve (Rop, LLIB, Suppress => Overflow_Check);
3746 end if;
3748 -- Now the three operands are of the same signed integer type,
3749 -- so we can use the normal expansion routine for membership,
3750 -- setting the flag to prevent recursion into this procedure.
3752 Set_No_Minimize_Eliminate (N);
3753 Expand_N_In (N);
3754 end if;
3756 -- Right operand is a subtype name and the subtype has a predicate. We
3757 -- have to make sure the predicate is checked, and for that we need to
3758 -- use the standard N_In circuitry with appropriate types.
3760 else
3761 pragma Assert (Present (Predicate_Function (Etype (Rop))));
3763 -- If types are "right", just call Expand_N_In preventing recursion
3765 if Base_Type (Etype (Lop)) = Base_Type (Etype (Rop)) then
3766 Set_No_Minimize_Eliminate (N);
3767 Expand_N_In (N);
3769 -- Bignum case
3771 elsif Is_RTE (Etype (Lop), RE_Bignum) then
3773 -- For X in T, we want to rewrite our node as
3775 -- do
3776 -- Bnn : Result_Type;
3778 -- declare
3779 -- M : Mark_Id := SS_Mark;
3780 -- Lnn : Long_Long_Integer'Base
3781 -- Nnn : Bignum;
3783 -- begin
3784 -- Nnn := X;
3786 -- if not Bignum_In_LLI_Range (Nnn) then
3787 -- Bnn := False;
3788 -- else
3789 -- Lnn := From_Bignum (Nnn);
3790 -- Bnn :=
3791 -- Lnn in LLIB (T'Base'First) .. LLIB (T'Base'Last)
3792 -- and then T'Base (Lnn) in T;
3793 -- end if;
3795 -- SS_Release (M);
3796 -- end
3797 -- in
3798 -- Bnn
3799 -- end
3801 -- A bit gruesome, but there doesn't seem to be a simpler way
3803 declare
3804 Blk : constant Node_Id := Make_Bignum_Block (Loc);
3805 Bnn : constant Entity_Id := Make_Temporary (Loc, 'B', N);
3806 Lnn : constant Entity_Id := Make_Temporary (Loc, 'L', N);
3807 Nnn : constant Entity_Id := Make_Temporary (Loc, 'N', N);
3808 T : constant Entity_Id := Etype (Rop);
3809 TB : constant Entity_Id := Base_Type (T);
3810 Nin : Node_Id;
3812 begin
3813 -- Mark the last membership operation to prevent recursion
3815 Nin :=
3816 Make_In (Loc,
3817 Left_Opnd => Convert_To (TB, New_Occurrence_Of (Lnn, Loc)),
3818 Right_Opnd => New_Occurrence_Of (T, Loc));
3819 Set_No_Minimize_Eliminate (Nin);
3821 -- Now decorate the block
3823 Insert_After
3824 (Last (Declarations (Blk)),
3825 Make_Object_Declaration (Loc,
3826 Defining_Identifier => Lnn,
3827 Object_Definition => New_Occurrence_Of (LLIB, Loc)));
3829 Insert_After
3830 (Last (Declarations (Blk)),
3831 Make_Object_Declaration (Loc,
3832 Defining_Identifier => Nnn,
3833 Object_Definition =>
3834 New_Occurrence_Of (RTE (RE_Bignum), Loc)));
3836 Insert_List_Before
3837 (First (Statements (Handled_Statement_Sequence (Blk))),
3838 New_List (
3839 Make_Assignment_Statement (Loc,
3840 Name => New_Occurrence_Of (Nnn, Loc),
3841 Expression => Relocate_Node (Lop)),
3843 Make_Implicit_If_Statement (N,
3844 Condition =>
3845 Make_Op_Not (Loc,
3846 Right_Opnd =>
3847 Make_Function_Call (Loc,
3848 Name =>
3849 New_Occurrence_Of
3850 (RTE (RE_Bignum_In_LLI_Range), Loc),
3851 Parameter_Associations => New_List (
3852 New_Occurrence_Of (Nnn, Loc)))),
3854 Then_Statements => New_List (
3855 Make_Assignment_Statement (Loc,
3856 Name => New_Occurrence_Of (Bnn, Loc),
3857 Expression =>
3858 New_Occurrence_Of (Standard_False, Loc))),
3860 Else_Statements => New_List (
3861 Make_Assignment_Statement (Loc,
3862 Name => New_Occurrence_Of (Lnn, Loc),
3863 Expression =>
3864 Make_Function_Call (Loc,
3865 Name =>
3866 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
3867 Parameter_Associations => New_List (
3868 New_Occurrence_Of (Nnn, Loc)))),
3870 Make_Assignment_Statement (Loc,
3871 Name => New_Occurrence_Of (Bnn, Loc),
3872 Expression =>
3873 Make_And_Then (Loc,
3874 Left_Opnd =>
3875 Make_In (Loc,
3876 Left_Opnd => New_Occurrence_Of (Lnn, Loc),
3877 Right_Opnd =>
3878 Make_Range (Loc,
3879 Low_Bound =>
3880 Convert_To (LLIB,
3881 Make_Attribute_Reference (Loc,
3882 Attribute_Name => Name_First,
3883 Prefix =>
3884 New_Occurrence_Of (TB, Loc))),
3886 High_Bound =>
3887 Convert_To (LLIB,
3888 Make_Attribute_Reference (Loc,
3889 Attribute_Name => Name_Last,
3890 Prefix =>
3891 New_Occurrence_Of (TB, Loc))))),
3893 Right_Opnd => Nin))))));
3895 -- Now we can do the rewrite
3897 Rewrite (N,
3898 Make_Expression_With_Actions (Loc,
3899 Actions => New_List (
3900 Make_Object_Declaration (Loc,
3901 Defining_Identifier => Bnn,
3902 Object_Definition =>
3903 New_Occurrence_Of (Result_Type, Loc)),
3904 Blk),
3905 Expression => New_Occurrence_Of (Bnn, Loc)));
3906 Analyze_And_Resolve (N, Result_Type);
3907 return;
3908 end;
3910 -- Not bignum case, but types don't match (this means we rewrote the
3911 -- left operand to be Long_Long_Integer).
3913 else
3914 pragma Assert (Base_Type (Etype (Lop)) = LLIB);
3916 -- We rewrite the membership test as (where T is the type with
3917 -- the predicate, i.e. the type of the right operand)
3919 -- Lop in LLIB (T'Base'First) .. LLIB (T'Base'Last)
3920 -- and then T'Base (Lop) in T
3922 declare
3923 T : constant Entity_Id := Etype (Rop);
3924 TB : constant Entity_Id := Base_Type (T);
3925 Nin : Node_Id;
3927 begin
3928 -- The last membership test is marked to prevent recursion
3930 Nin :=
3931 Make_In (Loc,
3932 Left_Opnd => Convert_To (TB, Duplicate_Subexpr (Lop)),
3933 Right_Opnd => New_Occurrence_Of (T, Loc));
3934 Set_No_Minimize_Eliminate (Nin);
3936 -- Now do the rewrite
3938 Rewrite (N,
3939 Make_And_Then (Loc,
3940 Left_Opnd =>
3941 Make_In (Loc,
3942 Left_Opnd => Lop,
3943 Right_Opnd =>
3944 Make_Range (Loc,
3945 Low_Bound =>
3946 Convert_To (LLIB,
3947 Make_Attribute_Reference (Loc,
3948 Attribute_Name => Name_First,
3949 Prefix =>
3950 New_Occurrence_Of (TB, Loc))),
3951 High_Bound =>
3952 Convert_To (LLIB,
3953 Make_Attribute_Reference (Loc,
3954 Attribute_Name => Name_Last,
3955 Prefix =>
3956 New_Occurrence_Of (TB, Loc))))),
3957 Right_Opnd => Nin));
3958 Set_Analyzed (N, False);
3959 Analyze_And_Resolve (N, Restype);
3960 end;
3961 end if;
3962 end if;
3963 end Expand_Membership_Minimize_Eliminate_Overflow;
3965 ----------------------------------
3966 -- Expand_Non_Binary_Modular_Op --
3967 ----------------------------------
3969 procedure Expand_Non_Binary_Modular_Op (N : Node_Id) is
3970 Loc : constant Source_Ptr := Sloc (N);
3971 Typ : constant Entity_Id := Etype (N);
3973 procedure Expand_Modular_Addition;
3974 -- Expand the modular addition handling the special case of adding a
3975 -- constant.
3977 procedure Expand_Modular_Op;
3978 -- Compute the general rule: (lhs OP rhs) mod Modulus
3980 procedure Expand_Modular_Subtraction;
3981 -- Expand the modular addition handling the special case of subtracting
3982 -- a constant.
3984 -----------------------------
3985 -- Expand_Modular_Addition --
3986 -----------------------------
3988 procedure Expand_Modular_Addition is
3989 begin
3990 -- If this is not the addition of a constant then compute it using
3991 -- the general rule: (lhs + rhs) mod Modulus
3993 if Nkind (Right_Opnd (N)) /= N_Integer_Literal then
3994 Expand_Modular_Op;
3996 -- If this is an addition of a constant, convert it to a subtraction
3997 -- plus a conditional expression since we can compute it faster than
3998 -- computing the modulus.
4000 -- modMinusRhs = Modulus - rhs
4001 -- if lhs < modMinusRhs then lhs + rhs
4002 -- else lhs - modMinusRhs
4004 else
4005 declare
4006 Mod_Minus_Right : constant Uint :=
4007 Modulus (Typ) - Intval (Right_Opnd (N));
4009 Exprs : constant List_Id := New_List;
4010 Cond_Expr : constant Node_Id := New_Op_Node (N_Op_Lt, Loc);
4011 Then_Expr : constant Node_Id := New_Op_Node (N_Op_Add, Loc);
4012 Else_Expr : constant Node_Id := New_Op_Node (N_Op_Subtract,
4013 Loc);
4014 begin
4015 Set_Left_Opnd (Cond_Expr,
4016 New_Copy_Tree (Left_Opnd (N)));
4017 Set_Right_Opnd (Cond_Expr,
4018 Make_Integer_Literal (Loc, Mod_Minus_Right));
4019 Append_To (Exprs, Cond_Expr);
4021 Set_Left_Opnd (Then_Expr,
4022 Unchecked_Convert_To (Standard_Unsigned,
4023 New_Copy_Tree (Left_Opnd (N))));
4024 Set_Right_Opnd (Then_Expr,
4025 Make_Integer_Literal (Loc, Intval (Right_Opnd (N))));
4026 Append_To (Exprs, Then_Expr);
4028 Set_Left_Opnd (Else_Expr,
4029 Unchecked_Convert_To (Standard_Unsigned,
4030 New_Copy_Tree (Left_Opnd (N))));
4031 Set_Right_Opnd (Else_Expr,
4032 Make_Integer_Literal (Loc, Mod_Minus_Right));
4033 Append_To (Exprs, Else_Expr);
4035 Rewrite (N,
4036 Unchecked_Convert_To (Typ,
4037 Make_If_Expression (Loc, Expressions => Exprs)));
4038 end;
4039 end if;
4040 end Expand_Modular_Addition;
4042 -----------------------
4043 -- Expand_Modular_Op --
4044 -----------------------
4046 procedure Expand_Modular_Op is
4047 Op_Expr : constant Node_Id := New_Op_Node (Nkind (N), Loc);
4048 Mod_Expr : constant Node_Id := New_Op_Node (N_Op_Mod, Loc);
4050 begin
4051 -- Convert non-binary modular type operands into integer or integer
4052 -- values. Thus we avoid never-ending loops expanding them, and we
4053 -- also ensure that the backend never receives non-binary modular
4054 -- type expressions.
4056 if Nkind_In (Nkind (N), N_Op_And, N_Op_Or) then
4057 Set_Left_Opnd (Op_Expr,
4058 Unchecked_Convert_To (Standard_Unsigned,
4059 New_Copy_Tree (Left_Opnd (N))));
4060 Set_Right_Opnd (Op_Expr,
4061 Unchecked_Convert_To (Standard_Unsigned,
4062 New_Copy_Tree (Right_Opnd (N))));
4063 Set_Left_Opnd (Mod_Expr,
4064 Unchecked_Convert_To (Standard_Integer, Op_Expr));
4065 else
4066 Set_Left_Opnd (Op_Expr,
4067 Unchecked_Convert_To (Standard_Integer,
4068 New_Copy_Tree (Left_Opnd (N))));
4069 Set_Right_Opnd (Op_Expr,
4070 Unchecked_Convert_To (Standard_Integer,
4071 New_Copy_Tree (Right_Opnd (N))));
4072 Set_Left_Opnd (Mod_Expr, Op_Expr);
4073 end if;
4075 Set_Right_Opnd (Mod_Expr,
4076 Make_Integer_Literal (Loc, Modulus (Typ)));
4078 Rewrite (N,
4079 Unchecked_Convert_To (Typ, Mod_Expr));
4080 end Expand_Modular_Op;
4082 --------------------------------
4083 -- Expand_Modular_Subtraction --
4084 --------------------------------
4086 procedure Expand_Modular_Subtraction is
4087 begin
4088 -- If this is not the addition of a constant then compute it using
4089 -- the general rule: (lhs + rhs) mod Modulus
4091 if Nkind (Right_Opnd (N)) /= N_Integer_Literal then
4092 Expand_Modular_Op;
4094 -- If this is an addition of a constant, convert it to a subtraction
4095 -- plus a conditional expression since we can compute it faster than
4096 -- computing the modulus.
4098 -- modMinusRhs = Modulus - rhs
4099 -- if lhs < rhs then lhs + modMinusRhs
4100 -- else lhs - rhs
4102 else
4103 declare
4104 Mod_Minus_Right : constant Uint :=
4105 Modulus (Typ) - Intval (Right_Opnd (N));
4107 Exprs : constant List_Id := New_List;
4108 Cond_Expr : constant Node_Id := New_Op_Node (N_Op_Lt, Loc);
4109 Then_Expr : constant Node_Id := New_Op_Node (N_Op_Add, Loc);
4110 Else_Expr : constant Node_Id := New_Op_Node (N_Op_Subtract,
4111 Loc);
4112 begin
4113 Set_Left_Opnd (Cond_Expr,
4114 New_Copy_Tree (Left_Opnd (N)));
4115 Set_Right_Opnd (Cond_Expr,
4116 Make_Integer_Literal (Loc, Intval (Right_Opnd (N))));
4117 Append_To (Exprs, Cond_Expr);
4119 Set_Left_Opnd (Then_Expr,
4120 Unchecked_Convert_To (Standard_Unsigned,
4121 New_Copy_Tree (Left_Opnd (N))));
4122 Set_Right_Opnd (Then_Expr,
4123 Make_Integer_Literal (Loc, Mod_Minus_Right));
4124 Append_To (Exprs, Then_Expr);
4126 Set_Left_Opnd (Else_Expr,
4127 Unchecked_Convert_To (Standard_Unsigned,
4128 New_Copy_Tree (Left_Opnd (N))));
4129 Set_Right_Opnd (Else_Expr,
4130 Unchecked_Convert_To (Standard_Unsigned,
4131 New_Copy_Tree (Right_Opnd (N))));
4132 Append_To (Exprs, Else_Expr);
4134 Rewrite (N,
4135 Unchecked_Convert_To (Typ,
4136 Make_If_Expression (Loc, Expressions => Exprs)));
4137 end;
4138 end if;
4139 end Expand_Modular_Subtraction;
4141 -- Start of processing for Expand_Non_Binary_Modular_Op
4143 begin
4144 -- No action needed if we are not generating C code for a non-binary
4145 -- modular operand.
4147 if not Modify_Tree_For_C
4148 or else not Non_Binary_Modulus (Typ)
4149 then
4150 return;
4151 end if;
4153 case Nkind (N) is
4154 when N_Op_Add =>
4155 Expand_Modular_Addition;
4157 when N_Op_Subtract =>
4158 Expand_Modular_Subtraction;
4160 when N_Op_Minus =>
4161 -- Expand -expr into (0 - expr)
4163 Rewrite (N,
4164 Make_Op_Subtract (Loc,
4165 Left_Opnd => Make_Integer_Literal (Loc, 0),
4166 Right_Opnd => Right_Opnd (N)));
4167 Analyze_And_Resolve (N, Typ);
4169 when others =>
4170 Expand_Modular_Op;
4171 end case;
4173 Analyze_And_Resolve (N, Typ);
4174 end Expand_Non_Binary_Modular_Op;
4176 ------------------------
4177 -- Expand_N_Allocator --
4178 ------------------------
4180 procedure Expand_N_Allocator (N : Node_Id) is
4181 Etyp : constant Entity_Id := Etype (Expression (N));
4182 Loc : constant Source_Ptr := Sloc (N);
4183 PtrT : constant Entity_Id := Etype (N);
4185 procedure Rewrite_Coextension (N : Node_Id);
4186 -- Static coextensions have the same lifetime as the entity they
4187 -- constrain. Such occurrences can be rewritten as aliased objects
4188 -- and their unrestricted access used instead of the coextension.
4190 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id;
4191 -- Given a constrained array type E, returns a node representing the
4192 -- code to compute the size in storage elements for the given type.
4193 -- This is done without using the attribute (which malfunctions for
4194 -- large sizes ???)
4196 -------------------------
4197 -- Rewrite_Coextension --
4198 -------------------------
4200 procedure Rewrite_Coextension (N : Node_Id) is
4201 Temp_Id : constant Node_Id := Make_Temporary (Loc, 'C');
4202 Temp_Decl : Node_Id;
4204 begin
4205 -- Generate:
4206 -- Cnn : aliased Etyp;
4208 Temp_Decl :=
4209 Make_Object_Declaration (Loc,
4210 Defining_Identifier => Temp_Id,
4211 Aliased_Present => True,
4212 Object_Definition => New_Occurrence_Of (Etyp, Loc));
4214 if Nkind (Expression (N)) = N_Qualified_Expression then
4215 Set_Expression (Temp_Decl, Expression (Expression (N)));
4216 end if;
4218 Insert_Action (N, Temp_Decl);
4219 Rewrite (N,
4220 Make_Attribute_Reference (Loc,
4221 Prefix => New_Occurrence_Of (Temp_Id, Loc),
4222 Attribute_Name => Name_Unrestricted_Access));
4224 Analyze_And_Resolve (N, PtrT);
4225 end Rewrite_Coextension;
4227 ------------------------------
4228 -- Size_In_Storage_Elements --
4229 ------------------------------
4231 function Size_In_Storage_Elements (E : Entity_Id) return Node_Id is
4232 begin
4233 -- Logically this just returns E'Max_Size_In_Storage_Elements.
4234 -- However, the reason for the existence of this function is
4235 -- to construct a test for sizes too large, which means near the
4236 -- 32-bit limit on a 32-bit machine, and precisely the trouble
4237 -- is that we get overflows when sizes are greater than 2**31.
4239 -- So what we end up doing for array types is to use the expression:
4241 -- number-of-elements * component_type'Max_Size_In_Storage_Elements
4243 -- which avoids this problem. All this is a bit bogus, but it does
4244 -- mean we catch common cases of trying to allocate arrays that
4245 -- are too large, and which in the absence of a check results in
4246 -- undetected chaos ???
4248 -- Note in particular that this is a pessimistic estimate in the
4249 -- case of packed array types, where an array element might occupy
4250 -- just a fraction of a storage element???
4252 declare
4253 Len : Node_Id;
4254 Res : Node_Id;
4255 pragma Warnings (Off, Res);
4257 begin
4258 for J in 1 .. Number_Dimensions (E) loop
4259 Len :=
4260 Make_Attribute_Reference (Loc,
4261 Prefix => New_Occurrence_Of (E, Loc),
4262 Attribute_Name => Name_Length,
4263 Expressions => New_List (Make_Integer_Literal (Loc, J)));
4265 if J = 1 then
4266 Res := Len;
4268 else
4269 Res :=
4270 Make_Op_Multiply (Loc,
4271 Left_Opnd => Res,
4272 Right_Opnd => Len);
4273 end if;
4274 end loop;
4276 return
4277 Make_Op_Multiply (Loc,
4278 Left_Opnd => Len,
4279 Right_Opnd =>
4280 Make_Attribute_Reference (Loc,
4281 Prefix => New_Occurrence_Of (Component_Type (E), Loc),
4282 Attribute_Name => Name_Max_Size_In_Storage_Elements));
4283 end;
4284 end Size_In_Storage_Elements;
4286 -- Local variables
4288 Dtyp : constant Entity_Id := Available_View (Designated_Type (PtrT));
4289 Desig : Entity_Id;
4290 Nod : Node_Id;
4291 Pool : Entity_Id;
4292 Rel_Typ : Entity_Id;
4293 Temp : Entity_Id;
4295 -- Start of processing for Expand_N_Allocator
4297 begin
4298 -- RM E.2.3(22). We enforce that the expected type of an allocator
4299 -- shall not be a remote access-to-class-wide-limited-private type
4301 -- Why is this being done at expansion time, seems clearly wrong ???
4303 Validate_Remote_Access_To_Class_Wide_Type (N);
4305 -- Processing for anonymous access-to-controlled types. These access
4306 -- types receive a special finalization master which appears in the
4307 -- declarations of the enclosing semantic unit. This expansion is done
4308 -- now to ensure that any additional types generated by this routine or
4309 -- Expand_Allocator_Expression inherit the proper type attributes.
4311 if (Ekind (PtrT) = E_Anonymous_Access_Type
4312 or else (Is_Itype (PtrT) and then No (Finalization_Master (PtrT))))
4313 and then Needs_Finalization (Dtyp)
4314 then
4315 -- Detect the allocation of an anonymous controlled object where the
4316 -- type of the context is named. For example:
4318 -- procedure Proc (Ptr : Named_Access_Typ);
4319 -- Proc (new Designated_Typ);
4321 -- Regardless of the anonymous-to-named access type conversion, the
4322 -- lifetime of the object must be associated with the named access
4323 -- type. Use the finalization-related attributes of this type.
4325 if Nkind_In (Parent (N), N_Type_Conversion,
4326 N_Unchecked_Type_Conversion)
4327 and then Ekind_In (Etype (Parent (N)), E_Access_Subtype,
4328 E_Access_Type,
4329 E_General_Access_Type)
4330 then
4331 Rel_Typ := Etype (Parent (N));
4332 else
4333 Rel_Typ := Empty;
4334 end if;
4336 -- Anonymous access-to-controlled types allocate on the global pool.
4337 -- Note that this is a "root type only" attribute.
4339 if No (Associated_Storage_Pool (PtrT)) then
4340 if Present (Rel_Typ) then
4341 Set_Associated_Storage_Pool
4342 (Root_Type (PtrT), Associated_Storage_Pool (Rel_Typ));
4343 else
4344 Set_Associated_Storage_Pool
4345 (Root_Type (PtrT), RTE (RE_Global_Pool_Object));
4346 end if;
4347 end if;
4349 -- The finalization master must be inserted and analyzed as part of
4350 -- the current semantic unit. Note that the master is updated when
4351 -- analysis changes current units. Note that this is a "root type
4352 -- only" attribute.
4354 if Present (Rel_Typ) then
4355 Set_Finalization_Master
4356 (Root_Type (PtrT), Finalization_Master (Rel_Typ));
4357 else
4358 Build_Anonymous_Master (Root_Type (PtrT));
4359 end if;
4360 end if;
4362 -- Set the storage pool and find the appropriate version of Allocate to
4363 -- call. Do not overwrite the storage pool if it is already set, which
4364 -- can happen for build-in-place function returns (see
4365 -- Exp_Ch4.Expand_N_Extended_Return_Statement).
4367 if No (Storage_Pool (N)) then
4368 Pool := Associated_Storage_Pool (Root_Type (PtrT));
4370 if Present (Pool) then
4371 Set_Storage_Pool (N, Pool);
4373 if Is_RTE (Pool, RE_SS_Pool) then
4374 Set_Procedure_To_Call (N, RTE (RE_SS_Allocate));
4376 -- In the case of an allocator for a simple storage pool, locate
4377 -- and save a reference to the pool type's Allocate routine.
4379 elsif Present (Get_Rep_Pragma
4380 (Etype (Pool), Name_Simple_Storage_Pool_Type))
4381 then
4382 declare
4383 Pool_Type : constant Entity_Id := Base_Type (Etype (Pool));
4384 Alloc_Op : Entity_Id;
4385 begin
4386 Alloc_Op := Get_Name_Entity_Id (Name_Allocate);
4387 while Present (Alloc_Op) loop
4388 if Scope (Alloc_Op) = Scope (Pool_Type)
4389 and then Present (First_Formal (Alloc_Op))
4390 and then Etype (First_Formal (Alloc_Op)) = Pool_Type
4391 then
4392 Set_Procedure_To_Call (N, Alloc_Op);
4393 exit;
4394 else
4395 Alloc_Op := Homonym (Alloc_Op);
4396 end if;
4397 end loop;
4398 end;
4400 elsif Is_Class_Wide_Type (Etype (Pool)) then
4401 Set_Procedure_To_Call (N, RTE (RE_Allocate_Any));
4403 else
4404 Set_Procedure_To_Call (N,
4405 Find_Prim_Op (Etype (Pool), Name_Allocate));
4406 end if;
4407 end if;
4408 end if;
4410 -- Under certain circumstances we can replace an allocator by an access
4411 -- to statically allocated storage. The conditions, as noted in AARM
4412 -- 3.10 (10c) are as follows:
4414 -- Size and initial value is known at compile time
4415 -- Access type is access-to-constant
4417 -- The allocator is not part of a constraint on a record component,
4418 -- because in that case the inserted actions are delayed until the
4419 -- record declaration is fully analyzed, which is too late for the
4420 -- analysis of the rewritten allocator.
4422 if Is_Access_Constant (PtrT)
4423 and then Nkind (Expression (N)) = N_Qualified_Expression
4424 and then Compile_Time_Known_Value (Expression (Expression (N)))
4425 and then Size_Known_At_Compile_Time
4426 (Etype (Expression (Expression (N))))
4427 and then not Is_Record_Type (Current_Scope)
4428 then
4429 -- Here we can do the optimization. For the allocator
4431 -- new x'(y)
4433 -- We insert an object declaration
4435 -- Tnn : aliased x := y;
4437 -- and replace the allocator by Tnn'Unrestricted_Access. Tnn is
4438 -- marked as requiring static allocation.
4440 Temp := Make_Temporary (Loc, 'T', Expression (Expression (N)));
4441 Desig := Subtype_Mark (Expression (N));
4443 -- If context is constrained, use constrained subtype directly,
4444 -- so that the constant is not labelled as having a nominally
4445 -- unconstrained subtype.
4447 if Entity (Desig) = Base_Type (Dtyp) then
4448 Desig := New_Occurrence_Of (Dtyp, Loc);
4449 end if;
4451 Insert_Action (N,
4452 Make_Object_Declaration (Loc,
4453 Defining_Identifier => Temp,
4454 Aliased_Present => True,
4455 Constant_Present => Is_Access_Constant (PtrT),
4456 Object_Definition => Desig,
4457 Expression => Expression (Expression (N))));
4459 Rewrite (N,
4460 Make_Attribute_Reference (Loc,
4461 Prefix => New_Occurrence_Of (Temp, Loc),
4462 Attribute_Name => Name_Unrestricted_Access));
4464 Analyze_And_Resolve (N, PtrT);
4466 -- We set the variable as statically allocated, since we don't want
4467 -- it going on the stack of the current procedure.
4469 Set_Is_Statically_Allocated (Temp);
4470 return;
4471 end if;
4473 -- Same if the allocator is an access discriminant for a local object:
4474 -- instead of an allocator we create a local value and constrain the
4475 -- enclosing object with the corresponding access attribute.
4477 if Is_Static_Coextension (N) then
4478 Rewrite_Coextension (N);
4479 return;
4480 end if;
4482 -- Check for size too large, we do this because the back end misses
4483 -- proper checks here and can generate rubbish allocation calls when
4484 -- we are near the limit. We only do this for the 32-bit address case
4485 -- since that is from a practical point of view where we see a problem.
4487 if System_Address_Size = 32
4488 and then not Storage_Checks_Suppressed (PtrT)
4489 and then not Storage_Checks_Suppressed (Dtyp)
4490 and then not Storage_Checks_Suppressed (Etyp)
4491 then
4492 -- The check we want to generate should look like
4494 -- if Etyp'Max_Size_In_Storage_Elements > 3.5 gigabytes then
4495 -- raise Storage_Error;
4496 -- end if;
4498 -- where 3.5 gigabytes is a constant large enough to accommodate any
4499 -- reasonable request for. But we can't do it this way because at
4500 -- least at the moment we don't compute this attribute right, and
4501 -- can silently give wrong results when the result gets large. Since
4502 -- this is all about large results, that's bad, so instead we only
4503 -- apply the check for constrained arrays, and manually compute the
4504 -- value of the attribute ???
4506 if Is_Array_Type (Etyp) and then Is_Constrained (Etyp) then
4507 Insert_Action (N,
4508 Make_Raise_Storage_Error (Loc,
4509 Condition =>
4510 Make_Op_Gt (Loc,
4511 Left_Opnd => Size_In_Storage_Elements (Etyp),
4512 Right_Opnd =>
4513 Make_Integer_Literal (Loc, Uint_7 * (Uint_2 ** 29))),
4514 Reason => SE_Object_Too_Large));
4515 end if;
4516 end if;
4518 -- If no storage pool has been specified and we have the restriction
4519 -- No_Standard_Allocators_After_Elaboration is present, then generate
4520 -- a call to Elaboration_Allocators.Check_Standard_Allocator.
4522 if Nkind (N) = N_Allocator
4523 and then No (Storage_Pool (N))
4524 and then Restriction_Active (No_Standard_Allocators_After_Elaboration)
4525 then
4526 Insert_Action (N,
4527 Make_Procedure_Call_Statement (Loc,
4528 Name =>
4529 New_Occurrence_Of (RTE (RE_Check_Standard_Allocator), Loc)));
4530 end if;
4532 -- Handle case of qualified expression (other than optimization above)
4533 -- First apply constraint checks, because the bounds or discriminants
4534 -- in the aggregate might not match the subtype mark in the allocator.
4536 if Nkind (Expression (N)) = N_Qualified_Expression then
4537 declare
4538 Exp : constant Node_Id := Expression (Expression (N));
4539 Typ : constant Entity_Id := Etype (Expression (N));
4541 begin
4542 Apply_Constraint_Check (Exp, Typ);
4543 Apply_Predicate_Check (Exp, Typ);
4544 end;
4546 Expand_Allocator_Expression (N);
4547 return;
4548 end if;
4550 -- If the allocator is for a type which requires initialization, and
4551 -- there is no initial value (i.e. operand is a subtype indication
4552 -- rather than a qualified expression), then we must generate a call to
4553 -- the initialization routine using an expressions action node:
4555 -- [Pnnn : constant ptr_T := new (T); Init (Pnnn.all,...); Pnnn]
4557 -- Here ptr_T is the pointer type for the allocator, and T is the
4558 -- subtype of the allocator. A special case arises if the designated
4559 -- type of the access type is a task or contains tasks. In this case
4560 -- the call to Init (Temp.all ...) is replaced by code that ensures
4561 -- that tasks get activated (see Exp_Ch9.Build_Task_Allocate_Block
4562 -- for details). In addition, if the type T is a task type, then the
4563 -- first argument to Init must be converted to the task record type.
4565 declare
4566 T : constant Entity_Id := Entity (Expression (N));
4567 Args : List_Id;
4568 Decls : List_Id;
4569 Decl : Node_Id;
4570 Discr : Elmt_Id;
4571 Init : Entity_Id;
4572 Init_Arg1 : Node_Id;
4573 Init_Call : Node_Id;
4574 Temp_Decl : Node_Id;
4575 Temp_Type : Entity_Id;
4577 begin
4578 if No_Initialization (N) then
4580 -- Even though this might be a simple allocation, create a custom
4581 -- Allocate if the context requires it.
4583 if Present (Finalization_Master (PtrT)) then
4584 Build_Allocate_Deallocate_Proc
4585 (N => N,
4586 Is_Allocate => True);
4587 end if;
4589 -- Case of no initialization procedure present
4591 elsif not Has_Non_Null_Base_Init_Proc (T) then
4593 -- Case of simple initialization required
4595 if Needs_Simple_Initialization (T) then
4596 Check_Restriction (No_Default_Initialization, N);
4597 Rewrite (Expression (N),
4598 Make_Qualified_Expression (Loc,
4599 Subtype_Mark => New_Occurrence_Of (T, Loc),
4600 Expression => Get_Simple_Init_Val (T, N)));
4602 Analyze_And_Resolve (Expression (Expression (N)), T);
4603 Analyze_And_Resolve (Expression (N), T);
4604 Set_Paren_Count (Expression (Expression (N)), 1);
4605 Expand_N_Allocator (N);
4607 -- No initialization required
4609 else
4610 null;
4611 end if;
4613 -- Case of initialization procedure present, must be called
4615 else
4616 Check_Restriction (No_Default_Initialization, N);
4618 if not Restriction_Active (No_Default_Initialization) then
4619 Init := Base_Init_Proc (T);
4620 Nod := N;
4621 Temp := Make_Temporary (Loc, 'P');
4623 -- Construct argument list for the initialization routine call
4625 Init_Arg1 :=
4626 Make_Explicit_Dereference (Loc,
4627 Prefix =>
4628 New_Occurrence_Of (Temp, Loc));
4630 Set_Assignment_OK (Init_Arg1);
4631 Temp_Type := PtrT;
4633 -- The initialization procedure expects a specific type. if the
4634 -- context is access to class wide, indicate that the object
4635 -- being allocated has the right specific type.
4637 if Is_Class_Wide_Type (Dtyp) then
4638 Init_Arg1 := Unchecked_Convert_To (T, Init_Arg1);
4639 end if;
4641 -- If designated type is a concurrent type or if it is private
4642 -- type whose definition is a concurrent type, the first
4643 -- argument in the Init routine has to be unchecked conversion
4644 -- to the corresponding record type. If the designated type is
4645 -- a derived type, also convert the argument to its root type.
4647 if Is_Concurrent_Type (T) then
4648 Init_Arg1 :=
4649 Unchecked_Convert_To (
4650 Corresponding_Record_Type (T), Init_Arg1);
4652 elsif Is_Private_Type (T)
4653 and then Present (Full_View (T))
4654 and then Is_Concurrent_Type (Full_View (T))
4655 then
4656 Init_Arg1 :=
4657 Unchecked_Convert_To
4658 (Corresponding_Record_Type (Full_View (T)), Init_Arg1);
4660 elsif Etype (First_Formal (Init)) /= Base_Type (T) then
4661 declare
4662 Ftyp : constant Entity_Id := Etype (First_Formal (Init));
4664 begin
4665 Init_Arg1 := OK_Convert_To (Etype (Ftyp), Init_Arg1);
4666 Set_Etype (Init_Arg1, Ftyp);
4667 end;
4668 end if;
4670 Args := New_List (Init_Arg1);
4672 -- For the task case, pass the Master_Id of the access type as
4673 -- the value of the _Master parameter, and _Chain as the value
4674 -- of the _Chain parameter (_Chain will be defined as part of
4675 -- the generated code for the allocator).
4677 -- In Ada 2005, the context may be a function that returns an
4678 -- anonymous access type. In that case the Master_Id has been
4679 -- created when expanding the function declaration.
4681 if Has_Task (T) then
4682 if No (Master_Id (Base_Type (PtrT))) then
4684 -- The designated type was an incomplete type, and the
4685 -- access type did not get expanded. Salvage it now.
4687 if not Restriction_Active (No_Task_Hierarchy) then
4688 if Present (Parent (Base_Type (PtrT))) then
4689 Expand_N_Full_Type_Declaration
4690 (Parent (Base_Type (PtrT)));
4692 -- The only other possibility is an itype. For this
4693 -- case, the master must exist in the context. This is
4694 -- the case when the allocator initializes an access
4695 -- component in an init-proc.
4697 else
4698 pragma Assert (Is_Itype (PtrT));
4699 Build_Master_Renaming (PtrT, N);
4700 end if;
4701 end if;
4702 end if;
4704 -- If the context of the allocator is a declaration or an
4705 -- assignment, we can generate a meaningful image for it,
4706 -- even though subsequent assignments might remove the
4707 -- connection between task and entity. We build this image
4708 -- when the left-hand side is a simple variable, a simple
4709 -- indexed assignment or a simple selected component.
4711 if Nkind (Parent (N)) = N_Assignment_Statement then
4712 declare
4713 Nam : constant Node_Id := Name (Parent (N));
4715 begin
4716 if Is_Entity_Name (Nam) then
4717 Decls :=
4718 Build_Task_Image_Decls
4719 (Loc,
4720 New_Occurrence_Of
4721 (Entity (Nam), Sloc (Nam)), T);
4723 elsif Nkind_In (Nam, N_Indexed_Component,
4724 N_Selected_Component)
4725 and then Is_Entity_Name (Prefix (Nam))
4726 then
4727 Decls :=
4728 Build_Task_Image_Decls
4729 (Loc, Nam, Etype (Prefix (Nam)));
4730 else
4731 Decls := Build_Task_Image_Decls (Loc, T, T);
4732 end if;
4733 end;
4735 elsif Nkind (Parent (N)) = N_Object_Declaration then
4736 Decls :=
4737 Build_Task_Image_Decls
4738 (Loc, Defining_Identifier (Parent (N)), T);
4740 else
4741 Decls := Build_Task_Image_Decls (Loc, T, T);
4742 end if;
4744 if Restriction_Active (No_Task_Hierarchy) then
4745 Append_To (Args,
4746 New_Occurrence_Of (RTE (RE_Library_Task_Level), Loc));
4747 else
4748 Append_To (Args,
4749 New_Occurrence_Of
4750 (Master_Id (Base_Type (Root_Type (PtrT))), Loc));
4751 end if;
4753 Append_To (Args, Make_Identifier (Loc, Name_uChain));
4755 Decl := Last (Decls);
4756 Append_To (Args,
4757 New_Occurrence_Of (Defining_Identifier (Decl), Loc));
4759 -- Has_Task is false, Decls not used
4761 else
4762 Decls := No_List;
4763 end if;
4765 -- Add discriminants if discriminated type
4767 declare
4768 Dis : Boolean := False;
4769 Typ : Entity_Id;
4771 begin
4772 if Has_Discriminants (T) then
4773 Dis := True;
4774 Typ := T;
4776 -- Type may be a private type with no visible discriminants
4777 -- in which case check full view if in scope, or the
4778 -- underlying_full_view if dealing with a type whose full
4779 -- view may be derived from a private type whose own full
4780 -- view has discriminants.
4782 elsif Is_Private_Type (T) then
4783 if Present (Full_View (T))
4784 and then Has_Discriminants (Full_View (T))
4785 then
4786 Dis := True;
4787 Typ := Full_View (T);
4789 elsif Present (Underlying_Full_View (T))
4790 and then Has_Discriminants (Underlying_Full_View (T))
4791 then
4792 Dis := True;
4793 Typ := Underlying_Full_View (T);
4794 end if;
4795 end if;
4797 if Dis then
4799 -- If the allocated object will be constrained by the
4800 -- default values for discriminants, then build a subtype
4801 -- with those defaults, and change the allocated subtype
4802 -- to that. Note that this happens in fewer cases in Ada
4803 -- 2005 (AI-363).
4805 if not Is_Constrained (Typ)
4806 and then Present (Discriminant_Default_Value
4807 (First_Discriminant (Typ)))
4808 and then (Ada_Version < Ada_2005
4809 or else not
4810 Object_Type_Has_Constrained_Partial_View
4811 (Typ, Current_Scope))
4812 then
4813 Typ := Build_Default_Subtype (Typ, N);
4814 Set_Expression (N, New_Occurrence_Of (Typ, Loc));
4815 end if;
4817 Discr := First_Elmt (Discriminant_Constraint (Typ));
4818 while Present (Discr) loop
4819 Nod := Node (Discr);
4820 Append (New_Copy_Tree (Node (Discr)), Args);
4822 -- AI-416: when the discriminant constraint is an
4823 -- anonymous access type make sure an accessibility
4824 -- check is inserted if necessary (3.10.2(22.q/2))
4826 if Ada_Version >= Ada_2005
4827 and then
4828 Ekind (Etype (Nod)) = E_Anonymous_Access_Type
4829 then
4830 Apply_Accessibility_Check
4831 (Nod, Typ, Insert_Node => Nod);
4832 end if;
4834 Next_Elmt (Discr);
4835 end loop;
4836 end if;
4837 end;
4839 -- We set the allocator as analyzed so that when we analyze
4840 -- the if expression node, we do not get an unwanted recursive
4841 -- expansion of the allocator expression.
4843 Set_Analyzed (N, True);
4844 Nod := Relocate_Node (N);
4846 -- Here is the transformation:
4847 -- input: new Ctrl_Typ
4848 -- output: Temp : constant Ctrl_Typ_Ptr := new Ctrl_Typ;
4849 -- Ctrl_TypIP (Temp.all, ...);
4850 -- [Deep_]Initialize (Temp.all);
4852 -- Here Ctrl_Typ_Ptr is the pointer type for the allocator, and
4853 -- is the subtype of the allocator.
4855 Temp_Decl :=
4856 Make_Object_Declaration (Loc,
4857 Defining_Identifier => Temp,
4858 Constant_Present => True,
4859 Object_Definition => New_Occurrence_Of (Temp_Type, Loc),
4860 Expression => Nod);
4862 Set_Assignment_OK (Temp_Decl);
4863 Insert_Action (N, Temp_Decl, Suppress => All_Checks);
4865 Build_Allocate_Deallocate_Proc (Temp_Decl, True);
4867 -- If the designated type is a task type or contains tasks,
4868 -- create block to activate created tasks, and insert
4869 -- declaration for Task_Image variable ahead of call.
4871 if Has_Task (T) then
4872 declare
4873 L : constant List_Id := New_List;
4874 Blk : Node_Id;
4875 begin
4876 Build_Task_Allocate_Block (L, Nod, Args);
4877 Blk := Last (L);
4878 Insert_List_Before (First (Declarations (Blk)), Decls);
4879 Insert_Actions (N, L);
4880 end;
4882 else
4883 Insert_Action (N,
4884 Make_Procedure_Call_Statement (Loc,
4885 Name => New_Occurrence_Of (Init, Loc),
4886 Parameter_Associations => Args));
4887 end if;
4889 if Needs_Finalization (T) then
4891 -- Generate:
4892 -- [Deep_]Initialize (Init_Arg1);
4894 Init_Call :=
4895 Make_Init_Call
4896 (Obj_Ref => New_Copy_Tree (Init_Arg1),
4897 Typ => T);
4899 -- Guard against a missing [Deep_]Initialize when the
4900 -- designated type was not properly frozen.
4902 if Present (Init_Call) then
4903 Insert_Action (N, Init_Call);
4904 end if;
4905 end if;
4907 Rewrite (N, New_Occurrence_Of (Temp, Loc));
4908 Analyze_And_Resolve (N, PtrT);
4909 end if;
4910 end if;
4911 end;
4913 -- Ada 2005 (AI-251): If the allocator is for a class-wide interface
4914 -- object that has been rewritten as a reference, we displace "this"
4915 -- to reference properly its secondary dispatch table.
4917 if Nkind (N) = N_Identifier and then Is_Interface (Dtyp) then
4918 Displace_Allocator_Pointer (N);
4919 end if;
4921 exception
4922 when RE_Not_Available =>
4923 return;
4924 end Expand_N_Allocator;
4926 -----------------------
4927 -- Expand_N_And_Then --
4928 -----------------------
4930 procedure Expand_N_And_Then (N : Node_Id)
4931 renames Expand_Short_Circuit_Operator;
4933 ------------------------------
4934 -- Expand_N_Case_Expression --
4935 ------------------------------
4937 procedure Expand_N_Case_Expression (N : Node_Id) is
4939 function Is_Copy_Type (Typ : Entity_Id) return Boolean;
4940 -- Return True if we can copy objects of this type when expanding a case
4941 -- expression.
4943 ------------------
4944 -- Is_Copy_Type --
4945 ------------------
4947 function Is_Copy_Type (Typ : Entity_Id) return Boolean is
4948 begin
4949 -- If Minimize_Expression_With_Actions is True, we can afford to copy
4950 -- large objects, as long as they are constrained and not limited.
4952 return
4953 Is_Elementary_Type (Underlying_Type (Typ))
4954 or else
4955 (Minimize_Expression_With_Actions
4956 and then Is_Constrained (Underlying_Type (Typ))
4957 and then not Is_Limited_View (Underlying_Type (Typ)));
4958 end Is_Copy_Type;
4960 -- Local variables
4962 Loc : constant Source_Ptr := Sloc (N);
4963 Par : constant Node_Id := Parent (N);
4964 Typ : constant Entity_Id := Etype (N);
4966 Acts : List_Id;
4967 Alt : Node_Id;
4968 Case_Stmt : Node_Id;
4969 Decl : Node_Id;
4970 Expr : Node_Id;
4971 Target : Entity_Id;
4972 Target_Typ : Entity_Id;
4974 In_Predicate : Boolean := False;
4975 -- Flag set when the case expression appears within a predicate
4977 Optimize_Return_Stmt : Boolean := False;
4978 -- Flag set when the case expression can be optimized in the context of
4979 -- a simple return statement.
4981 -- Start of processing for Expand_N_Case_Expression
4983 begin
4984 -- Check for MINIMIZED/ELIMINATED overflow mode
4986 if Minimized_Eliminated_Overflow_Check (N) then
4987 Apply_Arithmetic_Overflow_Check (N);
4988 return;
4989 end if;
4991 -- If the case expression is a predicate specification, and the type
4992 -- to which it applies has a static predicate aspect, do not expand,
4993 -- because it will be converted to the proper predicate form later.
4995 if Ekind_In (Current_Scope, E_Function, E_Procedure)
4996 and then Is_Predicate_Function (Current_Scope)
4997 then
4998 In_Predicate := True;
5000 if Has_Static_Predicate_Aspect (Etype (First_Entity (Current_Scope)))
5001 then
5002 return;
5003 end if;
5004 end if;
5006 -- When the type of the case expression is elementary, expand
5008 -- (case X is when A => AX, when B => BX ...)
5010 -- into
5012 -- do
5013 -- Target : Typ;
5014 -- case X is
5015 -- when A =>
5016 -- Target := AX;
5017 -- when B =>
5018 -- Target := BX;
5019 -- ...
5020 -- end case;
5021 -- in Target end;
5023 -- In all other cases expand into
5025 -- do
5026 -- type Ptr_Typ is access all Typ;
5027 -- Target : Ptr_Typ;
5028 -- case X is
5029 -- when A =>
5030 -- Target := AX'Unrestricted_Access;
5031 -- when B =>
5032 -- Target := BX'Unrestricted_Access;
5033 -- ...
5034 -- end case;
5035 -- in Target.all end;
5037 -- This approach avoids extra copies of potentially large objects. It
5038 -- also allows handling of values of limited or unconstrained types.
5039 -- Note that we do the copy also for constrained, nonlimited types
5040 -- when minimizing expressions with actions (e.g. when generating C
5041 -- code) since it allows us to do the optimization below in more cases.
5043 -- Small optimization: when the case expression appears in the context
5044 -- of a simple return statement, expand into
5046 -- case X is
5047 -- when A =>
5048 -- return AX;
5049 -- when B =>
5050 -- return BX;
5051 -- ...
5052 -- end case;
5054 Case_Stmt :=
5055 Make_Case_Statement (Loc,
5056 Expression => Expression (N),
5057 Alternatives => New_List);
5059 -- Preserve the original context for which the case statement is being
5060 -- generated. This is needed by the finalization machinery to prevent
5061 -- the premature finalization of controlled objects found within the
5062 -- case statement.
5064 Set_From_Conditional_Expression (Case_Stmt);
5065 Acts := New_List;
5067 -- Scalar/Copy case
5069 if Is_Copy_Type (Typ) then
5070 Target_Typ := Typ;
5072 -- ??? Do not perform the optimization when the return statement is
5073 -- within a predicate function, as this causes spurious errors. Could
5074 -- this be a possible mismatch in handling this case somewhere else
5075 -- in semantic analysis?
5077 Optimize_Return_Stmt :=
5078 Nkind (Par) = N_Simple_Return_Statement and then not In_Predicate;
5080 -- Otherwise create an access type to handle the general case using
5081 -- 'Unrestricted_Access.
5083 -- Generate:
5084 -- type Ptr_Typ is access all Typ;
5086 else
5087 if Generate_C_Code then
5089 -- We cannot ensure that correct C code will be generated if any
5090 -- temporary is created down the line (to e.g. handle checks or
5091 -- capture values) since we might end up with dangling references
5092 -- to local variables, so better be safe and reject the construct.
5094 Error_Msg_N
5095 ("case expression too complex, use case statement instead", N);
5096 end if;
5098 Target_Typ := Make_Temporary (Loc, 'P');
5100 Append_To (Acts,
5101 Make_Full_Type_Declaration (Loc,
5102 Defining_Identifier => Target_Typ,
5103 Type_Definition =>
5104 Make_Access_To_Object_Definition (Loc,
5105 All_Present => True,
5106 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5107 end if;
5109 -- Create the declaration of the target which captures the value of the
5110 -- expression.
5112 -- Generate:
5113 -- Target : [Ptr_]Typ;
5115 if not Optimize_Return_Stmt then
5116 Target := Make_Temporary (Loc, 'T');
5118 Decl :=
5119 Make_Object_Declaration (Loc,
5120 Defining_Identifier => Target,
5121 Object_Definition => New_Occurrence_Of (Target_Typ, Loc));
5122 Set_No_Initialization (Decl);
5124 Append_To (Acts, Decl);
5125 end if;
5127 -- Process the alternatives
5129 Alt := First (Alternatives (N));
5130 while Present (Alt) loop
5131 declare
5132 Alt_Expr : Node_Id := Expression (Alt);
5133 Alt_Loc : constant Source_Ptr := Sloc (Alt_Expr);
5134 Stmts : List_Id;
5136 begin
5137 -- Take the unrestricted access of the expression value for non-
5138 -- scalar types. This approach avoids big copies and covers the
5139 -- limited and unconstrained cases.
5141 -- Generate:
5142 -- AX'Unrestricted_Access
5144 if not Is_Copy_Type (Typ) then
5145 Alt_Expr :=
5146 Make_Attribute_Reference (Alt_Loc,
5147 Prefix => Relocate_Node (Alt_Expr),
5148 Attribute_Name => Name_Unrestricted_Access);
5149 end if;
5151 -- Generate:
5152 -- return AX['Unrestricted_Access];
5154 if Optimize_Return_Stmt then
5155 Stmts := New_List (
5156 Make_Simple_Return_Statement (Alt_Loc,
5157 Expression => Alt_Expr));
5159 -- Generate:
5160 -- Target := AX['Unrestricted_Access];
5162 else
5163 Stmts := New_List (
5164 Make_Assignment_Statement (Alt_Loc,
5165 Name => New_Occurrence_Of (Target, Loc),
5166 Expression => Alt_Expr));
5167 end if;
5169 -- Propagate declarations inserted in the node by Insert_Actions
5170 -- (for example, temporaries generated to remove side effects).
5171 -- These actions must remain attached to the alternative, given
5172 -- that they are generated by the corresponding expression.
5174 if Present (Actions (Alt)) then
5175 Prepend_List (Actions (Alt), Stmts);
5176 end if;
5178 -- Finalize any transient objects on exit from the alternative.
5179 -- This is done only in the return optimization case because
5180 -- otherwise the case expression is converted into an expression
5181 -- with actions which already contains this form of processing.
5183 if Optimize_Return_Stmt then
5184 Process_If_Case_Statements (N, Stmts);
5185 end if;
5187 Append_To
5188 (Alternatives (Case_Stmt),
5189 Make_Case_Statement_Alternative (Sloc (Alt),
5190 Discrete_Choices => Discrete_Choices (Alt),
5191 Statements => Stmts));
5192 end;
5194 Next (Alt);
5195 end loop;
5197 -- Rewrite the parent return statement as a case statement
5199 if Optimize_Return_Stmt then
5200 Rewrite (Par, Case_Stmt);
5201 Analyze (Par);
5203 -- Otherwise convert the case expression into an expression with actions
5205 else
5206 Append_To (Acts, Case_Stmt);
5208 if Is_Copy_Type (Typ) then
5209 Expr := New_Occurrence_Of (Target, Loc);
5211 else
5212 Expr :=
5213 Make_Explicit_Dereference (Loc,
5214 Prefix => New_Occurrence_Of (Target, Loc));
5215 end if;
5217 -- Generate:
5218 -- do
5219 -- ...
5220 -- in Target[.all] end;
5222 Rewrite (N,
5223 Make_Expression_With_Actions (Loc,
5224 Expression => Expr,
5225 Actions => Acts));
5227 Analyze_And_Resolve (N, Typ);
5228 end if;
5229 end Expand_N_Case_Expression;
5231 -----------------------------------
5232 -- Expand_N_Explicit_Dereference --
5233 -----------------------------------
5235 procedure Expand_N_Explicit_Dereference (N : Node_Id) is
5236 begin
5237 -- Insert explicit dereference call for the checked storage pool case
5239 Insert_Dereference_Action (Prefix (N));
5241 -- If the type is an Atomic type for which Atomic_Sync is enabled, then
5242 -- we set the atomic sync flag.
5244 if Is_Atomic (Etype (N))
5245 and then not Atomic_Synchronization_Disabled (Etype (N))
5246 then
5247 Activate_Atomic_Synchronization (N);
5248 end if;
5249 end Expand_N_Explicit_Dereference;
5251 --------------------------------------
5252 -- Expand_N_Expression_With_Actions --
5253 --------------------------------------
5255 procedure Expand_N_Expression_With_Actions (N : Node_Id) is
5256 Acts : constant List_Id := Actions (N);
5258 procedure Force_Boolean_Evaluation (Expr : Node_Id);
5259 -- Force the evaluation of Boolean expression Expr
5261 function Process_Action (Act : Node_Id) return Traverse_Result;
5262 -- Inspect and process a single action of an expression_with_actions for
5263 -- transient objects. If such objects are found, the routine generates
5264 -- code to clean them up when the context of the expression is evaluated
5265 -- or elaborated.
5267 ------------------------------
5268 -- Force_Boolean_Evaluation --
5269 ------------------------------
5271 procedure Force_Boolean_Evaluation (Expr : Node_Id) is
5272 Loc : constant Source_Ptr := Sloc (N);
5273 Flag_Decl : Node_Id;
5274 Flag_Id : Entity_Id;
5276 begin
5277 -- Relocate the expression to the actions list by capturing its value
5278 -- in a Boolean flag. Generate:
5279 -- Flag : constant Boolean := Expr;
5281 Flag_Id := Make_Temporary (Loc, 'F');
5283 Flag_Decl :=
5284 Make_Object_Declaration (Loc,
5285 Defining_Identifier => Flag_Id,
5286 Constant_Present => True,
5287 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
5288 Expression => Relocate_Node (Expr));
5290 Append (Flag_Decl, Acts);
5291 Analyze (Flag_Decl);
5293 -- Replace the expression with a reference to the flag
5295 Rewrite (Expression (N), New_Occurrence_Of (Flag_Id, Loc));
5296 Analyze (Expression (N));
5297 end Force_Boolean_Evaluation;
5299 --------------------
5300 -- Process_Action --
5301 --------------------
5303 function Process_Action (Act : Node_Id) return Traverse_Result is
5304 begin
5305 if Nkind (Act) = N_Object_Declaration
5306 and then Is_Finalizable_Transient (Act, N)
5307 then
5308 Process_Transient_In_Expression (Act, N, Acts);
5309 return Abandon;
5311 -- Avoid processing temporary function results multiple times when
5312 -- dealing with nested expression_with_actions.
5314 elsif Nkind (Act) = N_Expression_With_Actions then
5315 return Abandon;
5317 -- Do not process temporary function results in loops. This is done
5318 -- by Expand_N_Loop_Statement and Build_Finalizer.
5320 elsif Nkind (Act) = N_Loop_Statement then
5321 return Abandon;
5322 end if;
5324 return OK;
5325 end Process_Action;
5327 procedure Process_Single_Action is new Traverse_Proc (Process_Action);
5329 -- Local variables
5331 Act : Node_Id;
5333 -- Start of processing for Expand_N_Expression_With_Actions
5335 begin
5336 -- Do not evaluate the expression when it denotes an entity because the
5337 -- expression_with_actions node will be replaced by the reference.
5339 if Is_Entity_Name (Expression (N)) then
5340 null;
5342 -- Do not evaluate the expression when there are no actions because the
5343 -- expression_with_actions node will be replaced by the expression.
5345 elsif No (Acts) or else Is_Empty_List (Acts) then
5346 null;
5348 -- Force the evaluation of the expression by capturing its value in a
5349 -- temporary. This ensures that aliases of transient objects do not leak
5350 -- to the expression of the expression_with_actions node:
5352 -- do
5353 -- Trans_Id : Ctrl_Typ := ...;
5354 -- Alias : ... := Trans_Id;
5355 -- in ... Alias ... end;
5357 -- In the example above, Trans_Id cannot be finalized at the end of the
5358 -- actions list because this may affect the alias and the final value of
5359 -- the expression_with_actions. Forcing the evaluation encapsulates the
5360 -- reference to the Alias within the actions list:
5362 -- do
5363 -- Trans_Id : Ctrl_Typ := ...;
5364 -- Alias : ... := Trans_Id;
5365 -- Val : constant Boolean := ... Alias ...;
5366 -- <finalize Trans_Id>
5367 -- in Val end;
5369 -- Once this transformation is performed, it is safe to finalize the
5370 -- transient object at the end of the actions list.
5372 -- Note that Force_Evaluation does not remove side effects in operators
5373 -- because it assumes that all operands are evaluated and side effect
5374 -- free. This is not the case when an operand depends implicitly on the
5375 -- transient object through the use of access types.
5377 elsif Is_Boolean_Type (Etype (Expression (N))) then
5378 Force_Boolean_Evaluation (Expression (N));
5380 -- The expression of an expression_with_actions node may not necessarily
5381 -- be Boolean when the node appears in an if expression. In this case do
5382 -- the usual forced evaluation to encapsulate potential aliasing.
5384 else
5385 Force_Evaluation (Expression (N));
5386 end if;
5388 -- Process all transient objects found within the actions of the EWA
5389 -- node.
5391 Act := First (Acts);
5392 while Present (Act) loop
5393 Process_Single_Action (Act);
5394 Next (Act);
5395 end loop;
5397 -- Deal with case where there are no actions. In this case we simply
5398 -- rewrite the node with its expression since we don't need the actions
5399 -- and the specification of this node does not allow a null action list.
5401 -- Note: we use Rewrite instead of Replace, because Codepeer is using
5402 -- the expanded tree and relying on being able to retrieve the original
5403 -- tree in cases like this. This raises a whole lot of issues of whether
5404 -- we have problems elsewhere, which will be addressed in the future???
5406 if Is_Empty_List (Acts) then
5407 Rewrite (N, Relocate_Node (Expression (N)));
5408 end if;
5409 end Expand_N_Expression_With_Actions;
5411 ----------------------------
5412 -- Expand_N_If_Expression --
5413 ----------------------------
5415 -- Deal with limited types and condition actions
5417 procedure Expand_N_If_Expression (N : Node_Id) is
5418 Cond : constant Node_Id := First (Expressions (N));
5419 Loc : constant Source_Ptr := Sloc (N);
5420 Thenx : constant Node_Id := Next (Cond);
5421 Elsex : constant Node_Id := Next (Thenx);
5422 Typ : constant Entity_Id := Etype (N);
5424 Actions : List_Id;
5425 Cnn : Entity_Id;
5426 Decl : Node_Id;
5427 Expr : Node_Id;
5428 New_If : Node_Id;
5429 New_N : Node_Id;
5430 Ptr_Typ : Entity_Id;
5432 begin
5433 -- Check for MINIMIZED/ELIMINATED overflow mode
5435 if Minimized_Eliminated_Overflow_Check (N) then
5436 Apply_Arithmetic_Overflow_Check (N);
5437 return;
5438 end if;
5440 -- Fold at compile time if condition known. We have already folded
5441 -- static if expressions, but it is possible to fold any case in which
5442 -- the condition is known at compile time, even though the result is
5443 -- non-static.
5445 -- Note that we don't do the fold of such cases in Sem_Elab because
5446 -- it can cause infinite loops with the expander adding a conditional
5447 -- expression, and Sem_Elab circuitry removing it repeatedly.
5449 if Compile_Time_Known_Value (Cond) then
5450 declare
5451 function Fold_Known_Value (Cond : Node_Id) return Boolean;
5452 -- Fold at compile time. Assumes condition known. Return True if
5453 -- folding occurred, meaning we're done.
5455 ----------------------
5456 -- Fold_Known_Value --
5457 ----------------------
5459 function Fold_Known_Value (Cond : Node_Id) return Boolean is
5460 begin
5461 if Is_True (Expr_Value (Cond)) then
5462 Expr := Thenx;
5463 Actions := Then_Actions (N);
5464 else
5465 Expr := Elsex;
5466 Actions := Else_Actions (N);
5467 end if;
5469 Remove (Expr);
5471 if Present (Actions) then
5473 -- To minimize the use of Expression_With_Actions, just skip
5474 -- the optimization as it is not critical for correctness.
5476 if Minimize_Expression_With_Actions then
5477 return False;
5478 end if;
5480 Rewrite (N,
5481 Make_Expression_With_Actions (Loc,
5482 Expression => Relocate_Node (Expr),
5483 Actions => Actions));
5484 Analyze_And_Resolve (N, Typ);
5486 else
5487 Rewrite (N, Relocate_Node (Expr));
5488 end if;
5490 -- Note that the result is never static (legitimate cases of
5491 -- static if expressions were folded in Sem_Eval).
5493 Set_Is_Static_Expression (N, False);
5494 return True;
5495 end Fold_Known_Value;
5497 begin
5498 if Fold_Known_Value (Cond) then
5499 return;
5500 end if;
5501 end;
5502 end if;
5504 -- If the type is limited, and the back end does not handle limited
5505 -- types, then we expand as follows to avoid the possibility of
5506 -- improper copying.
5508 -- type Ptr is access all Typ;
5509 -- Cnn : Ptr;
5510 -- if cond then
5511 -- <<then actions>>
5512 -- Cnn := then-expr'Unrestricted_Access;
5513 -- else
5514 -- <<else actions>>
5515 -- Cnn := else-expr'Unrestricted_Access;
5516 -- end if;
5518 -- and replace the if expression by a reference to Cnn.all.
5520 -- This special case can be skipped if the back end handles limited
5521 -- types properly and ensures that no incorrect copies are made.
5523 if Is_By_Reference_Type (Typ)
5524 and then not Back_End_Handles_Limited_Types
5525 then
5526 -- When the "then" or "else" expressions involve controlled function
5527 -- calls, generated temporaries are chained on the corresponding list
5528 -- of actions. These temporaries need to be finalized after the if
5529 -- expression is evaluated.
5531 Process_If_Case_Statements (N, Then_Actions (N));
5532 Process_If_Case_Statements (N, Else_Actions (N));
5534 -- Generate:
5535 -- type Ann is access all Typ;
5537 Ptr_Typ := Make_Temporary (Loc, 'A');
5539 Insert_Action (N,
5540 Make_Full_Type_Declaration (Loc,
5541 Defining_Identifier => Ptr_Typ,
5542 Type_Definition =>
5543 Make_Access_To_Object_Definition (Loc,
5544 All_Present => True,
5545 Subtype_Indication => New_Occurrence_Of (Typ, Loc))));
5547 -- Generate:
5548 -- Cnn : Ann;
5550 Cnn := Make_Temporary (Loc, 'C', N);
5552 Decl :=
5553 Make_Object_Declaration (Loc,
5554 Defining_Identifier => Cnn,
5555 Object_Definition => New_Occurrence_Of (Ptr_Typ, Loc));
5557 -- Generate:
5558 -- if Cond then
5559 -- Cnn := <Thenx>'Unrestricted_Access;
5560 -- else
5561 -- Cnn := <Elsex>'Unrestricted_Access;
5562 -- end if;
5564 New_If :=
5565 Make_Implicit_If_Statement (N,
5566 Condition => Relocate_Node (Cond),
5567 Then_Statements => New_List (
5568 Make_Assignment_Statement (Sloc (Thenx),
5569 Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
5570 Expression =>
5571 Make_Attribute_Reference (Loc,
5572 Prefix => Relocate_Node (Thenx),
5573 Attribute_Name => Name_Unrestricted_Access))),
5575 Else_Statements => New_List (
5576 Make_Assignment_Statement (Sloc (Elsex),
5577 Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
5578 Expression =>
5579 Make_Attribute_Reference (Loc,
5580 Prefix => Relocate_Node (Elsex),
5581 Attribute_Name => Name_Unrestricted_Access))));
5583 -- Preserve the original context for which the if statement is being
5584 -- generated. This is needed by the finalization machinery to prevent
5585 -- the premature finalization of controlled objects found within the
5586 -- if statement.
5588 Set_From_Conditional_Expression (New_If);
5590 New_N :=
5591 Make_Explicit_Dereference (Loc,
5592 Prefix => New_Occurrence_Of (Cnn, Loc));
5594 -- If the result is an unconstrained array and the if expression is in a
5595 -- context other than the initializing expression of the declaration of
5596 -- an object, then we pull out the if expression as follows:
5598 -- Cnn : constant typ := if-expression
5600 -- and then replace the if expression with an occurrence of Cnn. This
5601 -- avoids the need in the back end to create on-the-fly variable length
5602 -- temporaries (which it cannot do!)
5604 -- Note that the test for being in an object declaration avoids doing an
5605 -- unnecessary expansion, and also avoids infinite recursion.
5607 elsif Is_Array_Type (Typ) and then not Is_Constrained (Typ)
5608 and then (Nkind (Parent (N)) /= N_Object_Declaration
5609 or else Expression (Parent (N)) /= N)
5610 then
5611 declare
5612 Cnn : constant Node_Id := Make_Temporary (Loc, 'C', N);
5613 begin
5614 Insert_Action (N,
5615 Make_Object_Declaration (Loc,
5616 Defining_Identifier => Cnn,
5617 Constant_Present => True,
5618 Object_Definition => New_Occurrence_Of (Typ, Loc),
5619 Expression => Relocate_Node (N),
5620 Has_Init_Expression => True));
5622 Rewrite (N, New_Occurrence_Of (Cnn, Loc));
5623 return;
5624 end;
5626 -- For other types, we only need to expand if there are other actions
5627 -- associated with either branch.
5629 elsif Present (Then_Actions (N)) or else Present (Else_Actions (N)) then
5631 -- We now wrap the actions into the appropriate expression
5633 if Minimize_Expression_With_Actions
5634 and then (Is_Elementary_Type (Underlying_Type (Typ))
5635 or else Is_Constrained (Underlying_Type (Typ)))
5636 then
5637 -- If we can't use N_Expression_With_Actions nodes, then we insert
5638 -- the following sequence of actions (using Insert_Actions):
5640 -- Cnn : typ;
5641 -- if cond then
5642 -- <<then actions>>
5643 -- Cnn := then-expr;
5644 -- else
5645 -- <<else actions>>
5646 -- Cnn := else-expr
5647 -- end if;
5649 -- and replace the if expression by a reference to Cnn
5651 Cnn := Make_Temporary (Loc, 'C', N);
5653 Decl :=
5654 Make_Object_Declaration (Loc,
5655 Defining_Identifier => Cnn,
5656 Object_Definition => New_Occurrence_Of (Typ, Loc));
5658 New_If :=
5659 Make_Implicit_If_Statement (N,
5660 Condition => Relocate_Node (Cond),
5662 Then_Statements => New_List (
5663 Make_Assignment_Statement (Sloc (Thenx),
5664 Name => New_Occurrence_Of (Cnn, Sloc (Thenx)),
5665 Expression => Relocate_Node (Thenx))),
5667 Else_Statements => New_List (
5668 Make_Assignment_Statement (Sloc (Elsex),
5669 Name => New_Occurrence_Of (Cnn, Sloc (Elsex)),
5670 Expression => Relocate_Node (Elsex))));
5672 Set_Assignment_OK (Name (First (Then_Statements (New_If))));
5673 Set_Assignment_OK (Name (First (Else_Statements (New_If))));
5675 New_N := New_Occurrence_Of (Cnn, Loc);
5677 -- Regular path using Expression_With_Actions
5679 else
5680 if Present (Then_Actions (N)) then
5681 Rewrite (Thenx,
5682 Make_Expression_With_Actions (Sloc (Thenx),
5683 Actions => Then_Actions (N),
5684 Expression => Relocate_Node (Thenx)));
5686 Set_Then_Actions (N, No_List);
5687 Analyze_And_Resolve (Thenx, Typ);
5688 end if;
5690 if Present (Else_Actions (N)) then
5691 Rewrite (Elsex,
5692 Make_Expression_With_Actions (Sloc (Elsex),
5693 Actions => Else_Actions (N),
5694 Expression => Relocate_Node (Elsex)));
5696 Set_Else_Actions (N, No_List);
5697 Analyze_And_Resolve (Elsex, Typ);
5698 end if;
5700 return;
5701 end if;
5703 -- If no actions then no expansion needed, gigi will handle it using the
5704 -- same approach as a C conditional expression.
5706 else
5707 return;
5708 end if;
5710 -- Fall through here for either the limited expansion, or the case of
5711 -- inserting actions for nonlimited types. In both these cases, we must
5712 -- move the SLOC of the parent If statement to the newly created one and
5713 -- change it to the SLOC of the expression which, after expansion, will
5714 -- correspond to what is being evaluated.
5716 if Present (Parent (N)) and then Nkind (Parent (N)) = N_If_Statement then
5717 Set_Sloc (New_If, Sloc (Parent (N)));
5718 Set_Sloc (Parent (N), Loc);
5719 end if;
5721 -- Make sure Then_Actions and Else_Actions are appropriately moved
5722 -- to the new if statement.
5724 if Present (Then_Actions (N)) then
5725 Insert_List_Before
5726 (First (Then_Statements (New_If)), Then_Actions (N));
5727 end if;
5729 if Present (Else_Actions (N)) then
5730 Insert_List_Before
5731 (First (Else_Statements (New_If)), Else_Actions (N));
5732 end if;
5734 Insert_Action (N, Decl);
5735 Insert_Action (N, New_If);
5736 Rewrite (N, New_N);
5737 Analyze_And_Resolve (N, Typ);
5738 end Expand_N_If_Expression;
5740 -----------------
5741 -- Expand_N_In --
5742 -----------------
5744 procedure Expand_N_In (N : Node_Id) is
5745 Loc : constant Source_Ptr := Sloc (N);
5746 Restyp : constant Entity_Id := Etype (N);
5747 Lop : constant Node_Id := Left_Opnd (N);
5748 Rop : constant Node_Id := Right_Opnd (N);
5749 Static : constant Boolean := Is_OK_Static_Expression (N);
5751 procedure Substitute_Valid_Check;
5752 -- Replaces node N by Lop'Valid. This is done when we have an explicit
5753 -- test for the left operand being in range of its subtype.
5755 ----------------------------
5756 -- Substitute_Valid_Check --
5757 ----------------------------
5759 procedure Substitute_Valid_Check is
5760 function Is_OK_Object_Reference (Nod : Node_Id) return Boolean;
5761 -- Determine whether arbitrary node Nod denotes a source object that
5762 -- may safely act as prefix of attribute 'Valid.
5764 ----------------------------
5765 -- Is_OK_Object_Reference --
5766 ----------------------------
5768 function Is_OK_Object_Reference (Nod : Node_Id) return Boolean is
5769 Obj_Ref : Node_Id;
5771 begin
5772 -- Inspect the original operand
5774 Obj_Ref := Original_Node (Nod);
5776 -- The object reference must be a source construct, otherwise the
5777 -- codefix suggestion may refer to nonexistent code from a user
5778 -- perspective.
5780 if Comes_From_Source (Obj_Ref) then
5782 -- Recover the actual object reference. There may be more cases
5783 -- to consider???
5785 loop
5786 if Nkind_In (Obj_Ref, N_Type_Conversion,
5787 N_Unchecked_Type_Conversion)
5788 then
5789 Obj_Ref := Expression (Obj_Ref);
5790 else
5791 exit;
5792 end if;
5793 end loop;
5795 return Is_Object_Reference (Obj_Ref);
5796 end if;
5798 return False;
5799 end Is_OK_Object_Reference;
5801 -- Start of processing for Substitute_Valid_Check
5803 begin
5804 Rewrite (N,
5805 Make_Attribute_Reference (Loc,
5806 Prefix => Relocate_Node (Lop),
5807 Attribute_Name => Name_Valid));
5809 Analyze_And_Resolve (N, Restyp);
5811 -- Emit a warning when the left-hand operand of the membership test
5812 -- is a source object, otherwise the use of attribute 'Valid would be
5813 -- illegal. The warning is not given when overflow checking is either
5814 -- MINIMIZED or ELIMINATED, as the danger of optimization has been
5815 -- eliminated above.
5817 if Is_OK_Object_Reference (Lop)
5818 and then Overflow_Check_Mode not in Minimized_Or_Eliminated
5819 then
5820 Error_Msg_N
5821 ("??explicit membership test may be optimized away", N);
5822 Error_Msg_N -- CODEFIX
5823 ("\??use ''Valid attribute instead", N);
5824 end if;
5825 end Substitute_Valid_Check;
5827 -- Local variables
5829 Ltyp : Entity_Id;
5830 Rtyp : Entity_Id;
5832 -- Start of processing for Expand_N_In
5834 begin
5835 -- If set membership case, expand with separate procedure
5837 if Present (Alternatives (N)) then
5838 Expand_Set_Membership (N);
5839 return;
5840 end if;
5842 -- Not set membership, proceed with expansion
5844 Ltyp := Etype (Left_Opnd (N));
5845 Rtyp := Etype (Right_Opnd (N));
5847 -- If MINIMIZED/ELIMINATED overflow mode and type is a signed integer
5848 -- type, then expand with a separate procedure. Note the use of the
5849 -- flag No_Minimize_Eliminate to prevent infinite recursion.
5851 if Overflow_Check_Mode in Minimized_Or_Eliminated
5852 and then Is_Signed_Integer_Type (Ltyp)
5853 and then not No_Minimize_Eliminate (N)
5854 then
5855 Expand_Membership_Minimize_Eliminate_Overflow (N);
5856 return;
5857 end if;
5859 -- Check case of explicit test for an expression in range of its
5860 -- subtype. This is suspicious usage and we replace it with a 'Valid
5861 -- test and give a warning for scalar types.
5863 if Is_Scalar_Type (Ltyp)
5865 -- Only relevant for source comparisons
5867 and then Comes_From_Source (N)
5869 -- In floating-point this is a standard way to check for finite values
5870 -- and using 'Valid would typically be a pessimization.
5872 and then not Is_Floating_Point_Type (Ltyp)
5874 -- Don't give the message unless right operand is a type entity and
5875 -- the type of the left operand matches this type. Note that this
5876 -- eliminates the cases where MINIMIZED/ELIMINATED mode overflow
5877 -- checks have changed the type of the left operand.
5879 and then Nkind (Rop) in N_Has_Entity
5880 and then Ltyp = Entity (Rop)
5882 -- Skip this for predicated types, where such expressions are a
5883 -- reasonable way of testing if something meets the predicate.
5885 and then not Present (Predicate_Function (Ltyp))
5886 then
5887 Substitute_Valid_Check;
5888 return;
5889 end if;
5891 -- Do validity check on operands
5893 if Validity_Checks_On and Validity_Check_Operands then
5894 Ensure_Valid (Left_Opnd (N));
5895 Validity_Check_Range (Right_Opnd (N));
5896 end if;
5898 -- Case of explicit range
5900 if Nkind (Rop) = N_Range then
5901 declare
5902 Lo : constant Node_Id := Low_Bound (Rop);
5903 Hi : constant Node_Id := High_Bound (Rop);
5905 Lo_Orig : constant Node_Id := Original_Node (Lo);
5906 Hi_Orig : constant Node_Id := Original_Node (Hi);
5908 Lcheck : Compare_Result;
5909 Ucheck : Compare_Result;
5911 Warn1 : constant Boolean :=
5912 Constant_Condition_Warnings
5913 and then Comes_From_Source (N)
5914 and then not In_Instance;
5915 -- This must be true for any of the optimization warnings, we
5916 -- clearly want to give them only for source with the flag on. We
5917 -- also skip these warnings in an instance since it may be the
5918 -- case that different instantiations have different ranges.
5920 Warn2 : constant Boolean :=
5921 Warn1
5922 and then Nkind (Original_Node (Rop)) = N_Range
5923 and then Is_Integer_Type (Etype (Lo));
5924 -- For the case where only one bound warning is elided, we also
5925 -- insist on an explicit range and an integer type. The reason is
5926 -- that the use of enumeration ranges including an end point is
5927 -- common, as is the use of a subtype name, one of whose bounds is
5928 -- the same as the type of the expression.
5930 begin
5931 -- If test is explicit x'First .. x'Last, replace by valid check
5933 -- Could use some individual comments for this complex test ???
5935 if Is_Scalar_Type (Ltyp)
5937 -- And left operand is X'First where X matches left operand
5938 -- type (this eliminates cases of type mismatch, including
5939 -- the cases where ELIMINATED/MINIMIZED mode has changed the
5940 -- type of the left operand.
5942 and then Nkind (Lo_Orig) = N_Attribute_Reference
5943 and then Attribute_Name (Lo_Orig) = Name_First
5944 and then Nkind (Prefix (Lo_Orig)) in N_Has_Entity
5945 and then Entity (Prefix (Lo_Orig)) = Ltyp
5947 -- Same tests for right operand
5949 and then Nkind (Hi_Orig) = N_Attribute_Reference
5950 and then Attribute_Name (Hi_Orig) = Name_Last
5951 and then Nkind (Prefix (Hi_Orig)) in N_Has_Entity
5952 and then Entity (Prefix (Hi_Orig)) = Ltyp
5954 -- Relevant only for source cases
5956 and then Comes_From_Source (N)
5957 then
5958 Substitute_Valid_Check;
5959 goto Leave;
5960 end if;
5962 -- If bounds of type are known at compile time, and the end points
5963 -- are known at compile time and identical, this is another case
5964 -- for substituting a valid test. We only do this for discrete
5965 -- types, since it won't arise in practice for float types.
5967 if Comes_From_Source (N)
5968 and then Is_Discrete_Type (Ltyp)
5969 and then Compile_Time_Known_Value (Type_High_Bound (Ltyp))
5970 and then Compile_Time_Known_Value (Type_Low_Bound (Ltyp))
5971 and then Compile_Time_Known_Value (Lo)
5972 and then Compile_Time_Known_Value (Hi)
5973 and then Expr_Value (Type_High_Bound (Ltyp)) = Expr_Value (Hi)
5974 and then Expr_Value (Type_Low_Bound (Ltyp)) = Expr_Value (Lo)
5976 -- Kill warnings in instances, since they may be cases where we
5977 -- have a test in the generic that makes sense with some types
5978 -- and not with other types.
5980 and then not In_Instance
5981 then
5982 Substitute_Valid_Check;
5983 goto Leave;
5984 end if;
5986 -- If we have an explicit range, do a bit of optimization based on
5987 -- range analysis (we may be able to kill one or both checks).
5989 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => False);
5990 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => False);
5992 -- If either check is known to fail, replace result by False since
5993 -- the other check does not matter. Preserve the static flag for
5994 -- legality checks, because we are constant-folding beyond RM 4.9.
5996 if Lcheck = LT or else Ucheck = GT then
5997 if Warn1 then
5998 Error_Msg_N ("?c?range test optimized away", N);
5999 Error_Msg_N ("\?c?value is known to be out of range", N);
6000 end if;
6002 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6003 Analyze_And_Resolve (N, Restyp);
6004 Set_Is_Static_Expression (N, Static);
6005 goto Leave;
6007 -- If both checks are known to succeed, replace result by True,
6008 -- since we know we are in range.
6010 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
6011 if Warn1 then
6012 Error_Msg_N ("?c?range test optimized away", N);
6013 Error_Msg_N ("\?c?value is known to be in range", N);
6014 end if;
6016 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6017 Analyze_And_Resolve (N, Restyp);
6018 Set_Is_Static_Expression (N, Static);
6019 goto Leave;
6021 -- If lower bound check succeeds and upper bound check is not
6022 -- known to succeed or fail, then replace the range check with
6023 -- a comparison against the upper bound.
6025 elsif Lcheck in Compare_GE then
6026 if Warn2 and then not In_Instance then
6027 Error_Msg_N ("??lower bound test optimized away", Lo);
6028 Error_Msg_N ("\??value is known to be in range", Lo);
6029 end if;
6031 Rewrite (N,
6032 Make_Op_Le (Loc,
6033 Left_Opnd => Lop,
6034 Right_Opnd => High_Bound (Rop)));
6035 Analyze_And_Resolve (N, Restyp);
6036 goto Leave;
6038 -- If upper bound check succeeds and lower bound check is not
6039 -- known to succeed or fail, then replace the range check with
6040 -- a comparison against the lower bound.
6042 elsif Ucheck in Compare_LE then
6043 if Warn2 and then not In_Instance then
6044 Error_Msg_N ("??upper bound test optimized away", Hi);
6045 Error_Msg_N ("\??value is known to be in range", Hi);
6046 end if;
6048 Rewrite (N,
6049 Make_Op_Ge (Loc,
6050 Left_Opnd => Lop,
6051 Right_Opnd => Low_Bound (Rop)));
6052 Analyze_And_Resolve (N, Restyp);
6053 goto Leave;
6054 end if;
6056 -- We couldn't optimize away the range check, but there is one
6057 -- more issue. If we are checking constant conditionals, then we
6058 -- see if we can determine the outcome assuming everything is
6059 -- valid, and if so give an appropriate warning.
6061 if Warn1 and then not Assume_No_Invalid_Values then
6062 Lcheck := Compile_Time_Compare (Lop, Lo, Assume_Valid => True);
6063 Ucheck := Compile_Time_Compare (Lop, Hi, Assume_Valid => True);
6065 -- Result is out of range for valid value
6067 if Lcheck = LT or else Ucheck = GT then
6068 Error_Msg_N
6069 ("?c?value can only be in range if it is invalid", N);
6071 -- Result is in range for valid value
6073 elsif Lcheck in Compare_GE and then Ucheck in Compare_LE then
6074 Error_Msg_N
6075 ("?c?value can only be out of range if it is invalid", N);
6077 -- Lower bound check succeeds if value is valid
6079 elsif Warn2 and then Lcheck in Compare_GE then
6080 Error_Msg_N
6081 ("?c?lower bound check only fails if it is invalid", Lo);
6083 -- Upper bound check succeeds if value is valid
6085 elsif Warn2 and then Ucheck in Compare_LE then
6086 Error_Msg_N
6087 ("?c?upper bound check only fails for invalid values", Hi);
6088 end if;
6089 end if;
6090 end;
6092 -- For all other cases of an explicit range, nothing to be done
6094 goto Leave;
6096 -- Here right operand is a subtype mark
6098 else
6099 declare
6100 Typ : Entity_Id := Etype (Rop);
6101 Is_Acc : constant Boolean := Is_Access_Type (Typ);
6102 Cond : Node_Id := Empty;
6103 New_N : Node_Id;
6104 Obj : Node_Id := Lop;
6105 SCIL_Node : Node_Id;
6107 begin
6108 Remove_Side_Effects (Obj);
6110 -- For tagged type, do tagged membership operation
6112 if Is_Tagged_Type (Typ) then
6114 -- No expansion will be performed for VM targets, as the VM
6115 -- back-ends will handle the membership tests directly.
6117 if Tagged_Type_Expansion then
6118 Tagged_Membership (N, SCIL_Node, New_N);
6119 Rewrite (N, New_N);
6120 Analyze_And_Resolve (N, Restyp, Suppress => All_Checks);
6122 -- Update decoration of relocated node referenced by the
6123 -- SCIL node.
6125 if Generate_SCIL and then Present (SCIL_Node) then
6126 Set_SCIL_Node (N, SCIL_Node);
6127 end if;
6128 end if;
6130 goto Leave;
6132 -- If type is scalar type, rewrite as x in t'First .. t'Last.
6133 -- This reason we do this is that the bounds may have the wrong
6134 -- type if they come from the original type definition. Also this
6135 -- way we get all the processing above for an explicit range.
6137 -- Don't do this for predicated types, since in this case we
6138 -- want to check the predicate.
6140 elsif Is_Scalar_Type (Typ) then
6141 if No (Predicate_Function (Typ)) then
6142 Rewrite (Rop,
6143 Make_Range (Loc,
6144 Low_Bound =>
6145 Make_Attribute_Reference (Loc,
6146 Attribute_Name => Name_First,
6147 Prefix => New_Occurrence_Of (Typ, Loc)),
6149 High_Bound =>
6150 Make_Attribute_Reference (Loc,
6151 Attribute_Name => Name_Last,
6152 Prefix => New_Occurrence_Of (Typ, Loc))));
6153 Analyze_And_Resolve (N, Restyp);
6154 end if;
6156 goto Leave;
6158 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
6159 -- a membership test if the subtype mark denotes a constrained
6160 -- Unchecked_Union subtype and the expression lacks inferable
6161 -- discriminants.
6163 elsif Is_Unchecked_Union (Base_Type (Typ))
6164 and then Is_Constrained (Typ)
6165 and then not Has_Inferable_Discriminants (Lop)
6166 then
6167 Insert_Action (N,
6168 Make_Raise_Program_Error (Loc,
6169 Reason => PE_Unchecked_Union_Restriction));
6171 -- Prevent Gigi from generating incorrect code by rewriting the
6172 -- test as False. What is this undocumented thing about ???
6174 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6175 goto Leave;
6176 end if;
6178 -- Here we have a non-scalar type
6180 if Is_Acc then
6181 Typ := Designated_Type (Typ);
6182 end if;
6184 if not Is_Constrained (Typ) then
6185 Rewrite (N, New_Occurrence_Of (Standard_True, Loc));
6186 Analyze_And_Resolve (N, Restyp);
6188 -- For the constrained array case, we have to check the subscripts
6189 -- for an exact match if the lengths are non-zero (the lengths
6190 -- must match in any case).
6192 elsif Is_Array_Type (Typ) then
6193 Check_Subscripts : declare
6194 function Build_Attribute_Reference
6195 (E : Node_Id;
6196 Nam : Name_Id;
6197 Dim : Nat) return Node_Id;
6198 -- Build attribute reference E'Nam (Dim)
6200 -------------------------------
6201 -- Build_Attribute_Reference --
6202 -------------------------------
6204 function Build_Attribute_Reference
6205 (E : Node_Id;
6206 Nam : Name_Id;
6207 Dim : Nat) return Node_Id
6209 begin
6210 return
6211 Make_Attribute_Reference (Loc,
6212 Prefix => E,
6213 Attribute_Name => Nam,
6214 Expressions => New_List (
6215 Make_Integer_Literal (Loc, Dim)));
6216 end Build_Attribute_Reference;
6218 -- Start of processing for Check_Subscripts
6220 begin
6221 for J in 1 .. Number_Dimensions (Typ) loop
6222 Evolve_And_Then (Cond,
6223 Make_Op_Eq (Loc,
6224 Left_Opnd =>
6225 Build_Attribute_Reference
6226 (Duplicate_Subexpr_No_Checks (Obj),
6227 Name_First, J),
6228 Right_Opnd =>
6229 Build_Attribute_Reference
6230 (New_Occurrence_Of (Typ, Loc), Name_First, J)));
6232 Evolve_And_Then (Cond,
6233 Make_Op_Eq (Loc,
6234 Left_Opnd =>
6235 Build_Attribute_Reference
6236 (Duplicate_Subexpr_No_Checks (Obj),
6237 Name_Last, J),
6238 Right_Opnd =>
6239 Build_Attribute_Reference
6240 (New_Occurrence_Of (Typ, Loc), Name_Last, J)));
6241 end loop;
6243 if Is_Acc then
6244 Cond :=
6245 Make_Or_Else (Loc,
6246 Left_Opnd =>
6247 Make_Op_Eq (Loc,
6248 Left_Opnd => Obj,
6249 Right_Opnd => Make_Null (Loc)),
6250 Right_Opnd => Cond);
6251 end if;
6253 Rewrite (N, Cond);
6254 Analyze_And_Resolve (N, Restyp);
6255 end Check_Subscripts;
6257 -- These are the cases where constraint checks may be required,
6258 -- e.g. records with possible discriminants
6260 else
6261 -- Expand the test into a series of discriminant comparisons.
6262 -- The expression that is built is the negation of the one that
6263 -- is used for checking discriminant constraints.
6265 Obj := Relocate_Node (Left_Opnd (N));
6267 if Has_Discriminants (Typ) then
6268 Cond := Make_Op_Not (Loc,
6269 Right_Opnd => Build_Discriminant_Checks (Obj, Typ));
6271 if Is_Acc then
6272 Cond := Make_Or_Else (Loc,
6273 Left_Opnd =>
6274 Make_Op_Eq (Loc,
6275 Left_Opnd => Obj,
6276 Right_Opnd => Make_Null (Loc)),
6277 Right_Opnd => Cond);
6278 end if;
6280 else
6281 Cond := New_Occurrence_Of (Standard_True, Loc);
6282 end if;
6284 Rewrite (N, Cond);
6285 Analyze_And_Resolve (N, Restyp);
6286 end if;
6288 -- Ada 2012 (AI05-0149): Handle membership tests applied to an
6289 -- expression of an anonymous access type. This can involve an
6290 -- accessibility test and a tagged type membership test in the
6291 -- case of tagged designated types.
6293 if Ada_Version >= Ada_2012
6294 and then Is_Acc
6295 and then Ekind (Ltyp) = E_Anonymous_Access_Type
6296 then
6297 declare
6298 Expr_Entity : Entity_Id := Empty;
6299 New_N : Node_Id;
6300 Param_Level : Node_Id;
6301 Type_Level : Node_Id;
6303 begin
6304 if Is_Entity_Name (Lop) then
6305 Expr_Entity := Param_Entity (Lop);
6307 if not Present (Expr_Entity) then
6308 Expr_Entity := Entity (Lop);
6309 end if;
6310 end if;
6312 -- If a conversion of the anonymous access value to the
6313 -- tested type would be illegal, then the result is False.
6315 if not Valid_Conversion
6316 (Lop, Rtyp, Lop, Report_Errs => False)
6317 then
6318 Rewrite (N, New_Occurrence_Of (Standard_False, Loc));
6319 Analyze_And_Resolve (N, Restyp);
6321 -- Apply an accessibility check if the access object has an
6322 -- associated access level and when the level of the type is
6323 -- less deep than the level of the access parameter. This
6324 -- only occur for access parameters and stand-alone objects
6325 -- of an anonymous access type.
6327 else
6328 if Present (Expr_Entity)
6329 and then
6330 Present
6331 (Effective_Extra_Accessibility (Expr_Entity))
6332 and then UI_Gt (Object_Access_Level (Lop),
6333 Type_Access_Level (Rtyp))
6334 then
6335 Param_Level :=
6336 New_Occurrence_Of
6337 (Effective_Extra_Accessibility (Expr_Entity), Loc);
6339 Type_Level :=
6340 Make_Integer_Literal (Loc, Type_Access_Level (Rtyp));
6342 -- Return True only if the accessibility level of the
6343 -- expression entity is not deeper than the level of
6344 -- the tested access type.
6346 Rewrite (N,
6347 Make_And_Then (Loc,
6348 Left_Opnd => Relocate_Node (N),
6349 Right_Opnd => Make_Op_Le (Loc,
6350 Left_Opnd => Param_Level,
6351 Right_Opnd => Type_Level)));
6353 Analyze_And_Resolve (N);
6354 end if;
6356 -- If the designated type is tagged, do tagged membership
6357 -- operation.
6359 -- *** NOTE: we have to check not null before doing the
6360 -- tagged membership test (but maybe that can be done
6361 -- inside Tagged_Membership?).
6363 if Is_Tagged_Type (Typ) then
6364 Rewrite (N,
6365 Make_And_Then (Loc,
6366 Left_Opnd => Relocate_Node (N),
6367 Right_Opnd =>
6368 Make_Op_Ne (Loc,
6369 Left_Opnd => Obj,
6370 Right_Opnd => Make_Null (Loc))));
6372 -- No expansion will be performed for VM targets, as
6373 -- the VM back-ends will handle the membership tests
6374 -- directly.
6376 if Tagged_Type_Expansion then
6378 -- Note that we have to pass Original_Node, because
6379 -- the membership test might already have been
6380 -- rewritten by earlier parts of membership test.
6382 Tagged_Membership
6383 (Original_Node (N), SCIL_Node, New_N);
6385 -- Update decoration of relocated node referenced
6386 -- by the SCIL node.
6388 if Generate_SCIL and then Present (SCIL_Node) then
6389 Set_SCIL_Node (New_N, SCIL_Node);
6390 end if;
6392 Rewrite (N,
6393 Make_And_Then (Loc,
6394 Left_Opnd => Relocate_Node (N),
6395 Right_Opnd => New_N));
6397 Analyze_And_Resolve (N, Restyp);
6398 end if;
6399 end if;
6400 end if;
6401 end;
6402 end if;
6403 end;
6404 end if;
6406 -- At this point, we have done the processing required for the basic
6407 -- membership test, but not yet dealt with the predicate.
6409 <<Leave>>
6411 -- If a predicate is present, then we do the predicate test, but we
6412 -- most certainly want to omit this if we are within the predicate
6413 -- function itself, since otherwise we have an infinite recursion.
6414 -- The check should also not be emitted when testing against a range
6415 -- (the check is only done when the right operand is a subtype; see
6416 -- RM12-4.5.2 (28.1/3-30/3)).
6418 Predicate_Check : declare
6419 function In_Range_Check return Boolean;
6420 -- Within an expanded range check that may raise Constraint_Error do
6421 -- not generate a predicate check as well. It is redundant because
6422 -- the context will add an explicit predicate check, and it will
6423 -- raise the wrong exception if it fails.
6425 --------------------
6426 -- In_Range_Check --
6427 --------------------
6429 function In_Range_Check return Boolean is
6430 P : Node_Id;
6431 begin
6432 P := Parent (N);
6433 while Present (P) loop
6434 if Nkind (P) = N_Raise_Constraint_Error then
6435 return True;
6437 elsif Nkind (P) in N_Statement_Other_Than_Procedure_Call
6438 or else Nkind (P) = N_Procedure_Call_Statement
6439 or else Nkind (P) in N_Declaration
6440 then
6441 return False;
6442 end if;
6444 P := Parent (P);
6445 end loop;
6447 return False;
6448 end In_Range_Check;
6450 -- Local variables
6452 PFunc : constant Entity_Id := Predicate_Function (Rtyp);
6453 R_Op : Node_Id;
6455 -- Start of processing for Predicate_Check
6457 begin
6458 if Present (PFunc)
6459 and then Current_Scope /= PFunc
6460 and then Nkind (Rop) /= N_Range
6461 then
6462 if not In_Range_Check then
6463 R_Op := Make_Predicate_Call (Rtyp, Lop, Mem => True);
6464 else
6465 R_Op := New_Occurrence_Of (Standard_True, Loc);
6466 end if;
6468 Rewrite (N,
6469 Make_And_Then (Loc,
6470 Left_Opnd => Relocate_Node (N),
6471 Right_Opnd => R_Op));
6473 -- Analyze new expression, mark left operand as analyzed to
6474 -- avoid infinite recursion adding predicate calls. Similarly,
6475 -- suppress further range checks on the call.
6477 Set_Analyzed (Left_Opnd (N));
6478 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
6480 -- All done, skip attempt at compile time determination of result
6482 return;
6483 end if;
6484 end Predicate_Check;
6485 end Expand_N_In;
6487 --------------------------------
6488 -- Expand_N_Indexed_Component --
6489 --------------------------------
6491 procedure Expand_N_Indexed_Component (N : Node_Id) is
6492 Loc : constant Source_Ptr := Sloc (N);
6493 Typ : constant Entity_Id := Etype (N);
6494 P : constant Node_Id := Prefix (N);
6495 T : constant Entity_Id := Etype (P);
6496 Atp : Entity_Id;
6498 begin
6499 -- A special optimization, if we have an indexed component that is
6500 -- selecting from a slice, then we can eliminate the slice, since, for
6501 -- example, x (i .. j)(k) is identical to x(k). The only difference is
6502 -- the range check required by the slice. The range check for the slice
6503 -- itself has already been generated. The range check for the
6504 -- subscripting operation is ensured by converting the subject to
6505 -- the subtype of the slice.
6507 -- This optimization not only generates better code, avoiding slice
6508 -- messing especially in the packed case, but more importantly bypasses
6509 -- some problems in handling this peculiar case, for example, the issue
6510 -- of dealing specially with object renamings.
6512 if Nkind (P) = N_Slice
6514 -- This optimization is disabled for CodePeer because it can transform
6515 -- an index-check constraint_error into a range-check constraint_error
6516 -- and CodePeer cares about that distinction.
6518 and then not CodePeer_Mode
6519 then
6520 Rewrite (N,
6521 Make_Indexed_Component (Loc,
6522 Prefix => Prefix (P),
6523 Expressions => New_List (
6524 Convert_To
6525 (Etype (First_Index (Etype (P))),
6526 First (Expressions (N))))));
6527 Analyze_And_Resolve (N, Typ);
6528 return;
6529 end if;
6531 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
6532 -- function, then additional actuals must be passed.
6534 if Ada_Version >= Ada_2005
6535 and then Is_Build_In_Place_Function_Call (P)
6536 then
6537 Make_Build_In_Place_Call_In_Anonymous_Context (P);
6538 end if;
6540 -- If the prefix is an access type, then we unconditionally rewrite if
6541 -- as an explicit dereference. This simplifies processing for several
6542 -- cases, including packed array cases and certain cases in which checks
6543 -- must be generated. We used to try to do this only when it was
6544 -- necessary, but it cleans up the code to do it all the time.
6546 if Is_Access_Type (T) then
6547 Insert_Explicit_Dereference (P);
6548 Analyze_And_Resolve (P, Designated_Type (T));
6549 Atp := Designated_Type (T);
6550 else
6551 Atp := T;
6552 end if;
6554 -- Generate index and validity checks
6556 Generate_Index_Checks (N);
6558 if Validity_Checks_On and then Validity_Check_Subscripts then
6559 Apply_Subscript_Validity_Checks (N);
6560 end if;
6562 -- If selecting from an array with atomic components, and atomic sync
6563 -- is not suppressed for this array type, set atomic sync flag.
6565 if (Has_Atomic_Components (Atp)
6566 and then not Atomic_Synchronization_Disabled (Atp))
6567 or else (Is_Atomic (Typ)
6568 and then not Atomic_Synchronization_Disabled (Typ))
6569 or else (Is_Entity_Name (P)
6570 and then Has_Atomic_Components (Entity (P))
6571 and then not Atomic_Synchronization_Disabled (Entity (P)))
6572 then
6573 Activate_Atomic_Synchronization (N);
6574 end if;
6576 -- All done if the prefix is not a packed array implemented specially
6578 if not (Is_Packed (Etype (Prefix (N)))
6579 and then Present (Packed_Array_Impl_Type (Etype (Prefix (N)))))
6580 then
6581 return;
6582 end if;
6584 -- For packed arrays that are not bit-packed (i.e. the case of an array
6585 -- with one or more index types with a non-contiguous enumeration type),
6586 -- we can always use the normal packed element get circuit.
6588 if not Is_Bit_Packed_Array (Etype (Prefix (N))) then
6589 Expand_Packed_Element_Reference (N);
6590 return;
6591 end if;
6593 -- For a reference to a component of a bit packed array, we convert it
6594 -- to a reference to the corresponding Packed_Array_Impl_Type. We only
6595 -- want to do this for simple references, and not for:
6597 -- Left side of assignment, or prefix of left side of assignment, or
6598 -- prefix of the prefix, to handle packed arrays of packed arrays,
6599 -- This case is handled in Exp_Ch5.Expand_N_Assignment_Statement
6601 -- Renaming objects in renaming associations
6602 -- This case is handled when a use of the renamed variable occurs
6604 -- Actual parameters for a procedure call
6605 -- This case is handled in Exp_Ch6.Expand_Actuals
6607 -- The second expression in a 'Read attribute reference
6609 -- The prefix of an address or bit or size attribute reference
6611 -- The following circuit detects these exceptions. Note that we need to
6612 -- deal with implicit dereferences when climbing up the parent chain,
6613 -- with the additional difficulty that the type of parents may have yet
6614 -- to be resolved since prefixes are usually resolved first.
6616 declare
6617 Child : Node_Id := N;
6618 Parnt : Node_Id := Parent (N);
6620 begin
6621 loop
6622 if Nkind (Parnt) = N_Unchecked_Expression then
6623 null;
6625 elsif Nkind_In (Parnt, N_Object_Renaming_Declaration,
6626 N_Procedure_Call_Statement)
6627 or else (Nkind (Parnt) = N_Parameter_Association
6628 and then
6629 Nkind (Parent (Parnt)) = N_Procedure_Call_Statement)
6630 then
6631 return;
6633 elsif Nkind (Parnt) = N_Attribute_Reference
6634 and then Nam_In (Attribute_Name (Parnt), Name_Address,
6635 Name_Bit,
6636 Name_Size)
6637 and then Prefix (Parnt) = Child
6638 then
6639 return;
6641 elsif Nkind (Parnt) = N_Assignment_Statement
6642 and then Name (Parnt) = Child
6643 then
6644 return;
6646 -- If the expression is an index of an indexed component, it must
6647 -- be expanded regardless of context.
6649 elsif Nkind (Parnt) = N_Indexed_Component
6650 and then Child /= Prefix (Parnt)
6651 then
6652 Expand_Packed_Element_Reference (N);
6653 return;
6655 elsif Nkind (Parent (Parnt)) = N_Assignment_Statement
6656 and then Name (Parent (Parnt)) = Parnt
6657 then
6658 return;
6660 elsif Nkind (Parnt) = N_Attribute_Reference
6661 and then Attribute_Name (Parnt) = Name_Read
6662 and then Next (First (Expressions (Parnt))) = Child
6663 then
6664 return;
6666 elsif Nkind (Parnt) = N_Indexed_Component
6667 and then Prefix (Parnt) = Child
6668 then
6669 null;
6671 elsif Nkind (Parnt) = N_Selected_Component
6672 and then Prefix (Parnt) = Child
6673 and then not (Present (Etype (Selector_Name (Parnt)))
6674 and then
6675 Is_Access_Type (Etype (Selector_Name (Parnt))))
6676 then
6677 null;
6679 -- If the parent is a dereference, either implicit or explicit,
6680 -- then the packed reference needs to be expanded.
6682 else
6683 Expand_Packed_Element_Reference (N);
6684 return;
6685 end if;
6687 -- Keep looking up tree for unchecked expression, or if we are the
6688 -- prefix of a possible assignment left side.
6690 Child := Parnt;
6691 Parnt := Parent (Child);
6692 end loop;
6693 end;
6694 end Expand_N_Indexed_Component;
6696 ---------------------
6697 -- Expand_N_Not_In --
6698 ---------------------
6700 -- Replace a not in b by not (a in b) so that the expansions for (a in b)
6701 -- can be done. This avoids needing to duplicate this expansion code.
6703 procedure Expand_N_Not_In (N : Node_Id) is
6704 Loc : constant Source_Ptr := Sloc (N);
6705 Typ : constant Entity_Id := Etype (N);
6706 Cfs : constant Boolean := Comes_From_Source (N);
6708 begin
6709 Rewrite (N,
6710 Make_Op_Not (Loc,
6711 Right_Opnd =>
6712 Make_In (Loc,
6713 Left_Opnd => Left_Opnd (N),
6714 Right_Opnd => Right_Opnd (N))));
6716 -- If this is a set membership, preserve list of alternatives
6718 Set_Alternatives (Right_Opnd (N), Alternatives (Original_Node (N)));
6720 -- We want this to appear as coming from source if original does (see
6721 -- transformations in Expand_N_In).
6723 Set_Comes_From_Source (N, Cfs);
6724 Set_Comes_From_Source (Right_Opnd (N), Cfs);
6726 -- Now analyze transformed node
6728 Analyze_And_Resolve (N, Typ);
6729 end Expand_N_Not_In;
6731 -------------------
6732 -- Expand_N_Null --
6733 -------------------
6735 -- The only replacement required is for the case of a null of a type that
6736 -- is an access to protected subprogram, or a subtype thereof. We represent
6737 -- such access values as a record, and so we must replace the occurrence of
6738 -- null by the equivalent record (with a null address and a null pointer in
6739 -- it), so that the backend creates the proper value.
6741 procedure Expand_N_Null (N : Node_Id) is
6742 Loc : constant Source_Ptr := Sloc (N);
6743 Typ : constant Entity_Id := Base_Type (Etype (N));
6744 Agg : Node_Id;
6746 begin
6747 if Is_Access_Protected_Subprogram_Type (Typ) then
6748 Agg :=
6749 Make_Aggregate (Loc,
6750 Expressions => New_List (
6751 New_Occurrence_Of (RTE (RE_Null_Address), Loc),
6752 Make_Null (Loc)));
6754 Rewrite (N, Agg);
6755 Analyze_And_Resolve (N, Equivalent_Type (Typ));
6757 -- For subsequent semantic analysis, the node must retain its type.
6758 -- Gigi in any case replaces this type by the corresponding record
6759 -- type before processing the node.
6761 Set_Etype (N, Typ);
6762 end if;
6764 exception
6765 when RE_Not_Available =>
6766 return;
6767 end Expand_N_Null;
6769 ---------------------
6770 -- Expand_N_Op_Abs --
6771 ---------------------
6773 procedure Expand_N_Op_Abs (N : Node_Id) is
6774 Loc : constant Source_Ptr := Sloc (N);
6775 Expr : constant Node_Id := Right_Opnd (N);
6777 begin
6778 Unary_Op_Validity_Checks (N);
6780 -- Check for MINIMIZED/ELIMINATED overflow mode
6782 if Minimized_Eliminated_Overflow_Check (N) then
6783 Apply_Arithmetic_Overflow_Check (N);
6784 return;
6785 end if;
6787 -- Deal with software overflow checking
6789 if not Backend_Overflow_Checks_On_Target
6790 and then Is_Signed_Integer_Type (Etype (N))
6791 and then Do_Overflow_Check (N)
6792 then
6793 -- The only case to worry about is when the argument is equal to the
6794 -- largest negative number, so what we do is to insert the check:
6796 -- [constraint_error when Expr = typ'Base'First]
6798 -- with the usual Duplicate_Subexpr use coding for expr
6800 Insert_Action (N,
6801 Make_Raise_Constraint_Error (Loc,
6802 Condition =>
6803 Make_Op_Eq (Loc,
6804 Left_Opnd => Duplicate_Subexpr (Expr),
6805 Right_Opnd =>
6806 Make_Attribute_Reference (Loc,
6807 Prefix =>
6808 New_Occurrence_Of (Base_Type (Etype (Expr)), Loc),
6809 Attribute_Name => Name_First)),
6810 Reason => CE_Overflow_Check_Failed));
6811 end if;
6812 end Expand_N_Op_Abs;
6814 ---------------------
6815 -- Expand_N_Op_Add --
6816 ---------------------
6818 procedure Expand_N_Op_Add (N : Node_Id) is
6819 Typ : constant Entity_Id := Etype (N);
6821 begin
6822 Binary_Op_Validity_Checks (N);
6824 -- Check for MINIMIZED/ELIMINATED overflow mode
6826 if Minimized_Eliminated_Overflow_Check (N) then
6827 Apply_Arithmetic_Overflow_Check (N);
6828 return;
6829 end if;
6831 -- N + 0 = 0 + N = N for integer types
6833 if Is_Integer_Type (Typ) then
6834 if Compile_Time_Known_Value (Right_Opnd (N))
6835 and then Expr_Value (Right_Opnd (N)) = Uint_0
6836 then
6837 Rewrite (N, Left_Opnd (N));
6838 return;
6840 elsif Compile_Time_Known_Value (Left_Opnd (N))
6841 and then Expr_Value (Left_Opnd (N)) = Uint_0
6842 then
6843 Rewrite (N, Right_Opnd (N));
6844 return;
6845 end if;
6846 end if;
6848 -- Arithmetic overflow checks for signed integer/fixed point types
6850 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
6851 Apply_Arithmetic_Overflow_Check (N);
6852 return;
6853 end if;
6855 -- Overflow checks for floating-point if -gnateF mode active
6857 Check_Float_Op_Overflow (N);
6859 -- Generating C code convert non-binary modular additions into code that
6860 -- relies on the frontend expansion of operator Mod.
6862 if Modify_Tree_For_C then
6863 Expand_Non_Binary_Modular_Op (N);
6864 end if;
6865 end Expand_N_Op_Add;
6867 ---------------------
6868 -- Expand_N_Op_And --
6869 ---------------------
6871 procedure Expand_N_Op_And (N : Node_Id) is
6872 Typ : constant Entity_Id := Etype (N);
6874 begin
6875 Binary_Op_Validity_Checks (N);
6877 if Is_Array_Type (Etype (N)) then
6878 Expand_Boolean_Operator (N);
6880 elsif Is_Boolean_Type (Etype (N)) then
6881 Adjust_Condition (Left_Opnd (N));
6882 Adjust_Condition (Right_Opnd (N));
6883 Set_Etype (N, Standard_Boolean);
6884 Adjust_Result_Type (N, Typ);
6886 elsif Is_Intrinsic_Subprogram (Entity (N)) then
6887 Expand_Intrinsic_Call (N, Entity (N));
6888 end if;
6890 -- Generating C code convert non-binary modular operators into code that
6891 -- relies on the frontend expansion of operator Mod.
6893 if Modify_Tree_For_C then
6894 Expand_Non_Binary_Modular_Op (N);
6895 end if;
6896 end Expand_N_Op_And;
6898 ------------------------
6899 -- Expand_N_Op_Concat --
6900 ------------------------
6902 procedure Expand_N_Op_Concat (N : Node_Id) is
6903 Opnds : List_Id;
6904 -- List of operands to be concatenated
6906 Cnode : Node_Id;
6907 -- Node which is to be replaced by the result of concatenating the nodes
6908 -- in the list Opnds.
6910 begin
6911 -- Ensure validity of both operands
6913 Binary_Op_Validity_Checks (N);
6915 -- If we are the left operand of a concatenation higher up the tree,
6916 -- then do nothing for now, since we want to deal with a series of
6917 -- concatenations as a unit.
6919 if Nkind (Parent (N)) = N_Op_Concat
6920 and then N = Left_Opnd (Parent (N))
6921 then
6922 return;
6923 end if;
6925 -- We get here with a concatenation whose left operand may be a
6926 -- concatenation itself with a consistent type. We need to process
6927 -- these concatenation operands from left to right, which means
6928 -- from the deepest node in the tree to the highest node.
6930 Cnode := N;
6931 while Nkind (Left_Opnd (Cnode)) = N_Op_Concat loop
6932 Cnode := Left_Opnd (Cnode);
6933 end loop;
6935 -- Now Cnode is the deepest concatenation, and its parents are the
6936 -- concatenation nodes above, so now we process bottom up, doing the
6937 -- operands.
6939 -- The outer loop runs more than once if more than one concatenation
6940 -- type is involved.
6942 Outer : loop
6943 Opnds := New_List (Left_Opnd (Cnode), Right_Opnd (Cnode));
6944 Set_Parent (Opnds, N);
6946 -- The inner loop gathers concatenation operands
6948 Inner : while Cnode /= N
6949 and then Base_Type (Etype (Cnode)) =
6950 Base_Type (Etype (Parent (Cnode)))
6951 loop
6952 Cnode := Parent (Cnode);
6953 Append (Right_Opnd (Cnode), Opnds);
6954 end loop Inner;
6956 -- Note: The following code is a temporary workaround for N731-034
6957 -- and N829-028 and will be kept until the general issue of internal
6958 -- symbol serialization is addressed. The workaround is kept under a
6959 -- debug switch to avoid permiating into the general case.
6961 -- Wrap the node to concatenate into an expression actions node to
6962 -- keep it nicely packaged. This is useful in the case of an assert
6963 -- pragma with a concatenation where we want to be able to delete
6964 -- the concatenation and all its expansion stuff.
6966 if Debug_Flag_Dot_H then
6967 declare
6968 Cnod : constant Node_Id := Relocate_Node (Cnode);
6969 Typ : constant Entity_Id := Base_Type (Etype (Cnode));
6971 begin
6972 -- Note: use Rewrite rather than Replace here, so that for
6973 -- example Why_Not_Static can find the original concatenation
6974 -- node OK!
6976 Rewrite (Cnode,
6977 Make_Expression_With_Actions (Sloc (Cnode),
6978 Actions => New_List (Make_Null_Statement (Sloc (Cnode))),
6979 Expression => Cnod));
6981 Expand_Concatenate (Cnod, Opnds);
6982 Analyze_And_Resolve (Cnode, Typ);
6983 end;
6985 -- Default case
6987 else
6988 Expand_Concatenate (Cnode, Opnds);
6989 end if;
6991 exit Outer when Cnode = N;
6992 Cnode := Parent (Cnode);
6993 end loop Outer;
6994 end Expand_N_Op_Concat;
6996 ------------------------
6997 -- Expand_N_Op_Divide --
6998 ------------------------
7000 procedure Expand_N_Op_Divide (N : Node_Id) is
7001 Loc : constant Source_Ptr := Sloc (N);
7002 Lopnd : constant Node_Id := Left_Opnd (N);
7003 Ropnd : constant Node_Id := Right_Opnd (N);
7004 Ltyp : constant Entity_Id := Etype (Lopnd);
7005 Rtyp : constant Entity_Id := Etype (Ropnd);
7006 Typ : Entity_Id := Etype (N);
7007 Rknow : constant Boolean := Is_Integer_Type (Typ)
7008 and then
7009 Compile_Time_Known_Value (Ropnd);
7010 Rval : Uint;
7012 begin
7013 Binary_Op_Validity_Checks (N);
7015 -- Check for MINIMIZED/ELIMINATED overflow mode
7017 if Minimized_Eliminated_Overflow_Check (N) then
7018 Apply_Arithmetic_Overflow_Check (N);
7019 return;
7020 end if;
7022 -- Otherwise proceed with expansion of division
7024 if Rknow then
7025 Rval := Expr_Value (Ropnd);
7026 end if;
7028 -- N / 1 = N for integer types
7030 if Rknow and then Rval = Uint_1 then
7031 Rewrite (N, Lopnd);
7032 return;
7033 end if;
7035 -- Convert x / 2 ** y to Shift_Right (x, y). Note that the fact that
7036 -- Is_Power_Of_2_For_Shift is set means that we know that our left
7037 -- operand is an unsigned integer, as required for this to work.
7039 if Nkind (Ropnd) = N_Op_Expon
7040 and then Is_Power_Of_2_For_Shift (Ropnd)
7042 -- We cannot do this transformation in configurable run time mode if we
7043 -- have 64-bit integers and long shifts are not available.
7045 and then (Esize (Ltyp) <= 32 or else Support_Long_Shifts_On_Target)
7046 then
7047 Rewrite (N,
7048 Make_Op_Shift_Right (Loc,
7049 Left_Opnd => Lopnd,
7050 Right_Opnd =>
7051 Convert_To (Standard_Natural, Right_Opnd (Ropnd))));
7052 Analyze_And_Resolve (N, Typ);
7053 return;
7054 end if;
7056 -- Do required fixup of universal fixed operation
7058 if Typ = Universal_Fixed then
7059 Fixup_Universal_Fixed_Operation (N);
7060 Typ := Etype (N);
7061 end if;
7063 -- Divisions with fixed-point results
7065 if Is_Fixed_Point_Type (Typ) then
7067 -- Deal with divide-by-zero check if back end cannot handle them
7068 -- and the flag is set indicating that we need such a check. Note
7069 -- that we don't need to bother here with the case of mixed-mode
7070 -- (Right operand an integer type), since these will be rewritten
7071 -- with conversions to a divide with a fixed-point right operand.
7073 if Do_Division_Check (N)
7074 and then not Backend_Divide_Checks_On_Target
7075 and then not Is_Integer_Type (Rtyp)
7076 then
7077 Set_Do_Division_Check (N, False);
7078 Insert_Action (N,
7079 Make_Raise_Constraint_Error (Loc,
7080 Condition =>
7081 Make_Op_Eq (Loc,
7082 Left_Opnd => Duplicate_Subexpr_Move_Checks (Ropnd),
7083 Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
7084 Reason => CE_Divide_By_Zero));
7085 end if;
7087 -- No special processing if Treat_Fixed_As_Integer is set, since
7088 -- from a semantic point of view such operations are simply integer
7089 -- operations and will be treated that way.
7091 if not Treat_Fixed_As_Integer (N) then
7092 if Is_Integer_Type (Rtyp) then
7093 Expand_Divide_Fixed_By_Integer_Giving_Fixed (N);
7094 else
7095 Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N);
7096 end if;
7097 end if;
7099 -- Other cases of division of fixed-point operands. Again we exclude the
7100 -- case where Treat_Fixed_As_Integer is set.
7102 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
7103 and then not Treat_Fixed_As_Integer (N)
7104 then
7105 if Is_Integer_Type (Typ) then
7106 Expand_Divide_Fixed_By_Fixed_Giving_Integer (N);
7107 else
7108 pragma Assert (Is_Floating_Point_Type (Typ));
7109 Expand_Divide_Fixed_By_Fixed_Giving_Float (N);
7110 end if;
7112 -- Mixed-mode operations can appear in a non-static universal context,
7113 -- in which case the integer argument must be converted explicitly.
7115 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
7116 Rewrite (Ropnd,
7117 Convert_To (Universal_Real, Relocate_Node (Ropnd)));
7119 Analyze_And_Resolve (Ropnd, Universal_Real);
7121 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
7122 Rewrite (Lopnd,
7123 Convert_To (Universal_Real, Relocate_Node (Lopnd)));
7125 Analyze_And_Resolve (Lopnd, Universal_Real);
7127 -- Non-fixed point cases, do integer zero divide and overflow checks
7129 elsif Is_Integer_Type (Typ) then
7130 Apply_Divide_Checks (N);
7131 end if;
7133 -- Overflow checks for floating-point if -gnateF mode active
7135 Check_Float_Op_Overflow (N);
7137 -- Generating C code convert non-binary modular divisions into code that
7138 -- relies on the frontend expansion of operator Mod.
7140 if Modify_Tree_For_C then
7141 Expand_Non_Binary_Modular_Op (N);
7142 end if;
7143 end Expand_N_Op_Divide;
7145 --------------------
7146 -- Expand_N_Op_Eq --
7147 --------------------
7149 procedure Expand_N_Op_Eq (N : Node_Id) is
7150 Loc : constant Source_Ptr := Sloc (N);
7151 Typ : constant Entity_Id := Etype (N);
7152 Lhs : constant Node_Id := Left_Opnd (N);
7153 Rhs : constant Node_Id := Right_Opnd (N);
7154 Bodies : constant List_Id := New_List;
7155 A_Typ : constant Entity_Id := Etype (Lhs);
7157 Typl : Entity_Id := A_Typ;
7158 Op_Name : Entity_Id;
7159 Prim : Elmt_Id;
7161 procedure Build_Equality_Call (Eq : Entity_Id);
7162 -- If a constructed equality exists for the type or for its parent,
7163 -- build and analyze call, adding conversions if the operation is
7164 -- inherited.
7166 function Has_Unconstrained_UU_Component (Typ : Node_Id) return Boolean;
7167 -- Determines whether a type has a subcomponent of an unconstrained
7168 -- Unchecked_Union subtype. Typ is a record type.
7170 -------------------------
7171 -- Build_Equality_Call --
7172 -------------------------
7174 procedure Build_Equality_Call (Eq : Entity_Id) is
7175 Op_Type : constant Entity_Id := Etype (First_Formal (Eq));
7176 L_Exp : Node_Id := Relocate_Node (Lhs);
7177 R_Exp : Node_Id := Relocate_Node (Rhs);
7179 begin
7180 -- Adjust operands if necessary to comparison type
7182 if Base_Type (Op_Type) /= Base_Type (A_Typ)
7183 and then not Is_Class_Wide_Type (A_Typ)
7184 then
7185 L_Exp := OK_Convert_To (Op_Type, L_Exp);
7186 R_Exp := OK_Convert_To (Op_Type, R_Exp);
7187 end if;
7189 -- If we have an Unchecked_Union, we need to add the inferred
7190 -- discriminant values as actuals in the function call. At this
7191 -- point, the expansion has determined that both operands have
7192 -- inferable discriminants.
7194 if Is_Unchecked_Union (Op_Type) then
7195 declare
7196 Lhs_Type : constant Node_Id := Etype (L_Exp);
7197 Rhs_Type : constant Node_Id := Etype (R_Exp);
7199 Lhs_Discr_Vals : Elist_Id;
7200 -- List of inferred discriminant values for left operand.
7202 Rhs_Discr_Vals : Elist_Id;
7203 -- List of inferred discriminant values for right operand.
7205 Discr : Entity_Id;
7207 begin
7208 Lhs_Discr_Vals := New_Elmt_List;
7209 Rhs_Discr_Vals := New_Elmt_List;
7211 -- Per-object constrained selected components require special
7212 -- attention. If the enclosing scope of the component is an
7213 -- Unchecked_Union, we cannot reference its discriminants
7214 -- directly. This is why we use the extra parameters of the
7215 -- equality function of the enclosing Unchecked_Union.
7217 -- type UU_Type (Discr : Integer := 0) is
7218 -- . . .
7219 -- end record;
7220 -- pragma Unchecked_Union (UU_Type);
7222 -- 1. Unchecked_Union enclosing record:
7224 -- type Enclosing_UU_Type (Discr : Integer := 0) is record
7225 -- . . .
7226 -- Comp : UU_Type (Discr);
7227 -- . . .
7228 -- end Enclosing_UU_Type;
7229 -- pragma Unchecked_Union (Enclosing_UU_Type);
7231 -- Obj1 : Enclosing_UU_Type;
7232 -- Obj2 : Enclosing_UU_Type (1);
7234 -- [. . .] Obj1 = Obj2 [. . .]
7236 -- Generated code:
7238 -- if not (uu_typeEQ (obj1.comp, obj2.comp, a, b)) then
7240 -- A and B are the formal parameters of the equality function
7241 -- of Enclosing_UU_Type. The function always has two extra
7242 -- formals to capture the inferred discriminant values for
7243 -- each discriminant of the type.
7245 -- 2. Non-Unchecked_Union enclosing record:
7247 -- type
7248 -- Enclosing_Non_UU_Type (Discr : Integer := 0)
7249 -- is record
7250 -- . . .
7251 -- Comp : UU_Type (Discr);
7252 -- . . .
7253 -- end Enclosing_Non_UU_Type;
7255 -- Obj1 : Enclosing_Non_UU_Type;
7256 -- Obj2 : Enclosing_Non_UU_Type (1);
7258 -- ... Obj1 = Obj2 ...
7260 -- Generated code:
7262 -- if not (uu_typeEQ (obj1.comp, obj2.comp,
7263 -- obj1.discr, obj2.discr)) then
7265 -- In this case we can directly reference the discriminants of
7266 -- the enclosing record.
7268 -- Process left operand of equality
7270 if Nkind (Lhs) = N_Selected_Component
7271 and then
7272 Has_Per_Object_Constraint (Entity (Selector_Name (Lhs)))
7273 then
7274 -- If enclosing record is an Unchecked_Union, use formals
7275 -- corresponding to each discriminant. The name of the
7276 -- formal is that of the discriminant, with added suffix,
7277 -- see Exp_Ch3.Build_Record_Equality for details.
7279 if Is_Unchecked_Union (Scope (Entity (Selector_Name (Lhs))))
7280 then
7281 Discr :=
7282 First_Discriminant
7283 (Scope (Entity (Selector_Name (Lhs))));
7284 while Present (Discr) loop
7285 Append_Elmt
7286 (Make_Identifier (Loc,
7287 Chars => New_External_Name (Chars (Discr), 'A')),
7288 To => Lhs_Discr_Vals);
7289 Next_Discriminant (Discr);
7290 end loop;
7292 -- If enclosing record is of a non-Unchecked_Union type, it
7293 -- is possible to reference its discriminants directly.
7295 else
7296 Discr := First_Discriminant (Lhs_Type);
7297 while Present (Discr) loop
7298 Append_Elmt
7299 (Make_Selected_Component (Loc,
7300 Prefix => Prefix (Lhs),
7301 Selector_Name =>
7302 New_Copy
7303 (Get_Discriminant_Value (Discr,
7304 Lhs_Type,
7305 Stored_Constraint (Lhs_Type)))),
7306 To => Lhs_Discr_Vals);
7307 Next_Discriminant (Discr);
7308 end loop;
7309 end if;
7311 -- Otherwise operand is on object with a constrained type.
7312 -- Infer the discriminant values from the constraint.
7314 else
7316 Discr := First_Discriminant (Lhs_Type);
7317 while Present (Discr) loop
7318 Append_Elmt
7319 (New_Copy
7320 (Get_Discriminant_Value (Discr,
7321 Lhs_Type,
7322 Stored_Constraint (Lhs_Type))),
7323 To => Lhs_Discr_Vals);
7324 Next_Discriminant (Discr);
7325 end loop;
7326 end if;
7328 -- Similar processing for right operand of equality
7330 if Nkind (Rhs) = N_Selected_Component
7331 and then
7332 Has_Per_Object_Constraint (Entity (Selector_Name (Rhs)))
7333 then
7334 if Is_Unchecked_Union
7335 (Scope (Entity (Selector_Name (Rhs))))
7336 then
7337 Discr :=
7338 First_Discriminant
7339 (Scope (Entity (Selector_Name (Rhs))));
7340 while Present (Discr) loop
7341 Append_Elmt
7342 (Make_Identifier (Loc,
7343 Chars => New_External_Name (Chars (Discr), 'B')),
7344 To => Rhs_Discr_Vals);
7345 Next_Discriminant (Discr);
7346 end loop;
7348 else
7349 Discr := First_Discriminant (Rhs_Type);
7350 while Present (Discr) loop
7351 Append_Elmt
7352 (Make_Selected_Component (Loc,
7353 Prefix => Prefix (Rhs),
7354 Selector_Name =>
7355 New_Copy (Get_Discriminant_Value
7356 (Discr,
7357 Rhs_Type,
7358 Stored_Constraint (Rhs_Type)))),
7359 To => Rhs_Discr_Vals);
7360 Next_Discriminant (Discr);
7361 end loop;
7362 end if;
7364 else
7365 Discr := First_Discriminant (Rhs_Type);
7366 while Present (Discr) loop
7367 Append_Elmt
7368 (New_Copy (Get_Discriminant_Value
7369 (Discr,
7370 Rhs_Type,
7371 Stored_Constraint (Rhs_Type))),
7372 To => Rhs_Discr_Vals);
7373 Next_Discriminant (Discr);
7374 end loop;
7375 end if;
7377 -- Now merge the list of discriminant values so that values
7378 -- of corresponding discriminants are adjacent.
7380 declare
7381 Params : List_Id;
7382 L_Elmt : Elmt_Id;
7383 R_Elmt : Elmt_Id;
7385 begin
7386 Params := New_List (L_Exp, R_Exp);
7387 L_Elmt := First_Elmt (Lhs_Discr_Vals);
7388 R_Elmt := First_Elmt (Rhs_Discr_Vals);
7389 while Present (L_Elmt) loop
7390 Append_To (Params, Node (L_Elmt));
7391 Append_To (Params, Node (R_Elmt));
7392 Next_Elmt (L_Elmt);
7393 Next_Elmt (R_Elmt);
7394 end loop;
7396 Rewrite (N,
7397 Make_Function_Call (Loc,
7398 Name => New_Occurrence_Of (Eq, Loc),
7399 Parameter_Associations => Params));
7400 end;
7401 end;
7403 -- Normal case, not an unchecked union
7405 else
7406 Rewrite (N,
7407 Make_Function_Call (Loc,
7408 Name => New_Occurrence_Of (Eq, Loc),
7409 Parameter_Associations => New_List (L_Exp, R_Exp)));
7410 end if;
7412 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7413 end Build_Equality_Call;
7415 ------------------------------------
7416 -- Has_Unconstrained_UU_Component --
7417 ------------------------------------
7419 function Has_Unconstrained_UU_Component
7420 (Typ : Node_Id) return Boolean
7422 Tdef : constant Node_Id :=
7423 Type_Definition (Declaration_Node (Base_Type (Typ)));
7424 Clist : Node_Id;
7425 Vpart : Node_Id;
7427 function Component_Is_Unconstrained_UU
7428 (Comp : Node_Id) return Boolean;
7429 -- Determines whether the subtype of the component is an
7430 -- unconstrained Unchecked_Union.
7432 function Variant_Is_Unconstrained_UU
7433 (Variant : Node_Id) return Boolean;
7434 -- Determines whether a component of the variant has an unconstrained
7435 -- Unchecked_Union subtype.
7437 -----------------------------------
7438 -- Component_Is_Unconstrained_UU --
7439 -----------------------------------
7441 function Component_Is_Unconstrained_UU
7442 (Comp : Node_Id) return Boolean
7444 begin
7445 if Nkind (Comp) /= N_Component_Declaration then
7446 return False;
7447 end if;
7449 declare
7450 Sindic : constant Node_Id :=
7451 Subtype_Indication (Component_Definition (Comp));
7453 begin
7454 -- Unconstrained nominal type. In the case of a constraint
7455 -- present, the node kind would have been N_Subtype_Indication.
7457 if Nkind (Sindic) = N_Identifier then
7458 return Is_Unchecked_Union (Base_Type (Etype (Sindic)));
7459 end if;
7461 return False;
7462 end;
7463 end Component_Is_Unconstrained_UU;
7465 ---------------------------------
7466 -- Variant_Is_Unconstrained_UU --
7467 ---------------------------------
7469 function Variant_Is_Unconstrained_UU
7470 (Variant : Node_Id) return Boolean
7472 Clist : constant Node_Id := Component_List (Variant);
7474 begin
7475 if Is_Empty_List (Component_Items (Clist)) then
7476 return False;
7477 end if;
7479 -- We only need to test one component
7481 declare
7482 Comp : Node_Id := First (Component_Items (Clist));
7484 begin
7485 while Present (Comp) loop
7486 if Component_Is_Unconstrained_UU (Comp) then
7487 return True;
7488 end if;
7490 Next (Comp);
7491 end loop;
7492 end;
7494 -- None of the components withing the variant were of
7495 -- unconstrained Unchecked_Union type.
7497 return False;
7498 end Variant_Is_Unconstrained_UU;
7500 -- Start of processing for Has_Unconstrained_UU_Component
7502 begin
7503 if Null_Present (Tdef) then
7504 return False;
7505 end if;
7507 Clist := Component_List (Tdef);
7508 Vpart := Variant_Part (Clist);
7510 -- Inspect available components
7512 if Present (Component_Items (Clist)) then
7513 declare
7514 Comp : Node_Id := First (Component_Items (Clist));
7516 begin
7517 while Present (Comp) loop
7519 -- One component is sufficient
7521 if Component_Is_Unconstrained_UU (Comp) then
7522 return True;
7523 end if;
7525 Next (Comp);
7526 end loop;
7527 end;
7528 end if;
7530 -- Inspect available components withing variants
7532 if Present (Vpart) then
7533 declare
7534 Variant : Node_Id := First (Variants (Vpart));
7536 begin
7537 while Present (Variant) loop
7539 -- One component within a variant is sufficient
7541 if Variant_Is_Unconstrained_UU (Variant) then
7542 return True;
7543 end if;
7545 Next (Variant);
7546 end loop;
7547 end;
7548 end if;
7550 -- Neither the available components, nor the components inside the
7551 -- variant parts were of an unconstrained Unchecked_Union subtype.
7553 return False;
7554 end Has_Unconstrained_UU_Component;
7556 -- Start of processing for Expand_N_Op_Eq
7558 begin
7559 Binary_Op_Validity_Checks (N);
7561 -- Deal with private types
7563 if Ekind (Typl) = E_Private_Type then
7564 Typl := Underlying_Type (Typl);
7565 elsif Ekind (Typl) = E_Private_Subtype then
7566 Typl := Underlying_Type (Base_Type (Typl));
7567 else
7568 null;
7569 end if;
7571 -- It may happen in error situations that the underlying type is not
7572 -- set. The error will be detected later, here we just defend the
7573 -- expander code.
7575 if No (Typl) then
7576 return;
7577 end if;
7579 -- Now get the implementation base type (note that plain Base_Type here
7580 -- might lead us back to the private type, which is not what we want!)
7582 Typl := Implementation_Base_Type (Typl);
7584 -- Equality between variant records results in a call to a routine
7585 -- that has conditional tests of the discriminant value(s), and hence
7586 -- violates the No_Implicit_Conditionals restriction.
7588 if Has_Variant_Part (Typl) then
7589 declare
7590 Msg : Boolean;
7592 begin
7593 Check_Restriction (Msg, No_Implicit_Conditionals, N);
7595 if Msg then
7596 Error_Msg_N
7597 ("\comparison of variant records tests discriminants", N);
7598 return;
7599 end if;
7600 end;
7601 end if;
7603 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
7604 -- means we no longer have a comparison operation, we are all done.
7606 Expand_Compare_Minimize_Eliminate_Overflow (N);
7608 if Nkind (N) /= N_Op_Eq then
7609 return;
7610 end if;
7612 -- Boolean types (requiring handling of non-standard case)
7614 if Is_Boolean_Type (Typl) then
7615 Adjust_Condition (Left_Opnd (N));
7616 Adjust_Condition (Right_Opnd (N));
7617 Set_Etype (N, Standard_Boolean);
7618 Adjust_Result_Type (N, Typ);
7620 -- Array types
7622 elsif Is_Array_Type (Typl) then
7624 -- If we are doing full validity checking, and it is possible for the
7625 -- array elements to be invalid then expand out array comparisons to
7626 -- make sure that we check the array elements.
7628 if Validity_Check_Operands
7629 and then not Is_Known_Valid (Component_Type (Typl))
7630 then
7631 declare
7632 Save_Force_Validity_Checks : constant Boolean :=
7633 Force_Validity_Checks;
7634 begin
7635 Force_Validity_Checks := True;
7636 Rewrite (N,
7637 Expand_Array_Equality
7639 Relocate_Node (Lhs),
7640 Relocate_Node (Rhs),
7641 Bodies,
7642 Typl));
7643 Insert_Actions (N, Bodies);
7644 Analyze_And_Resolve (N, Standard_Boolean);
7645 Force_Validity_Checks := Save_Force_Validity_Checks;
7646 end;
7648 -- Packed case where both operands are known aligned
7650 elsif Is_Bit_Packed_Array (Typl)
7651 and then not Is_Possibly_Unaligned_Object (Lhs)
7652 and then not Is_Possibly_Unaligned_Object (Rhs)
7653 then
7654 Expand_Packed_Eq (N);
7656 -- Where the component type is elementary we can use a block bit
7657 -- comparison (if supported on the target) exception in the case
7658 -- of floating-point (negative zero issues require element by
7659 -- element comparison), and atomic/VFA types (where we must be sure
7660 -- to load elements independently) and possibly unaligned arrays.
7662 elsif Is_Elementary_Type (Component_Type (Typl))
7663 and then not Is_Floating_Point_Type (Component_Type (Typl))
7664 and then not Is_Atomic_Or_VFA (Component_Type (Typl))
7665 and then not Is_Possibly_Unaligned_Object (Lhs)
7666 and then not Is_Possibly_Unaligned_Object (Rhs)
7667 and then Support_Composite_Compare_On_Target
7668 then
7669 null;
7671 -- For composite and floating-point cases, expand equality loop to
7672 -- make sure of using proper comparisons for tagged types, and
7673 -- correctly handling the floating-point case.
7675 else
7676 Rewrite (N,
7677 Expand_Array_Equality
7679 Relocate_Node (Lhs),
7680 Relocate_Node (Rhs),
7681 Bodies,
7682 Typl));
7683 Insert_Actions (N, Bodies, Suppress => All_Checks);
7684 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7685 end if;
7687 -- Record Types
7689 elsif Is_Record_Type (Typl) then
7691 -- For tagged types, use the primitive "="
7693 if Is_Tagged_Type (Typl) then
7695 -- No need to do anything else compiling under restriction
7696 -- No_Dispatching_Calls. During the semantic analysis we
7697 -- already notified such violation.
7699 if Restriction_Active (No_Dispatching_Calls) then
7700 return;
7701 end if;
7703 -- If this is derived from an untagged private type completed with
7704 -- a tagged type, it does not have a full view, so we use the
7705 -- primitive operations of the private type. This check should no
7706 -- longer be necessary when these types get their full views???
7708 if Is_Private_Type (A_Typ)
7709 and then not Is_Tagged_Type (A_Typ)
7710 and then Is_Derived_Type (A_Typ)
7711 and then No (Full_View (A_Typ))
7712 then
7713 -- Search for equality operation, checking that the operands
7714 -- have the same type. Note that we must find a matching entry,
7715 -- or something is very wrong.
7717 Prim := First_Elmt (Collect_Primitive_Operations (A_Typ));
7719 while Present (Prim) loop
7720 exit when Chars (Node (Prim)) = Name_Op_Eq
7721 and then Etype (First_Formal (Node (Prim))) =
7722 Etype (Next_Formal (First_Formal (Node (Prim))))
7723 and then
7724 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7726 Next_Elmt (Prim);
7727 end loop;
7729 pragma Assert (Present (Prim));
7730 Op_Name := Node (Prim);
7732 -- Find the type's predefined equality or an overriding
7733 -- user-defined equality. The reason for not simply calling
7734 -- Find_Prim_Op here is that there may be a user-defined
7735 -- overloaded equality op that precedes the equality that we
7736 -- want, so we have to explicitly search (e.g., there could be
7737 -- an equality with two different parameter types).
7739 else
7740 if Is_Class_Wide_Type (Typl) then
7741 Typl := Find_Specific_Type (Typl);
7742 end if;
7744 Prim := First_Elmt (Primitive_Operations (Typl));
7745 while Present (Prim) loop
7746 exit when Chars (Node (Prim)) = Name_Op_Eq
7747 and then Etype (First_Formal (Node (Prim))) =
7748 Etype (Next_Formal (First_Formal (Node (Prim))))
7749 and then
7750 Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7752 Next_Elmt (Prim);
7753 end loop;
7755 pragma Assert (Present (Prim));
7756 Op_Name := Node (Prim);
7757 end if;
7759 Build_Equality_Call (Op_Name);
7761 -- Ada 2005 (AI-216): Program_Error is raised when evaluating the
7762 -- predefined equality operator for a type which has a subcomponent
7763 -- of an Unchecked_Union type whose nominal subtype is unconstrained.
7765 elsif Has_Unconstrained_UU_Component (Typl) then
7766 Insert_Action (N,
7767 Make_Raise_Program_Error (Loc,
7768 Reason => PE_Unchecked_Union_Restriction));
7770 -- Prevent Gigi from generating incorrect code by rewriting the
7771 -- equality as a standard False. (is this documented somewhere???)
7773 Rewrite (N,
7774 New_Occurrence_Of (Standard_False, Loc));
7776 elsif Is_Unchecked_Union (Typl) then
7778 -- If we can infer the discriminants of the operands, we make a
7779 -- call to the TSS equality function.
7781 if Has_Inferable_Discriminants (Lhs)
7782 and then
7783 Has_Inferable_Discriminants (Rhs)
7784 then
7785 Build_Equality_Call
7786 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7788 else
7789 -- Ada 2005 (AI-216): Program_Error is raised when evaluating
7790 -- the predefined equality operator for an Unchecked_Union type
7791 -- if either of the operands lack inferable discriminants.
7793 Insert_Action (N,
7794 Make_Raise_Program_Error (Loc,
7795 Reason => PE_Unchecked_Union_Restriction));
7797 -- Emit a warning on source equalities only, otherwise the
7798 -- message may appear out of place due to internal use. The
7799 -- warning is unconditional because it is required by the
7800 -- language.
7802 if Comes_From_Source (N) then
7803 Error_Msg_N
7804 ("Unchecked_Union discriminants cannot be determined??",
7806 Error_Msg_N
7807 ("\Program_Error will be raised for equality operation??",
7809 end if;
7811 -- Prevent Gigi from generating incorrect code by rewriting
7812 -- the equality as a standard False (documented where???).
7814 Rewrite (N,
7815 New_Occurrence_Of (Standard_False, Loc));
7816 end if;
7818 -- If a type support function is present (for complex cases), use it
7820 elsif Present (TSS (Root_Type (Typl), TSS_Composite_Equality)) then
7821 Build_Equality_Call
7822 (TSS (Root_Type (Typl), TSS_Composite_Equality));
7824 -- When comparing two Bounded_Strings, use the primitive equality of
7825 -- the root Super_String type.
7827 elsif Is_Bounded_String (Typl) then
7828 Prim :=
7829 First_Elmt (Collect_Primitive_Operations (Root_Type (Typl)));
7831 while Present (Prim) loop
7832 exit when Chars (Node (Prim)) = Name_Op_Eq
7833 and then Etype (First_Formal (Node (Prim))) =
7834 Etype (Next_Formal (First_Formal (Node (Prim))))
7835 and then Base_Type (Etype (Node (Prim))) = Standard_Boolean;
7837 Next_Elmt (Prim);
7838 end loop;
7840 -- A Super_String type should always have a primitive equality
7842 pragma Assert (Present (Prim));
7843 Build_Equality_Call (Node (Prim));
7845 -- Otherwise expand the component by component equality. Note that
7846 -- we never use block-bit comparisons for records, because of the
7847 -- problems with gaps. The backend will often be able to recombine
7848 -- the separate comparisons that we generate here.
7850 else
7851 Remove_Side_Effects (Lhs);
7852 Remove_Side_Effects (Rhs);
7853 Rewrite (N,
7854 Expand_Record_Equality (N, Typl, Lhs, Rhs, Bodies));
7856 Insert_Actions (N, Bodies, Suppress => All_Checks);
7857 Analyze_And_Resolve (N, Standard_Boolean, Suppress => All_Checks);
7858 end if;
7859 end if;
7861 -- Test if result is known at compile time
7863 Rewrite_Comparison (N);
7865 -- Special optimization of length comparison
7867 Optimize_Length_Comparison (N);
7869 -- One more special case: if we have a comparison of X'Result = expr
7870 -- in floating-point, then if not already there, change expr to be
7871 -- f'Machine (expr) to eliminate surprise from extra precision.
7873 if Is_Floating_Point_Type (Typl)
7874 and then Nkind (Original_Node (Lhs)) = N_Attribute_Reference
7875 and then Attribute_Name (Original_Node (Lhs)) = Name_Result
7876 then
7877 -- Stick in the Typ'Machine call if not already there
7879 if Nkind (Rhs) /= N_Attribute_Reference
7880 or else Attribute_Name (Rhs) /= Name_Machine
7881 then
7882 Rewrite (Rhs,
7883 Make_Attribute_Reference (Loc,
7884 Prefix => New_Occurrence_Of (Typl, Loc),
7885 Attribute_Name => Name_Machine,
7886 Expressions => New_List (Relocate_Node (Rhs))));
7887 Analyze_And_Resolve (Rhs, Typl);
7888 end if;
7889 end if;
7890 end Expand_N_Op_Eq;
7892 -----------------------
7893 -- Expand_N_Op_Expon --
7894 -----------------------
7896 procedure Expand_N_Op_Expon (N : Node_Id) is
7897 Loc : constant Source_Ptr := Sloc (N);
7898 Ovflo : constant Boolean := Do_Overflow_Check (N);
7899 Typ : constant Entity_Id := Etype (N);
7900 Rtyp : constant Entity_Id := Root_Type (Typ);
7902 Bastyp : Entity_Id;
7904 function Wrap_MA (Exp : Node_Id) return Node_Id;
7905 -- Given an expression Exp, if the root type is Float or Long_Float,
7906 -- then wrap the expression in a call of Bastyp'Machine, to stop any
7907 -- extra precision. This is done to ensure that X**A = X**B when A is
7908 -- a static constant and B is a variable with the same value. For any
7909 -- other type, the node Exp is returned unchanged.
7911 -------------
7912 -- Wrap_MA --
7913 -------------
7915 function Wrap_MA (Exp : Node_Id) return Node_Id is
7916 Loc : constant Source_Ptr := Sloc (Exp);
7918 begin
7919 if Rtyp = Standard_Float or else Rtyp = Standard_Long_Float then
7920 return
7921 Make_Attribute_Reference (Loc,
7922 Attribute_Name => Name_Machine,
7923 Prefix => New_Occurrence_Of (Bastyp, Loc),
7924 Expressions => New_List (Relocate_Node (Exp)));
7925 else
7926 return Exp;
7927 end if;
7928 end Wrap_MA;
7930 -- Local variables
7932 Base : Node_Id;
7933 Ent : Entity_Id;
7934 Etyp : Entity_Id;
7935 Exp : Node_Id;
7936 Exptyp : Entity_Id;
7937 Expv : Uint;
7938 Rent : RE_Id;
7939 Temp : Node_Id;
7940 Xnode : Node_Id;
7942 -- Start of processing for Expand_N_Op_Expon
7944 begin
7945 Binary_Op_Validity_Checks (N);
7947 -- CodePeer wants to see the unexpanded N_Op_Expon node
7949 if CodePeer_Mode then
7950 return;
7951 end if;
7953 -- Relocation of left and right operands must be done after performing
7954 -- the validity checks since the generation of validation checks may
7955 -- remove side effects.
7957 Base := Relocate_Node (Left_Opnd (N));
7958 Bastyp := Etype (Base);
7959 Exp := Relocate_Node (Right_Opnd (N));
7960 Exptyp := Etype (Exp);
7962 -- If either operand is of a private type, then we have the use of an
7963 -- intrinsic operator, and we get rid of the privateness, by using root
7964 -- types of underlying types for the actual operation. Otherwise the
7965 -- private types will cause trouble if we expand multiplications or
7966 -- shifts etc. We also do this transformation if the result type is
7967 -- different from the base type.
7969 if Is_Private_Type (Etype (Base))
7970 or else Is_Private_Type (Typ)
7971 or else Is_Private_Type (Exptyp)
7972 or else Rtyp /= Root_Type (Bastyp)
7973 then
7974 declare
7975 Bt : constant Entity_Id := Root_Type (Underlying_Type (Bastyp));
7976 Et : constant Entity_Id := Root_Type (Underlying_Type (Exptyp));
7977 begin
7978 Rewrite (N,
7979 Unchecked_Convert_To (Typ,
7980 Make_Op_Expon (Loc,
7981 Left_Opnd => Unchecked_Convert_To (Bt, Base),
7982 Right_Opnd => Unchecked_Convert_To (Et, Exp))));
7983 Analyze_And_Resolve (N, Typ);
7984 return;
7985 end;
7986 end if;
7988 -- Check for MINIMIZED/ELIMINATED overflow mode
7990 if Minimized_Eliminated_Overflow_Check (N) then
7991 Apply_Arithmetic_Overflow_Check (N);
7992 return;
7993 end if;
7995 -- Test for case of known right argument where we can replace the
7996 -- exponentiation by an equivalent expression using multiplication.
7998 -- Note: use CRT_Safe version of Compile_Time_Known_Value because in
7999 -- configurable run-time mode, we may not have the exponentiation
8000 -- routine available, and we don't want the legality of the program
8001 -- to depend on how clever the compiler is in knowing values.
8003 if CRT_Safe_Compile_Time_Known_Value (Exp) then
8004 Expv := Expr_Value (Exp);
8006 -- We only fold small non-negative exponents. You might think we
8007 -- could fold small negative exponents for the real case, but we
8008 -- can't because we are required to raise Constraint_Error for
8009 -- the case of 0.0 ** (negative) even if Machine_Overflows = False.
8010 -- See ACVC test C4A012B, and it is not worth generating the test.
8012 -- For small negative exponents, we return the reciprocal of
8013 -- the folding of the exponentiation for the opposite (positive)
8014 -- exponent, as required by Ada RM 4.5.6(11/3).
8016 if abs Expv <= 4 then
8018 -- X ** 0 = 1 (or 1.0)
8020 if Expv = 0 then
8022 -- Call Remove_Side_Effects to ensure that any side effects
8023 -- in the ignored left operand (in particular function calls
8024 -- to user defined functions) are properly executed.
8026 Remove_Side_Effects (Base);
8028 if Ekind (Typ) in Integer_Kind then
8029 Xnode := Make_Integer_Literal (Loc, Intval => 1);
8030 else
8031 Xnode := Make_Real_Literal (Loc, Ureal_1);
8032 end if;
8034 -- X ** 1 = X
8036 elsif Expv = 1 then
8037 Xnode := Base;
8039 -- X ** 2 = X * X
8041 elsif Expv = 2 then
8042 Xnode :=
8043 Wrap_MA (
8044 Make_Op_Multiply (Loc,
8045 Left_Opnd => Duplicate_Subexpr (Base),
8046 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8048 -- X ** 3 = X * X * X
8050 elsif Expv = 3 then
8051 Xnode :=
8052 Wrap_MA (
8053 Make_Op_Multiply (Loc,
8054 Left_Opnd =>
8055 Make_Op_Multiply (Loc,
8056 Left_Opnd => Duplicate_Subexpr (Base),
8057 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)),
8058 Right_Opnd => Duplicate_Subexpr_No_Checks (Base)));
8060 -- X ** 4 ->
8062 -- do
8063 -- En : constant base'type := base * base;
8064 -- in
8065 -- En * En
8067 elsif Expv = 4 then
8068 Temp := Make_Temporary (Loc, 'E', Base);
8070 Xnode :=
8071 Make_Expression_With_Actions (Loc,
8072 Actions => New_List (
8073 Make_Object_Declaration (Loc,
8074 Defining_Identifier => Temp,
8075 Constant_Present => True,
8076 Object_Definition => New_Occurrence_Of (Typ, Loc),
8077 Expression =>
8078 Wrap_MA (
8079 Make_Op_Multiply (Loc,
8080 Left_Opnd =>
8081 Duplicate_Subexpr (Base),
8082 Right_Opnd =>
8083 Duplicate_Subexpr_No_Checks (Base))))),
8085 Expression =>
8086 Wrap_MA (
8087 Make_Op_Multiply (Loc,
8088 Left_Opnd => New_Occurrence_Of (Temp, Loc),
8089 Right_Opnd => New_Occurrence_Of (Temp, Loc))));
8091 -- X ** N = 1.0 / X ** (-N)
8092 -- N in -4 .. -1
8094 else
8095 pragma Assert
8096 (Expv = -1 or Expv = -2 or Expv = -3 or Expv = -4);
8098 Xnode :=
8099 Make_Op_Divide (Loc,
8100 Left_Opnd =>
8101 Make_Float_Literal (Loc,
8102 Radix => Uint_1,
8103 Significand => Uint_1,
8104 Exponent => Uint_0),
8105 Right_Opnd =>
8106 Make_Op_Expon (Loc,
8107 Left_Opnd => Duplicate_Subexpr (Base),
8108 Right_Opnd =>
8109 Make_Integer_Literal (Loc,
8110 Intval => -Expv)));
8111 end if;
8113 Rewrite (N, Xnode);
8114 Analyze_And_Resolve (N, Typ);
8115 return;
8116 end if;
8117 end if;
8119 -- Deal with optimizing 2 ** expression to shift where possible
8121 -- Note: we used to check that Exptyp was an unsigned type. But that is
8122 -- an unnecessary check, since if Exp is negative, we have a run-time
8123 -- error that is either caught (so we get the right result) or we have
8124 -- suppressed the check, in which case the code is erroneous anyway.
8126 if Is_Integer_Type (Rtyp)
8128 -- The base value must be "safe compile-time known", and exactly 2
8130 and then Nkind (Base) = N_Integer_Literal
8131 and then CRT_Safe_Compile_Time_Known_Value (Base)
8132 and then Expr_Value (Base) = Uint_2
8134 -- We only handle cases where the right type is a integer
8136 and then Is_Integer_Type (Root_Type (Exptyp))
8137 and then Esize (Root_Type (Exptyp)) <= Esize (Standard_Integer)
8139 -- This transformation is not applicable for a modular type with a
8140 -- nonbinary modulus because we do not handle modular reduction in
8141 -- a correct manner if we attempt this transformation in this case.
8143 and then not Non_Binary_Modulus (Typ)
8144 then
8145 -- Handle the cases where our parent is a division or multiplication
8146 -- specially. In these cases we can convert to using a shift at the
8147 -- parent level if we are not doing overflow checking, since it is
8148 -- too tricky to combine the overflow check at the parent level.
8150 if not Ovflo
8151 and then Nkind_In (Parent (N), N_Op_Divide, N_Op_Multiply)
8152 then
8153 declare
8154 P : constant Node_Id := Parent (N);
8155 L : constant Node_Id := Left_Opnd (P);
8156 R : constant Node_Id := Right_Opnd (P);
8158 begin
8159 if (Nkind (P) = N_Op_Multiply
8160 and then
8161 ((Is_Integer_Type (Etype (L)) and then R = N)
8162 or else
8163 (Is_Integer_Type (Etype (R)) and then L = N))
8164 and then not Do_Overflow_Check (P))
8166 or else
8167 (Nkind (P) = N_Op_Divide
8168 and then Is_Integer_Type (Etype (L))
8169 and then Is_Unsigned_Type (Etype (L))
8170 and then R = N
8171 and then not Do_Overflow_Check (P))
8172 then
8173 Set_Is_Power_Of_2_For_Shift (N);
8174 return;
8175 end if;
8176 end;
8178 -- Here we just have 2 ** N on its own, so we can convert this to a
8179 -- shift node. We are prepared to deal with overflow here, and we
8180 -- also have to handle proper modular reduction for binary modular.
8182 else
8183 declare
8184 OK : Boolean;
8185 Lo : Uint;
8186 Hi : Uint;
8188 MaxS : Uint;
8189 -- Maximum shift count with no overflow
8191 TestS : Boolean;
8192 -- Set True if we must test the shift count
8194 Test_Gt : Node_Id;
8195 -- Node for test against TestS
8197 begin
8198 -- Compute maximum shift based on the underlying size. For a
8199 -- modular type this is one less than the size.
8201 if Is_Modular_Integer_Type (Typ) then
8203 -- For modular integer types, this is the size of the value
8204 -- being shifted minus one. Any larger values will cause
8205 -- modular reduction to a result of zero. Note that we do
8206 -- want the RM_Size here (e.g. mod 2 ** 7, we want a result
8207 -- of 6, since 2**7 should be reduced to zero).
8209 MaxS := RM_Size (Rtyp) - 1;
8211 -- For signed integer types, we use the size of the value
8212 -- being shifted minus 2. Larger values cause overflow.
8214 else
8215 MaxS := Esize (Rtyp) - 2;
8216 end if;
8218 -- Determine range to see if it can be larger than MaxS
8220 Determine_Range
8221 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
8222 TestS := (not OK) or else Hi > MaxS;
8224 -- Signed integer case
8226 if Is_Signed_Integer_Type (Typ) then
8228 -- Generate overflow check if overflow is active. Note that
8229 -- we can simply ignore the possibility of overflow if the
8230 -- flag is not set (means that overflow cannot happen or
8231 -- that overflow checks are suppressed).
8233 if Ovflo and TestS then
8234 Insert_Action (N,
8235 Make_Raise_Constraint_Error (Loc,
8236 Condition =>
8237 Make_Op_Gt (Loc,
8238 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8239 Right_Opnd => Make_Integer_Literal (Loc, MaxS)),
8240 Reason => CE_Overflow_Check_Failed));
8241 end if;
8243 -- Now rewrite node as Shift_Left (1, right-operand)
8245 Rewrite (N,
8246 Make_Op_Shift_Left (Loc,
8247 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8248 Right_Opnd => Right_Opnd (N)));
8250 -- Modular integer case
8252 else pragma Assert (Is_Modular_Integer_Type (Typ));
8254 -- If shift count can be greater than MaxS, we need to wrap
8255 -- the shift in a test that will reduce the result value to
8256 -- zero if this shift count is exceeded.
8258 if TestS then
8260 -- Note: build node for the comparison first, before we
8261 -- reuse the Right_Opnd, so that we have proper parents
8262 -- in place for the Duplicate_Subexpr call.
8264 Test_Gt :=
8265 Make_Op_Gt (Loc,
8266 Left_Opnd => Duplicate_Subexpr (Right_Opnd (N)),
8267 Right_Opnd => Make_Integer_Literal (Loc, MaxS));
8269 Rewrite (N,
8270 Make_If_Expression (Loc,
8271 Expressions => New_List (
8272 Test_Gt,
8273 Make_Integer_Literal (Loc, Uint_0),
8274 Make_Op_Shift_Left (Loc,
8275 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8276 Right_Opnd => Right_Opnd (N)))));
8278 -- If we know shift count cannot be greater than MaxS, then
8279 -- it is safe to just rewrite as a shift with no test.
8281 else
8282 Rewrite (N,
8283 Make_Op_Shift_Left (Loc,
8284 Left_Opnd => Make_Integer_Literal (Loc, Uint_1),
8285 Right_Opnd => Right_Opnd (N)));
8286 end if;
8287 end if;
8289 Analyze_And_Resolve (N, Typ);
8290 return;
8291 end;
8292 end if;
8293 end if;
8295 -- Fall through if exponentiation must be done using a runtime routine
8297 -- First deal with modular case
8299 if Is_Modular_Integer_Type (Rtyp) then
8301 -- Nonbinary modular case, we call the special exponentiation
8302 -- routine for the nonbinary case, converting the argument to
8303 -- Long_Long_Integer and passing the modulus value. Then the
8304 -- result is converted back to the base type.
8306 if Non_Binary_Modulus (Rtyp) then
8307 Rewrite (N,
8308 Convert_To (Typ,
8309 Make_Function_Call (Loc,
8310 Name =>
8311 New_Occurrence_Of (RTE (RE_Exp_Modular), Loc),
8312 Parameter_Associations => New_List (
8313 Convert_To (RTE (RE_Unsigned), Base),
8314 Make_Integer_Literal (Loc, Modulus (Rtyp)),
8315 Exp))));
8317 -- Binary modular case, in this case, we call one of two routines,
8318 -- either the unsigned integer case, or the unsigned long long
8319 -- integer case, with a final "and" operation to do the required mod.
8321 else
8322 if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
8323 Ent := RTE (RE_Exp_Unsigned);
8324 else
8325 Ent := RTE (RE_Exp_Long_Long_Unsigned);
8326 end if;
8328 Rewrite (N,
8329 Convert_To (Typ,
8330 Make_Op_And (Loc,
8331 Left_Opnd =>
8332 Make_Function_Call (Loc,
8333 Name => New_Occurrence_Of (Ent, Loc),
8334 Parameter_Associations => New_List (
8335 Convert_To (Etype (First_Formal (Ent)), Base),
8336 Exp)),
8337 Right_Opnd =>
8338 Make_Integer_Literal (Loc, Modulus (Rtyp) - 1))));
8340 end if;
8342 -- Common exit point for modular type case
8344 Analyze_And_Resolve (N, Typ);
8345 return;
8347 -- Signed integer cases, done using either Integer or Long_Long_Integer.
8348 -- It is not worth having routines for Short_[Short_]Integer, since for
8349 -- most machines it would not help, and it would generate more code that
8350 -- might need certification when a certified run time is required.
8352 -- In the integer cases, we have two routines, one for when overflow
8353 -- checks are required, and one when they are not required, since there
8354 -- is a real gain in omitting checks on many machines.
8356 elsif Rtyp = Base_Type (Standard_Long_Long_Integer)
8357 or else (Rtyp = Base_Type (Standard_Long_Integer)
8358 and then
8359 Esize (Standard_Long_Integer) > Esize (Standard_Integer))
8360 or else Rtyp = Universal_Integer
8361 then
8362 Etyp := Standard_Long_Long_Integer;
8364 if Ovflo then
8365 Rent := RE_Exp_Long_Long_Integer;
8366 else
8367 Rent := RE_Exn_Long_Long_Integer;
8368 end if;
8370 elsif Is_Signed_Integer_Type (Rtyp) then
8371 Etyp := Standard_Integer;
8373 if Ovflo then
8374 Rent := RE_Exp_Integer;
8375 else
8376 Rent := RE_Exn_Integer;
8377 end if;
8379 -- Floating-point cases. We do not need separate routines for the
8380 -- overflow case here, since in the case of floating-point, we generate
8381 -- infinities anyway as a rule (either that or we automatically trap
8382 -- overflow), and if there is an infinity generated and a range check
8383 -- is required, the check will fail anyway.
8385 -- Historical note: we used to convert everything to Long_Long_Float
8386 -- and call a single common routine, but this had the undesirable effect
8387 -- of giving different results for small static exponent values and the
8388 -- same dynamic values.
8390 else
8391 pragma Assert (Is_Floating_Point_Type (Rtyp));
8393 if Rtyp = Standard_Float then
8394 Etyp := Standard_Float;
8395 Rent := RE_Exn_Float;
8397 elsif Rtyp = Standard_Long_Float then
8398 Etyp := Standard_Long_Float;
8399 Rent := RE_Exn_Long_Float;
8401 else
8402 Etyp := Standard_Long_Long_Float;
8403 Rent := RE_Exn_Long_Long_Float;
8404 end if;
8405 end if;
8407 -- Common processing for integer cases and floating-point cases.
8408 -- If we are in the right type, we can call runtime routine directly
8410 if Typ = Etyp
8411 and then Rtyp /= Universal_Integer
8412 and then Rtyp /= Universal_Real
8413 then
8414 Rewrite (N,
8415 Wrap_MA (
8416 Make_Function_Call (Loc,
8417 Name => New_Occurrence_Of (RTE (Rent), Loc),
8418 Parameter_Associations => New_List (Base, Exp))));
8420 -- Otherwise we have to introduce conversions (conversions are also
8421 -- required in the universal cases, since the runtime routine is
8422 -- typed using one of the standard types).
8424 else
8425 Rewrite (N,
8426 Convert_To (Typ,
8427 Make_Function_Call (Loc,
8428 Name => New_Occurrence_Of (RTE (Rent), Loc),
8429 Parameter_Associations => New_List (
8430 Convert_To (Etyp, Base),
8431 Exp))));
8432 end if;
8434 Analyze_And_Resolve (N, Typ);
8435 return;
8437 exception
8438 when RE_Not_Available =>
8439 return;
8440 end Expand_N_Op_Expon;
8442 --------------------
8443 -- Expand_N_Op_Ge --
8444 --------------------
8446 procedure Expand_N_Op_Ge (N : Node_Id) is
8447 Typ : constant Entity_Id := Etype (N);
8448 Op1 : constant Node_Id := Left_Opnd (N);
8449 Op2 : constant Node_Id := Right_Opnd (N);
8450 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8452 begin
8453 Binary_Op_Validity_Checks (N);
8455 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8456 -- means we no longer have a comparison operation, we are all done.
8458 Expand_Compare_Minimize_Eliminate_Overflow (N);
8460 if Nkind (N) /= N_Op_Ge then
8461 return;
8462 end if;
8464 -- Array type case
8466 if Is_Array_Type (Typ1) then
8467 Expand_Array_Comparison (N);
8468 return;
8469 end if;
8471 -- Deal with boolean operands
8473 if Is_Boolean_Type (Typ1) then
8474 Adjust_Condition (Op1);
8475 Adjust_Condition (Op2);
8476 Set_Etype (N, Standard_Boolean);
8477 Adjust_Result_Type (N, Typ);
8478 end if;
8480 Rewrite_Comparison (N);
8482 Optimize_Length_Comparison (N);
8483 end Expand_N_Op_Ge;
8485 --------------------
8486 -- Expand_N_Op_Gt --
8487 --------------------
8489 procedure Expand_N_Op_Gt (N : Node_Id) is
8490 Typ : constant Entity_Id := Etype (N);
8491 Op1 : constant Node_Id := Left_Opnd (N);
8492 Op2 : constant Node_Id := Right_Opnd (N);
8493 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8495 begin
8496 Binary_Op_Validity_Checks (N);
8498 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8499 -- means we no longer have a comparison operation, we are all done.
8501 Expand_Compare_Minimize_Eliminate_Overflow (N);
8503 if Nkind (N) /= N_Op_Gt then
8504 return;
8505 end if;
8507 -- Deal with array type operands
8509 if Is_Array_Type (Typ1) then
8510 Expand_Array_Comparison (N);
8511 return;
8512 end if;
8514 -- Deal with boolean type operands
8516 if Is_Boolean_Type (Typ1) then
8517 Adjust_Condition (Op1);
8518 Adjust_Condition (Op2);
8519 Set_Etype (N, Standard_Boolean);
8520 Adjust_Result_Type (N, Typ);
8521 end if;
8523 Rewrite_Comparison (N);
8525 Optimize_Length_Comparison (N);
8526 end Expand_N_Op_Gt;
8528 --------------------
8529 -- Expand_N_Op_Le --
8530 --------------------
8532 procedure Expand_N_Op_Le (N : Node_Id) is
8533 Typ : constant Entity_Id := Etype (N);
8534 Op1 : constant Node_Id := Left_Opnd (N);
8535 Op2 : constant Node_Id := Right_Opnd (N);
8536 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8538 begin
8539 Binary_Op_Validity_Checks (N);
8541 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8542 -- means we no longer have a comparison operation, we are all done.
8544 Expand_Compare_Minimize_Eliminate_Overflow (N);
8546 if Nkind (N) /= N_Op_Le then
8547 return;
8548 end if;
8550 -- Deal with array type operands
8552 if Is_Array_Type (Typ1) then
8553 Expand_Array_Comparison (N);
8554 return;
8555 end if;
8557 -- Deal with Boolean type operands
8559 if Is_Boolean_Type (Typ1) then
8560 Adjust_Condition (Op1);
8561 Adjust_Condition (Op2);
8562 Set_Etype (N, Standard_Boolean);
8563 Adjust_Result_Type (N, Typ);
8564 end if;
8566 Rewrite_Comparison (N);
8568 Optimize_Length_Comparison (N);
8569 end Expand_N_Op_Le;
8571 --------------------
8572 -- Expand_N_Op_Lt --
8573 --------------------
8575 procedure Expand_N_Op_Lt (N : Node_Id) is
8576 Typ : constant Entity_Id := Etype (N);
8577 Op1 : constant Node_Id := Left_Opnd (N);
8578 Op2 : constant Node_Id := Right_Opnd (N);
8579 Typ1 : constant Entity_Id := Base_Type (Etype (Op1));
8581 begin
8582 Binary_Op_Validity_Checks (N);
8584 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if that
8585 -- means we no longer have a comparison operation, we are all done.
8587 Expand_Compare_Minimize_Eliminate_Overflow (N);
8589 if Nkind (N) /= N_Op_Lt then
8590 return;
8591 end if;
8593 -- Deal with array type operands
8595 if Is_Array_Type (Typ1) then
8596 Expand_Array_Comparison (N);
8597 return;
8598 end if;
8600 -- Deal with Boolean type operands
8602 if Is_Boolean_Type (Typ1) then
8603 Adjust_Condition (Op1);
8604 Adjust_Condition (Op2);
8605 Set_Etype (N, Standard_Boolean);
8606 Adjust_Result_Type (N, Typ);
8607 end if;
8609 Rewrite_Comparison (N);
8611 Optimize_Length_Comparison (N);
8612 end Expand_N_Op_Lt;
8614 -----------------------
8615 -- Expand_N_Op_Minus --
8616 -----------------------
8618 procedure Expand_N_Op_Minus (N : Node_Id) is
8619 Loc : constant Source_Ptr := Sloc (N);
8620 Typ : constant Entity_Id := Etype (N);
8622 begin
8623 Unary_Op_Validity_Checks (N);
8625 -- Check for MINIMIZED/ELIMINATED overflow mode
8627 if Minimized_Eliminated_Overflow_Check (N) then
8628 Apply_Arithmetic_Overflow_Check (N);
8629 return;
8630 end if;
8632 if not Backend_Overflow_Checks_On_Target
8633 and then Is_Signed_Integer_Type (Etype (N))
8634 and then Do_Overflow_Check (N)
8635 then
8636 -- Software overflow checking expands -expr into (0 - expr)
8638 Rewrite (N,
8639 Make_Op_Subtract (Loc,
8640 Left_Opnd => Make_Integer_Literal (Loc, 0),
8641 Right_Opnd => Right_Opnd (N)));
8643 Analyze_And_Resolve (N, Typ);
8644 end if;
8646 -- Generating C code convert non-binary modular minus into code that
8647 -- relies on the frontend expansion of operator Mod.
8649 if Modify_Tree_For_C then
8650 Expand_Non_Binary_Modular_Op (N);
8651 end if;
8652 end Expand_N_Op_Minus;
8654 ---------------------
8655 -- Expand_N_Op_Mod --
8656 ---------------------
8658 procedure Expand_N_Op_Mod (N : Node_Id) is
8659 Loc : constant Source_Ptr := Sloc (N);
8660 Typ : constant Entity_Id := Etype (N);
8661 DDC : constant Boolean := Do_Division_Check (N);
8663 Left : Node_Id;
8664 Right : Node_Id;
8666 LLB : Uint;
8667 Llo : Uint;
8668 Lhi : Uint;
8669 LOK : Boolean;
8670 Rlo : Uint;
8671 Rhi : Uint;
8672 ROK : Boolean;
8674 pragma Warnings (Off, Lhi);
8676 begin
8677 Binary_Op_Validity_Checks (N);
8679 -- Check for MINIMIZED/ELIMINATED overflow mode
8681 if Minimized_Eliminated_Overflow_Check (N) then
8682 Apply_Arithmetic_Overflow_Check (N);
8683 return;
8684 end if;
8686 if Is_Integer_Type (Etype (N)) then
8687 Apply_Divide_Checks (N);
8689 -- All done if we don't have a MOD any more, which can happen as a
8690 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
8692 if Nkind (N) /= N_Op_Mod then
8693 return;
8694 end if;
8695 end if;
8697 -- Proceed with expansion of mod operator
8699 Left := Left_Opnd (N);
8700 Right := Right_Opnd (N);
8702 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
8703 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
8705 -- Convert mod to rem if operands are both known to be non-negative, or
8706 -- both known to be non-positive (these are the cases in which rem and
8707 -- mod are the same, see (RM 4.5.5(28-30)). We do this since it is quite
8708 -- likely that this will improve the quality of code, (the operation now
8709 -- corresponds to the hardware remainder), and it does not seem likely
8710 -- that it could be harmful. It also avoids some cases of the elaborate
8711 -- expansion in Modify_Tree_For_C mode below (since Ada rem = C %).
8713 if (LOK and ROK)
8714 and then ((Llo >= 0 and then Rlo >= 0)
8715 or else
8716 (Lhi <= 0 and then Rhi <= 0))
8717 then
8718 Rewrite (N,
8719 Make_Op_Rem (Sloc (N),
8720 Left_Opnd => Left_Opnd (N),
8721 Right_Opnd => Right_Opnd (N)));
8723 -- Instead of reanalyzing the node we do the analysis manually. This
8724 -- avoids anomalies when the replacement is done in an instance and
8725 -- is epsilon more efficient.
8727 Set_Entity (N, Standard_Entity (S_Op_Rem));
8728 Set_Etype (N, Typ);
8729 Set_Do_Division_Check (N, DDC);
8730 Expand_N_Op_Rem (N);
8731 Set_Analyzed (N);
8732 return;
8734 -- Otherwise, normal mod processing
8736 else
8737 -- Apply optimization x mod 1 = 0. We don't really need that with
8738 -- gcc, but it is useful with other back ends and is certainly
8739 -- harmless.
8741 if Is_Integer_Type (Etype (N))
8742 and then Compile_Time_Known_Value (Right)
8743 and then Expr_Value (Right) = Uint_1
8744 then
8745 -- Call Remove_Side_Effects to ensure that any side effects in
8746 -- the ignored left operand (in particular function calls to
8747 -- user defined functions) are properly executed.
8749 Remove_Side_Effects (Left);
8751 Rewrite (N, Make_Integer_Literal (Loc, 0));
8752 Analyze_And_Resolve (N, Typ);
8753 return;
8754 end if;
8756 -- If we still have a mod operator and we are in Modify_Tree_For_C
8757 -- mode, and we have a signed integer type, then here is where we do
8758 -- the rewrite in terms of Rem. Note this rewrite bypasses the need
8759 -- for the special handling of the annoying case of largest negative
8760 -- number mod minus one.
8762 if Nkind (N) = N_Op_Mod
8763 and then Is_Signed_Integer_Type (Typ)
8764 and then Modify_Tree_For_C
8765 then
8766 -- In the general case, we expand A mod B as
8768 -- Tnn : constant typ := A rem B;
8769 -- ..
8770 -- (if (A >= 0) = (B >= 0) then Tnn
8771 -- elsif Tnn = 0 then 0
8772 -- else Tnn + B)
8774 -- The comparison can be written simply as A >= 0 if we know that
8775 -- B >= 0 which is a very common case.
8777 -- An important optimization is when B is known at compile time
8778 -- to be 2**K for some constant. In this case we can simply AND
8779 -- the left operand with the bit string 2**K-1 (i.e. K 1-bits)
8780 -- and that works for both the positive and negative cases.
8782 declare
8783 P2 : constant Nat := Power_Of_Two (Right);
8785 begin
8786 if P2 /= 0 then
8787 Rewrite (N,
8788 Unchecked_Convert_To (Typ,
8789 Make_Op_And (Loc,
8790 Left_Opnd =>
8791 Unchecked_Convert_To
8792 (Corresponding_Unsigned_Type (Typ), Left),
8793 Right_Opnd =>
8794 Make_Integer_Literal (Loc, 2 ** P2 - 1))));
8795 Analyze_And_Resolve (N, Typ);
8796 return;
8797 end if;
8798 end;
8800 -- Here for the full rewrite
8802 declare
8803 Tnn : constant Entity_Id := Make_Temporary (Sloc (N), 'T', N);
8804 Cmp : Node_Id;
8806 begin
8807 Cmp :=
8808 Make_Op_Ge (Loc,
8809 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
8810 Right_Opnd => Make_Integer_Literal (Loc, 0));
8812 if not LOK or else Rlo < 0 then
8813 Cmp :=
8814 Make_Op_Eq (Loc,
8815 Left_Opnd => Cmp,
8816 Right_Opnd =>
8817 Make_Op_Ge (Loc,
8818 Left_Opnd => Duplicate_Subexpr_No_Checks (Right),
8819 Right_Opnd => Make_Integer_Literal (Loc, 0)));
8820 end if;
8822 Insert_Action (N,
8823 Make_Object_Declaration (Loc,
8824 Defining_Identifier => Tnn,
8825 Constant_Present => True,
8826 Object_Definition => New_Occurrence_Of (Typ, Loc),
8827 Expression =>
8828 Make_Op_Rem (Loc,
8829 Left_Opnd => Left,
8830 Right_Opnd => Right)));
8832 Rewrite (N,
8833 Make_If_Expression (Loc,
8834 Expressions => New_List (
8835 Cmp,
8836 New_Occurrence_Of (Tnn, Loc),
8837 Make_If_Expression (Loc,
8838 Is_Elsif => True,
8839 Expressions => New_List (
8840 Make_Op_Eq (Loc,
8841 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8842 Right_Opnd => Make_Integer_Literal (Loc, 0)),
8843 Make_Integer_Literal (Loc, 0),
8844 Make_Op_Add (Loc,
8845 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
8846 Right_Opnd =>
8847 Duplicate_Subexpr_No_Checks (Right)))))));
8849 Analyze_And_Resolve (N, Typ);
8850 return;
8851 end;
8852 end if;
8854 -- Deal with annoying case of largest negative number mod minus one.
8855 -- Gigi may not handle this case correctly, because on some targets,
8856 -- the mod value is computed using a divide instruction which gives
8857 -- an overflow trap for this case.
8859 -- It would be a bit more efficient to figure out which targets
8860 -- this is really needed for, but in practice it is reasonable
8861 -- to do the following special check in all cases, since it means
8862 -- we get a clearer message, and also the overhead is minimal given
8863 -- that division is expensive in any case.
8865 -- In fact the check is quite easy, if the right operand is -1, then
8866 -- the mod value is always 0, and we can just ignore the left operand
8867 -- completely in this case.
8869 -- This only applies if we still have a mod operator. Skip if we
8870 -- have already rewritten this (e.g. in the case of eliminated
8871 -- overflow checks which have driven us into bignum mode).
8873 if Nkind (N) = N_Op_Mod then
8875 -- The operand type may be private (e.g. in the expansion of an
8876 -- intrinsic operation) so we must use the underlying type to get
8877 -- the bounds, and convert the literals explicitly.
8879 LLB :=
8880 Expr_Value
8881 (Type_Low_Bound (Base_Type (Underlying_Type (Etype (Left)))));
8883 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
8884 and then ((not LOK) or else (Llo = LLB))
8885 then
8886 Rewrite (N,
8887 Make_If_Expression (Loc,
8888 Expressions => New_List (
8889 Make_Op_Eq (Loc,
8890 Left_Opnd => Duplicate_Subexpr (Right),
8891 Right_Opnd =>
8892 Unchecked_Convert_To (Typ,
8893 Make_Integer_Literal (Loc, -1))),
8894 Unchecked_Convert_To (Typ,
8895 Make_Integer_Literal (Loc, Uint_0)),
8896 Relocate_Node (N))));
8898 Set_Analyzed (Next (Next (First (Expressions (N)))));
8899 Analyze_And_Resolve (N, Typ);
8900 end if;
8901 end if;
8902 end if;
8903 end Expand_N_Op_Mod;
8905 --------------------------
8906 -- Expand_N_Op_Multiply --
8907 --------------------------
8909 procedure Expand_N_Op_Multiply (N : Node_Id) is
8910 Loc : constant Source_Ptr := Sloc (N);
8911 Lop : constant Node_Id := Left_Opnd (N);
8912 Rop : constant Node_Id := Right_Opnd (N);
8914 Lp2 : constant Boolean :=
8915 Nkind (Lop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Lop);
8916 Rp2 : constant Boolean :=
8917 Nkind (Rop) = N_Op_Expon and then Is_Power_Of_2_For_Shift (Rop);
8919 Ltyp : constant Entity_Id := Etype (Lop);
8920 Rtyp : constant Entity_Id := Etype (Rop);
8921 Typ : Entity_Id := Etype (N);
8923 begin
8924 Binary_Op_Validity_Checks (N);
8926 -- Check for MINIMIZED/ELIMINATED overflow mode
8928 if Minimized_Eliminated_Overflow_Check (N) then
8929 Apply_Arithmetic_Overflow_Check (N);
8930 return;
8931 end if;
8933 -- Special optimizations for integer types
8935 if Is_Integer_Type (Typ) then
8937 -- N * 0 = 0 for integer types
8939 if Compile_Time_Known_Value (Rop)
8940 and then Expr_Value (Rop) = Uint_0
8941 then
8942 -- Call Remove_Side_Effects to ensure that any side effects in
8943 -- the ignored left operand (in particular function calls to
8944 -- user defined functions) are properly executed.
8946 Remove_Side_Effects (Lop);
8948 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
8949 Analyze_And_Resolve (N, Typ);
8950 return;
8951 end if;
8953 -- Similar handling for 0 * N = 0
8955 if Compile_Time_Known_Value (Lop)
8956 and then Expr_Value (Lop) = Uint_0
8957 then
8958 Remove_Side_Effects (Rop);
8959 Rewrite (N, Make_Integer_Literal (Loc, Uint_0));
8960 Analyze_And_Resolve (N, Typ);
8961 return;
8962 end if;
8964 -- N * 1 = 1 * N = N for integer types
8966 -- This optimisation is not done if we are going to
8967 -- rewrite the product 1 * 2 ** N to a shift.
8969 if Compile_Time_Known_Value (Rop)
8970 and then Expr_Value (Rop) = Uint_1
8971 and then not Lp2
8972 then
8973 Rewrite (N, Lop);
8974 return;
8976 elsif Compile_Time_Known_Value (Lop)
8977 and then Expr_Value (Lop) = Uint_1
8978 and then not Rp2
8979 then
8980 Rewrite (N, Rop);
8981 return;
8982 end if;
8983 end if;
8985 -- Convert x * 2 ** y to Shift_Left (x, y). Note that the fact that
8986 -- Is_Power_Of_2_For_Shift is set means that we know that our left
8987 -- operand is an integer, as required for this to work.
8989 if Rp2 then
8990 if Lp2 then
8992 -- Convert 2 ** A * 2 ** B into 2 ** (A + B)
8994 Rewrite (N,
8995 Make_Op_Expon (Loc,
8996 Left_Opnd => Make_Integer_Literal (Loc, 2),
8997 Right_Opnd =>
8998 Make_Op_Add (Loc,
8999 Left_Opnd => Right_Opnd (Lop),
9000 Right_Opnd => Right_Opnd (Rop))));
9001 Analyze_And_Resolve (N, Typ);
9002 return;
9004 else
9005 -- If the result is modular, perform the reduction of the result
9006 -- appropriately.
9008 if Is_Modular_Integer_Type (Typ)
9009 and then not Non_Binary_Modulus (Typ)
9010 then
9011 Rewrite (N,
9012 Make_Op_And (Loc,
9013 Left_Opnd =>
9014 Make_Op_Shift_Left (Loc,
9015 Left_Opnd => Lop,
9016 Right_Opnd =>
9017 Convert_To (Standard_Natural, Right_Opnd (Rop))),
9018 Right_Opnd =>
9019 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9021 else
9022 Rewrite (N,
9023 Make_Op_Shift_Left (Loc,
9024 Left_Opnd => Lop,
9025 Right_Opnd =>
9026 Convert_To (Standard_Natural, Right_Opnd (Rop))));
9027 end if;
9029 Analyze_And_Resolve (N, Typ);
9030 return;
9031 end if;
9033 -- Same processing for the operands the other way round
9035 elsif Lp2 then
9036 if Is_Modular_Integer_Type (Typ)
9037 and then not Non_Binary_Modulus (Typ)
9038 then
9039 Rewrite (N,
9040 Make_Op_And (Loc,
9041 Left_Opnd =>
9042 Make_Op_Shift_Left (Loc,
9043 Left_Opnd => Rop,
9044 Right_Opnd =>
9045 Convert_To (Standard_Natural, Right_Opnd (Lop))),
9046 Right_Opnd =>
9047 Make_Integer_Literal (Loc, Modulus (Typ) - 1)));
9049 else
9050 Rewrite (N,
9051 Make_Op_Shift_Left (Loc,
9052 Left_Opnd => Rop,
9053 Right_Opnd =>
9054 Convert_To (Standard_Natural, Right_Opnd (Lop))));
9055 end if;
9057 Analyze_And_Resolve (N, Typ);
9058 return;
9059 end if;
9061 -- Do required fixup of universal fixed operation
9063 if Typ = Universal_Fixed then
9064 Fixup_Universal_Fixed_Operation (N);
9065 Typ := Etype (N);
9066 end if;
9068 -- Multiplications with fixed-point results
9070 if Is_Fixed_Point_Type (Typ) then
9072 -- No special processing if Treat_Fixed_As_Integer is set, since from
9073 -- a semantic point of view such operations are simply integer
9074 -- operations and will be treated that way.
9076 if not Treat_Fixed_As_Integer (N) then
9078 -- Case of fixed * integer => fixed
9080 if Is_Integer_Type (Rtyp) then
9081 Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N);
9083 -- Case of integer * fixed => fixed
9085 elsif Is_Integer_Type (Ltyp) then
9086 Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N);
9088 -- Case of fixed * fixed => fixed
9090 else
9091 Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N);
9092 end if;
9093 end if;
9095 -- Other cases of multiplication of fixed-point operands. Again we
9096 -- exclude the cases where Treat_Fixed_As_Integer flag is set.
9098 elsif (Is_Fixed_Point_Type (Ltyp) or else Is_Fixed_Point_Type (Rtyp))
9099 and then not Treat_Fixed_As_Integer (N)
9100 then
9101 if Is_Integer_Type (Typ) then
9102 Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N);
9103 else
9104 pragma Assert (Is_Floating_Point_Type (Typ));
9105 Expand_Multiply_Fixed_By_Fixed_Giving_Float (N);
9106 end if;
9108 -- Mixed-mode operations can appear in a non-static universal context,
9109 -- in which case the integer argument must be converted explicitly.
9111 elsif Typ = Universal_Real and then Is_Integer_Type (Rtyp) then
9112 Rewrite (Rop, Convert_To (Universal_Real, Relocate_Node (Rop)));
9113 Analyze_And_Resolve (Rop, Universal_Real);
9115 elsif Typ = Universal_Real and then Is_Integer_Type (Ltyp) then
9116 Rewrite (Lop, Convert_To (Universal_Real, Relocate_Node (Lop)));
9117 Analyze_And_Resolve (Lop, Universal_Real);
9119 -- Non-fixed point cases, check software overflow checking required
9121 elsif Is_Signed_Integer_Type (Etype (N)) then
9122 Apply_Arithmetic_Overflow_Check (N);
9123 end if;
9125 -- Overflow checks for floating-point if -gnateF mode active
9127 Check_Float_Op_Overflow (N);
9129 -- Generating C code convert non-binary modular multiplications into
9130 -- code that relies on the frontend expansion of operator Mod.
9132 if Modify_Tree_For_C then
9133 Expand_Non_Binary_Modular_Op (N);
9134 end if;
9135 end Expand_N_Op_Multiply;
9137 --------------------
9138 -- Expand_N_Op_Ne --
9139 --------------------
9141 procedure Expand_N_Op_Ne (N : Node_Id) is
9142 Typ : constant Entity_Id := Etype (Left_Opnd (N));
9144 begin
9145 -- Case of elementary type with standard operator
9147 if Is_Elementary_Type (Typ)
9148 and then Sloc (Entity (N)) = Standard_Location
9149 then
9150 Binary_Op_Validity_Checks (N);
9152 -- Deal with overflow checks in MINIMIZED/ELIMINATED mode and if
9153 -- means we no longer have a /= operation, we are all done.
9155 Expand_Compare_Minimize_Eliminate_Overflow (N);
9157 if Nkind (N) /= N_Op_Ne then
9158 return;
9159 end if;
9161 -- Boolean types (requiring handling of non-standard case)
9163 if Is_Boolean_Type (Typ) then
9164 Adjust_Condition (Left_Opnd (N));
9165 Adjust_Condition (Right_Opnd (N));
9166 Set_Etype (N, Standard_Boolean);
9167 Adjust_Result_Type (N, Typ);
9168 end if;
9170 Rewrite_Comparison (N);
9172 -- For all cases other than elementary types, we rewrite node as the
9173 -- negation of an equality operation, and reanalyze. The equality to be
9174 -- used is defined in the same scope and has the same signature. This
9175 -- signature must be set explicitly since in an instance it may not have
9176 -- the same visibility as in the generic unit. This avoids duplicating
9177 -- or factoring the complex code for record/array equality tests etc.
9179 -- This case is also used for the minimal expansion performed in
9180 -- GNATprove mode.
9182 else
9183 declare
9184 Loc : constant Source_Ptr := Sloc (N);
9185 Neg : Node_Id;
9186 Ne : constant Entity_Id := Entity (N);
9188 begin
9189 Binary_Op_Validity_Checks (N);
9191 Neg :=
9192 Make_Op_Not (Loc,
9193 Right_Opnd =>
9194 Make_Op_Eq (Loc,
9195 Left_Opnd => Left_Opnd (N),
9196 Right_Opnd => Right_Opnd (N)));
9198 -- The level of parentheses is useless in GNATprove mode, and
9199 -- bumping its level here leads to wrong columns being used in
9200 -- check messages, hence skip it in this mode.
9202 if not GNATprove_Mode then
9203 Set_Paren_Count (Right_Opnd (Neg), 1);
9204 end if;
9206 if Scope (Ne) /= Standard_Standard then
9207 Set_Entity (Right_Opnd (Neg), Corresponding_Equality (Ne));
9208 end if;
9210 -- For navigation purposes, we want to treat the inequality as an
9211 -- implicit reference to the corresponding equality. Preserve the
9212 -- Comes_From_ source flag to generate proper Xref entries.
9214 Preserve_Comes_From_Source (Neg, N);
9215 Preserve_Comes_From_Source (Right_Opnd (Neg), N);
9216 Rewrite (N, Neg);
9217 Analyze_And_Resolve (N, Standard_Boolean);
9218 end;
9219 end if;
9221 -- No need for optimization in GNATprove mode, where we would rather see
9222 -- the original source expression.
9224 if not GNATprove_Mode then
9225 Optimize_Length_Comparison (N);
9226 end if;
9227 end Expand_N_Op_Ne;
9229 ---------------------
9230 -- Expand_N_Op_Not --
9231 ---------------------
9233 -- If the argument is other than a Boolean array type, there is no special
9234 -- expansion required, except for dealing with validity checks, and non-
9235 -- standard boolean representations.
9237 -- For the packed array case, we call the special routine in Exp_Pakd,
9238 -- except that if the component size is greater than one, we use the
9239 -- standard routine generating a gruesome loop (it is so peculiar to have
9240 -- packed arrays with non-standard Boolean representations anyway, so it
9241 -- does not matter that we do not handle this case efficiently).
9243 -- For the unpacked array case (and for the special packed case where we
9244 -- have non standard Booleans, as discussed above), we generate and insert
9245 -- into the tree the following function definition:
9247 -- function Nnnn (A : arr) is
9248 -- B : arr;
9249 -- begin
9250 -- for J in a'range loop
9251 -- B (J) := not A (J);
9252 -- end loop;
9253 -- return B;
9254 -- end Nnnn;
9256 -- Here arr is the actual subtype of the parameter (and hence always
9257 -- constrained). Then we replace the not with a call to this function.
9259 procedure Expand_N_Op_Not (N : Node_Id) is
9260 Loc : constant Source_Ptr := Sloc (N);
9261 Typ : constant Entity_Id := Etype (N);
9262 Opnd : Node_Id;
9263 Arr : Entity_Id;
9264 A : Entity_Id;
9265 B : Entity_Id;
9266 J : Entity_Id;
9267 A_J : Node_Id;
9268 B_J : Node_Id;
9270 Func_Name : Entity_Id;
9271 Loop_Statement : Node_Id;
9273 begin
9274 Unary_Op_Validity_Checks (N);
9276 -- For boolean operand, deal with non-standard booleans
9278 if Is_Boolean_Type (Typ) then
9279 Adjust_Condition (Right_Opnd (N));
9280 Set_Etype (N, Standard_Boolean);
9281 Adjust_Result_Type (N, Typ);
9282 return;
9283 end if;
9285 -- Only array types need any other processing
9287 if not Is_Array_Type (Typ) then
9288 return;
9289 end if;
9291 -- Case of array operand. If bit packed with a component size of 1,
9292 -- handle it in Exp_Pakd if the operand is known to be aligned.
9294 if Is_Bit_Packed_Array (Typ)
9295 and then Component_Size (Typ) = 1
9296 and then not Is_Possibly_Unaligned_Object (Right_Opnd (N))
9297 then
9298 Expand_Packed_Not (N);
9299 return;
9300 end if;
9302 -- Case of array operand which is not bit-packed. If the context is
9303 -- a safe assignment, call in-place operation, If context is a larger
9304 -- boolean expression in the context of a safe assignment, expansion is
9305 -- done by enclosing operation.
9307 Opnd := Relocate_Node (Right_Opnd (N));
9308 Convert_To_Actual_Subtype (Opnd);
9309 Arr := Etype (Opnd);
9310 Ensure_Defined (Arr, N);
9311 Silly_Boolean_Array_Not_Test (N, Arr);
9313 if Nkind (Parent (N)) = N_Assignment_Statement then
9314 if Safe_In_Place_Array_Op (Name (Parent (N)), N, Empty) then
9315 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9316 return;
9318 -- Special case the negation of a binary operation
9320 elsif Nkind_In (Opnd, N_Op_And, N_Op_Or, N_Op_Xor)
9321 and then Safe_In_Place_Array_Op
9322 (Name (Parent (N)), Left_Opnd (Opnd), Right_Opnd (Opnd))
9323 then
9324 Build_Boolean_Array_Proc_Call (Parent (N), Opnd, Empty);
9325 return;
9326 end if;
9328 elsif Nkind (Parent (N)) in N_Binary_Op
9329 and then Nkind (Parent (Parent (N))) = N_Assignment_Statement
9330 then
9331 declare
9332 Op1 : constant Node_Id := Left_Opnd (Parent (N));
9333 Op2 : constant Node_Id := Right_Opnd (Parent (N));
9334 Lhs : constant Node_Id := Name (Parent (Parent (N)));
9336 begin
9337 if Safe_In_Place_Array_Op (Lhs, Op1, Op2) then
9339 -- (not A) op (not B) can be reduced to a single call
9341 if N = Op1 and then Nkind (Op2) = N_Op_Not then
9342 return;
9344 elsif N = Op2 and then Nkind (Op1) = N_Op_Not then
9345 return;
9347 -- A xor (not B) can also be special-cased
9349 elsif N = Op2 and then Nkind (Parent (N)) = N_Op_Xor then
9350 return;
9351 end if;
9352 end if;
9353 end;
9354 end if;
9356 A := Make_Defining_Identifier (Loc, Name_uA);
9357 B := Make_Defining_Identifier (Loc, Name_uB);
9358 J := Make_Defining_Identifier (Loc, Name_uJ);
9360 A_J :=
9361 Make_Indexed_Component (Loc,
9362 Prefix => New_Occurrence_Of (A, Loc),
9363 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9365 B_J :=
9366 Make_Indexed_Component (Loc,
9367 Prefix => New_Occurrence_Of (B, Loc),
9368 Expressions => New_List (New_Occurrence_Of (J, Loc)));
9370 Loop_Statement :=
9371 Make_Implicit_Loop_Statement (N,
9372 Identifier => Empty,
9374 Iteration_Scheme =>
9375 Make_Iteration_Scheme (Loc,
9376 Loop_Parameter_Specification =>
9377 Make_Loop_Parameter_Specification (Loc,
9378 Defining_Identifier => J,
9379 Discrete_Subtype_Definition =>
9380 Make_Attribute_Reference (Loc,
9381 Prefix => Make_Identifier (Loc, Chars (A)),
9382 Attribute_Name => Name_Range))),
9384 Statements => New_List (
9385 Make_Assignment_Statement (Loc,
9386 Name => B_J,
9387 Expression => Make_Op_Not (Loc, A_J))));
9389 Func_Name := Make_Temporary (Loc, 'N');
9390 Set_Is_Inlined (Func_Name);
9392 Insert_Action (N,
9393 Make_Subprogram_Body (Loc,
9394 Specification =>
9395 Make_Function_Specification (Loc,
9396 Defining_Unit_Name => Func_Name,
9397 Parameter_Specifications => New_List (
9398 Make_Parameter_Specification (Loc,
9399 Defining_Identifier => A,
9400 Parameter_Type => New_Occurrence_Of (Typ, Loc))),
9401 Result_Definition => New_Occurrence_Of (Typ, Loc)),
9403 Declarations => New_List (
9404 Make_Object_Declaration (Loc,
9405 Defining_Identifier => B,
9406 Object_Definition => New_Occurrence_Of (Arr, Loc))),
9408 Handled_Statement_Sequence =>
9409 Make_Handled_Sequence_Of_Statements (Loc,
9410 Statements => New_List (
9411 Loop_Statement,
9412 Make_Simple_Return_Statement (Loc,
9413 Expression => Make_Identifier (Loc, Chars (B)))))));
9415 Rewrite (N,
9416 Make_Function_Call (Loc,
9417 Name => New_Occurrence_Of (Func_Name, Loc),
9418 Parameter_Associations => New_List (Opnd)));
9420 Analyze_And_Resolve (N, Typ);
9421 end Expand_N_Op_Not;
9423 --------------------
9424 -- Expand_N_Op_Or --
9425 --------------------
9427 procedure Expand_N_Op_Or (N : Node_Id) is
9428 Typ : constant Entity_Id := Etype (N);
9430 begin
9431 Binary_Op_Validity_Checks (N);
9433 if Is_Array_Type (Etype (N)) then
9434 Expand_Boolean_Operator (N);
9436 elsif Is_Boolean_Type (Etype (N)) then
9437 Adjust_Condition (Left_Opnd (N));
9438 Adjust_Condition (Right_Opnd (N));
9439 Set_Etype (N, Standard_Boolean);
9440 Adjust_Result_Type (N, Typ);
9442 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9443 Expand_Intrinsic_Call (N, Entity (N));
9444 end if;
9446 -- Generating C code convert non-binary modular operators into code that
9447 -- relies on the frontend expansion of operator Mod.
9449 if Modify_Tree_For_C then
9450 Expand_Non_Binary_Modular_Op (N);
9451 end if;
9452 end Expand_N_Op_Or;
9454 ----------------------
9455 -- Expand_N_Op_Plus --
9456 ----------------------
9458 procedure Expand_N_Op_Plus (N : Node_Id) is
9459 begin
9460 Unary_Op_Validity_Checks (N);
9462 -- Check for MINIMIZED/ELIMINATED overflow mode
9464 if Minimized_Eliminated_Overflow_Check (N) then
9465 Apply_Arithmetic_Overflow_Check (N);
9466 return;
9467 end if;
9468 end Expand_N_Op_Plus;
9470 ---------------------
9471 -- Expand_N_Op_Rem --
9472 ---------------------
9474 procedure Expand_N_Op_Rem (N : Node_Id) is
9475 Loc : constant Source_Ptr := Sloc (N);
9476 Typ : constant Entity_Id := Etype (N);
9478 Left : Node_Id;
9479 Right : Node_Id;
9481 Lo : Uint;
9482 Hi : Uint;
9483 OK : Boolean;
9485 Lneg : Boolean;
9486 Rneg : Boolean;
9487 -- Set if corresponding operand can be negative
9489 pragma Unreferenced (Hi);
9491 begin
9492 Binary_Op_Validity_Checks (N);
9494 -- Check for MINIMIZED/ELIMINATED overflow mode
9496 if Minimized_Eliminated_Overflow_Check (N) then
9497 Apply_Arithmetic_Overflow_Check (N);
9498 return;
9499 end if;
9501 if Is_Integer_Type (Etype (N)) then
9502 Apply_Divide_Checks (N);
9504 -- All done if we don't have a REM any more, which can happen as a
9505 -- result of overflow expansion in MINIMIZED or ELIMINATED modes.
9507 if Nkind (N) /= N_Op_Rem then
9508 return;
9509 end if;
9510 end if;
9512 -- Proceed with expansion of REM
9514 Left := Left_Opnd (N);
9515 Right := Right_Opnd (N);
9517 -- Apply optimization x rem 1 = 0. We don't really need that with gcc,
9518 -- but it is useful with other back ends, and is certainly harmless.
9520 if Is_Integer_Type (Etype (N))
9521 and then Compile_Time_Known_Value (Right)
9522 and then Expr_Value (Right) = Uint_1
9523 then
9524 -- Call Remove_Side_Effects to ensure that any side effects in the
9525 -- ignored left operand (in particular function calls to user defined
9526 -- functions) are properly executed.
9528 Remove_Side_Effects (Left);
9530 Rewrite (N, Make_Integer_Literal (Loc, 0));
9531 Analyze_And_Resolve (N, Typ);
9532 return;
9533 end if;
9535 -- Deal with annoying case of largest negative number remainder minus
9536 -- one. Gigi may not handle this case correctly, because on some
9537 -- targets, the mod value is computed using a divide instruction
9538 -- which gives an overflow trap for this case.
9540 -- It would be a bit more efficient to figure out which targets this
9541 -- is really needed for, but in practice it is reasonable to do the
9542 -- following special check in all cases, since it means we get a clearer
9543 -- message, and also the overhead is minimal given that division is
9544 -- expensive in any case.
9546 -- In fact the check is quite easy, if the right operand is -1, then
9547 -- the remainder is always 0, and we can just ignore the left operand
9548 -- completely in this case.
9550 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9551 Lneg := (not OK) or else Lo < 0;
9553 Determine_Range (Left, OK, Lo, Hi, Assume_Valid => True);
9554 Rneg := (not OK) or else Lo < 0;
9556 -- We won't mess with trying to find out if the left operand can really
9557 -- be the largest negative number (that's a pain in the case of private
9558 -- types and this is really marginal). We will just assume that we need
9559 -- the test if the left operand can be negative at all.
9561 if Lneg and Rneg then
9562 Rewrite (N,
9563 Make_If_Expression (Loc,
9564 Expressions => New_List (
9565 Make_Op_Eq (Loc,
9566 Left_Opnd => Duplicate_Subexpr (Right),
9567 Right_Opnd =>
9568 Unchecked_Convert_To (Typ, Make_Integer_Literal (Loc, -1))),
9570 Unchecked_Convert_To (Typ,
9571 Make_Integer_Literal (Loc, Uint_0)),
9573 Relocate_Node (N))));
9575 Set_Analyzed (Next (Next (First (Expressions (N)))));
9576 Analyze_And_Resolve (N, Typ);
9577 end if;
9578 end Expand_N_Op_Rem;
9580 -----------------------------
9581 -- Expand_N_Op_Rotate_Left --
9582 -----------------------------
9584 procedure Expand_N_Op_Rotate_Left (N : Node_Id) is
9585 begin
9586 Binary_Op_Validity_Checks (N);
9588 -- If we are in Modify_Tree_For_C mode, there is no rotate left in C,
9589 -- so we rewrite in terms of logical shifts
9591 -- Shift_Left (Num, Bits) or Shift_Right (num, Esize - Bits)
9593 -- where Bits is the shift count mod Esize (the mod operation here
9594 -- deals with ludicrous large shift counts, which are apparently OK).
9596 -- What about nonbinary modulus ???
9598 declare
9599 Loc : constant Source_Ptr := Sloc (N);
9600 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9601 Typ : constant Entity_Id := Etype (N);
9603 begin
9604 if Modify_Tree_For_C then
9605 Rewrite (Right_Opnd (N),
9606 Make_Op_Rem (Loc,
9607 Left_Opnd => Relocate_Node (Right_Opnd (N)),
9608 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
9610 Analyze_And_Resolve (Right_Opnd (N), Rtp);
9612 Rewrite (N,
9613 Make_Op_Or (Loc,
9614 Left_Opnd =>
9615 Make_Op_Shift_Left (Loc,
9616 Left_Opnd => Left_Opnd (N),
9617 Right_Opnd => Right_Opnd (N)),
9619 Right_Opnd =>
9620 Make_Op_Shift_Right (Loc,
9621 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9622 Right_Opnd =>
9623 Make_Op_Subtract (Loc,
9624 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9625 Right_Opnd =>
9626 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9628 Analyze_And_Resolve (N, Typ);
9629 end if;
9630 end;
9631 end Expand_N_Op_Rotate_Left;
9633 ------------------------------
9634 -- Expand_N_Op_Rotate_Right --
9635 ------------------------------
9637 procedure Expand_N_Op_Rotate_Right (N : Node_Id) is
9638 begin
9639 Binary_Op_Validity_Checks (N);
9641 -- If we are in Modify_Tree_For_C mode, there is no rotate right in C,
9642 -- so we rewrite in terms of logical shifts
9644 -- Shift_Right (Num, Bits) or Shift_Left (num, Esize - Bits)
9646 -- where Bits is the shift count mod Esize (the mod operation here
9647 -- deals with ludicrous large shift counts, which are apparently OK).
9649 -- What about nonbinary modulus ???
9651 declare
9652 Loc : constant Source_Ptr := Sloc (N);
9653 Rtp : constant Entity_Id := Etype (Right_Opnd (N));
9654 Typ : constant Entity_Id := Etype (N);
9656 begin
9657 Rewrite (Right_Opnd (N),
9658 Make_Op_Rem (Loc,
9659 Left_Opnd => Relocate_Node (Right_Opnd (N)),
9660 Right_Opnd => Make_Integer_Literal (Loc, Esize (Typ))));
9662 Analyze_And_Resolve (Right_Opnd (N), Rtp);
9664 if Modify_Tree_For_C then
9665 Rewrite (N,
9666 Make_Op_Or (Loc,
9667 Left_Opnd =>
9668 Make_Op_Shift_Right (Loc,
9669 Left_Opnd => Left_Opnd (N),
9670 Right_Opnd => Right_Opnd (N)),
9672 Right_Opnd =>
9673 Make_Op_Shift_Left (Loc,
9674 Left_Opnd => Duplicate_Subexpr_No_Checks (Left_Opnd (N)),
9675 Right_Opnd =>
9676 Make_Op_Subtract (Loc,
9677 Left_Opnd => Make_Integer_Literal (Loc, Esize (Typ)),
9678 Right_Opnd =>
9679 Duplicate_Subexpr_No_Checks (Right_Opnd (N))))));
9681 Analyze_And_Resolve (N, Typ);
9682 end if;
9683 end;
9684 end Expand_N_Op_Rotate_Right;
9686 ----------------------------
9687 -- Expand_N_Op_Shift_Left --
9688 ----------------------------
9690 -- Note: nothing in this routine depends on left as opposed to right shifts
9691 -- so we share the routine for expanding shift right operations.
9693 procedure Expand_N_Op_Shift_Left (N : Node_Id) is
9694 begin
9695 Binary_Op_Validity_Checks (N);
9697 -- If we are in Modify_Tree_For_C mode, then ensure that the right
9698 -- operand is not greater than the word size (since that would not
9699 -- be defined properly by the corresponding C shift operator).
9701 if Modify_Tree_For_C then
9702 declare
9703 Right : constant Node_Id := Right_Opnd (N);
9704 Loc : constant Source_Ptr := Sloc (Right);
9705 Typ : constant Entity_Id := Etype (N);
9706 Siz : constant Uint := Esize (Typ);
9707 Orig : Node_Id;
9708 OK : Boolean;
9709 Lo : Uint;
9710 Hi : Uint;
9712 begin
9713 if Compile_Time_Known_Value (Right) then
9714 if Expr_Value (Right) >= Siz then
9715 Rewrite (N, Make_Integer_Literal (Loc, 0));
9716 Analyze_And_Resolve (N, Typ);
9717 end if;
9719 -- Not compile time known, find range
9721 else
9722 Determine_Range (Right, OK, Lo, Hi, Assume_Valid => True);
9724 -- Nothing to do if known to be OK range, otherwise expand
9726 if not OK or else Hi >= Siz then
9728 -- Prevent recursion on copy of shift node
9730 Orig := Relocate_Node (N);
9731 Set_Analyzed (Orig);
9733 -- Now do the rewrite
9735 Rewrite (N,
9736 Make_If_Expression (Loc,
9737 Expressions => New_List (
9738 Make_Op_Ge (Loc,
9739 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
9740 Right_Opnd => Make_Integer_Literal (Loc, Siz)),
9741 Make_Integer_Literal (Loc, 0),
9742 Orig)));
9743 Analyze_And_Resolve (N, Typ);
9744 end if;
9745 end if;
9746 end;
9747 end if;
9748 end Expand_N_Op_Shift_Left;
9750 -----------------------------
9751 -- Expand_N_Op_Shift_Right --
9752 -----------------------------
9754 procedure Expand_N_Op_Shift_Right (N : Node_Id) is
9755 begin
9756 -- Share shift left circuit
9758 Expand_N_Op_Shift_Left (N);
9759 end Expand_N_Op_Shift_Right;
9761 ----------------------------------------
9762 -- Expand_N_Op_Shift_Right_Arithmetic --
9763 ----------------------------------------
9765 procedure Expand_N_Op_Shift_Right_Arithmetic (N : Node_Id) is
9766 begin
9767 Binary_Op_Validity_Checks (N);
9769 -- If we are in Modify_Tree_For_C mode, there is no shift right
9770 -- arithmetic in C, so we rewrite in terms of logical shifts.
9772 -- Shift_Right (Num, Bits) or
9773 -- (if Num >= Sign
9774 -- then not (Shift_Right (Mask, bits))
9775 -- else 0)
9777 -- Here Mask is all 1 bits (2**size - 1), and Sign is 2**(size - 1)
9779 -- Note: in almost all C compilers it would work to just shift a
9780 -- signed integer right, but it's undefined and we cannot rely on it.
9782 -- Note: the above works fine for shift counts greater than or equal
9783 -- to the word size, since in this case (not (Shift_Right (Mask, bits)))
9784 -- generates all 1'bits.
9786 -- What about nonbinary modulus ???
9788 declare
9789 Loc : constant Source_Ptr := Sloc (N);
9790 Typ : constant Entity_Id := Etype (N);
9791 Sign : constant Uint := 2 ** (Esize (Typ) - 1);
9792 Mask : constant Uint := (2 ** Esize (Typ)) - 1;
9793 Left : constant Node_Id := Left_Opnd (N);
9794 Right : constant Node_Id := Right_Opnd (N);
9795 Maskx : Node_Id;
9797 begin
9798 if Modify_Tree_For_C then
9800 -- Here if not (Shift_Right (Mask, bits)) can be computed at
9801 -- compile time as a single constant.
9803 if Compile_Time_Known_Value (Right) then
9804 declare
9805 Val : constant Uint := Expr_Value (Right);
9807 begin
9808 if Val >= Esize (Typ) then
9809 Maskx := Make_Integer_Literal (Loc, Mask);
9811 else
9812 Maskx :=
9813 Make_Integer_Literal (Loc,
9814 Intval => Mask - (Mask / (2 ** Expr_Value (Right))));
9815 end if;
9816 end;
9818 else
9819 Maskx :=
9820 Make_Op_Not (Loc,
9821 Right_Opnd =>
9822 Make_Op_Shift_Right (Loc,
9823 Left_Opnd => Make_Integer_Literal (Loc, Mask),
9824 Right_Opnd => Duplicate_Subexpr_No_Checks (Right)));
9825 end if;
9827 -- Now do the rewrite
9829 Rewrite (N,
9830 Make_Op_Or (Loc,
9831 Left_Opnd =>
9832 Make_Op_Shift_Right (Loc,
9833 Left_Opnd => Left,
9834 Right_Opnd => Right),
9835 Right_Opnd =>
9836 Make_If_Expression (Loc,
9837 Expressions => New_List (
9838 Make_Op_Ge (Loc,
9839 Left_Opnd => Duplicate_Subexpr_No_Checks (Left),
9840 Right_Opnd => Make_Integer_Literal (Loc, Sign)),
9841 Maskx,
9842 Make_Integer_Literal (Loc, 0)))));
9843 Analyze_And_Resolve (N, Typ);
9844 end if;
9845 end;
9846 end Expand_N_Op_Shift_Right_Arithmetic;
9848 --------------------------
9849 -- Expand_N_Op_Subtract --
9850 --------------------------
9852 procedure Expand_N_Op_Subtract (N : Node_Id) is
9853 Typ : constant Entity_Id := Etype (N);
9855 begin
9856 Binary_Op_Validity_Checks (N);
9858 -- Check for MINIMIZED/ELIMINATED overflow mode
9860 if Minimized_Eliminated_Overflow_Check (N) then
9861 Apply_Arithmetic_Overflow_Check (N);
9862 return;
9863 end if;
9865 -- N - 0 = N for integer types
9867 if Is_Integer_Type (Typ)
9868 and then Compile_Time_Known_Value (Right_Opnd (N))
9869 and then Expr_Value (Right_Opnd (N)) = 0
9870 then
9871 Rewrite (N, Left_Opnd (N));
9872 return;
9873 end if;
9875 -- Arithmetic overflow checks for signed integer/fixed point types
9877 if Is_Signed_Integer_Type (Typ) or else Is_Fixed_Point_Type (Typ) then
9878 Apply_Arithmetic_Overflow_Check (N);
9879 end if;
9881 -- Overflow checks for floating-point if -gnateF mode active
9883 Check_Float_Op_Overflow (N);
9885 -- Generating C code convert non-binary modular subtractions into code
9886 -- that relies on the frontend expansion of operator Mod.
9888 if Modify_Tree_For_C then
9889 Expand_Non_Binary_Modular_Op (N);
9890 end if;
9891 end Expand_N_Op_Subtract;
9893 ---------------------
9894 -- Expand_N_Op_Xor --
9895 ---------------------
9897 procedure Expand_N_Op_Xor (N : Node_Id) is
9898 Typ : constant Entity_Id := Etype (N);
9900 begin
9901 Binary_Op_Validity_Checks (N);
9903 if Is_Array_Type (Etype (N)) then
9904 Expand_Boolean_Operator (N);
9906 elsif Is_Boolean_Type (Etype (N)) then
9907 Adjust_Condition (Left_Opnd (N));
9908 Adjust_Condition (Right_Opnd (N));
9909 Set_Etype (N, Standard_Boolean);
9910 Adjust_Result_Type (N, Typ);
9912 elsif Is_Intrinsic_Subprogram (Entity (N)) then
9913 Expand_Intrinsic_Call (N, Entity (N));
9915 end if;
9916 end Expand_N_Op_Xor;
9918 ----------------------
9919 -- Expand_N_Or_Else --
9920 ----------------------
9922 procedure Expand_N_Or_Else (N : Node_Id)
9923 renames Expand_Short_Circuit_Operator;
9925 -----------------------------------
9926 -- Expand_N_Qualified_Expression --
9927 -----------------------------------
9929 procedure Expand_N_Qualified_Expression (N : Node_Id) is
9930 Operand : constant Node_Id := Expression (N);
9931 Target_Type : constant Entity_Id := Entity (Subtype_Mark (N));
9933 begin
9934 -- Do validity check if validity checking operands
9936 if Validity_Checks_On and Validity_Check_Operands then
9937 Ensure_Valid (Operand);
9938 end if;
9940 -- Apply possible constraint check
9942 Apply_Constraint_Check (Operand, Target_Type, No_Sliding => True);
9944 if Do_Range_Check (Operand) then
9945 Set_Do_Range_Check (Operand, False);
9946 Generate_Range_Check (Operand, Target_Type, CE_Range_Check_Failed);
9947 end if;
9948 end Expand_N_Qualified_Expression;
9950 ------------------------------------
9951 -- Expand_N_Quantified_Expression --
9952 ------------------------------------
9954 -- We expand:
9956 -- for all X in range => Cond
9958 -- into:
9960 -- T := True;
9961 -- for X in range loop
9962 -- if not Cond then
9963 -- T := False;
9964 -- exit;
9965 -- end if;
9966 -- end loop;
9968 -- Similarly, an existentially quantified expression:
9970 -- for some X in range => Cond
9972 -- becomes:
9974 -- T := False;
9975 -- for X in range loop
9976 -- if Cond then
9977 -- T := True;
9978 -- exit;
9979 -- end if;
9980 -- end loop;
9982 -- In both cases, the iteration may be over a container in which case it is
9983 -- given by an iterator specification, not a loop parameter specification.
9985 procedure Expand_N_Quantified_Expression (N : Node_Id) is
9986 Actions : constant List_Id := New_List;
9987 For_All : constant Boolean := All_Present (N);
9988 Iter_Spec : constant Node_Id := Iterator_Specification (N);
9989 Loc : constant Source_Ptr := Sloc (N);
9990 Loop_Spec : constant Node_Id := Loop_Parameter_Specification (N);
9991 Cond : Node_Id;
9992 Flag : Entity_Id;
9993 Scheme : Node_Id;
9994 Stmts : List_Id;
9996 begin
9997 -- Create the declaration of the flag which tracks the status of the
9998 -- quantified expression. Generate:
10000 -- Flag : Boolean := (True | False);
10002 Flag := Make_Temporary (Loc, 'T', N);
10004 Append_To (Actions,
10005 Make_Object_Declaration (Loc,
10006 Defining_Identifier => Flag,
10007 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
10008 Expression =>
10009 New_Occurrence_Of (Boolean_Literals (For_All), Loc)));
10011 -- Construct the circuitry which tracks the status of the quantified
10012 -- expression. Generate:
10014 -- if [not] Cond then
10015 -- Flag := (False | True);
10016 -- exit;
10017 -- end if;
10019 Cond := Relocate_Node (Condition (N));
10021 if For_All then
10022 Cond := Make_Op_Not (Loc, Cond);
10023 end if;
10025 Stmts := New_List (
10026 Make_Implicit_If_Statement (N,
10027 Condition => Cond,
10028 Then_Statements => New_List (
10029 Make_Assignment_Statement (Loc,
10030 Name => New_Occurrence_Of (Flag, Loc),
10031 Expression =>
10032 New_Occurrence_Of (Boolean_Literals (not For_All), Loc)),
10033 Make_Exit_Statement (Loc))));
10035 -- Build the loop equivalent of the quantified expression
10037 if Present (Iter_Spec) then
10038 Scheme :=
10039 Make_Iteration_Scheme (Loc,
10040 Iterator_Specification => Iter_Spec);
10041 else
10042 Scheme :=
10043 Make_Iteration_Scheme (Loc,
10044 Loop_Parameter_Specification => Loop_Spec);
10045 end if;
10047 Append_To (Actions,
10048 Make_Loop_Statement (Loc,
10049 Iteration_Scheme => Scheme,
10050 Statements => Stmts,
10051 End_Label => Empty));
10053 -- Transform the quantified expression
10055 Rewrite (N,
10056 Make_Expression_With_Actions (Loc,
10057 Expression => New_Occurrence_Of (Flag, Loc),
10058 Actions => Actions));
10059 Analyze_And_Resolve (N, Standard_Boolean);
10060 end Expand_N_Quantified_Expression;
10062 ---------------------------------
10063 -- Expand_N_Selected_Component --
10064 ---------------------------------
10066 procedure Expand_N_Selected_Component (N : Node_Id) is
10067 Loc : constant Source_Ptr := Sloc (N);
10068 Par : constant Node_Id := Parent (N);
10069 P : constant Node_Id := Prefix (N);
10070 S : constant Node_Id := Selector_Name (N);
10071 Ptyp : Entity_Id := Underlying_Type (Etype (P));
10072 Disc : Entity_Id;
10073 New_N : Node_Id;
10074 Dcon : Elmt_Id;
10075 Dval : Node_Id;
10077 function In_Left_Hand_Side (Comp : Node_Id) return Boolean;
10078 -- Gigi needs a temporary for prefixes that depend on a discriminant,
10079 -- unless the context of an assignment can provide size information.
10080 -- Don't we have a general routine that does this???
10082 function Is_Subtype_Declaration return Boolean;
10083 -- The replacement of a discriminant reference by its value is required
10084 -- if this is part of the initialization of an temporary generated by a
10085 -- change of representation. This shows up as the construction of a
10086 -- discriminant constraint for a subtype declared at the same point as
10087 -- the entity in the prefix of the selected component. We recognize this
10088 -- case when the context of the reference is:
10089 -- subtype ST is T(Obj.D);
10090 -- where the entity for Obj comes from source, and ST has the same sloc.
10092 -----------------------
10093 -- In_Left_Hand_Side --
10094 -----------------------
10096 function In_Left_Hand_Side (Comp : Node_Id) return Boolean is
10097 begin
10098 return (Nkind (Parent (Comp)) = N_Assignment_Statement
10099 and then Comp = Name (Parent (Comp)))
10100 or else (Present (Parent (Comp))
10101 and then Nkind (Parent (Comp)) in N_Subexpr
10102 and then In_Left_Hand_Side (Parent (Comp)));
10103 end In_Left_Hand_Side;
10105 -----------------------------
10106 -- Is_Subtype_Declaration --
10107 -----------------------------
10109 function Is_Subtype_Declaration return Boolean is
10110 Par : constant Node_Id := Parent (N);
10111 begin
10112 return
10113 Nkind (Par) = N_Index_Or_Discriminant_Constraint
10114 and then Nkind (Parent (Parent (Par))) = N_Subtype_Declaration
10115 and then Comes_From_Source (Entity (Prefix (N)))
10116 and then Sloc (Par) = Sloc (Entity (Prefix (N)));
10117 end Is_Subtype_Declaration;
10119 -- Start of processing for Expand_N_Selected_Component
10121 begin
10122 -- Insert explicit dereference if required
10124 if Is_Access_Type (Ptyp) then
10126 -- First set prefix type to proper access type, in case it currently
10127 -- has a private (non-access) view of this type.
10129 Set_Etype (P, Ptyp);
10131 Insert_Explicit_Dereference (P);
10132 Analyze_And_Resolve (P, Designated_Type (Ptyp));
10134 if Ekind (Etype (P)) = E_Private_Subtype
10135 and then Is_For_Access_Subtype (Etype (P))
10136 then
10137 Set_Etype (P, Base_Type (Etype (P)));
10138 end if;
10140 Ptyp := Etype (P);
10141 end if;
10143 -- Deal with discriminant check required
10145 if Do_Discriminant_Check (N) then
10146 if Present (Discriminant_Checking_Func
10147 (Original_Record_Component (Entity (S))))
10148 then
10149 -- Present the discriminant checking function to the backend, so
10150 -- that it can inline the call to the function.
10152 Add_Inlined_Body
10153 (Discriminant_Checking_Func
10154 (Original_Record_Component (Entity (S))),
10157 -- Now reset the flag and generate the call
10159 Set_Do_Discriminant_Check (N, False);
10160 Generate_Discriminant_Check (N);
10162 -- In the case of Unchecked_Union, no discriminant checking is
10163 -- actually performed.
10165 else
10166 Set_Do_Discriminant_Check (N, False);
10167 end if;
10168 end if;
10170 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10171 -- function, then additional actuals must be passed.
10173 if Ada_Version >= Ada_2005
10174 and then Is_Build_In_Place_Function_Call (P)
10175 then
10176 Make_Build_In_Place_Call_In_Anonymous_Context (P);
10177 end if;
10179 -- Gigi cannot handle unchecked conversions that are the prefix of a
10180 -- selected component with discriminants. This must be checked during
10181 -- expansion, because during analysis the type of the selector is not
10182 -- known at the point the prefix is analyzed. If the conversion is the
10183 -- target of an assignment, then we cannot force the evaluation.
10185 if Nkind (Prefix (N)) = N_Unchecked_Type_Conversion
10186 and then Has_Discriminants (Etype (N))
10187 and then not In_Left_Hand_Side (N)
10188 then
10189 Force_Evaluation (Prefix (N));
10190 end if;
10192 -- Remaining processing applies only if selector is a discriminant
10194 if Ekind (Entity (Selector_Name (N))) = E_Discriminant then
10196 -- If the selector is a discriminant of a constrained record type,
10197 -- we may be able to rewrite the expression with the actual value
10198 -- of the discriminant, a useful optimization in some cases.
10200 if Is_Record_Type (Ptyp)
10201 and then Has_Discriminants (Ptyp)
10202 and then Is_Constrained (Ptyp)
10203 then
10204 -- Do this optimization for discrete types only, and not for
10205 -- access types (access discriminants get us into trouble).
10207 if not Is_Discrete_Type (Etype (N)) then
10208 null;
10210 -- Don't do this on the left-hand side of an assignment statement.
10211 -- Normally one would think that references like this would not
10212 -- occur, but they do in generated code, and mean that we really
10213 -- do want to assign the discriminant.
10215 elsif Nkind (Par) = N_Assignment_Statement
10216 and then Name (Par) = N
10217 then
10218 null;
10220 -- Don't do this optimization for the prefix of an attribute or
10221 -- the name of an object renaming declaration since these are
10222 -- contexts where we do not want the value anyway.
10224 elsif (Nkind (Par) = N_Attribute_Reference
10225 and then Prefix (Par) = N)
10226 or else Is_Renamed_Object (N)
10227 then
10228 null;
10230 -- Don't do this optimization if we are within the code for a
10231 -- discriminant check, since the whole point of such a check may
10232 -- be to verify the condition on which the code below depends.
10234 elsif Is_In_Discriminant_Check (N) then
10235 null;
10237 -- Green light to see if we can do the optimization. There is
10238 -- still one condition that inhibits the optimization below but
10239 -- now is the time to check the particular discriminant.
10241 else
10242 -- Loop through discriminants to find the matching discriminant
10243 -- constraint to see if we can copy it.
10245 Disc := First_Discriminant (Ptyp);
10246 Dcon := First_Elmt (Discriminant_Constraint (Ptyp));
10247 Discr_Loop : while Present (Dcon) loop
10248 Dval := Node (Dcon);
10250 -- Check if this is the matching discriminant and if the
10251 -- discriminant value is simple enough to make sense to
10252 -- copy. We don't want to copy complex expressions, and
10253 -- indeed to do so can cause trouble (before we put in
10254 -- this guard, a discriminant expression containing an
10255 -- AND THEN was copied, causing problems for coverage
10256 -- analysis tools).
10258 -- However, if the reference is part of the initialization
10259 -- code generated for an object declaration, we must use
10260 -- the discriminant value from the subtype constraint,
10261 -- because the selected component may be a reference to the
10262 -- object being initialized, whose discriminant is not yet
10263 -- set. This only happens in complex cases involving changes
10264 -- or representation.
10266 if Disc = Entity (Selector_Name (N))
10267 and then (Is_Entity_Name (Dval)
10268 or else Compile_Time_Known_Value (Dval)
10269 or else Is_Subtype_Declaration)
10270 then
10271 -- Here we have the matching discriminant. Check for
10272 -- the case of a discriminant of a component that is
10273 -- constrained by an outer discriminant, which cannot
10274 -- be optimized away.
10276 if Denotes_Discriminant
10277 (Dval, Check_Concurrent => True)
10278 then
10279 exit Discr_Loop;
10281 elsif Nkind (Original_Node (Dval)) = N_Selected_Component
10282 and then
10283 Denotes_Discriminant
10284 (Selector_Name (Original_Node (Dval)), True)
10285 then
10286 exit Discr_Loop;
10288 -- Do not retrieve value if constraint is not static. It
10289 -- is generally not useful, and the constraint may be a
10290 -- rewritten outer discriminant in which case it is in
10291 -- fact incorrect.
10293 elsif Is_Entity_Name (Dval)
10294 and then
10295 Nkind (Parent (Entity (Dval))) = N_Object_Declaration
10296 and then Present (Expression (Parent (Entity (Dval))))
10297 and then not
10298 Is_OK_Static_Expression
10299 (Expression (Parent (Entity (Dval))))
10300 then
10301 exit Discr_Loop;
10303 -- In the context of a case statement, the expression may
10304 -- have the base type of the discriminant, and we need to
10305 -- preserve the constraint to avoid spurious errors on
10306 -- missing cases.
10308 elsif Nkind (Parent (N)) = N_Case_Statement
10309 and then Etype (Dval) /= Etype (Disc)
10310 then
10311 Rewrite (N,
10312 Make_Qualified_Expression (Loc,
10313 Subtype_Mark =>
10314 New_Occurrence_Of (Etype (Disc), Loc),
10315 Expression =>
10316 New_Copy_Tree (Dval)));
10317 Analyze_And_Resolve (N, Etype (Disc));
10319 -- In case that comes out as a static expression,
10320 -- reset it (a selected component is never static).
10322 Set_Is_Static_Expression (N, False);
10323 return;
10325 -- Otherwise we can just copy the constraint, but the
10326 -- result is certainly not static. In some cases the
10327 -- discriminant constraint has been analyzed in the
10328 -- context of the original subtype indication, but for
10329 -- itypes the constraint might not have been analyzed
10330 -- yet, and this must be done now.
10332 else
10333 Rewrite (N, New_Copy_Tree (Dval));
10334 Analyze_And_Resolve (N);
10335 Set_Is_Static_Expression (N, False);
10336 return;
10337 end if;
10338 end if;
10340 Next_Elmt (Dcon);
10341 Next_Discriminant (Disc);
10342 end loop Discr_Loop;
10344 -- Note: the above loop should always find a matching
10345 -- discriminant, but if it does not, we just missed an
10346 -- optimization due to some glitch (perhaps a previous
10347 -- error), so ignore.
10349 end if;
10350 end if;
10352 -- The only remaining processing is in the case of a discriminant of
10353 -- a concurrent object, where we rewrite the prefix to denote the
10354 -- corresponding record type. If the type is derived and has renamed
10355 -- discriminants, use corresponding discriminant, which is the one
10356 -- that appears in the corresponding record.
10358 if not Is_Concurrent_Type (Ptyp) then
10359 return;
10360 end if;
10362 Disc := Entity (Selector_Name (N));
10364 if Is_Derived_Type (Ptyp)
10365 and then Present (Corresponding_Discriminant (Disc))
10366 then
10367 Disc := Corresponding_Discriminant (Disc);
10368 end if;
10370 New_N :=
10371 Make_Selected_Component (Loc,
10372 Prefix =>
10373 Unchecked_Convert_To (Corresponding_Record_Type (Ptyp),
10374 New_Copy_Tree (P)),
10375 Selector_Name => Make_Identifier (Loc, Chars (Disc)));
10377 Rewrite (N, New_N);
10378 Analyze (N);
10379 end if;
10381 -- Set Atomic_Sync_Required if necessary for atomic component
10383 if Nkind (N) = N_Selected_Component then
10384 declare
10385 E : constant Entity_Id := Entity (Selector_Name (N));
10386 Set : Boolean;
10388 begin
10389 -- If component is atomic, but type is not, setting depends on
10390 -- disable/enable state for the component.
10392 if Is_Atomic (E) and then not Is_Atomic (Etype (E)) then
10393 Set := not Atomic_Synchronization_Disabled (E);
10395 -- If component is not atomic, but its type is atomic, setting
10396 -- depends on disable/enable state for the type.
10398 elsif not Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10399 Set := not Atomic_Synchronization_Disabled (Etype (E));
10401 -- If both component and type are atomic, we disable if either
10402 -- component or its type have sync disabled.
10404 elsif Is_Atomic (E) and then Is_Atomic (Etype (E)) then
10405 Set := (not Atomic_Synchronization_Disabled (E))
10406 and then
10407 (not Atomic_Synchronization_Disabled (Etype (E)));
10409 else
10410 Set := False;
10411 end if;
10413 -- Set flag if required
10415 if Set then
10416 Activate_Atomic_Synchronization (N);
10417 end if;
10418 end;
10419 end if;
10420 end Expand_N_Selected_Component;
10422 --------------------
10423 -- Expand_N_Slice --
10424 --------------------
10426 procedure Expand_N_Slice (N : Node_Id) is
10427 Loc : constant Source_Ptr := Sloc (N);
10428 Typ : constant Entity_Id := Etype (N);
10430 function Is_Procedure_Actual (N : Node_Id) return Boolean;
10431 -- Check whether the argument is an actual for a procedure call, in
10432 -- which case the expansion of a bit-packed slice is deferred until the
10433 -- call itself is expanded. The reason this is required is that we might
10434 -- have an IN OUT or OUT parameter, and the copy out is essential, and
10435 -- that copy out would be missed if we created a temporary here in
10436 -- Expand_N_Slice. Note that we don't bother to test specifically for an
10437 -- IN OUT or OUT mode parameter, since it is a bit tricky to do, and it
10438 -- is harmless to defer expansion in the IN case, since the call
10439 -- processing will still generate the appropriate copy in operation,
10440 -- which will take care of the slice.
10442 procedure Make_Temporary_For_Slice;
10443 -- Create a named variable for the value of the slice, in cases where
10444 -- the back-end cannot handle it properly, e.g. when packed types or
10445 -- unaligned slices are involved.
10447 -------------------------
10448 -- Is_Procedure_Actual --
10449 -------------------------
10451 function Is_Procedure_Actual (N : Node_Id) return Boolean is
10452 Par : Node_Id := Parent (N);
10454 begin
10455 loop
10456 -- If our parent is a procedure call we can return
10458 if Nkind (Par) = N_Procedure_Call_Statement then
10459 return True;
10461 -- If our parent is a type conversion, keep climbing the tree,
10462 -- since a type conversion can be a procedure actual. Also keep
10463 -- climbing if parameter association or a qualified expression,
10464 -- since these are additional cases that do can appear on
10465 -- procedure actuals.
10467 elsif Nkind_In (Par, N_Type_Conversion,
10468 N_Parameter_Association,
10469 N_Qualified_Expression)
10470 then
10471 Par := Parent (Par);
10473 -- Any other case is not what we are looking for
10475 else
10476 return False;
10477 end if;
10478 end loop;
10479 end Is_Procedure_Actual;
10481 ------------------------------
10482 -- Make_Temporary_For_Slice --
10483 ------------------------------
10485 procedure Make_Temporary_For_Slice is
10486 Ent : constant Entity_Id := Make_Temporary (Loc, 'T', N);
10487 Decl : Node_Id;
10489 begin
10490 Decl :=
10491 Make_Object_Declaration (Loc,
10492 Defining_Identifier => Ent,
10493 Object_Definition => New_Occurrence_Of (Typ, Loc));
10495 Set_No_Initialization (Decl);
10497 Insert_Actions (N, New_List (
10498 Decl,
10499 Make_Assignment_Statement (Loc,
10500 Name => New_Occurrence_Of (Ent, Loc),
10501 Expression => Relocate_Node (N))));
10503 Rewrite (N, New_Occurrence_Of (Ent, Loc));
10504 Analyze_And_Resolve (N, Typ);
10505 end Make_Temporary_For_Slice;
10507 -- Local variables
10509 Pref : constant Node_Id := Prefix (N);
10510 Pref_Typ : Entity_Id := Etype (Pref);
10512 -- Start of processing for Expand_N_Slice
10514 begin
10515 -- Special handling for access types
10517 if Is_Access_Type (Pref_Typ) then
10518 Pref_Typ := Designated_Type (Pref_Typ);
10520 Rewrite (Pref,
10521 Make_Explicit_Dereference (Sloc (N),
10522 Prefix => Relocate_Node (Pref)));
10524 Analyze_And_Resolve (Pref, Pref_Typ);
10525 end if;
10527 -- Ada 2005 (AI-318-02): If the prefix is a call to a build-in-place
10528 -- function, then additional actuals must be passed.
10530 if Ada_Version >= Ada_2005
10531 and then Is_Build_In_Place_Function_Call (Pref)
10532 then
10533 Make_Build_In_Place_Call_In_Anonymous_Context (Pref);
10534 end if;
10536 -- The remaining case to be handled is packed slices. We can leave
10537 -- packed slices as they are in the following situations:
10539 -- 1. Right or left side of an assignment (we can handle this
10540 -- situation correctly in the assignment statement expansion).
10542 -- 2. Prefix of indexed component (the slide is optimized away in this
10543 -- case, see the start of Expand_N_Slice.)
10545 -- 3. Object renaming declaration, since we want the name of the
10546 -- slice, not the value.
10548 -- 4. Argument to procedure call, since copy-in/copy-out handling may
10549 -- be required, and this is handled in the expansion of call
10550 -- itself.
10552 -- 5. Prefix of an address attribute (this is an error which is caught
10553 -- elsewhere, and the expansion would interfere with generating the
10554 -- error message).
10556 if not Is_Packed (Typ) then
10558 -- Apply transformation for actuals of a function call, where
10559 -- Expand_Actuals is not used.
10561 if Nkind (Parent (N)) = N_Function_Call
10562 and then Is_Possibly_Unaligned_Slice (N)
10563 then
10564 Make_Temporary_For_Slice;
10565 end if;
10567 elsif Nkind (Parent (N)) = N_Assignment_Statement
10568 or else (Nkind (Parent (Parent (N))) = N_Assignment_Statement
10569 and then Parent (N) = Name (Parent (Parent (N))))
10570 then
10571 return;
10573 elsif Nkind (Parent (N)) = N_Indexed_Component
10574 or else Is_Renamed_Object (N)
10575 or else Is_Procedure_Actual (N)
10576 then
10577 return;
10579 elsif Nkind (Parent (N)) = N_Attribute_Reference
10580 and then Attribute_Name (Parent (N)) = Name_Address
10581 then
10582 return;
10584 else
10585 Make_Temporary_For_Slice;
10586 end if;
10587 end Expand_N_Slice;
10589 ------------------------------
10590 -- Expand_N_Type_Conversion --
10591 ------------------------------
10593 procedure Expand_N_Type_Conversion (N : Node_Id) is
10594 Loc : constant Source_Ptr := Sloc (N);
10595 Operand : constant Node_Id := Expression (N);
10596 Target_Type : constant Entity_Id := Etype (N);
10597 Operand_Type : Entity_Id := Etype (Operand);
10599 procedure Handle_Changed_Representation;
10600 -- This is called in the case of record and array type conversions to
10601 -- see if there is a change of representation to be handled. Change of
10602 -- representation is actually handled at the assignment statement level,
10603 -- and what this procedure does is rewrite node N conversion as an
10604 -- assignment to temporary. If there is no change of representation,
10605 -- then the conversion node is unchanged.
10607 procedure Raise_Accessibility_Error;
10608 -- Called when we know that an accessibility check will fail. Rewrites
10609 -- node N to an appropriate raise statement and outputs warning msgs.
10610 -- The Etype of the raise node is set to Target_Type. Note that in this
10611 -- case the rest of the processing should be skipped (i.e. the call to
10612 -- this procedure will be followed by "goto Done").
10614 procedure Real_Range_Check;
10615 -- Handles generation of range check for real target value
10617 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean;
10618 -- True iff Present (Effective_Extra_Accessibility (Id)) successfully
10619 -- evaluates to True.
10621 -----------------------------------
10622 -- Handle_Changed_Representation --
10623 -----------------------------------
10625 procedure Handle_Changed_Representation is
10626 Temp : Entity_Id;
10627 Decl : Node_Id;
10628 Odef : Node_Id;
10629 Disc : Node_Id;
10630 N_Ix : Node_Id;
10631 Cons : List_Id;
10633 begin
10634 -- Nothing else to do if no change of representation
10636 if Same_Representation (Operand_Type, Target_Type) then
10637 return;
10639 -- The real change of representation work is done by the assignment
10640 -- statement processing. So if this type conversion is appearing as
10641 -- the expression of an assignment statement, nothing needs to be
10642 -- done to the conversion.
10644 elsif Nkind (Parent (N)) = N_Assignment_Statement then
10645 return;
10647 -- Otherwise we need to generate a temporary variable, and do the
10648 -- change of representation assignment into that temporary variable.
10649 -- The conversion is then replaced by a reference to this variable.
10651 else
10652 Cons := No_List;
10654 -- If type is unconstrained we have to add a constraint, copied
10655 -- from the actual value of the left-hand side.
10657 if not Is_Constrained (Target_Type) then
10658 if Has_Discriminants (Operand_Type) then
10659 Disc := First_Discriminant (Operand_Type);
10661 if Disc /= First_Stored_Discriminant (Operand_Type) then
10662 Disc := First_Stored_Discriminant (Operand_Type);
10663 end if;
10665 Cons := New_List;
10666 while Present (Disc) loop
10667 Append_To (Cons,
10668 Make_Selected_Component (Loc,
10669 Prefix =>
10670 Duplicate_Subexpr_Move_Checks (Operand),
10671 Selector_Name =>
10672 Make_Identifier (Loc, Chars (Disc))));
10673 Next_Discriminant (Disc);
10674 end loop;
10676 elsif Is_Array_Type (Operand_Type) then
10677 N_Ix := First_Index (Target_Type);
10678 Cons := New_List;
10680 for J in 1 .. Number_Dimensions (Operand_Type) loop
10682 -- We convert the bounds explicitly. We use an unchecked
10683 -- conversion because bounds checks are done elsewhere.
10685 Append_To (Cons,
10686 Make_Range (Loc,
10687 Low_Bound =>
10688 Unchecked_Convert_To (Etype (N_Ix),
10689 Make_Attribute_Reference (Loc,
10690 Prefix =>
10691 Duplicate_Subexpr_No_Checks
10692 (Operand, Name_Req => True),
10693 Attribute_Name => Name_First,
10694 Expressions => New_List (
10695 Make_Integer_Literal (Loc, J)))),
10697 High_Bound =>
10698 Unchecked_Convert_To (Etype (N_Ix),
10699 Make_Attribute_Reference (Loc,
10700 Prefix =>
10701 Duplicate_Subexpr_No_Checks
10702 (Operand, Name_Req => True),
10703 Attribute_Name => Name_Last,
10704 Expressions => New_List (
10705 Make_Integer_Literal (Loc, J))))));
10707 Next_Index (N_Ix);
10708 end loop;
10709 end if;
10710 end if;
10712 Odef := New_Occurrence_Of (Target_Type, Loc);
10714 if Present (Cons) then
10715 Odef :=
10716 Make_Subtype_Indication (Loc,
10717 Subtype_Mark => Odef,
10718 Constraint =>
10719 Make_Index_Or_Discriminant_Constraint (Loc,
10720 Constraints => Cons));
10721 end if;
10723 Temp := Make_Temporary (Loc, 'C');
10724 Decl :=
10725 Make_Object_Declaration (Loc,
10726 Defining_Identifier => Temp,
10727 Object_Definition => Odef);
10729 Set_No_Initialization (Decl, True);
10731 -- Insert required actions. It is essential to suppress checks
10732 -- since we have suppressed default initialization, which means
10733 -- that the variable we create may have no discriminants.
10735 Insert_Actions (N,
10736 New_List (
10737 Decl,
10738 Make_Assignment_Statement (Loc,
10739 Name => New_Occurrence_Of (Temp, Loc),
10740 Expression => Relocate_Node (N))),
10741 Suppress => All_Checks);
10743 Rewrite (N, New_Occurrence_Of (Temp, Loc));
10744 return;
10745 end if;
10746 end Handle_Changed_Representation;
10748 -------------------------------
10749 -- Raise_Accessibility_Error --
10750 -------------------------------
10752 procedure Raise_Accessibility_Error is
10753 begin
10754 Error_Msg_Warn := SPARK_Mode /= On;
10755 Rewrite (N,
10756 Make_Raise_Program_Error (Sloc (N),
10757 Reason => PE_Accessibility_Check_Failed));
10758 Set_Etype (N, Target_Type);
10760 Error_Msg_N ("<<accessibility check failure", N);
10761 Error_Msg_NE ("\<<& [", N, Standard_Program_Error);
10762 end Raise_Accessibility_Error;
10764 ----------------------
10765 -- Real_Range_Check --
10766 ----------------------
10768 -- Case of conversions to floating-point or fixed-point. If range checks
10769 -- are enabled and the target type has a range constraint, we convert:
10771 -- typ (x)
10773 -- to
10775 -- Tnn : typ'Base := typ'Base (x);
10776 -- [constraint_error when Tnn < typ'First or else Tnn > typ'Last]
10777 -- Tnn
10779 -- This is necessary when there is a conversion of integer to float or
10780 -- to fixed-point to ensure that the correct checks are made. It is not
10781 -- necessary for float to float where it is enough to simply set the
10782 -- Do_Range_Check flag.
10784 procedure Real_Range_Check is
10785 Btyp : constant Entity_Id := Base_Type (Target_Type);
10786 Lo : constant Node_Id := Type_Low_Bound (Target_Type);
10787 Hi : constant Node_Id := Type_High_Bound (Target_Type);
10788 Xtyp : constant Entity_Id := Etype (Operand);
10789 Conv : Node_Id;
10790 Tnn : Entity_Id;
10792 begin
10793 -- Nothing to do if conversion was rewritten
10795 if Nkind (N) /= N_Type_Conversion then
10796 return;
10797 end if;
10799 -- Nothing to do if range checks suppressed, or target has the same
10800 -- range as the base type (or is the base type).
10802 if Range_Checks_Suppressed (Target_Type)
10803 or else (Lo = Type_Low_Bound (Btyp)
10804 and then
10805 Hi = Type_High_Bound (Btyp))
10806 then
10807 return;
10808 end if;
10810 -- Nothing to do if expression is an entity on which checks have been
10811 -- suppressed.
10813 if Is_Entity_Name (Operand)
10814 and then Range_Checks_Suppressed (Entity (Operand))
10815 then
10816 return;
10817 end if;
10819 -- Nothing to do if bounds are all static and we can tell that the
10820 -- expression is within the bounds of the target. Note that if the
10821 -- operand is of an unconstrained floating-point type, then we do
10822 -- not trust it to be in range (might be infinite)
10824 declare
10825 S_Lo : constant Node_Id := Type_Low_Bound (Xtyp);
10826 S_Hi : constant Node_Id := Type_High_Bound (Xtyp);
10828 begin
10829 if (not Is_Floating_Point_Type (Xtyp)
10830 or else Is_Constrained (Xtyp))
10831 and then Compile_Time_Known_Value (S_Lo)
10832 and then Compile_Time_Known_Value (S_Hi)
10833 and then Compile_Time_Known_Value (Hi)
10834 and then Compile_Time_Known_Value (Lo)
10835 then
10836 declare
10837 D_Lov : constant Ureal := Expr_Value_R (Lo);
10838 D_Hiv : constant Ureal := Expr_Value_R (Hi);
10839 S_Lov : Ureal;
10840 S_Hiv : Ureal;
10842 begin
10843 if Is_Real_Type (Xtyp) then
10844 S_Lov := Expr_Value_R (S_Lo);
10845 S_Hiv := Expr_Value_R (S_Hi);
10846 else
10847 S_Lov := UR_From_Uint (Expr_Value (S_Lo));
10848 S_Hiv := UR_From_Uint (Expr_Value (S_Hi));
10849 end if;
10851 if D_Hiv > D_Lov
10852 and then S_Lov >= D_Lov
10853 and then S_Hiv <= D_Hiv
10854 then
10855 -- Unset the range check flag on the current value of
10856 -- Expression (N), since the captured Operand may have
10857 -- been rewritten (such as for the case of a conversion
10858 -- to a fixed-point type).
10860 Set_Do_Range_Check (Expression (N), False);
10862 return;
10863 end if;
10864 end;
10865 end if;
10866 end;
10868 -- For float to float conversions, we are done
10870 if Is_Floating_Point_Type (Xtyp)
10871 and then
10872 Is_Floating_Point_Type (Btyp)
10873 then
10874 return;
10875 end if;
10877 -- Otherwise rewrite the conversion as described above
10879 Conv := Relocate_Node (N);
10880 Rewrite (Subtype_Mark (Conv), New_Occurrence_Of (Btyp, Loc));
10881 Set_Etype (Conv, Btyp);
10883 -- Enable overflow except for case of integer to float conversions,
10884 -- where it is never required, since we can never have overflow in
10885 -- this case.
10887 if not Is_Integer_Type (Etype (Operand)) then
10888 Enable_Overflow_Check (Conv);
10889 end if;
10891 Tnn := Make_Temporary (Loc, 'T', Conv);
10893 Insert_Actions (N, New_List (
10894 Make_Object_Declaration (Loc,
10895 Defining_Identifier => Tnn,
10896 Object_Definition => New_Occurrence_Of (Btyp, Loc),
10897 Constant_Present => True,
10898 Expression => Conv),
10900 Make_Raise_Constraint_Error (Loc,
10901 Condition =>
10902 Make_Or_Else (Loc,
10903 Left_Opnd =>
10904 Make_Op_Lt (Loc,
10905 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
10906 Right_Opnd =>
10907 Make_Attribute_Reference (Loc,
10908 Attribute_Name => Name_First,
10909 Prefix =>
10910 New_Occurrence_Of (Target_Type, Loc))),
10912 Right_Opnd =>
10913 Make_Op_Gt (Loc,
10914 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
10915 Right_Opnd =>
10916 Make_Attribute_Reference (Loc,
10917 Attribute_Name => Name_Last,
10918 Prefix =>
10919 New_Occurrence_Of (Target_Type, Loc)))),
10920 Reason => CE_Range_Check_Failed)));
10922 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
10923 Analyze_And_Resolve (N, Btyp);
10924 end Real_Range_Check;
10926 -----------------------------
10927 -- Has_Extra_Accessibility --
10928 -----------------------------
10930 -- Returns true for a formal of an anonymous access type or for
10931 -- an Ada 2012-style stand-alone object of an anonymous access type.
10933 function Has_Extra_Accessibility (Id : Entity_Id) return Boolean is
10934 begin
10935 if Is_Formal (Id) or else Ekind_In (Id, E_Constant, E_Variable) then
10936 return Present (Effective_Extra_Accessibility (Id));
10937 else
10938 return False;
10939 end if;
10940 end Has_Extra_Accessibility;
10942 -- Start of processing for Expand_N_Type_Conversion
10944 begin
10945 -- First remove check marks put by the semantic analysis on the type
10946 -- conversion between array types. We need these checks, and they will
10947 -- be generated by this expansion routine, but we do not depend on these
10948 -- flags being set, and since we do intend to expand the checks in the
10949 -- front end, we don't want them on the tree passed to the back end.
10951 if Is_Array_Type (Target_Type) then
10952 if Is_Constrained (Target_Type) then
10953 Set_Do_Length_Check (N, False);
10954 else
10955 Set_Do_Range_Check (Operand, False);
10956 end if;
10957 end if;
10959 -- Nothing at all to do if conversion is to the identical type so remove
10960 -- the conversion completely, it is useless, except that it may carry
10961 -- an Assignment_OK attribute, which must be propagated to the operand.
10963 if Operand_Type = Target_Type then
10964 if Assignment_OK (N) then
10965 Set_Assignment_OK (Operand);
10966 end if;
10968 Rewrite (N, Relocate_Node (Operand));
10969 goto Done;
10970 end if;
10972 -- Nothing to do if this is the second argument of read. This is a
10973 -- "backwards" conversion that will be handled by the specialized code
10974 -- in attribute processing.
10976 if Nkind (Parent (N)) = N_Attribute_Reference
10977 and then Attribute_Name (Parent (N)) = Name_Read
10978 and then Next (First (Expressions (Parent (N)))) = N
10979 then
10980 goto Done;
10981 end if;
10983 -- Check for case of converting to a type that has an invariant
10984 -- associated with it. This requires an invariant check. We insert
10985 -- a call:
10987 -- invariant_check (typ (expr))
10989 -- in the code, after removing side effects from the expression.
10990 -- This is clearer than replacing the conversion into an expression
10991 -- with actions, because the context may impose additional actions
10992 -- (tag checks, membership tests, etc.) that conflict with this
10993 -- rewriting (used previously).
10995 -- Note: the Comes_From_Source check, and then the resetting of this
10996 -- flag prevents what would otherwise be an infinite recursion.
10998 if Has_Invariants (Target_Type)
10999 and then Present (Invariant_Procedure (Target_Type))
11000 and then Comes_From_Source (N)
11001 then
11002 Set_Comes_From_Source (N, False);
11003 Remove_Side_Effects (N);
11004 Insert_Action (N, Make_Invariant_Call (Duplicate_Subexpr (N)));
11005 goto Done;
11006 end if;
11008 -- Here if we may need to expand conversion
11010 -- If the operand of the type conversion is an arithmetic operation on
11011 -- signed integers, and the based type of the signed integer type in
11012 -- question is smaller than Standard.Integer, we promote both of the
11013 -- operands to type Integer.
11015 -- For example, if we have
11017 -- target-type (opnd1 + opnd2)
11019 -- and opnd1 and opnd2 are of type short integer, then we rewrite
11020 -- this as:
11022 -- target-type (integer(opnd1) + integer(opnd2))
11024 -- We do this because we are always allowed to compute in a larger type
11025 -- if we do the right thing with the result, and in this case we are
11026 -- going to do a conversion which will do an appropriate check to make
11027 -- sure that things are in range of the target type in any case. This
11028 -- avoids some unnecessary intermediate overflows.
11030 -- We might consider a similar transformation in the case where the
11031 -- target is a real type or a 64-bit integer type, and the operand
11032 -- is an arithmetic operation using a 32-bit integer type. However,
11033 -- we do not bother with this case, because it could cause significant
11034 -- inefficiencies on 32-bit machines. On a 64-bit machine it would be
11035 -- much cheaper, but we don't want different behavior on 32-bit and
11036 -- 64-bit machines. Note that the exclusion of the 64-bit case also
11037 -- handles the configurable run-time cases where 64-bit arithmetic
11038 -- may simply be unavailable.
11040 -- Note: this circuit is partially redundant with respect to the circuit
11041 -- in Checks.Apply_Arithmetic_Overflow_Check, but we catch more cases in
11042 -- the processing here. Also we still need the Checks circuit, since we
11043 -- have to be sure not to generate junk overflow checks in the first
11044 -- place, since it would be trick to remove them here.
11046 if Integer_Promotion_Possible (N) then
11048 -- All conditions met, go ahead with transformation
11050 declare
11051 Opnd : Node_Id;
11052 L, R : Node_Id;
11054 begin
11055 R :=
11056 Make_Type_Conversion (Loc,
11057 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11058 Expression => Relocate_Node (Right_Opnd (Operand)));
11060 Opnd := New_Op_Node (Nkind (Operand), Loc);
11061 Set_Right_Opnd (Opnd, R);
11063 if Nkind (Operand) in N_Binary_Op then
11064 L :=
11065 Make_Type_Conversion (Loc,
11066 Subtype_Mark => New_Occurrence_Of (Standard_Integer, Loc),
11067 Expression => Relocate_Node (Left_Opnd (Operand)));
11069 Set_Left_Opnd (Opnd, L);
11070 end if;
11072 Rewrite (N,
11073 Make_Type_Conversion (Loc,
11074 Subtype_Mark => Relocate_Node (Subtype_Mark (N)),
11075 Expression => Opnd));
11077 Analyze_And_Resolve (N, Target_Type);
11078 goto Done;
11079 end;
11080 end if;
11082 -- Do validity check if validity checking operands
11084 if Validity_Checks_On and Validity_Check_Operands then
11085 Ensure_Valid (Operand);
11086 end if;
11088 -- Special case of converting from non-standard boolean type
11090 if Is_Boolean_Type (Operand_Type)
11091 and then (Nonzero_Is_True (Operand_Type))
11092 then
11093 Adjust_Condition (Operand);
11094 Set_Etype (Operand, Standard_Boolean);
11095 Operand_Type := Standard_Boolean;
11096 end if;
11098 -- Case of converting to an access type
11100 if Is_Access_Type (Target_Type) then
11102 -- If this type conversion was internally generated by the front end
11103 -- to displace the pointer to the object to reference an interface
11104 -- type and the original node was an Unrestricted_Access attribute,
11105 -- then skip applying accessibility checks (because, according to the
11106 -- GNAT Reference Manual, this attribute is similar to 'Access except
11107 -- that all accessibility and aliased view checks are omitted).
11109 if not Comes_From_Source (N)
11110 and then Is_Interface (Designated_Type (Target_Type))
11111 and then Nkind (Original_Node (N)) = N_Attribute_Reference
11112 and then Attribute_Name (Original_Node (N)) =
11113 Name_Unrestricted_Access
11114 then
11115 null;
11117 -- Apply an accessibility check when the conversion operand is an
11118 -- access parameter (or a renaming thereof), unless conversion was
11119 -- expanded from an Unchecked_ or Unrestricted_Access attribute.
11120 -- Note that other checks may still need to be applied below (such
11121 -- as tagged type checks).
11123 elsif Is_Entity_Name (Operand)
11124 and then Has_Extra_Accessibility (Entity (Operand))
11125 and then Ekind (Etype (Operand)) = E_Anonymous_Access_Type
11126 and then (Nkind (Original_Node (N)) /= N_Attribute_Reference
11127 or else Attribute_Name (Original_Node (N)) = Name_Access)
11128 then
11129 Apply_Accessibility_Check
11130 (Operand, Target_Type, Insert_Node => Operand);
11132 -- If the level of the operand type is statically deeper than the
11133 -- level of the target type, then force Program_Error. Note that this
11134 -- can only occur for cases where the attribute is within the body of
11135 -- an instantiation, otherwise the conversion will already have been
11136 -- rejected as illegal.
11138 -- Note: warnings are issued by the analyzer for the instance cases
11140 elsif In_Instance_Body
11142 -- The case where the target type is an anonymous access type of
11143 -- a discriminant is excluded, because the level of such a type
11144 -- depends on the context and currently the level returned for such
11145 -- types is zero, resulting in warnings about about check failures
11146 -- in certain legal cases involving class-wide interfaces as the
11147 -- designated type (some cases, such as return statements, are
11148 -- checked at run time, but not clear if these are handled right
11149 -- in general, see 3.10.2(12/2-12.5/3) ???).
11151 and then
11152 not (Ekind (Target_Type) = E_Anonymous_Access_Type
11153 and then Present (Associated_Node_For_Itype (Target_Type))
11154 and then Nkind (Associated_Node_For_Itype (Target_Type)) =
11155 N_Discriminant_Specification)
11156 and then
11157 Type_Access_Level (Operand_Type) > Type_Access_Level (Target_Type)
11158 then
11159 Raise_Accessibility_Error;
11160 goto Done;
11162 -- When the operand is a selected access discriminant the check needs
11163 -- to be made against the level of the object denoted by the prefix
11164 -- of the selected name. Force Program_Error for this case as well
11165 -- (this accessibility violation can only happen if within the body
11166 -- of an instantiation).
11168 elsif In_Instance_Body
11169 and then Ekind (Operand_Type) = E_Anonymous_Access_Type
11170 and then Nkind (Operand) = N_Selected_Component
11171 and then Object_Access_Level (Operand) >
11172 Type_Access_Level (Target_Type)
11173 then
11174 Raise_Accessibility_Error;
11175 goto Done;
11176 end if;
11177 end if;
11179 -- Case of conversions of tagged types and access to tagged types
11181 -- When needed, that is to say when the expression is class-wide, Add
11182 -- runtime a tag check for (strict) downward conversion by using the
11183 -- membership test, generating:
11185 -- [constraint_error when Operand not in Target_Type'Class]
11187 -- or in the access type case
11189 -- [constraint_error
11190 -- when Operand /= null
11191 -- and then Operand.all not in
11192 -- Designated_Type (Target_Type)'Class]
11194 if (Is_Access_Type (Target_Type)
11195 and then Is_Tagged_Type (Designated_Type (Target_Type)))
11196 or else Is_Tagged_Type (Target_Type)
11197 then
11198 -- Do not do any expansion in the access type case if the parent is a
11199 -- renaming, since this is an error situation which will be caught by
11200 -- Sem_Ch8, and the expansion can interfere with this error check.
11202 if Is_Access_Type (Target_Type) and then Is_Renamed_Object (N) then
11203 goto Done;
11204 end if;
11206 -- Otherwise, proceed with processing tagged conversion
11208 Tagged_Conversion : declare
11209 Actual_Op_Typ : Entity_Id;
11210 Actual_Targ_Typ : Entity_Id;
11211 Make_Conversion : Boolean := False;
11212 Root_Op_Typ : Entity_Id;
11214 procedure Make_Tag_Check (Targ_Typ : Entity_Id);
11215 -- Create a membership check to test whether Operand is a member
11216 -- of Targ_Typ. If the original Target_Type is an access, include
11217 -- a test for null value. The check is inserted at N.
11219 --------------------
11220 -- Make_Tag_Check --
11221 --------------------
11223 procedure Make_Tag_Check (Targ_Typ : Entity_Id) is
11224 Cond : Node_Id;
11226 begin
11227 -- Generate:
11228 -- [Constraint_Error
11229 -- when Operand /= null
11230 -- and then Operand.all not in Targ_Typ]
11232 if Is_Access_Type (Target_Type) then
11233 Cond :=
11234 Make_And_Then (Loc,
11235 Left_Opnd =>
11236 Make_Op_Ne (Loc,
11237 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11238 Right_Opnd => Make_Null (Loc)),
11240 Right_Opnd =>
11241 Make_Not_In (Loc,
11242 Left_Opnd =>
11243 Make_Explicit_Dereference (Loc,
11244 Prefix => Duplicate_Subexpr_No_Checks (Operand)),
11245 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc)));
11247 -- Generate:
11248 -- [Constraint_Error when Operand not in Targ_Typ]
11250 else
11251 Cond :=
11252 Make_Not_In (Loc,
11253 Left_Opnd => Duplicate_Subexpr_No_Checks (Operand),
11254 Right_Opnd => New_Occurrence_Of (Targ_Typ, Loc));
11255 end if;
11257 Insert_Action (N,
11258 Make_Raise_Constraint_Error (Loc,
11259 Condition => Cond,
11260 Reason => CE_Tag_Check_Failed),
11261 Suppress => All_Checks);
11262 end Make_Tag_Check;
11264 -- Start of processing for Tagged_Conversion
11266 begin
11267 -- Handle entities from the limited view
11269 if Is_Access_Type (Operand_Type) then
11270 Actual_Op_Typ :=
11271 Available_View (Designated_Type (Operand_Type));
11272 else
11273 Actual_Op_Typ := Operand_Type;
11274 end if;
11276 if Is_Access_Type (Target_Type) then
11277 Actual_Targ_Typ :=
11278 Available_View (Designated_Type (Target_Type));
11279 else
11280 Actual_Targ_Typ := Target_Type;
11281 end if;
11283 Root_Op_Typ := Root_Type (Actual_Op_Typ);
11285 -- Ada 2005 (AI-251): Handle interface type conversion
11287 if Is_Interface (Actual_Op_Typ)
11288 or else
11289 Is_Interface (Actual_Targ_Typ)
11290 then
11291 Expand_Interface_Conversion (N);
11292 goto Done;
11293 end if;
11295 if not Tag_Checks_Suppressed (Actual_Targ_Typ) then
11297 -- Create a runtime tag check for a downward class-wide type
11298 -- conversion.
11300 if Is_Class_Wide_Type (Actual_Op_Typ)
11301 and then Actual_Op_Typ /= Actual_Targ_Typ
11302 and then Root_Op_Typ /= Actual_Targ_Typ
11303 and then Is_Ancestor (Root_Op_Typ, Actual_Targ_Typ,
11304 Use_Full_View => True)
11305 then
11306 Make_Tag_Check (Class_Wide_Type (Actual_Targ_Typ));
11307 Make_Conversion := True;
11308 end if;
11310 -- AI05-0073: If the result subtype of the function is defined
11311 -- by an access_definition designating a specific tagged type
11312 -- T, a check is made that the result value is null or the tag
11313 -- of the object designated by the result value identifies T.
11314 -- Constraint_Error is raised if this check fails.
11316 if Nkind (Parent (N)) = N_Simple_Return_Statement then
11317 declare
11318 Func : Entity_Id;
11319 Func_Typ : Entity_Id;
11321 begin
11322 -- Climb scope stack looking for the enclosing function
11324 Func := Current_Scope;
11325 while Present (Func)
11326 and then Ekind (Func) /= E_Function
11327 loop
11328 Func := Scope (Func);
11329 end loop;
11331 -- The function's return subtype must be defined using
11332 -- an access definition.
11334 if Nkind (Result_Definition (Parent (Func))) =
11335 N_Access_Definition
11336 then
11337 Func_Typ := Directly_Designated_Type (Etype (Func));
11339 -- The return subtype denotes a specific tagged type,
11340 -- in other words, a non class-wide type.
11342 if Is_Tagged_Type (Func_Typ)
11343 and then not Is_Class_Wide_Type (Func_Typ)
11344 then
11345 Make_Tag_Check (Actual_Targ_Typ);
11346 Make_Conversion := True;
11347 end if;
11348 end if;
11349 end;
11350 end if;
11352 -- We have generated a tag check for either a class-wide type
11353 -- conversion or for AI05-0073.
11355 if Make_Conversion then
11356 declare
11357 Conv : Node_Id;
11358 begin
11359 Conv :=
11360 Make_Unchecked_Type_Conversion (Loc,
11361 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
11362 Expression => Relocate_Node (Expression (N)));
11363 Rewrite (N, Conv);
11364 Analyze_And_Resolve (N, Target_Type);
11365 end;
11366 end if;
11367 end if;
11368 end Tagged_Conversion;
11370 -- Case of other access type conversions
11372 elsif Is_Access_Type (Target_Type) then
11373 Apply_Constraint_Check (Operand, Target_Type);
11375 -- Case of conversions from a fixed-point type
11377 -- These conversions require special expansion and processing, found in
11378 -- the Exp_Fixd package. We ignore cases where Conversion_OK is set,
11379 -- since from a semantic point of view, these are simple integer
11380 -- conversions, which do not need further processing.
11382 elsif Is_Fixed_Point_Type (Operand_Type)
11383 and then not Conversion_OK (N)
11384 then
11385 -- We should never see universal fixed at this case, since the
11386 -- expansion of the constituent divide or multiply should have
11387 -- eliminated the explicit mention of universal fixed.
11389 pragma Assert (Operand_Type /= Universal_Fixed);
11391 -- Check for special case of the conversion to universal real that
11392 -- occurs as a result of the use of a round attribute. In this case,
11393 -- the real type for the conversion is taken from the target type of
11394 -- the Round attribute and the result must be marked as rounded.
11396 if Target_Type = Universal_Real
11397 and then Nkind (Parent (N)) = N_Attribute_Reference
11398 and then Attribute_Name (Parent (N)) = Name_Round
11399 then
11400 Set_Rounded_Result (N);
11401 Set_Etype (N, Etype (Parent (N)));
11402 end if;
11404 -- Otherwise do correct fixed-conversion, but skip these if the
11405 -- Conversion_OK flag is set, because from a semantic point of view
11406 -- these are simple integer conversions needing no further processing
11407 -- (the backend will simply treat them as integers).
11409 if not Conversion_OK (N) then
11410 if Is_Fixed_Point_Type (Etype (N)) then
11411 Expand_Convert_Fixed_To_Fixed (N);
11412 Real_Range_Check;
11414 elsif Is_Integer_Type (Etype (N)) then
11415 Expand_Convert_Fixed_To_Integer (N);
11417 else
11418 pragma Assert (Is_Floating_Point_Type (Etype (N)));
11419 Expand_Convert_Fixed_To_Float (N);
11420 Real_Range_Check;
11421 end if;
11422 end if;
11424 -- Case of conversions to a fixed-point type
11426 -- These conversions require special expansion and processing, found in
11427 -- the Exp_Fixd package. Again, ignore cases where Conversion_OK is set,
11428 -- since from a semantic point of view, these are simple integer
11429 -- conversions, which do not need further processing.
11431 elsif Is_Fixed_Point_Type (Target_Type)
11432 and then not Conversion_OK (N)
11433 then
11434 if Is_Integer_Type (Operand_Type) then
11435 Expand_Convert_Integer_To_Fixed (N);
11436 Real_Range_Check;
11437 else
11438 pragma Assert (Is_Floating_Point_Type (Operand_Type));
11439 Expand_Convert_Float_To_Fixed (N);
11440 Real_Range_Check;
11441 end if;
11443 -- Case of float-to-integer conversions
11445 -- We also handle float-to-fixed conversions with Conversion_OK set
11446 -- since semantically the fixed-point target is treated as though it
11447 -- were an integer in such cases.
11449 elsif Is_Floating_Point_Type (Operand_Type)
11450 and then
11451 (Is_Integer_Type (Target_Type)
11452 or else
11453 (Is_Fixed_Point_Type (Target_Type) and then Conversion_OK (N)))
11454 then
11455 -- One more check here, gcc is still not able to do conversions of
11456 -- this type with proper overflow checking, and so gigi is doing an
11457 -- approximation of what is required by doing floating-point compares
11458 -- with the end-point. But that can lose precision in some cases, and
11459 -- give a wrong result. Converting the operand to Universal_Real is
11460 -- helpful, but still does not catch all cases with 64-bit integers
11461 -- on targets with only 64-bit floats.
11463 -- The above comment seems obsoleted by Apply_Float_Conversion_Check
11464 -- Can this code be removed ???
11466 if Do_Range_Check (Operand) then
11467 Rewrite (Operand,
11468 Make_Type_Conversion (Loc,
11469 Subtype_Mark =>
11470 New_Occurrence_Of (Universal_Real, Loc),
11471 Expression =>
11472 Relocate_Node (Operand)));
11474 Set_Etype (Operand, Universal_Real);
11475 Enable_Range_Check (Operand);
11476 Set_Do_Range_Check (Expression (Operand), False);
11477 end if;
11479 -- Case of array conversions
11481 -- Expansion of array conversions, add required length/range checks but
11482 -- only do this if there is no change of representation. For handling of
11483 -- this case, see Handle_Changed_Representation.
11485 elsif Is_Array_Type (Target_Type) then
11486 if Is_Constrained (Target_Type) then
11487 Apply_Length_Check (Operand, Target_Type);
11488 else
11489 Apply_Range_Check (Operand, Target_Type);
11490 end if;
11492 Handle_Changed_Representation;
11494 -- Case of conversions of discriminated types
11496 -- Add required discriminant checks if target is constrained. Again this
11497 -- change is skipped if we have a change of representation.
11499 elsif Has_Discriminants (Target_Type)
11500 and then Is_Constrained (Target_Type)
11501 then
11502 Apply_Discriminant_Check (Operand, Target_Type);
11503 Handle_Changed_Representation;
11505 -- Case of all other record conversions. The only processing required
11506 -- is to check for a change of representation requiring the special
11507 -- assignment processing.
11509 elsif Is_Record_Type (Target_Type) then
11511 -- Ada 2005 (AI-216): Program_Error is raised when converting from
11512 -- a derived Unchecked_Union type to an unconstrained type that is
11513 -- not Unchecked_Union if the operand lacks inferable discriminants.
11515 if Is_Derived_Type (Operand_Type)
11516 and then Is_Unchecked_Union (Base_Type (Operand_Type))
11517 and then not Is_Constrained (Target_Type)
11518 and then not Is_Unchecked_Union (Base_Type (Target_Type))
11519 and then not Has_Inferable_Discriminants (Operand)
11520 then
11521 -- To prevent Gigi from generating illegal code, we generate a
11522 -- Program_Error node, but we give it the target type of the
11523 -- conversion (is this requirement documented somewhere ???)
11525 declare
11526 PE : constant Node_Id := Make_Raise_Program_Error (Loc,
11527 Reason => PE_Unchecked_Union_Restriction);
11529 begin
11530 Set_Etype (PE, Target_Type);
11531 Rewrite (N, PE);
11533 end;
11534 else
11535 Handle_Changed_Representation;
11536 end if;
11538 -- Case of conversions of enumeration types
11540 elsif Is_Enumeration_Type (Target_Type) then
11542 -- Special processing is required if there is a change of
11543 -- representation (from enumeration representation clauses).
11545 if not Same_Representation (Target_Type, Operand_Type) then
11547 -- Convert: x(y) to x'val (ytyp'val (y))
11549 Rewrite (N,
11550 Make_Attribute_Reference (Loc,
11551 Prefix => New_Occurrence_Of (Target_Type, Loc),
11552 Attribute_Name => Name_Val,
11553 Expressions => New_List (
11554 Make_Attribute_Reference (Loc,
11555 Prefix => New_Occurrence_Of (Operand_Type, Loc),
11556 Attribute_Name => Name_Pos,
11557 Expressions => New_List (Operand)))));
11559 Analyze_And_Resolve (N, Target_Type);
11560 end if;
11562 -- Case of conversions to floating-point
11564 elsif Is_Floating_Point_Type (Target_Type) then
11565 Real_Range_Check;
11566 end if;
11568 -- At this stage, either the conversion node has been transformed into
11569 -- some other equivalent expression, or left as a conversion that can be
11570 -- handled by Gigi, in the following cases:
11572 -- Conversions with no change of representation or type
11574 -- Numeric conversions involving integer, floating- and fixed-point
11575 -- values. Fixed-point values are allowed only if Conversion_OK is
11576 -- set, i.e. if the fixed-point values are to be treated as integers.
11578 -- No other conversions should be passed to Gigi
11580 -- Check: are these rules stated in sinfo??? if so, why restate here???
11582 -- The only remaining step is to generate a range check if we still have
11583 -- a type conversion at this stage and Do_Range_Check is set. For now we
11584 -- do this only for conversions of discrete types and for float-to-float
11585 -- conversions.
11587 if Nkind (N) = N_Type_Conversion then
11589 -- For now we only support floating-point cases where both source
11590 -- and target are floating-point types. Conversions where the source
11591 -- and target involve integer or fixed-point types are still TBD,
11592 -- though not clear whether those can even happen at this point, due
11593 -- to transformations above. ???
11595 if Is_Floating_Point_Type (Etype (N))
11596 and then Is_Floating_Point_Type (Etype (Expression (N)))
11597 then
11598 if Do_Range_Check (Expression (N))
11599 and then Is_Floating_Point_Type (Target_Type)
11600 then
11601 Generate_Range_Check
11602 (Expression (N), Target_Type, CE_Range_Check_Failed);
11603 end if;
11605 -- Discrete-to-discrete conversions
11607 elsif Is_Discrete_Type (Etype (N)) then
11608 declare
11609 Expr : constant Node_Id := Expression (N);
11610 Ftyp : Entity_Id;
11611 Ityp : Entity_Id;
11613 begin
11614 if Do_Range_Check (Expr)
11615 and then Is_Discrete_Type (Etype (Expr))
11616 then
11617 Set_Do_Range_Check (Expr, False);
11619 -- Before we do a range check, we have to deal with treating
11620 -- a fixed-point operand as an integer. The way we do this
11621 -- is simply to do an unchecked conversion to an appropriate
11622 -- integer type large enough to hold the result.
11624 -- This code is not active yet, because we are only dealing
11625 -- with discrete types so far ???
11627 if Nkind (Expr) in N_Has_Treat_Fixed_As_Integer
11628 and then Treat_Fixed_As_Integer (Expr)
11629 then
11630 Ftyp := Base_Type (Etype (Expr));
11632 if Esize (Ftyp) >= Esize (Standard_Integer) then
11633 Ityp := Standard_Long_Long_Integer;
11634 else
11635 Ityp := Standard_Integer;
11636 end if;
11638 Rewrite (Expr, Unchecked_Convert_To (Ityp, Expr));
11639 end if;
11641 -- Reset overflow flag, since the range check will include
11642 -- dealing with possible overflow, and generate the check.
11643 -- If Address is either a source type or target type,
11644 -- suppress range check to avoid typing anomalies when
11645 -- it is a visible integer type.
11647 Set_Do_Overflow_Check (N, False);
11649 if not Is_Descendant_Of_Address (Etype (Expr))
11650 and then not Is_Descendant_Of_Address (Target_Type)
11651 then
11652 Generate_Range_Check
11653 (Expr, Target_Type, CE_Range_Check_Failed);
11654 end if;
11655 end if;
11656 end;
11657 end if;
11658 end if;
11660 -- Here at end of processing
11662 <<Done>>
11663 -- Apply predicate check if required. Note that we can't just call
11664 -- Apply_Predicate_Check here, because the type looks right after
11665 -- the conversion and it would omit the check. The Comes_From_Source
11666 -- guard is necessary to prevent infinite recursions when we generate
11667 -- internal conversions for the purpose of checking predicates.
11669 if Present (Predicate_Function (Target_Type))
11670 and then not Predicates_Ignored (Target_Type)
11671 and then Target_Type /= Operand_Type
11672 and then Comes_From_Source (N)
11673 then
11674 declare
11675 New_Expr : constant Node_Id := Duplicate_Subexpr (N);
11677 begin
11678 -- Avoid infinite recursion on the subsequent expansion of
11679 -- of the copy of the original type conversion.
11681 Set_Comes_From_Source (New_Expr, False);
11682 Insert_Action (N, Make_Predicate_Check (Target_Type, New_Expr));
11683 end;
11684 end if;
11685 end Expand_N_Type_Conversion;
11687 -----------------------------------
11688 -- Expand_N_Unchecked_Expression --
11689 -----------------------------------
11691 -- Remove the unchecked expression node from the tree. Its job was simply
11692 -- to make sure that its constituent expression was handled with checks
11693 -- off, and now that that is done, we can remove it from the tree, and
11694 -- indeed must, since Gigi does not expect to see these nodes.
11696 procedure Expand_N_Unchecked_Expression (N : Node_Id) is
11697 Exp : constant Node_Id := Expression (N);
11698 begin
11699 Set_Assignment_OK (Exp, Assignment_OK (N) or else Assignment_OK (Exp));
11700 Rewrite (N, Exp);
11701 end Expand_N_Unchecked_Expression;
11703 ----------------------------------------
11704 -- Expand_N_Unchecked_Type_Conversion --
11705 ----------------------------------------
11707 -- If this cannot be handled by Gigi and we haven't already made a
11708 -- temporary for it, do it now.
11710 procedure Expand_N_Unchecked_Type_Conversion (N : Node_Id) is
11711 Target_Type : constant Entity_Id := Etype (N);
11712 Operand : constant Node_Id := Expression (N);
11713 Operand_Type : constant Entity_Id := Etype (Operand);
11715 begin
11716 -- Nothing at all to do if conversion is to the identical type so remove
11717 -- the conversion completely, it is useless, except that it may carry
11718 -- an Assignment_OK indication which must be propagated to the operand.
11720 if Operand_Type = Target_Type then
11722 -- Code duplicates Expand_N_Unchecked_Expression above, factor???
11724 if Assignment_OK (N) then
11725 Set_Assignment_OK (Operand);
11726 end if;
11728 Rewrite (N, Relocate_Node (Operand));
11729 return;
11730 end if;
11732 -- If we have a conversion of a compile time known value to a target
11733 -- type and the value is in range of the target type, then we can simply
11734 -- replace the construct by an integer literal of the correct type. We
11735 -- only apply this to integer types being converted. Possibly it may
11736 -- apply in other cases, but it is too much trouble to worry about.
11738 -- Note that we do not do this transformation if the Kill_Range_Check
11739 -- flag is set, since then the value may be outside the expected range.
11740 -- This happens in the Normalize_Scalars case.
11742 -- We also skip this if either the target or operand type is biased
11743 -- because in this case, the unchecked conversion is supposed to
11744 -- preserve the bit pattern, not the integer value.
11746 if Is_Integer_Type (Target_Type)
11747 and then not Has_Biased_Representation (Target_Type)
11748 and then Is_Integer_Type (Operand_Type)
11749 and then not Has_Biased_Representation (Operand_Type)
11750 and then Compile_Time_Known_Value (Operand)
11751 and then not Kill_Range_Check (N)
11752 then
11753 declare
11754 Val : constant Uint := Expr_Value (Operand);
11756 begin
11757 if Compile_Time_Known_Value (Type_Low_Bound (Target_Type))
11758 and then
11759 Compile_Time_Known_Value (Type_High_Bound (Target_Type))
11760 and then
11761 Val >= Expr_Value (Type_Low_Bound (Target_Type))
11762 and then
11763 Val <= Expr_Value (Type_High_Bound (Target_Type))
11764 then
11765 Rewrite (N, Make_Integer_Literal (Sloc (N), Val));
11767 -- If Address is the target type, just set the type to avoid a
11768 -- spurious type error on the literal when Address is a visible
11769 -- integer type.
11771 if Is_Descendant_Of_Address (Target_Type) then
11772 Set_Etype (N, Target_Type);
11773 else
11774 Analyze_And_Resolve (N, Target_Type);
11775 end if;
11777 return;
11778 end if;
11779 end;
11780 end if;
11782 -- Nothing to do if conversion is safe
11784 if Safe_Unchecked_Type_Conversion (N) then
11785 return;
11786 end if;
11788 -- Otherwise force evaluation unless Assignment_OK flag is set (this
11789 -- flag indicates ??? More comments needed here)
11791 if Assignment_OK (N) then
11792 null;
11793 else
11794 Force_Evaluation (N);
11795 end if;
11796 end Expand_N_Unchecked_Type_Conversion;
11798 ----------------------------
11799 -- Expand_Record_Equality --
11800 ----------------------------
11802 -- For non-variant records, Equality is expanded when needed into:
11804 -- and then Lhs.Discr1 = Rhs.Discr1
11805 -- and then ...
11806 -- and then Lhs.Discrn = Rhs.Discrn
11807 -- and then Lhs.Cmp1 = Rhs.Cmp1
11808 -- and then ...
11809 -- and then Lhs.Cmpn = Rhs.Cmpn
11811 -- The expression is folded by the back-end for adjacent fields. This
11812 -- function is called for tagged record in only one occasion: for imple-
11813 -- menting predefined primitive equality (see Predefined_Primitives_Bodies)
11814 -- otherwise the primitive "=" is used directly.
11816 function Expand_Record_Equality
11817 (Nod : Node_Id;
11818 Typ : Entity_Id;
11819 Lhs : Node_Id;
11820 Rhs : Node_Id;
11821 Bodies : List_Id) return Node_Id
11823 Loc : constant Source_Ptr := Sloc (Nod);
11825 Result : Node_Id;
11826 C : Entity_Id;
11828 First_Time : Boolean := True;
11830 function Element_To_Compare (C : Entity_Id) return Entity_Id;
11831 -- Return the next discriminant or component to compare, starting with
11832 -- C, skipping inherited components.
11834 ------------------------
11835 -- Element_To_Compare --
11836 ------------------------
11838 function Element_To_Compare (C : Entity_Id) return Entity_Id is
11839 Comp : Entity_Id;
11841 begin
11842 Comp := C;
11843 loop
11844 -- Exit loop when the next element to be compared is found, or
11845 -- there is no more such element.
11847 exit when No (Comp);
11849 exit when Ekind_In (Comp, E_Discriminant, E_Component)
11850 and then not (
11852 -- Skip inherited components
11854 -- Note: for a tagged type, we always generate the "=" primitive
11855 -- for the base type (not on the first subtype), so the test for
11856 -- Comp /= Original_Record_Component (Comp) is True for
11857 -- inherited components only.
11859 (Is_Tagged_Type (Typ)
11860 and then Comp /= Original_Record_Component (Comp))
11862 -- Skip _Tag
11864 or else Chars (Comp) = Name_uTag
11866 -- Skip interface elements (secondary tags???)
11868 or else Is_Interface (Etype (Comp)));
11870 Next_Entity (Comp);
11871 end loop;
11873 return Comp;
11874 end Element_To_Compare;
11876 -- Start of processing for Expand_Record_Equality
11878 begin
11879 -- Generates the following code: (assuming that Typ has one Discr and
11880 -- component C2 is also a record)
11882 -- True
11883 -- and then Lhs.Discr1 = Rhs.Discr1
11884 -- and then Lhs.C1 = Rhs.C1
11885 -- and then Lhs.C2.C1=Rhs.C2.C1 and then ... Lhs.C2.Cn=Rhs.C2.Cn
11886 -- and then ...
11887 -- and then Lhs.Cmpn = Rhs.Cmpn
11889 Result := New_Occurrence_Of (Standard_True, Loc);
11890 C := Element_To_Compare (First_Entity (Typ));
11891 while Present (C) loop
11892 declare
11893 New_Lhs : Node_Id;
11894 New_Rhs : Node_Id;
11895 Check : Node_Id;
11897 begin
11898 if First_Time then
11899 First_Time := False;
11900 New_Lhs := Lhs;
11901 New_Rhs := Rhs;
11902 else
11903 New_Lhs := New_Copy_Tree (Lhs);
11904 New_Rhs := New_Copy_Tree (Rhs);
11905 end if;
11907 Check :=
11908 Expand_Composite_Equality (Nod, Etype (C),
11909 Lhs =>
11910 Make_Selected_Component (Loc,
11911 Prefix => New_Lhs,
11912 Selector_Name => New_Occurrence_Of (C, Loc)),
11913 Rhs =>
11914 Make_Selected_Component (Loc,
11915 Prefix => New_Rhs,
11916 Selector_Name => New_Occurrence_Of (C, Loc)),
11917 Bodies => Bodies);
11919 -- If some (sub)component is an unchecked_union, the whole
11920 -- operation will raise program error.
11922 if Nkind (Check) = N_Raise_Program_Error then
11923 Result := Check;
11924 Set_Etype (Result, Standard_Boolean);
11925 exit;
11926 else
11927 Result :=
11928 Make_And_Then (Loc,
11929 Left_Opnd => Result,
11930 Right_Opnd => Check);
11931 end if;
11932 end;
11934 C := Element_To_Compare (Next_Entity (C));
11935 end loop;
11937 return Result;
11938 end Expand_Record_Equality;
11940 ---------------------------
11941 -- Expand_Set_Membership --
11942 ---------------------------
11944 procedure Expand_Set_Membership (N : Node_Id) is
11945 Lop : constant Node_Id := Left_Opnd (N);
11946 Alt : Node_Id;
11947 Res : Node_Id;
11949 function Make_Cond (Alt : Node_Id) return Node_Id;
11950 -- If the alternative is a subtype mark, create a simple membership
11951 -- test. Otherwise create an equality test for it.
11953 ---------------
11954 -- Make_Cond --
11955 ---------------
11957 function Make_Cond (Alt : Node_Id) return Node_Id is
11958 Cond : Node_Id;
11959 L : constant Node_Id := New_Copy (Lop);
11960 R : constant Node_Id := Relocate_Node (Alt);
11962 begin
11963 if (Is_Entity_Name (Alt) and then Is_Type (Entity (Alt)))
11964 or else Nkind (Alt) = N_Range
11965 then
11966 Cond :=
11967 Make_In (Sloc (Alt),
11968 Left_Opnd => L,
11969 Right_Opnd => R);
11970 else
11971 Cond :=
11972 Make_Op_Eq (Sloc (Alt),
11973 Left_Opnd => L,
11974 Right_Opnd => R);
11975 end if;
11977 return Cond;
11978 end Make_Cond;
11980 -- Start of processing for Expand_Set_Membership
11982 begin
11983 Remove_Side_Effects (Lop);
11985 Alt := Last (Alternatives (N));
11986 Res := Make_Cond (Alt);
11988 Prev (Alt);
11989 while Present (Alt) loop
11990 Res :=
11991 Make_Or_Else (Sloc (Alt),
11992 Left_Opnd => Make_Cond (Alt),
11993 Right_Opnd => Res);
11994 Prev (Alt);
11995 end loop;
11997 Rewrite (N, Res);
11998 Analyze_And_Resolve (N, Standard_Boolean);
11999 end Expand_Set_Membership;
12001 -----------------------------------
12002 -- Expand_Short_Circuit_Operator --
12003 -----------------------------------
12005 -- Deal with special expansion if actions are present for the right operand
12006 -- and deal with optimizing case of arguments being True or False. We also
12007 -- deal with the special case of non-standard boolean values.
12009 procedure Expand_Short_Circuit_Operator (N : Node_Id) is
12010 Loc : constant Source_Ptr := Sloc (N);
12011 Typ : constant Entity_Id := Etype (N);
12012 Left : constant Node_Id := Left_Opnd (N);
12013 Right : constant Node_Id := Right_Opnd (N);
12014 LocR : constant Source_Ptr := Sloc (Right);
12015 Actlist : List_Id;
12017 Shortcut_Value : constant Boolean := Nkind (N) = N_Or_Else;
12018 Shortcut_Ent : constant Entity_Id := Boolean_Literals (Shortcut_Value);
12019 -- If Left = Shortcut_Value then Right need not be evaluated
12021 function Make_Test_Expr (Opnd : Node_Id) return Node_Id;
12022 -- For Opnd a boolean expression, return a Boolean expression equivalent
12023 -- to Opnd /= Shortcut_Value.
12025 --------------------
12026 -- Make_Test_Expr --
12027 --------------------
12029 function Make_Test_Expr (Opnd : Node_Id) return Node_Id is
12030 begin
12031 if Shortcut_Value then
12032 return Make_Op_Not (Sloc (Opnd), Opnd);
12033 else
12034 return Opnd;
12035 end if;
12036 end Make_Test_Expr;
12038 -- Local variables
12040 Op_Var : Entity_Id;
12041 -- Entity for a temporary variable holding the value of the operator,
12042 -- used for expansion in the case where actions are present.
12044 -- Start of processing for Expand_Short_Circuit_Operator
12046 begin
12047 -- Deal with non-standard booleans
12049 if Is_Boolean_Type (Typ) then
12050 Adjust_Condition (Left);
12051 Adjust_Condition (Right);
12052 Set_Etype (N, Standard_Boolean);
12053 end if;
12055 -- Check for cases where left argument is known to be True or False
12057 if Compile_Time_Known_Value (Left) then
12059 -- Mark SCO for left condition as compile time known
12061 if Generate_SCO and then Comes_From_Source (Left) then
12062 Set_SCO_Condition (Left, Expr_Value_E (Left) = Standard_True);
12063 end if;
12065 -- Rewrite True AND THEN Right / False OR ELSE Right to Right.
12066 -- Any actions associated with Right will be executed unconditionally
12067 -- and can thus be inserted into the tree unconditionally.
12069 if Expr_Value_E (Left) /= Shortcut_Ent then
12070 if Present (Actions (N)) then
12071 Insert_Actions (N, Actions (N));
12072 end if;
12074 Rewrite (N, Right);
12076 -- Rewrite False AND THEN Right / True OR ELSE Right to Left.
12077 -- In this case we can forget the actions associated with Right,
12078 -- since they will never be executed.
12080 else
12081 Kill_Dead_Code (Right);
12082 Kill_Dead_Code (Actions (N));
12083 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12084 end if;
12086 Adjust_Result_Type (N, Typ);
12087 return;
12088 end if;
12090 -- If Actions are present for the right operand, we have to do some
12091 -- special processing. We can't just let these actions filter back into
12092 -- code preceding the short circuit (which is what would have happened
12093 -- if we had not trapped them in the short-circuit form), since they
12094 -- must only be executed if the right operand of the short circuit is
12095 -- executed and not otherwise.
12097 if Present (Actions (N)) then
12098 Actlist := Actions (N);
12100 -- The old approach is to expand:
12102 -- left AND THEN right
12104 -- into
12106 -- C : Boolean := False;
12107 -- IF left THEN
12108 -- Actions;
12109 -- IF right THEN
12110 -- C := True;
12111 -- END IF;
12112 -- END IF;
12114 -- and finally rewrite the operator into a reference to C. Similarly
12115 -- for left OR ELSE right, with negated values. Note that this
12116 -- rewrite causes some difficulties for coverage analysis because
12117 -- of the introduction of the new variable C, which obscures the
12118 -- structure of the test.
12120 -- We use this "old approach" if Minimize_Expression_With_Actions
12121 -- is True.
12123 if Minimize_Expression_With_Actions then
12124 Op_Var := Make_Temporary (Loc, 'C', Related_Node => N);
12126 Insert_Action (N,
12127 Make_Object_Declaration (Loc,
12128 Defining_Identifier => Op_Var,
12129 Object_Definition =>
12130 New_Occurrence_Of (Standard_Boolean, Loc),
12131 Expression =>
12132 New_Occurrence_Of (Shortcut_Ent, Loc)));
12134 Append_To (Actlist,
12135 Make_Implicit_If_Statement (Right,
12136 Condition => Make_Test_Expr (Right),
12137 Then_Statements => New_List (
12138 Make_Assignment_Statement (LocR,
12139 Name => New_Occurrence_Of (Op_Var, LocR),
12140 Expression =>
12141 New_Occurrence_Of
12142 (Boolean_Literals (not Shortcut_Value), LocR)))));
12144 Insert_Action (N,
12145 Make_Implicit_If_Statement (Left,
12146 Condition => Make_Test_Expr (Left),
12147 Then_Statements => Actlist));
12149 Rewrite (N, New_Occurrence_Of (Op_Var, Loc));
12150 Analyze_And_Resolve (N, Standard_Boolean);
12152 -- The new approach (the default) is to use an
12153 -- Expression_With_Actions node for the right operand of the
12154 -- short-circuit form. Note that this solves the traceability
12155 -- problems for coverage analysis.
12157 else
12158 Rewrite (Right,
12159 Make_Expression_With_Actions (LocR,
12160 Expression => Relocate_Node (Right),
12161 Actions => Actlist));
12163 Set_Actions (N, No_List);
12164 Analyze_And_Resolve (Right, Standard_Boolean);
12165 end if;
12167 Adjust_Result_Type (N, Typ);
12168 return;
12169 end if;
12171 -- No actions present, check for cases of right argument True/False
12173 if Compile_Time_Known_Value (Right) then
12175 -- Mark SCO for left condition as compile time known
12177 if Generate_SCO and then Comes_From_Source (Right) then
12178 Set_SCO_Condition (Right, Expr_Value_E (Right) = Standard_True);
12179 end if;
12181 -- Change (Left and then True), (Left or else False) to Left. Note
12182 -- that we know there are no actions associated with the right
12183 -- operand, since we just checked for this case above.
12185 if Expr_Value_E (Right) /= Shortcut_Ent then
12186 Rewrite (N, Left);
12188 -- Change (Left and then False), (Left or else True) to Right,
12189 -- making sure to preserve any side effects associated with the Left
12190 -- operand.
12192 else
12193 Remove_Side_Effects (Left);
12194 Rewrite (N, New_Occurrence_Of (Shortcut_Ent, Loc));
12195 end if;
12196 end if;
12198 Adjust_Result_Type (N, Typ);
12199 end Expand_Short_Circuit_Operator;
12201 -------------------------------------
12202 -- Fixup_Universal_Fixed_Operation --
12203 -------------------------------------
12205 procedure Fixup_Universal_Fixed_Operation (N : Node_Id) is
12206 Conv : constant Node_Id := Parent (N);
12208 begin
12209 -- We must have a type conversion immediately above us
12211 pragma Assert (Nkind (Conv) = N_Type_Conversion);
12213 -- Normally the type conversion gives our target type. The exception
12214 -- occurs in the case of the Round attribute, where the conversion
12215 -- will be to universal real, and our real type comes from the Round
12216 -- attribute (as well as an indication that we must round the result)
12218 if Nkind (Parent (Conv)) = N_Attribute_Reference
12219 and then Attribute_Name (Parent (Conv)) = Name_Round
12220 then
12221 Set_Etype (N, Etype (Parent (Conv)));
12222 Set_Rounded_Result (N);
12224 -- Normal case where type comes from conversion above us
12226 else
12227 Set_Etype (N, Etype (Conv));
12228 end if;
12229 end Fixup_Universal_Fixed_Operation;
12231 ---------------------------------
12232 -- Has_Inferable_Discriminants --
12233 ---------------------------------
12235 function Has_Inferable_Discriminants (N : Node_Id) return Boolean is
12237 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean;
12238 -- Determines whether the left-most prefix of a selected component is a
12239 -- formal parameter in a subprogram. Assumes N is a selected component.
12241 --------------------------------
12242 -- Prefix_Is_Formal_Parameter --
12243 --------------------------------
12245 function Prefix_Is_Formal_Parameter (N : Node_Id) return Boolean is
12246 Sel_Comp : Node_Id;
12248 begin
12249 -- Move to the left-most prefix by climbing up the tree
12251 Sel_Comp := N;
12252 while Present (Parent (Sel_Comp))
12253 and then Nkind (Parent (Sel_Comp)) = N_Selected_Component
12254 loop
12255 Sel_Comp := Parent (Sel_Comp);
12256 end loop;
12258 return Ekind (Entity (Prefix (Sel_Comp))) in Formal_Kind;
12259 end Prefix_Is_Formal_Parameter;
12261 -- Start of processing for Has_Inferable_Discriminants
12263 begin
12264 -- For selected components, the subtype of the selector must be a
12265 -- constrained Unchecked_Union. If the component is subject to a
12266 -- per-object constraint, then the enclosing object must have inferable
12267 -- discriminants.
12269 if Nkind (N) = N_Selected_Component then
12270 if Has_Per_Object_Constraint (Entity (Selector_Name (N))) then
12272 -- A small hack. If we have a per-object constrained selected
12273 -- component of a formal parameter, return True since we do not
12274 -- know the actual parameter association yet.
12276 if Prefix_Is_Formal_Parameter (N) then
12277 return True;
12279 -- Otherwise, check the enclosing object and the selector
12281 else
12282 return Has_Inferable_Discriminants (Prefix (N))
12283 and then Has_Inferable_Discriminants (Selector_Name (N));
12284 end if;
12286 -- The call to Has_Inferable_Discriminants will determine whether
12287 -- the selector has a constrained Unchecked_Union nominal type.
12289 else
12290 return Has_Inferable_Discriminants (Selector_Name (N));
12291 end if;
12293 -- A qualified expression has inferable discriminants if its subtype
12294 -- mark is a constrained Unchecked_Union subtype.
12296 elsif Nkind (N) = N_Qualified_Expression then
12297 return Is_Unchecked_Union (Etype (Subtype_Mark (N)))
12298 and then Is_Constrained (Etype (Subtype_Mark (N)));
12300 -- For all other names, it is sufficient to have a constrained
12301 -- Unchecked_Union nominal subtype.
12303 else
12304 return Is_Unchecked_Union (Base_Type (Etype (N)))
12305 and then Is_Constrained (Etype (N));
12306 end if;
12307 end Has_Inferable_Discriminants;
12309 -------------------------------
12310 -- Insert_Dereference_Action --
12311 -------------------------------
12313 procedure Insert_Dereference_Action (N : Node_Id) is
12314 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean;
12315 -- Return true if type of P is derived from Checked_Pool;
12317 -----------------------------
12318 -- Is_Checked_Storage_Pool --
12319 -----------------------------
12321 function Is_Checked_Storage_Pool (P : Entity_Id) return Boolean is
12322 T : Entity_Id;
12324 begin
12325 if No (P) then
12326 return False;
12327 end if;
12329 T := Etype (P);
12330 while T /= Etype (T) loop
12331 if Is_RTE (T, RE_Checked_Pool) then
12332 return True;
12333 else
12334 T := Etype (T);
12335 end if;
12336 end loop;
12338 return False;
12339 end Is_Checked_Storage_Pool;
12341 -- Local variables
12343 Context : constant Node_Id := Parent (N);
12344 Ptr_Typ : constant Entity_Id := Etype (N);
12345 Desig_Typ : constant Entity_Id :=
12346 Available_View (Designated_Type (Ptr_Typ));
12347 Loc : constant Source_Ptr := Sloc (N);
12348 Pool : constant Entity_Id := Associated_Storage_Pool (Ptr_Typ);
12350 Addr : Entity_Id;
12351 Alig : Entity_Id;
12352 Deref : Node_Id;
12353 Size : Entity_Id;
12354 Size_Bits : Node_Id;
12355 Stmt : Node_Id;
12357 -- Start of processing for Insert_Dereference_Action
12359 begin
12360 pragma Assert (Nkind (Context) = N_Explicit_Dereference);
12362 -- Do not re-expand a dereference which has already been processed by
12363 -- this routine.
12365 if Has_Dereference_Action (Context) then
12366 return;
12368 -- Do not perform this type of expansion for internally-generated
12369 -- dereferences.
12371 elsif not Comes_From_Source (Original_Node (Context)) then
12372 return;
12374 -- A dereference action is only applicable to objects which have been
12375 -- allocated on a checked pool.
12377 elsif not Is_Checked_Storage_Pool (Pool) then
12378 return;
12379 end if;
12381 -- Extract the address of the dereferenced object. Generate:
12383 -- Addr : System.Address := <N>'Pool_Address;
12385 Addr := Make_Temporary (Loc, 'P');
12387 Insert_Action (N,
12388 Make_Object_Declaration (Loc,
12389 Defining_Identifier => Addr,
12390 Object_Definition =>
12391 New_Occurrence_Of (RTE (RE_Address), Loc),
12392 Expression =>
12393 Make_Attribute_Reference (Loc,
12394 Prefix => Duplicate_Subexpr_Move_Checks (N),
12395 Attribute_Name => Name_Pool_Address)));
12397 -- Calculate the size of the dereferenced object. Generate:
12399 -- Size : Storage_Count := <N>.all'Size / Storage_Unit;
12401 Deref :=
12402 Make_Explicit_Dereference (Loc,
12403 Prefix => Duplicate_Subexpr_Move_Checks (N));
12404 Set_Has_Dereference_Action (Deref);
12406 Size_Bits :=
12407 Make_Attribute_Reference (Loc,
12408 Prefix => Deref,
12409 Attribute_Name => Name_Size);
12411 -- Special case of an unconstrained array: need to add descriptor size
12413 if Is_Array_Type (Desig_Typ)
12414 and then not Is_Constrained (First_Subtype (Desig_Typ))
12415 then
12416 Size_Bits :=
12417 Make_Op_Add (Loc,
12418 Left_Opnd =>
12419 Make_Attribute_Reference (Loc,
12420 Prefix =>
12421 New_Occurrence_Of (First_Subtype (Desig_Typ), Loc),
12422 Attribute_Name => Name_Descriptor_Size),
12423 Right_Opnd => Size_Bits);
12424 end if;
12426 Size := Make_Temporary (Loc, 'S');
12427 Insert_Action (N,
12428 Make_Object_Declaration (Loc,
12429 Defining_Identifier => Size,
12430 Object_Definition =>
12431 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12432 Expression =>
12433 Make_Op_Divide (Loc,
12434 Left_Opnd => Size_Bits,
12435 Right_Opnd => Make_Integer_Literal (Loc, System_Storage_Unit))));
12437 -- Calculate the alignment of the dereferenced object. Generate:
12438 -- Alig : constant Storage_Count := <N>.all'Alignment;
12440 Deref :=
12441 Make_Explicit_Dereference (Loc,
12442 Prefix => Duplicate_Subexpr_Move_Checks (N));
12443 Set_Has_Dereference_Action (Deref);
12445 Alig := Make_Temporary (Loc, 'A');
12446 Insert_Action (N,
12447 Make_Object_Declaration (Loc,
12448 Defining_Identifier => Alig,
12449 Object_Definition =>
12450 New_Occurrence_Of (RTE (RE_Storage_Count), Loc),
12451 Expression =>
12452 Make_Attribute_Reference (Loc,
12453 Prefix => Deref,
12454 Attribute_Name => Name_Alignment)));
12456 -- A dereference of a controlled object requires special processing. The
12457 -- finalization machinery requests additional space from the underlying
12458 -- pool to allocate and hide two pointers. As a result, a checked pool
12459 -- may mark the wrong memory as valid. Since checked pools do not have
12460 -- knowledge of hidden pointers, we have to bring the two pointers back
12461 -- in view in order to restore the original state of the object.
12463 -- The address manipulation is not performed for access types that are
12464 -- subject to pragma No_Heap_Finalization because the two pointers do
12465 -- not exist in the first place.
12467 if No_Heap_Finalization (Ptr_Typ) then
12468 null;
12470 elsif Needs_Finalization (Desig_Typ) then
12472 -- Adjust the address and size of the dereferenced object. Generate:
12473 -- Adjust_Controlled_Dereference (Addr, Size, Alig);
12475 Stmt :=
12476 Make_Procedure_Call_Statement (Loc,
12477 Name =>
12478 New_Occurrence_Of (RTE (RE_Adjust_Controlled_Dereference), Loc),
12479 Parameter_Associations => New_List (
12480 New_Occurrence_Of (Addr, Loc),
12481 New_Occurrence_Of (Size, Loc),
12482 New_Occurrence_Of (Alig, Loc)));
12484 -- Class-wide types complicate things because we cannot determine
12485 -- statically whether the actual object is truly controlled. We must
12486 -- generate a runtime check to detect this property. Generate:
12488 -- if Needs_Finalization (<N>.all'Tag) then
12489 -- <Stmt>;
12490 -- end if;
12492 if Is_Class_Wide_Type (Desig_Typ) then
12493 Deref :=
12494 Make_Explicit_Dereference (Loc,
12495 Prefix => Duplicate_Subexpr_Move_Checks (N));
12496 Set_Has_Dereference_Action (Deref);
12498 Stmt :=
12499 Make_Implicit_If_Statement (N,
12500 Condition =>
12501 Make_Function_Call (Loc,
12502 Name =>
12503 New_Occurrence_Of (RTE (RE_Needs_Finalization), Loc),
12504 Parameter_Associations => New_List (
12505 Make_Attribute_Reference (Loc,
12506 Prefix => Deref,
12507 Attribute_Name => Name_Tag))),
12508 Then_Statements => New_List (Stmt));
12509 end if;
12511 Insert_Action (N, Stmt);
12512 end if;
12514 -- Generate:
12515 -- Dereference (Pool, Addr, Size, Alig);
12517 Insert_Action (N,
12518 Make_Procedure_Call_Statement (Loc,
12519 Name =>
12520 New_Occurrence_Of
12521 (Find_Prim_Op (Etype (Pool), Name_Dereference), Loc),
12522 Parameter_Associations => New_List (
12523 New_Occurrence_Of (Pool, Loc),
12524 New_Occurrence_Of (Addr, Loc),
12525 New_Occurrence_Of (Size, Loc),
12526 New_Occurrence_Of (Alig, Loc))));
12528 -- Mark the explicit dereference as processed to avoid potential
12529 -- infinite expansion.
12531 Set_Has_Dereference_Action (Context);
12533 exception
12534 when RE_Not_Available =>
12535 return;
12536 end Insert_Dereference_Action;
12538 --------------------------------
12539 -- Integer_Promotion_Possible --
12540 --------------------------------
12542 function Integer_Promotion_Possible (N : Node_Id) return Boolean is
12543 Operand : constant Node_Id := Expression (N);
12544 Operand_Type : constant Entity_Id := Etype (Operand);
12545 Root_Operand_Type : constant Entity_Id := Root_Type (Operand_Type);
12547 begin
12548 pragma Assert (Nkind (N) = N_Type_Conversion);
12550 return
12552 -- We only do the transformation for source constructs. We assume
12553 -- that the expander knows what it is doing when it generates code.
12555 Comes_From_Source (N)
12557 -- If the operand type is Short_Integer or Short_Short_Integer,
12558 -- then we will promote to Integer, which is available on all
12559 -- targets, and is sufficient to ensure no intermediate overflow.
12560 -- Furthermore it is likely to be as efficient or more efficient
12561 -- than using the smaller type for the computation so we do this
12562 -- unconditionally.
12564 and then
12565 (Root_Operand_Type = Base_Type (Standard_Short_Integer)
12566 or else
12567 Root_Operand_Type = Base_Type (Standard_Short_Short_Integer))
12569 -- Test for interesting operation, which includes addition,
12570 -- division, exponentiation, multiplication, subtraction, absolute
12571 -- value and unary negation. Unary "+" is omitted since it is a
12572 -- no-op and thus can't overflow.
12574 and then Nkind_In (Operand, N_Op_Abs,
12575 N_Op_Add,
12576 N_Op_Divide,
12577 N_Op_Expon,
12578 N_Op_Minus,
12579 N_Op_Multiply,
12580 N_Op_Subtract);
12581 end Integer_Promotion_Possible;
12583 ------------------------------
12584 -- Make_Array_Comparison_Op --
12585 ------------------------------
12587 -- This is a hand-coded expansion of the following generic function:
12589 -- generic
12590 -- type elem is (<>);
12591 -- type index is (<>);
12592 -- type a is array (index range <>) of elem;
12594 -- function Gnnn (X : a; Y: a) return boolean is
12595 -- J : index := Y'first;
12597 -- begin
12598 -- if X'length = 0 then
12599 -- return false;
12601 -- elsif Y'length = 0 then
12602 -- return true;
12604 -- else
12605 -- for I in X'range loop
12606 -- if X (I) = Y (J) then
12607 -- if J = Y'last then
12608 -- exit;
12609 -- else
12610 -- J := index'succ (J);
12611 -- end if;
12613 -- else
12614 -- return X (I) > Y (J);
12615 -- end if;
12616 -- end loop;
12618 -- return X'length > Y'length;
12619 -- end if;
12620 -- end Gnnn;
12622 -- Note that since we are essentially doing this expansion by hand, we
12623 -- do not need to generate an actual or formal generic part, just the
12624 -- instantiated function itself.
12626 -- Perhaps we could have the actual generic available in the run-time,
12627 -- obtained by rtsfind, and actually expand a real instantiation ???
12629 function Make_Array_Comparison_Op
12630 (Typ : Entity_Id;
12631 Nod : Node_Id) return Node_Id
12633 Loc : constant Source_Ptr := Sloc (Nod);
12635 X : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uX);
12636 Y : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uY);
12637 I : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uI);
12638 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
12640 Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
12642 Loop_Statement : Node_Id;
12643 Loop_Body : Node_Id;
12644 If_Stat : Node_Id;
12645 Inner_If : Node_Id;
12646 Final_Expr : Node_Id;
12647 Func_Body : Node_Id;
12648 Func_Name : Entity_Id;
12649 Formals : List_Id;
12650 Length1 : Node_Id;
12651 Length2 : Node_Id;
12653 begin
12654 -- if J = Y'last then
12655 -- exit;
12656 -- else
12657 -- J := index'succ (J);
12658 -- end if;
12660 Inner_If :=
12661 Make_Implicit_If_Statement (Nod,
12662 Condition =>
12663 Make_Op_Eq (Loc,
12664 Left_Opnd => New_Occurrence_Of (J, Loc),
12665 Right_Opnd =>
12666 Make_Attribute_Reference (Loc,
12667 Prefix => New_Occurrence_Of (Y, Loc),
12668 Attribute_Name => Name_Last)),
12670 Then_Statements => New_List (
12671 Make_Exit_Statement (Loc)),
12673 Else_Statements =>
12674 New_List (
12675 Make_Assignment_Statement (Loc,
12676 Name => New_Occurrence_Of (J, Loc),
12677 Expression =>
12678 Make_Attribute_Reference (Loc,
12679 Prefix => New_Occurrence_Of (Index, Loc),
12680 Attribute_Name => Name_Succ,
12681 Expressions => New_List (New_Occurrence_Of (J, Loc))))));
12683 -- if X (I) = Y (J) then
12684 -- if ... end if;
12685 -- else
12686 -- return X (I) > Y (J);
12687 -- end if;
12689 Loop_Body :=
12690 Make_Implicit_If_Statement (Nod,
12691 Condition =>
12692 Make_Op_Eq (Loc,
12693 Left_Opnd =>
12694 Make_Indexed_Component (Loc,
12695 Prefix => New_Occurrence_Of (X, Loc),
12696 Expressions => New_List (New_Occurrence_Of (I, Loc))),
12698 Right_Opnd =>
12699 Make_Indexed_Component (Loc,
12700 Prefix => New_Occurrence_Of (Y, Loc),
12701 Expressions => New_List (New_Occurrence_Of (J, Loc)))),
12703 Then_Statements => New_List (Inner_If),
12705 Else_Statements => New_List (
12706 Make_Simple_Return_Statement (Loc,
12707 Expression =>
12708 Make_Op_Gt (Loc,
12709 Left_Opnd =>
12710 Make_Indexed_Component (Loc,
12711 Prefix => New_Occurrence_Of (X, Loc),
12712 Expressions => New_List (New_Occurrence_Of (I, Loc))),
12714 Right_Opnd =>
12715 Make_Indexed_Component (Loc,
12716 Prefix => New_Occurrence_Of (Y, Loc),
12717 Expressions => New_List (
12718 New_Occurrence_Of (J, Loc)))))));
12720 -- for I in X'range loop
12721 -- if ... end if;
12722 -- end loop;
12724 Loop_Statement :=
12725 Make_Implicit_Loop_Statement (Nod,
12726 Identifier => Empty,
12728 Iteration_Scheme =>
12729 Make_Iteration_Scheme (Loc,
12730 Loop_Parameter_Specification =>
12731 Make_Loop_Parameter_Specification (Loc,
12732 Defining_Identifier => I,
12733 Discrete_Subtype_Definition =>
12734 Make_Attribute_Reference (Loc,
12735 Prefix => New_Occurrence_Of (X, Loc),
12736 Attribute_Name => Name_Range))),
12738 Statements => New_List (Loop_Body));
12740 -- if X'length = 0 then
12741 -- return false;
12742 -- elsif Y'length = 0 then
12743 -- return true;
12744 -- else
12745 -- for ... loop ... end loop;
12746 -- return X'length > Y'length;
12747 -- end if;
12749 Length1 :=
12750 Make_Attribute_Reference (Loc,
12751 Prefix => New_Occurrence_Of (X, Loc),
12752 Attribute_Name => Name_Length);
12754 Length2 :=
12755 Make_Attribute_Reference (Loc,
12756 Prefix => New_Occurrence_Of (Y, Loc),
12757 Attribute_Name => Name_Length);
12759 Final_Expr :=
12760 Make_Op_Gt (Loc,
12761 Left_Opnd => Length1,
12762 Right_Opnd => Length2);
12764 If_Stat :=
12765 Make_Implicit_If_Statement (Nod,
12766 Condition =>
12767 Make_Op_Eq (Loc,
12768 Left_Opnd =>
12769 Make_Attribute_Reference (Loc,
12770 Prefix => New_Occurrence_Of (X, Loc),
12771 Attribute_Name => Name_Length),
12772 Right_Opnd =>
12773 Make_Integer_Literal (Loc, 0)),
12775 Then_Statements =>
12776 New_List (
12777 Make_Simple_Return_Statement (Loc,
12778 Expression => New_Occurrence_Of (Standard_False, Loc))),
12780 Elsif_Parts => New_List (
12781 Make_Elsif_Part (Loc,
12782 Condition =>
12783 Make_Op_Eq (Loc,
12784 Left_Opnd =>
12785 Make_Attribute_Reference (Loc,
12786 Prefix => New_Occurrence_Of (Y, Loc),
12787 Attribute_Name => Name_Length),
12788 Right_Opnd =>
12789 Make_Integer_Literal (Loc, 0)),
12791 Then_Statements =>
12792 New_List (
12793 Make_Simple_Return_Statement (Loc,
12794 Expression => New_Occurrence_Of (Standard_True, Loc))))),
12796 Else_Statements => New_List (
12797 Loop_Statement,
12798 Make_Simple_Return_Statement (Loc,
12799 Expression => Final_Expr)));
12801 -- (X : a; Y: a)
12803 Formals := New_List (
12804 Make_Parameter_Specification (Loc,
12805 Defining_Identifier => X,
12806 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
12808 Make_Parameter_Specification (Loc,
12809 Defining_Identifier => Y,
12810 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
12812 -- function Gnnn (...) return boolean is
12813 -- J : index := Y'first;
12814 -- begin
12815 -- if ... end if;
12816 -- end Gnnn;
12818 Func_Name := Make_Temporary (Loc, 'G');
12820 Func_Body :=
12821 Make_Subprogram_Body (Loc,
12822 Specification =>
12823 Make_Function_Specification (Loc,
12824 Defining_Unit_Name => Func_Name,
12825 Parameter_Specifications => Formals,
12826 Result_Definition => New_Occurrence_Of (Standard_Boolean, Loc)),
12828 Declarations => New_List (
12829 Make_Object_Declaration (Loc,
12830 Defining_Identifier => J,
12831 Object_Definition => New_Occurrence_Of (Index, Loc),
12832 Expression =>
12833 Make_Attribute_Reference (Loc,
12834 Prefix => New_Occurrence_Of (Y, Loc),
12835 Attribute_Name => Name_First))),
12837 Handled_Statement_Sequence =>
12838 Make_Handled_Sequence_Of_Statements (Loc,
12839 Statements => New_List (If_Stat)));
12841 return Func_Body;
12842 end Make_Array_Comparison_Op;
12844 ---------------------------
12845 -- Make_Boolean_Array_Op --
12846 ---------------------------
12848 -- For logical operations on boolean arrays, expand in line the following,
12849 -- replacing 'and' with 'or' or 'xor' where needed:
12851 -- function Annn (A : typ; B: typ) return typ is
12852 -- C : typ;
12853 -- begin
12854 -- for J in A'range loop
12855 -- C (J) := A (J) op B (J);
12856 -- end loop;
12857 -- return C;
12858 -- end Annn;
12860 -- Here typ is the boolean array type
12862 function Make_Boolean_Array_Op
12863 (Typ : Entity_Id;
12864 N : Node_Id) return Node_Id
12866 Loc : constant Source_Ptr := Sloc (N);
12868 A : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uA);
12869 B : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB);
12870 C : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uC);
12871 J : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uJ);
12873 A_J : Node_Id;
12874 B_J : Node_Id;
12875 C_J : Node_Id;
12876 Op : Node_Id;
12878 Formals : List_Id;
12879 Func_Name : Entity_Id;
12880 Func_Body : Node_Id;
12881 Loop_Statement : Node_Id;
12883 begin
12884 A_J :=
12885 Make_Indexed_Component (Loc,
12886 Prefix => New_Occurrence_Of (A, Loc),
12887 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12889 B_J :=
12890 Make_Indexed_Component (Loc,
12891 Prefix => New_Occurrence_Of (B, Loc),
12892 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12894 C_J :=
12895 Make_Indexed_Component (Loc,
12896 Prefix => New_Occurrence_Of (C, Loc),
12897 Expressions => New_List (New_Occurrence_Of (J, Loc)));
12899 if Nkind (N) = N_Op_And then
12900 Op :=
12901 Make_Op_And (Loc,
12902 Left_Opnd => A_J,
12903 Right_Opnd => B_J);
12905 elsif Nkind (N) = N_Op_Or then
12906 Op :=
12907 Make_Op_Or (Loc,
12908 Left_Opnd => A_J,
12909 Right_Opnd => B_J);
12911 else
12912 Op :=
12913 Make_Op_Xor (Loc,
12914 Left_Opnd => A_J,
12915 Right_Opnd => B_J);
12916 end if;
12918 Loop_Statement :=
12919 Make_Implicit_Loop_Statement (N,
12920 Identifier => Empty,
12922 Iteration_Scheme =>
12923 Make_Iteration_Scheme (Loc,
12924 Loop_Parameter_Specification =>
12925 Make_Loop_Parameter_Specification (Loc,
12926 Defining_Identifier => J,
12927 Discrete_Subtype_Definition =>
12928 Make_Attribute_Reference (Loc,
12929 Prefix => New_Occurrence_Of (A, Loc),
12930 Attribute_Name => Name_Range))),
12932 Statements => New_List (
12933 Make_Assignment_Statement (Loc,
12934 Name => C_J,
12935 Expression => Op)));
12937 Formals := New_List (
12938 Make_Parameter_Specification (Loc,
12939 Defining_Identifier => A,
12940 Parameter_Type => New_Occurrence_Of (Typ, Loc)),
12942 Make_Parameter_Specification (Loc,
12943 Defining_Identifier => B,
12944 Parameter_Type => New_Occurrence_Of (Typ, Loc)));
12946 Func_Name := Make_Temporary (Loc, 'A');
12947 Set_Is_Inlined (Func_Name);
12949 Func_Body :=
12950 Make_Subprogram_Body (Loc,
12951 Specification =>
12952 Make_Function_Specification (Loc,
12953 Defining_Unit_Name => Func_Name,
12954 Parameter_Specifications => Formals,
12955 Result_Definition => New_Occurrence_Of (Typ, Loc)),
12957 Declarations => New_List (
12958 Make_Object_Declaration (Loc,
12959 Defining_Identifier => C,
12960 Object_Definition => New_Occurrence_Of (Typ, Loc))),
12962 Handled_Statement_Sequence =>
12963 Make_Handled_Sequence_Of_Statements (Loc,
12964 Statements => New_List (
12965 Loop_Statement,
12966 Make_Simple_Return_Statement (Loc,
12967 Expression => New_Occurrence_Of (C, Loc)))));
12969 return Func_Body;
12970 end Make_Boolean_Array_Op;
12972 -----------------------------------------
12973 -- Minimized_Eliminated_Overflow_Check --
12974 -----------------------------------------
12976 function Minimized_Eliminated_Overflow_Check (N : Node_Id) return Boolean is
12977 begin
12978 return
12979 Is_Signed_Integer_Type (Etype (N))
12980 and then Overflow_Check_Mode in Minimized_Or_Eliminated;
12981 end Minimized_Eliminated_Overflow_Check;
12983 --------------------------------
12984 -- Optimize_Length_Comparison --
12985 --------------------------------
12987 procedure Optimize_Length_Comparison (N : Node_Id) is
12988 Loc : constant Source_Ptr := Sloc (N);
12989 Typ : constant Entity_Id := Etype (N);
12990 Result : Node_Id;
12992 Left : Node_Id;
12993 Right : Node_Id;
12994 -- First and Last attribute reference nodes, which end up as left and
12995 -- right operands of the optimized result.
12997 Is_Zero : Boolean;
12998 -- True for comparison operand of zero
13000 Comp : Node_Id;
13001 -- Comparison operand, set only if Is_Zero is false
13003 Ent : Entity_Id;
13004 -- Entity whose length is being compared
13006 Index : Node_Id;
13007 -- Integer_Literal node for length attribute expression, or Empty
13008 -- if there is no such expression present.
13010 Ityp : Entity_Id;
13011 -- Type of array index to which 'Length is applied
13013 Op : Node_Kind := Nkind (N);
13014 -- Kind of comparison operator, gets flipped if operands backwards
13016 function Is_Optimizable (N : Node_Id) return Boolean;
13017 -- Tests N to see if it is an optimizable comparison value (defined as
13018 -- constant zero or one, or something else where the value is known to
13019 -- be positive and in the range of 32-bits, and where the corresponding
13020 -- Length value is also known to be 32-bits. If result is true, sets
13021 -- Is_Zero, Ityp, and Comp accordingly.
13023 function Is_Entity_Length (N : Node_Id) return Boolean;
13024 -- Tests if N is a length attribute applied to a simple entity. If so,
13025 -- returns True, and sets Ent to the entity, and Index to the integer
13026 -- literal provided as an attribute expression, or to Empty if none.
13027 -- Also returns True if the expression is a generated type conversion
13028 -- whose expression is of the desired form. This latter case arises
13029 -- when Apply_Universal_Integer_Attribute_Check installs a conversion
13030 -- to check for being in range, which is not needed in this context.
13031 -- Returns False if neither condition holds.
13033 function Prepare_64 (N : Node_Id) return Node_Id;
13034 -- Given a discrete expression, returns a Long_Long_Integer typed
13035 -- expression representing the underlying value of the expression.
13036 -- This is done with an unchecked conversion to the result type. We
13037 -- use unchecked conversion to handle the enumeration type case.
13039 ----------------------
13040 -- Is_Entity_Length --
13041 ----------------------
13043 function Is_Entity_Length (N : Node_Id) return Boolean is
13044 begin
13045 if Nkind (N) = N_Attribute_Reference
13046 and then Attribute_Name (N) = Name_Length
13047 and then Is_Entity_Name (Prefix (N))
13048 then
13049 Ent := Entity (Prefix (N));
13051 if Present (Expressions (N)) then
13052 Index := First (Expressions (N));
13053 else
13054 Index := Empty;
13055 end if;
13057 return True;
13059 elsif Nkind (N) = N_Type_Conversion
13060 and then not Comes_From_Source (N)
13061 then
13062 return Is_Entity_Length (Expression (N));
13064 else
13065 return False;
13066 end if;
13067 end Is_Entity_Length;
13069 --------------------
13070 -- Is_Optimizable --
13071 --------------------
13073 function Is_Optimizable (N : Node_Id) return Boolean is
13074 Val : Uint;
13075 OK : Boolean;
13076 Lo : Uint;
13077 Hi : Uint;
13078 Indx : Node_Id;
13080 begin
13081 if Compile_Time_Known_Value (N) then
13082 Val := Expr_Value (N);
13084 if Val = Uint_0 then
13085 Is_Zero := True;
13086 Comp := Empty;
13087 return True;
13089 elsif Val = Uint_1 then
13090 Is_Zero := False;
13091 Comp := Empty;
13092 return True;
13093 end if;
13094 end if;
13096 -- Here we have to make sure of being within 32-bits
13098 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
13100 if not OK
13101 or else Lo < Uint_1
13102 or else Hi > UI_From_Int (Int'Last)
13103 then
13104 return False;
13105 end if;
13107 -- Comparison value was within range, so now we must check the index
13108 -- value to make sure it is also within 32-bits.
13110 Indx := First_Index (Etype (Ent));
13112 if Present (Index) then
13113 for J in 2 .. UI_To_Int (Intval (Index)) loop
13114 Next_Index (Indx);
13115 end loop;
13116 end if;
13118 Ityp := Etype (Indx);
13120 if Esize (Ityp) > 32 then
13121 return False;
13122 end if;
13124 Is_Zero := False;
13125 Comp := N;
13126 return True;
13127 end Is_Optimizable;
13129 ----------------
13130 -- Prepare_64 --
13131 ----------------
13133 function Prepare_64 (N : Node_Id) return Node_Id is
13134 begin
13135 return Unchecked_Convert_To (Standard_Long_Long_Integer, N);
13136 end Prepare_64;
13138 -- Start of processing for Optimize_Length_Comparison
13140 begin
13141 -- Nothing to do if not a comparison
13143 if Op not in N_Op_Compare then
13144 return;
13145 end if;
13147 -- Nothing to do if special -gnatd.P debug flag set.
13149 if Debug_Flag_Dot_PP then
13150 return;
13151 end if;
13153 -- Ent'Length op 0/1
13155 if Is_Entity_Length (Left_Opnd (N))
13156 and then Is_Optimizable (Right_Opnd (N))
13157 then
13158 null;
13160 -- 0/1 op Ent'Length
13162 elsif Is_Entity_Length (Right_Opnd (N))
13163 and then Is_Optimizable (Left_Opnd (N))
13164 then
13165 -- Flip comparison to opposite sense
13167 case Op is
13168 when N_Op_Lt => Op := N_Op_Gt;
13169 when N_Op_Le => Op := N_Op_Ge;
13170 when N_Op_Gt => Op := N_Op_Lt;
13171 when N_Op_Ge => Op := N_Op_Le;
13172 when others => null;
13173 end case;
13175 -- Else optimization not possible
13177 else
13178 return;
13179 end if;
13181 -- Fall through if we will do the optimization
13183 -- Cases to handle:
13185 -- X'Length = 0 => X'First > X'Last
13186 -- X'Length = 1 => X'First = X'Last
13187 -- X'Length = n => X'First + (n - 1) = X'Last
13189 -- X'Length /= 0 => X'First <= X'Last
13190 -- X'Length /= 1 => X'First /= X'Last
13191 -- X'Length /= n => X'First + (n - 1) /= X'Last
13193 -- X'Length >= 0 => always true, warn
13194 -- X'Length >= 1 => X'First <= X'Last
13195 -- X'Length >= n => X'First + (n - 1) <= X'Last
13197 -- X'Length > 0 => X'First <= X'Last
13198 -- X'Length > 1 => X'First < X'Last
13199 -- X'Length > n => X'First + (n - 1) < X'Last
13201 -- X'Length <= 0 => X'First > X'Last (warn, could be =)
13202 -- X'Length <= 1 => X'First >= X'Last
13203 -- X'Length <= n => X'First + (n - 1) >= X'Last
13205 -- X'Length < 0 => always false (warn)
13206 -- X'Length < 1 => X'First > X'Last
13207 -- X'Length < n => X'First + (n - 1) > X'Last
13209 -- Note: for the cases of n (not constant 0,1), we require that the
13210 -- corresponding index type be integer or shorter (i.e. not 64-bit),
13211 -- and the same for the comparison value. Then we do the comparison
13212 -- using 64-bit arithmetic (actually long long integer), so that we
13213 -- cannot have overflow intefering with the result.
13215 -- First deal with warning cases
13217 if Is_Zero then
13218 case Op is
13220 -- X'Length >= 0
13222 when N_Op_Ge =>
13223 Rewrite (N,
13224 Convert_To (Typ, New_Occurrence_Of (Standard_True, Loc)));
13225 Analyze_And_Resolve (N, Typ);
13226 Warn_On_Known_Condition (N);
13227 return;
13229 -- X'Length < 0
13231 when N_Op_Lt =>
13232 Rewrite (N,
13233 Convert_To (Typ, New_Occurrence_Of (Standard_False, Loc)));
13234 Analyze_And_Resolve (N, Typ);
13235 Warn_On_Known_Condition (N);
13236 return;
13238 when N_Op_Le =>
13239 if Constant_Condition_Warnings
13240 and then Comes_From_Source (Original_Node (N))
13241 then
13242 Error_Msg_N ("could replace by ""'=""?c?", N);
13243 end if;
13245 Op := N_Op_Eq;
13247 when others =>
13248 null;
13249 end case;
13250 end if;
13252 -- Build the First reference we will use
13254 Left :=
13255 Make_Attribute_Reference (Loc,
13256 Prefix => New_Occurrence_Of (Ent, Loc),
13257 Attribute_Name => Name_First);
13259 if Present (Index) then
13260 Set_Expressions (Left, New_List (New_Copy (Index)));
13261 end if;
13263 -- If general value case, then do the addition of (n - 1), and
13264 -- also add the needed conversions to type Long_Long_Integer.
13266 if Present (Comp) then
13267 Left :=
13268 Make_Op_Add (Loc,
13269 Left_Opnd => Prepare_64 (Left),
13270 Right_Opnd =>
13271 Make_Op_Subtract (Loc,
13272 Left_Opnd => Prepare_64 (Comp),
13273 Right_Opnd => Make_Integer_Literal (Loc, 1)));
13274 end if;
13276 -- Build the Last reference we will use
13278 Right :=
13279 Make_Attribute_Reference (Loc,
13280 Prefix => New_Occurrence_Of (Ent, Loc),
13281 Attribute_Name => Name_Last);
13283 if Present (Index) then
13284 Set_Expressions (Right, New_List (New_Copy (Index)));
13285 end if;
13287 -- If general operand, convert Last reference to Long_Long_Integer
13289 if Present (Comp) then
13290 Right := Prepare_64 (Right);
13291 end if;
13293 -- Check for cases to optimize
13295 -- X'Length = 0 => X'First > X'Last
13296 -- X'Length < 1 => X'First > X'Last
13297 -- X'Length < n => X'First + (n - 1) > X'Last
13299 if (Is_Zero and then Op = N_Op_Eq)
13300 or else (not Is_Zero and then Op = N_Op_Lt)
13301 then
13302 Result :=
13303 Make_Op_Gt (Loc,
13304 Left_Opnd => Left,
13305 Right_Opnd => Right);
13307 -- X'Length = 1 => X'First = X'Last
13308 -- X'Length = n => X'First + (n - 1) = X'Last
13310 elsif not Is_Zero and then Op = N_Op_Eq then
13311 Result :=
13312 Make_Op_Eq (Loc,
13313 Left_Opnd => Left,
13314 Right_Opnd => Right);
13316 -- X'Length /= 0 => X'First <= X'Last
13317 -- X'Length > 0 => X'First <= X'Last
13319 elsif Is_Zero and (Op = N_Op_Ne or else Op = N_Op_Gt) then
13320 Result :=
13321 Make_Op_Le (Loc,
13322 Left_Opnd => Left,
13323 Right_Opnd => Right);
13325 -- X'Length /= 1 => X'First /= X'Last
13326 -- X'Length /= n => X'First + (n - 1) /= X'Last
13328 elsif not Is_Zero and then Op = N_Op_Ne then
13329 Result :=
13330 Make_Op_Ne (Loc,
13331 Left_Opnd => Left,
13332 Right_Opnd => Right);
13334 -- X'Length >= 1 => X'First <= X'Last
13335 -- X'Length >= n => X'First + (n - 1) <= X'Last
13337 elsif not Is_Zero and then Op = N_Op_Ge then
13338 Result :=
13339 Make_Op_Le (Loc,
13340 Left_Opnd => Left,
13341 Right_Opnd => Right);
13343 -- X'Length > 1 => X'First < X'Last
13344 -- X'Length > n => X'First + (n = 1) < X'Last
13346 elsif not Is_Zero and then Op = N_Op_Gt then
13347 Result :=
13348 Make_Op_Lt (Loc,
13349 Left_Opnd => Left,
13350 Right_Opnd => Right);
13352 -- X'Length <= 1 => X'First >= X'Last
13353 -- X'Length <= n => X'First + (n - 1) >= X'Last
13355 elsif not Is_Zero and then Op = N_Op_Le then
13356 Result :=
13357 Make_Op_Ge (Loc,
13358 Left_Opnd => Left,
13359 Right_Opnd => Right);
13361 -- Should not happen at this stage
13363 else
13364 raise Program_Error;
13365 end if;
13367 -- Rewrite and finish up
13369 Rewrite (N, Result);
13370 Analyze_And_Resolve (N, Typ);
13371 return;
13372 end Optimize_Length_Comparison;
13374 --------------------------------
13375 -- Process_If_Case_Statements --
13376 --------------------------------
13378 procedure Process_If_Case_Statements (N : Node_Id; Stmts : List_Id) is
13379 Decl : Node_Id;
13381 begin
13382 Decl := First (Stmts);
13383 while Present (Decl) loop
13384 if Nkind (Decl) = N_Object_Declaration
13385 and then Is_Finalizable_Transient (Decl, N)
13386 then
13387 Process_Transient_In_Expression (Decl, N, Stmts);
13388 end if;
13390 Next (Decl);
13391 end loop;
13392 end Process_If_Case_Statements;
13394 -------------------------------------
13395 -- Process_Transient_In_Expression --
13396 -------------------------------------
13398 procedure Process_Transient_In_Expression
13399 (Obj_Decl : Node_Id;
13400 Expr : Node_Id;
13401 Stmts : List_Id)
13403 Loc : constant Source_Ptr := Sloc (Obj_Decl);
13404 Obj_Id : constant Entity_Id := Defining_Identifier (Obj_Decl);
13406 Hook_Context : constant Node_Id := Find_Hook_Context (Expr);
13407 -- The node on which to insert the hook as an action. This is usually
13408 -- the innermost enclosing non-transient construct.
13410 Fin_Call : Node_Id;
13411 Hook_Assign : Node_Id;
13412 Hook_Clear : Node_Id;
13413 Hook_Decl : Node_Id;
13414 Hook_Insert : Node_Id;
13415 Ptr_Decl : Node_Id;
13417 Fin_Context : Node_Id;
13418 -- The node after which to insert the finalization actions of the
13419 -- transient object.
13421 begin
13422 pragma Assert (Nkind_In (Expr, N_Case_Expression,
13423 N_Expression_With_Actions,
13424 N_If_Expression));
13426 -- When the context is a Boolean evaluation, all three nodes capture the
13427 -- result of their computation in a local temporary:
13429 -- do
13430 -- Trans_Id : Ctrl_Typ := ...;
13431 -- Result : constant Boolean := ... Trans_Id ...;
13432 -- <finalize Trans_Id>
13433 -- in Result end;
13435 -- As a result, the finalization of any transient objects can safely
13436 -- take place after the result capture.
13438 -- ??? could this be extended to elementary types?
13440 if Is_Boolean_Type (Etype (Expr)) then
13441 Fin_Context := Last (Stmts);
13443 -- Otherwise the immediate context may not be safe enough to carry
13444 -- out transient object finalization due to aliasing and nesting of
13445 -- constructs. Insert calls to [Deep_]Finalize after the innermost
13446 -- enclosing non-transient construct.
13448 else
13449 Fin_Context := Hook_Context;
13450 end if;
13452 -- Mark the transient object as successfully processed to avoid double
13453 -- finalization.
13455 Set_Is_Finalized_Transient (Obj_Id);
13457 -- Construct all the pieces necessary to hook and finalize a transient
13458 -- object.
13460 Build_Transient_Object_Statements
13461 (Obj_Decl => Obj_Decl,
13462 Fin_Call => Fin_Call,
13463 Hook_Assign => Hook_Assign,
13464 Hook_Clear => Hook_Clear,
13465 Hook_Decl => Hook_Decl,
13466 Ptr_Decl => Ptr_Decl,
13467 Finalize_Obj => False);
13469 -- Add the access type which provides a reference to the transient
13470 -- object. Generate:
13472 -- type Ptr_Typ is access all Desig_Typ;
13474 Insert_Action (Hook_Context, Ptr_Decl);
13476 -- Add the temporary which acts as a hook to the transient object.
13477 -- Generate:
13479 -- Hook : Ptr_Id := null;
13481 Insert_Action (Hook_Context, Hook_Decl);
13483 -- When the transient object is initialized by an aggregate, the hook
13484 -- must capture the object after the last aggregate assignment takes
13485 -- place. Only then is the object considered initialized. Generate:
13487 -- Hook := Ptr_Typ (Obj_Id);
13488 -- <or>
13489 -- Hook := Obj_Id'Unrestricted_Access;
13491 if Ekind_In (Obj_Id, E_Constant, E_Variable)
13492 and then Present (Last_Aggregate_Assignment (Obj_Id))
13493 then
13494 Hook_Insert := Last_Aggregate_Assignment (Obj_Id);
13496 -- Otherwise the hook seizes the related object immediately
13498 else
13499 Hook_Insert := Obj_Decl;
13500 end if;
13502 Insert_After_And_Analyze (Hook_Insert, Hook_Assign);
13504 -- When the node is part of a return statement, there is no need to
13505 -- insert a finalization call, as the general finalization mechanism
13506 -- (see Build_Finalizer) would take care of the transient object on
13507 -- subprogram exit. Note that it would also be impossible to insert the
13508 -- finalization code after the return statement as this will render it
13509 -- unreachable.
13511 if Nkind (Fin_Context) = N_Simple_Return_Statement then
13512 null;
13514 -- Finalize the hook after the context has been evaluated. Generate:
13516 -- if Hook /= null then
13517 -- [Deep_]Finalize (Hook.all);
13518 -- Hook := null;
13519 -- end if;
13521 else
13522 Insert_Action_After (Fin_Context,
13523 Make_Implicit_If_Statement (Obj_Decl,
13524 Condition =>
13525 Make_Op_Ne (Loc,
13526 Left_Opnd =>
13527 New_Occurrence_Of (Defining_Entity (Hook_Decl), Loc),
13528 Right_Opnd => Make_Null (Loc)),
13530 Then_Statements => New_List (
13531 Fin_Call,
13532 Hook_Clear)));
13533 end if;
13534 end Process_Transient_In_Expression;
13536 ------------------------
13537 -- Rewrite_Comparison --
13538 ------------------------
13540 procedure Rewrite_Comparison (N : Node_Id) is
13541 Typ : constant Entity_Id := Etype (N);
13543 False_Result : Boolean;
13544 True_Result : Boolean;
13546 begin
13547 if Nkind (N) = N_Type_Conversion then
13548 Rewrite_Comparison (Expression (N));
13549 return;
13551 elsif Nkind (N) not in N_Op_Compare then
13552 return;
13553 end if;
13555 -- Determine the potential outcome of the comparison assuming that the
13556 -- operands are valid and emit a warning when the comparison evaluates
13557 -- to True or False only in the presence of invalid values.
13559 Warn_On_Constant_Valid_Condition (N);
13561 -- Determine the potential outcome of the comparison assuming that the
13562 -- operands are not valid.
13564 Test_Comparison
13565 (Op => N,
13566 Assume_Valid => False,
13567 True_Result => True_Result,
13568 False_Result => False_Result);
13570 -- The outcome is a decisive False or True, rewrite the operator
13572 if False_Result or True_Result then
13573 Rewrite (N,
13574 Convert_To (Typ,
13575 New_Occurrence_Of (Boolean_Literals (True_Result), Sloc (N))));
13577 Analyze_And_Resolve (N, Typ);
13578 Warn_On_Known_Condition (N);
13579 end if;
13580 end Rewrite_Comparison;
13582 ----------------------------
13583 -- Safe_In_Place_Array_Op --
13584 ----------------------------
13586 function Safe_In_Place_Array_Op
13587 (Lhs : Node_Id;
13588 Op1 : Node_Id;
13589 Op2 : Node_Id) return Boolean
13591 Target : Entity_Id;
13593 function Is_Safe_Operand (Op : Node_Id) return Boolean;
13594 -- Operand is safe if it cannot overlap part of the target of the
13595 -- operation. If the operand and the target are identical, the operand
13596 -- is safe. The operand can be empty in the case of negation.
13598 function Is_Unaliased (N : Node_Id) return Boolean;
13599 -- Check that N is a stand-alone entity
13601 ------------------
13602 -- Is_Unaliased --
13603 ------------------
13605 function Is_Unaliased (N : Node_Id) return Boolean is
13606 begin
13607 return
13608 Is_Entity_Name (N)
13609 and then No (Address_Clause (Entity (N)))
13610 and then No (Renamed_Object (Entity (N)));
13611 end Is_Unaliased;
13613 ---------------------
13614 -- Is_Safe_Operand --
13615 ---------------------
13617 function Is_Safe_Operand (Op : Node_Id) return Boolean is
13618 begin
13619 if No (Op) then
13620 return True;
13622 elsif Is_Entity_Name (Op) then
13623 return Is_Unaliased (Op);
13625 elsif Nkind_In (Op, N_Indexed_Component, N_Selected_Component) then
13626 return Is_Unaliased (Prefix (Op));
13628 elsif Nkind (Op) = N_Slice then
13629 return
13630 Is_Unaliased (Prefix (Op))
13631 and then Entity (Prefix (Op)) /= Target;
13633 elsif Nkind (Op) = N_Op_Not then
13634 return Is_Safe_Operand (Right_Opnd (Op));
13636 else
13637 return False;
13638 end if;
13639 end Is_Safe_Operand;
13641 -- Start of processing for Safe_In_Place_Array_Op
13643 begin
13644 -- Skip this processing if the component size is different from system
13645 -- storage unit (since at least for NOT this would cause problems).
13647 if Component_Size (Etype (Lhs)) /= System_Storage_Unit then
13648 return False;
13650 -- Cannot do in place stuff if non-standard Boolean representation
13652 elsif Has_Non_Standard_Rep (Component_Type (Etype (Lhs))) then
13653 return False;
13655 elsif not Is_Unaliased (Lhs) then
13656 return False;
13658 else
13659 Target := Entity (Lhs);
13660 return Is_Safe_Operand (Op1) and then Is_Safe_Operand (Op2);
13661 end if;
13662 end Safe_In_Place_Array_Op;
13664 -----------------------
13665 -- Tagged_Membership --
13666 -----------------------
13668 -- There are two different cases to consider depending on whether the right
13669 -- operand is a class-wide type or not. If not we just compare the actual
13670 -- tag of the left expr to the target type tag:
13672 -- Left_Expr.Tag = Right_Type'Tag;
13674 -- If it is a class-wide type we use the RT function CW_Membership which is
13675 -- usually implemented by looking in the ancestor tables contained in the
13676 -- dispatch table pointed by Left_Expr.Tag for Typ'Tag
13678 -- Ada 2005 (AI-251): If it is a class-wide interface type we use the RT
13679 -- function IW_Membership which is usually implemented by looking in the
13680 -- table of abstract interface types plus the ancestor table contained in
13681 -- the dispatch table pointed by Left_Expr.Tag for Typ'Tag
13683 procedure Tagged_Membership
13684 (N : Node_Id;
13685 SCIL_Node : out Node_Id;
13686 Result : out Node_Id)
13688 Left : constant Node_Id := Left_Opnd (N);
13689 Right : constant Node_Id := Right_Opnd (N);
13690 Loc : constant Source_Ptr := Sloc (N);
13692 Full_R_Typ : Entity_Id;
13693 Left_Type : Entity_Id;
13694 New_Node : Node_Id;
13695 Right_Type : Entity_Id;
13696 Obj_Tag : Node_Id;
13698 begin
13699 SCIL_Node := Empty;
13701 -- Handle entities from the limited view
13703 Left_Type := Available_View (Etype (Left));
13704 Right_Type := Available_View (Etype (Right));
13706 -- In the case where the type is an access type, the test is applied
13707 -- using the designated types (needed in Ada 2012 for implicit anonymous
13708 -- access conversions, for AI05-0149).
13710 if Is_Access_Type (Right_Type) then
13711 Left_Type := Designated_Type (Left_Type);
13712 Right_Type := Designated_Type (Right_Type);
13713 end if;
13715 if Is_Class_Wide_Type (Left_Type) then
13716 Left_Type := Root_Type (Left_Type);
13717 end if;
13719 if Is_Class_Wide_Type (Right_Type) then
13720 Full_R_Typ := Underlying_Type (Root_Type (Right_Type));
13721 else
13722 Full_R_Typ := Underlying_Type (Right_Type);
13723 end if;
13725 Obj_Tag :=
13726 Make_Selected_Component (Loc,
13727 Prefix => Relocate_Node (Left),
13728 Selector_Name =>
13729 New_Occurrence_Of (First_Tag_Component (Left_Type), Loc));
13731 if Is_Class_Wide_Type (Right_Type) then
13733 -- No need to issue a run-time check if we statically know that the
13734 -- result of this membership test is always true. For example,
13735 -- considering the following declarations:
13737 -- type Iface is interface;
13738 -- type T is tagged null record;
13739 -- type DT is new T and Iface with null record;
13741 -- Obj1 : T;
13742 -- Obj2 : DT;
13744 -- These membership tests are always true:
13746 -- Obj1 in T'Class
13747 -- Obj2 in T'Class;
13748 -- Obj2 in Iface'Class;
13750 -- We do not need to handle cases where the membership is illegal.
13751 -- For example:
13753 -- Obj1 in DT'Class; -- Compile time error
13754 -- Obj1 in Iface'Class; -- Compile time error
13756 if not Is_Class_Wide_Type (Left_Type)
13757 and then (Is_Ancestor (Etype (Right_Type), Left_Type,
13758 Use_Full_View => True)
13759 or else (Is_Interface (Etype (Right_Type))
13760 and then Interface_Present_In_Ancestor
13761 (Typ => Left_Type,
13762 Iface => Etype (Right_Type))))
13763 then
13764 Result := New_Occurrence_Of (Standard_True, Loc);
13765 return;
13766 end if;
13768 -- Ada 2005 (AI-251): Class-wide applied to interfaces
13770 if Is_Interface (Etype (Class_Wide_Type (Right_Type)))
13772 -- Support to: "Iface_CW_Typ in Typ'Class"
13774 or else Is_Interface (Left_Type)
13775 then
13776 -- Issue error if IW_Membership operation not available in a
13777 -- configurable run time setting.
13779 if not RTE_Available (RE_IW_Membership) then
13780 Error_Msg_CRT
13781 ("dynamic membership test on interface types", N);
13782 Result := Empty;
13783 return;
13784 end if;
13786 Result :=
13787 Make_Function_Call (Loc,
13788 Name => New_Occurrence_Of (RTE (RE_IW_Membership), Loc),
13789 Parameter_Associations => New_List (
13790 Make_Attribute_Reference (Loc,
13791 Prefix => Obj_Tag,
13792 Attribute_Name => Name_Address),
13793 New_Occurrence_Of (
13794 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))),
13795 Loc)));
13797 -- Ada 95: Normal case
13799 else
13800 Build_CW_Membership (Loc,
13801 Obj_Tag_Node => Obj_Tag,
13802 Typ_Tag_Node =>
13803 New_Occurrence_Of (
13804 Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc),
13805 Related_Nod => N,
13806 New_Node => New_Node);
13808 -- Generate the SCIL node for this class-wide membership test.
13809 -- Done here because the previous call to Build_CW_Membership
13810 -- relocates Obj_Tag.
13812 if Generate_SCIL then
13813 SCIL_Node := Make_SCIL_Membership_Test (Sloc (N));
13814 Set_SCIL_Entity (SCIL_Node, Etype (Right_Type));
13815 Set_SCIL_Tag_Value (SCIL_Node, Obj_Tag);
13816 end if;
13818 Result := New_Node;
13819 end if;
13821 -- Right_Type is not a class-wide type
13823 else
13824 -- No need to check the tag of the object if Right_Typ is abstract
13826 if Is_Abstract_Type (Right_Type) then
13827 Result := New_Occurrence_Of (Standard_False, Loc);
13829 else
13830 Result :=
13831 Make_Op_Eq (Loc,
13832 Left_Opnd => Obj_Tag,
13833 Right_Opnd =>
13834 New_Occurrence_Of
13835 (Node (First_Elmt (Access_Disp_Table (Full_R_Typ))), Loc));
13836 end if;
13837 end if;
13838 end Tagged_Membership;
13840 ------------------------------
13841 -- Unary_Op_Validity_Checks --
13842 ------------------------------
13844 procedure Unary_Op_Validity_Checks (N : Node_Id) is
13845 begin
13846 if Validity_Checks_On and Validity_Check_Operands then
13847 Ensure_Valid (Right_Opnd (N));
13848 end if;
13849 end Unary_Op_Validity_Checks;
13851 end Exp_Ch4;