1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
9 -- Copyright (C) 1992-2007, 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 2, 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 COPYING. If not, write --
19 -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
20 -- Boston, MA 02110-1301, USA. --
22 -- GNAT was originally developed by the GNAT team at New York University. --
23 -- Extensive contributions were provided by Ada Core Technologies Inc. --
25 ------------------------------------------------------------------------------
27 with Atree; use Atree;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Errout; use Errout;
31 with Exp_Ch2; use Exp_Ch2;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Pakd; use Exp_Pakd;
34 with Exp_Util; use Exp_Util;
35 with Elists; use Elists;
36 with Eval_Fat; use Eval_Fat;
37 with Freeze; use Freeze;
39 with Namet; use Namet;
40 with Nlists; use Nlists;
41 with Nmake; use Nmake;
43 with Output; use Output;
44 with Restrict; use Restrict;
45 with Rident; use Rident;
46 with Rtsfind; use Rtsfind;
48 with Sem_Eval; use Sem_Eval;
49 with Sem_Ch3; use Sem_Ch3;
50 with Sem_Ch8; use Sem_Ch8;
51 with Sem_Res; use Sem_Res;
52 with Sem_Util; use Sem_Util;
53 with Sem_Warn; use Sem_Warn;
54 with Sinfo; use Sinfo;
55 with Sinput; use Sinput;
56 with Snames; use Snames;
57 with Sprint; use Sprint;
58 with Stand; use Stand;
59 with Targparm; use Targparm;
60 with Tbuild; use Tbuild;
61 with Ttypes; use Ttypes;
62 with Urealp; use Urealp;
63 with Validsw; use Validsw;
65 package body Checks is
67 -- General note: many of these routines are concerned with generating
68 -- checking code to make sure that constraint error is raised at runtime.
69 -- Clearly this code is only needed if the expander is active, since
70 -- otherwise we will not be generating code or going into the runtime
73 -- We therefore disconnect most of these checks if the expander is
74 -- inactive. This has the additional benefit that we do not need to
75 -- worry about the tree being messed up by previous errors (since errors
76 -- turn off expansion anyway).
78 -- There are a few exceptions to the above rule. For instance routines
79 -- such as Apply_Scalar_Range_Check that do not insert any code can be
80 -- safely called even when the Expander is inactive (but Errors_Detected
81 -- is 0). The benefit of executing this code when expansion is off, is
82 -- the ability to emit constraint error warning for static expressions
83 -- even when we are not generating code.
85 -------------------------------------
86 -- Suppression of Redundant Checks --
87 -------------------------------------
89 -- This unit implements a limited circuit for removal of redundant
90 -- checks. The processing is based on a tracing of simple sequential
91 -- flow. For any sequence of statements, we save expressions that are
92 -- marked to be checked, and then if the same expression appears later
93 -- with the same check, then under certain circumstances, the second
94 -- check can be suppressed.
96 -- Basically, we can suppress the check if we know for certain that
97 -- the previous expression has been elaborated (together with its
98 -- check), and we know that the exception frame is the same, and that
99 -- nothing has happened to change the result of the exception.
101 -- Let us examine each of these three conditions in turn to describe
102 -- how we ensure that this condition is met.
104 -- First, we need to know for certain that the previous expression has
105 -- been executed. This is done principly by the mechanism of calling
106 -- Conditional_Statements_Begin at the start of any statement sequence
107 -- and Conditional_Statements_End at the end. The End call causes all
108 -- checks remembered since the Begin call to be discarded. This does
109 -- miss a few cases, notably the case of a nested BEGIN-END block with
110 -- no exception handlers. But the important thing is to be conservative.
111 -- The other protection is that all checks are discarded if a label
112 -- is encountered, since then the assumption of sequential execution
113 -- is violated, and we don't know enough about the flow.
115 -- Second, we need to know that the exception frame is the same. We
116 -- do this by killing all remembered checks when we enter a new frame.
117 -- Again, that's over-conservative, but generally the cases we can help
118 -- with are pretty local anyway (like the body of a loop for example).
120 -- Third, we must be sure to forget any checks which are no longer valid.
121 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
122 -- used to note any changes to local variables. We only attempt to deal
123 -- with checks involving local variables, so we do not need to worry
124 -- about global variables. Second, a call to any non-global procedure
125 -- causes us to abandon all stored checks, since such a all may affect
126 -- the values of any local variables.
128 -- The following define the data structures used to deal with remembering
129 -- checks so that redundant checks can be eliminated as described above.
131 -- Right now, the only expressions that we deal with are of the form of
132 -- simple local objects (either declared locally, or IN parameters) or
133 -- such objects plus/minus a compile time known constant. We can do
134 -- more later on if it seems worthwhile, but this catches many simple
135 -- cases in practice.
137 -- The following record type reflects a single saved check. An entry
138 -- is made in the stack of saved checks if and only if the expression
139 -- has been elaborated with the indicated checks.
141 type Saved_Check is record
143 -- Set True if entry is killed by Kill_Checks
146 -- The entity involved in the expression that is checked
149 -- A compile time value indicating the result of adding or
150 -- subtracting a compile time value. This value is to be
151 -- added to the value of the Entity. A value of zero is
152 -- used for the case of a simple entity reference.
154 Check_Type : Character;
155 -- This is set to 'R' for a range check (in which case Target_Type
156 -- is set to the target type for the range check) or to 'O' for an
157 -- overflow check (in which case Target_Type is set to Empty).
159 Target_Type : Entity_Id;
160 -- Used only if Do_Range_Check is set. Records the target type for
161 -- the check. We need this, because a check is a duplicate only if
162 -- it has a the same target type (or more accurately one with a
163 -- range that is smaller or equal to the stored target type of a
167 -- The following table keeps track of saved checks. Rather than use an
168 -- extensible table. We just use a table of fixed size, and we discard
169 -- any saved checks that do not fit. That's very unlikely to happen and
170 -- this is only an optimization in any case.
172 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
173 -- Array of saved checks
175 Num_Saved_Checks : Nat := 0;
176 -- Number of saved checks
178 -- The following stack keeps track of statement ranges. It is treated
179 -- as a stack. When Conditional_Statements_Begin is called, an entry
180 -- is pushed onto this stack containing the value of Num_Saved_Checks
181 -- at the time of the call. Then when Conditional_Statements_End is
182 -- called, this value is popped off and used to reset Num_Saved_Checks.
184 -- Note: again, this is a fixed length stack with a size that should
185 -- always be fine. If the value of the stack pointer goes above the
186 -- limit, then we just forget all saved checks.
188 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
189 Saved_Checks_TOS : Nat := 0;
191 -----------------------
192 -- Local Subprograms --
193 -----------------------
195 procedure Apply_Float_Conversion_Check
197 Target_Typ : Entity_Id);
198 -- The checks on a conversion from a floating-point type to an integer
199 -- type are delicate. They have to be performed before conversion, they
200 -- have to raise an exception when the operand is a NaN, and rounding must
201 -- be taken into account to determine the safe bounds of the operand.
203 procedure Apply_Selected_Length_Checks
205 Target_Typ : Entity_Id;
206 Source_Typ : Entity_Id;
207 Do_Static : Boolean);
208 -- This is the subprogram that does all the work for Apply_Length_Check
209 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
210 -- described for the above routines. The Do_Static flag indicates that
211 -- only a static check is to be done.
213 procedure Apply_Selected_Range_Checks
215 Target_Typ : Entity_Id;
216 Source_Typ : Entity_Id;
217 Do_Static : Boolean);
218 -- This is the subprogram that does all the work for Apply_Range_Check.
219 -- Expr, Target_Typ and Source_Typ are as described for the above
220 -- routine. The Do_Static flag indicates that only a static check is
223 type Check_Type is (Access_Check, Division_Check);
224 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
225 -- This function is used to see if an access or division by zero check is
226 -- needed. The check is to be applied to a single variable appearing in the
227 -- source, and N is the node for the reference. If N is not of this form,
228 -- True is returned with no further processing. If N is of the right form,
229 -- then further processing determines if the given Check is needed.
231 -- The particular circuit is to see if we have the case of a check that is
232 -- not needed because it appears in the right operand of a short circuited
233 -- conditional where the left operand guards the check. For example:
235 -- if Var = 0 or else Q / Var > 12 then
239 -- In this example, the division check is not required. At the same time
240 -- we can issue warnings for suspicious use of non-short-circuited forms,
243 -- if Var = 0 or Q / Var > 12 then
249 Check_Type : Character;
250 Target_Type : Entity_Id;
251 Entry_OK : out Boolean;
255 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
256 -- to see if a check is of the form for optimization, and if so, to see
257 -- if it has already been performed. Expr is the expression to check,
258 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
259 -- Target_Type is the target type for a range check, and Empty for an
260 -- overflow check. If the entry is not of the form for optimization,
261 -- then Entry_OK is set to False, and the remaining out parameters
262 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
263 -- entity and offset from the expression. Check_Num is the number of
264 -- a matching saved entry in Saved_Checks, or zero if no such entry
267 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
268 -- If a discriminal is used in constraining a prival, Return reference
269 -- to the discriminal of the protected body (which renames the parameter
270 -- of the enclosing protected operation). This clumsy transformation is
271 -- needed because privals are created too late and their actual subtypes
272 -- are not available when analysing the bodies of the protected operations.
273 -- This function is called whenever the bound is an entity and the scope
274 -- indicates a protected operation. If the bound is an in-parameter of
275 -- a protected operation that is not a prival, the function returns the
277 -- To be cleaned up???
279 function Guard_Access
282 Ck_Node : Node_Id) return Node_Id;
283 -- In the access type case, guard the test with a test to ensure
284 -- that the access value is non-null, since the checks do not
285 -- not apply to null access values.
287 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
288 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
289 -- Constraint_Error node.
291 function Range_Or_Validity_Checks_Suppressed
292 (Expr : Node_Id) return Boolean;
293 -- Returns True if either range or validity checks or both are suppressed
294 -- for the type of the given expression, or, if the expression is the name
295 -- of an entity, if these checks are suppressed for the entity.
297 function Selected_Length_Checks
299 Target_Typ : Entity_Id;
300 Source_Typ : Entity_Id;
301 Warn_Node : Node_Id) return Check_Result;
302 -- Like Apply_Selected_Length_Checks, except it doesn't modify
303 -- anything, just returns a list of nodes as described in the spec of
304 -- this package for the Range_Check function.
306 function Selected_Range_Checks
308 Target_Typ : Entity_Id;
309 Source_Typ : Entity_Id;
310 Warn_Node : Node_Id) return Check_Result;
311 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
312 -- just returns a list of nodes as described in the spec of this package
313 -- for the Range_Check function.
315 ------------------------------
316 -- Access_Checks_Suppressed --
317 ------------------------------
319 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
321 if Present (E) and then Checks_May_Be_Suppressed (E) then
322 return Is_Check_Suppressed (E, Access_Check);
324 return Scope_Suppress (Access_Check);
326 end Access_Checks_Suppressed;
328 -------------------------------------
329 -- Accessibility_Checks_Suppressed --
330 -------------------------------------
332 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
334 if Present (E) and then Checks_May_Be_Suppressed (E) then
335 return Is_Check_Suppressed (E, Accessibility_Check);
337 return Scope_Suppress (Accessibility_Check);
339 end Accessibility_Checks_Suppressed;
341 -----------------------------
342 -- Activate_Division_Check --
343 -----------------------------
345 procedure Activate_Division_Check (N : Node_Id) is
347 Set_Do_Division_Check (N, True);
348 Possible_Local_Raise (N, Standard_Constraint_Error);
349 end Activate_Division_Check;
351 -----------------------------
352 -- Activate_Overflow_Check --
353 -----------------------------
355 procedure Activate_Overflow_Check (N : Node_Id) is
357 Set_Do_Overflow_Check (N, True);
358 Possible_Local_Raise (N, Standard_Constraint_Error);
359 end Activate_Overflow_Check;
361 --------------------------
362 -- Activate_Range_Check --
363 --------------------------
365 procedure Activate_Range_Check (N : Node_Id) is
367 Set_Do_Range_Check (N, True);
368 Possible_Local_Raise (N, Standard_Constraint_Error);
369 end Activate_Range_Check;
371 ---------------------------------
372 -- Alignment_Checks_Suppressed --
373 ---------------------------------
375 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
377 if Present (E) and then Checks_May_Be_Suppressed (E) then
378 return Is_Check_Suppressed (E, Alignment_Check);
380 return Scope_Suppress (Alignment_Check);
382 end Alignment_Checks_Suppressed;
384 -------------------------
385 -- Append_Range_Checks --
386 -------------------------
388 procedure Append_Range_Checks
389 (Checks : Check_Result;
391 Suppress_Typ : Entity_Id;
392 Static_Sloc : Source_Ptr;
395 Internal_Flag_Node : constant Node_Id := Flag_Node;
396 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
398 Checks_On : constant Boolean :=
399 (not Index_Checks_Suppressed (Suppress_Typ))
401 (not Range_Checks_Suppressed (Suppress_Typ));
404 -- For now we just return if Checks_On is false, however this should
405 -- be enhanced to check for an always True value in the condition
406 -- and to generate a compilation warning???
408 if not Checks_On then
413 exit when No (Checks (J));
415 if Nkind (Checks (J)) = N_Raise_Constraint_Error
416 and then Present (Condition (Checks (J)))
418 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
419 Append_To (Stmts, Checks (J));
420 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
426 Make_Raise_Constraint_Error (Internal_Static_Sloc,
427 Reason => CE_Range_Check_Failed));
430 end Append_Range_Checks;
432 ------------------------
433 -- Apply_Access_Check --
434 ------------------------
436 procedure Apply_Access_Check (N : Node_Id) is
437 P : constant Node_Id := Prefix (N);
440 -- We do not need checks if we are not generating code (i.e. the
441 -- expander is not active). This is not just an optimization, there
442 -- are cases (e.g. with pragma Debug) where generating the checks
443 -- can cause real trouble).
445 if not Expander_Active then
449 -- No check if short circuiting makes check unnecessary
451 if not Check_Needed (P, Access_Check) then
455 -- Otherwise go ahead and install the check
457 Install_Null_Excluding_Check (P);
458 end Apply_Access_Check;
460 -------------------------------
461 -- Apply_Accessibility_Check --
462 -------------------------------
464 procedure Apply_Accessibility_Check (N : Node_Id; Typ : Entity_Id) is
465 Loc : constant Source_Ptr := Sloc (N);
466 Param_Ent : constant Entity_Id := Param_Entity (N);
467 Param_Level : Node_Id;
468 Type_Level : Node_Id;
471 if Inside_A_Generic then
474 -- Only apply the run-time check if the access parameter
475 -- has an associated extra access level parameter and
476 -- when the level of the type is less deep than the level
477 -- of the access parameter.
479 elsif Present (Param_Ent)
480 and then Present (Extra_Accessibility (Param_Ent))
481 and then UI_Gt (Object_Access_Level (N),
482 Type_Access_Level (Typ))
483 and then not Accessibility_Checks_Suppressed (Param_Ent)
484 and then not Accessibility_Checks_Suppressed (Typ)
487 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
490 Make_Integer_Literal (Loc, Type_Access_Level (Typ));
492 -- Raise Program_Error if the accessibility level of the the access
493 -- parameter is deeper than the level of the target access type.
496 Make_Raise_Program_Error (Loc,
499 Left_Opnd => Param_Level,
500 Right_Opnd => Type_Level),
501 Reason => PE_Accessibility_Check_Failed));
503 Analyze_And_Resolve (N);
505 end Apply_Accessibility_Check;
507 --------------------------------
508 -- Apply_Address_Clause_Check --
509 --------------------------------
511 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
512 AC : constant Node_Id := Address_Clause (E);
513 Loc : constant Source_Ptr := Sloc (AC);
514 Typ : constant Entity_Id := Etype (E);
515 Aexp : constant Node_Id := Expression (AC);
518 -- Address expression (not necessarily the same as Aexp, for example
519 -- when Aexp is a reference to a constant, in which case Expr gets
520 -- reset to reference the value expression of the constant.
522 Size_Warning_Output : Boolean := False;
523 -- If we output a size warning we set this True, to stop generating
524 -- what is likely to be an unuseful redundant alignment warning.
526 procedure Compile_Time_Bad_Alignment;
527 -- Post error warnings when alignment is known to be incompatible. Note
528 -- that we do not go as far as inserting a raise of Program_Error since
529 -- this is an erroneous case, and it may happen that we are lucky and an
530 -- underaligned address turns out to be OK after all. Also this warning
531 -- is suppressed if we already complained about the size.
533 --------------------------------
534 -- Compile_Time_Bad_Alignment --
535 --------------------------------
537 procedure Compile_Time_Bad_Alignment is
539 if not Size_Warning_Output
540 and then Address_Clause_Overlay_Warnings
543 ("?specified address for& may be inconsistent with alignment ",
546 ("\?program execution may be erroneous ('R'M 13.3(27))",
549 end Compile_Time_Bad_Alignment;
551 -- Start of processing for Apply_Address_Check
554 -- First obtain expression from address clause
556 Expr := Expression (AC);
558 -- The following loop digs for the real expression to use in the check
561 -- For constant, get constant expression
563 if Is_Entity_Name (Expr)
564 and then Ekind (Entity (Expr)) = E_Constant
566 Expr := Constant_Value (Entity (Expr));
568 -- For unchecked conversion, get result to convert
570 elsif Nkind (Expr) = N_Unchecked_Type_Conversion then
571 Expr := Expression (Expr);
573 -- For (common case) of To_Address call, get argument
575 elsif Nkind (Expr) = N_Function_Call
576 and then Is_Entity_Name (Name (Expr))
577 and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
579 Expr := First (Parameter_Associations (Expr));
581 if Nkind (Expr) = N_Parameter_Association then
582 Expr := Explicit_Actual_Parameter (Expr);
585 -- We finally have the real expression
592 -- Output a warning if we have the situation of
594 -- for X'Address use Y'Address
596 -- and X and Y both have known object sizes, and Y is smaller than X
598 if Nkind (Expr) = N_Attribute_Reference
599 and then Attribute_Name (Expr) = Name_Address
600 and then Is_Entity_Name (Prefix (Expr))
603 Exp_Ent : constant Entity_Id := Entity (Prefix (Expr));
604 Obj_Size : Uint := No_Uint;
605 Exp_Size : Uint := No_Uint;
608 if Known_Esize (E) then
609 Obj_Size := Esize (E);
610 elsif Known_Esize (Etype (E)) then
611 Obj_Size := Esize (Etype (E));
614 if Known_Esize (Exp_Ent) then
615 Exp_Size := Esize (Exp_Ent);
616 elsif Known_Esize (Etype (Exp_Ent)) then
617 Exp_Size := Esize (Etype (Exp_Ent));
620 if Obj_Size /= No_Uint
621 and then Exp_Size /= No_Uint
622 and then Obj_Size > Exp_Size
623 and then not Warnings_Off (E)
625 if Address_Clause_Overlay_Warnings then
627 ("?& overlays smaller object", Aexp, E);
629 ("\?program execution may be erroneous", Aexp, E);
630 Size_Warning_Output := True;
636 -- See if alignment check needed. Note that we never need a check if the
637 -- maximum alignment is one, since the check will always succeed.
639 -- Note: we do not check for checks suppressed here, since that check
640 -- was done in Sem_Ch13 when the address clause was proceeds. We are
641 -- only called if checks were not suppressed. The reason for this is
642 -- that we have to delay the call to Apply_Alignment_Check till freeze
643 -- time (so that all types etc are elaborated), but we have to check
644 -- the status of check suppressing at the point of the address clause.
647 or else not Check_Address_Alignment (AC)
648 or else Maximum_Alignment = 1
653 -- See if we know that Expr is a bad alignment at compile time
655 if Compile_Time_Known_Value (Expr)
656 and then (Known_Alignment (E) or else Known_Alignment (Typ))
659 AL : Uint := Alignment (Typ);
662 -- The object alignment might be more restrictive than the
665 if Known_Alignment (E) then
669 if Expr_Value (Expr) mod AL /= 0 then
670 Compile_Time_Bad_Alignment;
676 -- If the expression has the form X'Address, then we can find out if
677 -- the object X has an alignment that is compatible with the object E.
679 elsif Nkind (Expr) = N_Attribute_Reference
680 and then Attribute_Name (Expr) = Name_Address
683 AR : constant Alignment_Result :=
684 Has_Compatible_Alignment (E, Prefix (Expr));
686 if AR = Known_Compatible then
688 elsif AR = Known_Incompatible then
689 Compile_Time_Bad_Alignment;
694 -- Here we do not know if the value is acceptable. Stricly we don't have
695 -- to do anything, since if the alignment is bad, we have an erroneous
696 -- program. However we are allowed to check for erroneous conditions and
697 -- we decide to do this by default if the check is not suppressed.
699 -- However, don't do the check if elaboration code is unwanted
701 if Restriction_Active (No_Elaboration_Code) then
704 -- Generate a check to raise PE if alignment may be inappropriate
707 -- If the original expression is a non-static constant, use the
708 -- name of the constant itself rather than duplicating its
709 -- defining expression, which was extracted above.
711 -- Note: Expr is empty if the address-clause is applied to in-mode
712 -- actuals (allowed by 13.1(22)).
714 if not Present (Expr)
716 (Is_Entity_Name (Expression (AC))
717 and then Ekind (Entity (Expression (AC))) = E_Constant
718 and then Nkind (Parent (Entity (Expression (AC))))
719 = N_Object_Declaration)
721 Expr := New_Copy_Tree (Expression (AC));
723 Remove_Side_Effects (Expr);
726 Insert_After_And_Analyze (N,
727 Make_Raise_Program_Error (Loc,
734 (RTE (RE_Integer_Address), Expr),
736 Make_Attribute_Reference (Loc,
737 Prefix => New_Occurrence_Of (E, Loc),
738 Attribute_Name => Name_Alignment)),
739 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
740 Reason => PE_Misaligned_Address_Value),
741 Suppress => All_Checks);
746 -- If we have some missing run time component in configurable run time
747 -- mode then just skip the check (it is not required in any case).
749 when RE_Not_Available =>
751 end Apply_Address_Clause_Check;
753 -------------------------------------
754 -- Apply_Arithmetic_Overflow_Check --
755 -------------------------------------
757 -- This routine is called only if the type is an integer type, and
758 -- a software arithmetic overflow check must be performed for op
759 -- (add, subtract, multiply). The check is performed only if
760 -- Software_Overflow_Checking is enabled and Do_Overflow_Check
761 -- is set. In this case we expand the operation into a more complex
762 -- sequence of tests that ensures that overflow is properly caught.
764 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
765 Loc : constant Source_Ptr := Sloc (N);
766 Typ : constant Entity_Id := Etype (N);
767 Rtyp : constant Entity_Id := Root_Type (Typ);
768 Siz : constant Int := UI_To_Int (Esize (Rtyp));
769 Dsiz : constant Int := Siz * 2;
776 -- Skip this if overflow checks are done in back end, or the overflow
777 -- flag is not set anyway, or we are not doing code expansion.
778 -- Special case CLI target, where arithmetic overflow checks can be
779 -- performed for integer and long_integer
781 if Backend_Overflow_Checks_On_Target
782 or else (VM_Target = CLI_Target and then Siz >= Standard_Integer_Size)
783 or else not Do_Overflow_Check (N)
784 or else not Expander_Active
789 -- Otherwise, we generate the full general code for front end overflow
790 -- detection, which works by doing arithmetic in a larger type:
796 -- Typ (Checktyp (x) op Checktyp (y));
798 -- where Typ is the type of the original expression, and Checktyp is
799 -- an integer type of sufficient length to hold the largest possible
802 -- In the case where check type exceeds the size of Long_Long_Integer,
803 -- we use a different approach, expanding to:
805 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
807 -- where xxx is Add, Multiply or Subtract as appropriate
809 -- Find check type if one exists
811 if Dsiz <= Standard_Integer_Size then
812 Ctyp := Standard_Integer;
814 elsif Dsiz <= Standard_Long_Long_Integer_Size then
815 Ctyp := Standard_Long_Long_Integer;
817 -- No check type exists, use runtime call
820 if Nkind (N) = N_Op_Add then
821 Cent := RE_Add_With_Ovflo_Check;
823 elsif Nkind (N) = N_Op_Multiply then
824 Cent := RE_Multiply_With_Ovflo_Check;
827 pragma Assert (Nkind (N) = N_Op_Subtract);
828 Cent := RE_Subtract_With_Ovflo_Check;
833 Make_Function_Call (Loc,
834 Name => New_Reference_To (RTE (Cent), Loc),
835 Parameter_Associations => New_List (
836 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
837 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
839 Analyze_And_Resolve (N, Typ);
843 -- If we fall through, we have the case where we do the arithmetic in
844 -- the next higher type and get the check by conversion. In these cases
845 -- Ctyp is set to the type to be used as the check type.
847 Opnod := Relocate_Node (N);
849 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
852 Set_Etype (Opnd, Ctyp);
853 Set_Analyzed (Opnd, True);
854 Set_Left_Opnd (Opnod, Opnd);
856 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
859 Set_Etype (Opnd, Ctyp);
860 Set_Analyzed (Opnd, True);
861 Set_Right_Opnd (Opnod, Opnd);
863 -- The type of the operation changes to the base type of the check type,
864 -- and we reset the overflow check indication, since clearly no overflow
865 -- is possible now that we are using a double length type. We also set
866 -- the Analyzed flag to avoid a recursive attempt to expand the node.
868 Set_Etype (Opnod, Base_Type (Ctyp));
869 Set_Do_Overflow_Check (Opnod, False);
870 Set_Analyzed (Opnod, True);
872 -- Now build the outer conversion
874 Opnd := OK_Convert_To (Typ, Opnod);
876 Set_Etype (Opnd, Typ);
878 -- In the discrete type case, we directly generate the range check for
879 -- the outer operand. This range check will implement the required
882 if Is_Discrete_Type (Typ) then
884 Generate_Range_Check (Expression (N), Typ, CE_Overflow_Check_Failed);
886 -- For other types, we enable overflow checking on the conversion,
887 -- after setting the node as analyzed to prevent recursive attempts
888 -- to expand the conversion node.
891 Set_Analyzed (Opnd, True);
892 Enable_Overflow_Check (Opnd);
897 when RE_Not_Available =>
899 end Apply_Arithmetic_Overflow_Check;
901 ----------------------------
902 -- Apply_Constraint_Check --
903 ----------------------------
905 procedure Apply_Constraint_Check
908 No_Sliding : Boolean := False)
910 Desig_Typ : Entity_Id;
913 if Inside_A_Generic then
916 elsif Is_Scalar_Type (Typ) then
917 Apply_Scalar_Range_Check (N, Typ);
919 elsif Is_Array_Type (Typ) then
921 -- A useful optimization: an aggregate with only an others clause
922 -- always has the right bounds.
924 if Nkind (N) = N_Aggregate
925 and then No (Expressions (N))
927 (First (Choices (First (Component_Associations (N)))))
933 if Is_Constrained (Typ) then
934 Apply_Length_Check (N, Typ);
937 Apply_Range_Check (N, Typ);
940 Apply_Range_Check (N, Typ);
943 elsif (Is_Record_Type (Typ)
944 or else Is_Private_Type (Typ))
945 and then Has_Discriminants (Base_Type (Typ))
946 and then Is_Constrained (Typ)
948 Apply_Discriminant_Check (N, Typ);
950 elsif Is_Access_Type (Typ) then
952 Desig_Typ := Designated_Type (Typ);
954 -- No checks necessary if expression statically null
956 if Nkind (N) = N_Null then
957 if Can_Never_Be_Null (Typ) then
958 Install_Null_Excluding_Check (N);
961 -- No sliding possible on access to arrays
963 elsif Is_Array_Type (Desig_Typ) then
964 if Is_Constrained (Desig_Typ) then
965 Apply_Length_Check (N, Typ);
968 Apply_Range_Check (N, Typ);
970 elsif Has_Discriminants (Base_Type (Desig_Typ))
971 and then Is_Constrained (Desig_Typ)
973 Apply_Discriminant_Check (N, Typ);
976 -- Apply the the 2005 Null_Excluding check. Note that we do not apply
977 -- this check if the constraint node is illegal, as shown by having
978 -- an error posted. This additional guard prevents cascaded errors
979 -- and compiler aborts on illegal programs involving Ada 2005 checks.
981 if Can_Never_Be_Null (Typ)
982 and then not Can_Never_Be_Null (Etype (N))
983 and then not Error_Posted (N)
985 Install_Null_Excluding_Check (N);
988 end Apply_Constraint_Check;
990 ------------------------------
991 -- Apply_Discriminant_Check --
992 ------------------------------
994 procedure Apply_Discriminant_Check
997 Lhs : Node_Id := Empty)
999 Loc : constant Source_Ptr := Sloc (N);
1000 Do_Access : constant Boolean := Is_Access_Type (Typ);
1001 S_Typ : Entity_Id := Etype (N);
1005 function Is_Aliased_Unconstrained_Component return Boolean;
1006 -- It is possible for an aliased component to have a nominal
1007 -- unconstrained subtype (through instantiation). If this is a
1008 -- discriminated component assigned in the expansion of an aggregate
1009 -- in an initialization, the check must be suppressed. This unusual
1010 -- situation requires a predicate of its own (see 7503-008).
1012 ----------------------------------------
1013 -- Is_Aliased_Unconstrained_Component --
1014 ----------------------------------------
1016 function Is_Aliased_Unconstrained_Component return Boolean is
1021 if Nkind (Lhs) /= N_Selected_Component then
1024 Comp := Entity (Selector_Name (Lhs));
1025 Pref := Prefix (Lhs);
1028 if Ekind (Comp) /= E_Component
1029 or else not Is_Aliased (Comp)
1034 return not Comes_From_Source (Pref)
1035 and then In_Instance
1036 and then not Is_Constrained (Etype (Comp));
1037 end Is_Aliased_Unconstrained_Component;
1039 -- Start of processing for Apply_Discriminant_Check
1043 T_Typ := Designated_Type (Typ);
1048 -- Nothing to do if discriminant checks are suppressed or else no code
1049 -- is to be generated
1051 if not Expander_Active
1052 or else Discriminant_Checks_Suppressed (T_Typ)
1057 -- No discriminant checks necessary for an access when expression is
1058 -- statically Null. This is not only an optimization, it is fundamental
1059 -- because otherwise discriminant checks may be generated in init procs
1060 -- for types containing an access to a not-yet-frozen record, causing a
1061 -- deadly forward reference.
1063 -- Also, if the expression is of an access type whose designated type is
1064 -- incomplete, then the access value must be null and we suppress the
1067 if Nkind (N) = N_Null then
1070 elsif Is_Access_Type (S_Typ) then
1071 S_Typ := Designated_Type (S_Typ);
1073 if Ekind (S_Typ) = E_Incomplete_Type then
1078 -- If an assignment target is present, then we need to generate the
1079 -- actual subtype if the target is a parameter or aliased object with
1080 -- an unconstrained nominal subtype.
1082 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1083 -- subtype to the parameter and dereference cases, since other aliased
1084 -- objects are unconstrained (unless the nominal subtype is explicitly
1085 -- constrained). (But we also need to test for renamings???)
1088 and then (Present (Param_Entity (Lhs))
1089 or else (Ada_Version < Ada_05
1090 and then not Is_Constrained (T_Typ)
1091 and then Is_Aliased_View (Lhs)
1092 and then not Is_Aliased_Unconstrained_Component)
1093 or else (Ada_Version >= Ada_05
1094 and then not Is_Constrained (T_Typ)
1095 and then Nkind (Lhs) = N_Explicit_Dereference
1096 and then Nkind (Original_Node (Lhs)) /=
1099 T_Typ := Get_Actual_Subtype (Lhs);
1102 -- Nothing to do if the type is unconstrained (this is the case where
1103 -- the actual subtype in the RM sense of N is unconstrained and no check
1106 if not Is_Constrained (T_Typ) then
1109 -- Ada 2005: nothing to do if the type is one for which there is a
1110 -- partial view that is constrained.
1112 elsif Ada_Version >= Ada_05
1113 and then Has_Constrained_Partial_View (Base_Type (T_Typ))
1118 -- Nothing to do if the type is an Unchecked_Union
1120 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1124 -- Suppress checks if the subtypes are the same. the check must be
1125 -- preserved in an assignment to a formal, because the constraint is
1126 -- given by the actual.
1128 if Nkind (Original_Node (N)) /= N_Allocator
1130 or else not Is_Entity_Name (Lhs)
1131 or else No (Param_Entity (Lhs)))
1134 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1135 and then not Is_Aliased_View (Lhs)
1140 -- We can also eliminate checks on allocators with a subtype mark that
1141 -- coincides with the context type. The context type may be a subtype
1142 -- without a constraint (common case, a generic actual).
1144 elsif Nkind (Original_Node (N)) = N_Allocator
1145 and then Is_Entity_Name (Expression (Original_Node (N)))
1148 Alloc_Typ : constant Entity_Id :=
1149 Entity (Expression (Original_Node (N)));
1152 if Alloc_Typ = T_Typ
1153 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1154 and then Is_Entity_Name (
1155 Subtype_Indication (Parent (T_Typ)))
1156 and then Alloc_Typ = Base_Type (T_Typ))
1164 -- See if we have a case where the types are both constrained, and all
1165 -- the constraints are constants. In this case, we can do the check
1166 -- successfully at compile time.
1168 -- We skip this check for the case where the node is a rewritten`
1169 -- allocator, because it already carries the context subtype, and
1170 -- extracting the discriminants from the aggregate is messy.
1172 if Is_Constrained (S_Typ)
1173 and then Nkind (Original_Node (N)) /= N_Allocator
1183 -- S_Typ may not have discriminants in the case where it is a
1184 -- private type completed by a default discriminated type. In that
1185 -- case, we need to get the constraints from the underlying_type.
1186 -- If the underlying type is unconstrained (i.e. has no default
1187 -- discriminants) no check is needed.
1189 if Has_Discriminants (S_Typ) then
1190 Discr := First_Discriminant (S_Typ);
1191 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1194 Discr := First_Discriminant (Underlying_Type (S_Typ));
1197 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1203 -- A further optimization: if T_Typ is derived from S_Typ
1204 -- without imposing a constraint, no check is needed.
1206 if Nkind (Original_Node (Parent (T_Typ))) =
1207 N_Full_Type_Declaration
1210 Type_Def : constant Node_Id :=
1212 (Original_Node (Parent (T_Typ)));
1214 if Nkind (Type_Def) = N_Derived_Type_Definition
1215 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1216 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1224 DconT := First_Elmt (Discriminant_Constraint (T_Typ));
1226 while Present (Discr) loop
1227 ItemS := Node (DconS);
1228 ItemT := Node (DconT);
1230 -- For a discriminated component type constrained by the
1231 -- current instance of an enclosing type, there is no
1232 -- applicable discriminant check.
1234 if Nkind (ItemT) = N_Attribute_Reference
1235 and then Is_Access_Type (Etype (ItemT))
1236 and then Is_Entity_Name (Prefix (ItemT))
1237 and then Is_Type (Entity (Prefix (ItemT)))
1243 not Is_OK_Static_Expression (ItemS)
1245 not Is_OK_Static_Expression (ItemT);
1247 if Expr_Value (ItemS) /= Expr_Value (ItemT) then
1248 if Do_Access then -- needs run-time check.
1251 Apply_Compile_Time_Constraint_Error
1252 (N, "incorrect value for discriminant&?",
1253 CE_Discriminant_Check_Failed, Ent => Discr);
1260 Next_Discriminant (Discr);
1269 -- Here we need a discriminant check. First build the expression
1270 -- for the comparisons of the discriminants:
1272 -- (n.disc1 /= typ.disc1) or else
1273 -- (n.disc2 /= typ.disc2) or else
1275 -- (n.discn /= typ.discn)
1277 Cond := Build_Discriminant_Checks (N, T_Typ);
1279 -- If Lhs is set and is a parameter, then the condition is
1280 -- guarded by: lhs'constrained and then (condition built above)
1282 if Present (Param_Entity (Lhs)) then
1286 Make_Attribute_Reference (Loc,
1287 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1288 Attribute_Name => Name_Constrained),
1289 Right_Opnd => Cond);
1293 Cond := Guard_Access (Cond, Loc, N);
1297 Make_Raise_Constraint_Error (Loc,
1299 Reason => CE_Discriminant_Check_Failed));
1300 end Apply_Discriminant_Check;
1302 ------------------------
1303 -- Apply_Divide_Check --
1304 ------------------------
1306 procedure Apply_Divide_Check (N : Node_Id) is
1307 Loc : constant Source_Ptr := Sloc (N);
1308 Typ : constant Entity_Id := Etype (N);
1309 Left : constant Node_Id := Left_Opnd (N);
1310 Right : constant Node_Id := Right_Opnd (N);
1322 and then not Backend_Divide_Checks_On_Target
1323 and then Check_Needed (Right, Division_Check)
1325 Determine_Range (Right, ROK, Rlo, Rhi);
1327 -- See if division by zero possible, and if so generate test. This
1328 -- part of the test is not controlled by the -gnato switch.
1330 if Do_Division_Check (N) then
1331 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1333 Make_Raise_Constraint_Error (Loc,
1336 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1337 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1338 Reason => CE_Divide_By_Zero));
1342 -- Test for extremely annoying case of xxx'First divided by -1
1344 if Do_Overflow_Check (N) then
1345 if Nkind (N) = N_Op_Divide
1346 and then Is_Signed_Integer_Type (Typ)
1348 Determine_Range (Left, LOK, Llo, Lhi);
1349 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1351 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1353 ((not LOK) or else (Llo = LLB))
1356 Make_Raise_Constraint_Error (Loc,
1362 Duplicate_Subexpr_Move_Checks (Left),
1363 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1367 Duplicate_Subexpr (Right),
1369 Make_Integer_Literal (Loc, -1))),
1370 Reason => CE_Overflow_Check_Failed));
1375 end Apply_Divide_Check;
1377 ----------------------------------
1378 -- Apply_Float_Conversion_Check --
1379 ----------------------------------
1381 -- Let F and I be the source and target types of the conversion. The RM
1382 -- specifies that a floating-point value X is rounded to the nearest
1383 -- integer, with halfway cases being rounded away from zero. The rounded
1384 -- value of X is checked against I'Range.
1386 -- The catch in the above paragraph is that there is no good way to know
1387 -- whether the round-to-integer operation resulted in overflow. A remedy is
1388 -- to perform a range check in the floating-point domain instead, however:
1390 -- (1) The bounds may not be known at compile time
1391 -- (2) The check must take into account possible rounding.
1392 -- (3) The range of type I may not be exactly representable in F.
1393 -- (4) The end-points I'First - 0.5 and I'Last + 0.5 may or may
1394 -- not be in range, depending on the sign of I'First and I'Last.
1395 -- (5) X may be a NaN, which will fail any comparison
1397 -- The following steps take care of these issues converting X:
1399 -- (1) If either I'First or I'Last is not known at compile time, use
1400 -- I'Base instead of I in the next three steps and perform a
1401 -- regular range check against I'Range after conversion.
1402 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1403 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1404 -- F'Machine (T) and let Lo_OK be (Lo >= I'First). In other words,
1405 -- take one of the closest floating-point numbers to T, and see if
1406 -- it is in range or not.
1407 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1408 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1409 -- F'Rounding (T) and let Hi_OK be (Hi <= I'Last).
1410 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1411 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1413 procedure Apply_Float_Conversion_Check
1415 Target_Typ : Entity_Id)
1417 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1418 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1419 Loc : constant Source_Ptr := Sloc (Ck_Node);
1420 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1421 Target_Base : constant Entity_Id :=
1422 Implementation_Base_Type (Target_Typ);
1424 Max_Bound : constant Uint := UI_Expon
1425 (Machine_Radix (Expr_Type),
1426 Machine_Mantissa (Expr_Type) - 1) - 1;
1427 -- Largest bound, so bound plus or minus half is a machine number of F
1429 Ifirst, Ilast : Uint;
1430 -- Bounds of integer type
1433 -- Bounds to check in floating-point domain
1435 Lo_OK, Hi_OK : Boolean;
1436 -- True iff Lo resp. Hi belongs to I'Range
1438 Lo_Chk, Hi_Chk : Node_Id;
1439 -- Expressions that are False iff check fails
1441 Reason : RT_Exception_Code;
1444 if not Compile_Time_Known_Value (LB)
1445 or not Compile_Time_Known_Value (HB)
1448 -- First check that the value falls in the range of the base type,
1449 -- to prevent overflow during conversion and then perform a
1450 -- regular range check against the (dynamic) bounds.
1452 Par : constant Node_Id := Parent (Ck_Node);
1454 pragma Assert (Target_Base /= Target_Typ);
1455 pragma Assert (Nkind (Par) = N_Type_Conversion);
1457 Temp : constant Entity_Id :=
1458 Make_Defining_Identifier (Loc,
1459 Chars => New_Internal_Name ('T'));
1462 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
1463 Set_Etype (Temp, Target_Base);
1465 Insert_Action (Parent (Par),
1466 Make_Object_Declaration (Loc,
1467 Defining_Identifier => Temp,
1468 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
1469 Expression => New_Copy_Tree (Par)),
1470 Suppress => All_Checks);
1473 Make_Raise_Constraint_Error (Loc,
1476 Left_Opnd => New_Occurrence_Of (Temp, Loc),
1477 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
1478 Reason => CE_Range_Check_Failed));
1479 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
1485 -- Get the bounds of the target type
1487 Ifirst := Expr_Value (LB);
1488 Ilast := Expr_Value (HB);
1490 -- Check against lower bound
1492 if abs (Ifirst) < Max_Bound then
1493 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
1494 Lo_OK := (Ifirst > 0);
1496 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
1497 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
1502 -- Lo_Chk := (X >= Lo)
1504 Lo_Chk := Make_Op_Ge (Loc,
1505 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1506 Right_Opnd => Make_Real_Literal (Loc, Lo));
1509 -- Lo_Chk := (X > Lo)
1511 Lo_Chk := Make_Op_Gt (Loc,
1512 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1513 Right_Opnd => Make_Real_Literal (Loc, Lo));
1516 -- Check against higher bound
1518 if abs (Ilast) < Max_Bound then
1519 Hi := UR_From_Uint (Ilast) + Ureal_Half;
1520 Hi_OK := (Ilast < 0);
1522 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
1523 Hi_OK := (Hi <= UR_From_Uint (Ilast));
1528 -- Hi_Chk := (X <= Hi)
1530 Hi_Chk := Make_Op_Le (Loc,
1531 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1532 Right_Opnd => Make_Real_Literal (Loc, Hi));
1535 -- Hi_Chk := (X < Hi)
1537 Hi_Chk := Make_Op_Lt (Loc,
1538 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
1539 Right_Opnd => Make_Real_Literal (Loc, Hi));
1542 -- If the bounds of the target type are the same as those of the base
1543 -- type, the check is an overflow check as a range check is not
1544 -- performed in these cases.
1546 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
1547 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
1549 Reason := CE_Overflow_Check_Failed;
1551 Reason := CE_Range_Check_Failed;
1554 -- Raise CE if either conditions does not hold
1556 Insert_Action (Ck_Node,
1557 Make_Raise_Constraint_Error (Loc,
1558 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
1560 end Apply_Float_Conversion_Check;
1562 ------------------------
1563 -- Apply_Length_Check --
1564 ------------------------
1566 procedure Apply_Length_Check
1568 Target_Typ : Entity_Id;
1569 Source_Typ : Entity_Id := Empty)
1572 Apply_Selected_Length_Checks
1573 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1574 end Apply_Length_Check;
1576 -----------------------
1577 -- Apply_Range_Check --
1578 -----------------------
1580 procedure Apply_Range_Check
1582 Target_Typ : Entity_Id;
1583 Source_Typ : Entity_Id := Empty)
1586 Apply_Selected_Range_Checks
1587 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
1588 end Apply_Range_Check;
1590 ------------------------------
1591 -- Apply_Scalar_Range_Check --
1592 ------------------------------
1594 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
1595 -- off if it is already set on.
1597 procedure Apply_Scalar_Range_Check
1599 Target_Typ : Entity_Id;
1600 Source_Typ : Entity_Id := Empty;
1601 Fixed_Int : Boolean := False)
1603 Parnt : constant Node_Id := Parent (Expr);
1605 Arr : Node_Id := Empty; -- initialize to prevent warning
1606 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
1609 Is_Subscr_Ref : Boolean;
1610 -- Set true if Expr is a subscript
1612 Is_Unconstrained_Subscr_Ref : Boolean;
1613 -- Set true if Expr is a subscript of an unconstrained array. In this
1614 -- case we do not attempt to do an analysis of the value against the
1615 -- range of the subscript, since we don't know the actual subtype.
1618 -- Set to True if Expr should be regarded as a real value even though
1619 -- the type of Expr might be discrete.
1621 procedure Bad_Value;
1622 -- Procedure called if value is determined to be out of range
1628 procedure Bad_Value is
1630 Apply_Compile_Time_Constraint_Error
1631 (Expr, "value not in range of}?", CE_Range_Check_Failed,
1636 -- Start of processing for Apply_Scalar_Range_Check
1639 if Inside_A_Generic then
1642 -- Return if check obviously not needed. Note that we do not check for
1643 -- the expander being inactive, since this routine does not insert any
1644 -- code, but it does generate useful warnings sometimes, which we would
1645 -- like even if we are in semantics only mode.
1647 elsif Target_Typ = Any_Type
1648 or else not Is_Scalar_Type (Target_Typ)
1649 or else Raises_Constraint_Error (Expr)
1654 -- Now, see if checks are suppressed
1657 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
1659 if Is_Subscr_Ref then
1660 Arr := Prefix (Parnt);
1661 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
1664 if not Do_Range_Check (Expr) then
1666 -- Subscript reference. Check for Index_Checks suppressed
1668 if Is_Subscr_Ref then
1670 -- Check array type and its base type
1672 if Index_Checks_Suppressed (Arr_Typ)
1673 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
1677 -- Check array itself if it is an entity name
1679 elsif Is_Entity_Name (Arr)
1680 and then Index_Checks_Suppressed (Entity (Arr))
1684 -- Check expression itself if it is an entity name
1686 elsif Is_Entity_Name (Expr)
1687 and then Index_Checks_Suppressed (Entity (Expr))
1692 -- All other cases, check for Range_Checks suppressed
1695 -- Check target type and its base type
1697 if Range_Checks_Suppressed (Target_Typ)
1698 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
1702 -- Check expression itself if it is an entity name
1704 elsif Is_Entity_Name (Expr)
1705 and then Range_Checks_Suppressed (Entity (Expr))
1709 -- If Expr is part of an assignment statement, then check left
1710 -- side of assignment if it is an entity name.
1712 elsif Nkind (Parnt) = N_Assignment_Statement
1713 and then Is_Entity_Name (Name (Parnt))
1714 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
1721 -- Do not set range checks if they are killed
1723 if Nkind (Expr) = N_Unchecked_Type_Conversion
1724 and then Kill_Range_Check (Expr)
1729 -- Do not set range checks for any values from System.Scalar_Values
1730 -- since the whole idea of such values is to avoid checking them!
1732 if Is_Entity_Name (Expr)
1733 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
1738 -- Now see if we need a check
1740 if No (Source_Typ) then
1741 S_Typ := Etype (Expr);
1743 S_Typ := Source_Typ;
1746 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
1750 Is_Unconstrained_Subscr_Ref :=
1751 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
1753 -- Always do a range check if the source type includes infinities and
1754 -- the target type does not include infinities. We do not do this if
1755 -- range checks are killed.
1757 if Is_Floating_Point_Type (S_Typ)
1758 and then Has_Infinities (S_Typ)
1759 and then not Has_Infinities (Target_Typ)
1761 Enable_Range_Check (Expr);
1764 -- Return if we know expression is definitely in the range of the target
1765 -- type as determined by Determine_Range. Right now we only do this for
1766 -- discrete types, and not fixed-point or floating-point types.
1768 -- The additional less-precise tests below catch these cases
1770 -- Note: skip this if we are given a source_typ, since the point of
1771 -- supplying a Source_Typ is to stop us looking at the expression.
1772 -- We could sharpen this test to be out parameters only ???
1774 if Is_Discrete_Type (Target_Typ)
1775 and then Is_Discrete_Type (Etype (Expr))
1776 and then not Is_Unconstrained_Subscr_Ref
1777 and then No (Source_Typ)
1780 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
1781 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
1786 if Compile_Time_Known_Value (Tlo)
1787 and then Compile_Time_Known_Value (Thi)
1790 Lov : constant Uint := Expr_Value (Tlo);
1791 Hiv : constant Uint := Expr_Value (Thi);
1794 -- If range is null, we for sure have a constraint error
1795 -- (we don't even need to look at the value involved,
1796 -- since all possible values will raise CE).
1803 -- Otherwise determine range of value
1805 Determine_Range (Expr, OK, Lo, Hi);
1809 -- If definitely in range, all OK
1811 if Lo >= Lov and then Hi <= Hiv then
1814 -- If definitely not in range, warn
1816 elsif Lov > Hi or else Hiv < Lo then
1820 -- Otherwise we don't know
1832 Is_Floating_Point_Type (S_Typ)
1833 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
1835 -- Check if we can determine at compile time whether Expr is in the
1836 -- range of the target type. Note that if S_Typ is within the bounds
1837 -- of Target_Typ then this must be the case. This check is meaningful
1838 -- only if this is not a conversion between integer and real types.
1840 if not Is_Unconstrained_Subscr_Ref
1842 Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
1844 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
1846 Is_In_Range (Expr, Target_Typ, Fixed_Int, Int_Real))
1850 elsif Is_Out_Of_Range (Expr, Target_Typ, Fixed_Int, Int_Real) then
1854 -- In the floating-point case, we only do range checks if the type is
1855 -- constrained. We definitely do NOT want range checks for unconstrained
1856 -- types, since we want to have infinities
1858 elsif Is_Floating_Point_Type (S_Typ) then
1859 if Is_Constrained (S_Typ) then
1860 Enable_Range_Check (Expr);
1863 -- For all other cases we enable a range check unconditionally
1866 Enable_Range_Check (Expr);
1869 end Apply_Scalar_Range_Check;
1871 ----------------------------------
1872 -- Apply_Selected_Length_Checks --
1873 ----------------------------------
1875 procedure Apply_Selected_Length_Checks
1877 Target_Typ : Entity_Id;
1878 Source_Typ : Entity_Id;
1879 Do_Static : Boolean)
1882 R_Result : Check_Result;
1885 Loc : constant Source_Ptr := Sloc (Ck_Node);
1886 Checks_On : constant Boolean :=
1887 (not Index_Checks_Suppressed (Target_Typ))
1889 (not Length_Checks_Suppressed (Target_Typ));
1892 if not Expander_Active then
1897 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
1899 for J in 1 .. 2 loop
1900 R_Cno := R_Result (J);
1901 exit when No (R_Cno);
1903 -- A length check may mention an Itype which is attached to a
1904 -- subsequent node. At the top level in a package this can cause
1905 -- an order-of-elaboration problem, so we make sure that the itype
1906 -- is referenced now.
1908 if Ekind (Current_Scope) = E_Package
1909 and then Is_Compilation_Unit (Current_Scope)
1911 Ensure_Defined (Target_Typ, Ck_Node);
1913 if Present (Source_Typ) then
1914 Ensure_Defined (Source_Typ, Ck_Node);
1916 elsif Is_Itype (Etype (Ck_Node)) then
1917 Ensure_Defined (Etype (Ck_Node), Ck_Node);
1921 -- If the item is a conditional raise of constraint error, then have
1922 -- a look at what check is being performed and ???
1924 if Nkind (R_Cno) = N_Raise_Constraint_Error
1925 and then Present (Condition (R_Cno))
1927 Cond := Condition (R_Cno);
1929 -- Case where node does not now have a dynamic check
1931 if not Has_Dynamic_Length_Check (Ck_Node) then
1933 -- If checks are on, just insert the check
1936 Insert_Action (Ck_Node, R_Cno);
1938 if not Do_Static then
1939 Set_Has_Dynamic_Length_Check (Ck_Node);
1942 -- If checks are off, then analyze the length check after
1943 -- temporarily attaching it to the tree in case the relevant
1944 -- condition can be evaluted at compile time. We still want a
1945 -- compile time warning in this case.
1948 Set_Parent (R_Cno, Ck_Node);
1953 -- Output a warning if the condition is known to be True
1955 if Is_Entity_Name (Cond)
1956 and then Entity (Cond) = Standard_True
1958 Apply_Compile_Time_Constraint_Error
1959 (Ck_Node, "wrong length for array of}?",
1960 CE_Length_Check_Failed,
1964 -- If we were only doing a static check, or if checks are not
1965 -- on, then we want to delete the check, since it is not needed.
1966 -- We do this by replacing the if statement by a null statement
1968 elsif Do_Static or else not Checks_On then
1969 Remove_Warning_Messages (R_Cno);
1970 Rewrite (R_Cno, Make_Null_Statement (Loc));
1974 Install_Static_Check (R_Cno, Loc);
1977 end Apply_Selected_Length_Checks;
1979 ---------------------------------
1980 -- Apply_Selected_Range_Checks --
1981 ---------------------------------
1983 procedure Apply_Selected_Range_Checks
1985 Target_Typ : Entity_Id;
1986 Source_Typ : Entity_Id;
1987 Do_Static : Boolean)
1990 R_Result : Check_Result;
1993 Loc : constant Source_Ptr := Sloc (Ck_Node);
1994 Checks_On : constant Boolean :=
1995 (not Index_Checks_Suppressed (Target_Typ))
1997 (not Range_Checks_Suppressed (Target_Typ));
2000 if not Expander_Active or else not Checks_On then
2005 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
2007 for J in 1 .. 2 loop
2009 R_Cno := R_Result (J);
2010 exit when No (R_Cno);
2012 -- If the item is a conditional raise of constraint error, then have
2013 -- a look at what check is being performed and ???
2015 if Nkind (R_Cno) = N_Raise_Constraint_Error
2016 and then Present (Condition (R_Cno))
2018 Cond := Condition (R_Cno);
2020 if not Has_Dynamic_Range_Check (Ck_Node) then
2021 Insert_Action (Ck_Node, R_Cno);
2023 if not Do_Static then
2024 Set_Has_Dynamic_Range_Check (Ck_Node);
2028 -- Output a warning if the condition is known to be True
2030 if Is_Entity_Name (Cond)
2031 and then Entity (Cond) = Standard_True
2033 -- Since an N_Range is technically not an expression, we have
2034 -- to set one of the bounds to C_E and then just flag the
2035 -- N_Range. The warning message will point to the lower bound
2036 -- and complain about a range, which seems OK.
2038 if Nkind (Ck_Node) = N_Range then
2039 Apply_Compile_Time_Constraint_Error
2040 (Low_Bound (Ck_Node), "static range out of bounds of}?",
2041 CE_Range_Check_Failed,
2045 Set_Raises_Constraint_Error (Ck_Node);
2048 Apply_Compile_Time_Constraint_Error
2049 (Ck_Node, "static value out of range of}?",
2050 CE_Range_Check_Failed,
2055 -- If we were only doing a static check, or if checks are not
2056 -- on, then we want to delete the check, since it is not needed.
2057 -- We do this by replacing the if statement by a null statement
2059 elsif Do_Static or else not Checks_On then
2060 Remove_Warning_Messages (R_Cno);
2061 Rewrite (R_Cno, Make_Null_Statement (Loc));
2065 Install_Static_Check (R_Cno, Loc);
2068 end Apply_Selected_Range_Checks;
2070 -------------------------------
2071 -- Apply_Static_Length_Check --
2072 -------------------------------
2074 procedure Apply_Static_Length_Check
2076 Target_Typ : Entity_Id;
2077 Source_Typ : Entity_Id := Empty)
2080 Apply_Selected_Length_Checks
2081 (Expr, Target_Typ, Source_Typ, Do_Static => True);
2082 end Apply_Static_Length_Check;
2084 -------------------------------------
2085 -- Apply_Subscript_Validity_Checks --
2086 -------------------------------------
2088 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
2092 pragma Assert (Nkind (Expr) = N_Indexed_Component);
2094 -- Loop through subscripts
2096 Sub := First (Expressions (Expr));
2097 while Present (Sub) loop
2099 -- Check one subscript. Note that we do not worry about enumeration
2100 -- type with holes, since we will convert the value to a Pos value
2101 -- for the subscript, and that convert will do the necessary validity
2104 Ensure_Valid (Sub, Holes_OK => True);
2106 -- Move to next subscript
2110 end Apply_Subscript_Validity_Checks;
2112 ----------------------------------
2113 -- Apply_Type_Conversion_Checks --
2114 ----------------------------------
2116 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
2117 Target_Type : constant Entity_Id := Etype (N);
2118 Target_Base : constant Entity_Id := Base_Type (Target_Type);
2119 Expr : constant Node_Id := Expression (N);
2120 Expr_Type : constant Entity_Id := Etype (Expr);
2123 if Inside_A_Generic then
2126 -- Skip these checks if serious errors detected, there are some nasty
2127 -- situations of incomplete trees that blow things up.
2129 elsif Serious_Errors_Detected > 0 then
2132 -- Scalar type conversions of the form Target_Type (Expr) require a
2133 -- range check if we cannot be sure that Expr is in the base type of
2134 -- Target_Typ and also that Expr is in the range of Target_Typ. These
2135 -- are not quite the same condition from an implementation point of
2136 -- view, but clearly the second includes the first.
2138 elsif Is_Scalar_Type (Target_Type) then
2140 Conv_OK : constant Boolean := Conversion_OK (N);
2141 -- If the Conversion_OK flag on the type conversion is set and no
2142 -- floating point type is involved in the type conversion then
2143 -- fixed point values must be read as integral values.
2145 Float_To_Int : constant Boolean :=
2146 Is_Floating_Point_Type (Expr_Type)
2147 and then Is_Integer_Type (Target_Type);
2150 if not Overflow_Checks_Suppressed (Target_Base)
2151 and then not In_Subrange_Of (Expr_Type, Target_Base, Conv_OK)
2152 and then not Float_To_Int
2154 Activate_Overflow_Check (N);
2157 if not Range_Checks_Suppressed (Target_Type)
2158 and then not Range_Checks_Suppressed (Expr_Type)
2160 if Float_To_Int then
2161 Apply_Float_Conversion_Check (Expr, Target_Type);
2163 Apply_Scalar_Range_Check
2164 (Expr, Target_Type, Fixed_Int => Conv_OK);
2169 elsif Comes_From_Source (N)
2170 and then Is_Record_Type (Target_Type)
2171 and then Is_Derived_Type (Target_Type)
2172 and then not Is_Tagged_Type (Target_Type)
2173 and then not Is_Constrained (Target_Type)
2174 and then Present (Stored_Constraint (Target_Type))
2176 -- An unconstrained derived type may have inherited discriminant
2177 -- Build an actual discriminant constraint list using the stored
2178 -- constraint, to verify that the expression of the parent type
2179 -- satisfies the constraints imposed by the (unconstrained!)
2180 -- derived type. This applies to value conversions, not to view
2181 -- conversions of tagged types.
2184 Loc : constant Source_Ptr := Sloc (N);
2186 Constraint : Elmt_Id;
2187 Discr_Value : Node_Id;
2190 New_Constraints : constant Elist_Id := New_Elmt_List;
2191 Old_Constraints : constant Elist_Id :=
2192 Discriminant_Constraint (Expr_Type);
2195 Constraint := First_Elmt (Stored_Constraint (Target_Type));
2196 while Present (Constraint) loop
2197 Discr_Value := Node (Constraint);
2199 if Is_Entity_Name (Discr_Value)
2200 and then Ekind (Entity (Discr_Value)) = E_Discriminant
2202 Discr := Corresponding_Discriminant (Entity (Discr_Value));
2205 and then Scope (Discr) = Base_Type (Expr_Type)
2207 -- Parent is constrained by new discriminant. Obtain
2208 -- Value of original discriminant in expression. If the
2209 -- new discriminant has been used to constrain more than
2210 -- one of the stored discriminants, this will provide the
2211 -- required consistency check.
2214 Make_Selected_Component (Loc,
2216 Duplicate_Subexpr_No_Checks
2217 (Expr, Name_Req => True),
2219 Make_Identifier (Loc, Chars (Discr))),
2223 -- Discriminant of more remote ancestor ???
2228 -- Derived type definition has an explicit value for this
2229 -- stored discriminant.
2233 (Duplicate_Subexpr_No_Checks (Discr_Value),
2237 Next_Elmt (Constraint);
2240 -- Use the unconstrained expression type to retrieve the
2241 -- discriminants of the parent, and apply momentarily the
2242 -- discriminant constraint synthesized above.
2244 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
2245 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
2246 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
2249 Make_Raise_Constraint_Error (Loc,
2251 Reason => CE_Discriminant_Check_Failed));
2254 -- For arrays, conversions are applied during expansion, to take into
2255 -- accounts changes of representation. The checks become range checks on
2256 -- the base type or length checks on the subtype, depending on whether
2257 -- the target type is unconstrained or constrained.
2262 end Apply_Type_Conversion_Checks;
2264 ----------------------------------------------
2265 -- Apply_Universal_Integer_Attribute_Checks --
2266 ----------------------------------------------
2268 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
2269 Loc : constant Source_Ptr := Sloc (N);
2270 Typ : constant Entity_Id := Etype (N);
2273 if Inside_A_Generic then
2276 -- Nothing to do if checks are suppressed
2278 elsif Range_Checks_Suppressed (Typ)
2279 and then Overflow_Checks_Suppressed (Typ)
2283 -- Nothing to do if the attribute does not come from source. The
2284 -- internal attributes we generate of this type do not need checks,
2285 -- and furthermore the attempt to check them causes some circular
2286 -- elaboration orders when dealing with packed types.
2288 elsif not Comes_From_Source (N) then
2291 -- If the prefix is a selected component that depends on a discriminant
2292 -- the check may improperly expose a discriminant instead of using
2293 -- the bounds of the object itself. Set the type of the attribute to
2294 -- the base type of the context, so that a check will be imposed when
2295 -- needed (e.g. if the node appears as an index).
2297 elsif Nkind (Prefix (N)) = N_Selected_Component
2298 and then Ekind (Typ) = E_Signed_Integer_Subtype
2299 and then Depends_On_Discriminant (Scalar_Range (Typ))
2301 Set_Etype (N, Base_Type (Typ));
2303 -- Otherwise, replace the attribute node with a type conversion node
2304 -- whose expression is the attribute, retyped to universal integer, and
2305 -- whose subtype mark is the target type. The call to analyze this
2306 -- conversion will set range and overflow checks as required for proper
2307 -- detection of an out of range value.
2310 Set_Etype (N, Universal_Integer);
2311 Set_Analyzed (N, True);
2314 Make_Type_Conversion (Loc,
2315 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
2316 Expression => Relocate_Node (N)));
2318 Analyze_And_Resolve (N, Typ);
2322 end Apply_Universal_Integer_Attribute_Checks;
2324 -------------------------------
2325 -- Build_Discriminant_Checks --
2326 -------------------------------
2328 function Build_Discriminant_Checks
2330 T_Typ : Entity_Id) return Node_Id
2332 Loc : constant Source_Ptr := Sloc (N);
2335 Disc_Ent : Entity_Id;
2339 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
2341 ----------------------------------
2342 -- Aggregate_Discriminant_Value --
2343 ----------------------------------
2345 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
2349 -- The aggregate has been normalized with named associations. We use
2350 -- the Chars field to locate the discriminant to take into account
2351 -- discriminants in derived types, which carry the same name as those
2354 Assoc := First (Component_Associations (N));
2355 while Present (Assoc) loop
2356 if Chars (First (Choices (Assoc))) = Chars (Disc) then
2357 return Expression (Assoc);
2363 -- Discriminant must have been found in the loop above
2365 raise Program_Error;
2366 end Aggregate_Discriminant_Val;
2368 -- Start of processing for Build_Discriminant_Checks
2371 -- Loop through discriminants evolving the condition
2374 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
2376 -- For a fully private type, use the discriminants of the parent type
2378 if Is_Private_Type (T_Typ)
2379 and then No (Full_View (T_Typ))
2381 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
2383 Disc_Ent := First_Discriminant (T_Typ);
2386 while Present (Disc) loop
2387 Dval := Node (Disc);
2389 if Nkind (Dval) = N_Identifier
2390 and then Ekind (Entity (Dval)) = E_Discriminant
2392 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
2394 Dval := Duplicate_Subexpr_No_Checks (Dval);
2397 -- If we have an Unchecked_Union node, we can infer the discriminants
2400 if Is_Unchecked_Union (Base_Type (T_Typ)) then
2402 Get_Discriminant_Value (
2403 First_Discriminant (T_Typ),
2405 Stored_Constraint (T_Typ)));
2407 elsif Nkind (N) = N_Aggregate then
2409 Duplicate_Subexpr_No_Checks
2410 (Aggregate_Discriminant_Val (Disc_Ent));
2414 Make_Selected_Component (Loc,
2416 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
2418 Make_Identifier (Loc, Chars (Disc_Ent)));
2420 Set_Is_In_Discriminant_Check (Dref);
2423 Evolve_Or_Else (Cond,
2426 Right_Opnd => Dval));
2429 Next_Discriminant (Disc_Ent);
2433 end Build_Discriminant_Checks;
2439 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
2447 -- Always check if not simple entity
2449 if Nkind (Nod) not in N_Has_Entity
2450 or else not Comes_From_Source (Nod)
2455 -- Look up tree for short circuit
2462 if K not in N_Subexpr then
2465 -- Or/Or Else case, left operand must be equality test
2467 elsif K = N_Op_Or or else K = N_Or_Else then
2468 exit when N = Right_Opnd (P)
2469 and then Nkind (Left_Opnd (P)) = N_Op_Eq;
2471 -- And/And then case, left operand must be inequality test
2473 elsif K = N_Op_And or else K = N_And_Then then
2474 exit when N = Right_Opnd (P)
2475 and then Nkind (Left_Opnd (P)) = N_Op_Ne;
2481 -- If we fall through the loop, then we have a conditional with an
2482 -- appropriate test as its left operand. So test further.
2486 if Nkind (L) = N_Op_Not then
2487 L := Right_Opnd (L);
2490 R := Right_Opnd (L);
2493 -- Left operand of test must match original variable
2495 if Nkind (L) not in N_Has_Entity
2496 or else Entity (L) /= Entity (Nod)
2501 -- Right operand of test mus be key value (zero or null)
2504 when Access_Check =>
2505 if Nkind (R) /= N_Null then
2509 when Division_Check =>
2510 if not Compile_Time_Known_Value (R)
2511 or else Expr_Value (R) /= Uint_0
2517 -- Here we have the optimizable case, warn if not short-circuited
2519 if K = N_Op_And or else K = N_Op_Or then
2521 when Access_Check =>
2523 ("Constraint_Error may be raised (access check)?",
2525 when Division_Check =>
2527 ("Constraint_Error may be raised (zero divide)?",
2531 if K = N_Op_And then
2532 Error_Msg_N ("use `AND THEN` instead of AND?", P);
2534 Error_Msg_N ("use `OR ELSE` instead of OR?", P);
2537 -- If not short-circuited, we need the ckeck
2541 -- If short-circuited, we can omit the check
2548 -----------------------------------
2549 -- Check_Valid_Lvalue_Subscripts --
2550 -----------------------------------
2552 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
2554 -- Skip this if range checks are suppressed
2556 if Range_Checks_Suppressed (Etype (Expr)) then
2559 -- Only do this check for expressions that come from source. We assume
2560 -- that expander generated assignments explicitly include any necessary
2561 -- checks. Note that this is not just an optimization, it avoids
2562 -- infinite recursions!
2564 elsif not Comes_From_Source (Expr) then
2567 -- For a selected component, check the prefix
2569 elsif Nkind (Expr) = N_Selected_Component then
2570 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2573 -- Case of indexed component
2575 elsif Nkind (Expr) = N_Indexed_Component then
2576 Apply_Subscript_Validity_Checks (Expr);
2578 -- Prefix may itself be or contain an indexed component, and these
2579 -- subscripts need checking as well.
2581 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
2583 end Check_Valid_Lvalue_Subscripts;
2585 ----------------------------------
2586 -- Null_Exclusion_Static_Checks --
2587 ----------------------------------
2589 procedure Null_Exclusion_Static_Checks (N : Node_Id) is
2590 Error_Node : Node_Id;
2592 Has_Null : constant Boolean := Has_Null_Exclusion (N);
2593 K : constant Node_Kind := Nkind (N);
2598 (K = N_Component_Declaration
2599 or else K = N_Discriminant_Specification
2600 or else K = N_Function_Specification
2601 or else K = N_Object_Declaration
2602 or else K = N_Parameter_Specification);
2604 if K = N_Function_Specification then
2605 Typ := Etype (Defining_Entity (N));
2607 Typ := Etype (Defining_Identifier (N));
2611 when N_Component_Declaration =>
2612 if Present (Access_Definition (Component_Definition (N))) then
2613 Error_Node := Component_Definition (N);
2615 Error_Node := Subtype_Indication (Component_Definition (N));
2618 when N_Discriminant_Specification =>
2619 Error_Node := Discriminant_Type (N);
2621 when N_Function_Specification =>
2622 Error_Node := Result_Definition (N);
2624 when N_Object_Declaration =>
2625 Error_Node := Object_Definition (N);
2627 when N_Parameter_Specification =>
2628 Error_Node := Parameter_Type (N);
2631 raise Program_Error;
2636 -- Enforce legality rule 3.10 (13): A null exclusion can only be
2637 -- applied to an access [sub]type.
2639 if not Is_Access_Type (Typ) then
2641 ("`NOT NULL` allowed only for an access type", Error_Node);
2643 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
2644 -- be applied to a [sub]type that does not exclude null already.
2646 elsif Can_Never_Be_Null (Typ)
2648 -- No need to check itypes that have a null exclusion because
2649 -- they are already examined at their point of creation.
2651 and then not Is_Itype (Typ)
2654 ("`NOT NULL` not allowed (& already excludes null)",
2659 -- Check that null-excluding objects are always initialized
2661 if K = N_Object_Declaration
2662 and then No (Expression (N))
2663 and then not No_Initialization (N)
2665 -- Add an expression that assigns null. This node is needed by
2666 -- Apply_Compile_Time_Constraint_Error, which will replace this with
2667 -- a Constraint_Error node.
2669 Set_Expression (N, Make_Null (Sloc (N)));
2670 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
2672 Apply_Compile_Time_Constraint_Error
2673 (N => Expression (N),
2674 Msg => "(Ada 2005) null-excluding objects must be initialized?",
2675 Reason => CE_Null_Not_Allowed);
2678 -- Check that a null-excluding component, formal or object is not
2679 -- being assigned a null value. Otherwise generate a warning message
2680 -- and replace Expression (N) by a N_Contraint_Error node.
2682 if K /= N_Function_Specification then
2683 Expr := Expression (N);
2686 and then Nkind (Expr) = N_Null
2689 when N_Component_Declaration |
2690 N_Discriminant_Specification =>
2691 Apply_Compile_Time_Constraint_Error
2693 Msg => "(Ada 2005) NULL not allowed " &
2694 "in null-excluding components?",
2695 Reason => CE_Null_Not_Allowed);
2697 when N_Object_Declaration =>
2698 Apply_Compile_Time_Constraint_Error
2700 Msg => "(Ada 2005) NULL not allowed " &
2701 "in null-excluding objects?",
2702 Reason => CE_Null_Not_Allowed);
2704 when N_Parameter_Specification =>
2705 Apply_Compile_Time_Constraint_Error
2707 Msg => "(Ada 2005) NULL not allowed " &
2708 "in null-excluding formals?",
2709 Reason => CE_Null_Not_Allowed);
2716 end Null_Exclusion_Static_Checks;
2718 ----------------------------------
2719 -- Conditional_Statements_Begin --
2720 ----------------------------------
2722 procedure Conditional_Statements_Begin is
2724 Saved_Checks_TOS := Saved_Checks_TOS + 1;
2726 -- If stack overflows, kill all checks, that way we know to simply reset
2727 -- the number of saved checks to zero on return. This should never occur
2730 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2733 -- In the normal case, we just make a new stack entry saving the current
2734 -- number of saved checks for a later restore.
2737 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
2739 if Debug_Flag_CC then
2740 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
2744 end Conditional_Statements_Begin;
2746 --------------------------------
2747 -- Conditional_Statements_End --
2748 --------------------------------
2750 procedure Conditional_Statements_End is
2752 pragma Assert (Saved_Checks_TOS > 0);
2754 -- If the saved checks stack overflowed, then we killed all checks, so
2755 -- setting the number of saved checks back to zero is correct. This
2756 -- should never occur in practice.
2758 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
2759 Num_Saved_Checks := 0;
2761 -- In the normal case, restore the number of saved checks from the top
2765 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
2766 if Debug_Flag_CC then
2767 w ("Conditional_Statements_End: Num_Saved_Checks = ",
2772 Saved_Checks_TOS := Saved_Checks_TOS - 1;
2773 end Conditional_Statements_End;
2775 ---------------------
2776 -- Determine_Range --
2777 ---------------------
2779 Cache_Size : constant := 2 ** 10;
2780 type Cache_Index is range 0 .. Cache_Size - 1;
2781 -- Determine size of below cache (power of 2 is more efficient!)
2783 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
2784 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
2785 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
2786 -- The above arrays are used to implement a small direct cache for
2787 -- Determine_Range calls. Because of the way Determine_Range recursively
2788 -- traces subexpressions, and because overflow checking calls the routine
2789 -- on the way up the tree, a quadratic behavior can otherwise be
2790 -- encountered in large expressions. The cache entry for node N is stored
2791 -- in the (N mod Cache_Size) entry, and can be validated by checking the
2792 -- actual node value stored there.
2794 procedure Determine_Range
2800 Typ : constant Entity_Id := Etype (N);
2804 -- Lo and Hi bounds of left operand
2808 -- Lo and Hi bounds of right (or only) operand
2811 -- Temp variable used to hold a bound node
2814 -- High bound of base type of expression
2818 -- Refined values for low and high bounds, after tightening
2821 -- Used in lower level calls to indicate if call succeeded
2823 Cindex : Cache_Index;
2824 -- Used to search cache
2826 function OK_Operands return Boolean;
2827 -- Used for binary operators. Determines the ranges of the left and
2828 -- right operands, and if they are both OK, returns True, and puts
2829 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left
2835 function OK_Operands return Boolean is
2837 Determine_Range (Left_Opnd (N), OK1, Lo_Left, Hi_Left);
2843 Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
2847 -- Start of processing for Determine_Range
2850 -- Prevent junk warnings by initializing range variables
2857 -- If the type is not discrete, or is undefined, then we can't do
2858 -- anything about determining the range.
2860 if No (Typ) or else not Is_Discrete_Type (Typ)
2861 or else Error_Posted (N)
2867 -- For all other cases, we can determine the range
2871 -- If value is compile time known, then the possible range is the one
2872 -- value that we know this expression definitely has!
2874 if Compile_Time_Known_Value (N) then
2875 Lo := Expr_Value (N);
2880 -- Return if already in the cache
2882 Cindex := Cache_Index (N mod Cache_Size);
2884 if Determine_Range_Cache_N (Cindex) = N then
2885 Lo := Determine_Range_Cache_Lo (Cindex);
2886 Hi := Determine_Range_Cache_Hi (Cindex);
2890 -- Otherwise, start by finding the bounds of the type of the expression,
2891 -- the value cannot be outside this range (if it is, then we have an
2892 -- overflow situation, which is a separate check, we are talking here
2893 -- only about the expression value).
2895 -- We use the actual bound unless it is dynamic, in which case use the
2896 -- corresponding base type bound if possible. If we can't get a bound
2897 -- then we figure we can't determine the range (a peculiar case, that
2898 -- perhaps cannot happen, but there is no point in bombing in this
2899 -- optimization circuit.
2901 -- First the low bound
2903 Bound := Type_Low_Bound (Typ);
2905 if Compile_Time_Known_Value (Bound) then
2906 Lo := Expr_Value (Bound);
2908 elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
2909 Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
2916 -- Now the high bound
2918 Bound := Type_High_Bound (Typ);
2920 -- We need the high bound of the base type later on, and this should
2921 -- always be compile time known. Again, it is not clear that this
2922 -- can ever be false, but no point in bombing.
2924 if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
2925 Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
2933 -- If we have a static subtype, then that may have a tighter bound so
2934 -- use the upper bound of the subtype instead in this case.
2936 if Compile_Time_Known_Value (Bound) then
2937 Hi := Expr_Value (Bound);
2940 -- We may be able to refine this value in certain situations. If any
2941 -- refinement is possible, then Lor and Hir are set to possibly tighter
2942 -- bounds, and OK1 is set to True.
2946 -- For unary plus, result is limited by range of operand
2949 Determine_Range (Right_Opnd (N), OK1, Lor, Hir);
2951 -- For unary minus, determine range of operand, and negate it
2954 Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
2961 -- For binary addition, get range of each operand and do the
2962 -- addition to get the result range.
2966 Lor := Lo_Left + Lo_Right;
2967 Hir := Hi_Left + Hi_Right;
2970 -- Division is tricky. The only case we consider is where the right
2971 -- operand is a positive constant, and in this case we simply divide
2972 -- the bounds of the left operand
2976 if Lo_Right = Hi_Right
2977 and then Lo_Right > 0
2979 Lor := Lo_Left / Lo_Right;
2980 Hir := Hi_Left / Lo_Right;
2987 -- For binary subtraction, get range of each operand and do the worst
2988 -- case subtraction to get the result range.
2990 when N_Op_Subtract =>
2992 Lor := Lo_Left - Hi_Right;
2993 Hir := Hi_Left - Lo_Right;
2996 -- For MOD, if right operand is a positive constant, then result must
2997 -- be in the allowable range of mod results.
3001 if Lo_Right = Hi_Right
3002 and then Lo_Right /= 0
3004 if Lo_Right > 0 then
3006 Hir := Lo_Right - 1;
3008 else -- Lo_Right < 0
3009 Lor := Lo_Right + 1;
3018 -- For REM, if right operand is a positive constant, then result must
3019 -- be in the allowable range of mod results.
3023 if Lo_Right = Hi_Right
3024 and then Lo_Right /= 0
3027 Dval : constant Uint := (abs Lo_Right) - 1;
3030 -- The sign of the result depends on the sign of the
3031 -- dividend (but not on the sign of the divisor, hence
3032 -- the abs operation above).
3052 -- Attribute reference cases
3054 when N_Attribute_Reference =>
3055 case Attribute_Name (N) is
3057 -- For Pos/Val attributes, we can refine the range using the
3058 -- possible range of values of the attribute expression
3060 when Name_Pos | Name_Val =>
3061 Determine_Range (First (Expressions (N)), OK1, Lor, Hir);
3063 -- For Length attribute, use the bounds of the corresponding
3064 -- index type to refine the range.
3068 Atyp : Entity_Id := Etype (Prefix (N));
3076 if Is_Access_Type (Atyp) then
3077 Atyp := Designated_Type (Atyp);
3080 -- For string literal, we know exact value
3082 if Ekind (Atyp) = E_String_Literal_Subtype then
3084 Lo := String_Literal_Length (Atyp);
3085 Hi := String_Literal_Length (Atyp);
3089 -- Otherwise check for expression given
3091 if No (Expressions (N)) then
3095 UI_To_Int (Expr_Value (First (Expressions (N))));
3098 Indx := First_Index (Atyp);
3099 for J in 2 .. Inum loop
3100 Indx := Next_Index (Indx);
3104 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU);
3108 (Type_High_Bound (Etype (Indx)), OK1, UL, UU);
3112 -- The maximum value for Length is the biggest
3113 -- possible gap between the values of the bounds.
3114 -- But of course, this value cannot be negative.
3116 Hir := UI_Max (Uint_0, UU - LL);
3118 -- For constrained arrays, the minimum value for
3119 -- Length is taken from the actual value of the
3120 -- bounds, since the index will be exactly of
3123 if Is_Constrained (Atyp) then
3124 Lor := UI_Max (Uint_0, UL - LU);
3126 -- For an unconstrained array, the minimum value
3127 -- for length is always zero.
3136 -- No special handling for other attributes
3137 -- Probably more opportunities exist here ???
3144 -- For type conversion from one discrete type to another, we can
3145 -- refine the range using the converted value.
3147 when N_Type_Conversion =>
3148 Determine_Range (Expression (N), OK1, Lor, Hir);
3150 -- Nothing special to do for all other expression kinds
3158 -- At this stage, if OK1 is true, then we know that the actual
3159 -- result of the computed expression is in the range Lor .. Hir.
3160 -- We can use this to restrict the possible range of results.
3164 -- If the refined value of the low bound is greater than the
3165 -- type high bound, then reset it to the more restrictive
3166 -- value. However, we do NOT do this for the case of a modular
3167 -- type where the possible upper bound on the value is above the
3168 -- base type high bound, because that means the result could wrap.
3171 and then not (Is_Modular_Integer_Type (Typ)
3172 and then Hir > Hbound)
3177 -- Similarly, if the refined value of the high bound is less
3178 -- than the value so far, then reset it to the more restrictive
3179 -- value. Again, we do not do this if the refined low bound is
3180 -- negative for a modular type, since this would wrap.
3183 and then not (Is_Modular_Integer_Type (Typ)
3184 and then Lor < Uint_0)
3190 -- Set cache entry for future call and we are all done
3192 Determine_Range_Cache_N (Cindex) := N;
3193 Determine_Range_Cache_Lo (Cindex) := Lo;
3194 Determine_Range_Cache_Hi (Cindex) := Hi;
3197 -- If any exception occurs, it means that we have some bug in the compiler
3198 -- possibly triggered by a previous error, or by some unforseen peculiar
3199 -- occurrence. However, this is only an optimization attempt, so there is
3200 -- really no point in crashing the compiler. Instead we just decide, too
3201 -- bad, we can't figure out a range in this case after all.
3206 -- Debug flag K disables this behavior (useful for debugging)
3208 if Debug_Flag_K then
3216 end Determine_Range;
3218 ------------------------------------
3219 -- Discriminant_Checks_Suppressed --
3220 ------------------------------------
3222 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
3225 if Is_Unchecked_Union (E) then
3227 elsif Checks_May_Be_Suppressed (E) then
3228 return Is_Check_Suppressed (E, Discriminant_Check);
3232 return Scope_Suppress (Discriminant_Check);
3233 end Discriminant_Checks_Suppressed;
3235 --------------------------------
3236 -- Division_Checks_Suppressed --
3237 --------------------------------
3239 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
3241 if Present (E) and then Checks_May_Be_Suppressed (E) then
3242 return Is_Check_Suppressed (E, Division_Check);
3244 return Scope_Suppress (Division_Check);
3246 end Division_Checks_Suppressed;
3248 -----------------------------------
3249 -- Elaboration_Checks_Suppressed --
3250 -----------------------------------
3252 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
3254 -- The complication in this routine is that if we are in the dynamic
3255 -- model of elaboration, we also check All_Checks, since All_Checks
3256 -- does not set Elaboration_Check explicitly.
3259 if Kill_Elaboration_Checks (E) then
3262 elsif Checks_May_Be_Suppressed (E) then
3263 if Is_Check_Suppressed (E, Elaboration_Check) then
3265 elsif Dynamic_Elaboration_Checks then
3266 return Is_Check_Suppressed (E, All_Checks);
3273 if Scope_Suppress (Elaboration_Check) then
3275 elsif Dynamic_Elaboration_Checks then
3276 return Scope_Suppress (All_Checks);
3280 end Elaboration_Checks_Suppressed;
3282 ---------------------------
3283 -- Enable_Overflow_Check --
3284 ---------------------------
3286 procedure Enable_Overflow_Check (N : Node_Id) is
3287 Typ : constant Entity_Id := Base_Type (Etype (N));
3296 if Debug_Flag_CC then
3297 w ("Enable_Overflow_Check for node ", Int (N));
3298 Write_Str (" Source location = ");
3303 -- Nothing to do if the range of the result is known OK. We skip this
3304 -- for conversions, since the caller already did the check, and in any
3305 -- case the condition for deleting the check for a type conversion is
3306 -- different in any case.
3308 if Nkind (N) /= N_Type_Conversion then
3309 Determine_Range (N, OK, Lo, Hi);
3311 -- Note in the test below that we assume that if a bound of the
3312 -- range is equal to that of the type. That's not quite accurate
3313 -- but we do this for the following reasons:
3315 -- a) The way that Determine_Range works, it will typically report
3316 -- the bounds of the value as being equal to the bounds of the
3317 -- type, because it either can't tell anything more precise, or
3318 -- does not think it is worth the effort to be more precise.
3320 -- b) It is very unusual to have a situation in which this would
3321 -- generate an unnecessary overflow check (an example would be
3322 -- a subtype with a range 0 .. Integer'Last - 1 to which the
3323 -- literal value one is added.
3325 -- c) The alternative is a lot of special casing in this routine
3326 -- which would partially duplicate Determine_Range processing.
3329 and then Lo > Expr_Value (Type_Low_Bound (Typ))
3330 and then Hi < Expr_Value (Type_High_Bound (Typ))
3332 if Debug_Flag_CC then
3333 w ("No overflow check required");
3340 -- If not in optimizing mode, set flag and we are done. We are also done
3341 -- (and just set the flag) if the type is not a discrete type, since it
3342 -- is not worth the effort to eliminate checks for other than discrete
3343 -- types. In addition, we take this same path if we have stored the
3344 -- maximum number of checks possible already (a very unlikely situation,
3345 -- but we do not want to blow up!)
3347 if Optimization_Level = 0
3348 or else not Is_Discrete_Type (Etype (N))
3349 or else Num_Saved_Checks = Saved_Checks'Last
3351 Activate_Overflow_Check (N);
3353 if Debug_Flag_CC then
3354 w ("Optimization off");
3360 -- Otherwise evaluate and check the expression
3365 Target_Type => Empty,
3371 if Debug_Flag_CC then
3372 w ("Called Find_Check");
3376 w (" Check_Num = ", Chk);
3377 w (" Ent = ", Int (Ent));
3378 Write_Str (" Ofs = ");
3383 -- If check is not of form to optimize, then set flag and we are done
3386 Activate_Overflow_Check (N);
3390 -- If check is already performed, then return without setting flag
3393 if Debug_Flag_CC then
3394 w ("Check suppressed!");
3400 -- Here we will make a new entry for the new check
3402 Activate_Overflow_Check (N);
3403 Num_Saved_Checks := Num_Saved_Checks + 1;
3404 Saved_Checks (Num_Saved_Checks) :=
3409 Target_Type => Empty);
3411 if Debug_Flag_CC then
3412 w ("Make new entry, check number = ", Num_Saved_Checks);
3413 w (" Entity = ", Int (Ent));
3414 Write_Str (" Offset = ");
3416 w (" Check_Type = O");
3417 w (" Target_Type = Empty");
3420 -- If we get an exception, then something went wrong, probably because of
3421 -- an error in the structure of the tree due to an incorrect program. Or it
3422 -- may be a bug in the optimization circuit. In either case the safest
3423 -- thing is simply to set the check flag unconditionally.
3427 Activate_Overflow_Check (N);
3429 if Debug_Flag_CC then
3430 w (" exception occurred, overflow flag set");
3434 end Enable_Overflow_Check;
3436 ------------------------
3437 -- Enable_Range_Check --
3438 ------------------------
3440 procedure Enable_Range_Check (N : Node_Id) is
3449 -- Return if unchecked type conversion with range check killed. In this
3450 -- case we never set the flag (that's what Kill_Range_Check is about!)
3452 if Nkind (N) = N_Unchecked_Type_Conversion
3453 and then Kill_Range_Check (N)
3458 -- Check for various cases where we should suppress the range check
3460 -- No check if range checks suppressed for type of node
3462 if Present (Etype (N))
3463 and then Range_Checks_Suppressed (Etype (N))
3467 -- No check if node is an entity name, and range checks are suppressed
3468 -- for this entity, or for the type of this entity.
3470 elsif Is_Entity_Name (N)
3471 and then (Range_Checks_Suppressed (Entity (N))
3472 or else Range_Checks_Suppressed (Etype (Entity (N))))
3476 -- No checks if index of array, and index checks are suppressed for
3477 -- the array object or the type of the array.
3479 elsif Nkind (Parent (N)) = N_Indexed_Component then
3481 Pref : constant Node_Id := Prefix (Parent (N));
3483 if Is_Entity_Name (Pref)
3484 and then Index_Checks_Suppressed (Entity (Pref))
3487 elsif Index_Checks_Suppressed (Etype (Pref)) then
3493 -- Debug trace output
3495 if Debug_Flag_CC then
3496 w ("Enable_Range_Check for node ", Int (N));
3497 Write_Str (" Source location = ");
3502 -- If not in optimizing mode, set flag and we are done. We are also done
3503 -- (and just set the flag) if the type is not a discrete type, since it
3504 -- is not worth the effort to eliminate checks for other than discrete
3505 -- types. In addition, we take this same path if we have stored the
3506 -- maximum number of checks possible already (a very unlikely situation,
3507 -- but we do not want to blow up!)
3509 if Optimization_Level = 0
3510 or else No (Etype (N))
3511 or else not Is_Discrete_Type (Etype (N))
3512 or else Num_Saved_Checks = Saved_Checks'Last
3514 Activate_Range_Check (N);
3516 if Debug_Flag_CC then
3517 w ("Optimization off");
3523 -- Otherwise find out the target type
3527 -- For assignment, use left side subtype
3529 if Nkind (P) = N_Assignment_Statement
3530 and then Expression (P) = N
3532 Ttyp := Etype (Name (P));
3534 -- For indexed component, use subscript subtype
3536 elsif Nkind (P) = N_Indexed_Component then
3543 Atyp := Etype (Prefix (P));
3545 if Is_Access_Type (Atyp) then
3546 Atyp := Designated_Type (Atyp);
3548 -- If the prefix is an access to an unconstrained array,
3549 -- perform check unconditionally: it depends on the bounds of
3550 -- an object and we cannot currently recognize whether the test
3551 -- may be redundant.
3553 if not Is_Constrained (Atyp) then
3554 Activate_Range_Check (N);
3558 -- Ditto if the prefix is an explicit dereference whose designated
3559 -- type is unconstrained.
3561 elsif Nkind (Prefix (P)) = N_Explicit_Dereference
3562 and then not Is_Constrained (Atyp)
3564 Activate_Range_Check (N);
3568 Indx := First_Index (Atyp);
3569 Subs := First (Expressions (P));
3572 Ttyp := Etype (Indx);
3581 -- For now, ignore all other cases, they are not so interesting
3584 if Debug_Flag_CC then
3585 w (" target type not found, flag set");
3588 Activate_Range_Check (N);
3592 -- Evaluate and check the expression
3597 Target_Type => Ttyp,
3603 if Debug_Flag_CC then
3604 w ("Called Find_Check");
3605 w ("Target_Typ = ", Int (Ttyp));
3609 w (" Check_Num = ", Chk);
3610 w (" Ent = ", Int (Ent));
3611 Write_Str (" Ofs = ");
3616 -- If check is not of form to optimize, then set flag and we are done
3619 if Debug_Flag_CC then
3620 w (" expression not of optimizable type, flag set");
3623 Activate_Range_Check (N);
3627 -- If check is already performed, then return without setting flag
3630 if Debug_Flag_CC then
3631 w ("Check suppressed!");
3637 -- Here we will make a new entry for the new check
3639 Activate_Range_Check (N);
3640 Num_Saved_Checks := Num_Saved_Checks + 1;
3641 Saved_Checks (Num_Saved_Checks) :=
3646 Target_Type => Ttyp);
3648 if Debug_Flag_CC then
3649 w ("Make new entry, check number = ", Num_Saved_Checks);
3650 w (" Entity = ", Int (Ent));
3651 Write_Str (" Offset = ");
3653 w (" Check_Type = R");
3654 w (" Target_Type = ", Int (Ttyp));
3655 pg (Union_Id (Ttyp));
3658 -- If we get an exception, then something went wrong, probably because of
3659 -- an error in the structure of the tree due to an incorrect program. Or
3660 -- it may be a bug in the optimization circuit. In either case the safest
3661 -- thing is simply to set the check flag unconditionally.
3665 Activate_Range_Check (N);
3667 if Debug_Flag_CC then
3668 w (" exception occurred, range flag set");
3672 end Enable_Range_Check;
3678 procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
3679 Typ : constant Entity_Id := Etype (Expr);
3682 -- Ignore call if we are not doing any validity checking
3684 if not Validity_Checks_On then
3687 -- Ignore call if range or validity checks suppressed on entity or type
3689 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
3692 -- No check required if expression is from the expander, we assume the
3693 -- expander will generate whatever checks are needed. Note that this is
3694 -- not just an optimization, it avoids infinite recursions!
3696 -- Unchecked conversions must be checked, unless they are initialized
3697 -- scalar values, as in a component assignment in an init proc.
3699 -- In addition, we force a check if Force_Validity_Checks is set
3701 elsif not Comes_From_Source (Expr)
3702 and then not Force_Validity_Checks
3703 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
3704 or else Kill_Range_Check (Expr))
3708 -- No check required if expression is known to have valid value
3710 elsif Expr_Known_Valid (Expr) then
3713 -- Ignore case of enumeration with holes where the flag is set not to
3714 -- worry about holes, since no special validity check is needed
3716 elsif Is_Enumeration_Type (Typ)
3717 and then Has_Non_Standard_Rep (Typ)
3722 -- No check required on the left-hand side of an assignment
3724 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
3725 and then Expr = Name (Parent (Expr))
3729 -- No check on a univeral real constant. The context will eventually
3730 -- convert it to a machine number for some target type, or report an
3733 elsif Nkind (Expr) = N_Real_Literal
3734 and then Etype (Expr) = Universal_Real
3738 -- If the expression denotes a component of a packed boolean arrray,
3739 -- no possible check applies. We ignore the old ACATS chestnuts that
3740 -- involve Boolean range True..True.
3742 -- Note: validity checks are generated for expressions that yield a
3743 -- scalar type, when it is possible to create a value that is outside of
3744 -- the type. If this is a one-bit boolean no such value exists. This is
3745 -- an optimization, and it also prevents compiler blowing up during the
3746 -- elaboration of improperly expanded packed array references.
3748 elsif Nkind (Expr) = N_Indexed_Component
3749 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
3750 and then Root_Type (Etype (Expr)) = Standard_Boolean
3754 -- An annoying special case. If this is an out parameter of a scalar
3755 -- type, then the value is not going to be accessed, therefore it is
3756 -- inappropriate to do any validity check at the call site.
3759 -- Only need to worry about scalar types
3761 if Is_Scalar_Type (Typ) then
3771 -- Find actual argument (which may be a parameter association)
3772 -- and the parent of the actual argument (the call statement)
3777 if Nkind (P) = N_Parameter_Association then
3782 -- Only need to worry if we are argument of a procedure call
3783 -- since functions don't have out parameters. If this is an
3784 -- indirect or dispatching call, get signature from the
3787 if Nkind (P) = N_Procedure_Call_Statement then
3788 L := Parameter_Associations (P);
3790 if Is_Entity_Name (Name (P)) then
3791 E := Entity (Name (P));
3793 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
3794 E := Etype (Name (P));
3797 -- Only need to worry if there are indeed actuals, and if
3798 -- this could be a procedure call, otherwise we cannot get a
3799 -- match (either we are not an argument, or the mode of the
3800 -- formal is not OUT). This test also filters out the
3803 if Is_Non_Empty_List (L)
3804 and then Is_Subprogram (E)
3806 -- This is the loop through parameters, looking for an
3807 -- OUT parameter for which we are the argument.
3809 F := First_Formal (E);
3811 while Present (F) loop
3812 if Ekind (F) = E_Out_Parameter and then A = N then
3825 -- If we fall through, a validity check is required
3827 Insert_Valid_Check (Expr);
3830 ----------------------
3831 -- Expr_Known_Valid --
3832 ----------------------
3834 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
3835 Typ : constant Entity_Id := Etype (Expr);
3838 -- Non-scalar types are always considered valid, since they never give
3839 -- rise to the issues of erroneous or bounded error behavior that are
3840 -- the concern. In formal reference manual terms the notion of validity
3841 -- only applies to scalar types. Note that even when packed arrays are
3842 -- represented using modular types, they are still arrays semantically,
3843 -- so they are also always valid (in particular, the unused bits can be
3844 -- random rubbish without affecting the validity of the array value).
3846 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
3849 -- If no validity checking, then everything is considered valid
3851 elsif not Validity_Checks_On then
3854 -- Floating-point types are considered valid unless floating-point
3855 -- validity checks have been specifically turned on.
3857 elsif Is_Floating_Point_Type (Typ)
3858 and then not Validity_Check_Floating_Point
3862 -- If the expression is the value of an object that is known to be
3863 -- valid, then clearly the expression value itself is valid.
3865 elsif Is_Entity_Name (Expr)
3866 and then Is_Known_Valid (Entity (Expr))
3870 -- References to discriminants are always considered valid. The value
3871 -- of a discriminant gets checked when the object is built. Within the
3872 -- record, we consider it valid, and it is important to do so, since
3873 -- otherwise we can try to generate bogus validity checks which
3874 -- reference discriminants out of scope. Discriminants of concurrent
3875 -- types are excluded for the same reason.
3877 elsif Is_Entity_Name (Expr)
3878 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
3882 -- If the type is one for which all values are known valid, then we are
3883 -- sure that the value is valid except in the slightly odd case where
3884 -- the expression is a reference to a variable whose size has been
3885 -- explicitly set to a value greater than the object size.
3887 elsif Is_Known_Valid (Typ) then
3888 if Is_Entity_Name (Expr)
3889 and then Ekind (Entity (Expr)) = E_Variable
3890 and then Esize (Entity (Expr)) > Esize (Typ)
3897 -- Integer and character literals always have valid values, where
3898 -- appropriate these will be range checked in any case.
3900 elsif Nkind (Expr) = N_Integer_Literal
3902 Nkind (Expr) = N_Character_Literal
3906 -- If we have a type conversion or a qualification of a known valid
3907 -- value, then the result will always be valid.
3909 elsif Nkind (Expr) = N_Type_Conversion
3911 Nkind (Expr) = N_Qualified_Expression
3913 return Expr_Known_Valid (Expression (Expr));
3915 -- The result of any operator is always considered valid, since we
3916 -- assume the necessary checks are done by the operator. For operators
3917 -- on floating-point operations, we must also check when the operation
3918 -- is the right-hand side of an assignment, or is an actual in a call.
3920 elsif Nkind (Expr) in N_Op then
3921 if Is_Floating_Point_Type (Typ)
3922 and then Validity_Check_Floating_Point
3924 (Nkind (Parent (Expr)) = N_Assignment_Statement
3925 or else Nkind (Parent (Expr)) = N_Function_Call
3926 or else Nkind (Parent (Expr)) = N_Parameter_Association)
3933 -- The result of a membership test is always valid, since it is true or
3934 -- false, there are no other possibilities.
3936 elsif Nkind (Expr) in N_Membership_Test then
3939 -- For all other cases, we do not know the expression is valid
3944 end Expr_Known_Valid;
3950 procedure Find_Check
3952 Check_Type : Character;
3953 Target_Type : Entity_Id;
3954 Entry_OK : out Boolean;
3955 Check_Num : out Nat;
3956 Ent : out Entity_Id;
3959 function Within_Range_Of
3960 (Target_Type : Entity_Id;
3961 Check_Type : Entity_Id) return Boolean;
3962 -- Given a requirement for checking a range against Target_Type, and
3963 -- and a range Check_Type against which a check has already been made,
3964 -- determines if the check against check type is sufficient to ensure
3965 -- that no check against Target_Type is required.
3967 ---------------------
3968 -- Within_Range_Of --
3969 ---------------------
3971 function Within_Range_Of
3972 (Target_Type : Entity_Id;
3973 Check_Type : Entity_Id) return Boolean
3976 if Target_Type = Check_Type then
3981 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
3982 Thi : constant Node_Id := Type_High_Bound (Target_Type);
3983 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
3984 Chi : constant Node_Id := Type_High_Bound (Check_Type);
3988 or else (Compile_Time_Known_Value (Tlo)
3990 Compile_Time_Known_Value (Clo)
3992 Expr_Value (Clo) >= Expr_Value (Tlo)))
3995 or else (Compile_Time_Known_Value (Thi)
3997 Compile_Time_Known_Value (Chi)
3999 Expr_Value (Chi) <= Expr_Value (Clo)))
4007 end Within_Range_Of;
4009 -- Start of processing for Find_Check
4012 -- Establish default, to avoid warnings from GCC
4016 -- Case of expression is simple entity reference
4018 if Is_Entity_Name (Expr) then
4019 Ent := Entity (Expr);
4022 -- Case of expression is entity + known constant
4024 elsif Nkind (Expr) = N_Op_Add
4025 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4026 and then Is_Entity_Name (Left_Opnd (Expr))
4028 Ent := Entity (Left_Opnd (Expr));
4029 Ofs := Expr_Value (Right_Opnd (Expr));
4031 -- Case of expression is entity - known constant
4033 elsif Nkind (Expr) = N_Op_Subtract
4034 and then Compile_Time_Known_Value (Right_Opnd (Expr))
4035 and then Is_Entity_Name (Left_Opnd (Expr))
4037 Ent := Entity (Left_Opnd (Expr));
4038 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
4040 -- Any other expression is not of the right form
4049 -- Come here with expression of appropriate form, check if entity is an
4050 -- appropriate one for our purposes.
4052 if (Ekind (Ent) = E_Variable
4054 Ekind (Ent) = E_Constant
4056 Ekind (Ent) = E_Loop_Parameter
4058 Ekind (Ent) = E_In_Parameter)
4059 and then not Is_Library_Level_Entity (Ent)
4067 -- See if there is matching check already
4069 for J in reverse 1 .. Num_Saved_Checks loop
4071 SC : Saved_Check renames Saved_Checks (J);
4074 if SC.Killed = False
4075 and then SC.Entity = Ent
4076 and then SC.Offset = Ofs
4077 and then SC.Check_Type = Check_Type
4078 and then Within_Range_Of (Target_Type, SC.Target_Type)
4086 -- If we fall through entry was not found
4092 ---------------------------------
4093 -- Generate_Discriminant_Check --
4094 ---------------------------------
4096 -- Note: the code for this procedure is derived from the
4097 -- Emit_Discriminant_Check Routine in trans.c.
4099 procedure Generate_Discriminant_Check (N : Node_Id) is
4100 Loc : constant Source_Ptr := Sloc (N);
4101 Pref : constant Node_Id := Prefix (N);
4102 Sel : constant Node_Id := Selector_Name (N);
4104 Orig_Comp : constant Entity_Id :=
4105 Original_Record_Component (Entity (Sel));
4106 -- The original component to be checked
4108 Discr_Fct : constant Entity_Id :=
4109 Discriminant_Checking_Func (Orig_Comp);
4110 -- The discriminant checking function
4113 -- One discriminant to be checked in the type
4115 Real_Discr : Entity_Id;
4116 -- Actual discriminant in the call
4118 Pref_Type : Entity_Id;
4119 -- Type of relevant prefix (ignoring private/access stuff)
4122 -- List of arguments for function call
4125 -- Keep track of the formal corresponding to the actual we build for
4126 -- each discriminant, in order to be able to perform the necessary type
4130 -- Selected component reference for checking function argument
4133 Pref_Type := Etype (Pref);
4135 -- Force evaluation of the prefix, so that it does not get evaluated
4136 -- twice (once for the check, once for the actual reference). Such a
4137 -- double evaluation is always a potential source of inefficiency,
4138 -- and is functionally incorrect in the volatile case, or when the
4139 -- prefix may have side-effects. An entity or a component of an
4140 -- entity requires no evaluation.
4142 if Is_Entity_Name (Pref) then
4143 if Treat_As_Volatile (Entity (Pref)) then
4144 Force_Evaluation (Pref, Name_Req => True);
4147 elsif Treat_As_Volatile (Etype (Pref)) then
4148 Force_Evaluation (Pref, Name_Req => True);
4150 elsif Nkind (Pref) = N_Selected_Component
4151 and then Is_Entity_Name (Prefix (Pref))
4156 Force_Evaluation (Pref, Name_Req => True);
4159 -- For a tagged type, use the scope of the original component to
4160 -- obtain the type, because ???
4162 if Is_Tagged_Type (Scope (Orig_Comp)) then
4163 Pref_Type := Scope (Orig_Comp);
4165 -- For an untagged derived type, use the discriminants of the parent
4166 -- which have been renamed in the derivation, possibly by a one-to-many
4167 -- discriminant constraint. For non-tagged type, initially get the Etype
4171 if Is_Derived_Type (Pref_Type)
4172 and then Number_Discriminants (Pref_Type) /=
4173 Number_Discriminants (Etype (Base_Type (Pref_Type)))
4175 Pref_Type := Etype (Base_Type (Pref_Type));
4179 -- We definitely should have a checking function, This routine should
4180 -- not be called if no discriminant checking function is present.
4182 pragma Assert (Present (Discr_Fct));
4184 -- Create the list of the actual parameters for the call. This list
4185 -- is the list of the discriminant fields of the record expression to
4186 -- be discriminant checked.
4189 Formal := First_Formal (Discr_Fct);
4190 Discr := First_Discriminant (Pref_Type);
4191 while Present (Discr) loop
4193 -- If we have a corresponding discriminant field, and a parent
4194 -- subtype is present, then we want to use the corresponding
4195 -- discriminant since this is the one with the useful value.
4197 if Present (Corresponding_Discriminant (Discr))
4198 and then Ekind (Pref_Type) = E_Record_Type
4199 and then Present (Parent_Subtype (Pref_Type))
4201 Real_Discr := Corresponding_Discriminant (Discr);
4203 Real_Discr := Discr;
4206 -- Construct the reference to the discriminant
4209 Make_Selected_Component (Loc,
4211 Unchecked_Convert_To (Pref_Type,
4212 Duplicate_Subexpr (Pref)),
4213 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
4215 -- Manually analyze and resolve this selected component. We really
4216 -- want it just as it appears above, and do not want the expander
4217 -- playing discriminal games etc with this reference. Then we append
4218 -- the argument to the list we are gathering.
4220 Set_Etype (Scomp, Etype (Real_Discr));
4221 Set_Analyzed (Scomp, True);
4222 Append_To (Args, Convert_To (Etype (Formal), Scomp));
4224 Next_Formal_With_Extras (Formal);
4225 Next_Discriminant (Discr);
4228 -- Now build and insert the call
4231 Make_Raise_Constraint_Error (Loc,
4233 Make_Function_Call (Loc,
4234 Name => New_Occurrence_Of (Discr_Fct, Loc),
4235 Parameter_Associations => Args),
4236 Reason => CE_Discriminant_Check_Failed));
4237 end Generate_Discriminant_Check;
4239 ---------------------------
4240 -- Generate_Index_Checks --
4241 ---------------------------
4243 procedure Generate_Index_Checks (N : Node_Id) is
4244 Loc : constant Source_Ptr := Sloc (N);
4245 A : constant Node_Id := Prefix (N);
4251 -- Ignore call if index checks suppressed for array object or type
4253 if (Is_Entity_Name (A) and then Index_Checks_Suppressed (Entity (A)))
4254 or else Index_Checks_Suppressed (Etype (A))
4259 -- Generate the checks
4261 Sub := First (Expressions (N));
4263 while Present (Sub) loop
4264 if Do_Range_Check (Sub) then
4265 Set_Do_Range_Check (Sub, False);
4267 -- Force evaluation except for the case of a simple name of a
4268 -- non-volatile entity.
4270 if not Is_Entity_Name (Sub)
4271 or else Treat_As_Volatile (Entity (Sub))
4273 Force_Evaluation (Sub);
4276 -- Generate a raise of constraint error with the appropriate
4277 -- reason and a condition of the form:
4279 -- Base_Type(Sub) not in array'range (subscript)
4281 -- Note that the reason we generate the conversion to the base
4282 -- type here is that we definitely want the range check to take
4283 -- place, even if it looks like the subtype is OK. Optimization
4284 -- considerations that allow us to omit the check have already
4285 -- been taken into account in the setting of the Do_Range_Check
4291 Num := New_List (Make_Integer_Literal (Loc, Ind));
4295 Make_Raise_Constraint_Error (Loc,
4299 Convert_To (Base_Type (Etype (Sub)),
4300 Duplicate_Subexpr_Move_Checks (Sub)),
4302 Make_Attribute_Reference (Loc,
4303 Prefix => Duplicate_Subexpr_Move_Checks (A),
4304 Attribute_Name => Name_Range,
4305 Expressions => Num)),
4306 Reason => CE_Index_Check_Failed));
4312 end Generate_Index_Checks;
4314 --------------------------
4315 -- Generate_Range_Check --
4316 --------------------------
4318 procedure Generate_Range_Check
4320 Target_Type : Entity_Id;
4321 Reason : RT_Exception_Code)
4323 Loc : constant Source_Ptr := Sloc (N);
4324 Source_Type : constant Entity_Id := Etype (N);
4325 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
4326 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
4329 -- First special case, if the source type is already within the range
4330 -- of the target type, then no check is needed (probably we should have
4331 -- stopped Do_Range_Check from being set in the first place, but better
4332 -- late than later in preventing junk code!
4334 -- We do NOT apply this if the source node is a literal, since in this
4335 -- case the literal has already been labeled as having the subtype of
4338 if In_Subrange_Of (Source_Type, Target_Type)
4340 (Nkind (N) = N_Integer_Literal
4342 Nkind (N) = N_Real_Literal
4344 Nkind (N) = N_Character_Literal
4347 and then Ekind (Entity (N)) = E_Enumeration_Literal))
4352 -- We need a check, so force evaluation of the node, so that it does
4353 -- not get evaluated twice (once for the check, once for the actual
4354 -- reference). Such a double evaluation is always a potential source
4355 -- of inefficiency, and is functionally incorrect in the volatile case.
4357 if not Is_Entity_Name (N)
4358 or else Treat_As_Volatile (Entity (N))
4360 Force_Evaluation (N);
4363 -- The easiest case is when Source_Base_Type and Target_Base_Type are
4364 -- the same since in this case we can simply do a direct check of the
4365 -- value of N against the bounds of Target_Type.
4367 -- [constraint_error when N not in Target_Type]
4369 -- Note: this is by far the most common case, for example all cases of
4370 -- checks on the RHS of assignments are in this category, but not all
4371 -- cases are like this. Notably conversions can involve two types.
4373 if Source_Base_Type = Target_Base_Type then
4375 Make_Raise_Constraint_Error (Loc,
4378 Left_Opnd => Duplicate_Subexpr (N),
4379 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4382 -- Next test for the case where the target type is within the bounds
4383 -- of the base type of the source type, since in this case we can
4384 -- simply convert these bounds to the base type of T to do the test.
4386 -- [constraint_error when N not in
4387 -- Source_Base_Type (Target_Type'First)
4389 -- Source_Base_Type(Target_Type'Last))]
4391 -- The conversions will always work and need no check
4393 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
4395 Make_Raise_Constraint_Error (Loc,
4398 Left_Opnd => Duplicate_Subexpr (N),
4403 Convert_To (Source_Base_Type,
4404 Make_Attribute_Reference (Loc,
4406 New_Occurrence_Of (Target_Type, Loc),
4407 Attribute_Name => Name_First)),
4410 Convert_To (Source_Base_Type,
4411 Make_Attribute_Reference (Loc,
4413 New_Occurrence_Of (Target_Type, Loc),
4414 Attribute_Name => Name_Last)))),
4417 -- Note that at this stage we now that the Target_Base_Type is not in
4418 -- the range of the Source_Base_Type (since even the Target_Type itself
4419 -- is not in this range). It could still be the case that Source_Type is
4420 -- in range of the target base type since we have not checked that case.
4422 -- If that is the case, we can freely convert the source to the target,
4423 -- and then test the target result against the bounds.
4425 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
4427 -- We make a temporary to hold the value of the converted value
4428 -- (converted to the base type), and then we will do the test against
4431 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
4432 -- [constraint_error when Tnn not in Target_Type]
4434 -- Then the conversion itself is replaced by an occurrence of Tnn
4437 Tnn : constant Entity_Id :=
4438 Make_Defining_Identifier (Loc,
4439 Chars => New_Internal_Name ('T'));
4442 Insert_Actions (N, New_List (
4443 Make_Object_Declaration (Loc,
4444 Defining_Identifier => Tnn,
4445 Object_Definition =>
4446 New_Occurrence_Of (Target_Base_Type, Loc),
4447 Constant_Present => True,
4449 Make_Type_Conversion (Loc,
4450 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
4451 Expression => Duplicate_Subexpr (N))),
4453 Make_Raise_Constraint_Error (Loc,
4456 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4457 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
4459 Reason => Reason)));
4461 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4464 -- At this stage, we know that we have two scalar types, which are
4465 -- directly convertible, and where neither scalar type has a base
4466 -- range that is in the range of the other scalar type.
4468 -- The only way this can happen is with a signed and unsigned type.
4469 -- So test for these two cases:
4472 -- Case of the source is unsigned and the target is signed
4474 if Is_Unsigned_Type (Source_Base_Type)
4475 and then not Is_Unsigned_Type (Target_Base_Type)
4477 -- If the source is unsigned and the target is signed, then we
4478 -- know that the source is not shorter than the target (otherwise
4479 -- the source base type would be in the target base type range).
4481 -- In other words, the unsigned type is either the same size as
4482 -- the target, or it is larger. It cannot be smaller.
4485 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
4487 -- We only need to check the low bound if the low bound of the
4488 -- target type is non-negative. If the low bound of the target
4489 -- type is negative, then we know that we will fit fine.
4491 -- If the high bound of the target type is negative, then we
4492 -- know we have a constraint error, since we can't possibly
4493 -- have a negative source.
4495 -- With these two checks out of the way, we can do the check
4496 -- using the source type safely
4498 -- This is definitely the most annoying case!
4500 -- [constraint_error
4501 -- when (Target_Type'First >= 0
4503 -- N < Source_Base_Type (Target_Type'First))
4504 -- or else Target_Type'Last < 0
4505 -- or else N > Source_Base_Type (Target_Type'Last)];
4507 -- We turn off all checks since we know that the conversions
4508 -- will work fine, given the guards for negative values.
4511 Make_Raise_Constraint_Error (Loc,
4517 Left_Opnd => Make_Op_Ge (Loc,
4519 Make_Attribute_Reference (Loc,
4521 New_Occurrence_Of (Target_Type, Loc),
4522 Attribute_Name => Name_First),
4523 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4527 Left_Opnd => Duplicate_Subexpr (N),
4529 Convert_To (Source_Base_Type,
4530 Make_Attribute_Reference (Loc,
4532 New_Occurrence_Of (Target_Type, Loc),
4533 Attribute_Name => Name_First)))),
4538 Make_Attribute_Reference (Loc,
4539 Prefix => New_Occurrence_Of (Target_Type, Loc),
4540 Attribute_Name => Name_Last),
4541 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
4545 Left_Opnd => Duplicate_Subexpr (N),
4547 Convert_To (Source_Base_Type,
4548 Make_Attribute_Reference (Loc,
4549 Prefix => New_Occurrence_Of (Target_Type, Loc),
4550 Attribute_Name => Name_Last)))),
4553 Suppress => All_Checks);
4555 -- Only remaining possibility is that the source is signed and
4556 -- the target is unsigned
4559 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
4560 and then Is_Unsigned_Type (Target_Base_Type));
4562 -- If the source is signed and the target is unsigned, then we
4563 -- know that the target is not shorter than the source (otherwise
4564 -- the target base type would be in the source base type range).
4566 -- In other words, the unsigned type is either the same size as
4567 -- the target, or it is larger. It cannot be smaller.
4569 -- Clearly we have an error if the source value is negative since
4570 -- no unsigned type can have negative values. If the source type
4571 -- is non-negative, then the check can be done using the target
4574 -- Tnn : constant Target_Base_Type (N) := Target_Type;
4576 -- [constraint_error
4577 -- when N < 0 or else Tnn not in Target_Type];
4579 -- We turn off all checks for the conversion of N to the target
4580 -- base type, since we generate the explicit check to ensure that
4581 -- the value is non-negative
4584 Tnn : constant Entity_Id :=
4585 Make_Defining_Identifier (Loc,
4586 Chars => New_Internal_Name ('T'));
4589 Insert_Actions (N, New_List (
4590 Make_Object_Declaration (Loc,
4591 Defining_Identifier => Tnn,
4592 Object_Definition =>
4593 New_Occurrence_Of (Target_Base_Type, Loc),
4594 Constant_Present => True,
4596 Make_Type_Conversion (Loc,
4598 New_Occurrence_Of (Target_Base_Type, Loc),
4599 Expression => Duplicate_Subexpr (N))),
4601 Make_Raise_Constraint_Error (Loc,
4606 Left_Opnd => Duplicate_Subexpr (N),
4607 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
4611 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
4613 New_Occurrence_Of (Target_Type, Loc))),
4616 Suppress => All_Checks);
4618 -- Set the Etype explicitly, because Insert_Actions may have
4619 -- placed the declaration in the freeze list for an enclosing
4620 -- construct, and thus it is not analyzed yet.
4622 Set_Etype (Tnn, Target_Base_Type);
4623 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
4627 end Generate_Range_Check;
4629 ---------------------
4630 -- Get_Discriminal --
4631 ---------------------
4633 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
4634 Loc : constant Source_Ptr := Sloc (E);
4639 -- The entity E is the type of a private component of the protected
4640 -- type, or the type of a renaming of that component within a protected
4641 -- operation of that type.
4645 if Ekind (Sc) /= E_Protected_Type then
4648 if Ekind (Sc) /= E_Protected_Type then
4653 -- The bound can be a bona fide parameter of a protected operation,
4654 -- rather than a prival encoded as an in-parameter.
4656 if No (Discriminal_Link (Entity (Bound))) then
4660 D := First_Discriminant (Sc);
4663 and then Chars (D) /= Chars (Bound)
4665 Next_Discriminant (D);
4668 return New_Occurrence_Of (Discriminal (D), Loc);
4669 end Get_Discriminal;
4675 function Guard_Access
4678 Ck_Node : Node_Id) return Node_Id
4681 if Nkind (Cond) = N_Or_Else then
4682 Set_Paren_Count (Cond, 1);
4685 if Nkind (Ck_Node) = N_Allocator then
4692 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
4693 Right_Opnd => Make_Null (Loc)),
4694 Right_Opnd => Cond);
4698 -----------------------------
4699 -- Index_Checks_Suppressed --
4700 -----------------------------
4702 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
4704 if Present (E) and then Checks_May_Be_Suppressed (E) then
4705 return Is_Check_Suppressed (E, Index_Check);
4707 return Scope_Suppress (Index_Check);
4709 end Index_Checks_Suppressed;
4715 procedure Initialize is
4717 for J in Determine_Range_Cache_N'Range loop
4718 Determine_Range_Cache_N (J) := Empty;
4722 -------------------------
4723 -- Insert_Range_Checks --
4724 -------------------------
4726 procedure Insert_Range_Checks
4727 (Checks : Check_Result;
4729 Suppress_Typ : Entity_Id;
4730 Static_Sloc : Source_Ptr := No_Location;
4731 Flag_Node : Node_Id := Empty;
4732 Do_Before : Boolean := False)
4734 Internal_Flag_Node : Node_Id := Flag_Node;
4735 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
4737 Check_Node : Node_Id;
4738 Checks_On : constant Boolean :=
4739 (not Index_Checks_Suppressed (Suppress_Typ))
4741 (not Range_Checks_Suppressed (Suppress_Typ));
4744 -- For now we just return if Checks_On is false, however this should be
4745 -- enhanced to check for an always True value in the condition and to
4746 -- generate a compilation warning???
4748 if not Expander_Active or else not Checks_On then
4752 if Static_Sloc = No_Location then
4753 Internal_Static_Sloc := Sloc (Node);
4756 if No (Flag_Node) then
4757 Internal_Flag_Node := Node;
4760 for J in 1 .. 2 loop
4761 exit when No (Checks (J));
4763 if Nkind (Checks (J)) = N_Raise_Constraint_Error
4764 and then Present (Condition (Checks (J)))
4766 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
4767 Check_Node := Checks (J);
4768 Mark_Rewrite_Insertion (Check_Node);
4771 Insert_Before_And_Analyze (Node, Check_Node);
4773 Insert_After_And_Analyze (Node, Check_Node);
4776 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
4781 Make_Raise_Constraint_Error (Internal_Static_Sloc,
4782 Reason => CE_Range_Check_Failed);
4783 Mark_Rewrite_Insertion (Check_Node);
4786 Insert_Before_And_Analyze (Node, Check_Node);
4788 Insert_After_And_Analyze (Node, Check_Node);
4792 end Insert_Range_Checks;
4794 ------------------------
4795 -- Insert_Valid_Check --
4796 ------------------------
4798 procedure Insert_Valid_Check (Expr : Node_Id) is
4799 Loc : constant Source_Ptr := Sloc (Expr);
4803 -- Do not insert if checks off, or if not checking validity
4805 if not Validity_Checks_On
4806 or else Range_Or_Validity_Checks_Suppressed (Expr)
4811 -- If we have a checked conversion, then validity check applies to
4812 -- the expression inside the conversion, not the result, since if
4813 -- the expression inside is valid, then so is the conversion result.
4816 while Nkind (Exp) = N_Type_Conversion loop
4817 Exp := Expression (Exp);
4820 -- We are about to insert the validity check for Exp. We save and
4821 -- reset the Do_Range_Check flag over this validity check, and then
4822 -- put it back for the final original reference (Exp may be rewritten).
4825 DRC : constant Boolean := Do_Range_Check (Exp);
4828 Set_Do_Range_Check (Exp, False);
4830 -- Insert the validity check. Note that we do this with validity
4831 -- checks turned off, to avoid recursion, we do not want validity
4832 -- checks on the validity checking code itself!
4836 Make_Raise_Constraint_Error (Loc,
4840 Make_Attribute_Reference (Loc,
4842 Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
4843 Attribute_Name => Name_Valid)),
4844 Reason => CE_Invalid_Data),
4845 Suppress => Validity_Check);
4847 -- If the expression is a a reference to an element of a bit-packed
4848 -- array, then it is rewritten as a renaming declaration. If the
4849 -- expression is an actual in a call, it has not been expanded,
4850 -- waiting for the proper point at which to do it. The same happens
4851 -- with renamings, so that we have to force the expansion now. This
4852 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
4855 if Is_Entity_Name (Exp)
4856 and then Nkind (Parent (Entity (Exp))) =
4857 N_Object_Renaming_Declaration
4860 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
4862 if Nkind (Old_Exp) = N_Indexed_Component
4863 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
4865 Expand_Packed_Element_Reference (Old_Exp);
4870 -- Put back the Do_Range_Check flag on the resulting (possibly
4871 -- rewritten) expression.
4873 -- Note: it might be thought that a validity check is not required
4874 -- when a range check is present, but that's not the case, because
4875 -- the back end is allowed to assume for the range check that the
4876 -- operand is within its declared range (an assumption that validity
4877 -- checking is all about NOT assuming!)
4879 -- Note: no need to worry about Possible_Local_Raise here, it will
4880 -- already have been called if original node has Do_Range_Check set.
4882 Set_Do_Range_Check (Exp, DRC);
4884 end Insert_Valid_Check;
4886 ----------------------------------
4887 -- Install_Null_Excluding_Check --
4888 ----------------------------------
4890 procedure Install_Null_Excluding_Check (N : Node_Id) is
4891 Loc : constant Source_Ptr := Sloc (N);
4892 Typ : constant Entity_Id := Etype (N);
4894 procedure Mark_Non_Null;
4895 -- After installation of check, marks node as non-null if entity
4901 procedure Mark_Non_Null is
4903 if Is_Entity_Name (N) then
4904 Set_Is_Known_Null (Entity (N), False);
4906 if Safe_To_Capture_Value (N, Entity (N)) then
4907 Set_Is_Known_Non_Null (Entity (N), True);
4912 -- Start of processing for Install_Null_Excluding_Check
4915 pragma Assert (Is_Access_Type (Typ));
4917 -- No check inside a generic (why not???)
4919 if Inside_A_Generic then
4923 -- No check needed if known to be non-null
4925 if Known_Non_Null (N) then
4929 -- If known to be null, here is where we generate a compile time check
4931 if Known_Null (N) then
4932 Apply_Compile_Time_Constraint_Error
4934 "null value not allowed here?",
4935 CE_Access_Check_Failed);
4940 -- If entity is never assigned, for sure a warning is appropriate
4942 if Is_Entity_Name (N) then
4943 Check_Unset_Reference (N);
4946 -- No check needed if checks are suppressed on the range. Note that we
4947 -- don't set Is_Known_Non_Null in this case (we could legitimately do
4948 -- so, since the program is erroneous, but we don't like to casually
4949 -- propagate such conclusions from erroneosity).
4951 if Access_Checks_Suppressed (Typ) then
4955 -- Otherwise install access check
4958 Make_Raise_Constraint_Error (Loc,
4961 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
4962 Right_Opnd => Make_Null (Loc)),
4963 Reason => CE_Access_Check_Failed));
4966 end Install_Null_Excluding_Check;
4968 --------------------------
4969 -- Install_Static_Check --
4970 --------------------------
4972 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
4973 Stat : constant Boolean := Is_Static_Expression (R_Cno);
4974 Typ : constant Entity_Id := Etype (R_Cno);
4978 Make_Raise_Constraint_Error (Loc,
4979 Reason => CE_Range_Check_Failed));
4980 Set_Analyzed (R_Cno);
4981 Set_Etype (R_Cno, Typ);
4982 Set_Raises_Constraint_Error (R_Cno);
4983 Set_Is_Static_Expression (R_Cno, Stat);
4984 end Install_Static_Check;
4986 ---------------------
4987 -- Kill_All_Checks --
4988 ---------------------
4990 procedure Kill_All_Checks is
4992 if Debug_Flag_CC then
4993 w ("Kill_All_Checks");
4996 -- We reset the number of saved checks to zero, and also modify all
4997 -- stack entries for statement ranges to indicate that the number of
4998 -- checks at each level is now zero.
5000 Num_Saved_Checks := 0;
5002 for J in 1 .. Saved_Checks_TOS loop
5003 Saved_Checks_Stack (J) := 0;
5005 end Kill_All_Checks;
5011 procedure Kill_Checks (V : Entity_Id) is
5013 if Debug_Flag_CC then
5014 w ("Kill_Checks for entity", Int (V));
5017 for J in 1 .. Num_Saved_Checks loop
5018 if Saved_Checks (J).Entity = V then
5019 if Debug_Flag_CC then
5020 w (" Checks killed for saved check ", J);
5023 Saved_Checks (J).Killed := True;
5028 ------------------------------
5029 -- Length_Checks_Suppressed --
5030 ------------------------------
5032 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
5034 if Present (E) and then Checks_May_Be_Suppressed (E) then
5035 return Is_Check_Suppressed (E, Length_Check);
5037 return Scope_Suppress (Length_Check);
5039 end Length_Checks_Suppressed;
5041 --------------------------------
5042 -- Overflow_Checks_Suppressed --
5043 --------------------------------
5045 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
5047 if Present (E) and then Checks_May_Be_Suppressed (E) then
5048 return Is_Check_Suppressed (E, Overflow_Check);
5050 return Scope_Suppress (Overflow_Check);
5052 end Overflow_Checks_Suppressed;
5058 function Range_Check
5060 Target_Typ : Entity_Id;
5061 Source_Typ : Entity_Id := Empty;
5062 Warn_Node : Node_Id := Empty) return Check_Result
5065 return Selected_Range_Checks
5066 (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
5069 -----------------------------
5070 -- Range_Checks_Suppressed --
5071 -----------------------------
5073 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
5077 -- Note: for now we always suppress range checks on Vax float types,
5078 -- since Gigi does not know how to generate these checks.
5080 if Vax_Float (E) then
5082 elsif Kill_Range_Checks (E) then
5084 elsif Checks_May_Be_Suppressed (E) then
5085 return Is_Check_Suppressed (E, Range_Check);
5089 return Scope_Suppress (Range_Check);
5090 end Range_Checks_Suppressed;
5092 -----------------------------------------
5093 -- Range_Or_Validity_Checks_Suppressed --
5094 -----------------------------------------
5096 -- Note: the coding would be simpler here if we simply made appropriate
5097 -- calls to Range/Validity_Checks_Suppressed, but that would result in
5098 -- duplicated checks which we prefer to avoid.
5100 function Range_Or_Validity_Checks_Suppressed
5101 (Expr : Node_Id) return Boolean
5104 -- Immediate return if scope checks suppressed for either check
5106 if Scope_Suppress (Range_Check) or Scope_Suppress (Validity_Check) then
5110 -- If no expression, that's odd, decide that checks are suppressed,
5111 -- since we don't want anyone trying to do checks in this case, which
5112 -- is most likely the result of some other error.
5118 -- Expression is present, so perform suppress checks on type
5121 Typ : constant Entity_Id := Etype (Expr);
5123 if Vax_Float (Typ) then
5125 elsif Checks_May_Be_Suppressed (Typ)
5126 and then (Is_Check_Suppressed (Typ, Range_Check)
5128 Is_Check_Suppressed (Typ, Validity_Check))
5134 -- If expression is an entity name, perform checks on this entity
5136 if Is_Entity_Name (Expr) then
5138 Ent : constant Entity_Id := Entity (Expr);
5140 if Checks_May_Be_Suppressed (Ent) then
5141 return Is_Check_Suppressed (Ent, Range_Check)
5142 or else Is_Check_Suppressed (Ent, Validity_Check);
5147 -- If we fall through, no checks suppressed
5150 end Range_Or_Validity_Checks_Suppressed;
5156 procedure Remove_Checks (Expr : Node_Id) is
5157 Discard : Traverse_Result;
5158 pragma Warnings (Off, Discard);
5160 function Process (N : Node_Id) return Traverse_Result;
5161 -- Process a single node during the traversal
5163 function Traverse is new Traverse_Func (Process);
5164 -- The traversal function itself
5170 function Process (N : Node_Id) return Traverse_Result is
5172 if Nkind (N) not in N_Subexpr then
5176 Set_Do_Range_Check (N, False);
5180 Discard := Traverse (Left_Opnd (N));
5183 when N_Attribute_Reference =>
5184 Set_Do_Overflow_Check (N, False);
5186 when N_Function_Call =>
5187 Set_Do_Tag_Check (N, False);
5190 Set_Do_Overflow_Check (N, False);
5194 Set_Do_Division_Check (N, False);
5197 Set_Do_Length_Check (N, False);
5200 Set_Do_Division_Check (N, False);
5203 Set_Do_Length_Check (N, False);
5206 Set_Do_Division_Check (N, False);
5209 Set_Do_Length_Check (N, False);
5216 Discard := Traverse (Left_Opnd (N));
5219 when N_Selected_Component =>
5220 Set_Do_Discriminant_Check (N, False);
5222 when N_Type_Conversion =>
5223 Set_Do_Length_Check (N, False);
5224 Set_Do_Tag_Check (N, False);
5225 Set_Do_Overflow_Check (N, False);
5234 -- Start of processing for Remove_Checks
5237 Discard := Traverse (Expr);
5240 ----------------------------
5241 -- Selected_Length_Checks --
5242 ----------------------------
5244 function Selected_Length_Checks
5246 Target_Typ : Entity_Id;
5247 Source_Typ : Entity_Id;
5248 Warn_Node : Node_Id) return Check_Result
5250 Loc : constant Source_Ptr := Sloc (Ck_Node);
5253 Expr_Actual : Node_Id;
5255 Cond : Node_Id := Empty;
5256 Do_Access : Boolean := False;
5257 Wnode : Node_Id := Warn_Node;
5258 Ret_Result : Check_Result := (Empty, Empty);
5259 Num_Checks : Natural := 0;
5261 procedure Add_Check (N : Node_Id);
5262 -- Adds the action given to Ret_Result if N is non-Empty
5264 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
5265 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
5266 -- Comments required ???
5268 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
5269 -- True for equal literals and for nodes that denote the same constant
5270 -- entity, even if its value is not a static constant. This includes the
5271 -- case of a discriminal reference within an init proc. Removes some
5272 -- obviously superfluous checks.
5274 function Length_E_Cond
5275 (Exptyp : Entity_Id;
5277 Indx : Nat) return Node_Id;
5278 -- Returns expression to compute:
5279 -- Typ'Length /= Exptyp'Length
5281 function Length_N_Cond
5284 Indx : Nat) return Node_Id;
5285 -- Returns expression to compute:
5286 -- Typ'Length /= Expr'Length
5292 procedure Add_Check (N : Node_Id) is
5296 -- For now, ignore attempt to place more than 2 checks ???
5298 if Num_Checks = 2 then
5302 pragma Assert (Num_Checks <= 1);
5303 Num_Checks := Num_Checks + 1;
5304 Ret_Result (Num_Checks) := N;
5312 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
5313 SE : constant Entity_Id := Scope (E);
5315 E1 : Entity_Id := E;
5318 if Ekind (Scope (E)) = E_Record_Type
5319 and then Has_Discriminants (Scope (E))
5321 N := Build_Discriminal_Subtype_Of_Component (E);
5324 Insert_Action (Ck_Node, N);
5325 E1 := Defining_Identifier (N);
5329 if Ekind (E1) = E_String_Literal_Subtype then
5331 Make_Integer_Literal (Loc,
5332 Intval => String_Literal_Length (E1));
5334 elsif SE /= Standard_Standard
5335 and then Ekind (Scope (SE)) = E_Protected_Type
5336 and then Has_Discriminants (Scope (SE))
5337 and then Has_Completion (Scope (SE))
5338 and then not Inside_Init_Proc
5340 -- If the type whose length is needed is a private component
5341 -- constrained by a discriminant, we must expand the 'Length
5342 -- attribute into an explicit computation, using the discriminal
5343 -- of the current protected operation. This is because the actual
5344 -- type of the prival is constructed after the protected opera-
5345 -- tion has been fully expanded.
5348 Indx_Type : Node_Id;
5351 Do_Expand : Boolean := False;
5354 Indx_Type := First_Index (E);
5356 for J in 1 .. Indx - 1 loop
5357 Next_Index (Indx_Type);
5360 Get_Index_Bounds (Indx_Type, Lo, Hi);
5362 if Nkind (Lo) = N_Identifier
5363 and then Ekind (Entity (Lo)) = E_In_Parameter
5365 Lo := Get_Discriminal (E, Lo);
5369 if Nkind (Hi) = N_Identifier
5370 and then Ekind (Entity (Hi)) = E_In_Parameter
5372 Hi := Get_Discriminal (E, Hi);
5377 if not Is_Entity_Name (Lo) then
5378 Lo := Duplicate_Subexpr_No_Checks (Lo);
5381 if not Is_Entity_Name (Hi) then
5382 Lo := Duplicate_Subexpr_No_Checks (Hi);
5388 Make_Op_Subtract (Loc,
5392 Right_Opnd => Make_Integer_Literal (Loc, 1));
5397 Make_Attribute_Reference (Loc,
5398 Attribute_Name => Name_Length,
5400 New_Occurrence_Of (E1, Loc));
5403 Set_Expressions (N, New_List (
5404 Make_Integer_Literal (Loc, Indx)));
5413 Make_Attribute_Reference (Loc,
5414 Attribute_Name => Name_Length,
5416 New_Occurrence_Of (E1, Loc));
5419 Set_Expressions (N, New_List (
5420 Make_Integer_Literal (Loc, Indx)));
5431 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
5434 Make_Attribute_Reference (Loc,
5435 Attribute_Name => Name_Length,
5437 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
5438 Expressions => New_List (
5439 Make_Integer_Literal (Loc, Indx)));
5446 function Length_E_Cond
5447 (Exptyp : Entity_Id;
5449 Indx : Nat) return Node_Id
5454 Left_Opnd => Get_E_Length (Typ, Indx),
5455 Right_Opnd => Get_E_Length (Exptyp, Indx));
5462 function Length_N_Cond
5465 Indx : Nat) return Node_Id
5470 Left_Opnd => Get_E_Length (Typ, Indx),
5471 Right_Opnd => Get_N_Length (Expr, Indx));
5478 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
5481 (Nkind (L) = N_Integer_Literal
5482 and then Nkind (R) = N_Integer_Literal
5483 and then Intval (L) = Intval (R))
5487 and then Ekind (Entity (L)) = E_Constant
5488 and then ((Is_Entity_Name (R)
5489 and then Entity (L) = Entity (R))
5491 (Nkind (R) = N_Type_Conversion
5492 and then Is_Entity_Name (Expression (R))
5493 and then Entity (L) = Entity (Expression (R)))))
5497 and then Ekind (Entity (R)) = E_Constant
5498 and then Nkind (L) = N_Type_Conversion
5499 and then Is_Entity_Name (Expression (L))
5500 and then Entity (R) = Entity (Expression (L)))
5504 and then Is_Entity_Name (R)
5505 and then Entity (L) = Entity (R)
5506 and then Ekind (Entity (L)) = E_In_Parameter
5507 and then Inside_Init_Proc);
5510 -- Start of processing for Selected_Length_Checks
5513 if not Expander_Active then
5517 if Target_Typ = Any_Type
5518 or else Target_Typ = Any_Composite
5519 or else Raises_Constraint_Error (Ck_Node)
5528 T_Typ := Target_Typ;
5530 if No (Source_Typ) then
5531 S_Typ := Etype (Ck_Node);
5533 S_Typ := Source_Typ;
5536 if S_Typ = Any_Type or else S_Typ = Any_Composite then
5540 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
5541 S_Typ := Designated_Type (S_Typ);
5542 T_Typ := Designated_Type (T_Typ);
5545 -- A simple optimization
5547 if Nkind (Ck_Node) = N_Null then
5552 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
5553 if Is_Constrained (T_Typ) then
5555 -- The checking code to be generated will freeze the
5556 -- corresponding array type. However, we must freeze the
5557 -- type now, so that the freeze node does not appear within
5558 -- the generated condional expression, but ahead of it.
5560 Freeze_Before (Ck_Node, T_Typ);
5562 Expr_Actual := Get_Referenced_Object (Ck_Node);
5563 Exptyp := Get_Actual_Subtype (Ck_Node);
5565 if Is_Access_Type (Exptyp) then
5566 Exptyp := Designated_Type (Exptyp);
5569 -- String_Literal case. This needs to be handled specially be-
5570 -- cause no index types are available for string literals. The
5571 -- condition is simply:
5573 -- T_Typ'Length = string-literal-length
5575 if Nkind (Expr_Actual) = N_String_Literal
5576 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
5580 Left_Opnd => Get_E_Length (T_Typ, 1),
5582 Make_Integer_Literal (Loc,
5584 String_Literal_Length (Etype (Expr_Actual))));
5586 -- General array case. Here we have a usable actual subtype for
5587 -- the expression, and the condition is built from the two types
5590 -- T_Typ'Length /= Exptyp'Length or else
5591 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
5592 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
5595 elsif Is_Constrained (Exptyp) then
5597 Ndims : constant Nat := Number_Dimensions (T_Typ);
5610 -- At the library level, we need to ensure that the type of
5611 -- the object is elaborated before the check itself is
5612 -- emitted. This is only done if the object is in the
5613 -- current compilation unit, otherwise the type is frozen
5614 -- and elaborated in its unit.
5616 if Is_Itype (Exptyp)
5618 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
5620 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
5621 and then In_Open_Scopes (Scope (Exptyp))
5623 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
5624 Set_Itype (Ref_Node, Exptyp);
5625 Insert_Action (Ck_Node, Ref_Node);
5628 L_Index := First_Index (T_Typ);
5629 R_Index := First_Index (Exptyp);
5631 for Indx in 1 .. Ndims loop
5632 if not (Nkind (L_Index) = N_Raise_Constraint_Error
5634 Nkind (R_Index) = N_Raise_Constraint_Error)
5636 Get_Index_Bounds (L_Index, L_Low, L_High);
5637 Get_Index_Bounds (R_Index, R_Low, R_High);
5639 -- Deal with compile time length check. Note that we
5640 -- skip this in the access case, because the access
5641 -- value may be null, so we cannot know statically.
5644 and then Compile_Time_Known_Value (L_Low)
5645 and then Compile_Time_Known_Value (L_High)
5646 and then Compile_Time_Known_Value (R_Low)
5647 and then Compile_Time_Known_Value (R_High)
5649 if Expr_Value (L_High) >= Expr_Value (L_Low) then
5650 L_Length := Expr_Value (L_High) -
5651 Expr_Value (L_Low) + 1;
5653 L_Length := UI_From_Int (0);
5656 if Expr_Value (R_High) >= Expr_Value (R_Low) then
5657 R_Length := Expr_Value (R_High) -
5658 Expr_Value (R_Low) + 1;
5660 R_Length := UI_From_Int (0);
5663 if L_Length > R_Length then
5665 (Compile_Time_Constraint_Error
5666 (Wnode, "too few elements for}?", T_Typ));
5668 elsif L_Length < R_Length then
5670 (Compile_Time_Constraint_Error
5671 (Wnode, "too many elements for}?", T_Typ));
5674 -- The comparison for an individual index subtype
5675 -- is omitted if the corresponding index subtypes
5676 -- statically match, since the result is known to
5677 -- be true. Note that this test is worth while even
5678 -- though we do static evaluation, because non-static
5679 -- subtypes can statically match.
5682 Subtypes_Statically_Match
5683 (Etype (L_Index), Etype (R_Index))
5686 (Same_Bounds (L_Low, R_Low)
5687 and then Same_Bounds (L_High, R_High))
5690 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
5699 -- Handle cases where we do not get a usable actual subtype that
5700 -- is constrained. This happens for example in the function call
5701 -- and explicit dereference cases. In these cases, we have to get
5702 -- the length or range from the expression itself, making sure we
5703 -- do not evaluate it more than once.
5705 -- Here Ck_Node is the original expression, or more properly the
5706 -- result of applying Duplicate_Expr to the original tree, forcing
5707 -- the result to be a name.
5711 Ndims : constant Nat := Number_Dimensions (T_Typ);
5714 -- Build the condition for the explicit dereference case
5716 for Indx in 1 .. Ndims loop
5718 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
5725 -- Construct the test and insert into the tree
5727 if Present (Cond) then
5729 Cond := Guard_Access (Cond, Loc, Ck_Node);
5733 (Make_Raise_Constraint_Error (Loc,
5735 Reason => CE_Length_Check_Failed));
5739 end Selected_Length_Checks;
5741 ---------------------------
5742 -- Selected_Range_Checks --
5743 ---------------------------
5745 function Selected_Range_Checks
5747 Target_Typ : Entity_Id;
5748 Source_Typ : Entity_Id;
5749 Warn_Node : Node_Id) return Check_Result
5751 Loc : constant Source_Ptr := Sloc (Ck_Node);
5754 Expr_Actual : Node_Id;
5756 Cond : Node_Id := Empty;
5757 Do_Access : Boolean := False;
5758 Wnode : Node_Id := Warn_Node;
5759 Ret_Result : Check_Result := (Empty, Empty);
5760 Num_Checks : Integer := 0;
5762 procedure Add_Check (N : Node_Id);
5763 -- Adds the action given to Ret_Result if N is non-Empty
5765 function Discrete_Range_Cond
5767 Typ : Entity_Id) return Node_Id;
5768 -- Returns expression to compute:
5769 -- Low_Bound (Expr) < Typ'First
5771 -- High_Bound (Expr) > Typ'Last
5773 function Discrete_Expr_Cond
5775 Typ : Entity_Id) return Node_Id;
5776 -- Returns expression to compute:
5781 function Get_E_First_Or_Last
5784 Nam : Name_Id) return Node_Id;
5785 -- Returns expression to compute:
5786 -- E'First or E'Last
5788 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
5789 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
5790 -- Returns expression to compute:
5791 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
5793 function Range_E_Cond
5794 (Exptyp : Entity_Id;
5798 -- Returns expression to compute:
5799 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
5801 function Range_Equal_E_Cond
5802 (Exptyp : Entity_Id;
5804 Indx : Nat) return Node_Id;
5805 -- Returns expression to compute:
5806 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
5808 function Range_N_Cond
5811 Indx : Nat) return Node_Id;
5812 -- Return expression to compute:
5813 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
5819 procedure Add_Check (N : Node_Id) is
5823 -- For now, ignore attempt to place more than 2 checks ???
5825 if Num_Checks = 2 then
5829 pragma Assert (Num_Checks <= 1);
5830 Num_Checks := Num_Checks + 1;
5831 Ret_Result (Num_Checks) := N;
5835 -------------------------
5836 -- Discrete_Expr_Cond --
5837 -------------------------
5839 function Discrete_Expr_Cond
5841 Typ : Entity_Id) return Node_Id
5849 Convert_To (Base_Type (Typ),
5850 Duplicate_Subexpr_No_Checks (Expr)),
5852 Convert_To (Base_Type (Typ),
5853 Get_E_First_Or_Last (Typ, 0, Name_First))),
5858 Convert_To (Base_Type (Typ),
5859 Duplicate_Subexpr_No_Checks (Expr)),
5863 Get_E_First_Or_Last (Typ, 0, Name_Last))));
5864 end Discrete_Expr_Cond;
5866 -------------------------
5867 -- Discrete_Range_Cond --
5868 -------------------------
5870 function Discrete_Range_Cond
5872 Typ : Entity_Id) return Node_Id
5874 LB : Node_Id := Low_Bound (Expr);
5875 HB : Node_Id := High_Bound (Expr);
5877 Left_Opnd : Node_Id;
5878 Right_Opnd : Node_Id;
5881 if Nkind (LB) = N_Identifier
5882 and then Ekind (Entity (LB)) = E_Discriminant
5884 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
5887 if Nkind (HB) = N_Identifier
5888 and then Ekind (Entity (HB)) = E_Discriminant
5890 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
5897 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
5901 (Base_Type (Typ), Get_E_First_Or_Last (Typ, 0, Name_First)));
5903 if Base_Type (Typ) = Typ then
5906 elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
5908 Compile_Time_Known_Value (High_Bound (Scalar_Range
5911 if Is_Floating_Point_Type (Typ) then
5912 if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
5913 Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
5919 if Expr_Value (High_Bound (Scalar_Range (Typ))) =
5920 Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
5931 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
5936 Get_E_First_Or_Last (Typ, 0, Name_Last)));
5938 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
5939 end Discrete_Range_Cond;
5941 -------------------------
5942 -- Get_E_First_Or_Last --
5943 -------------------------
5945 function Get_E_First_Or_Last
5948 Nam : Name_Id) return Node_Id
5956 if Is_Array_Type (E) then
5957 N := First_Index (E);
5959 for J in 2 .. Indx loop
5964 N := Scalar_Range (E);
5967 if Nkind (N) = N_Subtype_Indication then
5968 LB := Low_Bound (Range_Expression (Constraint (N)));
5969 HB := High_Bound (Range_Expression (Constraint (N)));
5971 elsif Is_Entity_Name (N) then
5972 LB := Type_Low_Bound (Etype (N));
5973 HB := Type_High_Bound (Etype (N));
5976 LB := Low_Bound (N);
5977 HB := High_Bound (N);
5980 if Nam = Name_First then
5986 if Nkind (Bound) = N_Identifier
5987 and then Ekind (Entity (Bound)) = E_Discriminant
5989 -- If this is a task discriminant, and we are the body, we must
5990 -- retrieve the corresponding body discriminal. This is another
5991 -- consequence of the early creation of discriminals, and the
5992 -- need to generate constraint checks before their declarations
5993 -- are made visible.
5995 if Is_Concurrent_Record_Type (Scope (Entity (Bound))) then
5997 Tsk : constant Entity_Id :=
5998 Corresponding_Concurrent_Type
5999 (Scope (Entity (Bound)));
6003 if In_Open_Scopes (Tsk)
6004 and then Has_Completion (Tsk)
6006 -- Find discriminant of original task, and use its
6007 -- current discriminal, which is the renaming within
6010 Disc := First_Discriminant (Tsk);
6011 while Present (Disc) loop
6012 if Chars (Disc) = Chars (Entity (Bound)) then
6013 Set_Scope (Discriminal (Disc), Tsk);
6014 return New_Occurrence_Of (Discriminal (Disc), Loc);
6017 Next_Discriminant (Disc);
6020 -- That loop should always succeed in finding a matching
6021 -- entry and returning. Fatal error if not.
6023 raise Program_Error;
6027 New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6031 return New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
6034 elsif Nkind (Bound) = N_Identifier
6035 and then Ekind (Entity (Bound)) = E_In_Parameter
6036 and then not Inside_Init_Proc
6038 return Get_Discriminal (E, Bound);
6040 elsif Nkind (Bound) = N_Integer_Literal then
6041 return Make_Integer_Literal (Loc, Intval (Bound));
6043 -- Case of a bound rewritten to an N_Raise_Constraint_Error node
6044 -- because it is an out-of-range value. Duplicate_Subexpr cannot be
6045 -- called on this node because an N_Raise_Constraint_Error is not
6046 -- side effect free, and we may not assume that we are in the proper
6047 -- context to remove side effects on it at the point of reference.
6049 elsif Nkind (Bound) = N_Raise_Constraint_Error then
6050 return New_Copy_Tree (Bound);
6053 return Duplicate_Subexpr_No_Checks (Bound);
6055 end Get_E_First_Or_Last;
6061 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
6064 Make_Attribute_Reference (Loc,
6065 Attribute_Name => Name_First,
6067 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6068 Expressions => New_List (
6069 Make_Integer_Literal (Loc, Indx)));
6076 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
6079 Make_Attribute_Reference (Loc,
6080 Attribute_Name => Name_Last,
6082 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
6083 Expressions => New_List (
6084 Make_Integer_Literal (Loc, Indx)));
6091 function Range_E_Cond
6092 (Exptyp : Entity_Id;
6094 Indx : Nat) return Node_Id
6101 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6102 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6106 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6107 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6110 ------------------------
6111 -- Range_Equal_E_Cond --
6112 ------------------------
6114 function Range_Equal_E_Cond
6115 (Exptyp : Entity_Id;
6117 Indx : Nat) return Node_Id
6124 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
6125 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6128 Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
6129 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6130 end Range_Equal_E_Cond;
6136 function Range_N_Cond
6139 Indx : Nat) return Node_Id
6146 Left_Opnd => Get_N_First (Expr, Indx),
6147 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
6151 Left_Opnd => Get_N_Last (Expr, Indx),
6152 Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
6155 -- Start of processing for Selected_Range_Checks
6158 if not Expander_Active then
6162 if Target_Typ = Any_Type
6163 or else Target_Typ = Any_Composite
6164 or else Raises_Constraint_Error (Ck_Node)
6173 T_Typ := Target_Typ;
6175 if No (Source_Typ) then
6176 S_Typ := Etype (Ck_Node);
6178 S_Typ := Source_Typ;
6181 if S_Typ = Any_Type or else S_Typ = Any_Composite then
6185 -- The order of evaluating T_Typ before S_Typ seems to be critical
6186 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
6187 -- in, and since Node can be an N_Range node, it might be invalid.
6188 -- Should there be an assert check somewhere for taking the Etype of
6189 -- an N_Range node ???
6191 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
6192 S_Typ := Designated_Type (S_Typ);
6193 T_Typ := Designated_Type (T_Typ);
6196 -- A simple optimization
6198 if Nkind (Ck_Node) = N_Null then
6203 -- For an N_Range Node, check for a null range and then if not
6204 -- null generate a range check action.
6206 if Nkind (Ck_Node) = N_Range then
6208 -- There's no point in checking a range against itself
6210 if Ck_Node = Scalar_Range (T_Typ) then
6215 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
6216 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
6217 LB : constant Node_Id := Low_Bound (Ck_Node);
6218 HB : constant Node_Id := High_Bound (Ck_Node);
6219 Null_Range : Boolean;
6221 Out_Of_Range_L : Boolean;
6222 Out_Of_Range_H : Boolean;
6225 -- Check for case where everything is static and we can
6226 -- do the check at compile time. This is skipped if we
6227 -- have an access type, since the access value may be null.
6229 -- ??? This code can be improved since you only need to know
6230 -- that the two respective bounds (LB & T_LB or HB & T_HB)
6231 -- are known at compile time to emit pertinent messages.
6233 if Compile_Time_Known_Value (LB)
6234 and then Compile_Time_Known_Value (HB)
6235 and then Compile_Time_Known_Value (T_LB)
6236 and then Compile_Time_Known_Value (T_HB)
6237 and then not Do_Access
6239 -- Floating-point case
6241 if Is_Floating_Point_Type (S_Typ) then
6242 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
6244 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
6246 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
6249 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
6251 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
6253 -- Fixed or discrete type case
6256 Null_Range := Expr_Value (HB) < Expr_Value (LB);
6258 (Expr_Value (LB) < Expr_Value (T_LB))
6260 (Expr_Value (LB) > Expr_Value (T_HB));
6263 (Expr_Value (HB) > Expr_Value (T_HB))
6265 (Expr_Value (HB) < Expr_Value (T_LB));
6268 if not Null_Range then
6269 if Out_Of_Range_L then
6270 if No (Warn_Node) then
6272 (Compile_Time_Constraint_Error
6273 (Low_Bound (Ck_Node),
6274 "static value out of range of}?", T_Typ));
6278 (Compile_Time_Constraint_Error
6280 "static range out of bounds of}?", T_Typ));
6284 if Out_Of_Range_H then
6285 if No (Warn_Node) then
6287 (Compile_Time_Constraint_Error
6288 (High_Bound (Ck_Node),
6289 "static value out of range of}?", T_Typ));
6293 (Compile_Time_Constraint_Error
6295 "static range out of bounds of}?", T_Typ));
6303 LB : Node_Id := Low_Bound (Ck_Node);
6304 HB : Node_Id := High_Bound (Ck_Node);
6307 -- If either bound is a discriminant and we are within the
6308 -- record declaration, it is a use of the discriminant in a
6309 -- constraint of a component, and nothing can be checked
6310 -- here. The check will be emitted within the init proc.
6311 -- Before then, the discriminal has no real meaning.
6312 -- Similarly, if the entity is a discriminal, there is no
6313 -- check to perform yet.
6315 -- The same holds within a discriminated synchronized type,
6316 -- where the discriminant may constrain a component or an
6319 if Nkind (LB) = N_Identifier
6320 and then Denotes_Discriminant (LB, True)
6322 if Current_Scope = Scope (Entity (LB))
6323 or else Is_Concurrent_Type (Current_Scope)
6324 or else Ekind (Entity (LB)) /= E_Discriminant
6329 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
6333 if Nkind (HB) = N_Identifier
6334 and then Denotes_Discriminant (HB, True)
6336 if Current_Scope = Scope (Entity (HB))
6337 or else Is_Concurrent_Type (Current_Scope)
6338 or else Ekind (Entity (HB)) /= E_Discriminant
6343 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
6347 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
6348 Set_Paren_Count (Cond, 1);
6354 Left_Opnd => Duplicate_Subexpr_No_Checks (HB),
6355 Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
6356 Right_Opnd => Cond);
6361 elsif Is_Scalar_Type (S_Typ) then
6363 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
6364 -- except the above simply sets a flag in the node and lets
6365 -- gigi generate the check base on the Etype of the expression.
6366 -- Sometimes, however we want to do a dynamic check against an
6367 -- arbitrary target type, so we do that here.
6369 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
6370 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6372 -- For literals, we can tell if the constraint error will be
6373 -- raised at compile time, so we never need a dynamic check, but
6374 -- if the exception will be raised, then post the usual warning,
6375 -- and replace the literal with a raise constraint error
6376 -- expression. As usual, skip this for access types
6378 elsif Compile_Time_Known_Value (Ck_Node)
6379 and then not Do_Access
6382 LB : constant Node_Id := Type_Low_Bound (T_Typ);
6383 UB : constant Node_Id := Type_High_Bound (T_Typ);
6385 Out_Of_Range : Boolean;
6386 Static_Bounds : constant Boolean :=
6387 Compile_Time_Known_Value (LB)
6388 and Compile_Time_Known_Value (UB);
6391 -- Following range tests should use Sem_Eval routine ???
6393 if Static_Bounds then
6394 if Is_Floating_Point_Type (S_Typ) then
6396 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
6398 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
6400 else -- fixed or discrete type
6402 Expr_Value (Ck_Node) < Expr_Value (LB)
6404 Expr_Value (Ck_Node) > Expr_Value (UB);
6407 -- Bounds of the type are static and the literal is
6408 -- out of range so make a warning message.
6410 if Out_Of_Range then
6411 if No (Warn_Node) then
6413 (Compile_Time_Constraint_Error
6415 "static value out of range of}?", T_Typ));
6419 (Compile_Time_Constraint_Error
6421 "static value out of range of}?", T_Typ));
6426 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6430 -- Here for the case of a non-static expression, we need a runtime
6431 -- check unless the source type range is guaranteed to be in the
6432 -- range of the target type.
6435 if not In_Subrange_Of (S_Typ, T_Typ) then
6436 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
6441 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
6442 if Is_Constrained (T_Typ) then
6444 Expr_Actual := Get_Referenced_Object (Ck_Node);
6445 Exptyp := Get_Actual_Subtype (Expr_Actual);
6447 if Is_Access_Type (Exptyp) then
6448 Exptyp := Designated_Type (Exptyp);
6451 -- String_Literal case. This needs to be handled specially be-
6452 -- cause no index types are available for string literals. The
6453 -- condition is simply:
6455 -- T_Typ'Length = string-literal-length
6457 if Nkind (Expr_Actual) = N_String_Literal then
6460 -- General array case. Here we have a usable actual subtype for
6461 -- the expression, and the condition is built from the two types
6463 -- T_Typ'First < Exptyp'First or else
6464 -- T_Typ'Last > Exptyp'Last or else
6465 -- T_Typ'First(1) < Exptyp'First(1) or else
6466 -- T_Typ'Last(1) > Exptyp'Last(1) or else
6469 elsif Is_Constrained (Exptyp) then
6471 Ndims : constant Nat := Number_Dimensions (T_Typ);
6481 L_Index := First_Index (T_Typ);
6482 R_Index := First_Index (Exptyp);
6484 for Indx in 1 .. Ndims loop
6485 if not (Nkind (L_Index) = N_Raise_Constraint_Error
6487 Nkind (R_Index) = N_Raise_Constraint_Error)
6489 Get_Index_Bounds (L_Index, L_Low, L_High);
6490 Get_Index_Bounds (R_Index, R_Low, R_High);
6492 -- Deal with compile time length check. Note that we
6493 -- skip this in the access case, because the access
6494 -- value may be null, so we cannot know statically.
6497 Subtypes_Statically_Match
6498 (Etype (L_Index), Etype (R_Index))
6500 -- If the target type is constrained then we
6501 -- have to check for exact equality of bounds
6502 -- (required for qualified expressions).
6504 if Is_Constrained (T_Typ) then
6507 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
6511 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
6522 -- Handle cases where we do not get a usable actual subtype that
6523 -- is constrained. This happens for example in the function call
6524 -- and explicit dereference cases. In these cases, we have to get
6525 -- the length or range from the expression itself, making sure we
6526 -- do not evaluate it more than once.
6528 -- Here Ck_Node is the original expression, or more properly the
6529 -- result of applying Duplicate_Expr to the original tree,
6530 -- forcing the result to be a name.
6534 Ndims : constant Nat := Number_Dimensions (T_Typ);
6537 -- Build the condition for the explicit dereference case
6539 for Indx in 1 .. Ndims loop
6541 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
6548 -- For a conversion to an unconstrained array type, generate an
6549 -- Action to check that the bounds of the source value are within
6550 -- the constraints imposed by the target type (RM 4.6(38)). No
6551 -- check is needed for a conversion to an access to unconstrained
6552 -- array type, as 4.6(24.15/2) requires the designated subtypes
6553 -- of the two access types to statically match.
6555 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
6556 and then not Do_Access
6559 Opnd_Index : Node_Id;
6560 Targ_Index : Node_Id;
6561 Opnd_Range : Node_Id;
6564 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
6565 Targ_Index := First_Index (T_Typ);
6567 while Present (Opnd_Index) loop
6569 -- If the index is a range, use its bounds. If it is an
6570 -- entity (as will be the case if it is a named subtype
6571 -- or an itype created for a slice) retrieve its range.
6573 if Is_Entity_Name (Opnd_Index)
6574 and then Is_Type (Entity (Opnd_Index))
6576 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
6578 Opnd_Range := Opnd_Index;
6581 if Nkind (Opnd_Range) = N_Range then
6583 (Low_Bound (Opnd_Range), Etype (Targ_Index))
6586 (High_Bound (Opnd_Range), Etype (Targ_Index))
6590 -- If null range, no check needed
6593 Compile_Time_Known_Value (High_Bound (Opnd_Range))
6595 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
6597 Expr_Value (High_Bound (Opnd_Range)) <
6598 Expr_Value (Low_Bound (Opnd_Range))
6602 elsif Is_Out_Of_Range
6603 (Low_Bound (Opnd_Range), Etype (Targ_Index))
6606 (High_Bound (Opnd_Range), Etype (Targ_Index))
6609 (Compile_Time_Constraint_Error
6610 (Wnode, "value out of range of}?", T_Typ));
6616 (Opnd_Range, Etype (Targ_Index)));
6620 Next_Index (Opnd_Index);
6621 Next_Index (Targ_Index);
6628 -- Construct the test and insert into the tree
6630 if Present (Cond) then
6632 Cond := Guard_Access (Cond, Loc, Ck_Node);
6636 (Make_Raise_Constraint_Error (Loc,
6638 Reason => CE_Range_Check_Failed));
6642 end Selected_Range_Checks;
6644 -------------------------------
6645 -- Storage_Checks_Suppressed --
6646 -------------------------------
6648 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
6650 if Present (E) and then Checks_May_Be_Suppressed (E) then
6651 return Is_Check_Suppressed (E, Storage_Check);
6653 return Scope_Suppress (Storage_Check);
6655 end Storage_Checks_Suppressed;
6657 ---------------------------
6658 -- Tag_Checks_Suppressed --
6659 ---------------------------
6661 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
6664 if Kill_Tag_Checks (E) then
6666 elsif Checks_May_Be_Suppressed (E) then
6667 return Is_Check_Suppressed (E, Tag_Check);
6671 return Scope_Suppress (Tag_Check);
6672 end Tag_Checks_Suppressed;
6674 --------------------------
6675 -- Validity_Check_Range --
6676 --------------------------
6678 procedure Validity_Check_Range (N : Node_Id) is
6680 if Validity_Checks_On and Validity_Check_Operands then
6681 if Nkind (N) = N_Range then
6682 Ensure_Valid (Low_Bound (N));
6683 Ensure_Valid (High_Bound (N));
6686 end Validity_Check_Range;
6688 --------------------------------
6689 -- Validity_Checks_Suppressed --
6690 --------------------------------
6692 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
6694 if Present (E) and then Checks_May_Be_Suppressed (E) then
6695 return Is_Check_Suppressed (E, Validity_Check);
6697 return Scope_Suppress (Validity_Check);
6699 end Validity_Checks_Suppressed;