1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2008, Free Software Foundation, Inc. --
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. --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
24 ------------------------------------------------------------------------------
26 with Atree; use Atree;
27 with Debug; use Debug;
28 with Einfo; use Einfo;
29 with Errout; use Errout;
30 with Exp_Ch2; use Exp_Ch2;
31 with Exp_Ch11; use Exp_Ch11;
32 with Exp_Pakd; use Exp_Pakd;
33 with Exp_Util; use Exp_Util;
34 with Elists; use Elists;
35 with Eval_Fat; use Eval_Fat;
36 with Freeze; use Freeze;
38 with Nlists; use Nlists;
39 with Nmake; use Nmake;
41 with Output; use Output;
42 with Restrict; use Restrict;
43 with Rident; use Rident;
44 with Rtsfind; use Rtsfind;
46 with Sem_Eval; use Sem_Eval;
47 with Sem_Ch3; use Sem_Ch3;
48 with Sem_Ch8; use Sem_Ch8;
49 with Sem_Res; use Sem_Res;
50 with Sem_Util; use Sem_Util;
51 with Sem_Warn; use Sem_Warn;
52 with Sinfo; use Sinfo;
53 with Sinput; use Sinput;
54 with Snames; use Snames;
55 with Sprint; use Sprint;
56 with Stand; use Stand;
57 with Targparm; use Targparm;
58 with Tbuild; use Tbuild;
59 with Ttypes; use Ttypes;
60 with Urealp; use Urealp;
61 with Validsw; use Validsw;
63 package body Checks is
65 -- General note: many of these routines are concerned with generating
66 -- checking code to make sure that constraint error is raised at runtime.
67 -- Clearly this code is only needed if the expander is active, since
68 -- otherwise we will not be generating code or going into the runtime
71 -- We therefore disconnect most of these checks if the expander is
72 -- inactive. This has the additional benefit that we do not need to
73 -- worry about the tree being messed up by previous errors (since errors
74 -- turn off expansion anyway).
76 -- There are a few exceptions to the above rule. For instance routines
77 -- such as Apply_Scalar_Range_Check that do not insert any code can be
78 -- safely called even when the Expander is inactive (but Errors_Detected
79 -- is 0). The benefit of executing this code when expansion is off, is
80 -- the ability to emit constraint error warning for static expressions
81 -- even when we are not generating code.
83 -------------------------------------
84 -- Suppression of Redundant Checks --
85 -------------------------------------
87 -- This unit implements a limited circuit for removal of redundant
88 -- checks. The processing is based on a tracing of simple sequential
89 -- flow. For any sequence of statements, we save expressions that are
90 -- marked to be checked, and then if the same expression appears later
91 -- with the same check, then under certain circumstances, the second
92 -- check can be suppressed.
94 -- Basically, we can suppress the check if we know for certain that
95 -- the previous expression has been elaborated (together with its
96 -- check), and we know that the exception frame is the same, and that
97 -- nothing has happened to change the result of the exception.
99 -- Let us examine each of these three conditions in turn to describe
100 -- how we ensure that this condition is met.
102 -- First, we need to know for certain that the previous expression has
103 -- been executed. This is done principly by the mechanism of calling
104 -- Conditional_Statements_Begin at the start of any statement sequence
105 -- and Conditional_Statements_End at the end. The End call causes all
106 -- checks remembered since the Begin call to be discarded. This does
107 -- miss a few cases, notably the case of a nested BEGIN-END block with
108 -- no exception handlers. But the important thing is to be conservative.
109 -- The other protection is that all checks are discarded if a label
110 -- is encountered, since then the assumption of sequential execution
111 -- is violated, and we don't know enough about the flow.
113 -- Second, we need to know that the exception frame is the same. We
114 -- do this by killing all remembered checks when we enter a new frame.
115 -- Again, that's over-conservative, but generally the cases we can help
116 -- with are pretty local anyway (like the body of a loop for example).
118 -- Third, we must be sure to forget any checks which are no longer valid.
119 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
120 -- used to note any changes to local variables. We only attempt to deal
121 -- with checks involving local variables, so we do not need to worry
122 -- about global variables. Second, a call to any non-global procedure
123 -- causes us to abandon all stored checks, since such a all may affect
124 -- the values of any local variables.
126 -- The following define the data structures used to deal with remembering
127 -- checks so that redundant checks can be eliminated as described above.
129 -- Right now, the only expressions that we deal with are of the form of
130 -- simple local objects (either declared locally, or IN parameters) or
131 -- such objects plus/minus a compile time known constant. We can do
132 -- more later on if it seems worthwhile, but this catches many simple
133 -- cases in practice.
135 -- The following record type reflects a single saved check. An entry
136 -- is made in the stack of saved checks if and only if the expression
137 -- has been elaborated with the indicated checks.
139 type Saved_Check is record
141 -- Set True if entry is killed by Kill_Checks
144 -- The entity involved in the expression that is checked
147 -- A compile time value indicating the result of adding or
148 -- subtracting a compile time value. This value is to be
149 -- added to the value of the Entity. A value of zero is
150 -- used for the case of a simple entity reference.
152 Check_Type : Character;
153 -- This is set to 'R' for a range check (in which case Target_Type
154 -- is set to the target type for the range check) or to 'O' for an
155 -- overflow check (in which case Target_Type is set to Empty).
157 Target_Type : Entity_Id;
158 -- Used only if Do_Range_Check is set. Records the target type for
159 -- the check. We need this, because a check is a duplicate only if
160 -- it has a the same target type (or more accurately one with a
161 -- range that is smaller or equal to the stored target type of a
165 -- The following table keeps track of saved checks. Rather than use an
166 -- extensible table. We just use a table of fixed size, and we discard
167 -- any saved checks that do not fit. That's very unlikely to happen and
168 -- this is only an optimization in any case.
170 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
171 -- Array of saved checks
173 Num_Saved_Checks : Nat := 0;
174 -- Number of saved checks
176 -- The following stack keeps track of statement ranges. It is treated
177 -- as a stack. When Conditional_Statements_Begin is called, an entry
178 -- is pushed onto this stack containing the value of Num_Saved_Checks
179 -- at the time of the call. Then when Conditional_Statements_End is
180 -- called, this value is popped off and used to reset Num_Saved_Checks.
182 -- Note: again, this is a fixed length stack with a size that should
183 -- always be fine. If the value of the stack pointer goes above the
184 -- limit, then we just forget all saved checks.
186 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
187 Saved_Checks_TOS : Nat := 0;
189 -----------------------
190 -- Local Subprograms --
191 -----------------------
193 procedure Apply_Float_Conversion_Check
195 Target_Typ : Entity_Id);
196 -- The checks on a conversion from a floating-point type to an integer
197 -- type are delicate. They have to be performed before conversion, they
198 -- have to raise an exception when the operand is a NaN, and rounding must
199 -- be taken into account to determine the safe bounds of the operand.
201 procedure Apply_Selected_Length_Checks
203 Target_Typ : Entity_Id;
204 Source_Typ : Entity_Id;
205 Do_Static : Boolean);
206 -- This is the subprogram that does all the work for Apply_Length_Check
207 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
208 -- described for the above routines. The Do_Static flag indicates that
209 -- only a static check is to be done.
211 procedure Apply_Selected_Range_Checks
213 Target_Typ : Entity_Id;
214 Source_Typ : Entity_Id;
215 Do_Static : Boolean);
216 -- This is the subprogram that does all the work for Apply_Range_Check.
217 -- Expr, Target_Typ and Source_Typ are as described for the above
218 -- routine. The Do_Static flag indicates that only a static check is
221 type Check_Type is new Check_Id range Access_Check .. Division_Check;
222 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
223 -- This function is used to see if an access or division by zero check is
224 -- needed. The check is to be applied to a single variable appearing in the
225 -- source, and N is the node for the reference. If N is not of this form,
226 -- True is returned with no further processing. If N is of the right form,
227 -- then further processing determines if the given Check is needed.
229 -- The particular circuit is to see if we have the case of a check that is
230 -- not needed because it appears in the right operand of a short circuited
231 -- conditional where the left operand guards the check. For example:
233 -- if Var = 0 or else Q / Var > 12 then
237 -- In this example, the division check is not required. At the same time
238 -- we can issue warnings for suspicious use of non-short-circuited forms,
241 -- if Var = 0 or Q / Var > 12 then
247 Check_Type : Character;
248 Target_Type : Entity_Id;
249 Entry_OK : out Boolean;
253 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
254 -- to see if a check is of the form for optimization, and if so, to see
255 -- if it has already been performed. Expr is the expression to check,
256 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
257 -- Target_Type is the target type for a range check, and Empty for an
258 -- overflow check. If the entry is not of the form for optimization,
259 -- then Entry_OK is set to False, and the remaining out parameters
260 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
261 -- entity and offset from the expression. Check_Num is the number of
262 -- a matching saved entry in Saved_Checks, or zero if no such entry
265 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
266 -- If a discriminal is used in constraining a prival, Return reference
267 -- to the discriminal of the protected body (which renames the parameter
268 -- of the enclosing protected operation). This clumsy transformation is
269 -- needed because privals are created too late and their actual subtypes
270 -- are not available when analysing the bodies of the protected operations.
271 -- This function is called whenever the bound is an entity and the scope
272 -- indicates a protected operation. If the bound is an in-parameter of
273 -- a protected operation that is not a prival, the function returns the
275 -- To be cleaned up???
277 function Guard_Access
280 Ck_Node : Node_Id) return Node_Id;
281 -- In the access type case, guard the test with a test to ensure
282 -- that the access value is non-null, since the checks do not
283 -- not apply to null access values.
285 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
286 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
287 -- Constraint_Error node.
289 function Range_Or_Validity_Checks_Suppressed
290 (Expr : Node_Id) return Boolean;
291 -- Returns True if either range or validity checks or both are suppressed
292 -- for the type of the given expression, or, if the expression is the name
293 -- of an entity, if these checks are suppressed for the entity.
295 function Selected_Length_Checks
297 Target_Typ : Entity_Id;
298 Source_Typ : Entity_Id;
299 Warn_Node : Node_Id) return Check_Result;
300 -- Like Apply_Selected_Length_Checks, except it doesn't modify
301 -- anything, just returns a list of nodes as described in the spec of
302 -- this package for the Range_Check function.
304 function Selected_Range_Checks
306 Target_Typ : Entity_Id;
307 Source_Typ : Entity_Id;
308 Warn_Node : Node_Id) return Check_Result;
309 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
310 -- just returns a list of nodes as described in the spec of this package
311 -- for the Range_Check function.
313 ------------------------------
314 -- Access_Checks_Suppressed --
315 ------------------------------
317 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
319 if Present (E) and then Checks_May_Be_Suppressed (E) then
320 return Is_Check_Suppressed (E, Access_Check);
322 return Scope_Suppress (Access_Check);
324 end Access_Checks_Suppressed;
326 -------------------------------------
327 -- Accessibility_Checks_Suppressed --
328 -------------------------------------
330 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
332 if Present (E) and then Checks_May_Be_Suppressed (E) then
333 return Is_Check_Suppressed (E, Accessibility_Check);
335 return Scope_Suppress (Accessibility_Check);
337 end Accessibility_Checks_Suppressed;
339 -----------------------------
340 -- Activate_Division_Check --
341 -----------------------------
343 procedure Activate_Division_Check (N : Node_Id) is
345 Set_Do_Division_Check (N, True);
346 Possible_Local_Raise (N, Standard_Constraint_Error);
347 end Activate_Division_Check;
349 -----------------------------
350 -- Activate_Overflow_Check --
351 -----------------------------
353 procedure Activate_Overflow_Check (N : Node_Id) is
355 Set_Do_Overflow_Check (N, True);
356 Possible_Local_Raise (N, Standard_Constraint_Error);
357 end Activate_Overflow_Check;
359 --------------------------
360 -- Activate_Range_Check --
361 --------------------------
363 procedure Activate_Range_Check (N : Node_Id) is
365 Set_Do_Range_Check (N, True);
366 Possible_Local_Raise (N, Standard_Constraint_Error);
367 end Activate_Range_Check;
369 ---------------------------------
370 -- Alignment_Checks_Suppressed --
371 ---------------------------------
373 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
375 if Present (E) and then Checks_May_Be_Suppressed (E) then
376 return Is_Check_Suppressed (E, Alignment_Check);
378 return Scope_Suppress (Alignment_Check);
380 end Alignment_Checks_Suppressed;
382 -------------------------
383 -- Append_Range_Checks --
384 -------------------------
386 procedure Append_Range_Checks
387 (Checks : Check_Result;
389 Suppress_Typ : Entity_Id;
390 Static_Sloc : Source_Ptr;
393 Internal_Flag_Node : constant Node_Id := Flag_Node;
394 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
396 Checks_On : constant Boolean :=
397 (not Index_Checks_Suppressed (Suppress_Typ))
399 (not Range_Checks_Suppressed (Suppress_Typ));
402 -- For now we just return if Checks_On is false, however this should
403 -- be enhanced to check for an always True value in the condition
404 -- and to generate a compilation warning???
406 if not Checks_On then
411 exit when No (Checks (J));
413 if Nkind (Checks (J)) = N_Raise_Constraint_Error
414 and then Present (Condition (Checks (J)))
416 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
417 Append_To (Stmts, Checks (J));
418 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
424 Make_Raise_Constraint_Error (Internal_Static_Sloc,
425 Reason => CE_Range_Check_Failed));
428 end Append_Range_Checks;
430 ------------------------
431 -- Apply_Access_Check --
432 ------------------------
434 procedure Apply_Access_Check (N : Node_Id) is
435 P : constant Node_Id := Prefix (N);
438 -- We do not need checks if we are not generating code (i.e. the
439 -- expander is not active). This is not just an optimization, there
440 -- are cases (e.g. with pragma Debug) where generating the checks
441 -- can cause real trouble).
443 if not Expander_Active then
447 -- No check if short circuiting makes check unnecessary
449 if not Check_Needed (P, Access_Check) then
453 -- No check if accessing the Offset_To_Top component of a dispatch
454 -- table. They are safe by construction.
456 if Present (Etype (P))
457 and then RTU_Loaded (Ada_Tags)
458 and then RTE_Available (RE_Offset_To_Top_Ptr)
459 and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
464 -- Otherwise go ahead and install the check
466 Install_Null_Excluding_Check (P);
467 end Apply_Access_Check;
469 -------------------------------
470 -- Apply_Accessibility_Check --
471 -------------------------------
473 procedure Apply_Accessibility_Check
476 Insert_Node : Node_Id)
478 Loc : constant Source_Ptr := Sloc (N);
479 Param_Ent : constant Entity_Id := Param_Entity (N);
480 Param_Level : Node_Id;
481 Type_Level : Node_Id;
484 if Inside_A_Generic then
487 -- Only apply the run-time check if the access parameter
488 -- has an associated extra access level parameter and
489 -- when the level of the type is less deep than the level
490 -- of the access parameter.
492 elsif Present (Param_Ent)
493 and then Present (Extra_Accessibility (Param_Ent))
494 and then UI_Gt (Object_Access_Level (N),
495 Type_Access_Level (Typ))
496 and then not Accessibility_Checks_Suppressed (Param_Ent)
497 and then not Accessibility_Checks_Suppressed (Typ)
500 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
503 Make_Integer_Literal (Loc, Type_Access_Level (Typ));
505 -- Raise Program_Error if the accessibility level of the the access
506 -- parameter is deeper than the level of the target access type.
508 Insert_Action (Insert_Node,
509 Make_Raise_Program_Error (Loc,
512 Left_Opnd => Param_Level,
513 Right_Opnd => Type_Level),
514 Reason => PE_Accessibility_Check_Failed));
516 Analyze_And_Resolve (N);
518 end Apply_Accessibility_Check;
520 --------------------------------
521 -- Apply_Address_Clause_Check --
522 --------------------------------
524 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
525 AC : constant Node_Id := Address_Clause (E);
526 Loc : constant Source_Ptr := Sloc (AC);
527 Typ : constant Entity_Id := Etype (E);
528 Aexp : constant Node_Id := Expression (AC);
531 -- Address expression (not necessarily the same as Aexp, for example
532 -- when Aexp is a reference to a constant, in which case Expr gets
533 -- reset to reference the value expression of the constant.
535 Size_Warning_Output : Boolean := False;
536 -- If we output a size warning we set this True, to stop generating
537 -- what is likely to be an unuseful redundant alignment warning.
539 procedure Compile_Time_Bad_Alignment;
540 -- Post error warnings when alignment is known to be incompatible. Note
541 -- that we do not go as far as inserting a raise of Program_Error since
542 -- this is an erroneous case, and it may happen that we are lucky and an
543 -- underaligned address turns out to be OK after all. Also this warning
544 -- is suppressed if we already complained about the size.
546 --------------------------------
547 -- Compile_Time_Bad_Alignment --
548 --------------------------------
550 procedure Compile_Time_Bad_Alignment is
552 if not Size_Warning_Output
553 and then Address_Clause_Overlay_Warnings
556 ("?specified address for& may be inconsistent with alignment ",
559 ("\?program execution may be erroneous (RM 13.3(27))",
561 Set_Address_Warning_Posted (AC);
563 end Compile_Time_Bad_Alignment;
565 -- Start of processing for Apply_Address_Clause_Check
568 -- First obtain expression from address clause
570 Expr := Expression (AC);
572 -- The following loop digs for the real expression to use in the check
575 -- For constant, get constant expression
577 if Is_Entity_Name (Expr)
578 and then Ekind (Entity (Expr)) = E_Constant
580 Expr := Constant_Value (Entity (Expr));
582 -- For unchecked conversion, get result to convert
584 elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
585 Expr := Expression (Expr);
587 -- For (common case) of To_Address call, get argument
589 elsif Nkind (Expr) = N_Function_Call
590 and then Is_Entity_Name (Name (Expr))
591 and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
593 Expr := First (Parameter_Associations (Expr));
595 if Nkind (Expr) = N_Parameter_Association then
596 Expr := Explicit_Actual_Parameter (Expr);
599 -- We finally have the real expression
606 -- Output a warning if we have the situation of
608 -- for X'Address use Y'Address
610 -- and X and Y both have known object sizes, and Y is smaller than X
612 if Nkind (Expr) = N_Attribute_Reference
613 and then Attribute_Name (Expr) = Name_Address
614 and then Is_Entity_Name (Prefix (Expr))
617 Exp_Ent : constant Entity_Id := Entity (Prefix (Expr));
618 Obj_Size : Uint := No_Uint;
619 Exp_Size : Uint := No_Uint;
622 if Known_Esize (E) then
623 Obj_Size := Esize (E);
624 elsif Known_Esize (Etype (E)) then
625 Obj_Size := Esize (Etype (E));
628 if Known_Esize (Exp_Ent) then
629 Exp_Size := Esize (Exp_Ent);
630 elsif Known_Esize (Etype (Exp_Ent)) then
631 Exp_Size := Esize (Etype (Exp_Ent));
634 if Obj_Size /= No_Uint
635 and then Exp_Size /= No_Uint
636 and then Obj_Size > Exp_Size
637 and then not Has_Warnings_Off (E)
639 if Address_Clause_Overlay_Warnings then
641 ("?& overlays smaller object", Aexp, E);
643 ("\?program execution may be erroneous", Aexp, E);
644 Size_Warning_Output := True;
645 Set_Address_Warning_Posted (AC);
651 -- See if alignment check needed. Note that we never need a check if the
652 -- maximum alignment is one, since the check will always succeed.
654 -- Note: we do not check for checks suppressed here, since that check
655 -- was done in Sem_Ch13 when the address clause was processed. We are
656 -- only called if checks were not suppressed. The reason for this is
657 -- that we have to delay the call to Apply_Alignment_Check till freeze
658 -- time (so that all types etc are elaborated), but we have to check
659 -- the status of check suppressing at the point of the address clause.
662 or else not Check_Address_Alignment (AC)
663 or else Maximum_Alignment = 1
668 -- See if we know that Expr is a bad alignment at compile time
670 if Compile_Time_Known_Value (Expr)
671 and then (Known_Alignment (E) or else Known_Alignment (Typ))
674 AL : Uint := Alignment (Typ);
677 -- The object alignment might be more restrictive than the
680 if Known_Alignment (E) then
684 if Expr_Value (Expr) mod AL /= 0 then
685 Compile_Time_Bad_Alignment;
691 -- If the expression has the form X'Address, then we can find out if
692 -- the object X has an alignment that is compatible with the object E.
694 elsif Nkind (Expr) = N_Attribute_Reference
695 and then Attribute_Name (Expr) = Name_Address
698 AR : constant Alignment_Result :=
699 Has_Compatible_Alignment (E, Prefix (Expr));
701 if AR = Known_Compatible then
703 elsif AR = Known_Incompatible then
704 Compile_Time_Bad_Alignment;
709 -- Here we do not know if the value is acceptable. Stricly we don't have
710 -- to do anything, since if the alignment is bad, we have an erroneous
711 -- program. However we are allowed to check for erroneous conditions and
712 -- we decide to do this by default if the check is not suppressed.
714 -- However, don't do the check if elaboration code is unwanted
716 if Restriction_Active (No_Elaboration_Code) then
719 -- Generate a check to raise PE if alignment may be inappropriate
722 -- If the original expression is a non-static constant, use the
723 -- name of the constant itself rather than duplicating its
724 -- defining expression, which was extracted above.
726 -- Note: Expr is empty if the address-clause is applied to in-mode
727 -- actuals (allowed by 13.1(22)).
729 if not Present (Expr)
731 (Is_Entity_Name (Expression (AC))
732 and then Ekind (Entity (Expression (AC))) = E_Constant
733 and then Nkind (Parent (Entity (Expression (AC))))
734 = N_Object_Declaration)
736 Expr := New_Copy_Tree (Expression (AC));
738 Remove_Side_Effects (Expr);
741 Insert_After_And_Analyze (N,
742 Make_Raise_Program_Error (Loc,
749 (RTE (RE_Integer_Address), Expr),
751 Make_Attribute_Reference (Loc,
752 Prefix => New_Occurrence_Of (E, Loc),
753 Attribute_Name => Name_Alignment)),
754 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
755 Reason => PE_Misaligned_Address_Value),
756 Suppress => All_Checks);
761 -- If we have some missing run time component in configurable run time
762 -- mode then just skip the check (it is not required in any case).
764 when RE_Not_Available =>
766 end Apply_Address_Clause_Check;
768 -------------------------------------
769 -- Apply_Arithmetic_Overflow_Check --
770 -------------------------------------
772 -- This routine is called only if the type is an integer type, and a
773 -- software arithmetic overflow check may be needed for op (add, subtract,
774 -- or multiply). This check is performed only if Software_Overflow_Checking
775 -- is enabled and Do_Overflow_Check is set. In this case we expand the
776 -- operation into a more complex sequence of tests that ensures that
777 -- overflow is properly caught.
779 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
780 Loc : constant Source_Ptr := Sloc (N);
781 Typ : Entity_Id := Etype (N);
782 Rtyp : Entity_Id := Root_Type (Typ);
785 -- An interesting special case. If the arithmetic operation appears as
786 -- the operand of a type conversion:
790 -- and all the following conditions apply:
792 -- arithmetic operation is for a signed integer type
793 -- target type type1 is a static integer subtype
794 -- range of x and y are both included in the range of type1
795 -- range of x op y is included in the range of type1
796 -- size of type1 is at least twice the result size of op
798 -- then we don't do an overflow check in any case, instead we transform
799 -- the operation so that we end up with:
801 -- type1 (type1 (x) op type1 (y))
803 -- This avoids intermediate overflow before the conversion. It is
804 -- explicitly permitted by RM 3.5.4(24):
806 -- For the execution of a predefined operation of a signed integer
807 -- type, the implementation need not raise Constraint_Error if the
808 -- result is outside the base range of the type, so long as the
809 -- correct result is produced.
811 -- It's hard to imagine that any programmer counts on the exception
812 -- being raised in this case, and in any case it's wrong coding to
813 -- have this expectation, given the RM permission. Furthermore, other
814 -- Ada compilers do allow such out of range results.
816 -- Note that we do this transformation even if overflow checking is
817 -- off, since this is precisely about giving the "right" result and
818 -- avoiding the need for an overflow check.
820 if Is_Signed_Integer_Type (Typ)
821 and then Nkind (Parent (N)) = N_Type_Conversion
824 Target_Type : constant Entity_Id :=
825 Base_Type (Entity (Subtype_Mark (Parent (N))));
839 if Is_Integer_Type (Target_Type)
840 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
842 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
843 Thi := Expr_Value (Type_High_Bound (Target_Type));
845 Determine_Range (Left_Opnd (N), LOK, Llo, Lhi);
846 Determine_Range (Right_Opnd (N), ROK, Rlo, Rhi);
849 and then Tlo <= Llo and then Lhi <= Thi
850 and then Tlo <= Rlo and then Rhi <= Thi
852 Determine_Range (N, VOK, Vlo, Vhi);
854 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
855 Rewrite (Left_Opnd (N),
856 Make_Type_Conversion (Loc,
857 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
858 Expression => Relocate_Node (Left_Opnd (N))));
860 Rewrite (Right_Opnd (N),
861 Make_Type_Conversion (Loc,
862 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
863 Expression => Relocate_Node (Right_Opnd (N))));
865 Set_Etype (N, Target_Type);
867 Rtyp := Root_Type (Typ);
868 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
869 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
871 -- Given that the target type is twice the size of the
872 -- source type, overflow is now impossible, so we can
873 -- safely kill the overflow check and return.
875 Set_Do_Overflow_Check (N, False);
883 -- Now see if an overflow check is required
886 Siz : constant Int := UI_To_Int (Esize (Rtyp));
887 Dsiz : constant Int := Siz * 2;
894 -- Skip check if back end does overflow checks, or the overflow flag
895 -- is not set anyway, or we are not doing code expansion.
897 -- Special case CLI target, where arithmetic overflow checks can be
898 -- performed for integer and long_integer
900 if Backend_Overflow_Checks_On_Target
901 or else not Do_Overflow_Check (N)
902 or else not Expander_Active
904 (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
909 -- Otherwise, generate the full general code for front end overflow
910 -- detection, which works by doing arithmetic in a larger type:
916 -- Typ (Checktyp (x) op Checktyp (y));
918 -- where Typ is the type of the original expression, and Checktyp is
919 -- an integer type of sufficient length to hold the largest possible
922 -- If the size of check type exceeds the size of Long_Long_Integer,
923 -- we use a different approach, expanding to:
925 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
927 -- where xxx is Add, Multiply or Subtract as appropriate
929 -- Find check type if one exists
931 if Dsiz <= Standard_Integer_Size then
932 Ctyp := Standard_Integer;
934 elsif Dsiz <= Standard_Long_Long_Integer_Size then
935 Ctyp := Standard_Long_Long_Integer;
937 -- No check type exists, use runtime call
940 if Nkind (N) = N_Op_Add then
941 Cent := RE_Add_With_Ovflo_Check;
943 elsif Nkind (N) = N_Op_Multiply then
944 Cent := RE_Multiply_With_Ovflo_Check;
947 pragma Assert (Nkind (N) = N_Op_Subtract);
948 Cent := RE_Subtract_With_Ovflo_Check;
953 Make_Function_Call (Loc,
954 Name => New_Reference_To (RTE (Cent), Loc),
955 Parameter_Associations => New_List (
956 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
957 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
959 Analyze_And_Resolve (N, Typ);
963 -- If we fall through, we have the case where we do the arithmetic
964 -- in the next higher type and get the check by conversion. In these
965 -- cases Ctyp is set to the type to be used as the check type.
967 Opnod := Relocate_Node (N);
969 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
972 Set_Etype (Opnd, Ctyp);
973 Set_Analyzed (Opnd, True);
974 Set_Left_Opnd (Opnod, Opnd);
976 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
979 Set_Etype (Opnd, Ctyp);
980 Set_Analyzed (Opnd, True);
981 Set_Right_Opnd (Opnod, Opnd);
983 -- The type of the operation changes to the base type of the check
984 -- type, and we reset the overflow check indication, since clearly no
985 -- overflow is possible now that we are using a double length type.
986 -- We also set the Analyzed flag to avoid a recursive attempt to
989 Set_Etype (Opnod, Base_Type (Ctyp));
990 Set_Do_Overflow_Check (Opnod, False);
991 Set_Analyzed (Opnod, True);
993 -- Now build the outer conversion
995 Opnd := OK_Convert_To (Typ, Opnod);
997 Set_Etype (Opnd, Typ);
999 -- In the discrete type case, we directly generate the range check
1000 -- for the outer operand. This range check will implement the
1001 -- required overflow check.
1003 if Is_Discrete_Type (Typ) then
1005 Generate_Range_Check
1006 (Expression (N), Typ, CE_Overflow_Check_Failed);
1008 -- For other types, we enable overflow checking on the conversion,
1009 -- after setting the node as analyzed to prevent recursive attempts
1010 -- to expand the conversion node.
1013 Set_Analyzed (Opnd, True);
1014 Enable_Overflow_Check (Opnd);
1019 when RE_Not_Available =>
1022 end Apply_Arithmetic_Overflow_Check;
1024 ----------------------------
1025 -- Apply_Constraint_Check --
1026 ----------------------------
1028 procedure Apply_Constraint_Check
1031 No_Sliding : Boolean := False)
1033 Desig_Typ : Entity_Id;
1036 if Inside_A_Generic then
1039 elsif Is_Scalar_Type (Typ) then
1040 Apply_Scalar_Range_Check (N, Typ);
1042 elsif Is_Array_Type (Typ) then
1044 -- A useful optimization: an aggregate with only an others clause
1045 -- always has the right bounds.
1047 if Nkind (N) = N_Aggregate
1048 and then No (Expressions (N))
1050 (First (Choices (First (Component_Associations (N)))))
1056 if Is_Constrained (Typ) then
1057 Apply_Length_Check (N, Typ);
1060 Apply_Range_Check (N, Typ);
1063 Apply_Range_Check (N, Typ);
1066 elsif (Is_Record_Type (Typ)
1067 or else Is_Private_Type (Typ))
1068 and then Has_Discriminants (Base_Type (Typ))
1069 and then Is_Constrained (Typ)
1071 Apply_Discriminant_Check (N, Typ);
1073 elsif Is_Access_Type (Typ) then
1075 Desig_Typ := Designated_Type (Typ);
1077 -- No checks necessary if expression statically null
1079 if Known_Null (N) then
1080 if Can_Never_Be_Null (Typ) then
1081 Install_Null_Excluding_Check (N);
1084 -- No sliding possible on access to arrays
1086 elsif Is_Array_Type (Desig_Typ) then
1087 if Is_Constrained (Desig_Typ) then
1088 Apply_Length_Check (N, Typ);
1091 Apply_Range_Check (N, Typ);
1093 elsif Has_Discriminants (Base_Type (Desig_Typ))
1094 and then Is_Constrained (Desig_Typ)
1096 Apply_Discriminant_Check (N, Typ);
1099 -- Apply the the 2005 Null_Excluding check. Note that we do not apply
1100 -- this check if the constraint node is illegal, as shown by having
1101 -- an error posted. This additional guard prevents cascaded errors
1102 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1104 if Can_Never_Be_Null (Typ)
1105 and then not Can_Never_Be_Null (Etype (N))
1106 and then not Error_Posted (N)
1108 Install_Null_Excluding_Check (N);
1111 end Apply_Constraint_Check;
1113 ------------------------------
1114 -- Apply_Discriminant_Check --
1115 ------------------------------
1117 procedure Apply_Discriminant_Check
1120 Lhs : Node_Id := Empty)
1122 Loc : constant Source_Ptr := Sloc (N);
1123 Do_Access : constant Boolean := Is_Access_Type (Typ);
1124 S_Typ : Entity_Id := Etype (N);
1128 function Is_Aliased_Unconstrained_Component return Boolean;
1129 -- It is possible for an aliased component to have a nominal
1130 -- unconstrained subtype (through instantiation). If this is a
1131 -- discriminated component assigned in the expansion of an aggregate
1132 -- in an initialization, the check must be suppressed. This unusual
1133 -- situation requires a predicate of its own.
1135 ----------------------------------------
1136 -- Is_Aliased_Unconstrained_Component --
1137 ----------------------------------------
1139 function Is_Aliased_Unconstrained_Component return Boolean is
1144 if Nkind (Lhs) /= N_Selected_Component then
1147 Comp := Entity (Selector_Name (Lhs));
1148 Pref := Prefix (Lhs);
1151 if Ekind (Comp) /= E_Component
1152 or else not Is_Aliased (Comp)
1157 return not Comes_From_Source (Pref)
1158 and then In_Instance
1159 and then not Is_Constrained (Etype (Comp));
1160 end Is_Aliased_Unconstrained_Component;
1162 -- Start of processing for Apply_Discriminant_Check
1166 T_Typ := Designated_Type (Typ);
1171 -- Nothing to do if discriminant checks are suppressed or else no code
1172 -- is to be generated
1174 if not Expander_Active
1175 or else Discriminant_Checks_Suppressed (T_Typ)
1180 -- No discriminant checks necessary for an access when expression is
1181 -- statically Null. This is not only an optimization, it is fundamental
1182 -- because otherwise discriminant checks may be generated in init procs
1183 -- for types containing an access to a not-yet-frozen record, causing a
1184 -- deadly forward reference.
1186 -- Also, if the expression is of an access type whose designated type is
1187 -- incomplete, then the access value must be null and we suppress the
1190 if Known_Null (N) then
1193 elsif Is_Access_Type (S_Typ) then
1194 S_Typ := Designated_Type (S_Typ);
1196 if Ekind (S_Typ) = E_Incomplete_Type then
1201 -- If an assignment target is present, then we need to generate the
1202 -- actual subtype if the target is a parameter or aliased object with
1203 -- an unconstrained nominal subtype.
1205 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1206 -- subtype to the parameter and dereference cases, since other aliased
1207 -- objects are unconstrained (unless the nominal subtype is explicitly
1208 -- constrained). (But we also need to test for renamings???)
1211 and then (Present (Param_Entity (Lhs))
1212 or else (Ada_Version < Ada_05
1213 and then not Is_Constrained (T_Typ)
1214 and then Is_Aliased_View (Lhs)
1215 and then not Is_Aliased_Unconstrained_Component)
1216 or else (Ada_Version >= Ada_05
1217 and then not Is_Constrained (T_Typ)
1218 and then Nkind (Lhs) = N_Explicit_Dereference
1219 and then Nkind (Original_Node (Lhs)) /=
1222 T_Typ := Get_Actual_Subtype (Lhs);
1225 -- Nothing to do if the type is unconstrained (this is the case where
1226 -- the actual subtype in the RM sense of N is unconstrained and no check
1229 if not Is_Constrained (T_Typ) then
1232 -- Ada 2005: nothing to do if the type is one for which there is a
1233 -- partial view that is constrained.
1235 elsif Ada_Version >= Ada_05
1236 and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1241 -- Nothing to do if the type is an Unchecked_Union
1243 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1247 -- Suppress checks if the subtypes are the same. the check must be
1248 -- preserved in an assignment to a formal, because the constraint is
1249 -- given by the actual.
1251 if Nkind (Original_Node (N)) /= N_Allocator
1253 or else not Is_Entity_Name (Lhs)
1254 or else No (Param_Entity (Lhs)))
1257 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1258 and then not Is_Aliased_View (Lhs)
1263 -- We can also eliminate checks on allocators with a subtype mark that
1264 -- coincides with the context type. The context type may be a subtype
1265 -- without a constraint (common case, a generic actual).
1267 elsif Nkind (Original_Node (N)) = N_Allocator
1268 and then Is_Entity_Name (Expression (Original_Node (N)))
1271 Alloc_Typ : constant Entity_Id :=
1272 Entity (Expression (Original_Node (N)));
1275 if Alloc_Typ = T_Typ
1276 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1277 and then Is_Entity_Name (
1278 Subtype_Indication (Parent (T_Typ)))
1279 and then Alloc_Typ = Base_Type (T_Typ))
1287 -- See if we have a case where the types are both constrained, and all
1288 -- the constraints are constants. In this case, we can do the check
1289 -- successfully at compile time.
1291 -- We skip this check for the case where the node is a rewritten`
1292 -- allocator, because it already carries the context subtype, and
1293 -- extracting the discriminants from the aggregate is messy.
1295 if Is_Constrained (S_Typ)
1296 and then Nkind (Original_Node (N)) /= N_Allocator
1306 -- S_Typ may not have discriminants in the case where it is a
1307 -- private type completed by a default discriminated type. In that
1308 -- case, we need to get the constraints from the underlying_type.
1309 -- If the underlying type is unconstrained (i.e. has no default
1310 -- discriminants) no check is needed.
1312 if Has_Discriminants (S_Typ) then
1313 Discr := First_Discriminant (S_Typ);
1314 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1317 Discr := First_Discriminant (Underlying_Type (S_Typ));
1320 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1326 -- A further optimization: if T_Typ is derived from S_Typ
1327 -- without imposing a constraint, no check is needed.
1329 if Nkind (Original_Node (Parent (T_Typ))) =
1330 N_Full_Type_Declaration
1333 Type_Def : constant Node_Id :=
1335 (Original_Node (Parent (T_Typ)));
1337 if Nkind (Type_Def) = N_Derived_Type_Definition
1338 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1339 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1347 DconT := First_Elmt (Discriminant_Constraint (T_Typ));
1349 while Present (Discr) loop
1350 ItemS := Node (DconS);
1351 ItemT := Node (DconT);
1353 -- For a discriminated component type constrained by the
1354 -- current instance of an enclosing type, there is no
1355 -- applicable discriminant check.
1357 if Nkind (ItemT) = N_Attribute_Reference
1358 and then Is_Access_Type (Etype (ItemT))
1359 and then Is_Entity_Name (Prefix (ItemT))
1360 and then Is_Type (Entity (Prefix (ItemT)))
1365 -- If the expressions for the discriminants are identical
1366 -- and it is side-effect free (for now just an entity),
1367 -- this may be a shared constraint, e.g. from a subtype
1368 -- without a constraint introduced as a generic actual.
1369 -- Examine other discriminants if any.
1372 and then Is_Entity_Name (ItemS)
1376 elsif not Is_OK_Static_Expression (ItemS)
1377 or else not Is_OK_Static_Expression (ItemT)
1381 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1382 if Do_Access then -- needs run-time check.
1385 Apply_Compile_Time_Constraint_Error
1386 (N, "incorrect value for discriminant&?",
1387 CE_Discriminant_Check_Failed, Ent => Discr);
1394 Next_Discriminant (Discr);
1403 -- Here we need a discriminant check. First build the expression
1404 -- for the comparisons of the discriminants:
1406 -- (n.disc1 /= typ.disc1) or else
1407 -- (n.disc2 /= typ.disc2) or else
1409 -- (n.discn /= typ.discn)
1411 Cond := Build_Discriminant_Checks (N, T_Typ);
1413 -- If Lhs is set and is a parameter, then the condition is
1414 -- guarded by: lhs'constrained and then (condition built above)
1416 if Present (Param_Entity (Lhs)) then
1420 Make_Attribute_Reference (Loc,
1421 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1422 Attribute_Name => Name_Constrained),
1423 Right_Opnd => Cond);
1427 Cond := Guard_Access (Cond, Loc, N);
1431 Make_Raise_Constraint_Error (Loc,
1433 Reason => CE_Discriminant_Check_Failed));
1434 end Apply_Discriminant_Check;
1436 ------------------------
1437 -- Apply_Divide_Check --
1438 ------------------------
1440 procedure Apply_Divide_Check (N : Node_Id) is
1441 Loc : constant Source_Ptr := Sloc (N);
1442 Typ : constant Entity_Id := Etype (N);
1443 Left : constant Node_Id := Left_Opnd (N);
1444 Right : constant Node_Id := Right_Opnd (N);
1454 pragma Warnings (Off, Lhi);
1455 -- Don't actually use this value
1459 and then not Backend_Divide_Checks_On_Target
1460 and then Check_Needed (Right, Division_Check)
1462 Determine_Range (Right, ROK, Rlo, Rhi);
1464 -- See if division by zero possible, and if so generate test. This
1465 -- part of the test is not controlled by the -gnato switch.
1467 if Do_Division_Check (N) then
1468 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1470 Make_Raise_Constraint_Error (Loc,
1473 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1474 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1475 Reason => CE_Divide_By_Zero));
1479 -- Test for extremely annoying case of xxx'First divided by -1
1481 if Do_Overflow_Check (N) then
1482 if Nkind (N) = N_Op_Divide
1483 and then Is_Signed_Integer_Type (Typ)
1485 Determine_Range (Left, LOK, Llo, Lhi);
1486 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1488 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1490 ((not LOK) or else (Llo = LLB))
1493 Make_Raise_Constraint_Error (Loc,
1499 Duplicate_Subexpr_Move_Checks (Left),
1500 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1504 Duplicate_Subexpr (Right),
1506 Make_Integer_Literal (Loc, -1))),
1507 Reason => CE_Overflow_Check_Failed));
1512 end Apply_Divide_Check;
1514 ----------------------------------
1515 -- Apply_Float_Conversion_Check --
1516 ----------------------------------
1518 -- Let F and I be the source and target types of the conversion. The RM
1519 -- specifies that a floating-point value X is rounded to the nearest
1520 -- integer, with halfway cases being rounded away from zero. The rounded
1521 -- value of X is checked against I'Range.
1523 -- The catch in the above paragraph is that there is no good way to know
1524 -- whether the round-to-integer operation resulted in overflow. A remedy is
1525 -- to perform a range check in the floating-point domain instead, however:
1527 -- (1) The bounds may not be known at compile time
1528 -- (2) The check must take into account rounding or truncation.
1529 -- (3) The range of type I may not be exactly representable in F.
1530 -- (4) For the rounding case, The end-points I'First - 0.5 and
1531 -- I'Last + 0.5 may or may not be in range, depending on the
1532 -- sign of I'First and I'Last.
1533 -- (5) X may be a NaN, which will fail any comparison
1535 -- The following steps correctly convert X with rounding:
1537 -- (1) If either I'First or I'Last is not known at compile time, use
1538 -- I'Base instead of I in the next three steps and perform a
1539 -- regular range check against I'Range after conversion.
1540 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1541 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1542 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1543 -- In other words, take one of the closest floating-point numbers
1544 -- (which is an integer value) to I'First, and see if it is in
1546 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1547 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1548 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1549 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1550 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1552 -- For the truncating case, replace steps (2) and (3) as follows:
1553 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1554 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1556 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1557 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1560 procedure Apply_Float_Conversion_Check
1562 Target_Typ : Entity_Id)
1564 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1565 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1566 Loc : constant Source_Ptr := Sloc (Ck_Node);
1567 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1568 Target_Base : constant Entity_Id :=
1569 Implementation_Base_Type (Target_Typ);
1571 Par : constant Node_Id := Parent (Ck_Node);
1572 pragma Assert (Nkind (Par) = N_Type_Conversion);
1573 -- Parent of check node, must be a type conversion
1575 Truncate : constant Boolean := Float_Truncate (Par);
1576 Max_Bound : constant Uint :=
1578 (Machine_Radix (Expr_Type),
1579 Machine_Mantissa (Expr_Type) - 1) - 1;
1581 -- Largest bound, so bound plus or minus half is a machine number of F
1583 Ifirst, Ilast : Uint;
1584 -- Bounds of integer type
1587 -- Bounds to check in floating-point domain
1589 Lo_OK, Hi_OK : Boolean;
1590 -- True iff Lo resp. Hi belongs to I'Range
1592 Lo_Chk, Hi_Chk : Node_Id;
1593 -- Expressions that are False iff check fails
1595 Reason : RT_Exception_Code;
1598 if not Compile_Time_Known_Value (LB)
1599 or not Compile_Time_Known_Value (HB)
1602 -- First check that the value falls in the range of the base type,
1603 -- to prevent overflow during conversion and then perform a
1604 -- regular range check against the (dynamic) bounds.
1606 pragma Assert (Target_Base /= Target_Typ);
1608 Temp : constant Entity_Id :=
1609 Make_Defining_Identifier (Loc,
1610 Chars => New_Internal_Name ('T'));
1613 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1614 Set_Etype (Temp, Target_Base);
1616 Insert_Action (Parent (Par),
1617 Make_Object_Declaration (Loc,
1618 Defining_Identifier => Temp,
1619 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1620 Expression => New_Copy_Tree (Par)),
1621 Suppress => All_Checks);
1624 Make_Raise_Constraint_Error (Loc,
1627 Left_Opnd => New_Occurrence_Of (Temp, Loc),
1628 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1629 Reason => CE_Range_Check_Failed));
1630 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1636 -- Get the (static) bounds of the target type
1638 Ifirst := Expr_Value (LB);
1639 Ilast := Expr_Value (HB);
1641 -- A simple optimization: if the expression is a universal literal,
1642 -- we can do the comparison with the bounds and the conversion to
1643 -- an integer type statically. The range checks are unchanged.
1645 if Nkind (Ck_Node) = N_Real_Literal
1646 and then Etype (Ck_Node) = Universal_Real
1647 and then Is_Integer_Type (Target_Typ)
1648 and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
1651 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
1654 if Int_Val <= Ilast and then Int_Val >= Ifirst then
1656 -- Conversion is safe
1658 Rewrite (Parent (Ck_Node),
1659 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
1660 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
1666 -- Check against lower bound
1668 if Truncate and then Ifirst > 0 then
1669 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
1673 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
1676 elsif abs (Ifirst) < Max_Bound then
1677 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1678 Lo_OK := (Ifirst > 0);
1681 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1682 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1687 -- Lo_Chk := (X >= Lo)
1689 Lo_Chk := Make_Op_Ge (Loc,
1690 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1691 Right_Opnd => Make_Real_Literal (Loc, Lo));
1694 -- Lo_Chk := (X > Lo)
1696 Lo_Chk := Make_Op_Gt (Loc,
1697 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1698 Right_Opnd => Make_Real_Literal (Loc, Lo));
1701 -- Check against higher bound
1703 if Truncate and then Ilast < 0 then
1704 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
1708 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
1711 elsif abs (Ilast) < Max_Bound then
1712 Hi := UR_From_Uint (Ilast) + Ureal_Half;
1713 Hi_OK := (Ilast < 0);
1715 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1716 Hi_OK := (Hi <= UR_From_Uint (Ilast));
1721 -- Hi_Chk := (X <= Hi)
1723 Hi_Chk := Make_Op_Le (Loc,
1724 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1725 Right_Opnd => Make_Real_Literal (Loc, Hi));
1728 -- Hi_Chk := (X < Hi)
1730 Hi_Chk := Make_Op_Lt (Loc,
1731 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1732 Right_Opnd => Make_Real_Literal (Loc, Hi));
1735 -- If the bounds of the target type are the same as those of the base
1736 -- type, the check is an overflow check as a range check is not
1737 -- performed in these cases.
1739 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1740 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1742 Reason := CE_Overflow_Check_Failed;
1744 Reason := CE_Range_Check_Failed;
1747 -- Raise CE if either conditions does not hold
1749 Insert_Action (Ck_Node,
1750 Make_Raise_Constraint_Error (Loc,
1751 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1753 end Apply_Float_Conversion_Check;
1755 ------------------------
1756 -- Apply_Length_Check --
1757 ------------------------
1759 procedure Apply_Length_Check
1761 Target_Typ : Entity_Id;
1762 Source_Typ : Entity_Id := Empty)
1765 Apply_Selected_Length_Checks
1766 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1767 end Apply_Length_Check;
1769 -----------------------
1770 -- Apply_Range_Check --
1771 -----------------------
1773 procedure Apply_Range_Check
1775 Target_Typ : Entity_Id;
1776 Source_Typ : Entity_Id := Empty)
1779 Apply_Selected_Range_Checks
1780 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1781 end Apply_Range_Check;
1783 ------------------------------
1784 -- Apply_Scalar_Range_Check --
1785 ------------------------------
1787 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1788 -- off if it is already set on.
1790 procedure Apply_Scalar_Range_Check
1792 Target_Typ : Entity_Id;
1793 Source_Typ : Entity_Id := Empty;
1794 Fixed_Int : Boolean := False)
1796 Parnt : constant Node_Id := Parent (Expr);
1798 Arr : Node_Id := Empty; -- initialize to prevent warning
1799 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
1802 Is_Subscr_Ref : Boolean;
1803 -- Set true if Expr is a subscript
1805 Is_Unconstrained_Subscr_Ref : Boolean;
1806 -- Set true if Expr is a subscript of an unconstrained array. In this
1807 -- case we do not attempt to do an analysis of the value against the
1808 -- range of the subscript, since we don't know the actual subtype.
1811 -- Set to True if Expr should be regarded as a real value even though
1812 -- the type of Expr might be discrete.
1814 procedure Bad_Value;
1815 -- Procedure called if value is determined to be out of range
1821 procedure Bad_Value is
1823 Apply_Compile_Time_Constraint_Error
1824 (Expr, "value not in range of}?", CE_Range_Check_Failed,
1829 -- Start of processing for Apply_Scalar_Range_Check
1832 -- Return if check obviously not needed
1835 -- Not needed inside generic
1839 -- Not needed if previous error
1841 or else Target_Typ = Any_Type
1842 or else Nkind (Expr) = N_Error
1844 -- Not needed for non-scalar type
1846 or else not Is_Scalar_Type (Target_Typ)
1848 -- Not needed if we know node raises CE already
1850 or else Raises_Constraint_Error (Expr)
1855 -- Now, see if checks are suppressed
1858 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1860 if Is_Subscr_Ref then
1861 Arr := Prefix (Parnt);
1862 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1865 if not Do_Range_Check (Expr) then
1867 -- Subscript reference. Check for Index_Checks suppressed
1869 if Is_Subscr_Ref then
1871 -- Check array type and its base type
1873 if Index_Checks_Suppressed (Arr_Typ)
1874 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1878 -- Check array itself if it is an entity name
1880 elsif Is_Entity_Name (Arr)
1881 and then Index_Checks_Suppressed (Entity (Arr))
1885 -- Check expression itself if it is an entity name
1887 elsif Is_Entity_Name (Expr)
1888 and then Index_Checks_Suppressed (Entity (Expr))
1893 -- All other cases, check for Range_Checks suppressed
1896 -- Check target type and its base type
1898 if Range_Checks_Suppressed (Target_Typ)
1899 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1903 -- Check expression itself if it is an entity name
1905 elsif Is_Entity_Name (Expr)
1906 and then Range_Checks_Suppressed (Entity (Expr))
1910 -- If Expr is part of an assignment statement, then check left
1911 -- side of assignment if it is an entity name.
1913 elsif Nkind (Parnt) = N_Assignment_Statement
1914 and then Is_Entity_Name (Name (Parnt))
1915 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1922 -- Do not set range checks if they are killed
1924 if Nkind (Expr) = N_Unchecked_Type_Conversion
1925 and then Kill_Range_Check (Expr)
1930 -- Do not set range checks for any values from System.Scalar_Values
1931 -- since the whole idea of such values is to avoid checking them!
1933 if Is_Entity_Name (Expr)
1934 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1939 -- Now see if we need a check
1941 if No (Source_Typ) then
1942 S_Typ := Etype (Expr);
1944 S_Typ := Source_Typ;
1947 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1951 Is_Unconstrained_Subscr_Ref :=
1952 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1954 -- Always do a range check if the source type includes infinities and
1955 -- the target type does not include infinities. We do not do this if
1956 -- range checks are killed.
1958 if Is_Floating_Point_Type (S_Typ)
1959 and then Has_Infinities (S_Typ)
1960 and then not Has_Infinities (Target_Typ)
1962 Enable_Range_Check (Expr);
1965 -- Return if we know expression is definitely in the range of the target
1966 -- type as determined by Determine_Range. Right now we only do this for
1967 -- discrete types, and not fixed-point or floating-point types.
1969 -- The additional less-precise tests below catch these cases
1971 -- Note: skip this if we are given a source_typ, since the point of
1972 -- supplying a Source_Typ is to stop us looking at the expression.
1973 -- We could sharpen this test to be out parameters only ???
1975 if Is_Discrete_Type (Target_Typ)
1976 and then Is_Discrete_Type (Etype (Expr))
1977 and then not Is_Unconstrained_Subscr_Ref
1978 and then No (Source_Typ)
1981 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
1982 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
1987 if Compile_Time_Known_Value (Tlo)
1988 and then Compile_Time_Known_Value (Thi)
1991 Lov : constant Uint := Expr_Value (Tlo);
1992 Hiv : constant Uint := Expr_Value (Thi);
1995 -- If range is null, we for sure have a constraint error
1996 -- (we don't even need to look at the value involved,
1997 -- since all possible values will raise CE).
2004 -- Otherwise determine range of value
2006 Determine_Range (Expr, OK, Lo, Hi);
2010 -- If definitely in range, all OK
2012 if Lo >= Lov and then Hi <= Hiv then
2015 -- If definitely not in range, warn
2017 elsif Lov > Hi or else Hiv < Lo then
2021 -- Otherwise we don't know
2033 Is_Floating_Point_Type (S_Typ)
2034 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
2036 -- Check if we can determine at compile time whether Expr is in the
2037 -- range of the target type. Note that if S_Typ is within the bounds
2038 -- of Target_Typ then this must be the case. This check is meaningful
2039 -- only if this is not a conversion between integer and real types.
2041 if not Is_Unconstrained_Subscr_Ref
2043 Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
2045 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
2047 Is_In_Range (Expr, Target_Typ, Fixed_Int, Int_Real))
2051 elsif Is_Out_Of_Range (Expr, Target_Typ, Fixed_Int, Int_Real) then
2055 -- In the floating-point case, we only do range checks if the type is
2056 -- constrained. We definitely do NOT want range checks for unconstrained
2057 -- types, since we want to have infinities
2059 elsif Is_Floating_Point_Type (S_Typ) then
2060 if Is_Constrained (S_Typ) then
2061 Enable_Range_Check (Expr);
2064 -- For all other cases we enable a range check unconditionally
2067 Enable_Range_Check (Expr);
2070 end Apply_Scalar_Range_Check;
2072 ----------------------------------
2073 -- Apply_Selected_Length_Checks --
2074 ----------------------------------
2076 procedure Apply_Selected_Length_Checks
2078 Target_Typ : Entity_Id;
2079 Source_Typ : Entity_Id;
2080 Do_Static : Boolean)
2083 R_Result : Check_Result;
2086 Loc : constant Source_Ptr := Sloc (Ck_Node);
2087 Checks_On : constant Boolean :=
2088 (not Index_Checks_Suppressed (Target_Typ))
2090 (not Length_Checks_Suppressed (Target_Typ));
2093 if not Expander_Active then
2098 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2100 for J in 1 .. 2 loop
2101 R_Cno := R_Result (J);
2102 exit when No (R_Cno);
2104 -- A length check may mention an Itype which is attached to a
2105 -- subsequent node. At the top level in a package this can cause
2106 -- an order-of-elaboration problem, so we make sure that the itype
2107 -- is referenced now.
2109 if Ekind (Current_Scope) = E_Package
2110 and then Is_Compilation_Unit (Current_Scope)
2112 Ensure_Defined (Target_Typ, Ck_Node);
2114 if Present (Source_Typ) then
2115 Ensure_Defined (Source_Typ, Ck_Node);
2117 elsif Is_Itype (Etype (Ck_Node)) then
2118 Ensure_Defined (Etype (Ck_Node), Ck_Node);
2122 -- If the item is a conditional raise of constraint error, then have
2123 -- a look at what check is being performed and ???
2125 if Nkind (R_Cno) = N_Raise_Constraint_Error
2126 and then Present (Condition (R_Cno))
2128 Cond := Condition (R_Cno);
2130 -- Case where node does not now have a dynamic check
2132 if not Has_Dynamic_Length_Check (Ck_Node) then
2134 -- If checks are on, just insert the check
2137 Insert_Action (Ck_Node, R_Cno);
2139 if not Do_Static then
2140 Set_Has_Dynamic_Length_Check (Ck_Node);
2143 -- If checks are off, then analyze the length check after
2144 -- temporarily attaching it to the tree in case the relevant
2145 -- condition can be evaluted at compile time. We still want a
2146 -- compile time warning in this case.
2149 Set_Parent (R_Cno, Ck_Node);
2154 -- Output a warning if the condition is known to be True
2156 if Is_Entity_Name (Cond)
2157 and then Entity (Cond) = Standard_True
2159 Apply_Compile_Time_Constraint_Error
2160 (Ck_Node, "wrong length for array of}?",
2161 CE_Length_Check_Failed,
2165 -- If we were only doing a static check, or if checks are not
2166 -- on, then we want to delete the check, since it is not needed.
2167 -- We do this by replacing the if statement by a null statement
2169 elsif Do_Static or else not Checks_On then
2170 Remove_Warning_Messages (R_Cno);
2171 Rewrite (R_Cno, Make_Null_Statement (Loc));
2175 Install_Static_Check (R_Cno, Loc);
2178 end Apply_Selected_Length_Checks;
2180 ---------------------------------
2181 -- Apply_Selected_Range_Checks --
2182 ---------------------------------
2184 procedure Apply_Selected_Range_Checks
2186 Target_Typ : Entity_Id;
2187 Source_Typ : Entity_Id;
2188 Do_Static : Boolean)
2191 R_Result : Check_Result;
2194 Loc : constant Source_Ptr := Sloc (Ck_Node);
2195 Checks_On : constant Boolean :=
2196 (not Index_Checks_Suppressed (Target_Typ))
2198 (not Range_Checks_Suppressed (Target_Typ));
2201 if not Expander_Active or else not Checks_On then
2206 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2208 for J in 1 .. 2 loop
2210 R_Cno := R_Result (J);
2211 exit when No (R_Cno);
2213 -- If the item is a conditional raise of constraint error, then have
2214 -- a look at what check is being performed and ???
2216 if Nkind (R_Cno) = N_Raise_Constraint_Error
2217 and then Present (Condition (R_Cno))
2219 Cond := Condition (R_Cno);
2221 if not Has_Dynamic_Range_Check (Ck_Node) then
2222 Insert_Action (Ck_Node, R_Cno);
2224 if not Do_Static then
2225 Set_Has_Dynamic_Range_Check (Ck_Node);
2229 -- Output a warning if the condition is known to be True
2231 if Is_Entity_Name (Cond)
2232 and then Entity (Cond) = Standard_True
2234 -- Since an N_Range is technically not an expression, we have
2235 -- to set one of the bounds to C_E and then just flag the
2236 -- N_Range. The warning message will point to the lower bound
2237 -- and complain about a range, which seems OK.
2239 if Nkind (Ck_Node) = N_Range then
2240 Apply_Compile_Time_Constraint_Error
2241 (Low_Bound (Ck_Node), "static range out of bounds of}?",
2242 CE_Range_Check_Failed,
2246 Set_Raises_Constraint_Error (Ck_Node);
2249 Apply_Compile_Time_Constraint_Error
2250 (Ck_Node, "static value out of range of}?",
2251 CE_Range_Check_Failed,
2256 -- If we were only doing a static check, or if checks are not
2257 -- on, then we want to delete the check, since it is not needed.
2258 -- We do this by replacing the if statement by a null statement
2260 elsif Do_Static or else not Checks_On then
2261 Remove_Warning_Messages (R_Cno);
2262 Rewrite (R_Cno, Make_Null_Statement (Loc));
2266 Install_Static_Check (R_Cno, Loc);
2269 end Apply_Selected_Range_Checks;
2271 -------------------------------
2272 -- Apply_Static_Length_Check --
2273 -------------------------------
2275 procedure Apply_Static_Length_Check
2277 Target_Typ : Entity_Id;
2278 Source_Typ : Entity_Id := Empty)
2281 Apply_Selected_Length_Checks
2282 (Expr, Target_Typ, Source_Typ, Do_Static => True);
2283 end Apply_Static_Length_Check;
2285 -------------------------------------
2286 -- Apply_Subscript_Validity_Checks --
2287 -------------------------------------
2289 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2293 pragma Assert (Nkind (Expr) = N_Indexed_Component);
2295 -- Loop through subscripts
2297 Sub := First (Expressions (Expr));
2298 while Present (Sub) loop
2300 -- Check one subscript. Note that we do not worry about enumeration
2301 -- type with holes, since we will convert the value to a Pos value
2302 -- for the subscript, and that convert will do the necessary validity
2305 Ensure_Valid (Sub, Holes_OK => True);
2307 -- Move to next subscript
2311 end Apply_Subscript_Validity_Checks;
2313 ----------------------------------
2314 -- Apply_Type_Conversion_Checks --
2315 ----------------------------------
2317 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2318 Target_Type : constant Entity_Id := Etype (N);
2319 Target_Base : constant Entity_Id := Base_Type (Target_Type);
2320 Expr : constant Node_Id := Expression (N);
2321 Expr_Type : constant Entity_Id := Etype (Expr);
2324 if Inside_A_Generic then
2327 -- Skip these checks if serious errors detected, there are some nasty
2328 -- situations of incomplete trees that blow things up.
2330 elsif Serious_Errors_Detected > 0 then
2333 -- Scalar type conversions of the form Target_Type (Expr) require a
2334 -- range check if we cannot be sure that Expr is in the base type of
2335 -- Target_Typ and also that Expr is in the range of Target_Typ. These
2336 -- are not quite the same condition from an implementation point of
2337 -- view, but clearly the second includes the first.
2339 elsif Is_Scalar_Type (Target_Type) then
2341 Conv_OK : constant Boolean := Conversion_OK (N);
2342 -- If the Conversion_OK flag on the type conversion is set and no
2343 -- floating point type is involved in the type conversion then
2344 -- fixed point values must be read as integral values.
2346 Float_To_Int : constant Boolean :=
2347 Is_Floating_Point_Type (Expr_Type)
2348 and then Is_Integer_Type (Target_Type);
2351 if not Overflow_Checks_Suppressed (Target_Base)
2352 and then not In_Subrange_Of (Expr_Type, Target_Base, Conv_OK)
2353 and then not Float_To_Int
2355 Activate_Overflow_Check (N);
2358 if not Range_Checks_Suppressed (Target_Type)
2359 and then not Range_Checks_Suppressed (Expr_Type)
2361 if Float_To_Int then
2362 Apply_Float_Conversion_Check (Expr, Target_Type);
2364 Apply_Scalar_Range_Check
2365 (Expr, Target_Type, Fixed_Int => Conv_OK);
2370 elsif Comes_From_Source (N)
2371 and then not Discriminant_Checks_Suppressed (Target_Type)
2372 and then Is_Record_Type (Target_Type)
2373 and then Is_Derived_Type (Target_Type)
2374 and then not Is_Tagged_Type (Target_Type)
2375 and then not Is_Constrained (Target_Type)
2376 and then Present (Stored_Constraint (Target_Type))
2378 -- An unconstrained derived type may have inherited discriminant
2379 -- Build an actual discriminant constraint list using the stored
2380 -- constraint, to verify that the expression of the parent type
2381 -- satisfies the constraints imposed by the (unconstrained!)
2382 -- derived type. This applies to value conversions, not to view
2383 -- conversions of tagged types.
2386 Loc : constant Source_Ptr := Sloc (N);
2388 Constraint : Elmt_Id;
2389 Discr_Value : Node_Id;
2392 New_Constraints : constant Elist_Id := New_Elmt_List;
2393 Old_Constraints : constant Elist_Id :=
2394 Discriminant_Constraint (Expr_Type);
2397 Constraint := First_Elmt (Stored_Constraint (Target_Type));
2398 while Present (Constraint) loop
2399 Discr_Value := Node (Constraint);
2401 if Is_Entity_Name (Discr_Value)
2402 and then Ekind (Entity (Discr_Value)) = E_Discriminant
2404 Discr := Corresponding_Discriminant (Entity (Discr_Value));
2407 and then Scope (Discr) = Base_Type (Expr_Type)
2409 -- Parent is constrained by new discriminant. Obtain
2410 -- Value of original discriminant in expression. If the
2411 -- new discriminant has been used to constrain more than
2412 -- one of the stored discriminants, this will provide the
2413 -- required consistency check.
2416 Make_Selected_Component (Loc,
2418 Duplicate_Subexpr_No_Checks
2419 (Expr, Name_Req => True),
2421 Make_Identifier (Loc, Chars (Discr))),
2425 -- Discriminant of more remote ancestor ???
2430 -- Derived type definition has an explicit value for this
2431 -- stored discriminant.
2435 (Duplicate_Subexpr_No_Checks (Discr_Value),
2439 Next_Elmt (Constraint);
2442 -- Use the unconstrained expression type to retrieve the
2443 -- discriminants of the parent, and apply momentarily the
2444 -- discriminant constraint synthesized above.
2446 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2447 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2448 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2451 Make_Raise_Constraint_Error (Loc,
2453 Reason => CE_Discriminant_Check_Failed));
2456 -- For arrays, conversions are applied during expansion, to take into
2457 -- accounts changes of representation. The checks become range checks on
2458 -- the base type or length checks on the subtype, depending on whether
2459 -- the target type is unconstrained or constrained.
2464 end Apply_Type_Conversion_Checks;
2466 ----------------------------------------------
2467 -- Apply_Universal_Integer_Attribute_Checks --
2468 ----------------------------------------------
2470 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2471 Loc : constant Source_Ptr := Sloc (N);
2472 Typ : constant Entity_Id := Etype (N);
2475 if Inside_A_Generic then
2478 -- Nothing to do if checks are suppressed
2480 elsif Range_Checks_Suppressed (Typ)
2481 and then Overflow_Checks_Suppressed (Typ)
2485 -- Nothing to do if the attribute does not come from source. The
2486 -- internal attributes we generate of this type do not need checks,
2487 -- and furthermore the attempt to check them causes some circular
2488 -- elaboration orders when dealing with packed types.
2490 elsif not Comes_From_Source (N) then
2493 -- If the prefix is a selected component that depends on a discriminant
2494 -- the check may improperly expose a discriminant instead of using
2495 -- the bounds of the object itself. Set the type of the attribute to
2496 -- the base type of the context, so that a check will be imposed when
2497 -- needed (e.g. if the node appears as an index).
2499 elsif Nkind (Prefix (N)) = N_Selected_Component
2500 and then Ekind (Typ) = E_Signed_Integer_Subtype
2501 and then Depends_On_Discriminant (Scalar_Range (Typ))
2503 Set_Etype (N, Base_Type (Typ));
2505 -- Otherwise, replace the attribute node with a type conversion node
2506 -- whose expression is the attribute, retyped to universal integer, and
2507 -- whose subtype mark is the target type. The call to analyze this
2508 -- conversion will set range and overflow checks as required for proper
2509 -- detection of an out of range value.
2512 Set_Etype (N, Universal_Integer);
2513 Set_Analyzed (N, True);
2516 Make_Type_Conversion (Loc,
2517 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2518 Expression => Relocate_Node (N)));
2520 Analyze_And_Resolve (N, Typ);
2523 end Apply_Universal_Integer_Attribute_Checks;
2525 -------------------------------
2526 -- Build_Discriminant_Checks --
2527 -------------------------------
2529 function Build_Discriminant_Checks
2531 T_Typ : Entity_Id) return Node_Id
2533 Loc : constant Source_Ptr := Sloc (N);
2536 Disc_Ent : Entity_Id;
2540 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2542 ----------------------------------
2543 -- Aggregate_Discriminant_Value --
2544 ----------------------------------
2546 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2550 -- The aggregate has been normalized with named associations. We use
2551 -- the Chars field to locate the discriminant to take into account
2552 -- discriminants in derived types, which carry the same name as those
2555 Assoc := First (Component_Associations (N));
2556 while Present (Assoc) loop
2557 if Chars (First (Choices (Assoc))) = Chars (Disc) then
2558 return Expression (Assoc);
2564 -- Discriminant must have been found in the loop above
2566 raise Program_Error;
2567 end Aggregate_Discriminant_Val;
2569 -- Start of processing for Build_Discriminant_Checks
2572 -- Loop through discriminants evolving the condition
2575 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2577 -- For a fully private type, use the discriminants of the parent type
2579 if Is_Private_Type (T_Typ)
2580 and then No (Full_View (T_Typ))
2582 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2584 Disc_Ent := First_Discriminant (T_Typ);
2587 while Present (Disc) loop
2588 Dval := Node (Disc);
2590 if Nkind (Dval) = N_Identifier
2591 and then Ekind (Entity (Dval)) = E_Discriminant
2593 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2595 Dval := Duplicate_Subexpr_No_Checks (Dval);
2598 -- If we have an Unchecked_Union node, we can infer the discriminants
2601 if Is_Unchecked_Union (Base_Type (T_Typ)) then
2603 Get_Discriminant_Value (
2604 First_Discriminant (T_Typ),
2606 Stored_Constraint (T_Typ)));
2608 elsif Nkind (N) = N_Aggregate then
2610 Duplicate_Subexpr_No_Checks
2611 (Aggregate_Discriminant_Val (Disc_Ent));
2615 Make_Selected_Component (Loc,
2617 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2619 Make_Identifier (Loc, Chars (Disc_Ent)));
2621 Set_Is_In_Discriminant_Check (Dref);
2624 Evolve_Or_Else (Cond,
2627 Right_Opnd => Dval));
2630 Next_Discriminant (Disc_Ent);
2634 end Build_Discriminant_Checks;
2640 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2648 -- Always check if not simple entity
2650 if Nkind (Nod) not in N_Has_Entity
2651 or else not Comes_From_Source (Nod)
2656 -- Look up tree for short circuit
2663 -- Done if out of subexpression (note that we allow generated stuff
2664 -- such as itype declarations in this context, to keep the loop going
2665 -- since we may well have generated such stuff in complex situations.
2666 -- Also done if no parent (probably an error condition, but no point
2667 -- in behaving nasty if we find it!)
2670 or else (K not in N_Subexpr and then Comes_From_Source (P))
2674 -- Or/Or Else case, where test is part of the right operand, or is
2675 -- part of one of the actions associated with the right operand, and
2676 -- the left operand is an equality test.
2678 elsif K = N_Op_Or then
2679 exit when N = Right_Opnd (P)
2680 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2682 elsif K = N_Or_Else then
2683 exit when (N = Right_Opnd (P)
2686 and then List_Containing (N) = Actions (P)))
2687 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2689 -- Similar test for the And/And then case, where the left operand
2690 -- is an inequality test.
2692 elsif K = N_Op_And then
2693 exit when N = Right_Opnd (P)
2694 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2696 elsif K = N_And_Then then
2697 exit when (N = Right_Opnd (P)
2700 and then List_Containing (N) = Actions (P)))
2701 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2707 -- If we fall through the loop, then we have a conditional with an
2708 -- appropriate test as its left operand. So test further.
2711 R := Right_Opnd (L);
2714 -- Left operand of test must match original variable
2716 if Nkind (L) not in N_Has_Entity
2717 or else Entity (L) /= Entity (Nod)
2722 -- Right operand of test must be key value (zero or null)
2725 when Access_Check =>
2726 if not Known_Null (R) then
2730 when Division_Check =>
2731 if not Compile_Time_Known_Value (R)
2732 or else Expr_Value (R) /= Uint_0
2738 raise Program_Error;
2741 -- Here we have the optimizable case, warn if not short-circuited
2743 if K = N_Op_And or else K = N_Op_Or then
2745 when Access_Check =>
2747 ("Constraint_Error may be raised (access check)?",
2749 when Division_Check =>
2751 ("Constraint_Error may be raised (zero divide)?",
2755 raise Program_Error;
2758 if K = N_Op_And then
2759 Error_Msg_N ("use `AND THEN` instead of AND?", P);
2761 Error_Msg_N ("use `OR ELSE` instead of OR?", P);
2764 -- If not short-circuited, we need the ckeck
2768 -- If short-circuited, we can omit the check
2775 -----------------------------------
2776 -- Check_Valid_Lvalue_Subscripts --
2777 -----------------------------------
2779 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2781 -- Skip this if range checks are suppressed
2783 if Range_Checks_Suppressed (Etype (Expr)) then
2786 -- Only do this check for expressions that come from source. We assume
2787 -- that expander generated assignments explicitly include any necessary
2788 -- checks. Note that this is not just an optimization, it avoids
2789 -- infinite recursions!
2791 elsif not Comes_From_Source (Expr) then
2794 -- For a selected component, check the prefix
2796 elsif Nkind (Expr) = N_Selected_Component then
2797 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2800 -- Case of indexed component
2802 elsif Nkind (Expr) = N_Indexed_Component then
2803 Apply_Subscript_Validity_Checks (Expr);
2805 -- Prefix may itself be or contain an indexed component, and these
2806 -- subscripts need checking as well.
2808 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2810 end Check_Valid_Lvalue_Subscripts;
2812 ----------------------------------
2813 -- Null_Exclusion_Static_Checks --
2814 ----------------------------------
2816 procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2817 Error_Node : Node_Id;
2819 Has_Null : constant Boolean := Has_Null_Exclusion (N);
2820 K : constant Node_Kind := Nkind (N);
2825 (K = N_Component_Declaration
2826 or else K = N_Discriminant_Specification
2827 or else K = N_Function_Specification
2828 or else K = N_Object_Declaration
2829 or else K = N_Parameter_Specification);
2831 if K = N_Function_Specification then
2832 Typ := Etype (Defining_Entity (N));
2834 Typ := Etype (Defining_Identifier (N));
2838 when N_Component_Declaration =>
2839 if Present (Access_Definition (Component_Definition (N))) then
2840 Error_Node := Component_Definition (N);
2842 Error_Node := Subtype_Indication (Component_Definition (N));
2845 when N_Discriminant_Specification =>
2846 Error_Node := Discriminant_Type (N);
2848 when N_Function_Specification =>
2849 Error_Node := Result_Definition (N);
2851 when N_Object_Declaration =>
2852 Error_Node := Object_Definition (N);
2854 when N_Parameter_Specification =>
2855 Error_Node := Parameter_Type (N);
2858 raise Program_Error;
2863 -- Enforce legality rule 3.10 (13): A null exclusion can only be
2864 -- applied to an access [sub]type.
2866 if not Is_Access_Type (Typ) then
2868 ("`NOT NULL` allowed only for an access type", Error_Node);
2870 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
2871 -- be applied to a [sub]type that does not exclude null already.
2873 elsif Can_Never_Be_Null (Typ)
2874 and then Comes_From_Source (Typ)
2877 ("`NOT NULL` not allowed (& already excludes null)",
2882 -- Check that null-excluding objects are always initialized, except for
2883 -- deferred constants, for which the expression will appear in the full
2886 if K = N_Object_Declaration
2887 and then No (Expression (N))
2888 and then not Constant_Present (N)
2889 and then not No_Initialization (N)
2891 -- Add an expression that assigns null. This node is needed by
2892 -- Apply_Compile_Time_Constraint_Error, which will replace this with
2893 -- a Constraint_Error node.
2895 Set_Expression (N, Make_Null (Sloc (N)));
2896 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2898 Apply_Compile_Time_Constraint_Error
2899 (N => Expression (N),
2900 Msg => "(Ada 2005) null-excluding objects must be initialized?",
2901 Reason => CE_Null_Not_Allowed);
2904 -- Check that a null-excluding component, formal or object is not being
2905 -- assigned a null value. Otherwise generate a warning message and
2906 -- replace Expression (N) by an N_Constraint_Error node.
2908 if K /= N_Function_Specification then
2909 Expr := Expression (N);
2911 if Present (Expr) and then Known_Null (Expr) then
2913 when N_Component_Declaration |
2914 N_Discriminant_Specification =>
2915 Apply_Compile_Time_Constraint_Error
2917 Msg => "(Ada 2005) null not allowed " &
2918 "in null-excluding components?",
2919 Reason => CE_Null_Not_Allowed);
2921 when N_Object_Declaration =>
2922 Apply_Compile_Time_Constraint_Error
2924 Msg => "(Ada 2005) null not allowed " &
2925 "in null-excluding objects?",
2926 Reason => CE_Null_Not_Allowed);
2928 when N_Parameter_Specification =>
2929 Apply_Compile_Time_Constraint_Error
2931 Msg => "(Ada 2005) null not allowed " &
2932 "in null-excluding formals?",
2933 Reason => CE_Null_Not_Allowed);
2940 end Null_Exclusion_Static_Checks;
2942 ----------------------------------
2943 -- Conditional_Statements_Begin --
2944 ----------------------------------
2946 procedure Conditional_Statements_Begin is
2948 Saved_Checks_TOS := Saved_Checks_TOS + 1;
2950 -- If stack overflows, kill all checks, that way we know to simply reset
2951 -- the number of saved checks to zero on return. This should never occur
2954 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2957 -- In the normal case, we just make a new stack entry saving the current
2958 -- number of saved checks for a later restore.
2961 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
2963 if Debug_Flag_CC then
2964 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
2968 end Conditional_Statements_Begin;
2970 --------------------------------
2971 -- Conditional_Statements_End --
2972 --------------------------------
2974 procedure Conditional_Statements_End is
2976 pragma Assert (Saved_Checks_TOS > 0);
2978 -- If the saved checks stack overflowed, then we killed all checks, so
2979 -- setting the number of saved checks back to zero is correct. This
2980 -- should never occur in practice.
2982 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2983 Num_Saved_Checks := 0;
2985 -- In the normal case, restore the number of saved checks from the top
2989 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
2990 if Debug_Flag_CC then
2991 w ("Conditional_Statements_End: Num_Saved_Checks = ",
2996 Saved_Checks_TOS := Saved_Checks_TOS - 1;
2997 end Conditional_Statements_End;
2999 ---------------------
3000 -- Determine_Range --
3001 ---------------------
3003 Cache_Size : constant := 2 ** 10;
3004 type Cache_Index is range 0 .. Cache_Size - 1;
3005 -- Determine size of below cache (power of 2 is more efficient!)
3007 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
3008 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
3009 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
3010 -- The above arrays are used to implement a small direct cache for
3011 -- Determine_Range calls. Because of the way Determine_Range recursively
3012 -- traces subexpressions, and because overflow checking calls the routine
3013 -- on the way up the tree, a quadratic behavior can otherwise be
3014 -- encountered in large expressions. The cache entry for node N is stored
3015 -- in the (N mod Cache_Size) entry, and can be validated by checking the
3016 -- actual node value stored there.
3018 procedure Determine_Range
3024 Typ : constant Entity_Id := Etype (N);
3028 -- Lo and Hi bounds of left operand
3032 -- Lo and Hi bounds of right (or only) operand
3035 -- Temp variable used to hold a bound node
3038 -- High bound of base type of expression
3042 -- Refined values for low and high bounds, after tightening
3045 -- Used in lower level calls to indicate if call succeeded
3047 Cindex : Cache_Index;
3048 -- Used to search cache
3050 function OK_Operands return Boolean;
3051 -- Used for binary operators. Determines the ranges of the left and
3052 -- right operands, and if they are both OK, returns True, and puts
3053 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left
3059 function OK_Operands return Boolean is
3061 Determine_Range (Left_Opnd (N), OK1, Lo_Left, Hi_Left);
3067 Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
3071 -- Start of processing for Determine_Range
3074 -- Prevent junk warnings by initializing range variables
3081 -- If the type is not discrete, or is undefined, then we can't do
3082 -- anything about determining the range.
3084 if No (Typ) or else not Is_Discrete_Type (Typ)
3085 or else Error_Posted (N)
3091 -- For all other cases, we can determine the range
3095 -- If value is compile time known, then the possible range is the one
3096 -- value that we know this expression definitely has!
3098 if Compile_Time_Known_Value (N) then
3099 Lo := Expr_Value (N);
3104 -- Return if already in the cache
3106 Cindex := Cache_Index (N mod Cache_Size);
3108 if Determine_Range_Cache_N (Cindex) = N then
3109 Lo := Determine_Range_Cache_Lo (Cindex);
3110 Hi := Determine_Range_Cache_Hi (Cindex);
3114 -- Otherwise, start by finding the bounds of the type of the expression,
3115 -- the value cannot be outside this range (if it is, then we have an
3116 -- overflow situation, which is a separate check, we are talking here
3117 -- only about the expression value).
3119 -- We use the actual bound unless it is dynamic, in which case use the
3120 -- corresponding base type bound if possible. If we can't get a bound
3121 -- then we figure we can't determine the range (a peculiar case, that
3122 -- perhaps cannot happen, but there is no point in bombing in this
3123 -- optimization circuit.
3125 -- First the low bound
3127 Bound := Type_Low_Bound (Typ);
3129 if Compile_Time_Known_Value (Bound) then
3130 Lo := Expr_Value (Bound);
3132 elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
3133 Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
3140 -- Now the high bound
3142 Bound := Type_High_Bound (Typ);
3144 -- We need the high bound of the base type later on, and this should
3145 -- always be compile time known. Again, it is not clear that this
3146 -- can ever be false, but no point in bombing.
3148 if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
3149 Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
3157 -- If we have a static subtype, then that may have a tighter bound so
3158 -- use the upper bound of the subtype instead in this case.
3160 if Compile_Time_Known_Value (Bound) then
3161 Hi := Expr_Value (Bound);
3164 -- We may be able to refine this value in certain situations. If any
3165 -- refinement is possible, then Lor and Hir are set to possibly tighter
3166 -- bounds, and OK1 is set to True.
3170 -- For unary plus, result is limited by range of operand
3173 Determine_Range (Right_Opnd (N), OK1, Lor, Hir);
3175 -- For unary minus, determine range of operand, and negate it
3178 Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
3185 -- For binary addition, get range of each operand and do the
3186 -- addition to get the result range.
3190 Lor := Lo_Left + Lo_Right;
3191 Hir := Hi_Left + Hi_Right;
3194 -- Division is tricky. The only case we consider is where the right
3195 -- operand is a positive constant, and in this case we simply divide
3196 -- the bounds of the left operand
3200 if Lo_Right = Hi_Right
3201 and then Lo_Right > 0
3203 Lor := Lo_Left / Lo_Right;
3204 Hir := Hi_Left / Lo_Right;
3211 -- For binary subtraction, get range of each operand and do the worst
3212 -- case subtraction to get the result range.
3214 when N_Op_Subtract =>
3216 Lor := Lo_Left - Hi_Right;
3217 Hir := Hi_Left - Lo_Right;
3220 -- For MOD, if right operand is a positive constant, then result must
3221 -- be in the allowable range of mod results.
3225 if Lo_Right = Hi_Right
3226 and then Lo_Right /= 0
3228 if Lo_Right > 0 then
3230 Hir := Lo_Right - 1;
3232 else -- Lo_Right < 0
3233 Lor := Lo_Right + 1;
3242 -- For REM, if right operand is a positive constant, then result must
3243 -- be in the allowable range of mod results.
3247 if Lo_Right = Hi_Right
3248 and then Lo_Right /= 0
3251 Dval : constant Uint := (abs Lo_Right) - 1;
3254 -- The sign of the result depends on the sign of the
3255 -- dividend (but not on the sign of the divisor, hence
3256 -- the abs operation above).
3276 -- Attribute reference cases
3278 when N_Attribute_Reference =>
3279 case Attribute_Name (N) is
3281 -- For Pos/Val attributes, we can refine the range using the
3282 -- possible range of values of the attribute expression
3284 when Name_Pos | Name_Val =>
3285 Determine_Range (First (Expressions (N)), OK1, Lor, Hir);
3287 -- For Length attribute, use the bounds of the corresponding
3288 -- index type to refine the range.
3292 Atyp : Entity_Id := Etype (Prefix (N));
3300 if Is_Access_Type (Atyp) then
3301 Atyp := Designated_Type (Atyp);
3304 -- For string literal, we know exact value
3306 if Ekind (Atyp) = E_String_Literal_Subtype then
3308 Lo := String_Literal_Length (Atyp);
3309 Hi := String_Literal_Length (Atyp);
3313 -- Otherwise check for expression given
3315 if No (Expressions (N)) then
3319 UI_To_Int (Expr_Value (First (Expressions (N))));
3322 Indx := First_Index (Atyp);
3323 for J in 2 .. Inum loop
3324 Indx := Next_Index (Indx);
3328 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU);
3332 (Type_High_Bound (Etype (Indx)), OK1, UL, UU);
3336 -- The maximum value for Length is the biggest
3337 -- possible gap between the values of the bounds.
3338 -- But of course, this value cannot be negative.
3340 Hir := UI_Max (Uint_0, UU - LL);
3342 -- For constrained arrays, the minimum value for
3343 -- Length is taken from the actual value of the
3344 -- bounds, since the index will be exactly of
3347 if Is_Constrained (Atyp) then
3348 Lor := UI_Max (Uint_0, UL - LU);
3350 -- For an unconstrained array, the minimum value
3351 -- for length is always zero.
3360 -- No special handling for other attributes
3361 -- Probably more opportunities exist here ???
3368 -- For type conversion from one discrete type to another, we can
3369 -- refine the range using the converted value.
3371 when N_Type_Conversion =>
3372 Determine_Range (Expression (N), OK1, Lor, Hir);
3374 -- Nothing special to do for all other expression kinds
3382 -- At this stage, if OK1 is true, then we know that the actual
3383 -- result of the computed expression is in the range Lor .. Hir.
3384 -- We can use this to restrict the possible range of results.
3388 -- If the refined value of the low bound is greater than the
3389 -- type high bound, then reset it to the more restrictive
3390 -- value. However, we do NOT do this for the case of a modular
3391 -- type where the possible upper bound on the value is above the
3392 -- base type high bound, because that means the result could wrap.
3395 and then not (Is_Modular_Integer_Type (Typ)
3396 and then Hir > Hbound)
3401 -- Similarly, if the refined value of the high bound is less
3402 -- than the value so far, then reset it to the more restrictive
3403 -- value. Again, we do not do this if the refined low bound is
3404 -- negative for a modular type, since this would wrap.
3407 and then not (Is_Modular_Integer_Type (Typ)
3408 and then Lor < Uint_0)
3414 -- Set cache entry for future call and we are all done
3416 Determine_Range_Cache_N (Cindex) := N;
3417 Determine_Range_Cache_Lo (Cindex) := Lo;
3418 Determine_Range_Cache_Hi (Cindex) := Hi;
3421 -- If any exception occurs, it means that we have some bug in the compiler
3422 -- possibly triggered by a previous error, or by some unforseen peculiar
3423 -- occurrence. However, this is only an optimization attempt, so there is
3424 -- really no point in crashing the compiler. Instead we just decide, too
3425 -- bad, we can't figure out a range in this case after all.
3430 -- Debug flag K disables this behavior (useful for debugging)
3432 if Debug_Flag_K then
3440 end Determine_Range;
3442 ------------------------------------
3443 -- Discriminant_Checks_Suppressed --
3444 ------------------------------------
3446 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3449 if Is_Unchecked_Union (E) then
3451 elsif Checks_May_Be_Suppressed (E) then
3452 return Is_Check_Suppressed (E, Discriminant_Check);
3456 return Scope_Suppress (Discriminant_Check);
3457 end Discriminant_Checks_Suppressed;
3459 --------------------------------
3460 -- Division_Checks_Suppressed --
3461 --------------------------------
3463 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3465 if Present (E) and then Checks_May_Be_Suppressed (E) then
3466 return Is_Check_Suppressed (E, Division_Check);
3468 return Scope_Suppress (Division_Check);
3470 end Division_Checks_Suppressed;
3472 -----------------------------------
3473 -- Elaboration_Checks_Suppressed --
3474 -----------------------------------
3476 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3478 -- The complication in this routine is that if we are in the dynamic
3479 -- model of elaboration, we also check All_Checks, since All_Checks
3480 -- does not set Elaboration_Check explicitly.
3483 if Kill_Elaboration_Checks (E) then
3486 elsif Checks_May_Be_Suppressed (E) then
3487 if Is_Check_Suppressed (E, Elaboration_Check) then
3489 elsif Dynamic_Elaboration_Checks then
3490 return Is_Check_Suppressed (E, All_Checks);
3497 if Scope_Suppress (Elaboration_Check) then
3499 elsif Dynamic_Elaboration_Checks then
3500 return Scope_Suppress (All_Checks);
3504 end Elaboration_Checks_Suppressed;
3506 ---------------------------
3507 -- Enable_Overflow_Check --
3508 ---------------------------
3510 procedure Enable_Overflow_Check (N : Node_Id) is
3511 Typ : constant Entity_Id := Base_Type (Etype (N));
3520 if Debug_Flag_CC then
3521 w ("Enable_Overflow_Check for node ", Int (N));
3522 Write_Str (" Source location = ");
3527 -- Nothing to do if the range of the result is known OK. We skip this
3528 -- for conversions, since the caller already did the check, and in any
3529 -- case the condition for deleting the check for a type conversion is
3532 if Nkind (N) /= N_Type_Conversion then
3533 Determine_Range (N, OK, Lo, Hi);
3535 -- Note in the test below that we assume that the range is not OK
3536 -- if a bound of the range is equal to that of the type. That's not
3537 -- quite accurate but we do this for the following reasons:
3539 -- a) The way that Determine_Range works, it will typically report
3540 -- the bounds of the value as being equal to the bounds of the
3541 -- type, because it either can't tell anything more precise, or
3542 -- does not think it is worth the effort to be more precise.
3544 -- b) It is very unusual to have a situation in which this would
3545 -- generate an unnecessary overflow check (an example would be
3546 -- a subtype with a range 0 .. Integer'Last - 1 to which the
3547 -- literal value one is added).
3549 -- c) The alternative is a lot of special casing in this routine
3550 -- which would partially duplicate Determine_Range processing.
3553 and then Lo > Expr_Value (Type_Low_Bound (Typ))
3554 and then Hi < Expr_Value (Type_High_Bound (Typ))
3556 if Debug_Flag_CC then
3557 w ("No overflow check required");
3564 -- If not in optimizing mode, set flag and we are done. We are also done
3565 -- (and just set the flag) if the type is not a discrete type, since it
3566 -- is not worth the effort to eliminate checks for other than discrete
3567 -- types. In addition, we take this same path if we have stored the
3568 -- maximum number of checks possible already (a very unlikely situation,
3569 -- but we do not want to blow up!)
3571 if Optimization_Level = 0
3572 or else not Is_Discrete_Type (Etype (N))
3573 or else Num_Saved_Checks = Saved_Checks'Last
3575 Activate_Overflow_Check (N);
3577 if Debug_Flag_CC then
3578 w ("Optimization off");
3584 -- Otherwise evaluate and check the expression
3589 Target_Type => Empty,
3595 if Debug_Flag_CC then
3596 w ("Called Find_Check");
3600 w (" Check_Num = ", Chk);
3601 w (" Ent = ", Int (Ent));
3602 Write_Str (" Ofs = ");
3607 -- If check is not of form to optimize, then set flag and we are done
3610 Activate_Overflow_Check (N);
3614 -- If check is already performed, then return without setting flag
3617 if Debug_Flag_CC then
3618 w ("Check suppressed!");
3624 -- Here we will make a new entry for the new check
3626 Activate_Overflow_Check (N);
3627 Num_Saved_Checks := Num_Saved_Checks + 1;
3628 Saved_Checks (Num_Saved_Checks) :=
3633 Target_Type => Empty);
3635 if Debug_Flag_CC then
3636 w ("Make new entry, check number = ", Num_Saved_Checks);
3637 w (" Entity = ", Int (Ent));
3638 Write_Str (" Offset = ");
3640 w (" Check_Type = O");
3641 w (" Target_Type = Empty");
3644 -- If we get an exception, then something went wrong, probably because of
3645 -- an error in the structure of the tree due to an incorrect program. Or it
3646 -- may be a bug in the optimization circuit. In either case the safest
3647 -- thing is simply to set the check flag unconditionally.
3651 Activate_Overflow_Check (N);
3653 if Debug_Flag_CC then
3654 w (" exception occurred, overflow flag set");
3658 end Enable_Overflow_Check;
3660 ------------------------
3661 -- Enable_Range_Check --
3662 ------------------------
3664 procedure Enable_Range_Check (N : Node_Id) is
3673 -- Return if unchecked type conversion with range check killed. In this
3674 -- case we never set the flag (that's what Kill_Range_Check is about!)
3676 if Nkind (N) = N_Unchecked_Type_Conversion
3677 and then Kill_Range_Check (N)
3682 -- Check for various cases where we should suppress the range check
3684 -- No check if range checks suppressed for type of node
3686 if Present (Etype (N))
3687 and then Range_Checks_Suppressed (Etype (N))
3691 -- No check if node is an entity name, and range checks are suppressed
3692 -- for this entity, or for the type of this entity.
3694 elsif Is_Entity_Name (N)
3695 and then (Range_Checks_Suppressed (Entity (N))
3696 or else Range_Checks_Suppressed (Etype (Entity (N))))
3700 -- No checks if index of array, and index checks are suppressed for
3701 -- the array object or the type of the array.
3703 elsif Nkind (Parent (N)) = N_Indexed_Component then
3705 Pref : constant Node_Id := Prefix (Parent (N));
3707 if Is_Entity_Name (Pref)
3708 and then Index_Checks_Suppressed (Entity (Pref))
3711 elsif Index_Checks_Suppressed (Etype (Pref)) then
3717 -- Debug trace output
3719 if Debug_Flag_CC then
3720 w ("Enable_Range_Check for node ", Int (N));
3721 Write_Str (" Source location = ");
3726 -- If not in optimizing mode, set flag and we are done. We are also done
3727 -- (and just set the flag) if the type is not a discrete type, since it
3728 -- is not worth the effort to eliminate checks for other than discrete
3729 -- types. In addition, we take this same path if we have stored the
3730 -- maximum number of checks possible already (a very unlikely situation,
3731 -- but we do not want to blow up!)
3733 if Optimization_Level = 0
3734 or else No (Etype (N))
3735 or else not Is_Discrete_Type (Etype (N))
3736 or else Num_Saved_Checks = Saved_Checks'Last
3738 Activate_Range_Check (N);
3740 if Debug_Flag_CC then
3741 w ("Optimization off");
3747 -- Otherwise find out the target type
3751 -- For assignment, use left side subtype
3753 if Nkind (P) = N_Assignment_Statement
3754 and then Expression (P) = N
3756 Ttyp := Etype (Name (P));
3758 -- For indexed component, use subscript subtype
3760 elsif Nkind (P) = N_Indexed_Component then
3767 Atyp := Etype (Prefix (P));
3769 if Is_Access_Type (Atyp) then
3770 Atyp := Designated_Type (Atyp);
3772 -- If the prefix is an access to an unconstrained array,
3773 -- perform check unconditionally: it depends on the bounds of
3774 -- an object and we cannot currently recognize whether the test
3775 -- may be redundant.
3777 if not Is_Constrained (Atyp) then
3778 Activate_Range_Check (N);
3782 -- Ditto if the prefix is an explicit dereference whose designated
3783 -- type is unconstrained.
3785 elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3786 and then not Is_Constrained (Atyp)
3788 Activate_Range_Check (N);
3792 Indx := First_Index (Atyp);
3793 Subs := First (Expressions (P));
3796 Ttyp := Etype (Indx);
3805 -- For now, ignore all other cases, they are not so interesting
3808 if Debug_Flag_CC then
3809 w (" target type not found, flag set");
3812 Activate_Range_Check (N);
3816 -- Evaluate and check the expression
3821 Target_Type => Ttyp,
3827 if Debug_Flag_CC then
3828 w ("Called Find_Check");
3829 w ("Target_Typ = ", Int (Ttyp));
3833 w (" Check_Num = ", Chk);
3834 w (" Ent = ", Int (Ent));
3835 Write_Str (" Ofs = ");
3840 -- If check is not of form to optimize, then set flag and we are done
3843 if Debug_Flag_CC then
3844 w (" expression not of optimizable type, flag set");
3847 Activate_Range_Check (N);
3851 -- If check is already performed, then return without setting flag
3854 if Debug_Flag_CC then
3855 w ("Check suppressed!");
3861 -- Here we will make a new entry for the new check
3863 Activate_Range_Check (N);
3864 Num_Saved_Checks := Num_Saved_Checks + 1;
3865 Saved_Checks (Num_Saved_Checks) :=
3870 Target_Type => Ttyp);
3872 if Debug_Flag_CC then
3873 w ("Make new entry, check number = ", Num_Saved_Checks);
3874 w (" Entity = ", Int (Ent));
3875 Write_Str (" Offset = ");
3877 w (" Check_Type = R");
3878 w (" Target_Type = ", Int (Ttyp));
3879 pg (Union_Id (Ttyp));
3882 -- If we get an exception, then something went wrong, probably because of
3883 -- an error in the structure of the tree due to an incorrect program. Or
3884 -- it may be a bug in the optimization circuit. In either case the safest
3885 -- thing is simply to set the check flag unconditionally.
3889 Activate_Range_Check (N);
3891 if Debug_Flag_CC then
3892 w (" exception occurred, range flag set");
3896 end Enable_Range_Check;
3902 procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
3903 Typ : constant Entity_Id := Etype (Expr);
3906 -- Ignore call if we are not doing any validity checking
3908 if not Validity_Checks_On then
3911 -- Ignore call if range or validity checks suppressed on entity or type
3913 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
3916 -- No check required if expression is from the expander, we assume the
3917 -- expander will generate whatever checks are needed. Note that this is
3918 -- not just an optimization, it avoids infinite recursions!
3920 -- Unchecked conversions must be checked, unless they are initialized
3921 -- scalar values, as in a component assignment in an init proc.
3923 -- In addition, we force a check if Force_Validity_Checks is set
3925 elsif not Comes_From_Source (Expr)
3926 and then not Force_Validity_Checks
3927 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
3928 or else Kill_Range_Check (Expr))
3932 -- No check required if expression is known to have valid value
3934 elsif Expr_Known_Valid (Expr) then
3937 -- Ignore case of enumeration with holes where the flag is set not to
3938 -- worry about holes, since no special validity check is needed
3940 elsif Is_Enumeration_Type (Typ)
3941 and then Has_Non_Standard_Rep (Typ)
3946 -- No check required on the left-hand side of an assignment
3948 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
3949 and then Expr = Name (Parent (Expr))
3953 -- No check on a univeral real constant. The context will eventually
3954 -- convert it to a machine number for some target type, or report an
3957 elsif Nkind (Expr) = N_Real_Literal
3958 and then Etype (Expr) = Universal_Real
3962 -- If the expression denotes a component of a packed boolean arrray,
3963 -- no possible check applies. We ignore the old ACATS chestnuts that
3964 -- involve Boolean range True..True.
3966 -- Note: validity checks are generated for expressions that yield a
3967 -- scalar type, when it is possible to create a value that is outside of
3968 -- the type. If this is a one-bit boolean no such value exists. This is
3969 -- an optimization, and it also prevents compiler blowing up during the
3970 -- elaboration of improperly expanded packed array references.
3972 elsif Nkind (Expr) = N_Indexed_Component
3973 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
3974 and then Root_Type (Etype (Expr)) = Standard_Boolean
3978 -- An annoying special case. If this is an out parameter of a scalar
3979 -- type, then the value is not going to be accessed, therefore it is
3980 -- inappropriate to do any validity check at the call site.
3983 -- Only need to worry about scalar types
3985 if Is_Scalar_Type (Typ) then
3995 -- Find actual argument (which may be a parameter association)
3996 -- and the parent of the actual argument (the call statement)
4001 if Nkind (P) = N_Parameter_Association then
4006 -- Only need to worry if we are argument of a procedure call
4007 -- since functions don't have out parameters. If this is an
4008 -- indirect or dispatching call, get signature from the
4011 if Nkind (P) = N_Procedure_Call_Statement then
4012 L := Parameter_Associations (P);
4014 if Is_Entity_Name (Name (P)) then
4015 E := Entity (Name (P));
4017 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
4018 E := Etype (Name (P));
4021 -- Only need to worry if there are indeed actuals, and if
4022 -- this could be a procedure call, otherwise we cannot get a
4023 -- match (either we are not an argument, or the mode of the
4024 -- formal is not OUT). This test also filters out the
4027 if Is_Non_Empty_List (L)
4028 and then Is_Subprogram (E)
4030 -- This is the loop through parameters, looking for an
4031 -- OUT parameter for which we are the argument.
4033 F := First_Formal (E);
4035 while Present (F) loop
4036 if Ekind (F) = E_Out_Parameter and then A = N then
4049 -- If we fall through, a validity check is required
4051 Insert_Valid_Check (Expr);
4053 if Is_Entity_Name (Expr)
4054 and then Safe_To_Capture_Value (Expr, Entity (Expr))
4056 Set_Is_Known_Valid (Entity (Expr));
4060 ----------------------
4061 -- Expr_Known_Valid --
4062 ----------------------
4064 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
4065 Typ : constant Entity_Id := Etype (Expr);
4068 -- Non-scalar types are always considered valid, since they never give
4069 -- rise to the issues of erroneous or bounded error behavior that are
4070 -- the concern. In formal reference manual terms the notion of validity
4071 -- only applies to scalar types. Note that even when packed arrays are
4072 -- represented using modular types, they are still arrays semantically,
4073 -- so they are also always valid (in particular, the unused bits can be
4074 -- random rubbish without affecting the validity of the array value).
4076 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
4079 -- If no validity checking, then everything is considered valid
4081 elsif not Validity_Checks_On then
4084 -- Floating-point types are considered valid unless floating-point
4085 -- validity checks have been specifically turned on.
4087 elsif Is_Floating_Point_Type (Typ)
4088 and then not Validity_Check_Floating_Point
4092 -- If the expression is the value of an object that is known to be
4093 -- valid, then clearly the expression value itself is valid.
4095 elsif Is_Entity_Name (Expr)
4096 and then Is_Known_Valid (Entity (Expr))
4100 -- References to discriminants are always considered valid. The value
4101 -- of a discriminant gets checked when the object is built. Within the
4102 -- record, we consider it valid, and it is important to do so, since
4103 -- otherwise we can try to generate bogus validity checks which
4104 -- reference discriminants out of scope. Discriminants of concurrent
4105 -- types are excluded for the same reason.
4107 elsif Is_Entity_Name (Expr)
4108 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
4112 -- If the type is one for which all values are known valid, then we are
4113 -- sure that the value is valid except in the slightly odd case where
4114 -- the expression is a reference to a variable whose size has been
4115 -- explicitly set to a value greater than the object size.
4117 elsif Is_Known_Valid (Typ) then
4118 if Is_Entity_Name (Expr)
4119 and then Ekind (Entity (Expr)) = E_Variable
4120 and then Esize (Entity (Expr)) > Esize (Typ)
4127 -- Integer and character literals always have valid values, where
4128 -- appropriate these will be range checked in any case.
4130 elsif Nkind (Expr) = N_Integer_Literal
4132 Nkind (Expr) = N_Character_Literal
4136 -- If we have a type conversion or a qualification of a known valid
4137 -- value, then the result will always be valid.
4139 elsif Nkind (Expr) = N_Type_Conversion
4141 Nkind (Expr) = N_Qualified_Expression
4143 return Expr_Known_Valid (Expression (Expr));
4145 -- The result of any operator is always considered valid, since we
4146 -- assume the necessary checks are done by the operator. For operators
4147 -- on floating-point operations, we must also check when the operation
4148 -- is the right-hand side of an assignment, or is an actual in a call.
4150 elsif Nkind (Expr) in N_Op then
4151 if Is_Floating_Point_Type (Typ)
4152 and then Validity_Check_Floating_Point
4154 (Nkind (Parent (Expr)) = N_Assignment_Statement
4155 or else Nkind (Parent (Expr)) = N_Function_Call
4156 or else Nkind (Parent (Expr)) = N_Parameter_Association)
4163 -- The result of a membership test is always valid, since it is true or
4164 -- false, there are no other possibilities.
4166 elsif Nkind (Expr) in N_Membership_Test then
4169 -- For all other cases, we do not know the expression is valid
4174 end Expr_Known_Valid;
4180 procedure Find_Check
4182 Check_Type : Character;
4183 Target_Type : Entity_Id;
4184 Entry_OK : out Boolean;
4185 Check_Num : out Nat;
4186 Ent : out Entity_Id;
4189 function Within_Range_Of
4190 (Target_Type : Entity_Id;
4191 Check_Type : Entity_Id) return Boolean;
4192 -- Given a requirement for checking a range against Target_Type, and
4193 -- and a range Check_Type against which a check has already been made,
4194 -- determines if the check against check type is sufficient to ensure
4195 -- that no check against Target_Type is required.
4197 ---------------------
4198 -- Within_Range_Of --
4199 ---------------------
4201 function Within_Range_Of
4202 (Target_Type : Entity_Id;
4203 Check_Type : Entity_Id) return Boolean
4206 if Target_Type = Check_Type then
4211 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
4212 Thi : constant Node_Id := Type_High_Bound (Target_Type);
4213 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
4214 Chi : constant Node_Id := Type_High_Bound (Check_Type);
4218 or else (Compile_Time_Known_Value (Tlo)
4220 Compile_Time_Known_Value (Clo)
4222 Expr_Value (Clo) >= Expr_Value (Tlo)))
4225 or else (Compile_Time_Known_Value (Thi)
4227 Compile_Time_Known_Value (Chi)
4229 Expr_Value (Chi) <= Expr_Value (Clo)))
4237 end Within_Range_Of;
4239 -- Start of processing for Find_Check
4242 -- Establish default, to avoid warnings from GCC
4246 -- Case of expression is simple entity reference
4248 if Is_Entity_Name (Expr) then
4249 Ent := Entity (Expr);
4252 -- Case of expression is entity + known constant
4254 elsif Nkind (Expr) = N_Op_Add
4255 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4256 and then Is_Entity_Name (Left_Opnd (Expr))
4258 Ent := Entity (Left_Opnd (Expr));
4259 Ofs := Expr_Value (Right_Opnd (Expr));
4261 -- Case of expression is entity - known constant
4263 elsif Nkind (Expr) = N_Op_Subtract
4264 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4265 and then Is_Entity_Name (Left_Opnd (Expr))
4267 Ent := Entity (Left_Opnd (Expr));
4268 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4270 -- Any other expression is not of the right form
4279 -- Come here with expression of appropriate form, check if entity is an
4280 -- appropriate one for our purposes.
4282 if (Ekind (Ent) = E_Variable
4283 or else Is_Constant_Object (Ent))
4284 and then not Is_Library_Level_Entity (Ent)
4292 -- See if there is matching check already
4294 for J in reverse 1 .. Num_Saved_Checks loop
4296 SC : Saved_Check renames Saved_Checks (J);
4299 if SC.Killed = False
4300 and then SC.Entity = Ent
4301 and then SC.Offset = Ofs
4302 and then SC.Check_Type = Check_Type
4303 and then Within_Range_Of (Target_Type, SC.Target_Type)
4311 -- If we fall through entry was not found
4317 ---------------------------------
4318 -- Generate_Discriminant_Check --
4319 ---------------------------------
4321 -- Note: the code for this procedure is derived from the
4322 -- Emit_Discriminant_Check Routine in trans.c.
4324 procedure Generate_Discriminant_Check (N : Node_Id) is
4325 Loc : constant Source_Ptr := Sloc (N);
4326 Pref : constant Node_Id := Prefix (N);
4327 Sel : constant Node_Id := Selector_Name (N);
4329 Orig_Comp : constant Entity_Id :=
4330 Original_Record_Component (Entity (Sel));
4331 -- The original component to be checked
4333 Discr_Fct : constant Entity_Id :=
4334 Discriminant_Checking_Func (Orig_Comp);
4335 -- The discriminant checking function
4338 -- One discriminant to be checked in the type
4340 Real_Discr : Entity_Id;
4341 -- Actual discriminant in the call
4343 Pref_Type : Entity_Id;
4344 -- Type of relevant prefix (ignoring private/access stuff)
4347 -- List of arguments for function call
4350 -- Keep track of the formal corresponding to the actual we build for
4351 -- each discriminant, in order to be able to perform the necessary type
4355 -- Selected component reference for checking function argument
4358 Pref_Type := Etype (Pref);
4360 -- Force evaluation of the prefix, so that it does not get evaluated
4361 -- twice (once for the check, once for the actual reference). Such a
4362 -- double evaluation is always a potential source of inefficiency,
4363 -- and is functionally incorrect in the volatile case, or when the
4364 -- prefix may have side-effects. An entity or a component of an
4365 -- entity requires no evaluation.
4367 if Is_Entity_Name (Pref) then
4368 if Treat_As_Volatile (Entity (Pref)) then
4369 Force_Evaluation (Pref, Name_Req => True);
4372 elsif Treat_As_Volatile (Etype (Pref)) then
4373 Force_Evaluation (Pref, Name_Req => True);
4375 elsif Nkind (Pref) = N_Selected_Component
4376 and then Is_Entity_Name (Prefix (Pref))
4381 Force_Evaluation (Pref, Name_Req => True);
4384 -- For a tagged type, use the scope of the original component to
4385 -- obtain the type, because ???
4387 if Is_Tagged_Type (Scope (Orig_Comp)) then
4388 Pref_Type := Scope (Orig_Comp);
4390 -- For an untagged derived type, use the discriminants of the parent
4391 -- which have been renamed in the derivation, possibly by a one-to-many
4392 -- discriminant constraint. For non-tagged type, initially get the Etype
4396 if Is_Derived_Type (Pref_Type)
4397 and then Number_Discriminants (Pref_Type) /=
4398 Number_Discriminants (Etype (Base_Type (Pref_Type)))
4400 Pref_Type := Etype (Base_Type (Pref_Type));
4404 -- We definitely should have a checking function, This routine should
4405 -- not be called if no discriminant checking function is present.
4407 pragma Assert (Present (Discr_Fct));
4409 -- Create the list of the actual parameters for the call. This list
4410 -- is the list of the discriminant fields of the record expression to
4411 -- be discriminant checked.
4414 Formal := First_Formal (Discr_Fct);
4415 Discr := First_Discriminant (Pref_Type);
4416 while Present (Discr) loop
4418 -- If we have a corresponding discriminant field, and a parent
4419 -- subtype is present, then we want to use the corresponding
4420 -- discriminant since this is the one with the useful value.
4422 if Present (Corresponding_Discriminant (Discr))
4423 and then Ekind (Pref_Type) = E_Record_Type
4424 and then Present (Parent_Subtype (Pref_Type))
4426 Real_Discr := Corresponding_Discriminant (Discr);
4428 Real_Discr := Discr;
4431 -- Construct the reference to the discriminant
4434 Make_Selected_Component (Loc,
4436 Unchecked_Convert_To (Pref_Type,
4437 Duplicate_Subexpr (Pref)),
4438 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4440 -- Manually analyze and resolve this selected component. We really
4441 -- want it just as it appears above, and do not want the expander
4442 -- playing discriminal games etc with this reference. Then we append
4443 -- the argument to the list we are gathering.
4445 Set_Etype (Scomp, Etype (Real_Discr));
4446 Set_Analyzed (Scomp, True);
4447 Append_To (Args, Convert_To (Etype (Formal), Scomp));
4449 Next_Formal_With_Extras (Formal);
4450 Next_Discriminant (Discr);
4453 -- Now build and insert the call
4456 Make_Raise_Constraint_Error (Loc,
4458 Make_Function_Call (Loc,
4459 Name => New_Occurrence_Of (Discr_Fct, Loc),
4460 Parameter_Associations => Args),
4461 Reason => CE_Discriminant_Check_Failed));
4462 end Generate_Discriminant_Check;
4464 ---------------------------
4465 -- Generate_Index_Checks --
4466 ---------------------------
4468 procedure Generate_Index_Checks (N : Node_Id) is
4469 Loc : constant Source_Ptr := Sloc (N);
4470 A : constant Node_Id := Prefix (N);
4476 -- Ignore call if index checks suppressed for array object or type
4478 if (Is_Entity_Name (A) and then Index_Checks_Suppressed (Entity (A)))
4479 or else Index_Checks_Suppressed (Etype (A))
4484 -- Generate the checks
4486 Sub := First (Expressions (N));
4488 while Present (Sub) loop
4489 if Do_Range_Check (Sub) then
4490 Set_Do_Range_Check (Sub, False);
4492 -- Force evaluation except for the case of a simple name of a
4493 -- non-volatile entity.
4495 if not Is_Entity_Name (Sub)
4496 or else Treat_As_Volatile (Entity (Sub))
4498 Force_Evaluation (Sub);
4501 -- Generate a raise of constraint error with the appropriate
4502 -- reason and a condition of the form:
4504 -- Base_Type(Sub) not in array'range (subscript)
4506 -- Note that the reason we generate the conversion to the base
4507 -- type here is that we definitely want the range check to take
4508 -- place, even if it looks like the subtype is OK. Optimization
4509 -- considerations that allow us to omit the check have already
4510 -- been taken into account in the setting of the Do_Range_Check
4516 Num := New_List (Make_Integer_Literal (Loc, Ind));
4520 Make_Raise_Constraint_Error (Loc,
4524 Convert_To (Base_Type (Etype (Sub)),
4525 Duplicate_Subexpr_Move_Checks (Sub)),
4527 Make_Attribute_Reference (Loc,
4529 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
4530 Attribute_Name => Name_Range,
4531 Expressions => Num)),
4532 Reason => CE_Index_Check_Failed));
4538 end Generate_Index_Checks;
4540 --------------------------
4541 -- Generate_Range_Check --
4542 --------------------------
4544 procedure Generate_Range_Check
4546 Target_Type : Entity_Id;
4547 Reason : RT_Exception_Code)
4549 Loc : constant Source_Ptr := Sloc (N);
4550 Source_Type : constant Entity_Id := Etype (N);
4551 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
4552 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
4555 -- First special case, if the source type is already within the range
4556 -- of the target type, then no check is needed (probably we should have
4557 -- stopped Do_Range_Check from being set in the first place, but better
4558 -- late than later in preventing junk code!
4560 -- We do NOT apply this if the source node is a literal, since in this
4561 -- case the literal has already been labeled as having the subtype of
4564 if In_Subrange_Of (Source_Type, Target_Type)
4566 (Nkind (N) = N_Integer_Literal
4568 Nkind (N) = N_Real_Literal
4570 Nkind (N) = N_Character_Literal
4573 and then Ekind (Entity (N)) = E_Enumeration_Literal))
4578 -- We need a check, so force evaluation of the node, so that it does
4579 -- not get evaluated twice (once for the check, once for the actual
4580 -- reference). Such a double evaluation is always a potential source
4581 -- of inefficiency, and is functionally incorrect in the volatile case.
4583 if not Is_Entity_Name (N)
4584 or else Treat_As_Volatile (Entity (N))
4586 Force_Evaluation (N);
4589 -- The easiest case is when Source_Base_Type and Target_Base_Type are
4590 -- the same since in this case we can simply do a direct check of the
4591 -- value of N against the bounds of Target_Type.
4593 -- [constraint_error when N not in Target_Type]
4595 -- Note: this is by far the most common case, for example all cases of
4596 -- checks on the RHS of assignments are in this category, but not all
4597 -- cases are like this. Notably conversions can involve two types.
4599 if Source_Base_Type = Target_Base_Type then
4601 Make_Raise_Constraint_Error (Loc,
4604 Left_Opnd => Duplicate_Subexpr (N),
4605 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4608 -- Next test for the case where the target type is within the bounds
4609 -- of the base type of the source type, since in this case we can
4610 -- simply convert these bounds to the base type of T to do the test.
4612 -- [constraint_error when N not in
4613 -- Source_Base_Type (Target_Type'First)
4615 -- Source_Base_Type(Target_Type'Last))]
4617 -- The conversions will always work and need no check
4619 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4621 Make_Raise_Constraint_Error (Loc,
4624 Left_Opnd => Duplicate_Subexpr (N),
4629 Convert_To (Source_Base_Type,
4630 Make_Attribute_Reference (Loc,
4632 New_Occurrence_Of (Target_Type, Loc),
4633 Attribute_Name => Name_First)),
4636 Convert_To (Source_Base_Type,
4637 Make_Attribute_Reference (Loc,
4639 New_Occurrence_Of (Target_Type, Loc),
4640 Attribute_Name => Name_Last)))),
4643 -- Note that at this stage we now that the Target_Base_Type is not in
4644 -- the range of the Source_Base_Type (since even the Target_Type itself
4645 -- is not in this range). It could still be the case that Source_Type is
4646 -- in range of the target base type since we have not checked that case.
4648 -- If that is the case, we can freely convert the source to the target,
4649 -- and then test the target result against the bounds.
4651 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4653 -- We make a temporary to hold the value of the converted value
4654 -- (converted to the base type), and then we will do the test against
4657 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
4658 -- [constraint_error when Tnn not in Target_Type]
4660 -- Then the conversion itself is replaced by an occurrence of Tnn
4663 Tnn : constant Entity_Id :=
4664 Make_Defining_Identifier (Loc,
4665 Chars => New_Internal_Name ('T'));
4668 Insert_Actions (N, New_List (
4669 Make_Object_Declaration (Loc,
4670 Defining_Identifier => Tnn,
4671 Object_Definition =>
4672 New_Occurrence_Of (Target_Base_Type, Loc),
4673 Constant_Present => True,
4675 Make_Type_Conversion (Loc,
4676 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4677 Expression => Duplicate_Subexpr (N))),
4679 Make_Raise_Constraint_Error (Loc,
4682 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4683 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4685 Reason => Reason)));
4687 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4689 -- Set the type of N, because the declaration for Tnn might not
4690 -- be analyzed yet, as is the case if N appears within a record
4691 -- declaration, as a discriminant constraint or expression.
4693 Set_Etype (N, Target_Base_Type);
4696 -- At this stage, we know that we have two scalar types, which are
4697 -- directly convertible, and where neither scalar type has a base
4698 -- range that is in the range of the other scalar type.
4700 -- The only way this can happen is with a signed and unsigned type.
4701 -- So test for these two cases:
4704 -- Case of the source is unsigned and the target is signed
4706 if Is_Unsigned_Type (Source_Base_Type)
4707 and then not Is_Unsigned_Type (Target_Base_Type)
4709 -- If the source is unsigned and the target is signed, then we
4710 -- know that the source is not shorter than the target (otherwise
4711 -- the source base type would be in the target base type range).
4713 -- In other words, the unsigned type is either the same size as
4714 -- the target, or it is larger. It cannot be smaller.
4717 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
4719 -- We only need to check the low bound if the low bound of the
4720 -- target type is non-negative. If the low bound of the target
4721 -- type is negative, then we know that we will fit fine.
4723 -- If the high bound of the target type is negative, then we
4724 -- know we have a constraint error, since we can't possibly
4725 -- have a negative source.
4727 -- With these two checks out of the way, we can do the check
4728 -- using the source type safely
4730 -- This is definitely the most annoying case!
4732 -- [constraint_error
4733 -- when (Target_Type'First >= 0
4735 -- N < Source_Base_Type (Target_Type'First))
4736 -- or else Target_Type'Last < 0
4737 -- or else N > Source_Base_Type (Target_Type'Last)];
4739 -- We turn off all checks since we know that the conversions
4740 -- will work fine, given the guards for negative values.
4743 Make_Raise_Constraint_Error (Loc,
4749 Left_Opnd => Make_Op_Ge (Loc,
4751 Make_Attribute_Reference (Loc,
4753 New_Occurrence_Of (Target_Type, Loc),
4754 Attribute_Name => Name_First),
4755 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4759 Left_Opnd => Duplicate_Subexpr (N),
4761 Convert_To (Source_Base_Type,
4762 Make_Attribute_Reference (Loc,
4764 New_Occurrence_Of (Target_Type, Loc),
4765 Attribute_Name => Name_First)))),
4770 Make_Attribute_Reference (Loc,
4771 Prefix => New_Occurrence_Of (Target_Type, Loc),
4772 Attribute_Name => Name_Last),
4773 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
4777 Left_Opnd => Duplicate_Subexpr (N),
4779 Convert_To (Source_Base_Type,
4780 Make_Attribute_Reference (Loc,
4781 Prefix => New_Occurrence_Of (Target_Type, Loc),
4782 Attribute_Name => Name_Last)))),
4785 Suppress => All_Checks);
4787 -- Only remaining possibility is that the source is signed and
4788 -- the target is unsigned
4791 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
4792 and then Is_Unsigned_Type (Target_Base_Type));
4794 -- If the source is signed and the target is unsigned, then we
4795 -- know that the target is not shorter than the source (otherwise
4796 -- the target base type would be in the source base type range).
4798 -- In other words, the unsigned type is either the same size as
4799 -- the target, or it is larger. It cannot be smaller.
4801 -- Clearly we have an error if the source value is negative since
4802 -- no unsigned type can have negative values. If the source type
4803 -- is non-negative, then the check can be done using the target
4806 -- Tnn : constant Target_Base_Type (N) := Target_Type;
4808 -- [constraint_error
4809 -- when N < 0 or else Tnn not in Target_Type];
4811 -- We turn off all checks for the conversion of N to the target
4812 -- base type, since we generate the explicit check to ensure that
4813 -- the value is non-negative
4816 Tnn : constant Entity_Id :=
4817 Make_Defining_Identifier (Loc,
4818 Chars => New_Internal_Name ('T'));
4821 Insert_Actions (N, New_List (
4822 Make_Object_Declaration (Loc,
4823 Defining_Identifier => Tnn,
4824 Object_Definition =>
4825 New_Occurrence_Of (Target_Base_Type, Loc),
4826 Constant_Present => True,
4828 Make_Type_Conversion (Loc,
4830 New_Occurrence_Of (Target_Base_Type, Loc),
4831 Expression => Duplicate_Subexpr (N))),
4833 Make_Raise_Constraint_Error (Loc,
4838 Left_Opnd => Duplicate_Subexpr (N),
4839 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4843 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4845 New_Occurrence_Of (Target_Type, Loc))),
4848 Suppress => All_Checks);
4850 -- Set the Etype explicitly, because Insert_Actions may have
4851 -- placed the declaration in the freeze list for an enclosing
4852 -- construct, and thus it is not analyzed yet.
4854 Set_Etype (Tnn, Target_Base_Type);
4855 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4859 end Generate_Range_Check;
4865 function Get_Check_Id (N : Name_Id) return Check_Id is
4867 -- For standard check name, we can do a direct computation
4869 if N in First_Check_Name .. Last_Check_Name then
4870 return Check_Id (N - (First_Check_Name - 1));
4872 -- For non-standard names added by pragma Check_Name, search table
4875 for J in All_Checks + 1 .. Check_Names.Last loop
4876 if Check_Names.Table (J) = N then
4882 -- No matching name found
4887 ---------------------
4888 -- Get_Discriminal --
4889 ---------------------
4891 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
4892 Loc : constant Source_Ptr := Sloc (E);
4897 -- The bound can be a bona fide parameter of a protected operation,
4898 -- rather than a prival encoded as an in-parameter.
4900 if No (Discriminal_Link (Entity (Bound))) then
4904 -- Climb the scope stack looking for an enclosing protected type. If
4905 -- we run out of scopes, return the bound itself.
4908 while Present (Sc) loop
4909 if Sc = Standard_Standard then
4912 elsif Ekind (Sc) = E_Protected_Type then
4919 D := First_Discriminant (Sc);
4920 while Present (D) loop
4921 if Chars (D) = Chars (Bound) then
4922 return New_Occurrence_Of (Discriminal (D), Loc);
4925 Next_Discriminant (D);
4929 end Get_Discriminal;
4931 ----------------------
4932 -- Get_Range_Checks --
4933 ----------------------
4935 function Get_Range_Checks
4937 Target_Typ : Entity_Id;
4938 Source_Typ : Entity_Id := Empty;
4939 Warn_Node : Node_Id := Empty) return Check_Result
4942 return Selected_Range_Checks
4943 (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
4944 end Get_Range_Checks;
4950 function Guard_Access
4953 Ck_Node : Node_Id) return Node_Id
4956 if Nkind (Cond) = N_Or_Else then
4957 Set_Paren_Count (Cond, 1);
4960 if Nkind (Ck_Node) = N_Allocator then
4967 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
4968 Right_Opnd => Make_Null (Loc)),
4969 Right_Opnd => Cond);
4973 -----------------------------
4974 -- Index_Checks_Suppressed --
4975 -----------------------------
4977 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
4979 if Present (E) and then Checks_May_Be_Suppressed (E) then
4980 return Is_Check_Suppressed (E, Index_Check);
4982 return Scope_Suppress (Index_Check);
4984 end Index_Checks_Suppressed;
4990 procedure Initialize is
4992 for J in Determine_Range_Cache_N'Range loop
4993 Determine_Range_Cache_N (J) := Empty;
4998 for J in Int range 1 .. All_Checks loop
4999 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
5003 -------------------------
5004 -- Insert_Range_Checks --
5005 -------------------------
5007 procedure Insert_Range_Checks
5008 (Checks : Check_Result;
5010 Suppress_Typ : Entity_Id;
5011 Static_Sloc : Source_Ptr := No_Location;
5012 Flag_Node : Node_Id := Empty;
5013 Do_Before : Boolean := False)
5015 Internal_Flag_Node : Node_Id := Flag_Node;
5016 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
5018 Check_Node : Node_Id;
5019 Checks_On : constant Boolean :=
5020 (not Index_Checks_Suppressed (Suppress_Typ))
5022 (not Range_Checks_Suppressed (Suppress_Typ));
5025 -- For now we just return if Checks_On is false, however this should be
5026 -- enhanced to check for an always True value in the condition and to
5027 -- generate a compilation warning???
5029 if not Expander_Active or else not Checks_On then
5033 if Static_Sloc = No_Location then
5034 Internal_Static_Sloc := Sloc (Node);
5037 if No (Flag_Node) then
5038 Internal_Flag_Node := Node;
5041 for J in 1 .. 2 loop
5042 exit when No (Checks (J));
5044 if Nkind (Checks (J)) = N_Raise_Constraint_Error
5045 and then Present (Condition (Checks (J)))
5047 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
5048 Check_Node := Checks (J);
5049 Mark_Rewrite_Insertion (Check_Node);
5052 Insert_Before_And_Analyze (Node, Check_Node);
5054 Insert_After_And_Analyze (Node, Check_Node);
5057 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
5062 Make_Raise_Constraint_Error (Internal_Static_Sloc,
5063 Reason => CE_Range_Check_Failed);
5064 Mark_Rewrite_Insertion (Check_Node);
5067 Insert_Before_And_Analyze (Node, Check_Node);
5069 Insert_After_And_Analyze (Node, Check_Node);
5073 end Insert_Range_Checks;
5075 ------------------------
5076 -- Insert_Valid_Check --
5077 ------------------------
5079 procedure Insert_Valid_Check (Expr : Node_Id) is
5080 Loc : constant Source_Ptr := Sloc (Expr);
5084 -- Do not insert if checks off, or if not checking validity
5086 if not Validity_Checks_On
5087 or else Range_Or_Validity_Checks_Suppressed (Expr)
5092 -- If we have a checked conversion, then validity check applies to
5093 -- the expression inside the conversion, not the result, since if
5094 -- the expression inside is valid, then so is the conversion result.
5097 while Nkind (Exp) = N_Type_Conversion loop
5098 Exp := Expression (Exp);
5101 -- We are about to insert the validity check for Exp. We save and
5102 -- reset the Do_Range_Check flag over this validity check, and then
5103 -- put it back for the final original reference (Exp may be rewritten).
5106 DRC : constant Boolean := Do_Range_Check (Exp);
5109 Set_Do_Range_Check (Exp, False);
5111 -- Insert the validity check. Note that we do this with validity
5112 -- checks turned off, to avoid recursion, we do not want validity
5113 -- checks on the validity checking code itself!
5117 Make_Raise_Constraint_Error (Loc,
5121 Make_Attribute_Reference (Loc,
5123 Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
5124 Attribute_Name => Name_Valid)),
5125 Reason => CE_Invalid_Data),
5126 Suppress => Validity_Check);
5128 -- If the expression is a a reference to an element of a bit-packed
5129 -- array, then it is rewritten as a renaming declaration. If the
5130 -- expression is an actual in a call, it has not been expanded,
5131 -- waiting for the proper point at which to do it. The same happens
5132 -- with renamings, so that we have to force the expansion now. This
5133 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
5136 if Is_Entity_Name (Exp)
5137 and then Nkind (Parent (Entity (Exp))) =
5138 N_Object_Renaming_Declaration
5141 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
5143 if Nkind (Old_Exp) = N_Indexed_Component
5144 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
5146 Expand_Packed_Element_Reference (Old_Exp);
5151 -- Put back the Do_Range_Check flag on the resulting (possibly
5152 -- rewritten) expression.
5154 -- Note: it might be thought that a validity check is not required
5155 -- when a range check is present, but that's not the case, because
5156 -- the back end is allowed to assume for the range check that the
5157 -- operand is within its declared range (an assumption that validity
5158 -- checking is all about NOT assuming!)
5160 -- Note: no need to worry about Possible_Local_Raise here, it will
5161 -- already have been called if original node has Do_Range_Check set.
5163 Set_Do_Range_Check (Exp, DRC);
5165 end Insert_Valid_Check;
5167 ----------------------------------
5168 -- Install_Null_Excluding_Check --
5169 ----------------------------------
5171 procedure Install_Null_Excluding_Check (N : Node_Id) is
5172 Loc : constant Source_Ptr := Sloc (N);
5173 Typ : constant Entity_Id := Etype (N);
5175 function In_Declarative_Region_Of_Subprogram_Body return Boolean;
5176 -- Determine whether node N, a reference to an *in* parameter, is
5177 -- inside the declarative region of the current subprogram body.
5179 procedure Mark_Non_Null;
5180 -- After installation of check, if the node in question is an entity
5181 -- name, then mark this entity as non-null if possible.
5183 ----------------------------------------------
5184 -- In_Declarative_Region_Of_Subprogram_Body --
5185 ----------------------------------------------
5187 function In_Declarative_Region_Of_Subprogram_Body return Boolean is
5188 E : constant Entity_Id := Entity (N);
5189 S : constant Entity_Id := Current_Scope;
5193 pragma Assert (Ekind (E) = E_In_Parameter);
5195 -- Two initial context checks. We must be inside a subprogram body
5196 -- with declarations and reference must not appear in nested scopes.
5198 if (Ekind (S) /= E_Function
5199 and then Ekind (S) /= E_Procedure)
5200 or else Scope (E) /= S
5205 S_Par := Parent (Parent (S));
5207 if Nkind (S_Par) /= N_Subprogram_Body
5208 or else No (Declarations (S_Par))
5218 -- Retrieve the declaration node of N (if any). Note that N
5219 -- may be a part of a complex initialization expression.
5223 while Present (P) loop
5225 -- While traversing the parent chain, we find that N
5226 -- belongs to a statement, thus it may never appear in
5227 -- a declarative region.
5229 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
5230 or else Nkind (P) = N_Procedure_Call_Statement
5235 if Nkind (P) in N_Declaration
5236 and then Nkind (P) not in N_Subprogram_Specification
5249 return List_Containing (N_Decl) = Declarations (S_Par);
5251 end In_Declarative_Region_Of_Subprogram_Body;
5257 procedure Mark_Non_Null is
5259 -- Only case of interest is if node N is an entity name
5261 if Is_Entity_Name (N) then
5263 -- For sure, we want to clear an indication that this is known to
5264 -- be null, since if we get past this check, it definitely is not!
5266 Set_Is_Known_Null (Entity (N), False);
5268 -- We can mark the entity as known to be non-null if either it is
5269 -- safe to capture the value, or in the case of an IN parameter,
5270 -- which is a constant, if the check we just installed is in the
5271 -- declarative region of the subprogram body. In this latter case,
5272 -- a check is decisive for the rest of the body, since we know we
5273 -- must complete all declarations before executing the body.
5275 if Safe_To_Capture_Value (N, Entity (N))
5277 (Ekind (Entity (N)) = E_In_Parameter
5278 and then In_Declarative_Region_Of_Subprogram_Body)
5280 Set_Is_Known_Non_Null (Entity (N));
5285 -- Start of processing for Install_Null_Excluding_Check
5288 pragma Assert (Is_Access_Type (Typ));
5290 -- No check inside a generic (why not???)
5292 if Inside_A_Generic then
5296 -- No check needed if known to be non-null
5298 if Known_Non_Null (N) then
5302 -- If known to be null, here is where we generate a compile time check
5304 if Known_Null (N) then
5306 -- Avoid generating warning message inside init procs
5308 if not Inside_Init_Proc then
5309 Apply_Compile_Time_Constraint_Error
5311 "null value not allowed here?",
5312 CE_Access_Check_Failed);
5315 Make_Raise_Constraint_Error (Loc,
5316 Reason => CE_Access_Check_Failed));
5323 -- If entity is never assigned, for sure a warning is appropriate
5325 if Is_Entity_Name (N) then
5326 Check_Unset_Reference (N);
5329 -- No check needed if checks are suppressed on the range. Note that we
5330 -- don't set Is_Known_Non_Null in this case (we could legitimately do
5331 -- so, since the program is erroneous, but we don't like to casually
5332 -- propagate such conclusions from erroneosity).
5334 if Access_Checks_Suppressed (Typ) then
5338 -- No check needed for access to concurrent record types generated by
5339 -- the expander. This is not just an optimization (though it does indeed
5340 -- remove junk checks). It also avoids generation of junk warnings.
5342 if Nkind (N) in N_Has_Chars
5343 and then Chars (N) = Name_uObject
5344 and then Is_Concurrent_Record_Type
5345 (Directly_Designated_Type (Etype (N)))
5350 -- Otherwise install access check
5353 Make_Raise_Constraint_Error (Loc,
5356 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
5357 Right_Opnd => Make_Null (Loc)),
5358 Reason => CE_Access_Check_Failed));
5361 end Install_Null_Excluding_Check;
5363 --------------------------
5364 -- Install_Static_Check --
5365 --------------------------
5367 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
5368 Stat : constant Boolean := Is_Static_Expression (R_Cno);
5369 Typ : constant Entity_Id := Etype (R_Cno);
5373 Make_Raise_Constraint_Error (Loc,
5374 Reason => CE_Range_Check_Failed));
5375 Set_Analyzed (R_Cno);
5376 Set_Etype (R_Cno, Typ);
5377 Set_Raises_Constraint_Error (R_Cno);
5378 Set_Is_Static_Expression (R_Cno, Stat);
5379 end Install_Static_Check;
5381 ---------------------
5382 -- Kill_All_Checks --
5383 ---------------------
5385 procedure Kill_All_Checks is
5387 if Debug_Flag_CC then
5388 w ("Kill_All_Checks");
5391 -- We reset the number of saved checks to zero, and also modify all
5392 -- stack entries for statement ranges to indicate that the number of
5393 -- checks at each level is now zero.
5395 Num_Saved_Checks := 0;
5397 -- Note: the Int'Min here avoids any possibility of J being out of
5398 -- range when called from e.g. Conditional_Statements_Begin.
5400 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
5401 Saved_Checks_Stack (J) := 0;
5403 end Kill_All_Checks;
5409 procedure Kill_Checks (V : Entity_Id) is
5411 if Debug_Flag_CC then
5412 w ("Kill_Checks for entity", Int (V));
5415 for J in 1 .. Num_Saved_Checks loop
5416 if Saved_Checks (J).Entity = V then
5417 if Debug_Flag_CC then
5418 w (" Checks killed for saved check ", J);
5421 Saved_Checks (J).Killed := True;
5426 ------------------------------
5427 -- Length_Checks_Suppressed --
5428 ------------------------------
5430 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5432 if Present (E) and then Checks_May_Be_Suppressed (E) then
5433 return Is_Check_Suppressed (E, Length_Check);
5435 return Scope_Suppress (Length_Check);
5437 end Length_Checks_Suppressed;
5439 --------------------------------
5440 -- Overflow_Checks_Suppressed --
5441 --------------------------------
5443 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5445 if Present (E) and then Checks_May_Be_Suppressed (E) then
5446 return Is_Check_Suppressed (E, Overflow_Check);
5448 return Scope_Suppress (Overflow_Check);
5450 end Overflow_Checks_Suppressed;
5451 -----------------------------
5452 -- Range_Checks_Suppressed --
5453 -----------------------------
5455 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5459 -- Note: for now we always suppress range checks on Vax float types,
5460 -- since Gigi does not know how to generate these checks.
5462 if Vax_Float (E) then
5464 elsif Kill_Range_Checks (E) then
5466 elsif Checks_May_Be_Suppressed (E) then
5467 return Is_Check_Suppressed (E, Range_Check);
5471 return Scope_Suppress (Range_Check);
5472 end Range_Checks_Suppressed;
5474 -----------------------------------------
5475 -- Range_Or_Validity_Checks_Suppressed --
5476 -----------------------------------------
5478 -- Note: the coding would be simpler here if we simply made appropriate
5479 -- calls to Range/Validity_Checks_Suppressed, but that would result in
5480 -- duplicated checks which we prefer to avoid.
5482 function Range_Or_Validity_Checks_Suppressed
5483 (Expr : Node_Id) return Boolean
5486 -- Immediate return if scope checks suppressed for either check
5488 if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5492 -- If no expression, that's odd, decide that checks are suppressed,
5493 -- since we don't want anyone trying to do checks in this case, which
5494 -- is most likely the result of some other error.
5500 -- Expression is present, so perform suppress checks on type
5503 Typ : constant Entity_Id := Etype (Expr);
5505 if Vax_Float (Typ) then
5507 elsif Checks_May_Be_Suppressed (Typ)
5508 and then (Is_Check_Suppressed (Typ, Range_Check)
5510 Is_Check_Suppressed (Typ, Validity_Check))
5516 -- If expression is an entity name, perform checks on this entity
5518 if Is_Entity_Name (Expr) then
5520 Ent : constant Entity_Id := Entity (Expr);
5522 if Checks_May_Be_Suppressed (Ent) then
5523 return Is_Check_Suppressed (Ent, Range_Check)
5524 or else Is_Check_Suppressed (Ent, Validity_Check);
5529 -- If we fall through, no checks suppressed
5532 end Range_Or_Validity_Checks_Suppressed;
5538 procedure Remove_Checks (Expr : Node_Id) is
5539 function Process (N : Node_Id) return Traverse_Result;
5540 -- Process a single node during the traversal
5542 procedure Traverse is new Traverse_Proc (Process);
5543 -- The traversal procedure itself
5549 function Process (N : Node_Id) return Traverse_Result is
5551 if Nkind (N) not in N_Subexpr then
5555 Set_Do_Range_Check (N, False);
5559 Traverse (Left_Opnd (N));
5562 when N_Attribute_Reference =>
5563 Set_Do_Overflow_Check (N, False);
5565 when N_Function_Call =>
5566 Set_Do_Tag_Check (N, False);
5569 Set_Do_Overflow_Check (N, False);
5573 Set_Do_Division_Check (N, False);
5576 Set_Do_Length_Check (N, False);
5579 Set_Do_Division_Check (N, False);
5582 Set_Do_Length_Check (N, False);
5585 Set_Do_Division_Check (N, False);
5588 Set_Do_Length_Check (N, False);
5595 Traverse (Left_Opnd (N));
5598 when N_Selected_Component =>
5599 Set_Do_Discriminant_Check (N, False);
5601 when N_Type_Conversion =>
5602 Set_Do_Length_Check (N, False);
5603 Set_Do_Tag_Check (N, False);
5604 Set_Do_Overflow_Check (N, False);
5613 -- Start of processing for Remove_Checks
5619 ----------------------------
5620 -- Selected_Length_Checks --
5621 ----------------------------
5623 function Selected_Length_Checks
5625 Target_Typ : Entity_Id;
5626 Source_Typ : Entity_Id;
5627 Warn_Node : Node_Id) return Check_Result
5629 Loc : constant Source_Ptr := Sloc (Ck_Node);
5632 Expr_Actual : Node_Id;
5634 Cond : Node_Id := Empty;
5635 Do_Access : Boolean := False;
5636 Wnode : Node_Id := Warn_Node;
5637 Ret_Result : Check_Result := (Empty, Empty);
5638 Num_Checks : Natural := 0;
5640 procedure Add_Check (N : Node_Id);
5641 -- Adds the action given to Ret_Result if N is non-Empty
5643 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5644 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5645 -- Comments required ???
5647 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5648 -- True for equal literals and for nodes that denote the same constant
5649 -- entity, even if its value is not a static constant. This includes the
5650 -- case of a discriminal reference within an init proc. Removes some
5651 -- obviously superfluous checks.
5653 function Length_E_Cond
5654 (Exptyp : Entity_Id;
5656 Indx : Nat) return Node_Id;
5657 -- Returns expression to compute:
5658 -- Typ'Length /= Exptyp'Length
5660 function Length_N_Cond
5663 Indx : Nat) return Node_Id;
5664 -- Returns expression to compute:
5665 -- Typ'Length /= Expr'Length
5671 procedure Add_Check (N : Node_Id) is
5675 -- For now, ignore attempt to place more than 2 checks ???
5677 if Num_Checks = 2 then
5681 pragma Assert (Num_Checks <= 1);
5682 Num_Checks := Num_Checks + 1;
5683 Ret_Result (Num_Checks) := N;
5691 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
5692 SE : constant Entity_Id := Scope (E);
5694 E1 : Entity_Id := E;
5697 if Ekind (Scope (E)) = E_Record_Type
5698 and then Has_Discriminants (Scope (E))
5700 N := Build_Discriminal_Subtype_Of_Component (E);
5703 Insert_Action (Ck_Node, N);
5704 E1 := Defining_Identifier (N);
5708 if Ekind (E1) = E_String_Literal_Subtype then
5710 Make_Integer_Literal (Loc,
5711 Intval => String_Literal_Length (E1));
5713 elsif SE /= Standard_Standard
5714 and then Ekind (Scope (SE)) = E_Protected_Type
5715 and then Has_Discriminants (Scope (SE))
5716 and then Has_Completion (Scope (SE))
5717 and then not Inside_Init_Proc
5719 -- If the type whose length is needed is a private component
5720 -- constrained by a discriminant, we must expand the 'Length
5721 -- attribute into an explicit computation, using the discriminal
5722 -- of the current protected operation. This is because the actual
5723 -- type of the prival is constructed after the protected opera-
5724 -- tion has been fully expanded.
5727 Indx_Type : Node_Id;
5730 Do_Expand : Boolean := False;
5733 Indx_Type := First_Index (E);
5735 for J in 1 .. Indx - 1 loop
5736 Next_Index (Indx_Type);
5739 Get_Index_Bounds (Indx_Type, Lo, Hi);
5741 if Nkind (Lo) = N_Identifier
5742 and then Ekind (Entity (Lo)) = E_In_Parameter
5744 Lo := Get_Discriminal (E, Lo);
5748 if Nkind (Hi) = N_Identifier
5749 and then Ekind (Entity (Hi)) = E_In_Parameter
5751 Hi := Get_Discriminal (E, Hi);
5756 if not Is_Entity_Name (Lo) then
5757 Lo := Duplicate_Subexpr_No_Checks (Lo);
5760 if not Is_Entity_Name (Hi) then
5761 Lo := Duplicate_Subexpr_No_Checks (Hi);
5767 Make_Op_Subtract (Loc,
5771 Right_Opnd => Make_Integer_Literal (Loc, 1));
5776 Make_Attribute_Reference (Loc,
5777 Attribute_Name => Name_Length,
5779 New_Occurrence_Of (E1, Loc));
5782 Set_Expressions (N, New_List (
5783 Make_Integer_Literal (Loc, Indx)));
5792 Make_Attribute_Reference (Loc,
5793 Attribute_Name => Name_Length,
5795 New_Occurrence_Of (E1, Loc));
5798 Set_Expressions (N, New_List (
5799 Make_Integer_Literal (Loc, Indx)));
5810 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
5813 Make_Attribute_Reference (Loc,
5814 Attribute_Name => Name_Length,
5816 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
5817 Expressions => New_List (
5818 Make_Integer_Literal (Loc, Indx)));
5825 function Length_E_Cond
5826 (Exptyp : Entity_Id;
5828 Indx : Nat) return Node_Id
5833 Left_Opnd => Get_E_Length (Typ, Indx),
5834 Right_Opnd => Get_E_Length (Exptyp, Indx));
5841 function Length_N_Cond
5844 Indx : Nat) return Node_Id
5849 Left_Opnd => Get_E_Length (Typ, Indx),
5850 Right_Opnd => Get_N_Length (Expr, Indx));
5857 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
5860 (Nkind (L) = N_Integer_Literal
5861 and then Nkind (R) = N_Integer_Literal
5862 and then Intval (L) = Intval (R))
5866 and then Ekind (Entity (L)) = E_Constant
5867 and then ((Is_Entity_Name (R)
5868 and then Entity (L) = Entity (R))
5870 (Nkind (R) = N_Type_Conversion
5871 and then Is_Entity_Name (Expression (R))
5872 and then Entity (L) = Entity (Expression (R)))))
5876 and then Ekind (Entity (R)) = E_Constant
5877 and then Nkind (L) = N_Type_Conversion
5878 and then Is_Entity_Name (Expression (L))
5879 and then Entity (R) = Entity (Expression (L)))
5883 and then Is_Entity_Name (R)
5884 and then Entity (L) = Entity (R)
5885 and then Ekind (Entity (L)) = E_In_Parameter
5886 and then Inside_Init_Proc);
5889 -- Start of processing for Selected_Length_Checks
5892 if not Expander_Active then
5896 if Target_Typ = Any_Type
5897 or else Target_Typ = Any_Composite
5898 or else Raises_Constraint_Error (Ck_Node)
5907 T_Typ := Target_Typ;
5909 if No (Source_Typ) then
5910 S_Typ := Etype (Ck_Node);
5912 S_Typ := Source_Typ;
5915 if S_Typ = Any_Type or else S_Typ = Any_Composite then
5919 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
5920 S_Typ := Designated_Type (S_Typ);
5921 T_Typ := Designated_Type (T_Typ);
5924 -- A simple optimization for the null case
5926 if Known_Null (Ck_Node) then
5931 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
5932 if Is_Constrained (T_Typ) then
5934 -- The checking code to be generated will freeze the
5935 -- corresponding array type. However, we must freeze the
5936 -- type now, so that the freeze node does not appear within
5937 -- the generated condional expression, but ahead of it.
5939 Freeze_Before (Ck_Node, T_Typ);
5941 Expr_Actual := Get_Referenced_Object (Ck_Node);
5942 Exptyp := Get_Actual_Subtype (Ck_Node);
5944 if Is_Access_Type (Exptyp) then
5945 Exptyp := Designated_Type (Exptyp);
5948 -- String_Literal case. This needs to be handled specially be-
5949 -- cause no index types are available for string literals. The
5950 -- condition is simply:
5952 -- T_Typ'Length = string-literal-length
5954 if Nkind (Expr_Actual) = N_String_Literal
5955 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
5959 Left_Opnd => Get_E_Length (T_Typ, 1),
5961 Make_Integer_Literal (Loc,
5963 String_Literal_Length (Etype (Expr_Actual))));
5965 -- General array case. Here we have a usable actual subtype for
5966 -- the expression, and the condition is built from the two types
5969 -- T_Typ'Length /= Exptyp'Length or else
5970 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
5971 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
5974 elsif Is_Constrained (Exptyp) then
5976 Ndims : constant Nat := Number_Dimensions (T_Typ);
5989 -- At the library level, we need to ensure that the type of
5990 -- the object is elaborated before the check itself is
5991 -- emitted. This is only done if the object is in the
5992 -- current compilation unit, otherwise the type is frozen
5993 -- and elaborated in its unit.
5995 if Is_Itype (Exptyp)
5997 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
5999 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
6000 and then In_Open_Scopes (Scope (Exptyp))
6002 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
6003 Set_Itype (Ref_Node, Exptyp);
6004 Insert_Action (Ck_Node, Ref_Node);
6007 L_Index := First_Index (T_Typ);
6008 R_Index := First_Index (Exptyp);
6010 for Indx in 1 .. Ndims loop
6011 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6013 Nkind (R_Index) = N_Raise_Constraint_Error)
6015 Get_Index_Bounds (L_Index, L_Low, L_High);
6016 Get_Index_Bounds (R_Index, R_Low, R_High);
6018 -- Deal with compile time length check. Note that we
6019 -- skip this in the access case, because the access
6020 -- value may be null, so we cannot know statically.
6023 and then Compile_Time_Known_Value (L_Low)
6024 and then Compile_Time_Known_Value (L_High)
6025 and then Compile_Time_Known_Value (R_Low)
6026 and then Compile_Time_Known_Value (R_High)
6028 if Expr_Value (L_High) >= Expr_Value (L_Low) then
6029 L_Length := Expr_Value (L_High) -
6030 Expr_Value (L_Low) + 1;
6032 L_Length := UI_From_Int (0);
6035 if Expr_Value (R_High) >= Expr_Value (R_Low) then
6036 R_Length := Expr_Value (R_High) -
6037 Expr_Value (R_Low) + 1;
6039 R_Length := UI_From_Int (0);
6042 if L_Length > R_Length then
6044 (Compile_Time_Constraint_Error
6045 (Wnode, "too few elements for}?", T_Typ));
6047 elsif L_Length < R_Length then
6049 (Compile_Time_Constraint_Error
6050 (Wnode, "too many elements for}?", T_Typ));
6053 -- The comparison for an individual index subtype
6054 -- is omitted if the corresponding index subtypes
6055 -- statically match, since the result is known to
6056 -- be true. Note that this test is worth while even
6057 -- though we do static evaluation, because non-static
6058 -- subtypes can statically match.
6061 Subtypes_Statically_Match
6062 (Etype (L_Index), Etype (R_Index))
6065 (Same_Bounds (L_Low, R_Low)
6066 and then Same_Bounds (L_High, R_High))
6069 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
6078 -- Handle cases where we do not get a usable actual subtype that
6079 -- is constrained. This happens for example in the function call
6080 -- and explicit dereference cases. In these cases, we have to get
6081 -- the length or range from the expression itself, making sure we
6082 -- do not evaluate it more than once.
6084 -- Here Ck_Node is the original expression, or more properly the
6085 -- result of applying Duplicate_Expr to the original tree, forcing
6086 -- the result to be a name.
6090 Ndims : constant Nat := Number_Dimensions (T_Typ);
6093 -- Build the condition for the explicit dereference case
6095 for Indx in 1 .. Ndims loop
6097 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
6104 -- Construct the test and insert into the tree
6106 if Present (Cond) then
6108 Cond := Guard_Access (Cond, Loc, Ck_Node);
6112 (Make_Raise_Constraint_Error (Loc,
6114 Reason => CE_Length_Check_Failed));
6118 end Selected_Length_Checks;
6120 ---------------------------
6121 -- Selected_Range_Checks --
6122 ---------------------------
6124 function Selected_Range_Checks
6126 Target_Typ : Entity_Id;
6127 Source_Typ : Entity_Id;
6128 Warn_Node : Node_Id) return Check_Result
6130 Loc : constant Source_Ptr := Sloc (Ck_Node);
6133 Expr_Actual : Node_Id;
6135 Cond : Node_Id := Empty;
6136 Do_Access : Boolean := False;
6137 Wnode : Node_Id := Warn_Node;
6138 Ret_Result : Check_Result := (Empty, Empty);
6139 Num_Checks : Integer := 0;
6141 procedure Add_Check (N : Node_Id);
6142 -- Adds the action given to Ret_Result if N is non-Empty
6144 function Discrete_Range_Cond
6146 Typ : Entity_Id) return Node_Id;
6147 -- Returns expression to compute:
6148 -- Low_Bound (Expr) < Typ'First
6150 -- High_Bound (Expr) > Typ'Last
6152 function Discrete_Expr_Cond
6154 Typ : Entity_Id) return Node_Id;
6155 -- Returns expression to compute:
6160 function Get_E_First_Or_Last
6163 Nam : Name_Id) return Node_Id;
6164 -- Returns expression to compute:
6165 -- E'First or E'Last
6167 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
6168 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
6169 -- Returns expression to compute:
6170 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
6172 function Range_E_Cond
6173 (Exptyp : Entity_Id;
6177 -- Returns expression to compute:
6178 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
6180 function Range_Equal_E_Cond
6181 (Exptyp : Entity_Id;
6183 Indx : Nat) return Node_Id;
6184 -- Returns expression to compute:
6185 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
6187 function Range_N_Cond
6190 Indx : Nat) return Node_Id;
6191 -- Return expression to compute:
6192 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
6198 procedure Add_Check (N : Node_Id) is
6202 -- For now, ignore attempt to place more than 2 checks ???
6204 if Num_Checks = 2 then
6208 pragma Assert (Num_Checks <= 1);
6209 Num_Checks := Num_Checks + 1;
6210 Ret_Result (Num_Checks) := N;
6214 -------------------------
6215 -- Discrete_Expr_Cond --
6216 -------------------------
6218 function Discrete_Expr_Cond
6220 Typ : Entity_Id) return Node_Id
6228 Convert_To (Base_Type (Typ),
6229 Duplicate_Subexpr_No_Checks (Expr)),
6231 Convert_To (Base_Type (Typ),
6232 Get_E_First_Or_Last (Typ, 0, Name_First))),
6237 Convert_To (Base_Type (Typ),
6238 Duplicate_Subexpr_No_Checks (Expr)),
6242 Get_E_First_Or_Last (Typ, 0, Name_Last))));
6243 end Discrete_Expr_Cond;
6245 -------------------------
6246 -- Discrete_Range_Cond --
6247 -------------------------
6249 function Discrete_Range_Cond
6251 Typ : Entity_Id) return Node_Id
6253 LB : Node_Id := Low_Bound (Expr);
6254 HB : Node_Id := High_Bound (Expr);
6256 Left_Opnd : Node_Id;
6257 Right_Opnd : Node_Id;
6260 if Nkind (LB) = N_Identifier
6261 and then Ekind (Entity (LB)) = E_Discriminant
6263 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6266 if Nkind (HB) = N_Identifier
6267 and then Ekind (Entity (HB)) = E_Discriminant
6269 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6276 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
6280 (Base_Type (Typ), Get_E_First_Or_Last (Typ, 0, Name_First)));
6282 if Base_Type (Typ) = Typ then
6285 elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
6287 Compile_Time_Known_Value (High_Bound (Scalar_Range
6290 if Is_Floating_Point_Type (Typ) then
6291 if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
6292 Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
6298 if Expr_Value (High_Bound (Scalar_Range (Typ))) =
6299 Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
6310 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
6315 Get_E_First_Or_Last (Typ, 0, Name_Last)));
6317 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
6318 end Discrete_Range_Cond;
6320 -------------------------
6321 -- Get_E_First_Or_Last --
6322 -------------------------
6324 function Get_E_First_Or_Last
6327 Nam : Name_Id) return Node_Id
6335 if Is_Array_Type (E) then
6336 N := First_Index (E);
6338 for J in 2 .. Indx loop
6343 N := Scalar_Range (E);
6346 if Nkind (N) = N_Subtype_Indication then
6347 LB := Low_Bound (Range_Expression (Constraint (N)));
6348 HB := High_Bound (Range_Expression (Constraint (N)));
6350 elsif Is_Entity_Name (N) then
6351 LB := Type_Low_Bound (Etype (N));
6352 HB := Type_High_Bound (Etype (N));
6355 LB := Low_Bound (N);
6356 HB := High_Bound (N);
6359 if Nam = Name_First then
6365 if Nkind (Bound) = N_Identifier
6366 and then Ekind (Entity (Bound)) = E_Discriminant
6368 -- If this is a task discriminant, and we are the body, we must
6369 -- retrieve the corresponding body discriminal. This is another
6370 -- consequence of the early creation of discriminals, and the
6371 -- need to generate constraint checks before their declarations
6372 -- are made visible.
6374 if Is_Concurrent_Record_Type (Scope (Entity (Bound))) then
6376 Tsk : constant Entity_Id :=
6377 Corresponding_Concurrent_Type
6378 (Scope (Entity (Bound)));
6382 if In_Open_Scopes (Tsk)
6383 and then Has_Completion (Tsk)
6385 -- Find discriminant of original task, and use its
6386 -- current discriminal, which is the renaming within
6389 Disc := First_Discriminant (Tsk);
6390 while Present (Disc) loop
6391 if Chars (Disc) = Chars (Entity (Bound)) then
6392 Set_Scope (Discriminal (Disc), Tsk);
6393 return New_Occurrence_Of (Discriminal (Disc), Loc);
6396 Next_Discriminant (Disc);
6399 -- That loop should always succeed in finding a matching
6400 -- entry and returning. Fatal error if not.
6402 raise Program_Error;
6406 New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6410 return New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6413 elsif Nkind (Bound) = N_Identifier
6414 and then Ekind (Entity (Bound)) = E_In_Parameter
6415 and then not Inside_Init_Proc
6417 return Get_Discriminal (E, Bound);
6419 elsif Nkind (Bound) = N_Integer_Literal then
6420 return Make_Integer_Literal (Loc, Intval (Bound));
6422 -- Case of a bound rewritten to an N_Raise_Constraint_Error node
6423 -- because it is an out-of-range value. Duplicate_Subexpr cannot be
6424 -- called on this node because an N_Raise_Constraint_Error is not
6425 -- side effect free, and we may not assume that we are in the proper
6426 -- context to remove side effects on it at the point of reference.
6428 elsif Nkind (Bound) = N_Raise_Constraint_Error then
6429 return New_Copy_Tree (Bound);
6432 return Duplicate_Subexpr_No_Checks (Bound);
6434 end Get_E_First_Or_Last;
6440 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6443 Make_Attribute_Reference (Loc,
6444 Attribute_Name => Name_First,
6446 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6447 Expressions => New_List (
6448 Make_Integer_Literal (Loc, Indx)));
6455 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6458 Make_Attribute_Reference (Loc,
6459 Attribute_Name => Name_Last,
6461 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6462 Expressions => New_List (
6463 Make_Integer_Literal (Loc, Indx)));
6470 function Range_E_Cond
6471 (Exptyp : Entity_Id;
6473 Indx : Nat) return Node_Id
6480 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6481 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6485 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6486 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6489 ------------------------
6490 -- Range_Equal_E_Cond --
6491 ------------------------
6493 function Range_Equal_E_Cond
6494 (Exptyp : Entity_Id;
6496 Indx : Nat) return Node_Id
6503 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6504 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6507 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6508 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6509 end Range_Equal_E_Cond;
6515 function Range_N_Cond
6518 Indx : Nat) return Node_Id
6525 Left_Opnd => Get_N_First (Expr, Indx),
6526 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6530 Left_Opnd => Get_N_Last (Expr, Indx),
6531 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6534 -- Start of processing for Selected_Range_Checks
6537 if not Expander_Active then
6541 if Target_Typ = Any_Type
6542 or else Target_Typ = Any_Composite
6543 or else Raises_Constraint_Error (Ck_Node)
6552 T_Typ := Target_Typ;
6554 if No (Source_Typ) then
6555 S_Typ := Etype (Ck_Node);
6557 S_Typ := Source_Typ;
6560 if S_Typ = Any_Type or else S_Typ = Any_Composite then
6564 -- The order of evaluating T_Typ before S_Typ seems to be critical
6565 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6566 -- in, and since Node can be an N_Range node, it might be invalid.
6567 -- Should there be an assert check somewhere for taking the Etype of
6568 -- an N_Range node ???
6570 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6571 S_Typ := Designated_Type (S_Typ);
6572 T_Typ := Designated_Type (T_Typ);
6575 -- A simple optimization for the null case
6577 if Known_Null (Ck_Node) then
6582 -- For an N_Range Node, check for a null range and then if not
6583 -- null generate a range check action.
6585 if Nkind (Ck_Node) = N_Range then
6587 -- There's no point in checking a range against itself
6589 if Ck_Node = Scalar_Range (T_Typ) then
6594 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
6595 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
6596 LB : constant Node_Id := Low_Bound (Ck_Node);
6597 HB : constant Node_Id := High_Bound (Ck_Node);
6598 Null_Range : Boolean;
6600 Out_Of_Range_L : Boolean;
6601 Out_Of_Range_H : Boolean;
6604 -- Check for case where everything is static and we can
6605 -- do the check at compile time. This is skipped if we
6606 -- have an access type, since the access value may be null.
6608 -- ??? This code can be improved since you only need to know
6609 -- that the two respective bounds (LB & T_LB or HB & T_HB)
6610 -- are known at compile time to emit pertinent messages.
6612 if Compile_Time_Known_Value (LB)
6613 and then Compile_Time_Known_Value (HB)
6614 and then Compile_Time_Known_Value (T_LB)
6615 and then Compile_Time_Known_Value (T_HB)
6616 and then not Do_Access
6618 -- Floating-point case
6620 if Is_Floating_Point_Type (S_Typ) then
6621 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6623 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6625 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6628 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6630 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6632 -- Fixed or discrete type case
6635 Null_Range := Expr_Value (HB) < Expr_Value (LB);
6637 (Expr_Value (LB) < Expr_Value (T_LB))
6639 (Expr_Value (LB) > Expr_Value (T_HB));
6642 (Expr_Value (HB) > Expr_Value (T_HB))
6644 (Expr_Value (HB) < Expr_Value (T_LB));
6647 if not Null_Range then
6648 if Out_Of_Range_L then
6649 if No (Warn_Node) then
6651 (Compile_Time_Constraint_Error
6652 (Low_Bound (Ck_Node),
6653 "static value out of range of}?", T_Typ));
6657 (Compile_Time_Constraint_Error
6659 "static range out of bounds of}?", T_Typ));
6663 if Out_Of_Range_H then
6664 if No (Warn_Node) then
6666 (Compile_Time_Constraint_Error
6667 (High_Bound (Ck_Node),
6668 "static value out of range of}?", T_Typ));
6672 (Compile_Time_Constraint_Error
6674 "static range out of bounds of}?", T_Typ));
6682 LB : Node_Id := Low_Bound (Ck_Node);
6683 HB : Node_Id := High_Bound (Ck_Node);
6686 -- If either bound is a discriminant and we are within the
6687 -- record declaration, it is a use of the discriminant in a
6688 -- constraint of a component, and nothing can be checked
6689 -- here. The check will be emitted within the init proc.
6690 -- Before then, the discriminal has no real meaning.
6691 -- Similarly, if the entity is a discriminal, there is no
6692 -- check to perform yet.
6694 -- The same holds within a discriminated synchronized type,
6695 -- where the discriminant may constrain a component or an
6698 if Nkind (LB) = N_Identifier
6699 and then Denotes_Discriminant (LB, True)
6701 if Current_Scope = Scope (Entity (LB))
6702 or else Is_Concurrent_Type (Current_Scope)
6703 or else Ekind (Entity (LB)) /= E_Discriminant
6708 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6712 if Nkind (HB) = N_Identifier
6713 and then Denotes_Discriminant (HB, True)
6715 if Current_Scope = Scope (Entity (HB))
6716 or else Is_Concurrent_Type (Current_Scope)
6717 or else Ekind (Entity (HB)) /= E_Discriminant
6722 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6726 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
6727 Set_Paren_Count (Cond, 1);
6733 Left_Opnd => Duplicate_Subexpr_No_Checks (HB),
6734 Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
6735 Right_Opnd => Cond);
6740 elsif Is_Scalar_Type (S_Typ) then
6742 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
6743 -- except the above simply sets a flag in the node and lets
6744 -- gigi generate the check base on the Etype of the expression.
6745 -- Sometimes, however we want to do a dynamic check against an
6746 -- arbitrary target type, so we do that here.
6748 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
6749 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6751 -- For literals, we can tell if the constraint error will be
6752 -- raised at compile time, so we never need a dynamic check, but
6753 -- if the exception will be raised, then post the usual warning,
6754 -- and replace the literal with a raise constraint error
6755 -- expression. As usual, skip this for access types
6757 elsif Compile_Time_Known_Value (Ck_Node)
6758 and then not Do_Access
6761 LB : constant Node_Id := Type_Low_Bound (T_Typ);
6762 UB : constant Node_Id := Type_High_Bound (T_Typ);
6764 Out_Of_Range : Boolean;
6765 Static_Bounds : constant Boolean :=
6766 Compile_Time_Known_Value (LB)
6767 and Compile_Time_Known_Value (UB);
6770 -- Following range tests should use Sem_Eval routine ???
6772 if Static_Bounds then
6773 if Is_Floating_Point_Type (S_Typ) then
6775 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
6777 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
6779 else -- fixed or discrete type
6781 Expr_Value (Ck_Node) < Expr_Value (LB)
6783 Expr_Value (Ck_Node) > Expr_Value (UB);
6786 -- Bounds of the type are static and the literal is
6787 -- out of range so make a warning message.
6789 if Out_Of_Range then
6790 if No (Warn_Node) then
6792 (Compile_Time_Constraint_Error
6794 "static value out of range of}?", T_Typ));
6798 (Compile_Time_Constraint_Error
6800 "static value out of range of}?", T_Typ));
6805 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6809 -- Here for the case of a non-static expression, we need a runtime
6810 -- check unless the source type range is guaranteed to be in the
6811 -- range of the target type.
6814 if not In_Subrange_Of (S_Typ, T_Typ) then
6815 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6820 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6821 if Is_Constrained (T_Typ) then
6823 Expr_Actual := Get_Referenced_Object (Ck_Node);
6824 Exptyp := Get_Actual_Subtype (Expr_Actual);
6826 if Is_Access_Type (Exptyp) then
6827 Exptyp := Designated_Type (Exptyp);
6830 -- String_Literal case. This needs to be handled specially be-
6831 -- cause no index types are available for string literals. The
6832 -- condition is simply:
6834 -- T_Typ'Length = string-literal-length
6836 if Nkind (Expr_Actual) = N_String_Literal then
6839 -- General array case. Here we have a usable actual subtype for
6840 -- the expression, and the condition is built from the two types
6842 -- T_Typ'First < Exptyp'First or else
6843 -- T_Typ'Last > Exptyp'Last or else
6844 -- T_Typ'First(1) < Exptyp'First(1) or else
6845 -- T_Typ'Last(1) > Exptyp'Last(1) or else
6848 elsif Is_Constrained (Exptyp) then
6850 Ndims : constant Nat := Number_Dimensions (T_Typ);
6856 L_Index := First_Index (T_Typ);
6857 R_Index := First_Index (Exptyp);
6859 for Indx in 1 .. Ndims loop
6860 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6862 Nkind (R_Index) = N_Raise_Constraint_Error)
6864 -- Deal with compile time length check. Note that we
6865 -- skip this in the access case, because the access
6866 -- value may be null, so we cannot know statically.
6869 Subtypes_Statically_Match
6870 (Etype (L_Index), Etype (R_Index))
6872 -- If the target type is constrained then we
6873 -- have to check for exact equality of bounds
6874 -- (required for qualified expressions).
6876 if Is_Constrained (T_Typ) then
6879 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
6882 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
6893 -- Handle cases where we do not get a usable actual subtype that
6894 -- is constrained. This happens for example in the function call
6895 -- and explicit dereference cases. In these cases, we have to get
6896 -- the length or range from the expression itself, making sure we
6897 -- do not evaluate it more than once.
6899 -- Here Ck_Node is the original expression, or more properly the
6900 -- result of applying Duplicate_Expr to the original tree,
6901 -- forcing the result to be a name.
6905 Ndims : constant Nat := Number_Dimensions (T_Typ);
6908 -- Build the condition for the explicit dereference case
6910 for Indx in 1 .. Ndims loop
6912 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
6919 -- For a conversion to an unconstrained array type, generate an
6920 -- Action to check that the bounds of the source value are within
6921 -- the constraints imposed by the target type (RM 4.6(38)). No
6922 -- check is needed for a conversion to an access to unconstrained
6923 -- array type, as 4.6(24.15/2) requires the designated subtypes
6924 -- of the two access types to statically match.
6926 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
6927 and then not Do_Access
6930 Opnd_Index : Node_Id;
6931 Targ_Index : Node_Id;
6932 Opnd_Range : Node_Id;
6935 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
6936 Targ_Index := First_Index (T_Typ);
6938 while Present (Opnd_Index) loop
6940 -- If the index is a range, use its bounds. If it is an
6941 -- entity (as will be the case if it is a named subtype
6942 -- or an itype created for a slice) retrieve its range.
6944 if Is_Entity_Name (Opnd_Index)
6945 and then Is_Type (Entity (Opnd_Index))
6947 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
6949 Opnd_Range := Opnd_Index;
6952 if Nkind (Opnd_Range) = N_Range then
6954 (Low_Bound (Opnd_Range), Etype (Targ_Index))
6957 (High_Bound (Opnd_Range), Etype (Targ_Index))
6961 -- If null range, no check needed
6964 Compile_Time_Known_Value (High_Bound (Opnd_Range))
6966 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
6968 Expr_Value (High_Bound (Opnd_Range)) <
6969 Expr_Value (Low_Bound (Opnd_Range))
6973 elsif Is_Out_Of_Range
6974 (Low_Bound (Opnd_Range), Etype (Targ_Index))
6977 (High_Bound (Opnd_Range), Etype (Targ_Index))
6980 (Compile_Time_Constraint_Error
6981 (Wnode, "value out of range of}?", T_Typ));
6987 (Opnd_Range, Etype (Targ_Index)));
6991 Next_Index (Opnd_Index);
6992 Next_Index (Targ_Index);
6999 -- Construct the test and insert into the tree
7001 if Present (Cond) then
7003 Cond := Guard_Access (Cond, Loc, Ck_Node);
7007 (Make_Raise_Constraint_Error (Loc,
7009 Reason => CE_Range_Check_Failed));
7013 end Selected_Range_Checks;
7015 -------------------------------
7016 -- Storage_Checks_Suppressed --
7017 -------------------------------
7019 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
7021 if Present (E) and then Checks_May_Be_Suppressed (E) then
7022 return Is_Check_Suppressed (E, Storage_Check);
7024 return Scope_Suppress (Storage_Check);
7026 end Storage_Checks_Suppressed;
7028 ---------------------------
7029 -- Tag_Checks_Suppressed --
7030 ---------------------------
7032 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
7035 if Kill_Tag_Checks (E) then
7037 elsif Checks_May_Be_Suppressed (E) then
7038 return Is_Check_Suppressed (E, Tag_Check);
7042 return Scope_Suppress (Tag_Check);
7043 end Tag_Checks_Suppressed;
7045 --------------------------
7046 -- Validity_Check_Range --
7047 --------------------------
7049 procedure Validity_Check_Range (N : Node_Id) is
7051 if Validity_Checks_On and Validity_Check_Operands then
7052 if Nkind (N) = N_Range then
7053 Ensure_Valid (Low_Bound (N));
7054 Ensure_Valid (High_Bound (N));
7057 end Validity_Check_Range;
7059 --------------------------------
7060 -- Validity_Checks_Suppressed --
7061 --------------------------------
7063 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
7065 if Present (E) and then Checks_May_Be_Suppressed (E) then
7066 return Is_Check_Suppressed (E, Validity_Check);
7068 return Scope_Suppress (Validity_Check);
7070 end Validity_Checks_Suppressed;