Fix failure when -fno-rtti test is run in C++17 or later
[official-gcc.git] / gcc / ada / checks.adb
blob1704a2f81f2a31a7a7e444b5c810aa2221cf5919
1 ------------------------------------------------------------------------------
2 -- --
3 -- GNAT COMPILER COMPONENTS --
4 -- --
5 -- C H E C K S --
6 -- --
7 -- B o d y --
8 -- --
9 -- Copyright (C) 1992-2018, Free Software Foundation, Inc. --
10 -- --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 3, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING3. If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license. --
20 -- --
21 -- GNAT was originally developed by the GNAT team at New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc. --
23 -- --
24 ------------------------------------------------------------------------------
26 with Atree; use Atree;
27 with Casing; use Casing;
28 with Debug; use Debug;
29 with Einfo; use Einfo;
30 with Elists; use Elists;
31 with Eval_Fat; use Eval_Fat;
32 with Exp_Ch11; use Exp_Ch11;
33 with Exp_Ch2; use Exp_Ch2;
34 with Exp_Ch4; use Exp_Ch4;
35 with Exp_Pakd; use Exp_Pakd;
36 with Exp_Util; use Exp_Util;
37 with Expander; use Expander;
38 with Freeze; use Freeze;
39 with Lib; use Lib;
40 with Nlists; use Nlists;
41 with Nmake; use Nmake;
42 with Opt; use Opt;
43 with Output; use Output;
44 with Restrict; use Restrict;
45 with Rident; use Rident;
46 with Rtsfind; use Rtsfind;
47 with Sem; use Sem;
48 with Sem_Aux; use Sem_Aux;
49 with Sem_Ch3; use Sem_Ch3;
50 with Sem_Ch8; use Sem_Ch8;
51 with Sem_Disp; use Sem_Disp;
52 with Sem_Eval; use Sem_Eval;
53 with Sem_Res; use Sem_Res;
54 with Sem_Util; use Sem_Util;
55 with Sem_Warn; use Sem_Warn;
56 with Sinfo; use Sinfo;
57 with Sinput; use Sinput;
58 with Snames; use Snames;
59 with Sprint; use Sprint;
60 with Stand; use Stand;
61 with Stringt; use Stringt;
62 with Targparm; use Targparm;
63 with Tbuild; use Tbuild;
64 with Ttypes; use Ttypes;
65 with Validsw; use Validsw;
67 package body Checks is
69 -- General note: many of these routines are concerned with generating
70 -- checking code to make sure that constraint error is raised at runtime.
71 -- Clearly this code is only needed if the expander is active, since
72 -- otherwise we will not be generating code or going into the runtime
73 -- execution anyway.
75 -- We therefore disconnect most of these checks if the expander is
76 -- inactive. This has the additional benefit that we do not need to
77 -- worry about the tree being messed up by previous errors (since errors
78 -- turn off expansion anyway).
80 -- There are a few exceptions to the above rule. For instance routines
81 -- such as Apply_Scalar_Range_Check that do not insert any code can be
82 -- safely called even when the Expander is inactive (but Errors_Detected
83 -- is 0). The benefit of executing this code when expansion is off, is
84 -- the ability to emit constraint error warning for static expressions
85 -- even when we are not generating code.
87 -- The above is modified in gnatprove mode to ensure that proper check
88 -- flags are always placed, even if expansion is off.
90 -------------------------------------
91 -- Suppression of Redundant Checks --
92 -------------------------------------
94 -- This unit implements a limited circuit for removal of redundant
95 -- checks. The processing is based on a tracing of simple sequential
96 -- flow. For any sequence of statements, we save expressions that are
97 -- marked to be checked, and then if the same expression appears later
98 -- with the same check, then under certain circumstances, the second
99 -- check can be suppressed.
101 -- Basically, we can suppress the check if we know for certain that
102 -- the previous expression has been elaborated (together with its
103 -- check), and we know that the exception frame is the same, and that
104 -- nothing has happened to change the result of the exception.
106 -- Let us examine each of these three conditions in turn to describe
107 -- how we ensure that this condition is met.
109 -- First, we need to know for certain that the previous expression has
110 -- been executed. This is done principally by the mechanism of calling
111 -- Conditional_Statements_Begin at the start of any statement sequence
112 -- and Conditional_Statements_End at the end. The End call causes all
113 -- checks remembered since the Begin call to be discarded. This does
114 -- miss a few cases, notably the case of a nested BEGIN-END block with
115 -- no exception handlers. But the important thing is to be conservative.
116 -- The other protection is that all checks are discarded if a label
117 -- is encountered, since then the assumption of sequential execution
118 -- is violated, and we don't know enough about the flow.
120 -- Second, we need to know that the exception frame is the same. We
121 -- do this by killing all remembered checks when we enter a new frame.
122 -- Again, that's over-conservative, but generally the cases we can help
123 -- with are pretty local anyway (like the body of a loop for example).
125 -- Third, we must be sure to forget any checks which are no longer valid.
126 -- This is done by two mechanisms, first the Kill_Checks_Variable call is
127 -- used to note any changes to local variables. We only attempt to deal
128 -- with checks involving local variables, so we do not need to worry
129 -- about global variables. Second, a call to any non-global procedure
130 -- causes us to abandon all stored checks, since such a all may affect
131 -- the values of any local variables.
133 -- The following define the data structures used to deal with remembering
134 -- checks so that redundant checks can be eliminated as described above.
136 -- Right now, the only expressions that we deal with are of the form of
137 -- simple local objects (either declared locally, or IN parameters) or
138 -- such objects plus/minus a compile time known constant. We can do
139 -- more later on if it seems worthwhile, but this catches many simple
140 -- cases in practice.
142 -- The following record type reflects a single saved check. An entry
143 -- is made in the stack of saved checks if and only if the expression
144 -- has been elaborated with the indicated checks.
146 type Saved_Check is record
147 Killed : Boolean;
148 -- Set True if entry is killed by Kill_Checks
150 Entity : Entity_Id;
151 -- The entity involved in the expression that is checked
153 Offset : Uint;
154 -- A compile time value indicating the result of adding or
155 -- subtracting a compile time value. This value is to be
156 -- added to the value of the Entity. A value of zero is
157 -- used for the case of a simple entity reference.
159 Check_Type : Character;
160 -- This is set to 'R' for a range check (in which case Target_Type
161 -- is set to the target type for the range check) or to 'O' for an
162 -- overflow check (in which case Target_Type is set to Empty).
164 Target_Type : Entity_Id;
165 -- Used only if Do_Range_Check is set. Records the target type for
166 -- the check. We need this, because a check is a duplicate only if
167 -- it has the same target type (or more accurately one with a
168 -- range that is smaller or equal to the stored target type of a
169 -- saved check).
170 end record;
172 -- The following table keeps track of saved checks. Rather than use an
173 -- extensible table, we just use a table of fixed size, and we discard
174 -- any saved checks that do not fit. That's very unlikely to happen and
175 -- this is only an optimization in any case.
177 Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
178 -- Array of saved checks
180 Num_Saved_Checks : Nat := 0;
181 -- Number of saved checks
183 -- The following stack keeps track of statement ranges. It is treated
184 -- as a stack. When Conditional_Statements_Begin is called, an entry
185 -- is pushed onto this stack containing the value of Num_Saved_Checks
186 -- at the time of the call. Then when Conditional_Statements_End is
187 -- called, this value is popped off and used to reset Num_Saved_Checks.
189 -- Note: again, this is a fixed length stack with a size that should
190 -- always be fine. If the value of the stack pointer goes above the
191 -- limit, then we just forget all saved checks.
193 Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
194 Saved_Checks_TOS : Nat := 0;
196 -----------------------
197 -- Local Subprograms --
198 -----------------------
200 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id);
201 -- Used to apply arithmetic overflow checks for all cases except operators
202 -- on signed arithmetic types in MINIMIZED/ELIMINATED case (for which we
203 -- call Apply_Arithmetic_Overflow_Minimized_Eliminated below). N can be a
204 -- signed integer arithmetic operator (but not an if or case expression).
205 -- It is also called for types other than signed integers.
207 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id);
208 -- Used to apply arithmetic overflow checks for the case where the overflow
209 -- checking mode is MINIMIZED or ELIMINATED and we have a signed integer
210 -- arithmetic op (which includes the case of if and case expressions). Note
211 -- that Do_Overflow_Check may or may not be set for node Op. In these modes
212 -- we have work to do even if overflow checking is suppressed.
214 procedure Apply_Division_Check
215 (N : Node_Id;
216 Rlo : Uint;
217 Rhi : Uint;
218 ROK : Boolean);
219 -- N is an N_Op_Div, N_Op_Rem, or N_Op_Mod node. This routine applies
220 -- division checks as required if the Do_Division_Check flag is set.
221 -- Rlo and Rhi give the possible range of the right operand, these values
222 -- can be referenced and trusted only if ROK is set True.
224 procedure Apply_Float_Conversion_Check
225 (Ck_Node : Node_Id;
226 Target_Typ : Entity_Id);
227 -- The checks on a conversion from a floating-point type to an integer
228 -- type are delicate. They have to be performed before conversion, they
229 -- have to raise an exception when the operand is a NaN, and rounding must
230 -- be taken into account to determine the safe bounds of the operand.
232 procedure Apply_Selected_Length_Checks
233 (Ck_Node : Node_Id;
234 Target_Typ : Entity_Id;
235 Source_Typ : Entity_Id;
236 Do_Static : Boolean);
237 -- This is the subprogram that does all the work for Apply_Length_Check
238 -- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
239 -- described for the above routines. The Do_Static flag indicates that
240 -- only a static check is to be done.
242 procedure Apply_Selected_Range_Checks
243 (Ck_Node : Node_Id;
244 Target_Typ : Entity_Id;
245 Source_Typ : Entity_Id;
246 Do_Static : Boolean);
247 -- This is the subprogram that does all the work for Apply_Range_Check.
248 -- Expr, Target_Typ and Source_Typ are as described for the above
249 -- routine. The Do_Static flag indicates that only a static check is
250 -- to be done.
252 type Check_Type is new Check_Id range Access_Check .. Division_Check;
253 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
254 -- This function is used to see if an access or division by zero check is
255 -- needed. The check is to be applied to a single variable appearing in the
256 -- source, and N is the node for the reference. If N is not of this form,
257 -- True is returned with no further processing. If N is of the right form,
258 -- then further processing determines if the given Check is needed.
260 -- The particular circuit is to see if we have the case of a check that is
261 -- not needed because it appears in the right operand of a short circuited
262 -- conditional where the left operand guards the check. For example:
264 -- if Var = 0 or else Q / Var > 12 then
265 -- ...
266 -- end if;
268 -- In this example, the division check is not required. At the same time
269 -- we can issue warnings for suspicious use of non-short-circuited forms,
270 -- such as:
272 -- if Var = 0 or Q / Var > 12 then
273 -- ...
274 -- end if;
276 procedure Find_Check
277 (Expr : Node_Id;
278 Check_Type : Character;
279 Target_Type : Entity_Id;
280 Entry_OK : out Boolean;
281 Check_Num : out Nat;
282 Ent : out Entity_Id;
283 Ofs : out Uint);
284 -- This routine is used by Enable_Range_Check and Enable_Overflow_Check
285 -- to see if a check is of the form for optimization, and if so, to see
286 -- if it has already been performed. Expr is the expression to check,
287 -- and Check_Type is 'R' for a range check, 'O' for an overflow check.
288 -- Target_Type is the target type for a range check, and Empty for an
289 -- overflow check. If the entry is not of the form for optimization,
290 -- then Entry_OK is set to False, and the remaining out parameters
291 -- are undefined. If the entry is OK, then Ent/Ofs are set to the
292 -- entity and offset from the expression. Check_Num is the number of
293 -- a matching saved entry in Saved_Checks, or zero if no such entry
294 -- is located.
296 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
297 -- If a discriminal is used in constraining a prival, Return reference
298 -- to the discriminal of the protected body (which renames the parameter
299 -- of the enclosing protected operation). This clumsy transformation is
300 -- needed because privals are created too late and their actual subtypes
301 -- are not available when analysing the bodies of the protected operations.
302 -- This function is called whenever the bound is an entity and the scope
303 -- indicates a protected operation. If the bound is an in-parameter of
304 -- a protected operation that is not a prival, the function returns the
305 -- bound itself.
306 -- To be cleaned up???
308 function Guard_Access
309 (Cond : Node_Id;
310 Loc : Source_Ptr;
311 Ck_Node : Node_Id) return Node_Id;
312 -- In the access type case, guard the test with a test to ensure
313 -- that the access value is non-null, since the checks do not
314 -- not apply to null access values.
316 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
317 -- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
318 -- Constraint_Error node.
320 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean;
321 -- Returns True if node N is for an arithmetic operation with signed
322 -- integer operands. This includes unary and binary operators, and also
323 -- if and case expression nodes where the dependent expressions are of
324 -- a signed integer type. These are the kinds of nodes for which special
325 -- handling applies in MINIMIZED or ELIMINATED overflow checking mode.
327 function Range_Or_Validity_Checks_Suppressed
328 (Expr : Node_Id) return Boolean;
329 -- Returns True if either range or validity checks or both are suppressed
330 -- for the type of the given expression, or, if the expression is the name
331 -- of an entity, if these checks are suppressed for the entity.
333 function Selected_Length_Checks
334 (Ck_Node : Node_Id;
335 Target_Typ : Entity_Id;
336 Source_Typ : Entity_Id;
337 Warn_Node : Node_Id) return Check_Result;
338 -- Like Apply_Selected_Length_Checks, except it doesn't modify
339 -- anything, just returns a list of nodes as described in the spec of
340 -- this package for the Range_Check function.
341 -- ??? In fact it does construct the test and insert it into the tree,
342 -- and insert actions in various ways (calling Insert_Action directly
343 -- in particular) so we do not call it in GNATprove mode, contrary to
344 -- Selected_Range_Checks.
346 function Selected_Range_Checks
347 (Ck_Node : Node_Id;
348 Target_Typ : Entity_Id;
349 Source_Typ : Entity_Id;
350 Warn_Node : Node_Id) return Check_Result;
351 -- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
352 -- just returns a list of nodes as described in the spec of this package
353 -- for the Range_Check function.
355 ------------------------------
356 -- Access_Checks_Suppressed --
357 ------------------------------
359 function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
360 begin
361 if Present (E) and then Checks_May_Be_Suppressed (E) then
362 return Is_Check_Suppressed (E, Access_Check);
363 else
364 return Scope_Suppress.Suppress (Access_Check);
365 end if;
366 end Access_Checks_Suppressed;
368 -------------------------------------
369 -- Accessibility_Checks_Suppressed --
370 -------------------------------------
372 function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
373 begin
374 if Present (E) and then Checks_May_Be_Suppressed (E) then
375 return Is_Check_Suppressed (E, Accessibility_Check);
376 else
377 return Scope_Suppress.Suppress (Accessibility_Check);
378 end if;
379 end Accessibility_Checks_Suppressed;
381 -----------------------------
382 -- Activate_Division_Check --
383 -----------------------------
385 procedure Activate_Division_Check (N : Node_Id) is
386 begin
387 Set_Do_Division_Check (N, True);
388 Possible_Local_Raise (N, Standard_Constraint_Error);
389 end Activate_Division_Check;
391 -----------------------------
392 -- Activate_Overflow_Check --
393 -----------------------------
395 procedure Activate_Overflow_Check (N : Node_Id) is
396 Typ : constant Entity_Id := Etype (N);
398 begin
399 -- Floating-point case. If Etype is not set (this can happen when we
400 -- activate a check on a node that has not yet been analyzed), then
401 -- we assume we do not have a floating-point type (as per our spec).
403 if Present (Typ) and then Is_Floating_Point_Type (Typ) then
405 -- Ignore call if we have no automatic overflow checks on the target
406 -- and Check_Float_Overflow mode is not set. These are the cases in
407 -- which we expect to generate infinities and NaN's with no check.
409 if not (Machine_Overflows_On_Target or Check_Float_Overflow) then
410 return;
412 -- Ignore for unary operations ("+", "-", abs) since these can never
413 -- result in overflow for floating-point cases.
415 elsif Nkind (N) in N_Unary_Op then
416 return;
418 -- Otherwise we will set the flag
420 else
421 null;
422 end if;
424 -- Discrete case
426 else
427 -- Nothing to do for Rem/Mod/Plus (overflow not possible, the check
428 -- for zero-divide is a divide check, not an overflow check).
430 if Nkind_In (N, N_Op_Rem, N_Op_Mod, N_Op_Plus) then
431 return;
432 end if;
433 end if;
435 -- Fall through for cases where we do set the flag
437 Set_Do_Overflow_Check (N, True);
438 Possible_Local_Raise (N, Standard_Constraint_Error);
439 end Activate_Overflow_Check;
441 --------------------------
442 -- Activate_Range_Check --
443 --------------------------
445 procedure Activate_Range_Check (N : Node_Id) is
446 begin
447 Set_Do_Range_Check (N, True);
448 Possible_Local_Raise (N, Standard_Constraint_Error);
449 end Activate_Range_Check;
451 ---------------------------------
452 -- Alignment_Checks_Suppressed --
453 ---------------------------------
455 function Alignment_Checks_Suppressed (E : Entity_Id) return Boolean is
456 begin
457 if Present (E) and then Checks_May_Be_Suppressed (E) then
458 return Is_Check_Suppressed (E, Alignment_Check);
459 else
460 return Scope_Suppress.Suppress (Alignment_Check);
461 end if;
462 end Alignment_Checks_Suppressed;
464 ----------------------------------
465 -- Allocation_Checks_Suppressed --
466 ----------------------------------
468 -- Note: at the current time there are no calls to this function, because
469 -- the relevant check is in the run-time, so it is not a check that the
470 -- compiler can suppress anyway, but we still have to recognize the check
471 -- name Allocation_Check since it is part of the standard.
473 function Allocation_Checks_Suppressed (E : Entity_Id) return Boolean is
474 begin
475 if Present (E) and then Checks_May_Be_Suppressed (E) then
476 return Is_Check_Suppressed (E, Allocation_Check);
477 else
478 return Scope_Suppress.Suppress (Allocation_Check);
479 end if;
480 end Allocation_Checks_Suppressed;
482 -------------------------
483 -- Append_Range_Checks --
484 -------------------------
486 procedure Append_Range_Checks
487 (Checks : Check_Result;
488 Stmts : List_Id;
489 Suppress_Typ : Entity_Id;
490 Static_Sloc : Source_Ptr;
491 Flag_Node : Node_Id)
493 Checks_On : constant Boolean :=
494 not Index_Checks_Suppressed (Suppress_Typ)
495 or else
496 not Range_Checks_Suppressed (Suppress_Typ);
498 Internal_Flag_Node : constant Node_Id := Flag_Node;
499 Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
501 begin
502 -- For now we just return if Checks_On is false, however this should be
503 -- enhanced to check for an always True value in the condition and to
504 -- generate a compilation warning???
506 if not Checks_On then
507 return;
508 end if;
510 for J in 1 .. 2 loop
511 exit when No (Checks (J));
513 if Nkind (Checks (J)) = N_Raise_Constraint_Error
514 and then Present (Condition (Checks (J)))
515 then
516 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
517 Append_To (Stmts, Checks (J));
518 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
519 end if;
521 else
522 Append_To
523 (Stmts,
524 Make_Raise_Constraint_Error (Internal_Static_Sloc,
525 Reason => CE_Range_Check_Failed));
526 end if;
527 end loop;
528 end Append_Range_Checks;
530 ------------------------
531 -- Apply_Access_Check --
532 ------------------------
534 procedure Apply_Access_Check (N : Node_Id) is
535 P : constant Node_Id := Prefix (N);
537 begin
538 -- We do not need checks if we are not generating code (i.e. the
539 -- expander is not active). This is not just an optimization, there
540 -- are cases (e.g. with pragma Debug) where generating the checks
541 -- can cause real trouble).
543 if not Expander_Active then
544 return;
545 end if;
547 -- No check if short circuiting makes check unnecessary
549 if not Check_Needed (P, Access_Check) then
550 return;
551 end if;
553 -- No check if accessing the Offset_To_Top component of a dispatch
554 -- table. They are safe by construction.
556 if Tagged_Type_Expansion
557 and then Present (Etype (P))
558 and then RTU_Loaded (Ada_Tags)
559 and then RTE_Available (RE_Offset_To_Top_Ptr)
560 and then Etype (P) = RTE (RE_Offset_To_Top_Ptr)
561 then
562 return;
563 end if;
565 -- Otherwise go ahead and install the check
567 Install_Null_Excluding_Check (P);
568 end Apply_Access_Check;
570 -------------------------------
571 -- Apply_Accessibility_Check --
572 -------------------------------
574 procedure Apply_Accessibility_Check
575 (N : Node_Id;
576 Typ : Entity_Id;
577 Insert_Node : Node_Id)
579 Loc : constant Source_Ptr := Sloc (N);
580 Param_Ent : Entity_Id := Param_Entity (N);
581 Param_Level : Node_Id;
582 Type_Level : Node_Id;
584 begin
585 if Ada_Version >= Ada_2012
586 and then not Present (Param_Ent)
587 and then Is_Entity_Name (N)
588 and then Ekind_In (Entity (N), E_Constant, E_Variable)
589 and then Present (Effective_Extra_Accessibility (Entity (N)))
590 then
591 Param_Ent := Entity (N);
592 while Present (Renamed_Object (Param_Ent)) loop
594 -- Renamed_Object must return an Entity_Name here
595 -- because of preceding "Present (E_E_A (...))" test.
597 Param_Ent := Entity (Renamed_Object (Param_Ent));
598 end loop;
599 end if;
601 if Inside_A_Generic then
602 return;
604 -- Only apply the run-time check if the access parameter has an
605 -- associated extra access level parameter and when the level of the
606 -- type is less deep than the level of the access parameter, and
607 -- accessibility checks are not suppressed.
609 elsif Present (Param_Ent)
610 and then Present (Extra_Accessibility (Param_Ent))
611 and then UI_Gt (Object_Access_Level (N),
612 Deepest_Type_Access_Level (Typ))
613 and then not Accessibility_Checks_Suppressed (Param_Ent)
614 and then not Accessibility_Checks_Suppressed (Typ)
615 then
616 Param_Level :=
617 New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
619 Type_Level :=
620 Make_Integer_Literal (Loc, Deepest_Type_Access_Level (Typ));
622 -- Raise Program_Error if the accessibility level of the access
623 -- parameter is deeper than the level of the target access type.
625 Insert_Action (Insert_Node,
626 Make_Raise_Program_Error (Loc,
627 Condition =>
628 Make_Op_Gt (Loc,
629 Left_Opnd => Param_Level,
630 Right_Opnd => Type_Level),
631 Reason => PE_Accessibility_Check_Failed));
633 Analyze_And_Resolve (N);
634 end if;
635 end Apply_Accessibility_Check;
637 --------------------------------
638 -- Apply_Address_Clause_Check --
639 --------------------------------
641 procedure Apply_Address_Clause_Check (E : Entity_Id; N : Node_Id) is
642 pragma Assert (Nkind (N) = N_Freeze_Entity);
644 AC : constant Node_Id := Address_Clause (E);
645 Loc : constant Source_Ptr := Sloc (AC);
646 Typ : constant Entity_Id := Etype (E);
648 Expr : Node_Id;
649 -- Address expression (not necessarily the same as Aexp, for example
650 -- when Aexp is a reference to a constant, in which case Expr gets
651 -- reset to reference the value expression of the constant).
653 begin
654 -- See if alignment check needed. Note that we never need a check if the
655 -- maximum alignment is one, since the check will always succeed.
657 -- Note: we do not check for checks suppressed here, since that check
658 -- was done in Sem_Ch13 when the address clause was processed. We are
659 -- only called if checks were not suppressed. The reason for this is
660 -- that we have to delay the call to Apply_Alignment_Check till freeze
661 -- time (so that all types etc are elaborated), but we have to check
662 -- the status of check suppressing at the point of the address clause.
664 if No (AC)
665 or else not Check_Address_Alignment (AC)
666 or else Maximum_Alignment = 1
667 then
668 return;
669 end if;
671 -- Obtain expression from address clause
673 Expr := Address_Value (Expression (AC));
675 -- See if we know that Expr has an acceptable value at compile time. If
676 -- it hasn't or we don't know, we defer issuing the warning until the
677 -- end of the compilation to take into account back end annotations.
679 if Compile_Time_Known_Value (Expr)
680 and then (Known_Alignment (E) or else Known_Alignment (Typ))
681 then
682 declare
683 AL : Uint := Alignment (Typ);
685 begin
686 -- The object alignment might be more restrictive than the type
687 -- alignment.
689 if Known_Alignment (E) then
690 AL := Alignment (E);
691 end if;
693 if Expr_Value (Expr) mod AL = 0 then
694 return;
695 end if;
696 end;
698 -- If the expression has the form X'Address, then we can find out if the
699 -- object X has an alignment that is compatible with the object E. If it
700 -- hasn't or we don't know, we defer issuing the warning until the end
701 -- of the compilation to take into account back end annotations.
703 elsif Nkind (Expr) = N_Attribute_Reference
704 and then Attribute_Name (Expr) = Name_Address
705 and then
706 Has_Compatible_Alignment (E, Prefix (Expr), False) = Known_Compatible
707 then
708 return;
709 end if;
711 -- Here we do not know if the value is acceptable. Strictly we don't
712 -- have to do anything, since if the alignment is bad, we have an
713 -- erroneous program. However we are allowed to check for erroneous
714 -- conditions and we decide to do this by default if the check is not
715 -- suppressed.
717 -- However, don't do the check if elaboration code is unwanted
719 if Restriction_Active (No_Elaboration_Code) then
720 return;
722 -- Generate a check to raise PE if alignment may be inappropriate
724 else
725 -- If the original expression is a non-static constant, use the name
726 -- of the constant itself rather than duplicating its initialization
727 -- expression, which was extracted above.
729 -- Note: Expr is empty if the address-clause is applied to in-mode
730 -- actuals (allowed by 13.1(22)).
732 if not Present (Expr)
733 or else
734 (Is_Entity_Name (Expression (AC))
735 and then Ekind (Entity (Expression (AC))) = E_Constant
736 and then Nkind (Parent (Entity (Expression (AC)))) =
737 N_Object_Declaration)
738 then
739 Expr := New_Copy_Tree (Expression (AC));
740 else
741 Remove_Side_Effects (Expr);
742 end if;
744 if No (Actions (N)) then
745 Set_Actions (N, New_List);
746 end if;
748 Prepend_To (Actions (N),
749 Make_Raise_Program_Error (Loc,
750 Condition =>
751 Make_Op_Ne (Loc,
752 Left_Opnd =>
753 Make_Op_Mod (Loc,
754 Left_Opnd =>
755 Unchecked_Convert_To
756 (RTE (RE_Integer_Address), Expr),
757 Right_Opnd =>
758 Make_Attribute_Reference (Loc,
759 Prefix => New_Occurrence_Of (E, Loc),
760 Attribute_Name => Name_Alignment)),
761 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
762 Reason => PE_Misaligned_Address_Value));
764 Warning_Msg := No_Error_Msg;
765 Analyze (First (Actions (N)), Suppress => All_Checks);
767 -- If the above raise action generated a warning message (for example
768 -- from Warn_On_Non_Local_Exception mode with the active restriction
769 -- No_Exception_Propagation).
771 if Warning_Msg /= No_Error_Msg then
773 -- If the expression has a known at compile time value, then
774 -- once we know the alignment of the type, we can check if the
775 -- exception will be raised or not, and if not, we don't need
776 -- the warning so we will kill the warning later on.
778 if Compile_Time_Known_Value (Expr) then
779 Alignment_Warnings.Append
780 ((E => E, A => Expr_Value (Expr), W => Warning_Msg));
782 -- Add explanation of the warning generated by the check
784 else
785 Error_Msg_N
786 ("\address value may be incompatible with alignment of "
787 & "object?X?", AC);
788 end if;
789 end if;
791 return;
792 end if;
794 exception
796 -- If we have some missing run time component in configurable run time
797 -- mode then just skip the check (it is not required in any case).
799 when RE_Not_Available =>
800 return;
801 end Apply_Address_Clause_Check;
803 -------------------------------------
804 -- Apply_Arithmetic_Overflow_Check --
805 -------------------------------------
807 procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
808 begin
809 -- Use old routine in almost all cases (the only case we are treating
810 -- specially is the case of a signed integer arithmetic op with the
811 -- overflow checking mode set to MINIMIZED or ELIMINATED).
813 if Overflow_Check_Mode = Strict
814 or else not Is_Signed_Integer_Arithmetic_Op (N)
815 then
816 Apply_Arithmetic_Overflow_Strict (N);
818 -- Otherwise use the new routine for the case of a signed integer
819 -- arithmetic op, with Do_Overflow_Check set to True, and the checking
820 -- mode is MINIMIZED or ELIMINATED.
822 else
823 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
824 end if;
825 end Apply_Arithmetic_Overflow_Check;
827 --------------------------------------
828 -- Apply_Arithmetic_Overflow_Strict --
829 --------------------------------------
831 -- This routine is called only if the type is an integer type and an
832 -- arithmetic overflow check may be needed for op (add, subtract, or
833 -- multiply). This check is performed if Backend_Overflow_Checks_On_Target
834 -- is not enabled and Do_Overflow_Check is set. In this case we expand the
835 -- operation into a more complex sequence of tests that ensures that
836 -- overflow is properly caught.
838 -- This is used in CHECKED modes. It is identical to the code for this
839 -- cases before the big overflow earthquake, thus ensuring that in this
840 -- modes we have compatible behavior (and reliability) to what was there
841 -- before. It is also called for types other than signed integers, and if
842 -- the Do_Overflow_Check flag is off.
844 -- Note: we also call this routine if we decide in the MINIMIZED case
845 -- to give up and just generate an overflow check without any fuss.
847 procedure Apply_Arithmetic_Overflow_Strict (N : Node_Id) is
848 Loc : constant Source_Ptr := Sloc (N);
849 Typ : constant Entity_Id := Etype (N);
850 Rtyp : constant Entity_Id := Root_Type (Typ);
852 begin
853 -- Nothing to do if Do_Overflow_Check not set or overflow checks
854 -- suppressed.
856 if not Do_Overflow_Check (N) then
857 return;
858 end if;
860 -- An interesting special case. If the arithmetic operation appears as
861 -- the operand of a type conversion:
863 -- type1 (x op y)
865 -- and all the following conditions apply:
867 -- arithmetic operation is for a signed integer type
868 -- target type type1 is a static integer subtype
869 -- range of x and y are both included in the range of type1
870 -- range of x op y is included in the range of type1
871 -- size of type1 is at least twice the result size of op
873 -- then we don't do an overflow check in any case. Instead, we transform
874 -- the operation so that we end up with:
876 -- type1 (type1 (x) op type1 (y))
878 -- This avoids intermediate overflow before the conversion. It is
879 -- explicitly permitted by RM 3.5.4(24):
881 -- For the execution of a predefined operation of a signed integer
882 -- type, the implementation need not raise Constraint_Error if the
883 -- result is outside the base range of the type, so long as the
884 -- correct result is produced.
886 -- It's hard to imagine that any programmer counts on the exception
887 -- being raised in this case, and in any case it's wrong coding to
888 -- have this expectation, given the RM permission. Furthermore, other
889 -- Ada compilers do allow such out of range results.
891 -- Note that we do this transformation even if overflow checking is
892 -- off, since this is precisely about giving the "right" result and
893 -- avoiding the need for an overflow check.
895 -- Note: this circuit is partially redundant with respect to the similar
896 -- processing in Exp_Ch4.Expand_N_Type_Conversion, but the latter deals
897 -- with cases that do not come through here. We still need the following
898 -- processing even with the Exp_Ch4 code in place, since we want to be
899 -- sure not to generate the arithmetic overflow check in these cases
900 -- (Exp_Ch4 would have a hard time removing them once generated).
902 if Is_Signed_Integer_Type (Typ)
903 and then Nkind (Parent (N)) = N_Type_Conversion
904 then
905 Conversion_Optimization : declare
906 Target_Type : constant Entity_Id :=
907 Base_Type (Entity (Subtype_Mark (Parent (N))));
909 Llo, Lhi : Uint;
910 Rlo, Rhi : Uint;
911 LOK, ROK : Boolean;
913 Vlo : Uint;
914 Vhi : Uint;
915 VOK : Boolean;
917 Tlo : Uint;
918 Thi : Uint;
920 begin
921 if Is_Integer_Type (Target_Type)
922 and then RM_Size (Root_Type (Target_Type)) >= 2 * RM_Size (Rtyp)
923 then
924 Tlo := Expr_Value (Type_Low_Bound (Target_Type));
925 Thi := Expr_Value (Type_High_Bound (Target_Type));
927 Determine_Range
928 (Left_Opnd (N), LOK, Llo, Lhi, Assume_Valid => True);
929 Determine_Range
930 (Right_Opnd (N), ROK, Rlo, Rhi, Assume_Valid => True);
932 if (LOK and ROK)
933 and then Tlo <= Llo and then Lhi <= Thi
934 and then Tlo <= Rlo and then Rhi <= Thi
935 then
936 Determine_Range (N, VOK, Vlo, Vhi, Assume_Valid => True);
938 if VOK and then Tlo <= Vlo and then Vhi <= Thi then
939 Rewrite (Left_Opnd (N),
940 Make_Type_Conversion (Loc,
941 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
942 Expression => Relocate_Node (Left_Opnd (N))));
944 Rewrite (Right_Opnd (N),
945 Make_Type_Conversion (Loc,
946 Subtype_Mark => New_Occurrence_Of (Target_Type, Loc),
947 Expression => Relocate_Node (Right_Opnd (N))));
949 -- Rewrite the conversion operand so that the original
950 -- node is retained, in order to avoid the warning for
951 -- redundant conversions in Resolve_Type_Conversion.
953 Rewrite (N, Relocate_Node (N));
955 Set_Etype (N, Target_Type);
957 Analyze_And_Resolve (Left_Opnd (N), Target_Type);
958 Analyze_And_Resolve (Right_Opnd (N), Target_Type);
960 -- Given that the target type is twice the size of the
961 -- source type, overflow is now impossible, so we can
962 -- safely kill the overflow check and return.
964 Set_Do_Overflow_Check (N, False);
965 return;
966 end if;
967 end if;
968 end if;
969 end Conversion_Optimization;
970 end if;
972 -- Now see if an overflow check is required
974 declare
975 Siz : constant Int := UI_To_Int (Esize (Rtyp));
976 Dsiz : constant Int := Siz * 2;
977 Opnod : Node_Id;
978 Ctyp : Entity_Id;
979 Opnd : Node_Id;
980 Cent : RE_Id;
982 begin
983 -- Skip check if back end does overflow checks, or the overflow flag
984 -- is not set anyway, or we are not doing code expansion, or the
985 -- parent node is a type conversion whose operand is an arithmetic
986 -- operation on signed integers on which the expander can promote
987 -- later the operands to type Integer (see Expand_N_Type_Conversion).
989 if Backend_Overflow_Checks_On_Target
990 or else not Do_Overflow_Check (N)
991 or else not Expander_Active
992 or else (Present (Parent (N))
993 and then Nkind (Parent (N)) = N_Type_Conversion
994 and then Integer_Promotion_Possible (Parent (N)))
995 then
996 return;
997 end if;
999 -- Otherwise, generate the full general code for front end overflow
1000 -- detection, which works by doing arithmetic in a larger type:
1002 -- x op y
1004 -- is expanded into
1006 -- Typ (Checktyp (x) op Checktyp (y));
1008 -- where Typ is the type of the original expression, and Checktyp is
1009 -- an integer type of sufficient length to hold the largest possible
1010 -- result.
1012 -- If the size of check type exceeds the size of Long_Long_Integer,
1013 -- we use a different approach, expanding to:
1015 -- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
1017 -- where xxx is Add, Multiply or Subtract as appropriate
1019 -- Find check type if one exists
1021 if Dsiz <= Standard_Integer_Size then
1022 Ctyp := Standard_Integer;
1024 elsif Dsiz <= Standard_Long_Long_Integer_Size then
1025 Ctyp := Standard_Long_Long_Integer;
1027 -- No check type exists, use runtime call
1029 else
1030 if Nkind (N) = N_Op_Add then
1031 Cent := RE_Add_With_Ovflo_Check;
1033 elsif Nkind (N) = N_Op_Multiply then
1034 Cent := RE_Multiply_With_Ovflo_Check;
1036 else
1037 pragma Assert (Nkind (N) = N_Op_Subtract);
1038 Cent := RE_Subtract_With_Ovflo_Check;
1039 end if;
1041 Rewrite (N,
1042 OK_Convert_To (Typ,
1043 Make_Function_Call (Loc,
1044 Name => New_Occurrence_Of (RTE (Cent), Loc),
1045 Parameter_Associations => New_List (
1046 OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
1047 OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
1049 Analyze_And_Resolve (N, Typ);
1050 return;
1051 end if;
1053 -- If we fall through, we have the case where we do the arithmetic
1054 -- in the next higher type and get the check by conversion. In these
1055 -- cases Ctyp is set to the type to be used as the check type.
1057 Opnod := Relocate_Node (N);
1059 Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
1061 Analyze (Opnd);
1062 Set_Etype (Opnd, Ctyp);
1063 Set_Analyzed (Opnd, True);
1064 Set_Left_Opnd (Opnod, Opnd);
1066 Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
1068 Analyze (Opnd);
1069 Set_Etype (Opnd, Ctyp);
1070 Set_Analyzed (Opnd, True);
1071 Set_Right_Opnd (Opnod, Opnd);
1073 -- The type of the operation changes to the base type of the check
1074 -- type, and we reset the overflow check indication, since clearly no
1075 -- overflow is possible now that we are using a double length type.
1076 -- We also set the Analyzed flag to avoid a recursive attempt to
1077 -- expand the node.
1079 Set_Etype (Opnod, Base_Type (Ctyp));
1080 Set_Do_Overflow_Check (Opnod, False);
1081 Set_Analyzed (Opnod, True);
1083 -- Now build the outer conversion
1085 Opnd := OK_Convert_To (Typ, Opnod);
1086 Analyze (Opnd);
1087 Set_Etype (Opnd, Typ);
1089 -- In the discrete type case, we directly generate the range check
1090 -- for the outer operand. This range check will implement the
1091 -- required overflow check.
1093 if Is_Discrete_Type (Typ) then
1094 Rewrite (N, Opnd);
1095 Generate_Range_Check
1096 (Expression (N), Typ, CE_Overflow_Check_Failed);
1098 -- For other types, we enable overflow checking on the conversion,
1099 -- after setting the node as analyzed to prevent recursive attempts
1100 -- to expand the conversion node.
1102 else
1103 Set_Analyzed (Opnd, True);
1104 Enable_Overflow_Check (Opnd);
1105 Rewrite (N, Opnd);
1106 end if;
1108 exception
1109 when RE_Not_Available =>
1110 return;
1111 end;
1112 end Apply_Arithmetic_Overflow_Strict;
1114 ----------------------------------------------------
1115 -- Apply_Arithmetic_Overflow_Minimized_Eliminated --
1116 ----------------------------------------------------
1118 procedure Apply_Arithmetic_Overflow_Minimized_Eliminated (Op : Node_Id) is
1119 pragma Assert (Is_Signed_Integer_Arithmetic_Op (Op));
1121 Loc : constant Source_Ptr := Sloc (Op);
1122 P : constant Node_Id := Parent (Op);
1124 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
1125 -- Operands and results are of this type when we convert
1127 Result_Type : constant Entity_Id := Etype (Op);
1128 -- Original result type
1130 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1131 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
1133 Lo, Hi : Uint;
1134 -- Ranges of values for result
1136 begin
1137 -- Nothing to do if our parent is one of the following:
1139 -- Another signed integer arithmetic op
1140 -- A membership operation
1141 -- A comparison operation
1143 -- In all these cases, we will process at the higher level (and then
1144 -- this node will be processed during the downwards recursion that
1145 -- is part of the processing in Minimize_Eliminate_Overflows).
1147 if Is_Signed_Integer_Arithmetic_Op (P)
1148 or else Nkind (P) in N_Membership_Test
1149 or else Nkind (P) in N_Op_Compare
1151 -- This is also true for an alternative in a case expression
1153 or else Nkind (P) = N_Case_Expression_Alternative
1155 -- This is also true for a range operand in a membership test
1157 or else (Nkind (P) = N_Range
1158 and then Nkind (Parent (P)) in N_Membership_Test)
1159 then
1160 -- If_Expressions and Case_Expressions are treated as arithmetic
1161 -- ops, but if they appear in an assignment or similar contexts
1162 -- there is no overflow check that starts from that parent node,
1163 -- so apply check now.
1165 if Nkind_In (P, N_If_Expression, N_Case_Expression)
1166 and then not Is_Signed_Integer_Arithmetic_Op (Parent (P))
1167 then
1168 null;
1169 else
1170 return;
1171 end if;
1172 end if;
1174 -- Otherwise, we have a top level arithmetic operation node, and this
1175 -- is where we commence the special processing for MINIMIZED/ELIMINATED
1176 -- modes. This is the case where we tell the machinery not to move into
1177 -- Bignum mode at this top level (of course the top level operation
1178 -- will still be in Bignum mode if either of its operands are of type
1179 -- Bignum).
1181 Minimize_Eliminate_Overflows (Op, Lo, Hi, Top_Level => True);
1183 -- That call may but does not necessarily change the result type of Op.
1184 -- It is the job of this routine to undo such changes, so that at the
1185 -- top level, we have the proper type. This "undoing" is a point at
1186 -- which a final overflow check may be applied.
1188 -- If the result type was not fiddled we are all set. We go to base
1189 -- types here because things may have been rewritten to generate the
1190 -- base type of the operand types.
1192 if Base_Type (Etype (Op)) = Base_Type (Result_Type) then
1193 return;
1195 -- Bignum case
1197 elsif Is_RTE (Etype (Op), RE_Bignum) then
1199 -- We need a sequence that looks like:
1201 -- Rnn : Result_Type;
1203 -- declare
1204 -- M : Mark_Id := SS_Mark;
1205 -- begin
1206 -- Rnn := Long_Long_Integer'Base (From_Bignum (Op));
1207 -- SS_Release (M);
1208 -- end;
1210 -- This block is inserted (using Insert_Actions), and then the node
1211 -- is replaced with a reference to Rnn.
1213 -- If our parent is a conversion node then there is no point in
1214 -- generating a conversion to Result_Type. Instead, we let the parent
1215 -- handle this. Note that this special case is not just about
1216 -- optimization. Consider
1218 -- A,B,C : Integer;
1219 -- ...
1220 -- X := Long_Long_Integer'Base (A * (B ** C));
1222 -- Now the product may fit in Long_Long_Integer but not in Integer.
1223 -- In MINIMIZED/ELIMINATED mode, we don't want to introduce an
1224 -- overflow exception for this intermediate value.
1226 declare
1227 Blk : constant Node_Id := Make_Bignum_Block (Loc);
1228 Rnn : constant Entity_Id := Make_Temporary (Loc, 'R', Op);
1229 RHS : Node_Id;
1231 Rtype : Entity_Id;
1233 begin
1234 RHS := Convert_From_Bignum (Op);
1236 if Nkind (P) /= N_Type_Conversion then
1237 Convert_To_And_Rewrite (Result_Type, RHS);
1238 Rtype := Result_Type;
1240 -- Interesting question, do we need a check on that conversion
1241 -- operation. Answer, not if we know the result is in range.
1242 -- At the moment we are not taking advantage of this. To be
1243 -- looked at later ???
1245 else
1246 Rtype := LLIB;
1247 end if;
1249 Insert_Before
1250 (First (Statements (Handled_Statement_Sequence (Blk))),
1251 Make_Assignment_Statement (Loc,
1252 Name => New_Occurrence_Of (Rnn, Loc),
1253 Expression => RHS));
1255 Insert_Actions (Op, New_List (
1256 Make_Object_Declaration (Loc,
1257 Defining_Identifier => Rnn,
1258 Object_Definition => New_Occurrence_Of (Rtype, Loc)),
1259 Blk));
1261 Rewrite (Op, New_Occurrence_Of (Rnn, Loc));
1262 Analyze_And_Resolve (Op);
1263 end;
1265 -- Here we know the result is Long_Long_Integer'Base, or that it has
1266 -- been rewritten because the parent operation is a conversion. See
1267 -- Apply_Arithmetic_Overflow_Strict.Conversion_Optimization.
1269 else
1270 pragma Assert
1271 (Etype (Op) = LLIB or else Nkind (Parent (Op)) = N_Type_Conversion);
1273 -- All we need to do here is to convert the result to the proper
1274 -- result type. As explained above for the Bignum case, we can
1275 -- omit this if our parent is a type conversion.
1277 if Nkind (P) /= N_Type_Conversion then
1278 Convert_To_And_Rewrite (Result_Type, Op);
1279 end if;
1281 Analyze_And_Resolve (Op);
1282 end if;
1283 end Apply_Arithmetic_Overflow_Minimized_Eliminated;
1285 ----------------------------
1286 -- Apply_Constraint_Check --
1287 ----------------------------
1289 procedure Apply_Constraint_Check
1290 (N : Node_Id;
1291 Typ : Entity_Id;
1292 No_Sliding : Boolean := False)
1294 Desig_Typ : Entity_Id;
1296 begin
1297 -- No checks inside a generic (check the instantiations)
1299 if Inside_A_Generic then
1300 return;
1301 end if;
1303 -- Apply required constraint checks
1305 if Is_Scalar_Type (Typ) then
1306 Apply_Scalar_Range_Check (N, Typ);
1308 elsif Is_Array_Type (Typ) then
1310 -- A useful optimization: an aggregate with only an others clause
1311 -- always has the right bounds.
1313 if Nkind (N) = N_Aggregate
1314 and then No (Expressions (N))
1315 and then Nkind
1316 (First (Choices (First (Component_Associations (N)))))
1317 = N_Others_Choice
1318 then
1319 return;
1320 end if;
1322 if Is_Constrained (Typ) then
1323 Apply_Length_Check (N, Typ);
1325 if No_Sliding then
1326 Apply_Range_Check (N, Typ);
1327 end if;
1328 else
1329 Apply_Range_Check (N, Typ);
1330 end if;
1332 elsif (Is_Record_Type (Typ) or else Is_Private_Type (Typ))
1333 and then Has_Discriminants (Base_Type (Typ))
1334 and then Is_Constrained (Typ)
1335 then
1336 Apply_Discriminant_Check (N, Typ);
1338 elsif Is_Access_Type (Typ) then
1340 Desig_Typ := Designated_Type (Typ);
1342 -- No checks necessary if expression statically null
1344 if Known_Null (N) then
1345 if Can_Never_Be_Null (Typ) then
1346 Install_Null_Excluding_Check (N);
1347 end if;
1349 -- No sliding possible on access to arrays
1351 elsif Is_Array_Type (Desig_Typ) then
1352 if Is_Constrained (Desig_Typ) then
1353 Apply_Length_Check (N, Typ);
1354 end if;
1356 Apply_Range_Check (N, Typ);
1358 -- Do not install a discriminant check for a constrained subtype
1359 -- created for an unconstrained nominal type because the subtype
1360 -- has the correct constraints by construction.
1362 elsif Has_Discriminants (Base_Type (Desig_Typ))
1363 and then Is_Constrained (Desig_Typ)
1364 and then not Is_Constr_Subt_For_U_Nominal (Desig_Typ)
1365 then
1366 Apply_Discriminant_Check (N, Typ);
1367 end if;
1369 -- Apply the 2005 Null_Excluding check. Note that we do not apply
1370 -- this check if the constraint node is illegal, as shown by having
1371 -- an error posted. This additional guard prevents cascaded errors
1372 -- and compiler aborts on illegal programs involving Ada 2005 checks.
1374 if Can_Never_Be_Null (Typ)
1375 and then not Can_Never_Be_Null (Etype (N))
1376 and then not Error_Posted (N)
1377 then
1378 Install_Null_Excluding_Check (N);
1379 end if;
1380 end if;
1381 end Apply_Constraint_Check;
1383 ------------------------------
1384 -- Apply_Discriminant_Check --
1385 ------------------------------
1387 procedure Apply_Discriminant_Check
1388 (N : Node_Id;
1389 Typ : Entity_Id;
1390 Lhs : Node_Id := Empty)
1392 Loc : constant Source_Ptr := Sloc (N);
1393 Do_Access : constant Boolean := Is_Access_Type (Typ);
1394 S_Typ : Entity_Id := Etype (N);
1395 Cond : Node_Id;
1396 T_Typ : Entity_Id;
1398 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean;
1399 -- A heap object with an indefinite subtype is constrained by its
1400 -- initial value, and assigning to it requires a constraint_check.
1401 -- The target may be an explicit dereference, or a renaming of one.
1403 function Is_Aliased_Unconstrained_Component return Boolean;
1404 -- It is possible for an aliased component to have a nominal
1405 -- unconstrained subtype (through instantiation). If this is a
1406 -- discriminated component assigned in the expansion of an aggregate
1407 -- in an initialization, the check must be suppressed. This unusual
1408 -- situation requires a predicate of its own.
1410 ----------------------------------
1411 -- Denotes_Explicit_Dereference --
1412 ----------------------------------
1414 function Denotes_Explicit_Dereference (Obj : Node_Id) return Boolean is
1415 begin
1416 return
1417 Nkind (Obj) = N_Explicit_Dereference
1418 or else
1419 (Is_Entity_Name (Obj)
1420 and then Present (Renamed_Object (Entity (Obj)))
1421 and then Nkind (Renamed_Object (Entity (Obj))) =
1422 N_Explicit_Dereference);
1423 end Denotes_Explicit_Dereference;
1425 ----------------------------------------
1426 -- Is_Aliased_Unconstrained_Component --
1427 ----------------------------------------
1429 function Is_Aliased_Unconstrained_Component return Boolean is
1430 Comp : Entity_Id;
1431 Pref : Node_Id;
1433 begin
1434 if Nkind (Lhs) /= N_Selected_Component then
1435 return False;
1436 else
1437 Comp := Entity (Selector_Name (Lhs));
1438 Pref := Prefix (Lhs);
1439 end if;
1441 if Ekind (Comp) /= E_Component
1442 or else not Is_Aliased (Comp)
1443 then
1444 return False;
1445 end if;
1447 return not Comes_From_Source (Pref)
1448 and then In_Instance
1449 and then not Is_Constrained (Etype (Comp));
1450 end Is_Aliased_Unconstrained_Component;
1452 -- Start of processing for Apply_Discriminant_Check
1454 begin
1455 if Do_Access then
1456 T_Typ := Designated_Type (Typ);
1457 else
1458 T_Typ := Typ;
1459 end if;
1461 -- If the expression is a function call that returns a limited object
1462 -- it cannot be copied. It is not clear how to perform the proper
1463 -- discriminant check in this case because the discriminant value must
1464 -- be retrieved from the constructed object itself.
1466 if Nkind (N) = N_Function_Call
1467 and then Is_Limited_Type (Typ)
1468 and then Is_Entity_Name (Name (N))
1469 and then Returns_By_Ref (Entity (Name (N)))
1470 then
1471 return;
1472 end if;
1474 -- Only apply checks when generating code and discriminant checks are
1475 -- not suppressed. In GNATprove mode, we do not apply the checks, but we
1476 -- still analyze the expression to possibly issue errors on SPARK code
1477 -- when a run-time error can be detected at compile time.
1479 if not GNATprove_Mode then
1480 if not Expander_Active
1481 or else Discriminant_Checks_Suppressed (T_Typ)
1482 then
1483 return;
1484 end if;
1485 end if;
1487 -- No discriminant checks necessary for an access when expression is
1488 -- statically Null. This is not only an optimization, it is fundamental
1489 -- because otherwise discriminant checks may be generated in init procs
1490 -- for types containing an access to a not-yet-frozen record, causing a
1491 -- deadly forward reference.
1493 -- Also, if the expression is of an access type whose designated type is
1494 -- incomplete, then the access value must be null and we suppress the
1495 -- check.
1497 if Known_Null (N) then
1498 return;
1500 elsif Is_Access_Type (S_Typ) then
1501 S_Typ := Designated_Type (S_Typ);
1503 if Ekind (S_Typ) = E_Incomplete_Type then
1504 return;
1505 end if;
1506 end if;
1508 -- If an assignment target is present, then we need to generate the
1509 -- actual subtype if the target is a parameter or aliased object with
1510 -- an unconstrained nominal subtype.
1512 -- Ada 2005 (AI-363): For Ada 2005, we limit the building of the actual
1513 -- subtype to the parameter and dereference cases, since other aliased
1514 -- objects are unconstrained (unless the nominal subtype is explicitly
1515 -- constrained).
1517 if Present (Lhs)
1518 and then (Present (Param_Entity (Lhs))
1519 or else (Ada_Version < Ada_2005
1520 and then not Is_Constrained (T_Typ)
1521 and then Is_Aliased_View (Lhs)
1522 and then not Is_Aliased_Unconstrained_Component)
1523 or else (Ada_Version >= Ada_2005
1524 and then not Is_Constrained (T_Typ)
1525 and then Denotes_Explicit_Dereference (Lhs)
1526 and then Nkind (Original_Node (Lhs)) /=
1527 N_Function_Call))
1528 then
1529 T_Typ := Get_Actual_Subtype (Lhs);
1530 end if;
1532 -- Nothing to do if the type is unconstrained (this is the case where
1533 -- the actual subtype in the RM sense of N is unconstrained and no check
1534 -- is required).
1536 if not Is_Constrained (T_Typ) then
1537 return;
1539 -- Ada 2005: nothing to do if the type is one for which there is a
1540 -- partial view that is constrained.
1542 elsif Ada_Version >= Ada_2005
1543 and then Object_Type_Has_Constrained_Partial_View
1544 (Typ => Base_Type (T_Typ),
1545 Scop => Current_Scope)
1546 then
1547 return;
1548 end if;
1550 -- Nothing to do if the type is an Unchecked_Union
1552 if Is_Unchecked_Union (Base_Type (T_Typ)) then
1553 return;
1554 end if;
1556 -- Suppress checks if the subtypes are the same. The check must be
1557 -- preserved in an assignment to a formal, because the constraint is
1558 -- given by the actual.
1560 if Nkind (Original_Node (N)) /= N_Allocator
1561 and then (No (Lhs)
1562 or else not Is_Entity_Name (Lhs)
1563 or else No (Param_Entity (Lhs)))
1564 then
1565 if (Etype (N) = Typ
1566 or else (Do_Access and then Designated_Type (Typ) = S_Typ))
1567 and then not Is_Aliased_View (Lhs)
1568 then
1569 return;
1570 end if;
1572 -- We can also eliminate checks on allocators with a subtype mark that
1573 -- coincides with the context type. The context type may be a subtype
1574 -- without a constraint (common case, a generic actual).
1576 elsif Nkind (Original_Node (N)) = N_Allocator
1577 and then Is_Entity_Name (Expression (Original_Node (N)))
1578 then
1579 declare
1580 Alloc_Typ : constant Entity_Id :=
1581 Entity (Expression (Original_Node (N)));
1583 begin
1584 if Alloc_Typ = T_Typ
1585 or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
1586 and then Is_Entity_Name (
1587 Subtype_Indication (Parent (T_Typ)))
1588 and then Alloc_Typ = Base_Type (T_Typ))
1590 then
1591 return;
1592 end if;
1593 end;
1594 end if;
1596 -- See if we have a case where the types are both constrained, and all
1597 -- the constraints are constants. In this case, we can do the check
1598 -- successfully at compile time.
1600 -- We skip this check for the case where the node is rewritten as
1601 -- an allocator, because it already carries the context subtype,
1602 -- and extracting the discriminants from the aggregate is messy.
1604 if Is_Constrained (S_Typ)
1605 and then Nkind (Original_Node (N)) /= N_Allocator
1606 then
1607 declare
1608 DconT : Elmt_Id;
1609 Discr : Entity_Id;
1610 DconS : Elmt_Id;
1611 ItemS : Node_Id;
1612 ItemT : Node_Id;
1614 begin
1615 -- S_Typ may not have discriminants in the case where it is a
1616 -- private type completed by a default discriminated type. In that
1617 -- case, we need to get the constraints from the underlying type.
1618 -- If the underlying type is unconstrained (i.e. has no default
1619 -- discriminants) no check is needed.
1621 if Has_Discriminants (S_Typ) then
1622 Discr := First_Discriminant (S_Typ);
1623 DconS := First_Elmt (Discriminant_Constraint (S_Typ));
1625 else
1626 Discr := First_Discriminant (Underlying_Type (S_Typ));
1627 DconS :=
1628 First_Elmt
1629 (Discriminant_Constraint (Underlying_Type (S_Typ)));
1631 if No (DconS) then
1632 return;
1633 end if;
1635 -- A further optimization: if T_Typ is derived from S_Typ
1636 -- without imposing a constraint, no check is needed.
1638 if Nkind (Original_Node (Parent (T_Typ))) =
1639 N_Full_Type_Declaration
1640 then
1641 declare
1642 Type_Def : constant Node_Id :=
1643 Type_Definition (Original_Node (Parent (T_Typ)));
1644 begin
1645 if Nkind (Type_Def) = N_Derived_Type_Definition
1646 and then Is_Entity_Name (Subtype_Indication (Type_Def))
1647 and then Entity (Subtype_Indication (Type_Def)) = S_Typ
1648 then
1649 return;
1650 end if;
1651 end;
1652 end if;
1653 end if;
1655 -- Constraint may appear in full view of type
1657 if Ekind (T_Typ) = E_Private_Subtype
1658 and then Present (Full_View (T_Typ))
1659 then
1660 DconT :=
1661 First_Elmt (Discriminant_Constraint (Full_View (T_Typ)));
1662 else
1663 DconT :=
1664 First_Elmt (Discriminant_Constraint (T_Typ));
1665 end if;
1667 while Present (Discr) loop
1668 ItemS := Node (DconS);
1669 ItemT := Node (DconT);
1671 -- For a discriminated component type constrained by the
1672 -- current instance of an enclosing type, there is no
1673 -- applicable discriminant check.
1675 if Nkind (ItemT) = N_Attribute_Reference
1676 and then Is_Access_Type (Etype (ItemT))
1677 and then Is_Entity_Name (Prefix (ItemT))
1678 and then Is_Type (Entity (Prefix (ItemT)))
1679 then
1680 return;
1681 end if;
1683 -- If the expressions for the discriminants are identical
1684 -- and it is side-effect free (for now just an entity),
1685 -- this may be a shared constraint, e.g. from a subtype
1686 -- without a constraint introduced as a generic actual.
1687 -- Examine other discriminants if any.
1689 if ItemS = ItemT
1690 and then Is_Entity_Name (ItemS)
1691 then
1692 null;
1694 elsif not Is_OK_Static_Expression (ItemS)
1695 or else not Is_OK_Static_Expression (ItemT)
1696 then
1697 exit;
1699 elsif Expr_Value (ItemS) /= Expr_Value (ItemT) then
1700 if Do_Access then -- needs run-time check.
1701 exit;
1702 else
1703 Apply_Compile_Time_Constraint_Error
1704 (N, "incorrect value for discriminant&??",
1705 CE_Discriminant_Check_Failed, Ent => Discr);
1706 return;
1707 end if;
1708 end if;
1710 Next_Elmt (DconS);
1711 Next_Elmt (DconT);
1712 Next_Discriminant (Discr);
1713 end loop;
1715 if No (Discr) then
1716 return;
1717 end if;
1718 end;
1719 end if;
1721 -- In GNATprove mode, we do not apply the checks
1723 if GNATprove_Mode then
1724 return;
1725 end if;
1727 -- Here we need a discriminant check. First build the expression
1728 -- for the comparisons of the discriminants:
1730 -- (n.disc1 /= typ.disc1) or else
1731 -- (n.disc2 /= typ.disc2) or else
1732 -- ...
1733 -- (n.discn /= typ.discn)
1735 Cond := Build_Discriminant_Checks (N, T_Typ);
1737 -- If Lhs is set and is a parameter, then the condition is guarded by:
1738 -- lhs'constrained and then (condition built above)
1740 if Present (Param_Entity (Lhs)) then
1741 Cond :=
1742 Make_And_Then (Loc,
1743 Left_Opnd =>
1744 Make_Attribute_Reference (Loc,
1745 Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
1746 Attribute_Name => Name_Constrained),
1747 Right_Opnd => Cond);
1748 end if;
1750 if Do_Access then
1751 Cond := Guard_Access (Cond, Loc, N);
1752 end if;
1754 Insert_Action (N,
1755 Make_Raise_Constraint_Error (Loc,
1756 Condition => Cond,
1757 Reason => CE_Discriminant_Check_Failed));
1758 end Apply_Discriminant_Check;
1760 -------------------------
1761 -- Apply_Divide_Checks --
1762 -------------------------
1764 procedure Apply_Divide_Checks (N : Node_Id) is
1765 Loc : constant Source_Ptr := Sloc (N);
1766 Typ : constant Entity_Id := Etype (N);
1767 Left : constant Node_Id := Left_Opnd (N);
1768 Right : constant Node_Id := Right_Opnd (N);
1770 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
1771 -- Current overflow checking mode
1773 LLB : Uint;
1774 Llo : Uint;
1775 Lhi : Uint;
1776 LOK : Boolean;
1777 Rlo : Uint;
1778 Rhi : Uint;
1779 ROK : Boolean;
1781 pragma Warnings (Off, Lhi);
1782 -- Don't actually use this value
1784 begin
1785 -- If we are operating in MINIMIZED or ELIMINATED mode, and we are
1786 -- operating on signed integer types, then the only thing this routine
1787 -- does is to call Apply_Arithmetic_Overflow_Minimized_Eliminated. That
1788 -- procedure will (possibly later on during recursive downward calls),
1789 -- ensure that any needed overflow/division checks are properly applied.
1791 if Mode in Minimized_Or_Eliminated
1792 and then Is_Signed_Integer_Type (Typ)
1793 then
1794 Apply_Arithmetic_Overflow_Minimized_Eliminated (N);
1795 return;
1796 end if;
1798 -- Proceed here in SUPPRESSED or CHECKED modes
1800 if Expander_Active
1801 and then not Backend_Divide_Checks_On_Target
1802 and then Check_Needed (Right, Division_Check)
1803 then
1804 Determine_Range (Right, ROK, Rlo, Rhi, Assume_Valid => True);
1806 -- Deal with division check
1808 if Do_Division_Check (N)
1809 and then not Division_Checks_Suppressed (Typ)
1810 then
1811 Apply_Division_Check (N, Rlo, Rhi, ROK);
1812 end if;
1814 -- Deal with overflow check
1816 if Do_Overflow_Check (N)
1817 and then not Overflow_Checks_Suppressed (Etype (N))
1818 then
1819 Set_Do_Overflow_Check (N, False);
1821 -- Test for extremely annoying case of xxx'First divided by -1
1822 -- for division of signed integer types (only overflow case).
1824 if Nkind (N) = N_Op_Divide
1825 and then Is_Signed_Integer_Type (Typ)
1826 then
1827 Determine_Range (Left, LOK, Llo, Lhi, Assume_Valid => True);
1828 LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
1830 if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
1831 and then
1832 ((not LOK) or else (Llo = LLB))
1833 then
1834 -- Ensure that expressions are not evaluated twice (once
1835 -- for their runtime checks and once for their regular
1836 -- computation).
1838 Force_Evaluation (Left, Mode => Strict);
1839 Force_Evaluation (Right, Mode => Strict);
1841 Insert_Action (N,
1842 Make_Raise_Constraint_Error (Loc,
1843 Condition =>
1844 Make_And_Then (Loc,
1845 Left_Opnd =>
1846 Make_Op_Eq (Loc,
1847 Left_Opnd =>
1848 Duplicate_Subexpr_Move_Checks (Left),
1849 Right_Opnd => Make_Integer_Literal (Loc, LLB)),
1851 Right_Opnd =>
1852 Make_Op_Eq (Loc,
1853 Left_Opnd => Duplicate_Subexpr (Right),
1854 Right_Opnd => Make_Integer_Literal (Loc, -1))),
1856 Reason => CE_Overflow_Check_Failed));
1857 end if;
1858 end if;
1859 end if;
1860 end if;
1861 end Apply_Divide_Checks;
1863 --------------------------
1864 -- Apply_Division_Check --
1865 --------------------------
1867 procedure Apply_Division_Check
1868 (N : Node_Id;
1869 Rlo : Uint;
1870 Rhi : Uint;
1871 ROK : Boolean)
1873 pragma Assert (Do_Division_Check (N));
1875 Loc : constant Source_Ptr := Sloc (N);
1876 Right : constant Node_Id := Right_Opnd (N);
1877 Opnd : Node_Id;
1879 begin
1880 if Expander_Active
1881 and then not Backend_Divide_Checks_On_Target
1882 and then Check_Needed (Right, Division_Check)
1884 -- See if division by zero possible, and if so generate test. This
1885 -- part of the test is not controlled by the -gnato switch, since it
1886 -- is a Division_Check and not an Overflow_Check.
1888 and then Do_Division_Check (N)
1889 then
1890 Set_Do_Division_Check (N, False);
1892 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1893 if Is_Floating_Point_Type (Etype (N)) then
1894 Opnd := Make_Real_Literal (Loc, Ureal_0);
1895 else
1896 Opnd := Make_Integer_Literal (Loc, 0);
1897 end if;
1899 Insert_Action (N,
1900 Make_Raise_Constraint_Error (Loc,
1901 Condition =>
1902 Make_Op_Eq (Loc,
1903 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1904 Right_Opnd => Opnd),
1905 Reason => CE_Divide_By_Zero));
1906 end if;
1907 end if;
1908 end Apply_Division_Check;
1910 ----------------------------------
1911 -- Apply_Float_Conversion_Check --
1912 ----------------------------------
1914 -- Let F and I be the source and target types of the conversion. The RM
1915 -- specifies that a floating-point value X is rounded to the nearest
1916 -- integer, with halfway cases being rounded away from zero. The rounded
1917 -- value of X is checked against I'Range.
1919 -- The catch in the above paragraph is that there is no good way to know
1920 -- whether the round-to-integer operation resulted in overflow. A remedy is
1921 -- to perform a range check in the floating-point domain instead, however:
1923 -- (1) The bounds may not be known at compile time
1924 -- (2) The check must take into account rounding or truncation.
1925 -- (3) The range of type I may not be exactly representable in F.
1926 -- (4) For the rounding case, The end-points I'First - 0.5 and
1927 -- I'Last + 0.5 may or may not be in range, depending on the
1928 -- sign of I'First and I'Last.
1929 -- (5) X may be a NaN, which will fail any comparison
1931 -- The following steps correctly convert X with rounding:
1933 -- (1) If either I'First or I'Last is not known at compile time, use
1934 -- I'Base instead of I in the next three steps and perform a
1935 -- regular range check against I'Range after conversion.
1936 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1937 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1938 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1939 -- In other words, take one of the closest floating-point numbers
1940 -- (which is an integer value) to I'First, and see if it is in
1941 -- range or not.
1942 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1943 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1944 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1945 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1946 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1948 -- For the truncating case, replace steps (2) and (3) as follows:
1949 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1950 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1951 -- Lo_OK be True.
1952 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1953 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1954 -- Hi_OK be True.
1956 procedure Apply_Float_Conversion_Check
1957 (Ck_Node : Node_Id;
1958 Target_Typ : Entity_Id)
1960 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1961 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1962 Loc : constant Source_Ptr := Sloc (Ck_Node);
1963 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1964 Target_Base : constant Entity_Id :=
1965 Implementation_Base_Type (Target_Typ);
1967 Par : constant Node_Id := Parent (Ck_Node);
1968 pragma Assert (Nkind (Par) = N_Type_Conversion);
1969 -- Parent of check node, must be a type conversion
1971 Truncate : constant Boolean := Float_Truncate (Par);
1972 Max_Bound : constant Uint :=
1973 UI_Expon
1974 (Machine_Radix_Value (Expr_Type),
1975 Machine_Mantissa_Value (Expr_Type) - 1) - 1;
1977 -- Largest bound, so bound plus or minus half is a machine number of F
1979 Ifirst, Ilast : Uint;
1980 -- Bounds of integer type
1982 Lo, Hi : Ureal;
1983 -- Bounds to check in floating-point domain
1985 Lo_OK, Hi_OK : Boolean;
1986 -- True iff Lo resp. Hi belongs to I'Range
1988 Lo_Chk, Hi_Chk : Node_Id;
1989 -- Expressions that are False iff check fails
1991 Reason : RT_Exception_Code;
1993 begin
1994 -- We do not need checks if we are not generating code (i.e. the full
1995 -- expander is not active). In SPARK mode, we specifically don't want
1996 -- the frontend to expand these checks, which are dealt with directly
1997 -- in the formal verification backend.
1999 if not Expander_Active then
2000 return;
2001 end if;
2003 if not Compile_Time_Known_Value (LB)
2004 or not Compile_Time_Known_Value (HB)
2005 then
2006 declare
2007 -- First check that the value falls in the range of the base type,
2008 -- to prevent overflow during conversion and then perform a
2009 -- regular range check against the (dynamic) bounds.
2011 pragma Assert (Target_Base /= Target_Typ);
2013 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
2015 begin
2016 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
2017 Set_Etype (Temp, Target_Base);
2019 Insert_Action (Parent (Par),
2020 Make_Object_Declaration (Loc,
2021 Defining_Identifier => Temp,
2022 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
2023 Expression => New_Copy_Tree (Par)),
2024 Suppress => All_Checks);
2026 Insert_Action (Par,
2027 Make_Raise_Constraint_Error (Loc,
2028 Condition =>
2029 Make_Not_In (Loc,
2030 Left_Opnd => New_Occurrence_Of (Temp, Loc),
2031 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
2032 Reason => CE_Range_Check_Failed));
2033 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
2035 return;
2036 end;
2037 end if;
2039 -- Get the (static) bounds of the target type
2041 Ifirst := Expr_Value (LB);
2042 Ilast := Expr_Value (HB);
2044 -- A simple optimization: if the expression is a universal literal,
2045 -- we can do the comparison with the bounds and the conversion to
2046 -- an integer type statically. The range checks are unchanged.
2048 if Nkind (Ck_Node) = N_Real_Literal
2049 and then Etype (Ck_Node) = Universal_Real
2050 and then Is_Integer_Type (Target_Typ)
2051 and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
2052 then
2053 declare
2054 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
2056 begin
2057 if Int_Val <= Ilast and then Int_Val >= Ifirst then
2059 -- Conversion is safe
2061 Rewrite (Parent (Ck_Node),
2062 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
2063 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
2064 return;
2065 end if;
2066 end;
2067 end if;
2069 -- Check against lower bound
2071 if Truncate and then Ifirst > 0 then
2072 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
2073 Lo_OK := False;
2075 elsif Truncate then
2076 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
2077 Lo_OK := True;
2079 elsif abs (Ifirst) < Max_Bound then
2080 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
2081 Lo_OK := (Ifirst > 0);
2083 else
2084 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
2085 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
2086 end if;
2088 if Lo_OK then
2090 -- Lo_Chk := (X >= Lo)
2092 Lo_Chk := Make_Op_Ge (Loc,
2093 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2094 Right_Opnd => Make_Real_Literal (Loc, Lo));
2096 else
2097 -- Lo_Chk := (X > Lo)
2099 Lo_Chk := Make_Op_Gt (Loc,
2100 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2101 Right_Opnd => Make_Real_Literal (Loc, Lo));
2102 end if;
2104 -- Check against higher bound
2106 if Truncate and then Ilast < 0 then
2107 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
2108 Hi_OK := False;
2110 elsif Truncate then
2111 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
2112 Hi_OK := True;
2114 elsif abs (Ilast) < Max_Bound then
2115 Hi := UR_From_Uint (Ilast) + Ureal_Half;
2116 Hi_OK := (Ilast < 0);
2117 else
2118 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
2119 Hi_OK := (Hi <= UR_From_Uint (Ilast));
2120 end if;
2122 if Hi_OK then
2124 -- Hi_Chk := (X <= Hi)
2126 Hi_Chk := Make_Op_Le (Loc,
2127 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2128 Right_Opnd => Make_Real_Literal (Loc, Hi));
2130 else
2131 -- Hi_Chk := (X < Hi)
2133 Hi_Chk := Make_Op_Lt (Loc,
2134 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2135 Right_Opnd => Make_Real_Literal (Loc, Hi));
2136 end if;
2138 -- If the bounds of the target type are the same as those of the base
2139 -- type, the check is an overflow check as a range check is not
2140 -- performed in these cases.
2142 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
2143 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
2144 then
2145 Reason := CE_Overflow_Check_Failed;
2146 else
2147 Reason := CE_Range_Check_Failed;
2148 end if;
2150 -- Raise CE if either conditions does not hold
2152 Insert_Action (Ck_Node,
2153 Make_Raise_Constraint_Error (Loc,
2154 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
2155 Reason => Reason));
2156 end Apply_Float_Conversion_Check;
2158 ------------------------
2159 -- Apply_Length_Check --
2160 ------------------------
2162 procedure Apply_Length_Check
2163 (Ck_Node : Node_Id;
2164 Target_Typ : Entity_Id;
2165 Source_Typ : Entity_Id := Empty)
2167 begin
2168 Apply_Selected_Length_Checks
2169 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2170 end Apply_Length_Check;
2172 -------------------------------------
2173 -- Apply_Parameter_Aliasing_Checks --
2174 -------------------------------------
2176 procedure Apply_Parameter_Aliasing_Checks
2177 (Call : Node_Id;
2178 Subp : Entity_Id)
2180 Loc : constant Source_Ptr := Sloc (Call);
2182 function May_Cause_Aliasing
2183 (Formal_1 : Entity_Id;
2184 Formal_2 : Entity_Id) return Boolean;
2185 -- Determine whether two formal parameters can alias each other
2186 -- depending on their modes.
2188 function Original_Actual (N : Node_Id) return Node_Id;
2189 -- The expander may replace an actual with a temporary for the sake of
2190 -- side effect removal. The temporary may hide a potential aliasing as
2191 -- it does not share the address of the actual. This routine attempts
2192 -- to retrieve the original actual.
2194 procedure Overlap_Check
2195 (Actual_1 : Node_Id;
2196 Actual_2 : Node_Id;
2197 Formal_1 : Entity_Id;
2198 Formal_2 : Entity_Id;
2199 Check : in out Node_Id);
2200 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2201 -- If detailed exception messages are enabled, the check is augmented to
2202 -- provide information about the names of the corresponding formals. See
2203 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2204 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2205 -- Check contains all and-ed simple tests generated so far or remains
2206 -- unchanged in the case of detailed exception messaged.
2208 ------------------------
2209 -- May_Cause_Aliasing --
2210 ------------------------
2212 function May_Cause_Aliasing
2213 (Formal_1 : Entity_Id;
2214 Formal_2 : Entity_Id) return Boolean
2216 begin
2217 -- The following combination cannot lead to aliasing
2219 -- Formal 1 Formal 2
2220 -- IN IN
2222 if Ekind (Formal_1) = E_In_Parameter
2223 and then
2224 Ekind (Formal_2) = E_In_Parameter
2225 then
2226 return False;
2228 -- The following combinations may lead to aliasing
2230 -- Formal 1 Formal 2
2231 -- IN OUT
2232 -- IN IN OUT
2233 -- OUT IN
2234 -- OUT IN OUT
2235 -- OUT OUT
2237 else
2238 return True;
2239 end if;
2240 end May_Cause_Aliasing;
2242 ---------------------
2243 -- Original_Actual --
2244 ---------------------
2246 function Original_Actual (N : Node_Id) return Node_Id is
2247 begin
2248 if Nkind (N) = N_Type_Conversion then
2249 return Expression (N);
2251 -- The expander created a temporary to capture the result of a type
2252 -- conversion where the expression is the real actual.
2254 elsif Nkind (N) = N_Identifier
2255 and then Present (Original_Node (N))
2256 and then Nkind (Original_Node (N)) = N_Type_Conversion
2257 then
2258 return Expression (Original_Node (N));
2259 end if;
2261 return N;
2262 end Original_Actual;
2264 -------------------
2265 -- Overlap_Check --
2266 -------------------
2268 procedure Overlap_Check
2269 (Actual_1 : Node_Id;
2270 Actual_2 : Node_Id;
2271 Formal_1 : Entity_Id;
2272 Formal_2 : Entity_Id;
2273 Check : in out Node_Id)
2275 Cond : Node_Id;
2276 ID_Casing : constant Casing_Type :=
2277 Identifier_Casing (Source_Index (Current_Sem_Unit));
2279 begin
2280 -- Generate:
2281 -- Actual_1'Overlaps_Storage (Actual_2)
2283 Cond :=
2284 Make_Attribute_Reference (Loc,
2285 Prefix => New_Copy_Tree (Original_Actual (Actual_1)),
2286 Attribute_Name => Name_Overlaps_Storage,
2287 Expressions =>
2288 New_List (New_Copy_Tree (Original_Actual (Actual_2))));
2290 -- Generate the following check when detailed exception messages are
2291 -- enabled:
2293 -- if Actual_1'Overlaps_Storage (Actual_2) then
2294 -- raise Program_Error with <detailed message>;
2295 -- end if;
2297 if Exception_Extra_Info then
2298 Start_String;
2300 -- Do not generate location information for internal calls
2302 if Comes_From_Source (Call) then
2303 Store_String_Chars (Build_Location_String (Loc));
2304 Store_String_Char (' ');
2305 end if;
2307 Store_String_Chars ("aliased parameters, actuals for """);
2309 Get_Name_String (Chars (Formal_1));
2310 Set_Casing (ID_Casing);
2311 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2313 Store_String_Chars (""" and """);
2315 Get_Name_String (Chars (Formal_2));
2316 Set_Casing (ID_Casing);
2317 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2319 Store_String_Chars (""" overlap");
2321 Insert_Action (Call,
2322 Make_If_Statement (Loc,
2323 Condition => Cond,
2324 Then_Statements => New_List (
2325 Make_Raise_Statement (Loc,
2326 Name =>
2327 New_Occurrence_Of (Standard_Program_Error, Loc),
2328 Expression => Make_String_Literal (Loc, End_String)))));
2330 -- Create a sequence of overlapping checks by and-ing them all
2331 -- together.
2333 else
2334 if No (Check) then
2335 Check := Cond;
2336 else
2337 Check :=
2338 Make_And_Then (Loc,
2339 Left_Opnd => Check,
2340 Right_Opnd => Cond);
2341 end if;
2342 end if;
2343 end Overlap_Check;
2345 -- Local variables
2347 Actual_1 : Node_Id;
2348 Actual_2 : Node_Id;
2349 Check : Node_Id;
2350 Formal_1 : Entity_Id;
2351 Formal_2 : Entity_Id;
2352 Orig_Act_1 : Node_Id;
2353 Orig_Act_2 : Node_Id;
2355 -- Start of processing for Apply_Parameter_Aliasing_Checks
2357 begin
2358 Check := Empty;
2360 Actual_1 := First_Actual (Call);
2361 Formal_1 := First_Formal (Subp);
2362 while Present (Actual_1) and then Present (Formal_1) loop
2363 Orig_Act_1 := Original_Actual (Actual_1);
2365 -- Ensure that the actual is an object that is not passed by value.
2366 -- Elementary types are always passed by value, therefore actuals of
2367 -- such types cannot lead to aliasing. An aggregate is an object in
2368 -- Ada 2012, but an actual that is an aggregate cannot overlap with
2369 -- another actual. A type that is By_Reference (such as an array of
2370 -- controlled types) is not subject to the check because any update
2371 -- will be done in place and a subsequent read will always see the
2372 -- correct value, see RM 6.2 (12/3).
2374 if Nkind (Orig_Act_1) = N_Aggregate
2375 or else (Nkind (Orig_Act_1) = N_Qualified_Expression
2376 and then Nkind (Expression (Orig_Act_1)) = N_Aggregate)
2377 then
2378 null;
2380 elsif Is_Object_Reference (Orig_Act_1)
2381 and then not Is_Elementary_Type (Etype (Orig_Act_1))
2382 and then not Is_By_Reference_Type (Etype (Orig_Act_1))
2383 then
2384 Actual_2 := Next_Actual (Actual_1);
2385 Formal_2 := Next_Formal (Formal_1);
2386 while Present (Actual_2) and then Present (Formal_2) loop
2387 Orig_Act_2 := Original_Actual (Actual_2);
2389 -- The other actual we are testing against must also denote
2390 -- a non pass-by-value object. Generate the check only when
2391 -- the mode of the two formals may lead to aliasing.
2393 if Is_Object_Reference (Orig_Act_2)
2394 and then not Is_Elementary_Type (Etype (Orig_Act_2))
2395 and then May_Cause_Aliasing (Formal_1, Formal_2)
2396 then
2397 Remove_Side_Effects (Actual_1);
2398 Remove_Side_Effects (Actual_2);
2400 Overlap_Check
2401 (Actual_1 => Actual_1,
2402 Actual_2 => Actual_2,
2403 Formal_1 => Formal_1,
2404 Formal_2 => Formal_2,
2405 Check => Check);
2406 end if;
2408 Next_Actual (Actual_2);
2409 Next_Formal (Formal_2);
2410 end loop;
2411 end if;
2413 Next_Actual (Actual_1);
2414 Next_Formal (Formal_1);
2415 end loop;
2417 -- Place a simple check right before the call
2419 if Present (Check) and then not Exception_Extra_Info then
2420 Insert_Action (Call,
2421 Make_Raise_Program_Error (Loc,
2422 Condition => Check,
2423 Reason => PE_Aliased_Parameters));
2424 end if;
2425 end Apply_Parameter_Aliasing_Checks;
2427 -------------------------------------
2428 -- Apply_Parameter_Validity_Checks --
2429 -------------------------------------
2431 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id) is
2432 Subp_Decl : Node_Id;
2434 procedure Add_Validity_Check
2435 (Formal : Entity_Id;
2436 Prag_Nam : Name_Id;
2437 For_Result : Boolean := False);
2438 -- Add a single 'Valid[_Scalar] check which verifies the initialization
2439 -- of Formal. Prag_Nam denotes the pre or post condition pragma name.
2440 -- Set flag For_Result when to verify the result of a function.
2442 ------------------------
2443 -- Add_Validity_Check --
2444 ------------------------
2446 procedure Add_Validity_Check
2447 (Formal : Entity_Id;
2448 Prag_Nam : Name_Id;
2449 For_Result : Boolean := False)
2451 procedure Build_Pre_Post_Condition (Expr : Node_Id);
2452 -- Create a pre/postcondition pragma that tests expression Expr
2454 ------------------------------
2455 -- Build_Pre_Post_Condition --
2456 ------------------------------
2458 procedure Build_Pre_Post_Condition (Expr : Node_Id) is
2459 Loc : constant Source_Ptr := Sloc (Subp);
2460 Decls : List_Id;
2461 Prag : Node_Id;
2463 begin
2464 Prag :=
2465 Make_Pragma (Loc,
2466 Chars => Prag_Nam,
2467 Pragma_Argument_Associations => New_List (
2468 Make_Pragma_Argument_Association (Loc,
2469 Chars => Name_Check,
2470 Expression => Expr)));
2472 -- Add a message unless exception messages are suppressed
2474 if not Exception_Locations_Suppressed then
2475 Append_To (Pragma_Argument_Associations (Prag),
2476 Make_Pragma_Argument_Association (Loc,
2477 Chars => Name_Message,
2478 Expression =>
2479 Make_String_Literal (Loc,
2480 Strval => "failed "
2481 & Get_Name_String (Prag_Nam)
2482 & " from "
2483 & Build_Location_String (Loc))));
2484 end if;
2486 -- Insert the pragma in the tree
2488 if Nkind (Parent (Subp_Decl)) = N_Compilation_Unit then
2489 Add_Global_Declaration (Prag);
2490 Analyze (Prag);
2492 -- PPC pragmas associated with subprogram bodies must be inserted
2493 -- in the declarative part of the body.
2495 elsif Nkind (Subp_Decl) = N_Subprogram_Body then
2496 Decls := Declarations (Subp_Decl);
2498 if No (Decls) then
2499 Decls := New_List;
2500 Set_Declarations (Subp_Decl, Decls);
2501 end if;
2503 Prepend_To (Decls, Prag);
2504 Analyze (Prag);
2506 -- For subprogram declarations insert the PPC pragma right after
2507 -- the declarative node.
2509 else
2510 Insert_After_And_Analyze (Subp_Decl, Prag);
2511 end if;
2512 end Build_Pre_Post_Condition;
2514 -- Local variables
2516 Loc : constant Source_Ptr := Sloc (Subp);
2517 Typ : constant Entity_Id := Etype (Formal);
2518 Check : Node_Id;
2519 Nam : Name_Id;
2521 -- Start of processing for Add_Validity_Check
2523 begin
2524 -- For scalars, generate 'Valid test
2526 if Is_Scalar_Type (Typ) then
2527 Nam := Name_Valid;
2529 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2531 elsif Scalar_Part_Present (Typ) then
2532 Nam := Name_Valid_Scalars;
2534 -- No test needed for other cases (no scalars to test)
2536 else
2537 return;
2538 end if;
2540 -- Step 1: Create the expression to verify the validity of the
2541 -- context.
2543 Check := New_Occurrence_Of (Formal, Loc);
2545 -- When processing a function result, use 'Result. Generate
2546 -- Context'Result
2548 if For_Result then
2549 Check :=
2550 Make_Attribute_Reference (Loc,
2551 Prefix => Check,
2552 Attribute_Name => Name_Result);
2553 end if;
2555 -- Generate:
2556 -- Context['Result]'Valid[_Scalars]
2558 Check :=
2559 Make_Attribute_Reference (Loc,
2560 Prefix => Check,
2561 Attribute_Name => Nam);
2563 -- Step 2: Create a pre or post condition pragma
2565 Build_Pre_Post_Condition (Check);
2566 end Add_Validity_Check;
2568 -- Local variables
2570 Formal : Entity_Id;
2571 Subp_Spec : Node_Id;
2573 -- Start of processing for Apply_Parameter_Validity_Checks
2575 begin
2576 -- Extract the subprogram specification and declaration nodes
2578 Subp_Spec := Parent (Subp);
2580 if Nkind (Subp_Spec) = N_Defining_Program_Unit_Name then
2581 Subp_Spec := Parent (Subp_Spec);
2582 end if;
2584 Subp_Decl := Parent (Subp_Spec);
2586 if not Comes_From_Source (Subp)
2588 -- Do not process formal subprograms because the corresponding actual
2589 -- will receive the proper checks when the instance is analyzed.
2591 or else Is_Formal_Subprogram (Subp)
2593 -- Do not process imported subprograms since pre and postconditions
2594 -- are never verified on routines coming from a different language.
2596 or else Is_Imported (Subp)
2597 or else Is_Intrinsic_Subprogram (Subp)
2599 -- The PPC pragmas generated by this routine do not correspond to
2600 -- source aspects, therefore they cannot be applied to abstract
2601 -- subprograms.
2603 or else Nkind (Subp_Decl) = N_Abstract_Subprogram_Declaration
2605 -- Do not consider subprogram renaminds because the renamed entity
2606 -- already has the proper PPC pragmas.
2608 or else Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
2610 -- Do not process null procedures because there is no benefit of
2611 -- adding the checks to a no action routine.
2613 or else (Nkind (Subp_Spec) = N_Procedure_Specification
2614 and then Null_Present (Subp_Spec))
2615 then
2616 return;
2617 end if;
2619 -- Inspect all the formals applying aliasing and scalar initialization
2620 -- checks where applicable.
2622 Formal := First_Formal (Subp);
2623 while Present (Formal) loop
2625 -- Generate the following scalar initialization checks for each
2626 -- formal parameter:
2628 -- mode IN - Pre => Formal'Valid[_Scalars]
2629 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2630 -- mode OUT - Post => Formal'Valid[_Scalars]
2632 if Check_Validity_Of_Parameters then
2633 if Ekind_In (Formal, E_In_Parameter, E_In_Out_Parameter) then
2634 Add_Validity_Check (Formal, Name_Precondition, False);
2635 end if;
2637 if Ekind_In (Formal, E_In_Out_Parameter, E_Out_Parameter) then
2638 Add_Validity_Check (Formal, Name_Postcondition, False);
2639 end if;
2640 end if;
2642 Next_Formal (Formal);
2643 end loop;
2645 -- Generate following scalar initialization check for function result:
2647 -- Post => Subp'Result'Valid[_Scalars]
2649 if Check_Validity_Of_Parameters and then Ekind (Subp) = E_Function then
2650 Add_Validity_Check (Subp, Name_Postcondition, True);
2651 end if;
2652 end Apply_Parameter_Validity_Checks;
2654 ---------------------------
2655 -- Apply_Predicate_Check --
2656 ---------------------------
2658 procedure Apply_Predicate_Check
2659 (N : Node_Id;
2660 Typ : Entity_Id;
2661 Fun : Entity_Id := Empty)
2663 S : Entity_Id;
2665 begin
2666 if Predicate_Checks_Suppressed (Empty) then
2667 return;
2669 elsif Predicates_Ignored (Typ) then
2670 return;
2672 elsif Present (Predicate_Function (Typ)) then
2673 S := Current_Scope;
2674 while Present (S) and then not Is_Subprogram (S) loop
2675 S := Scope (S);
2676 end loop;
2678 -- A predicate check does not apply within internally generated
2679 -- subprograms, such as TSS functions.
2681 if Within_Internal_Subprogram then
2682 return;
2684 -- If the check appears within the predicate function itself, it
2685 -- means that the user specified a check whose formal is the
2686 -- predicated subtype itself, rather than some covering type. This
2687 -- is likely to be a common error, and thus deserves a warning.
2689 elsif Present (S) and then S = Predicate_Function (Typ) then
2690 Error_Msg_NE
2691 ("predicate check includes a call to& that requires a "
2692 & "predicate check??", Parent (N), Fun);
2693 Error_Msg_N
2694 ("\this will result in infinite recursion??", Parent (N));
2696 if Is_First_Subtype (Typ) then
2697 Error_Msg_NE
2698 ("\use an explicit subtype of& to carry the predicate",
2699 Parent (N), Typ);
2700 end if;
2702 Insert_Action (N,
2703 Make_Raise_Storage_Error (Sloc (N),
2704 Reason => SE_Infinite_Recursion));
2706 -- Here for normal case of predicate active
2708 else
2709 -- If the type has a static predicate and the expression is known
2710 -- at compile time, see if the expression satisfies the predicate.
2712 Check_Expression_Against_Static_Predicate (N, Typ);
2714 if not Expander_Active then
2715 return;
2716 end if;
2718 -- For an entity of the type, generate a call to the predicate
2719 -- function, unless its type is an actual subtype, which is not
2720 -- visible outside of the enclosing subprogram.
2722 if Is_Entity_Name (N)
2723 and then not Is_Actual_Subtype (Typ)
2724 then
2725 Insert_Action (N,
2726 Make_Predicate_Check
2727 (Typ, New_Occurrence_Of (Entity (N), Sloc (N))));
2729 -- If the expression is not an entity it may have side effects,
2730 -- and the following call will create an object declaration for
2731 -- it. We disable checks during its analysis, to prevent an
2732 -- infinite recursion.
2734 -- If the prefix is an aggregate in an assignment, apply the
2735 -- check to the LHS after assignment, rather than create a
2736 -- redundant temporary. This is only necessary in rare cases
2737 -- of array types (including strings) initialized with an
2738 -- aggregate with an "others" clause, either coming from source
2739 -- or generated by an Initialize_Scalars pragma.
2741 elsif Nkind (N) = N_Aggregate
2742 and then Nkind (Parent (N)) = N_Assignment_Statement
2743 then
2744 Insert_Action_After (Parent (N),
2745 Make_Predicate_Check
2746 (Typ, Duplicate_Subexpr (Name (Parent (N)))));
2748 else
2749 Insert_Action (N,
2750 Make_Predicate_Check
2751 (Typ, Duplicate_Subexpr (N)), Suppress => All_Checks);
2752 end if;
2753 end if;
2754 end if;
2755 end Apply_Predicate_Check;
2757 -----------------------
2758 -- Apply_Range_Check --
2759 -----------------------
2761 procedure Apply_Range_Check
2762 (Ck_Node : Node_Id;
2763 Target_Typ : Entity_Id;
2764 Source_Typ : Entity_Id := Empty)
2766 begin
2767 Apply_Selected_Range_Checks
2768 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2769 end Apply_Range_Check;
2771 ------------------------------
2772 -- Apply_Scalar_Range_Check --
2773 ------------------------------
2775 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
2776 -- off if it is already set on.
2778 procedure Apply_Scalar_Range_Check
2779 (Expr : Node_Id;
2780 Target_Typ : Entity_Id;
2781 Source_Typ : Entity_Id := Empty;
2782 Fixed_Int : Boolean := False)
2784 Parnt : constant Node_Id := Parent (Expr);
2785 S_Typ : Entity_Id;
2786 Arr : Node_Id := Empty; -- initialize to prevent warning
2787 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
2789 Is_Subscr_Ref : Boolean;
2790 -- Set true if Expr is a subscript
2792 Is_Unconstrained_Subscr_Ref : Boolean;
2793 -- Set true if Expr is a subscript of an unconstrained array. In this
2794 -- case we do not attempt to do an analysis of the value against the
2795 -- range of the subscript, since we don't know the actual subtype.
2797 Int_Real : Boolean;
2798 -- Set to True if Expr should be regarded as a real value even though
2799 -- the type of Expr might be discrete.
2801 procedure Bad_Value (Warn : Boolean := False);
2802 -- Procedure called if value is determined to be out of range. Warn is
2803 -- True to force a warning instead of an error, even when SPARK_Mode is
2804 -- On.
2806 ---------------
2807 -- Bad_Value --
2808 ---------------
2810 procedure Bad_Value (Warn : Boolean := False) is
2811 begin
2812 Apply_Compile_Time_Constraint_Error
2813 (Expr, "value not in range of}??", CE_Range_Check_Failed,
2814 Ent => Target_Typ,
2815 Typ => Target_Typ,
2816 Warn => Warn);
2817 end Bad_Value;
2819 -- Start of processing for Apply_Scalar_Range_Check
2821 begin
2822 -- Return if check obviously not needed
2825 -- Not needed inside generic
2827 Inside_A_Generic
2829 -- Not needed if previous error
2831 or else Target_Typ = Any_Type
2832 or else Nkind (Expr) = N_Error
2834 -- Not needed for non-scalar type
2836 or else not Is_Scalar_Type (Target_Typ)
2838 -- Not needed if we know node raises CE already
2840 or else Raises_Constraint_Error (Expr)
2841 then
2842 return;
2843 end if;
2845 -- Now, see if checks are suppressed
2847 Is_Subscr_Ref :=
2848 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
2850 if Is_Subscr_Ref then
2851 Arr := Prefix (Parnt);
2852 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
2854 if Is_Access_Type (Arr_Typ) then
2855 Arr_Typ := Designated_Type (Arr_Typ);
2856 end if;
2857 end if;
2859 if not Do_Range_Check (Expr) then
2861 -- Subscript reference. Check for Index_Checks suppressed
2863 if Is_Subscr_Ref then
2865 -- Check array type and its base type
2867 if Index_Checks_Suppressed (Arr_Typ)
2868 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
2869 then
2870 return;
2872 -- Check array itself if it is an entity name
2874 elsif Is_Entity_Name (Arr)
2875 and then Index_Checks_Suppressed (Entity (Arr))
2876 then
2877 return;
2879 -- Check expression itself if it is an entity name
2881 elsif Is_Entity_Name (Expr)
2882 and then Index_Checks_Suppressed (Entity (Expr))
2883 then
2884 return;
2885 end if;
2887 -- All other cases, check for Range_Checks suppressed
2889 else
2890 -- Check target type and its base type
2892 if Range_Checks_Suppressed (Target_Typ)
2893 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
2894 then
2895 return;
2897 -- Check expression itself if it is an entity name
2899 elsif Is_Entity_Name (Expr)
2900 and then Range_Checks_Suppressed (Entity (Expr))
2901 then
2902 return;
2904 -- If Expr is part of an assignment statement, then check left
2905 -- side of assignment if it is an entity name.
2907 elsif Nkind (Parnt) = N_Assignment_Statement
2908 and then Is_Entity_Name (Name (Parnt))
2909 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
2910 then
2911 return;
2912 end if;
2913 end if;
2914 end if;
2916 -- Do not set range checks if they are killed
2918 if Nkind (Expr) = N_Unchecked_Type_Conversion
2919 and then Kill_Range_Check (Expr)
2920 then
2921 return;
2922 end if;
2924 -- Do not set range checks for any values from System.Scalar_Values
2925 -- since the whole idea of such values is to avoid checking them.
2927 if Is_Entity_Name (Expr)
2928 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
2929 then
2930 return;
2931 end if;
2933 -- Now see if we need a check
2935 if No (Source_Typ) then
2936 S_Typ := Etype (Expr);
2937 else
2938 S_Typ := Source_Typ;
2939 end if;
2941 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
2942 return;
2943 end if;
2945 Is_Unconstrained_Subscr_Ref :=
2946 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
2948 -- Special checks for floating-point type
2950 if Is_Floating_Point_Type (S_Typ) then
2952 -- Always do a range check if the source type includes infinities and
2953 -- the target type does not include infinities. We do not do this if
2954 -- range checks are killed.
2955 -- If the expression is a literal and the bounds of the type are
2956 -- static constants it may be possible to optimize the check.
2958 if Has_Infinities (S_Typ)
2959 and then not Has_Infinities (Target_Typ)
2960 then
2961 -- If the expression is a literal and the bounds of the type are
2962 -- static constants it may be possible to optimize the check.
2964 if Nkind (Expr) = N_Real_Literal then
2965 declare
2966 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
2967 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
2969 begin
2970 if Compile_Time_Known_Value (Tlo)
2971 and then Compile_Time_Known_Value (Thi)
2972 and then Expr_Value_R (Expr) >= Expr_Value_R (Tlo)
2973 and then Expr_Value_R (Expr) <= Expr_Value_R (Thi)
2974 then
2975 return;
2976 else
2977 Enable_Range_Check (Expr);
2978 end if;
2979 end;
2981 else
2982 Enable_Range_Check (Expr);
2983 end if;
2984 end if;
2985 end if;
2987 -- Return if we know expression is definitely in the range of the target
2988 -- type as determined by Determine_Range. Right now we only do this for
2989 -- discrete types, and not fixed-point or floating-point types.
2991 -- The additional less-precise tests below catch these cases
2993 -- In GNATprove_Mode, also deal with the case of a conversion from
2994 -- floating-point to integer. It is only possible because analysis
2995 -- in GNATprove rules out the possibility of a NaN or infinite value.
2997 -- Note: skip this if we are given a source_typ, since the point of
2998 -- supplying a Source_Typ is to stop us looking at the expression.
2999 -- We could sharpen this test to be out parameters only ???
3001 if Is_Discrete_Type (Target_Typ)
3002 and then (Is_Discrete_Type (Etype (Expr))
3003 or else (GNATprove_Mode
3004 and then Is_Floating_Point_Type (Etype (Expr))))
3005 and then not Is_Unconstrained_Subscr_Ref
3006 and then No (Source_Typ)
3007 then
3008 declare
3009 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
3010 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
3012 begin
3013 if Compile_Time_Known_Value (Tlo)
3014 and then Compile_Time_Known_Value (Thi)
3015 then
3016 declare
3017 OK : Boolean := False; -- initialize to prevent warning
3018 Hiv : constant Uint := Expr_Value (Thi);
3019 Lov : constant Uint := Expr_Value (Tlo);
3020 Hi : Uint := No_Uint;
3021 Lo : Uint := No_Uint;
3023 begin
3024 -- If range is null, we for sure have a constraint error (we
3025 -- don't even need to look at the value involved, since all
3026 -- possible values will raise CE).
3028 if Lov > Hiv then
3030 -- When SPARK_Mode is On, force a warning instead of
3031 -- an error in that case, as this likely corresponds
3032 -- to deactivated code.
3034 Bad_Value (Warn => SPARK_Mode = On);
3036 -- In GNATprove mode, we enable the range check so that
3037 -- GNATprove will issue a message if it cannot be proved.
3039 if GNATprove_Mode then
3040 Enable_Range_Check (Expr);
3041 end if;
3043 return;
3044 end if;
3046 -- Otherwise determine range of value
3048 if Is_Discrete_Type (Etype (Expr)) then
3049 Determine_Range
3050 (Expr, OK, Lo, Hi, Assume_Valid => True);
3052 -- When converting a float to an integer type, determine the
3053 -- range in real first, and then convert the bounds using
3054 -- UR_To_Uint which correctly rounds away from zero when
3055 -- half way between two integers, as required by normal
3056 -- Ada 95 rounding semantics. It is only possible because
3057 -- analysis in GNATprove rules out the possibility of a NaN
3058 -- or infinite value.
3060 elsif GNATprove_Mode
3061 and then Is_Floating_Point_Type (Etype (Expr))
3062 then
3063 declare
3064 Hir : Ureal;
3065 Lor : Ureal;
3067 begin
3068 Determine_Range_R
3069 (Expr, OK, Lor, Hir, Assume_Valid => True);
3071 if OK then
3072 Lo := UR_To_Uint (Lor);
3073 Hi := UR_To_Uint (Hir);
3074 end if;
3075 end;
3076 end if;
3078 if OK then
3080 -- If definitely in range, all OK
3082 if Lo >= Lov and then Hi <= Hiv then
3083 return;
3085 -- If definitely not in range, warn
3087 elsif Lov > Hi or else Hiv < Lo then
3089 -- Ignore out of range values for System.Priority in
3090 -- CodePeer mode since the actual target compiler may
3091 -- provide a wider range.
3093 if not CodePeer_Mode
3094 or else Target_Typ /= RTE (RE_Priority)
3095 then
3096 Bad_Value;
3097 end if;
3099 return;
3101 -- Otherwise we don't know
3103 else
3104 null;
3105 end if;
3106 end if;
3107 end;
3108 end if;
3109 end;
3110 end if;
3112 Int_Real :=
3113 Is_Floating_Point_Type (S_Typ)
3114 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
3116 -- Check if we can determine at compile time whether Expr is in the
3117 -- range of the target type. Note that if S_Typ is within the bounds
3118 -- of Target_Typ then this must be the case. This check is meaningful
3119 -- only if this is not a conversion between integer and real types.
3121 if not Is_Unconstrained_Subscr_Ref
3122 and then Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
3123 and then
3124 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
3126 -- Also check if the expression itself is in the range of the
3127 -- target type if it is a known at compile time value. We skip
3128 -- this test if S_Typ is set since for OUT and IN OUT parameters
3129 -- the Expr itself is not relevant to the checking.
3131 or else
3132 (No (Source_Typ)
3133 and then Is_In_Range (Expr, Target_Typ,
3134 Assume_Valid => True,
3135 Fixed_Int => Fixed_Int,
3136 Int_Real => Int_Real)))
3137 then
3138 return;
3140 elsif Is_Out_Of_Range (Expr, Target_Typ,
3141 Assume_Valid => True,
3142 Fixed_Int => Fixed_Int,
3143 Int_Real => Int_Real)
3144 then
3145 Bad_Value;
3146 return;
3148 -- Floating-point case
3149 -- In the floating-point case, we only do range checks if the type is
3150 -- constrained. We definitely do NOT want range checks for unconstrained
3151 -- types, since we want to have infinities, except when
3152 -- Check_Float_Overflow is set.
3154 elsif Is_Floating_Point_Type (S_Typ) then
3155 if Is_Constrained (S_Typ) or else Check_Float_Overflow then
3156 Enable_Range_Check (Expr);
3157 end if;
3159 -- For all other cases we enable a range check unconditionally
3161 else
3162 Enable_Range_Check (Expr);
3163 return;
3164 end if;
3165 end Apply_Scalar_Range_Check;
3167 ----------------------------------
3168 -- Apply_Selected_Length_Checks --
3169 ----------------------------------
3171 procedure Apply_Selected_Length_Checks
3172 (Ck_Node : Node_Id;
3173 Target_Typ : Entity_Id;
3174 Source_Typ : Entity_Id;
3175 Do_Static : Boolean)
3177 Checks_On : constant Boolean :=
3178 not Index_Checks_Suppressed (Target_Typ)
3179 or else
3180 not Length_Checks_Suppressed (Target_Typ);
3182 Loc : constant Source_Ptr := Sloc (Ck_Node);
3184 Cond : Node_Id;
3185 R_Cno : Node_Id;
3186 R_Result : Check_Result;
3188 begin
3189 -- Only apply checks when generating code
3191 -- Note: this means that we lose some useful warnings if the expander
3192 -- is not active.
3194 if not Expander_Active then
3195 return;
3196 end if;
3198 R_Result :=
3199 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3201 for J in 1 .. 2 loop
3202 R_Cno := R_Result (J);
3203 exit when No (R_Cno);
3205 -- A length check may mention an Itype which is attached to a
3206 -- subsequent node. At the top level in a package this can cause
3207 -- an order-of-elaboration problem, so we make sure that the itype
3208 -- is referenced now.
3210 if Ekind (Current_Scope) = E_Package
3211 and then Is_Compilation_Unit (Current_Scope)
3212 then
3213 Ensure_Defined (Target_Typ, Ck_Node);
3215 if Present (Source_Typ) then
3216 Ensure_Defined (Source_Typ, Ck_Node);
3218 elsif Is_Itype (Etype (Ck_Node)) then
3219 Ensure_Defined (Etype (Ck_Node), Ck_Node);
3220 end if;
3221 end if;
3223 -- If the item is a conditional raise of constraint error, then have
3224 -- a look at what check is being performed and ???
3226 if Nkind (R_Cno) = N_Raise_Constraint_Error
3227 and then Present (Condition (R_Cno))
3228 then
3229 Cond := Condition (R_Cno);
3231 -- Case where node does not now have a dynamic check
3233 if not Has_Dynamic_Length_Check (Ck_Node) then
3235 -- If checks are on, just insert the check
3237 if Checks_On then
3238 Insert_Action (Ck_Node, R_Cno);
3240 if not Do_Static then
3241 Set_Has_Dynamic_Length_Check (Ck_Node);
3242 end if;
3244 -- If checks are off, then analyze the length check after
3245 -- temporarily attaching it to the tree in case the relevant
3246 -- condition can be evaluated at compile time. We still want a
3247 -- compile time warning in this case.
3249 else
3250 Set_Parent (R_Cno, Ck_Node);
3251 Analyze (R_Cno);
3252 end if;
3253 end if;
3255 -- Output a warning if the condition is known to be True
3257 if Is_Entity_Name (Cond)
3258 and then Entity (Cond) = Standard_True
3259 then
3260 Apply_Compile_Time_Constraint_Error
3261 (Ck_Node, "wrong length for array of}??",
3262 CE_Length_Check_Failed,
3263 Ent => Target_Typ,
3264 Typ => Target_Typ);
3266 -- If we were only doing a static check, or if checks are not
3267 -- on, then we want to delete the check, since it is not needed.
3268 -- We do this by replacing the if statement by a null statement
3270 elsif Do_Static or else not Checks_On then
3271 Remove_Warning_Messages (R_Cno);
3272 Rewrite (R_Cno, Make_Null_Statement (Loc));
3273 end if;
3275 else
3276 Install_Static_Check (R_Cno, Loc);
3277 end if;
3278 end loop;
3279 end Apply_Selected_Length_Checks;
3281 ---------------------------------
3282 -- Apply_Selected_Range_Checks --
3283 ---------------------------------
3285 procedure Apply_Selected_Range_Checks
3286 (Ck_Node : Node_Id;
3287 Target_Typ : Entity_Id;
3288 Source_Typ : Entity_Id;
3289 Do_Static : Boolean)
3291 Checks_On : constant Boolean :=
3292 not Index_Checks_Suppressed (Target_Typ)
3293 or else
3294 not Range_Checks_Suppressed (Target_Typ);
3296 Loc : constant Source_Ptr := Sloc (Ck_Node);
3298 Cond : Node_Id;
3299 R_Cno : Node_Id;
3300 R_Result : Check_Result;
3302 begin
3303 -- Only apply checks when generating code. In GNATprove mode, we do not
3304 -- apply the checks, but we still call Selected_Range_Checks to possibly
3305 -- issue errors on SPARK code when a run-time error can be detected at
3306 -- compile time.
3308 if not GNATprove_Mode then
3309 if not Expander_Active or not Checks_On then
3310 return;
3311 end if;
3312 end if;
3314 R_Result :=
3315 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3317 if GNATprove_Mode then
3318 return;
3319 end if;
3321 for J in 1 .. 2 loop
3322 R_Cno := R_Result (J);
3323 exit when No (R_Cno);
3325 -- The range check requires runtime evaluation. Depending on what its
3326 -- triggering condition is, the check may be converted into a compile
3327 -- time constraint check.
3329 if Nkind (R_Cno) = N_Raise_Constraint_Error
3330 and then Present (Condition (R_Cno))
3331 then
3332 Cond := Condition (R_Cno);
3334 -- Insert the range check before the related context. Note that
3335 -- this action analyses the triggering condition.
3337 Insert_Action (Ck_Node, R_Cno);
3339 -- This old code doesn't make sense, why is the context flagged as
3340 -- requiring dynamic range checks now in the middle of generating
3341 -- them ???
3343 if not Do_Static then
3344 Set_Has_Dynamic_Range_Check (Ck_Node);
3345 end if;
3347 -- The triggering condition evaluates to True, the range check
3348 -- can be converted into a compile time constraint check.
3350 if Is_Entity_Name (Cond)
3351 and then Entity (Cond) = Standard_True
3352 then
3353 -- Since an N_Range is technically not an expression, we have
3354 -- to set one of the bounds to C_E and then just flag the
3355 -- N_Range. The warning message will point to the lower bound
3356 -- and complain about a range, which seems OK.
3358 if Nkind (Ck_Node) = N_Range then
3359 Apply_Compile_Time_Constraint_Error
3360 (Low_Bound (Ck_Node),
3361 "static range out of bounds of}??",
3362 CE_Range_Check_Failed,
3363 Ent => Target_Typ,
3364 Typ => Target_Typ);
3366 Set_Raises_Constraint_Error (Ck_Node);
3368 else
3369 Apply_Compile_Time_Constraint_Error
3370 (Ck_Node,
3371 "static value out of range of}??",
3372 CE_Range_Check_Failed,
3373 Ent => Target_Typ,
3374 Typ => Target_Typ);
3375 end if;
3377 -- If we were only doing a static check, or if checks are not
3378 -- on, then we want to delete the check, since it is not needed.
3379 -- We do this by replacing the if statement by a null statement
3381 elsif Do_Static then
3382 Remove_Warning_Messages (R_Cno);
3383 Rewrite (R_Cno, Make_Null_Statement (Loc));
3384 end if;
3386 -- The range check raises Constraint_Error explicitly
3388 else
3389 Install_Static_Check (R_Cno, Loc);
3390 end if;
3391 end loop;
3392 end Apply_Selected_Range_Checks;
3394 -------------------------------
3395 -- Apply_Static_Length_Check --
3396 -------------------------------
3398 procedure Apply_Static_Length_Check
3399 (Expr : Node_Id;
3400 Target_Typ : Entity_Id;
3401 Source_Typ : Entity_Id := Empty)
3403 begin
3404 Apply_Selected_Length_Checks
3405 (Expr, Target_Typ, Source_Typ, Do_Static => True);
3406 end Apply_Static_Length_Check;
3408 -------------------------------------
3409 -- Apply_Subscript_Validity_Checks --
3410 -------------------------------------
3412 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
3413 Sub : Node_Id;
3415 begin
3416 pragma Assert (Nkind (Expr) = N_Indexed_Component);
3418 -- Loop through subscripts
3420 Sub := First (Expressions (Expr));
3421 while Present (Sub) loop
3423 -- Check one subscript. Note that we do not worry about enumeration
3424 -- type with holes, since we will convert the value to a Pos value
3425 -- for the subscript, and that convert will do the necessary validity
3426 -- check.
3428 Ensure_Valid (Sub, Holes_OK => True);
3430 -- Move to next subscript
3432 Sub := Next (Sub);
3433 end loop;
3434 end Apply_Subscript_Validity_Checks;
3436 ----------------------------------
3437 -- Apply_Type_Conversion_Checks --
3438 ----------------------------------
3440 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
3441 Target_Type : constant Entity_Id := Etype (N);
3442 Target_Base : constant Entity_Id := Base_Type (Target_Type);
3443 Expr : constant Node_Id := Expression (N);
3445 Expr_Type : constant Entity_Id := Underlying_Type (Etype (Expr));
3446 -- Note: if Etype (Expr) is a private type without discriminants, its
3447 -- full view might have discriminants with defaults, so we need the
3448 -- full view here to retrieve the constraints.
3450 begin
3451 if Inside_A_Generic then
3452 return;
3454 -- Skip these checks if serious errors detected, there are some nasty
3455 -- situations of incomplete trees that blow things up.
3457 elsif Serious_Errors_Detected > 0 then
3458 return;
3460 -- Never generate discriminant checks for Unchecked_Union types
3462 elsif Present (Expr_Type)
3463 and then Is_Unchecked_Union (Expr_Type)
3464 then
3465 return;
3467 -- Scalar type conversions of the form Target_Type (Expr) require a
3468 -- range check if we cannot be sure that Expr is in the base type of
3469 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3470 -- are not quite the same condition from an implementation point of
3471 -- view, but clearly the second includes the first.
3473 elsif Is_Scalar_Type (Target_Type) then
3474 declare
3475 Conv_OK : constant Boolean := Conversion_OK (N);
3476 -- If the Conversion_OK flag on the type conversion is set and no
3477 -- floating-point type is involved in the type conversion then
3478 -- fixed-point values must be read as integral values.
3480 Float_To_Int : constant Boolean :=
3481 Is_Floating_Point_Type (Expr_Type)
3482 and then Is_Integer_Type (Target_Type);
3484 begin
3485 if not Overflow_Checks_Suppressed (Target_Base)
3486 and then not Overflow_Checks_Suppressed (Target_Type)
3487 and then not
3488 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
3489 and then not Float_To_Int
3490 then
3491 -- A small optimization: the attribute 'Pos applied to an
3492 -- enumeration type has a known range, even though its type is
3493 -- Universal_Integer. So in numeric conversions it is usually
3494 -- within range of the target integer type. Use the static
3495 -- bounds of the base types to check. Disable this optimization
3496 -- in case of a generic formal discrete type, because we don't
3497 -- necessarily know the upper bound yet.
3499 if Nkind (Expr) = N_Attribute_Reference
3500 and then Attribute_Name (Expr) = Name_Pos
3501 and then Is_Enumeration_Type (Etype (Prefix (Expr)))
3502 and then not Is_Generic_Type (Etype (Prefix (Expr)))
3503 and then Is_Integer_Type (Target_Type)
3504 then
3505 declare
3506 Enum_T : constant Entity_Id :=
3507 Root_Type (Etype (Prefix (Expr)));
3508 Int_T : constant Entity_Id := Base_Type (Target_Type);
3509 Last_I : constant Uint :=
3510 Intval (High_Bound (Scalar_Range (Int_T)));
3511 Last_E : Uint;
3513 begin
3514 -- Character types have no explicit literals, so we use
3515 -- the known number of characters in the type.
3517 if Root_Type (Enum_T) = Standard_Character then
3518 Last_E := UI_From_Int (255);
3520 elsif Enum_T = Standard_Wide_Character
3521 or else Enum_T = Standard_Wide_Wide_Character
3522 then
3523 Last_E := UI_From_Int (65535);
3525 else
3526 Last_E :=
3527 Enumeration_Pos
3528 (Entity (High_Bound (Scalar_Range (Enum_T))));
3529 end if;
3531 if Last_E <= Last_I then
3532 null;
3534 else
3535 Activate_Overflow_Check (N);
3536 end if;
3537 end;
3539 else
3540 Activate_Overflow_Check (N);
3541 end if;
3542 end if;
3544 if not Range_Checks_Suppressed (Target_Type)
3545 and then not Range_Checks_Suppressed (Expr_Type)
3546 then
3547 if Float_To_Int
3548 and then not GNATprove_Mode
3549 then
3550 Apply_Float_Conversion_Check (Expr, Target_Type);
3552 else
3553 Apply_Scalar_Range_Check
3554 (Expr, Target_Type, Fixed_Int => Conv_OK);
3556 -- If the target type has predicates, we need to indicate
3557 -- the need for a check, even if Determine_Range finds that
3558 -- the value is within bounds. This may be the case e.g for
3559 -- a division with a constant denominator.
3561 if Has_Predicates (Target_Type) then
3562 Enable_Range_Check (Expr);
3563 end if;
3564 end if;
3565 end if;
3566 end;
3568 elsif Comes_From_Source (N)
3569 and then not Discriminant_Checks_Suppressed (Target_Type)
3570 and then Is_Record_Type (Target_Type)
3571 and then Is_Derived_Type (Target_Type)
3572 and then not Is_Tagged_Type (Target_Type)
3573 and then not Is_Constrained (Target_Type)
3574 and then Present (Stored_Constraint (Target_Type))
3575 then
3576 -- An unconstrained derived type may have inherited discriminant.
3577 -- Build an actual discriminant constraint list using the stored
3578 -- constraint, to verify that the expression of the parent type
3579 -- satisfies the constraints imposed by the (unconstrained) derived
3580 -- type. This applies to value conversions, not to view conversions
3581 -- of tagged types.
3583 declare
3584 Loc : constant Source_Ptr := Sloc (N);
3585 Cond : Node_Id;
3586 Constraint : Elmt_Id;
3587 Discr_Value : Node_Id;
3588 Discr : Entity_Id;
3590 New_Constraints : constant Elist_Id := New_Elmt_List;
3591 Old_Constraints : constant Elist_Id :=
3592 Discriminant_Constraint (Expr_Type);
3594 begin
3595 Constraint := First_Elmt (Stored_Constraint (Target_Type));
3596 while Present (Constraint) loop
3597 Discr_Value := Node (Constraint);
3599 if Is_Entity_Name (Discr_Value)
3600 and then Ekind (Entity (Discr_Value)) = E_Discriminant
3601 then
3602 Discr := Corresponding_Discriminant (Entity (Discr_Value));
3604 if Present (Discr)
3605 and then Scope (Discr) = Base_Type (Expr_Type)
3606 then
3607 -- Parent is constrained by new discriminant. Obtain
3608 -- Value of original discriminant in expression. If the
3609 -- new discriminant has been used to constrain more than
3610 -- one of the stored discriminants, this will provide the
3611 -- required consistency check.
3613 Append_Elmt
3614 (Make_Selected_Component (Loc,
3615 Prefix =>
3616 Duplicate_Subexpr_No_Checks
3617 (Expr, Name_Req => True),
3618 Selector_Name =>
3619 Make_Identifier (Loc, Chars (Discr))),
3620 New_Constraints);
3622 else
3623 -- Discriminant of more remote ancestor ???
3625 return;
3626 end if;
3628 -- Derived type definition has an explicit value for this
3629 -- stored discriminant.
3631 else
3632 Append_Elmt
3633 (Duplicate_Subexpr_No_Checks (Discr_Value),
3634 New_Constraints);
3635 end if;
3637 Next_Elmt (Constraint);
3638 end loop;
3640 -- Use the unconstrained expression type to retrieve the
3641 -- discriminants of the parent, and apply momentarily the
3642 -- discriminant constraint synthesized above.
3644 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
3645 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
3646 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
3648 Insert_Action (N,
3649 Make_Raise_Constraint_Error (Loc,
3650 Condition => Cond,
3651 Reason => CE_Discriminant_Check_Failed));
3652 end;
3654 -- For arrays, checks are set now, but conversions are applied during
3655 -- expansion, to take into accounts changes of representation. The
3656 -- checks become range checks on the base type or length checks on the
3657 -- subtype, depending on whether the target type is unconstrained or
3658 -- constrained. Note that the range check is put on the expression of a
3659 -- type conversion, while the length check is put on the type conversion
3660 -- itself.
3662 elsif Is_Array_Type (Target_Type) then
3663 if Is_Constrained (Target_Type) then
3664 Set_Do_Length_Check (N);
3665 else
3666 Set_Do_Range_Check (Expr);
3667 end if;
3668 end if;
3669 end Apply_Type_Conversion_Checks;
3671 ----------------------------------------------
3672 -- Apply_Universal_Integer_Attribute_Checks --
3673 ----------------------------------------------
3675 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
3676 Loc : constant Source_Ptr := Sloc (N);
3677 Typ : constant Entity_Id := Etype (N);
3679 begin
3680 if Inside_A_Generic then
3681 return;
3683 -- Nothing to do if checks are suppressed
3685 elsif Range_Checks_Suppressed (Typ)
3686 and then Overflow_Checks_Suppressed (Typ)
3687 then
3688 return;
3690 -- Nothing to do if the attribute does not come from source. The
3691 -- internal attributes we generate of this type do not need checks,
3692 -- and furthermore the attempt to check them causes some circular
3693 -- elaboration orders when dealing with packed types.
3695 elsif not Comes_From_Source (N) then
3696 return;
3698 -- If the prefix is a selected component that depends on a discriminant
3699 -- the check may improperly expose a discriminant instead of using
3700 -- the bounds of the object itself. Set the type of the attribute to
3701 -- the base type of the context, so that a check will be imposed when
3702 -- needed (e.g. if the node appears as an index).
3704 elsif Nkind (Prefix (N)) = N_Selected_Component
3705 and then Ekind (Typ) = E_Signed_Integer_Subtype
3706 and then Depends_On_Discriminant (Scalar_Range (Typ))
3707 then
3708 Set_Etype (N, Base_Type (Typ));
3710 -- Otherwise, replace the attribute node with a type conversion node
3711 -- whose expression is the attribute, retyped to universal integer, and
3712 -- whose subtype mark is the target type. The call to analyze this
3713 -- conversion will set range and overflow checks as required for proper
3714 -- detection of an out of range value.
3716 else
3717 Set_Etype (N, Universal_Integer);
3718 Set_Analyzed (N, True);
3720 Rewrite (N,
3721 Make_Type_Conversion (Loc,
3722 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
3723 Expression => Relocate_Node (N)));
3725 Analyze_And_Resolve (N, Typ);
3726 return;
3727 end if;
3728 end Apply_Universal_Integer_Attribute_Checks;
3730 -------------------------------------
3731 -- Atomic_Synchronization_Disabled --
3732 -------------------------------------
3734 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3735 -- using a bogus check called Atomic_Synchronization. This is to make it
3736 -- more convenient to get exactly the same semantics as [Un]Suppress.
3738 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean is
3739 begin
3740 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3741 -- looks enabled, since it is never disabled.
3743 if Debug_Flag_Dot_E then
3744 return False;
3746 -- If debug flag d.d is set then always return True, i.e. all atomic
3747 -- sync looks disabled, since it always tests True.
3749 elsif Debug_Flag_Dot_D then
3750 return True;
3752 -- If entity present, then check result for that entity
3754 elsif Present (E) and then Checks_May_Be_Suppressed (E) then
3755 return Is_Check_Suppressed (E, Atomic_Synchronization);
3757 -- Otherwise result depends on current scope setting
3759 else
3760 return Scope_Suppress.Suppress (Atomic_Synchronization);
3761 end if;
3762 end Atomic_Synchronization_Disabled;
3764 -------------------------------
3765 -- Build_Discriminant_Checks --
3766 -------------------------------
3768 function Build_Discriminant_Checks
3769 (N : Node_Id;
3770 T_Typ : Entity_Id) return Node_Id
3772 Loc : constant Source_Ptr := Sloc (N);
3773 Cond : Node_Id;
3774 Disc : Elmt_Id;
3775 Disc_Ent : Entity_Id;
3776 Dref : Node_Id;
3777 Dval : Node_Id;
3779 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
3781 --------------------------------
3782 -- Aggregate_Discriminant_Val --
3783 --------------------------------
3785 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
3786 Assoc : Node_Id;
3788 begin
3789 -- The aggregate has been normalized with named associations. We use
3790 -- the Chars field to locate the discriminant to take into account
3791 -- discriminants in derived types, which carry the same name as those
3792 -- in the parent.
3794 Assoc := First (Component_Associations (N));
3795 while Present (Assoc) loop
3796 if Chars (First (Choices (Assoc))) = Chars (Disc) then
3797 return Expression (Assoc);
3798 else
3799 Next (Assoc);
3800 end if;
3801 end loop;
3803 -- Discriminant must have been found in the loop above
3805 raise Program_Error;
3806 end Aggregate_Discriminant_Val;
3808 -- Start of processing for Build_Discriminant_Checks
3810 begin
3811 -- Loop through discriminants evolving the condition
3813 Cond := Empty;
3814 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
3816 -- For a fully private type, use the discriminants of the parent type
3818 if Is_Private_Type (T_Typ)
3819 and then No (Full_View (T_Typ))
3820 then
3821 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
3822 else
3823 Disc_Ent := First_Discriminant (T_Typ);
3824 end if;
3826 while Present (Disc) loop
3827 Dval := Node (Disc);
3829 if Nkind (Dval) = N_Identifier
3830 and then Ekind (Entity (Dval)) = E_Discriminant
3831 then
3832 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
3833 else
3834 Dval := Duplicate_Subexpr_No_Checks (Dval);
3835 end if;
3837 -- If we have an Unchecked_Union node, we can infer the discriminants
3838 -- of the node.
3840 if Is_Unchecked_Union (Base_Type (T_Typ)) then
3841 Dref := New_Copy (
3842 Get_Discriminant_Value (
3843 First_Discriminant (T_Typ),
3844 T_Typ,
3845 Stored_Constraint (T_Typ)));
3847 elsif Nkind (N) = N_Aggregate then
3848 Dref :=
3849 Duplicate_Subexpr_No_Checks
3850 (Aggregate_Discriminant_Val (Disc_Ent));
3852 else
3853 Dref :=
3854 Make_Selected_Component (Loc,
3855 Prefix =>
3856 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
3857 Selector_Name => Make_Identifier (Loc, Chars (Disc_Ent)));
3859 Set_Is_In_Discriminant_Check (Dref);
3860 end if;
3862 Evolve_Or_Else (Cond,
3863 Make_Op_Ne (Loc,
3864 Left_Opnd => Dref,
3865 Right_Opnd => Dval));
3867 Next_Elmt (Disc);
3868 Next_Discriminant (Disc_Ent);
3869 end loop;
3871 return Cond;
3872 end Build_Discriminant_Checks;
3874 ------------------
3875 -- Check_Needed --
3876 ------------------
3878 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
3879 N : Node_Id;
3880 P : Node_Id;
3881 K : Node_Kind;
3882 L : Node_Id;
3883 R : Node_Id;
3885 function Left_Expression (Op : Node_Id) return Node_Id;
3886 -- Return the relevant expression from the left operand of the given
3887 -- short circuit form: this is LO itself, except if LO is a qualified
3888 -- expression, a type conversion, or an expression with actions, in
3889 -- which case this is Left_Expression (Expression (LO)).
3891 ---------------------
3892 -- Left_Expression --
3893 ---------------------
3895 function Left_Expression (Op : Node_Id) return Node_Id is
3896 LE : Node_Id := Left_Opnd (Op);
3897 begin
3898 while Nkind_In (LE, N_Qualified_Expression,
3899 N_Type_Conversion,
3900 N_Expression_With_Actions)
3901 loop
3902 LE := Expression (LE);
3903 end loop;
3905 return LE;
3906 end Left_Expression;
3908 -- Start of processing for Check_Needed
3910 begin
3911 -- Always check if not simple entity
3913 if Nkind (Nod) not in N_Has_Entity
3914 or else not Comes_From_Source (Nod)
3915 then
3916 return True;
3917 end if;
3919 -- Look up tree for short circuit
3921 N := Nod;
3922 loop
3923 P := Parent (N);
3924 K := Nkind (P);
3926 -- Done if out of subexpression (note that we allow generated stuff
3927 -- such as itype declarations in this context, to keep the loop going
3928 -- since we may well have generated such stuff in complex situations.
3929 -- Also done if no parent (probably an error condition, but no point
3930 -- in behaving nasty if we find it).
3932 if No (P)
3933 or else (K not in N_Subexpr and then Comes_From_Source (P))
3934 then
3935 return True;
3937 -- Or/Or Else case, where test is part of the right operand, or is
3938 -- part of one of the actions associated with the right operand, and
3939 -- the left operand is an equality test.
3941 elsif K = N_Op_Or then
3942 exit when N = Right_Opnd (P)
3943 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3945 elsif K = N_Or_Else then
3946 exit when (N = Right_Opnd (P)
3947 or else
3948 (Is_List_Member (N)
3949 and then List_Containing (N) = Actions (P)))
3950 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3952 -- Similar test for the And/And then case, where the left operand
3953 -- is an inequality test.
3955 elsif K = N_Op_And then
3956 exit when N = Right_Opnd (P)
3957 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3959 elsif K = N_And_Then then
3960 exit when (N = Right_Opnd (P)
3961 or else
3962 (Is_List_Member (N)
3963 and then List_Containing (N) = Actions (P)))
3964 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3965 end if;
3967 N := P;
3968 end loop;
3970 -- If we fall through the loop, then we have a conditional with an
3971 -- appropriate test as its left operand, so look further.
3973 L := Left_Expression (P);
3975 -- L is an "=" or "/=" operator: extract its operands
3977 R := Right_Opnd (L);
3978 L := Left_Opnd (L);
3980 -- Left operand of test must match original variable
3982 if Nkind (L) not in N_Has_Entity or else Entity (L) /= Entity (Nod) then
3983 return True;
3984 end if;
3986 -- Right operand of test must be key value (zero or null)
3988 case Check is
3989 when Access_Check =>
3990 if not Known_Null (R) then
3991 return True;
3992 end if;
3994 when Division_Check =>
3995 if not Compile_Time_Known_Value (R)
3996 or else Expr_Value (R) /= Uint_0
3997 then
3998 return True;
3999 end if;
4001 when others =>
4002 raise Program_Error;
4003 end case;
4005 -- Here we have the optimizable case, warn if not short-circuited
4007 if K = N_Op_And or else K = N_Op_Or then
4008 Error_Msg_Warn := SPARK_Mode /= On;
4010 case Check is
4011 when Access_Check =>
4012 if GNATprove_Mode then
4013 Error_Msg_N
4014 ("Constraint_Error might have been raised (access check)",
4015 Parent (Nod));
4016 else
4017 Error_Msg_N
4018 ("Constraint_Error may be raised (access check)??",
4019 Parent (Nod));
4020 end if;
4022 when Division_Check =>
4023 if GNATprove_Mode then
4024 Error_Msg_N
4025 ("Constraint_Error might have been raised (zero divide)",
4026 Parent (Nod));
4027 else
4028 Error_Msg_N
4029 ("Constraint_Error may be raised (zero divide)??",
4030 Parent (Nod));
4031 end if;
4033 when others =>
4034 raise Program_Error;
4035 end case;
4037 if K = N_Op_And then
4038 Error_Msg_N -- CODEFIX
4039 ("use `AND THEN` instead of AND??", P);
4040 else
4041 Error_Msg_N -- CODEFIX
4042 ("use `OR ELSE` instead of OR??", P);
4043 end if;
4045 -- If not short-circuited, we need the check
4047 return True;
4049 -- If short-circuited, we can omit the check
4051 else
4052 return False;
4053 end if;
4054 end Check_Needed;
4056 -----------------------------------
4057 -- Check_Valid_Lvalue_Subscripts --
4058 -----------------------------------
4060 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
4061 begin
4062 -- Skip this if range checks are suppressed
4064 if Range_Checks_Suppressed (Etype (Expr)) then
4065 return;
4067 -- Only do this check for expressions that come from source. We assume
4068 -- that expander generated assignments explicitly include any necessary
4069 -- checks. Note that this is not just an optimization, it avoids
4070 -- infinite recursions.
4072 elsif not Comes_From_Source (Expr) then
4073 return;
4075 -- For a selected component, check the prefix
4077 elsif Nkind (Expr) = N_Selected_Component then
4078 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4079 return;
4081 -- Case of indexed component
4083 elsif Nkind (Expr) = N_Indexed_Component then
4084 Apply_Subscript_Validity_Checks (Expr);
4086 -- Prefix may itself be or contain an indexed component, and these
4087 -- subscripts need checking as well.
4089 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4090 end if;
4091 end Check_Valid_Lvalue_Subscripts;
4093 ----------------------------------
4094 -- Null_Exclusion_Static_Checks --
4095 ----------------------------------
4097 procedure Null_Exclusion_Static_Checks
4098 (N : Node_Id;
4099 Comp : Node_Id := Empty;
4100 Array_Comp : Boolean := False)
4102 Has_Null : constant Boolean := Has_Null_Exclusion (N);
4103 Kind : constant Node_Kind := Nkind (N);
4104 Error_Nod : Node_Id;
4105 Expr : Node_Id;
4106 Typ : Entity_Id;
4108 begin
4109 pragma Assert
4110 (Nkind_In (Kind, N_Component_Declaration,
4111 N_Discriminant_Specification,
4112 N_Function_Specification,
4113 N_Object_Declaration,
4114 N_Parameter_Specification));
4116 if Kind = N_Function_Specification then
4117 Typ := Etype (Defining_Entity (N));
4118 else
4119 Typ := Etype (Defining_Identifier (N));
4120 end if;
4122 case Kind is
4123 when N_Component_Declaration =>
4124 if Present (Access_Definition (Component_Definition (N))) then
4125 Error_Nod := Component_Definition (N);
4126 else
4127 Error_Nod := Subtype_Indication (Component_Definition (N));
4128 end if;
4130 when N_Discriminant_Specification =>
4131 Error_Nod := Discriminant_Type (N);
4133 when N_Function_Specification =>
4134 Error_Nod := Result_Definition (N);
4136 when N_Object_Declaration =>
4137 Error_Nod := Object_Definition (N);
4139 when N_Parameter_Specification =>
4140 Error_Nod := Parameter_Type (N);
4142 when others =>
4143 raise Program_Error;
4144 end case;
4146 if Has_Null then
4148 -- Enforce legality rule 3.10 (13): A null exclusion can only be
4149 -- applied to an access [sub]type.
4151 if not Is_Access_Type (Typ) then
4152 Error_Msg_N
4153 ("`NOT NULL` allowed only for an access type", Error_Nod);
4155 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
4156 -- be applied to a [sub]type that does not exclude null already.
4158 elsif Can_Never_Be_Null (Typ) and then Comes_From_Source (Typ) then
4159 Error_Msg_NE
4160 ("`NOT NULL` not allowed (& already excludes null)",
4161 Error_Nod, Typ);
4162 end if;
4163 end if;
4165 -- Check that null-excluding objects are always initialized, except for
4166 -- deferred constants, for which the expression will appear in the full
4167 -- declaration.
4169 if Kind = N_Object_Declaration
4170 and then No (Expression (N))
4171 and then not Constant_Present (N)
4172 and then not No_Initialization (N)
4173 then
4174 if Present (Comp) then
4176 -- Specialize the warning message to indicate that we are dealing
4177 -- with an uninitialized composite object that has a defaulted
4178 -- null-excluding component.
4180 Error_Msg_Name_1 := Chars (Defining_Identifier (Comp));
4181 Error_Msg_Name_2 := Chars (Defining_Identifier (N));
4183 Discard_Node
4184 (Compile_Time_Constraint_Error
4185 (N => N,
4186 Msg =>
4187 "(Ada 2005) null-excluding component % of object % must "
4188 & "be initialized??",
4189 Ent => Defining_Identifier (Comp)));
4191 -- This is a case of an array with null-excluding components, so
4192 -- indicate that in the warning.
4194 elsif Array_Comp then
4195 Discard_Node
4196 (Compile_Time_Constraint_Error
4197 (N => N,
4198 Msg =>
4199 "(Ada 2005) null-excluding array components must "
4200 & "be initialized??",
4201 Ent => Defining_Identifier (N)));
4203 -- Normal case of object of a null-excluding access type
4205 else
4206 -- Add an expression that assigns null. This node is needed by
4207 -- Apply_Compile_Time_Constraint_Error, which will replace this
4208 -- with a Constraint_Error node.
4210 Set_Expression (N, Make_Null (Sloc (N)));
4211 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
4213 Apply_Compile_Time_Constraint_Error
4214 (N => Expression (N),
4215 Msg =>
4216 "(Ada 2005) null-excluding objects must be initialized??",
4217 Reason => CE_Null_Not_Allowed);
4218 end if;
4219 end if;
4221 -- Check that a null-excluding component, formal or object is not being
4222 -- assigned a null value. Otherwise generate a warning message and
4223 -- replace Expression (N) by an N_Constraint_Error node.
4225 if Kind /= N_Function_Specification then
4226 Expr := Expression (N);
4228 if Present (Expr) and then Known_Null (Expr) then
4229 case Kind is
4230 when N_Component_Declaration
4231 | N_Discriminant_Specification
4233 Apply_Compile_Time_Constraint_Error
4234 (N => Expr,
4235 Msg =>
4236 "(Ada 2005) null not allowed in null-excluding "
4237 & "components??",
4238 Reason => CE_Null_Not_Allowed);
4240 when N_Object_Declaration =>
4241 Apply_Compile_Time_Constraint_Error
4242 (N => Expr,
4243 Msg =>
4244 "(Ada 2005) null not allowed in null-excluding "
4245 & "objects??",
4246 Reason => CE_Null_Not_Allowed);
4248 when N_Parameter_Specification =>
4249 Apply_Compile_Time_Constraint_Error
4250 (N => Expr,
4251 Msg =>
4252 "(Ada 2005) null not allowed in null-excluding "
4253 & "formals??",
4254 Reason => CE_Null_Not_Allowed);
4256 when others =>
4257 null;
4258 end case;
4259 end if;
4260 end if;
4261 end Null_Exclusion_Static_Checks;
4263 ----------------------------------
4264 -- Conditional_Statements_Begin --
4265 ----------------------------------
4267 procedure Conditional_Statements_Begin is
4268 begin
4269 Saved_Checks_TOS := Saved_Checks_TOS + 1;
4271 -- If stack overflows, kill all checks, that way we know to simply reset
4272 -- the number of saved checks to zero on return. This should never occur
4273 -- in practice.
4275 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4276 Kill_All_Checks;
4278 -- In the normal case, we just make a new stack entry saving the current
4279 -- number of saved checks for a later restore.
4281 else
4282 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
4284 if Debug_Flag_CC then
4285 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
4286 Num_Saved_Checks);
4287 end if;
4288 end if;
4289 end Conditional_Statements_Begin;
4291 --------------------------------
4292 -- Conditional_Statements_End --
4293 --------------------------------
4295 procedure Conditional_Statements_End is
4296 begin
4297 pragma Assert (Saved_Checks_TOS > 0);
4299 -- If the saved checks stack overflowed, then we killed all checks, so
4300 -- setting the number of saved checks back to zero is correct. This
4301 -- should never occur in practice.
4303 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4304 Num_Saved_Checks := 0;
4306 -- In the normal case, restore the number of saved checks from the top
4307 -- stack entry.
4309 else
4310 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
4312 if Debug_Flag_CC then
4313 w ("Conditional_Statements_End: Num_Saved_Checks = ",
4314 Num_Saved_Checks);
4315 end if;
4316 end if;
4318 Saved_Checks_TOS := Saved_Checks_TOS - 1;
4319 end Conditional_Statements_End;
4321 -------------------------
4322 -- Convert_From_Bignum --
4323 -------------------------
4325 function Convert_From_Bignum (N : Node_Id) return Node_Id is
4326 Loc : constant Source_Ptr := Sloc (N);
4328 begin
4329 pragma Assert (Is_RTE (Etype (N), RE_Bignum));
4331 -- Construct call From Bignum
4333 return
4334 Make_Function_Call (Loc,
4335 Name =>
4336 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
4337 Parameter_Associations => New_List (Relocate_Node (N)));
4338 end Convert_From_Bignum;
4340 -----------------------
4341 -- Convert_To_Bignum --
4342 -----------------------
4344 function Convert_To_Bignum (N : Node_Id) return Node_Id is
4345 Loc : constant Source_Ptr := Sloc (N);
4347 begin
4348 -- Nothing to do if Bignum already except call Relocate_Node
4350 if Is_RTE (Etype (N), RE_Bignum) then
4351 return Relocate_Node (N);
4353 -- Otherwise construct call to To_Bignum, converting the operand to the
4354 -- required Long_Long_Integer form.
4356 else
4357 pragma Assert (Is_Signed_Integer_Type (Etype (N)));
4358 return
4359 Make_Function_Call (Loc,
4360 Name =>
4361 New_Occurrence_Of (RTE (RE_To_Bignum), Loc),
4362 Parameter_Associations => New_List (
4363 Convert_To (Standard_Long_Long_Integer, Relocate_Node (N))));
4364 end if;
4365 end Convert_To_Bignum;
4367 ---------------------
4368 -- Determine_Range --
4369 ---------------------
4371 Cache_Size : constant := 2 ** 10;
4372 type Cache_Index is range 0 .. Cache_Size - 1;
4373 -- Determine size of below cache (power of 2 is more efficient)
4375 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
4376 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
4377 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
4378 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
4379 Determine_Range_Cache_Lo_R : array (Cache_Index) of Ureal;
4380 Determine_Range_Cache_Hi_R : array (Cache_Index) of Ureal;
4381 -- The above arrays are used to implement a small direct cache for
4382 -- Determine_Range and Determine_Range_R calls. Because of the way these
4383 -- subprograms recursively traces subexpressions, and because overflow
4384 -- checking calls the routine on the way up the tree, a quadratic behavior
4385 -- can otherwise be encountered in large expressions. The cache entry for
4386 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4387 -- by checking the actual node value stored there. The Range_Cache_V array
4388 -- records the setting of Assume_Valid for the cache entry.
4390 procedure Determine_Range
4391 (N : Node_Id;
4392 OK : out Boolean;
4393 Lo : out Uint;
4394 Hi : out Uint;
4395 Assume_Valid : Boolean := False)
4397 Typ : Entity_Id := Etype (N);
4398 -- Type to use, may get reset to base type for possibly invalid entity
4400 Lo_Left : Uint;
4401 Hi_Left : Uint;
4402 -- Lo and Hi bounds of left operand
4404 Lo_Right : Uint := No_Uint;
4405 Hi_Right : Uint := No_Uint;
4406 -- Lo and Hi bounds of right (or only) operand
4408 Bound : Node_Id;
4409 -- Temp variable used to hold a bound node
4411 Hbound : Uint;
4412 -- High bound of base type of expression
4414 Lor : Uint;
4415 Hir : Uint;
4416 -- Refined values for low and high bounds, after tightening
4418 OK1 : Boolean;
4419 -- Used in lower level calls to indicate if call succeeded
4421 Cindex : Cache_Index;
4422 -- Used to search cache
4424 Btyp : Entity_Id;
4425 -- Base type
4427 function OK_Operands return Boolean;
4428 -- Used for binary operators. Determines the ranges of the left and
4429 -- right operands, and if they are both OK, returns True, and puts
4430 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4432 -----------------
4433 -- OK_Operands --
4434 -----------------
4436 function OK_Operands return Boolean is
4437 begin
4438 Determine_Range
4439 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4441 if not OK1 then
4442 return False;
4443 end if;
4445 Determine_Range
4446 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4447 return OK1;
4448 end OK_Operands;
4450 -- Start of processing for Determine_Range
4452 begin
4453 -- Prevent junk warnings by initializing range variables
4455 Lo := No_Uint;
4456 Hi := No_Uint;
4457 Lor := No_Uint;
4458 Hir := No_Uint;
4460 -- For temporary constants internally generated to remove side effects
4461 -- we must use the corresponding expression to determine the range of
4462 -- the expression. But note that the expander can also generate
4463 -- constants in other cases, including deferred constants.
4465 if Is_Entity_Name (N)
4466 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
4467 and then Ekind (Entity (N)) = E_Constant
4468 and then Is_Internal_Name (Chars (Entity (N)))
4469 then
4470 if Present (Expression (Parent (Entity (N)))) then
4471 Determine_Range
4472 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
4474 elsif Present (Full_View (Entity (N))) then
4475 Determine_Range
4476 (Expression (Parent (Full_View (Entity (N)))),
4477 OK, Lo, Hi, Assume_Valid);
4479 else
4480 OK := False;
4481 end if;
4482 return;
4483 end if;
4485 -- If type is not defined, we can't determine its range
4487 if No (Typ)
4489 -- We don't deal with anything except discrete types
4491 or else not Is_Discrete_Type (Typ)
4493 -- Don't deal with enumerated types with non-standard representation
4495 or else (Is_Enumeration_Type (Typ)
4496 and then Present (Enum_Pos_To_Rep (Base_Type (Typ))))
4498 -- Ignore type for which an error has been posted, since range in
4499 -- this case may well be a bogosity deriving from the error. Also
4500 -- ignore if error posted on the reference node.
4502 or else Error_Posted (N) or else Error_Posted (Typ)
4503 then
4504 OK := False;
4505 return;
4506 end if;
4508 -- For all other cases, we can determine the range
4510 OK := True;
4512 -- If value is compile time known, then the possible range is the one
4513 -- value that we know this expression definitely has.
4515 if Compile_Time_Known_Value (N) then
4516 Lo := Expr_Value (N);
4517 Hi := Lo;
4518 return;
4519 end if;
4521 -- Return if already in the cache
4523 Cindex := Cache_Index (N mod Cache_Size);
4525 if Determine_Range_Cache_N (Cindex) = N
4526 and then
4527 Determine_Range_Cache_V (Cindex) = Assume_Valid
4528 then
4529 Lo := Determine_Range_Cache_Lo (Cindex);
4530 Hi := Determine_Range_Cache_Hi (Cindex);
4531 return;
4532 end if;
4534 -- Otherwise, start by finding the bounds of the type of the expression,
4535 -- the value cannot be outside this range (if it is, then we have an
4536 -- overflow situation, which is a separate check, we are talking here
4537 -- only about the expression value).
4539 -- First a check, never try to find the bounds of a generic type, since
4540 -- these bounds are always junk values, and it is only valid to look at
4541 -- the bounds in an instance.
4543 if Is_Generic_Type (Typ) then
4544 OK := False;
4545 return;
4546 end if;
4548 -- First step, change to use base type unless we know the value is valid
4550 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
4551 or else Assume_No_Invalid_Values
4552 or else Assume_Valid
4553 then
4554 null;
4555 else
4556 Typ := Underlying_Type (Base_Type (Typ));
4557 end if;
4559 -- Retrieve the base type. Handle the case where the base type is a
4560 -- private enumeration type.
4562 Btyp := Base_Type (Typ);
4564 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
4565 Btyp := Full_View (Btyp);
4566 end if;
4568 -- We use the actual bound unless it is dynamic, in which case use the
4569 -- corresponding base type bound if possible. If we can't get a bound
4570 -- then we figure we can't determine the range (a peculiar case, that
4571 -- perhaps cannot happen, but there is no point in bombing in this
4572 -- optimization circuit.
4574 -- First the low bound
4576 Bound := Type_Low_Bound (Typ);
4578 if Compile_Time_Known_Value (Bound) then
4579 Lo := Expr_Value (Bound);
4581 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
4582 Lo := Expr_Value (Type_Low_Bound (Btyp));
4584 else
4585 OK := False;
4586 return;
4587 end if;
4589 -- Now the high bound
4591 Bound := Type_High_Bound (Typ);
4593 -- We need the high bound of the base type later on, and this should
4594 -- always be compile time known. Again, it is not clear that this
4595 -- can ever be false, but no point in bombing.
4597 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
4598 Hbound := Expr_Value (Type_High_Bound (Btyp));
4599 Hi := Hbound;
4601 else
4602 OK := False;
4603 return;
4604 end if;
4606 -- If we have a static subtype, then that may have a tighter bound so
4607 -- use the upper bound of the subtype instead in this case.
4609 if Compile_Time_Known_Value (Bound) then
4610 Hi := Expr_Value (Bound);
4611 end if;
4613 -- We may be able to refine this value in certain situations. If any
4614 -- refinement is possible, then Lor and Hir are set to possibly tighter
4615 -- bounds, and OK1 is set to True.
4617 case Nkind (N) is
4619 -- For unary plus, result is limited by range of operand
4621 when N_Op_Plus =>
4622 Determine_Range
4623 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
4625 -- For unary minus, determine range of operand, and negate it
4627 when N_Op_Minus =>
4628 Determine_Range
4629 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4631 if OK1 then
4632 Lor := -Hi_Right;
4633 Hir := -Lo_Right;
4634 end if;
4636 -- For binary addition, get range of each operand and do the
4637 -- addition to get the result range.
4639 when N_Op_Add =>
4640 if OK_Operands then
4641 Lor := Lo_Left + Lo_Right;
4642 Hir := Hi_Left + Hi_Right;
4643 end if;
4645 -- Division is tricky. The only case we consider is where the right
4646 -- operand is a positive constant, and in this case we simply divide
4647 -- the bounds of the left operand
4649 when N_Op_Divide =>
4650 if OK_Operands then
4651 if Lo_Right = Hi_Right
4652 and then Lo_Right > 0
4653 then
4654 Lor := Lo_Left / Lo_Right;
4655 Hir := Hi_Left / Lo_Right;
4656 else
4657 OK1 := False;
4658 end if;
4659 end if;
4661 -- For binary subtraction, get range of each operand and do the worst
4662 -- case subtraction to get the result range.
4664 when N_Op_Subtract =>
4665 if OK_Operands then
4666 Lor := Lo_Left - Hi_Right;
4667 Hir := Hi_Left - Lo_Right;
4668 end if;
4670 -- For MOD, if right operand is a positive constant, then result must
4671 -- be in the allowable range of mod results.
4673 when N_Op_Mod =>
4674 if OK_Operands then
4675 if Lo_Right = Hi_Right
4676 and then Lo_Right /= 0
4677 then
4678 if Lo_Right > 0 then
4679 Lor := Uint_0;
4680 Hir := Lo_Right - 1;
4682 else -- Lo_Right < 0
4683 Lor := Lo_Right + 1;
4684 Hir := Uint_0;
4685 end if;
4687 else
4688 OK1 := False;
4689 end if;
4690 end if;
4692 -- For REM, if right operand is a positive constant, then result must
4693 -- be in the allowable range of mod results.
4695 when N_Op_Rem =>
4696 if OK_Operands then
4697 if Lo_Right = Hi_Right and then Lo_Right /= 0 then
4698 declare
4699 Dval : constant Uint := (abs Lo_Right) - 1;
4701 begin
4702 -- The sign of the result depends on the sign of the
4703 -- dividend (but not on the sign of the divisor, hence
4704 -- the abs operation above).
4706 if Lo_Left < 0 then
4707 Lor := -Dval;
4708 else
4709 Lor := Uint_0;
4710 end if;
4712 if Hi_Left < 0 then
4713 Hir := Uint_0;
4714 else
4715 Hir := Dval;
4716 end if;
4717 end;
4719 else
4720 OK1 := False;
4721 end if;
4722 end if;
4724 -- Attribute reference cases
4726 when N_Attribute_Reference =>
4727 case Attribute_Name (N) is
4729 -- For Pos/Val attributes, we can refine the range using the
4730 -- possible range of values of the attribute expression.
4732 when Name_Pos
4733 | Name_Val
4735 Determine_Range
4736 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
4738 -- For Length attribute, use the bounds of the corresponding
4739 -- index type to refine the range.
4741 when Name_Length =>
4742 declare
4743 Atyp : Entity_Id := Etype (Prefix (N));
4744 Inum : Nat;
4745 Indx : Node_Id;
4747 LL, LU : Uint;
4748 UL, UU : Uint;
4750 begin
4751 if Is_Access_Type (Atyp) then
4752 Atyp := Designated_Type (Atyp);
4753 end if;
4755 -- For string literal, we know exact value
4757 if Ekind (Atyp) = E_String_Literal_Subtype then
4758 OK := True;
4759 Lo := String_Literal_Length (Atyp);
4760 Hi := String_Literal_Length (Atyp);
4761 return;
4762 end if;
4764 -- Otherwise check for expression given
4766 if No (Expressions (N)) then
4767 Inum := 1;
4768 else
4769 Inum :=
4770 UI_To_Int (Expr_Value (First (Expressions (N))));
4771 end if;
4773 Indx := First_Index (Atyp);
4774 for J in 2 .. Inum loop
4775 Indx := Next_Index (Indx);
4776 end loop;
4778 -- If the index type is a formal type or derived from
4779 -- one, the bounds are not static.
4781 if Is_Generic_Type (Root_Type (Etype (Indx))) then
4782 OK := False;
4783 return;
4784 end if;
4786 Determine_Range
4787 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
4788 Assume_Valid);
4790 if OK1 then
4791 Determine_Range
4792 (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
4793 Assume_Valid);
4795 if OK1 then
4797 -- The maximum value for Length is the biggest
4798 -- possible gap between the values of the bounds.
4799 -- But of course, this value cannot be negative.
4801 Hir := UI_Max (Uint_0, UU - LL + 1);
4803 -- For constrained arrays, the minimum value for
4804 -- Length is taken from the actual value of the
4805 -- bounds, since the index will be exactly of this
4806 -- subtype.
4808 if Is_Constrained (Atyp) then
4809 Lor := UI_Max (Uint_0, UL - LU + 1);
4811 -- For an unconstrained array, the minimum value
4812 -- for length is always zero.
4814 else
4815 Lor := Uint_0;
4816 end if;
4817 end if;
4818 end if;
4819 end;
4821 -- No special handling for other attributes
4822 -- Probably more opportunities exist here???
4824 when others =>
4825 OK1 := False;
4827 end case;
4829 when N_Type_Conversion =>
4831 -- For type conversion from one discrete type to another, we can
4832 -- refine the range using the converted value.
4834 if Is_Discrete_Type (Etype (Expression (N))) then
4835 Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
4837 -- When converting a float to an integer type, determine the range
4838 -- in real first, and then convert the bounds using UR_To_Uint
4839 -- which correctly rounds away from zero when half way between two
4840 -- integers, as required by normal Ada 95 rounding semantics. It
4841 -- is only possible because analysis in GNATprove rules out the
4842 -- possibility of a NaN or infinite value.
4844 elsif GNATprove_Mode
4845 and then Is_Floating_Point_Type (Etype (Expression (N)))
4846 then
4847 declare
4848 Lor_Real, Hir_Real : Ureal;
4849 begin
4850 Determine_Range_R (Expression (N), OK1, Lor_Real, Hir_Real,
4851 Assume_Valid);
4853 if OK1 then
4854 Lor := UR_To_Uint (Lor_Real);
4855 Hir := UR_To_Uint (Hir_Real);
4856 end if;
4857 end;
4859 else
4860 OK1 := False;
4861 end if;
4863 -- Nothing special to do for all other expression kinds
4865 when others =>
4866 OK1 := False;
4867 Lor := No_Uint;
4868 Hir := No_Uint;
4869 end case;
4871 -- At this stage, if OK1 is true, then we know that the actual result of
4872 -- the computed expression is in the range Lor .. Hir. We can use this
4873 -- to restrict the possible range of results.
4875 if OK1 then
4877 -- If the refined value of the low bound is greater than the type
4878 -- low bound, then reset it to the more restrictive value. However,
4879 -- we do NOT do this for the case of a modular type where the
4880 -- possible upper bound on the value is above the base type high
4881 -- bound, because that means the result could wrap.
4883 if Lor > Lo
4884 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
4885 then
4886 Lo := Lor;
4887 end if;
4889 -- Similarly, if the refined value of the high bound is less than the
4890 -- value so far, then reset it to the more restrictive value. Again,
4891 -- we do not do this if the refined low bound is negative for a
4892 -- modular type, since this would wrap.
4894 if Hir < Hi
4895 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
4896 then
4897 Hi := Hir;
4898 end if;
4899 end if;
4901 -- Set cache entry for future call and we are all done
4903 Determine_Range_Cache_N (Cindex) := N;
4904 Determine_Range_Cache_V (Cindex) := Assume_Valid;
4905 Determine_Range_Cache_Lo (Cindex) := Lo;
4906 Determine_Range_Cache_Hi (Cindex) := Hi;
4907 return;
4909 -- If any exception occurs, it means that we have some bug in the compiler,
4910 -- possibly triggered by a previous error, or by some unforeseen peculiar
4911 -- occurrence. However, this is only an optimization attempt, so there is
4912 -- really no point in crashing the compiler. Instead we just decide, too
4913 -- bad, we can't figure out a range in this case after all.
4915 exception
4916 when others =>
4918 -- Debug flag K disables this behavior (useful for debugging)
4920 if Debug_Flag_K then
4921 raise;
4922 else
4923 OK := False;
4924 Lo := No_Uint;
4925 Hi := No_Uint;
4926 return;
4927 end if;
4928 end Determine_Range;
4930 -----------------------
4931 -- Determine_Range_R --
4932 -----------------------
4934 procedure Determine_Range_R
4935 (N : Node_Id;
4936 OK : out Boolean;
4937 Lo : out Ureal;
4938 Hi : out Ureal;
4939 Assume_Valid : Boolean := False)
4941 Typ : Entity_Id := Etype (N);
4942 -- Type to use, may get reset to base type for possibly invalid entity
4944 Lo_Left : Ureal;
4945 Hi_Left : Ureal;
4946 -- Lo and Hi bounds of left operand
4948 Lo_Right : Ureal := No_Ureal;
4949 Hi_Right : Ureal := No_Ureal;
4950 -- Lo and Hi bounds of right (or only) operand
4952 Bound : Node_Id;
4953 -- Temp variable used to hold a bound node
4955 Hbound : Ureal;
4956 -- High bound of base type of expression
4958 Lor : Ureal;
4959 Hir : Ureal;
4960 -- Refined values for low and high bounds, after tightening
4962 OK1 : Boolean;
4963 -- Used in lower level calls to indicate if call succeeded
4965 Cindex : Cache_Index;
4966 -- Used to search cache
4968 Btyp : Entity_Id;
4969 -- Base type
4971 function OK_Operands return Boolean;
4972 -- Used for binary operators. Determines the ranges of the left and
4973 -- right operands, and if they are both OK, returns True, and puts
4974 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4976 function Round_Machine (B : Ureal) return Ureal;
4977 -- B is a real bound. Round it using mode Round_Even.
4979 -----------------
4980 -- OK_Operands --
4981 -----------------
4983 function OK_Operands return Boolean is
4984 begin
4985 Determine_Range_R
4986 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4988 if not OK1 then
4989 return False;
4990 end if;
4992 Determine_Range_R
4993 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4994 return OK1;
4995 end OK_Operands;
4997 -------------------
4998 -- Round_Machine --
4999 -------------------
5001 function Round_Machine (B : Ureal) return Ureal is
5002 begin
5003 return Machine (Typ, B, Round_Even, N);
5004 end Round_Machine;
5006 -- Start of processing for Determine_Range_R
5008 begin
5009 -- Prevent junk warnings by initializing range variables
5011 Lo := No_Ureal;
5012 Hi := No_Ureal;
5013 Lor := No_Ureal;
5014 Hir := No_Ureal;
5016 -- For temporary constants internally generated to remove side effects
5017 -- we must use the corresponding expression to determine the range of
5018 -- the expression. But note that the expander can also generate
5019 -- constants in other cases, including deferred constants.
5021 if Is_Entity_Name (N)
5022 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
5023 and then Ekind (Entity (N)) = E_Constant
5024 and then Is_Internal_Name (Chars (Entity (N)))
5025 then
5026 if Present (Expression (Parent (Entity (N)))) then
5027 Determine_Range_R
5028 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
5030 elsif Present (Full_View (Entity (N))) then
5031 Determine_Range_R
5032 (Expression (Parent (Full_View (Entity (N)))),
5033 OK, Lo, Hi, Assume_Valid);
5035 else
5036 OK := False;
5037 end if;
5039 return;
5040 end if;
5042 -- If type is not defined, we can't determine its range
5044 if No (Typ)
5046 -- We don't deal with anything except IEEE floating-point types
5048 or else not Is_Floating_Point_Type (Typ)
5049 or else Float_Rep (Typ) /= IEEE_Binary
5051 -- Ignore type for which an error has been posted, since range in
5052 -- this case may well be a bogosity deriving from the error. Also
5053 -- ignore if error posted on the reference node.
5055 or else Error_Posted (N) or else Error_Posted (Typ)
5056 then
5057 OK := False;
5058 return;
5059 end if;
5061 -- For all other cases, we can determine the range
5063 OK := True;
5065 -- If value is compile time known, then the possible range is the one
5066 -- value that we know this expression definitely has.
5068 if Compile_Time_Known_Value (N) then
5069 Lo := Expr_Value_R (N);
5070 Hi := Lo;
5071 return;
5072 end if;
5074 -- Return if already in the cache
5076 Cindex := Cache_Index (N mod Cache_Size);
5078 if Determine_Range_Cache_N (Cindex) = N
5079 and then
5080 Determine_Range_Cache_V (Cindex) = Assume_Valid
5081 then
5082 Lo := Determine_Range_Cache_Lo_R (Cindex);
5083 Hi := Determine_Range_Cache_Hi_R (Cindex);
5084 return;
5085 end if;
5087 -- Otherwise, start by finding the bounds of the type of the expression,
5088 -- the value cannot be outside this range (if it is, then we have an
5089 -- overflow situation, which is a separate check, we are talking here
5090 -- only about the expression value).
5092 -- First a check, never try to find the bounds of a generic type, since
5093 -- these bounds are always junk values, and it is only valid to look at
5094 -- the bounds in an instance.
5096 if Is_Generic_Type (Typ) then
5097 OK := False;
5098 return;
5099 end if;
5101 -- First step, change to use base type unless we know the value is valid
5103 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
5104 or else Assume_No_Invalid_Values
5105 or else Assume_Valid
5106 then
5107 null;
5108 else
5109 Typ := Underlying_Type (Base_Type (Typ));
5110 end if;
5112 -- Retrieve the base type. Handle the case where the base type is a
5113 -- private type.
5115 Btyp := Base_Type (Typ);
5117 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
5118 Btyp := Full_View (Btyp);
5119 end if;
5121 -- We use the actual bound unless it is dynamic, in which case use the
5122 -- corresponding base type bound if possible. If we can't get a bound
5123 -- then we figure we can't determine the range (a peculiar case, that
5124 -- perhaps cannot happen, but there is no point in bombing in this
5125 -- optimization circuit).
5127 -- First the low bound
5129 Bound := Type_Low_Bound (Typ);
5131 if Compile_Time_Known_Value (Bound) then
5132 Lo := Expr_Value_R (Bound);
5134 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
5135 Lo := Expr_Value_R (Type_Low_Bound (Btyp));
5137 else
5138 OK := False;
5139 return;
5140 end if;
5142 -- Now the high bound
5144 Bound := Type_High_Bound (Typ);
5146 -- We need the high bound of the base type later on, and this should
5147 -- always be compile time known. Again, it is not clear that this
5148 -- can ever be false, but no point in bombing.
5150 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
5151 Hbound := Expr_Value_R (Type_High_Bound (Btyp));
5152 Hi := Hbound;
5154 else
5155 OK := False;
5156 return;
5157 end if;
5159 -- If we have a static subtype, then that may have a tighter bound so
5160 -- use the upper bound of the subtype instead in this case.
5162 if Compile_Time_Known_Value (Bound) then
5163 Hi := Expr_Value_R (Bound);
5164 end if;
5166 -- We may be able to refine this value in certain situations. If any
5167 -- refinement is possible, then Lor and Hir are set to possibly tighter
5168 -- bounds, and OK1 is set to True.
5170 case Nkind (N) is
5172 -- For unary plus, result is limited by range of operand
5174 when N_Op_Plus =>
5175 Determine_Range_R
5176 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
5178 -- For unary minus, determine range of operand, and negate it
5180 when N_Op_Minus =>
5181 Determine_Range_R
5182 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5184 if OK1 then
5185 Lor := -Hi_Right;
5186 Hir := -Lo_Right;
5187 end if;
5189 -- For binary addition, get range of each operand and do the
5190 -- addition to get the result range.
5192 when N_Op_Add =>
5193 if OK_Operands then
5194 Lor := Round_Machine (Lo_Left + Lo_Right);
5195 Hir := Round_Machine (Hi_Left + Hi_Right);
5196 end if;
5198 -- For binary subtraction, get range of each operand and do the worst
5199 -- case subtraction to get the result range.
5201 when N_Op_Subtract =>
5202 if OK_Operands then
5203 Lor := Round_Machine (Lo_Left - Hi_Right);
5204 Hir := Round_Machine (Hi_Left - Lo_Right);
5205 end if;
5207 -- For multiplication, get range of each operand and do the
5208 -- four multiplications to get the result range.
5210 when N_Op_Multiply =>
5211 if OK_Operands then
5212 declare
5213 M1 : constant Ureal := Round_Machine (Lo_Left * Lo_Right);
5214 M2 : constant Ureal := Round_Machine (Lo_Left * Hi_Right);
5215 M3 : constant Ureal := Round_Machine (Hi_Left * Lo_Right);
5216 M4 : constant Ureal := Round_Machine (Hi_Left * Hi_Right);
5218 begin
5219 Lor := UR_Min (UR_Min (M1, M2), UR_Min (M3, M4));
5220 Hir := UR_Max (UR_Max (M1, M2), UR_Max (M3, M4));
5221 end;
5222 end if;
5224 -- For division, consider separately the cases where the right
5225 -- operand is positive or negative. Otherwise, the right operand
5226 -- can be arbitrarily close to zero, so the result is likely to
5227 -- be unbounded in one direction, do not attempt to compute it.
5229 when N_Op_Divide =>
5230 if OK_Operands then
5232 -- Right operand is positive
5234 if Lo_Right > Ureal_0 then
5236 -- If the low bound of the left operand is negative, obtain
5237 -- the overall low bound by dividing it by the smallest
5238 -- value of the right operand, and otherwise by the largest
5239 -- value of the right operand.
5241 if Lo_Left < Ureal_0 then
5242 Lor := Round_Machine (Lo_Left / Lo_Right);
5243 else
5244 Lor := Round_Machine (Lo_Left / Hi_Right);
5245 end if;
5247 -- If the high bound of the left operand is negative, obtain
5248 -- the overall high bound by dividing it by the largest
5249 -- value of the right operand, and otherwise by the
5250 -- smallest value of the right operand.
5252 if Hi_Left < Ureal_0 then
5253 Hir := Round_Machine (Hi_Left / Hi_Right);
5254 else
5255 Hir := Round_Machine (Hi_Left / Lo_Right);
5256 end if;
5258 -- Right operand is negative
5260 elsif Hi_Right < Ureal_0 then
5262 -- If the low bound of the left operand is negative, obtain
5263 -- the overall low bound by dividing it by the largest
5264 -- value of the right operand, and otherwise by the smallest
5265 -- value of the right operand.
5267 if Lo_Left < Ureal_0 then
5268 Lor := Round_Machine (Lo_Left / Hi_Right);
5269 else
5270 Lor := Round_Machine (Lo_Left / Lo_Right);
5271 end if;
5273 -- If the high bound of the left operand is negative, obtain
5274 -- the overall high bound by dividing it by the smallest
5275 -- value of the right operand, and otherwise by the
5276 -- largest value of the right operand.
5278 if Hi_Left < Ureal_0 then
5279 Hir := Round_Machine (Hi_Left / Lo_Right);
5280 else
5281 Hir := Round_Machine (Hi_Left / Hi_Right);
5282 end if;
5284 else
5285 OK1 := False;
5286 end if;
5287 end if;
5289 when N_Type_Conversion =>
5291 -- For type conversion from one floating-point type to another, we
5292 -- can refine the range using the converted value.
5294 if Is_Floating_Point_Type (Etype (Expression (N))) then
5295 Determine_Range_R (Expression (N), OK1, Lor, Hir, Assume_Valid);
5297 -- When converting an integer to a floating-point type, determine
5298 -- the range in integer first, and then convert the bounds.
5300 elsif Is_Discrete_Type (Etype (Expression (N))) then
5301 declare
5302 Hir_Int : Uint;
5303 Lor_Int : Uint;
5305 begin
5306 Determine_Range
5307 (Expression (N), OK1, Lor_Int, Hir_Int, Assume_Valid);
5309 if OK1 then
5310 Lor := Round_Machine (UR_From_Uint (Lor_Int));
5311 Hir := Round_Machine (UR_From_Uint (Hir_Int));
5312 end if;
5313 end;
5315 else
5316 OK1 := False;
5317 end if;
5319 -- Nothing special to do for all other expression kinds
5321 when others =>
5322 OK1 := False;
5323 Lor := No_Ureal;
5324 Hir := No_Ureal;
5325 end case;
5327 -- At this stage, if OK1 is true, then we know that the actual result of
5328 -- the computed expression is in the range Lor .. Hir. We can use this
5329 -- to restrict the possible range of results.
5331 if OK1 then
5333 -- If the refined value of the low bound is greater than the type
5334 -- low bound, then reset it to the more restrictive value.
5336 if Lor > Lo then
5337 Lo := Lor;
5338 end if;
5340 -- Similarly, if the refined value of the high bound is less than the
5341 -- value so far, then reset it to the more restrictive value.
5343 if Hir < Hi then
5344 Hi := Hir;
5345 end if;
5346 end if;
5348 -- Set cache entry for future call and we are all done
5350 Determine_Range_Cache_N (Cindex) := N;
5351 Determine_Range_Cache_V (Cindex) := Assume_Valid;
5352 Determine_Range_Cache_Lo_R (Cindex) := Lo;
5353 Determine_Range_Cache_Hi_R (Cindex) := Hi;
5354 return;
5356 -- If any exception occurs, it means that we have some bug in the compiler,
5357 -- possibly triggered by a previous error, or by some unforeseen peculiar
5358 -- occurrence. However, this is only an optimization attempt, so there is
5359 -- really no point in crashing the compiler. Instead we just decide, too
5360 -- bad, we can't figure out a range in this case after all.
5362 exception
5363 when others =>
5365 -- Debug flag K disables this behavior (useful for debugging)
5367 if Debug_Flag_K then
5368 raise;
5369 else
5370 OK := False;
5371 Lo := No_Ureal;
5372 Hi := No_Ureal;
5373 return;
5374 end if;
5375 end Determine_Range_R;
5377 ------------------------------------
5378 -- Discriminant_Checks_Suppressed --
5379 ------------------------------------
5381 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
5382 begin
5383 if Present (E) then
5384 if Is_Unchecked_Union (E) then
5385 return True;
5386 elsif Checks_May_Be_Suppressed (E) then
5387 return Is_Check_Suppressed (E, Discriminant_Check);
5388 end if;
5389 end if;
5391 return Scope_Suppress.Suppress (Discriminant_Check);
5392 end Discriminant_Checks_Suppressed;
5394 --------------------------------
5395 -- Division_Checks_Suppressed --
5396 --------------------------------
5398 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
5399 begin
5400 if Present (E) and then Checks_May_Be_Suppressed (E) then
5401 return Is_Check_Suppressed (E, Division_Check);
5402 else
5403 return Scope_Suppress.Suppress (Division_Check);
5404 end if;
5405 end Division_Checks_Suppressed;
5407 --------------------------------------
5408 -- Duplicated_Tag_Checks_Suppressed --
5409 --------------------------------------
5411 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
5412 begin
5413 if Present (E) and then Checks_May_Be_Suppressed (E) then
5414 return Is_Check_Suppressed (E, Duplicated_Tag_Check);
5415 else
5416 return Scope_Suppress.Suppress (Duplicated_Tag_Check);
5417 end if;
5418 end Duplicated_Tag_Checks_Suppressed;
5420 -----------------------------------
5421 -- Elaboration_Checks_Suppressed --
5422 -----------------------------------
5424 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
5425 begin
5426 -- The complication in this routine is that if we are in the dynamic
5427 -- model of elaboration, we also check All_Checks, since All_Checks
5428 -- does not set Elaboration_Check explicitly.
5430 if Present (E) then
5431 if Kill_Elaboration_Checks (E) then
5432 return True;
5434 elsif Checks_May_Be_Suppressed (E) then
5435 if Is_Check_Suppressed (E, Elaboration_Check) then
5436 return True;
5438 elsif Dynamic_Elaboration_Checks then
5439 return Is_Check_Suppressed (E, All_Checks);
5441 else
5442 return False;
5443 end if;
5444 end if;
5445 end if;
5447 if Scope_Suppress.Suppress (Elaboration_Check) then
5448 return True;
5450 elsif Dynamic_Elaboration_Checks then
5451 return Scope_Suppress.Suppress (All_Checks);
5453 else
5454 return False;
5455 end if;
5456 end Elaboration_Checks_Suppressed;
5458 ---------------------------
5459 -- Enable_Overflow_Check --
5460 ---------------------------
5462 procedure Enable_Overflow_Check (N : Node_Id) is
5463 Typ : constant Entity_Id := Base_Type (Etype (N));
5464 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
5465 Chk : Nat;
5466 OK : Boolean;
5467 Ent : Entity_Id;
5468 Ofs : Uint;
5469 Lo : Uint;
5470 Hi : Uint;
5472 Do_Ovflow_Check : Boolean;
5474 begin
5475 if Debug_Flag_CC then
5476 w ("Enable_Overflow_Check for node ", Int (N));
5477 Write_Str (" Source location = ");
5478 wl (Sloc (N));
5479 pg (Union_Id (N));
5480 end if;
5482 -- No check if overflow checks suppressed for type of node
5484 if Overflow_Checks_Suppressed (Etype (N)) then
5485 return;
5487 -- Nothing to do for unsigned integer types, which do not overflow
5489 elsif Is_Modular_Integer_Type (Typ) then
5490 return;
5491 end if;
5493 -- This is the point at which processing for STRICT mode diverges
5494 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
5495 -- probably more extreme that it needs to be, but what is going on here
5496 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
5497 -- to leave the processing for STRICT mode untouched. There were
5498 -- two reasons for this. First it avoided any incompatible change of
5499 -- behavior. Second, it guaranteed that STRICT mode continued to be
5500 -- legacy reliable.
5502 -- The big difference is that in STRICT mode there is a fair amount of
5503 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
5504 -- know that no check is needed. We skip all that in the two new modes,
5505 -- since really overflow checking happens over a whole subtree, and we
5506 -- do the corresponding optimizations later on when applying the checks.
5508 if Mode in Minimized_Or_Eliminated then
5509 if not (Overflow_Checks_Suppressed (Etype (N)))
5510 and then not (Is_Entity_Name (N)
5511 and then Overflow_Checks_Suppressed (Entity (N)))
5512 then
5513 Activate_Overflow_Check (N);
5514 end if;
5516 if Debug_Flag_CC then
5517 w ("Minimized/Eliminated mode");
5518 end if;
5520 return;
5521 end if;
5523 -- Remainder of processing is for STRICT case, and is unchanged from
5524 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
5526 -- Nothing to do if the range of the result is known OK. We skip this
5527 -- for conversions, since the caller already did the check, and in any
5528 -- case the condition for deleting the check for a type conversion is
5529 -- different.
5531 if Nkind (N) /= N_Type_Conversion then
5532 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
5534 -- Note in the test below that we assume that the range is not OK
5535 -- if a bound of the range is equal to that of the type. That's not
5536 -- quite accurate but we do this for the following reasons:
5538 -- a) The way that Determine_Range works, it will typically report
5539 -- the bounds of the value as being equal to the bounds of the
5540 -- type, because it either can't tell anything more precise, or
5541 -- does not think it is worth the effort to be more precise.
5543 -- b) It is very unusual to have a situation in which this would
5544 -- generate an unnecessary overflow check (an example would be
5545 -- a subtype with a range 0 .. Integer'Last - 1 to which the
5546 -- literal value one is added).
5548 -- c) The alternative is a lot of special casing in this routine
5549 -- which would partially duplicate Determine_Range processing.
5551 if OK then
5552 Do_Ovflow_Check := True;
5554 -- Note that the following checks are quite deliberately > and <
5555 -- rather than >= and <= as explained above.
5557 if Lo > Expr_Value (Type_Low_Bound (Typ))
5558 and then
5559 Hi < Expr_Value (Type_High_Bound (Typ))
5560 then
5561 Do_Ovflow_Check := False;
5563 -- Despite the comments above, it is worth dealing specially with
5564 -- division specially. The only case where integer division can
5565 -- overflow is (largest negative number) / (-1). So we will do
5566 -- an extra range analysis to see if this is possible.
5568 elsif Nkind (N) = N_Op_Divide then
5569 Determine_Range
5570 (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5572 if OK and then Lo > Expr_Value (Type_Low_Bound (Typ)) then
5573 Do_Ovflow_Check := False;
5575 else
5576 Determine_Range
5577 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5579 if OK and then (Lo > Uint_Minus_1
5580 or else
5581 Hi < Uint_Minus_1)
5582 then
5583 Do_Ovflow_Check := False;
5584 end if;
5585 end if;
5586 end if;
5588 -- If no overflow check required, we are done
5590 if not Do_Ovflow_Check then
5591 if Debug_Flag_CC then
5592 w ("No overflow check required");
5593 end if;
5595 return;
5596 end if;
5597 end if;
5598 end if;
5600 -- If not in optimizing mode, set flag and we are done. We are also done
5601 -- (and just set the flag) if the type is not a discrete type, since it
5602 -- is not worth the effort to eliminate checks for other than discrete
5603 -- types. In addition, we take this same path if we have stored the
5604 -- maximum number of checks possible already (a very unlikely situation,
5605 -- but we do not want to blow up).
5607 if Optimization_Level = 0
5608 or else not Is_Discrete_Type (Etype (N))
5609 or else Num_Saved_Checks = Saved_Checks'Last
5610 then
5611 Activate_Overflow_Check (N);
5613 if Debug_Flag_CC then
5614 w ("Optimization off");
5615 end if;
5617 return;
5618 end if;
5620 -- Otherwise evaluate and check the expression
5622 Find_Check
5623 (Expr => N,
5624 Check_Type => 'O',
5625 Target_Type => Empty,
5626 Entry_OK => OK,
5627 Check_Num => Chk,
5628 Ent => Ent,
5629 Ofs => Ofs);
5631 if Debug_Flag_CC then
5632 w ("Called Find_Check");
5633 w (" OK = ", OK);
5635 if OK then
5636 w (" Check_Num = ", Chk);
5637 w (" Ent = ", Int (Ent));
5638 Write_Str (" Ofs = ");
5639 pid (Ofs);
5640 end if;
5641 end if;
5643 -- If check is not of form to optimize, then set flag and we are done
5645 if not OK then
5646 Activate_Overflow_Check (N);
5647 return;
5648 end if;
5650 -- If check is already performed, then return without setting flag
5652 if Chk /= 0 then
5653 if Debug_Flag_CC then
5654 w ("Check suppressed!");
5655 end if;
5657 return;
5658 end if;
5660 -- Here we will make a new entry for the new check
5662 Activate_Overflow_Check (N);
5663 Num_Saved_Checks := Num_Saved_Checks + 1;
5664 Saved_Checks (Num_Saved_Checks) :=
5665 (Killed => False,
5666 Entity => Ent,
5667 Offset => Ofs,
5668 Check_Type => 'O',
5669 Target_Type => Empty);
5671 if Debug_Flag_CC then
5672 w ("Make new entry, check number = ", Num_Saved_Checks);
5673 w (" Entity = ", Int (Ent));
5674 Write_Str (" Offset = ");
5675 pid (Ofs);
5676 w (" Check_Type = O");
5677 w (" Target_Type = Empty");
5678 end if;
5680 -- If we get an exception, then something went wrong, probably because of
5681 -- an error in the structure of the tree due to an incorrect program. Or
5682 -- it may be a bug in the optimization circuit. In either case the safest
5683 -- thing is simply to set the check flag unconditionally.
5685 exception
5686 when others =>
5687 Activate_Overflow_Check (N);
5689 if Debug_Flag_CC then
5690 w (" exception occurred, overflow flag set");
5691 end if;
5693 return;
5694 end Enable_Overflow_Check;
5696 ------------------------
5697 -- Enable_Range_Check --
5698 ------------------------
5700 procedure Enable_Range_Check (N : Node_Id) is
5701 Chk : Nat;
5702 OK : Boolean;
5703 Ent : Entity_Id;
5704 Ofs : Uint;
5705 Ttyp : Entity_Id;
5706 P : Node_Id;
5708 begin
5709 -- Return if unchecked type conversion with range check killed. In this
5710 -- case we never set the flag (that's what Kill_Range_Check is about).
5712 if Nkind (N) = N_Unchecked_Type_Conversion
5713 and then Kill_Range_Check (N)
5714 then
5715 return;
5716 end if;
5718 -- Do not set range check flag if parent is assignment statement or
5719 -- object declaration with Suppress_Assignment_Checks flag set
5721 if Nkind_In (Parent (N), N_Assignment_Statement, N_Object_Declaration)
5722 and then Suppress_Assignment_Checks (Parent (N))
5723 then
5724 return;
5725 end if;
5727 -- Check for various cases where we should suppress the range check
5729 -- No check if range checks suppressed for type of node
5731 if Present (Etype (N)) and then Range_Checks_Suppressed (Etype (N)) then
5732 return;
5734 -- No check if node is an entity name, and range checks are suppressed
5735 -- for this entity, or for the type of this entity.
5737 elsif Is_Entity_Name (N)
5738 and then (Range_Checks_Suppressed (Entity (N))
5739 or else Range_Checks_Suppressed (Etype (Entity (N))))
5740 then
5741 return;
5743 -- No checks if index of array, and index checks are suppressed for
5744 -- the array object or the type of the array.
5746 elsif Nkind (Parent (N)) = N_Indexed_Component then
5747 declare
5748 Pref : constant Node_Id := Prefix (Parent (N));
5749 begin
5750 if Is_Entity_Name (Pref)
5751 and then Index_Checks_Suppressed (Entity (Pref))
5752 then
5753 return;
5754 elsif Index_Checks_Suppressed (Etype (Pref)) then
5755 return;
5756 end if;
5757 end;
5758 end if;
5760 -- Debug trace output
5762 if Debug_Flag_CC then
5763 w ("Enable_Range_Check for node ", Int (N));
5764 Write_Str (" Source location = ");
5765 wl (Sloc (N));
5766 pg (Union_Id (N));
5767 end if;
5769 -- If not in optimizing mode, set flag and we are done. We are also done
5770 -- (and just set the flag) if the type is not a discrete type, since it
5771 -- is not worth the effort to eliminate checks for other than discrete
5772 -- types. In addition, we take this same path if we have stored the
5773 -- maximum number of checks possible already (a very unlikely situation,
5774 -- but we do not want to blow up).
5776 if Optimization_Level = 0
5777 or else No (Etype (N))
5778 or else not Is_Discrete_Type (Etype (N))
5779 or else Num_Saved_Checks = Saved_Checks'Last
5780 then
5781 Activate_Range_Check (N);
5783 if Debug_Flag_CC then
5784 w ("Optimization off");
5785 end if;
5787 return;
5788 end if;
5790 -- Otherwise find out the target type
5792 P := Parent (N);
5794 -- For assignment, use left side subtype
5796 if Nkind (P) = N_Assignment_Statement
5797 and then Expression (P) = N
5798 then
5799 Ttyp := Etype (Name (P));
5801 -- For indexed component, use subscript subtype
5803 elsif Nkind (P) = N_Indexed_Component then
5804 declare
5805 Atyp : Entity_Id;
5806 Indx : Node_Id;
5807 Subs : Node_Id;
5809 begin
5810 Atyp := Etype (Prefix (P));
5812 if Is_Access_Type (Atyp) then
5813 Atyp := Designated_Type (Atyp);
5815 -- If the prefix is an access to an unconstrained array,
5816 -- perform check unconditionally: it depends on the bounds of
5817 -- an object and we cannot currently recognize whether the test
5818 -- may be redundant.
5820 if not Is_Constrained (Atyp) then
5821 Activate_Range_Check (N);
5822 return;
5823 end if;
5825 -- Ditto if prefix is simply an unconstrained array. We used
5826 -- to think this case was OK, if the prefix was not an explicit
5827 -- dereference, but we have now seen a case where this is not
5828 -- true, so it is safer to just suppress the optimization in this
5829 -- case. The back end is getting better at eliminating redundant
5830 -- checks in any case, so the loss won't be important.
5832 elsif Is_Array_Type (Atyp)
5833 and then not Is_Constrained (Atyp)
5834 then
5835 Activate_Range_Check (N);
5836 return;
5837 end if;
5839 Indx := First_Index (Atyp);
5840 Subs := First (Expressions (P));
5841 loop
5842 if Subs = N then
5843 Ttyp := Etype (Indx);
5844 exit;
5845 end if;
5847 Next_Index (Indx);
5848 Next (Subs);
5849 end loop;
5850 end;
5852 -- For now, ignore all other cases, they are not so interesting
5854 else
5855 if Debug_Flag_CC then
5856 w (" target type not found, flag set");
5857 end if;
5859 Activate_Range_Check (N);
5860 return;
5861 end if;
5863 -- Evaluate and check the expression
5865 Find_Check
5866 (Expr => N,
5867 Check_Type => 'R',
5868 Target_Type => Ttyp,
5869 Entry_OK => OK,
5870 Check_Num => Chk,
5871 Ent => Ent,
5872 Ofs => Ofs);
5874 if Debug_Flag_CC then
5875 w ("Called Find_Check");
5876 w ("Target_Typ = ", Int (Ttyp));
5877 w (" OK = ", OK);
5879 if OK then
5880 w (" Check_Num = ", Chk);
5881 w (" Ent = ", Int (Ent));
5882 Write_Str (" Ofs = ");
5883 pid (Ofs);
5884 end if;
5885 end if;
5887 -- If check is not of form to optimize, then set flag and we are done
5889 if not OK then
5890 if Debug_Flag_CC then
5891 w (" expression not of optimizable type, flag set");
5892 end if;
5894 Activate_Range_Check (N);
5895 return;
5896 end if;
5898 -- If check is already performed, then return without setting flag
5900 if Chk /= 0 then
5901 if Debug_Flag_CC then
5902 w ("Check suppressed!");
5903 end if;
5905 return;
5906 end if;
5908 -- Here we will make a new entry for the new check
5910 Activate_Range_Check (N);
5911 Num_Saved_Checks := Num_Saved_Checks + 1;
5912 Saved_Checks (Num_Saved_Checks) :=
5913 (Killed => False,
5914 Entity => Ent,
5915 Offset => Ofs,
5916 Check_Type => 'R',
5917 Target_Type => Ttyp);
5919 if Debug_Flag_CC then
5920 w ("Make new entry, check number = ", Num_Saved_Checks);
5921 w (" Entity = ", Int (Ent));
5922 Write_Str (" Offset = ");
5923 pid (Ofs);
5924 w (" Check_Type = R");
5925 w (" Target_Type = ", Int (Ttyp));
5926 pg (Union_Id (Ttyp));
5927 end if;
5929 -- If we get an exception, then something went wrong, probably because of
5930 -- an error in the structure of the tree due to an incorrect program. Or
5931 -- it may be a bug in the optimization circuit. In either case the safest
5932 -- thing is simply to set the check flag unconditionally.
5934 exception
5935 when others =>
5936 Activate_Range_Check (N);
5938 if Debug_Flag_CC then
5939 w (" exception occurred, range flag set");
5940 end if;
5942 return;
5943 end Enable_Range_Check;
5945 ------------------
5946 -- Ensure_Valid --
5947 ------------------
5949 procedure Ensure_Valid
5950 (Expr : Node_Id;
5951 Holes_OK : Boolean := False;
5952 Related_Id : Entity_Id := Empty;
5953 Is_Low_Bound : Boolean := False;
5954 Is_High_Bound : Boolean := False)
5956 Typ : constant Entity_Id := Etype (Expr);
5958 begin
5959 -- Ignore call if we are not doing any validity checking
5961 if not Validity_Checks_On then
5962 return;
5964 -- Ignore call if range or validity checks suppressed on entity or type
5966 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
5967 return;
5969 -- No check required if expression is from the expander, we assume the
5970 -- expander will generate whatever checks are needed. Note that this is
5971 -- not just an optimization, it avoids infinite recursions.
5973 -- Unchecked conversions must be checked, unless they are initialized
5974 -- scalar values, as in a component assignment in an init proc.
5976 -- In addition, we force a check if Force_Validity_Checks is set
5978 elsif not Comes_From_Source (Expr)
5979 and then not
5980 (Nkind (Expr) = N_Identifier
5981 and then Present (Renamed_Object (Entity (Expr)))
5982 and then Comes_From_Source (Renamed_Object (Entity (Expr))))
5983 and then not Force_Validity_Checks
5984 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
5985 or else Kill_Range_Check (Expr))
5986 then
5987 return;
5989 -- No check required if expression is known to have valid value
5991 elsif Expr_Known_Valid (Expr) then
5992 return;
5994 -- No check needed within a generated predicate function. Validity
5995 -- of input value will have been checked earlier.
5997 elsif Ekind (Current_Scope) = E_Function
5998 and then Is_Predicate_Function (Current_Scope)
5999 then
6000 return;
6002 -- Ignore case of enumeration with holes where the flag is set not to
6003 -- worry about holes, since no special validity check is needed
6005 elsif Is_Enumeration_Type (Typ)
6006 and then Has_Non_Standard_Rep (Typ)
6007 and then Holes_OK
6008 then
6009 return;
6011 -- No check required on the left-hand side of an assignment
6013 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
6014 and then Expr = Name (Parent (Expr))
6015 then
6016 return;
6018 -- No check on a universal real constant. The context will eventually
6019 -- convert it to a machine number for some target type, or report an
6020 -- illegality.
6022 elsif Nkind (Expr) = N_Real_Literal
6023 and then Etype (Expr) = Universal_Real
6024 then
6025 return;
6027 -- If the expression denotes a component of a packed boolean array,
6028 -- no possible check applies. We ignore the old ACATS chestnuts that
6029 -- involve Boolean range True..True.
6031 -- Note: validity checks are generated for expressions that yield a
6032 -- scalar type, when it is possible to create a value that is outside of
6033 -- the type. If this is a one-bit boolean no such value exists. This is
6034 -- an optimization, and it also prevents compiler blowing up during the
6035 -- elaboration of improperly expanded packed array references.
6037 elsif Nkind (Expr) = N_Indexed_Component
6038 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
6039 and then Root_Type (Etype (Expr)) = Standard_Boolean
6040 then
6041 return;
6043 -- For an expression with actions, we want to insert the validity check
6044 -- on the final Expression.
6046 elsif Nkind (Expr) = N_Expression_With_Actions then
6047 Ensure_Valid (Expression (Expr));
6048 return;
6050 -- An annoying special case. If this is an out parameter of a scalar
6051 -- type, then the value is not going to be accessed, therefore it is
6052 -- inappropriate to do any validity check at the call site.
6054 else
6055 -- Only need to worry about scalar types
6057 if Is_Scalar_Type (Typ) then
6058 declare
6059 P : Node_Id;
6060 N : Node_Id;
6061 E : Entity_Id;
6062 F : Entity_Id;
6063 A : Node_Id;
6064 L : List_Id;
6066 begin
6067 -- Find actual argument (which may be a parameter association)
6068 -- and the parent of the actual argument (the call statement)
6070 N := Expr;
6071 P := Parent (Expr);
6073 if Nkind (P) = N_Parameter_Association then
6074 N := P;
6075 P := Parent (N);
6076 end if;
6078 -- Only need to worry if we are argument of a procedure call
6079 -- since functions don't have out parameters. If this is an
6080 -- indirect or dispatching call, get signature from the
6081 -- subprogram type.
6083 if Nkind (P) = N_Procedure_Call_Statement then
6084 L := Parameter_Associations (P);
6086 if Is_Entity_Name (Name (P)) then
6087 E := Entity (Name (P));
6088 else
6089 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
6090 E := Etype (Name (P));
6091 end if;
6093 -- Only need to worry if there are indeed actuals, and if
6094 -- this could be a procedure call, otherwise we cannot get a
6095 -- match (either we are not an argument, or the mode of the
6096 -- formal is not OUT). This test also filters out the
6097 -- generic case.
6099 if Is_Non_Empty_List (L) and then Is_Subprogram (E) then
6101 -- This is the loop through parameters, looking for an
6102 -- OUT parameter for which we are the argument.
6104 F := First_Formal (E);
6105 A := First (L);
6106 while Present (F) loop
6107 if Ekind (F) = E_Out_Parameter and then A = N then
6108 return;
6109 end if;
6111 Next_Formal (F);
6112 Next (A);
6113 end loop;
6114 end if;
6115 end if;
6116 end;
6117 end if;
6118 end if;
6120 -- If this is a boolean expression, only its elementary operands need
6121 -- checking: if they are valid, a boolean or short-circuit operation
6122 -- with them will be valid as well.
6124 if Base_Type (Typ) = Standard_Boolean
6125 and then
6126 (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
6127 then
6128 return;
6129 end if;
6131 -- If we fall through, a validity check is required
6133 Insert_Valid_Check (Expr, Related_Id, Is_Low_Bound, Is_High_Bound);
6135 if Is_Entity_Name (Expr)
6136 and then Safe_To_Capture_Value (Expr, Entity (Expr))
6137 then
6138 Set_Is_Known_Valid (Entity (Expr));
6139 end if;
6140 end Ensure_Valid;
6142 ----------------------
6143 -- Expr_Known_Valid --
6144 ----------------------
6146 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
6147 Typ : constant Entity_Id := Etype (Expr);
6149 begin
6150 -- Non-scalar types are always considered valid, since they never give
6151 -- rise to the issues of erroneous or bounded error behavior that are
6152 -- the concern. In formal reference manual terms the notion of validity
6153 -- only applies to scalar types. Note that even when packed arrays are
6154 -- represented using modular types, they are still arrays semantically,
6155 -- so they are also always valid (in particular, the unused bits can be
6156 -- random rubbish without affecting the validity of the array value).
6158 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Impl_Type (Typ) then
6159 return True;
6161 -- If no validity checking, then everything is considered valid
6163 elsif not Validity_Checks_On then
6164 return True;
6166 -- Floating-point types are considered valid unless floating-point
6167 -- validity checks have been specifically turned on.
6169 elsif Is_Floating_Point_Type (Typ)
6170 and then not Validity_Check_Floating_Point
6171 then
6172 return True;
6174 -- If the expression is the value of an object that is known to be
6175 -- valid, then clearly the expression value itself is valid.
6177 elsif Is_Entity_Name (Expr)
6178 and then Is_Known_Valid (Entity (Expr))
6180 -- Exclude volatile variables
6182 and then not Treat_As_Volatile (Entity (Expr))
6183 then
6184 return True;
6186 -- References to discriminants are always considered valid. The value
6187 -- of a discriminant gets checked when the object is built. Within the
6188 -- record, we consider it valid, and it is important to do so, since
6189 -- otherwise we can try to generate bogus validity checks which
6190 -- reference discriminants out of scope. Discriminants of concurrent
6191 -- types are excluded for the same reason.
6193 elsif Is_Entity_Name (Expr)
6194 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
6195 then
6196 return True;
6198 -- If the type is one for which all values are known valid, then we are
6199 -- sure that the value is valid except in the slightly odd case where
6200 -- the expression is a reference to a variable whose size has been
6201 -- explicitly set to a value greater than the object size.
6203 elsif Is_Known_Valid (Typ) then
6204 if Is_Entity_Name (Expr)
6205 and then Ekind (Entity (Expr)) = E_Variable
6206 and then Esize (Entity (Expr)) > Esize (Typ)
6207 then
6208 return False;
6209 else
6210 return True;
6211 end if;
6213 -- Integer and character literals always have valid values, where
6214 -- appropriate these will be range checked in any case.
6216 elsif Nkind_In (Expr, N_Integer_Literal, N_Character_Literal) then
6217 return True;
6219 -- If we have a type conversion or a qualification of a known valid
6220 -- value, then the result will always be valid.
6222 elsif Nkind_In (Expr, N_Type_Conversion, N_Qualified_Expression) then
6223 return Expr_Known_Valid (Expression (Expr));
6225 -- Case of expression is a non-floating-point operator. In this case we
6226 -- can assume the result is valid the generated code for the operator
6227 -- will include whatever checks are needed (e.g. range checks) to ensure
6228 -- validity. This assumption does not hold for the floating-point case,
6229 -- since floating-point operators can generate Infinite or NaN results
6230 -- which are considered invalid.
6232 -- Historical note: in older versions, the exemption of floating-point
6233 -- types from this assumption was done only in cases where the parent
6234 -- was an assignment, function call or parameter association. Presumably
6235 -- the idea was that in other contexts, the result would be checked
6236 -- elsewhere, but this list of cases was missing tests (at least the
6237 -- N_Object_Declaration case, as shown by a reported missing validity
6238 -- check), and it is not clear why function calls but not procedure
6239 -- calls were tested for. It really seems more accurate and much
6240 -- safer to recognize that expressions which are the result of a
6241 -- floating-point operator can never be assumed to be valid.
6243 elsif Nkind (Expr) in N_Op and then not Is_Floating_Point_Type (Typ) then
6244 return True;
6246 -- The result of a membership test is always valid, since it is true or
6247 -- false, there are no other possibilities.
6249 elsif Nkind (Expr) in N_Membership_Test then
6250 return True;
6252 -- For all other cases, we do not know the expression is valid
6254 else
6255 return False;
6256 end if;
6257 end Expr_Known_Valid;
6259 ----------------
6260 -- Find_Check --
6261 ----------------
6263 procedure Find_Check
6264 (Expr : Node_Id;
6265 Check_Type : Character;
6266 Target_Type : Entity_Id;
6267 Entry_OK : out Boolean;
6268 Check_Num : out Nat;
6269 Ent : out Entity_Id;
6270 Ofs : out Uint)
6272 function Within_Range_Of
6273 (Target_Type : Entity_Id;
6274 Check_Type : Entity_Id) return Boolean;
6275 -- Given a requirement for checking a range against Target_Type, and
6276 -- and a range Check_Type against which a check has already been made,
6277 -- determines if the check against check type is sufficient to ensure
6278 -- that no check against Target_Type is required.
6280 ---------------------
6281 -- Within_Range_Of --
6282 ---------------------
6284 function Within_Range_Of
6285 (Target_Type : Entity_Id;
6286 Check_Type : Entity_Id) return Boolean
6288 begin
6289 if Target_Type = Check_Type then
6290 return True;
6292 else
6293 declare
6294 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
6295 Thi : constant Node_Id := Type_High_Bound (Target_Type);
6296 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
6297 Chi : constant Node_Id := Type_High_Bound (Check_Type);
6299 begin
6300 if (Tlo = Clo
6301 or else (Compile_Time_Known_Value (Tlo)
6302 and then
6303 Compile_Time_Known_Value (Clo)
6304 and then
6305 Expr_Value (Clo) >= Expr_Value (Tlo)))
6306 and then
6307 (Thi = Chi
6308 or else (Compile_Time_Known_Value (Thi)
6309 and then
6310 Compile_Time_Known_Value (Chi)
6311 and then
6312 Expr_Value (Chi) <= Expr_Value (Clo)))
6313 then
6314 return True;
6315 else
6316 return False;
6317 end if;
6318 end;
6319 end if;
6320 end Within_Range_Of;
6322 -- Start of processing for Find_Check
6324 begin
6325 -- Establish default, in case no entry is found
6327 Check_Num := 0;
6329 -- Case of expression is simple entity reference
6331 if Is_Entity_Name (Expr) then
6332 Ent := Entity (Expr);
6333 Ofs := Uint_0;
6335 -- Case of expression is entity + known constant
6337 elsif Nkind (Expr) = N_Op_Add
6338 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6339 and then Is_Entity_Name (Left_Opnd (Expr))
6340 then
6341 Ent := Entity (Left_Opnd (Expr));
6342 Ofs := Expr_Value (Right_Opnd (Expr));
6344 -- Case of expression is entity - known constant
6346 elsif Nkind (Expr) = N_Op_Subtract
6347 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6348 and then Is_Entity_Name (Left_Opnd (Expr))
6349 then
6350 Ent := Entity (Left_Opnd (Expr));
6351 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
6353 -- Any other expression is not of the right form
6355 else
6356 Ent := Empty;
6357 Ofs := Uint_0;
6358 Entry_OK := False;
6359 return;
6360 end if;
6362 -- Come here with expression of appropriate form, check if entity is an
6363 -- appropriate one for our purposes.
6365 if (Ekind (Ent) = E_Variable
6366 or else Is_Constant_Object (Ent))
6367 and then not Is_Library_Level_Entity (Ent)
6368 then
6369 Entry_OK := True;
6370 else
6371 Entry_OK := False;
6372 return;
6373 end if;
6375 -- See if there is matching check already
6377 for J in reverse 1 .. Num_Saved_Checks loop
6378 declare
6379 SC : Saved_Check renames Saved_Checks (J);
6380 begin
6381 if SC.Killed = False
6382 and then SC.Entity = Ent
6383 and then SC.Offset = Ofs
6384 and then SC.Check_Type = Check_Type
6385 and then Within_Range_Of (Target_Type, SC.Target_Type)
6386 then
6387 Check_Num := J;
6388 return;
6389 end if;
6390 end;
6391 end loop;
6393 -- If we fall through entry was not found
6395 return;
6396 end Find_Check;
6398 ---------------------------------
6399 -- Generate_Discriminant_Check --
6400 ---------------------------------
6402 -- Note: the code for this procedure is derived from the
6403 -- Emit_Discriminant_Check Routine in trans.c.
6405 procedure Generate_Discriminant_Check (N : Node_Id) is
6406 Loc : constant Source_Ptr := Sloc (N);
6407 Pref : constant Node_Id := Prefix (N);
6408 Sel : constant Node_Id := Selector_Name (N);
6410 Orig_Comp : constant Entity_Id :=
6411 Original_Record_Component (Entity (Sel));
6412 -- The original component to be checked
6414 Discr_Fct : constant Entity_Id :=
6415 Discriminant_Checking_Func (Orig_Comp);
6416 -- The discriminant checking function
6418 Discr : Entity_Id;
6419 -- One discriminant to be checked in the type
6421 Real_Discr : Entity_Id;
6422 -- Actual discriminant in the call
6424 Pref_Type : Entity_Id;
6425 -- Type of relevant prefix (ignoring private/access stuff)
6427 Args : List_Id;
6428 -- List of arguments for function call
6430 Formal : Entity_Id;
6431 -- Keep track of the formal corresponding to the actual we build for
6432 -- each discriminant, in order to be able to perform the necessary type
6433 -- conversions.
6435 Scomp : Node_Id;
6436 -- Selected component reference for checking function argument
6438 begin
6439 Pref_Type := Etype (Pref);
6441 -- Force evaluation of the prefix, so that it does not get evaluated
6442 -- twice (once for the check, once for the actual reference). Such a
6443 -- double evaluation is always a potential source of inefficiency, and
6444 -- is functionally incorrect in the volatile case, or when the prefix
6445 -- may have side effects. A nonvolatile entity or a component of a
6446 -- nonvolatile entity requires no evaluation.
6448 if Is_Entity_Name (Pref) then
6449 if Treat_As_Volatile (Entity (Pref)) then
6450 Force_Evaluation (Pref, Name_Req => True);
6451 end if;
6453 elsif Treat_As_Volatile (Etype (Pref)) then
6454 Force_Evaluation (Pref, Name_Req => True);
6456 elsif Nkind (Pref) = N_Selected_Component
6457 and then Is_Entity_Name (Prefix (Pref))
6458 then
6459 null;
6461 else
6462 Force_Evaluation (Pref, Name_Req => True);
6463 end if;
6465 -- For a tagged type, use the scope of the original component to
6466 -- obtain the type, because ???
6468 if Is_Tagged_Type (Scope (Orig_Comp)) then
6469 Pref_Type := Scope (Orig_Comp);
6471 -- For an untagged derived type, use the discriminants of the parent
6472 -- which have been renamed in the derivation, possibly by a one-to-many
6473 -- discriminant constraint. For untagged type, initially get the Etype
6474 -- of the prefix
6476 else
6477 if Is_Derived_Type (Pref_Type)
6478 and then Number_Discriminants (Pref_Type) /=
6479 Number_Discriminants (Etype (Base_Type (Pref_Type)))
6480 then
6481 Pref_Type := Etype (Base_Type (Pref_Type));
6482 end if;
6483 end if;
6485 -- We definitely should have a checking function, This routine should
6486 -- not be called if no discriminant checking function is present.
6488 pragma Assert (Present (Discr_Fct));
6490 -- Create the list of the actual parameters for the call. This list
6491 -- is the list of the discriminant fields of the record expression to
6492 -- be discriminant checked.
6494 Args := New_List;
6495 Formal := First_Formal (Discr_Fct);
6496 Discr := First_Discriminant (Pref_Type);
6497 while Present (Discr) loop
6499 -- If we have a corresponding discriminant field, and a parent
6500 -- subtype is present, then we want to use the corresponding
6501 -- discriminant since this is the one with the useful value.
6503 if Present (Corresponding_Discriminant (Discr))
6504 and then Ekind (Pref_Type) = E_Record_Type
6505 and then Present (Parent_Subtype (Pref_Type))
6506 then
6507 Real_Discr := Corresponding_Discriminant (Discr);
6508 else
6509 Real_Discr := Discr;
6510 end if;
6512 -- Construct the reference to the discriminant
6514 Scomp :=
6515 Make_Selected_Component (Loc,
6516 Prefix =>
6517 Unchecked_Convert_To (Pref_Type,
6518 Duplicate_Subexpr (Pref)),
6519 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
6521 -- Manually analyze and resolve this selected component. We really
6522 -- want it just as it appears above, and do not want the expander
6523 -- playing discriminal games etc with this reference. Then we append
6524 -- the argument to the list we are gathering.
6526 Set_Etype (Scomp, Etype (Real_Discr));
6527 Set_Analyzed (Scomp, True);
6528 Append_To (Args, Convert_To (Etype (Formal), Scomp));
6530 Next_Formal_With_Extras (Formal);
6531 Next_Discriminant (Discr);
6532 end loop;
6534 -- Now build and insert the call
6536 Insert_Action (N,
6537 Make_Raise_Constraint_Error (Loc,
6538 Condition =>
6539 Make_Function_Call (Loc,
6540 Name => New_Occurrence_Of (Discr_Fct, Loc),
6541 Parameter_Associations => Args),
6542 Reason => CE_Discriminant_Check_Failed));
6543 end Generate_Discriminant_Check;
6545 ---------------------------
6546 -- Generate_Index_Checks --
6547 ---------------------------
6549 procedure Generate_Index_Checks (N : Node_Id) is
6551 function Entity_Of_Prefix return Entity_Id;
6552 -- Returns the entity of the prefix of N (or Empty if not found)
6554 ----------------------
6555 -- Entity_Of_Prefix --
6556 ----------------------
6558 function Entity_Of_Prefix return Entity_Id is
6559 P : Node_Id;
6561 begin
6562 P := Prefix (N);
6563 while not Is_Entity_Name (P) loop
6564 if not Nkind_In (P, N_Selected_Component,
6565 N_Indexed_Component)
6566 then
6567 return Empty;
6568 end if;
6570 P := Prefix (P);
6571 end loop;
6573 return Entity (P);
6574 end Entity_Of_Prefix;
6576 -- Local variables
6578 Loc : constant Source_Ptr := Sloc (N);
6579 A : constant Node_Id := Prefix (N);
6580 A_Ent : constant Entity_Id := Entity_Of_Prefix;
6581 Sub : Node_Id;
6583 -- Start of processing for Generate_Index_Checks
6585 begin
6586 -- Ignore call if the prefix is not an array since we have a serious
6587 -- error in the sources. Ignore it also if index checks are suppressed
6588 -- for array object or type.
6590 if not Is_Array_Type (Etype (A))
6591 or else (Present (A_Ent) and then Index_Checks_Suppressed (A_Ent))
6592 or else Index_Checks_Suppressed (Etype (A))
6593 then
6594 return;
6596 -- The indexed component we are dealing with contains 'Loop_Entry in its
6597 -- prefix. This case arises when analysis has determined that constructs
6598 -- such as
6600 -- Prefix'Loop_Entry (Expr)
6601 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
6603 -- require rewriting for error detection purposes. A side effect of this
6604 -- action is the generation of index checks that mention 'Loop_Entry.
6605 -- Delay the generation of the check until 'Loop_Entry has been properly
6606 -- expanded. This is done in Expand_Loop_Entry_Attributes.
6608 elsif Nkind (Prefix (N)) = N_Attribute_Reference
6609 and then Attribute_Name (Prefix (N)) = Name_Loop_Entry
6610 then
6611 return;
6612 end if;
6614 -- Generate a raise of constraint error with the appropriate reason and
6615 -- a condition of the form:
6617 -- Base_Type (Sub) not in Array'Range (Subscript)
6619 -- Note that the reason we generate the conversion to the base type here
6620 -- is that we definitely want the range check to take place, even if it
6621 -- looks like the subtype is OK. Optimization considerations that allow
6622 -- us to omit the check have already been taken into account in the
6623 -- setting of the Do_Range_Check flag earlier on.
6625 Sub := First (Expressions (N));
6627 -- Handle string literals
6629 if Ekind (Etype (A)) = E_String_Literal_Subtype then
6630 if Do_Range_Check (Sub) then
6631 Set_Do_Range_Check (Sub, False);
6633 -- For string literals we obtain the bounds of the string from the
6634 -- associated subtype.
6636 Insert_Action (N,
6637 Make_Raise_Constraint_Error (Loc,
6638 Condition =>
6639 Make_Not_In (Loc,
6640 Left_Opnd =>
6641 Convert_To (Base_Type (Etype (Sub)),
6642 Duplicate_Subexpr_Move_Checks (Sub)),
6643 Right_Opnd =>
6644 Make_Attribute_Reference (Loc,
6645 Prefix => New_Occurrence_Of (Etype (A), Loc),
6646 Attribute_Name => Name_Range)),
6647 Reason => CE_Index_Check_Failed));
6648 end if;
6650 -- General case
6652 else
6653 declare
6654 A_Idx : Node_Id := Empty;
6655 A_Range : Node_Id;
6656 Ind : Nat;
6657 Num : List_Id;
6658 Range_N : Node_Id;
6660 begin
6661 A_Idx := First_Index (Etype (A));
6662 Ind := 1;
6663 while Present (Sub) loop
6664 if Do_Range_Check (Sub) then
6665 Set_Do_Range_Check (Sub, False);
6667 -- Force evaluation except for the case of a simple name of
6668 -- a nonvolatile entity.
6670 if not Is_Entity_Name (Sub)
6671 or else Treat_As_Volatile (Entity (Sub))
6672 then
6673 Force_Evaluation (Sub);
6674 end if;
6676 if Nkind (A_Idx) = N_Range then
6677 A_Range := A_Idx;
6679 elsif Nkind (A_Idx) = N_Identifier
6680 or else Nkind (A_Idx) = N_Expanded_Name
6681 then
6682 A_Range := Scalar_Range (Entity (A_Idx));
6684 else pragma Assert (Nkind (A_Idx) = N_Subtype_Indication);
6685 A_Range := Range_Expression (Constraint (A_Idx));
6686 end if;
6688 -- For array objects with constant bounds we can generate
6689 -- the index check using the bounds of the type of the index
6691 if Present (A_Ent)
6692 and then Ekind (A_Ent) = E_Variable
6693 and then Is_Constant_Bound (Low_Bound (A_Range))
6694 and then Is_Constant_Bound (High_Bound (A_Range))
6695 then
6696 Range_N :=
6697 Make_Attribute_Reference (Loc,
6698 Prefix =>
6699 New_Occurrence_Of (Etype (A_Idx), Loc),
6700 Attribute_Name => Name_Range);
6702 -- For arrays with non-constant bounds we cannot generate
6703 -- the index check using the bounds of the type of the index
6704 -- since it may reference discriminants of some enclosing
6705 -- type. We obtain the bounds directly from the prefix
6706 -- object.
6708 else
6709 if Ind = 1 then
6710 Num := No_List;
6711 else
6712 Num := New_List (Make_Integer_Literal (Loc, Ind));
6713 end if;
6715 Range_N :=
6716 Make_Attribute_Reference (Loc,
6717 Prefix =>
6718 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
6719 Attribute_Name => Name_Range,
6720 Expressions => Num);
6721 end if;
6723 Insert_Action (N,
6724 Make_Raise_Constraint_Error (Loc,
6725 Condition =>
6726 Make_Not_In (Loc,
6727 Left_Opnd =>
6728 Convert_To (Base_Type (Etype (Sub)),
6729 Duplicate_Subexpr_Move_Checks (Sub)),
6730 Right_Opnd => Range_N),
6731 Reason => CE_Index_Check_Failed));
6732 end if;
6734 A_Idx := Next_Index (A_Idx);
6735 Ind := Ind + 1;
6736 Next (Sub);
6737 end loop;
6738 end;
6739 end if;
6740 end Generate_Index_Checks;
6742 --------------------------
6743 -- Generate_Range_Check --
6744 --------------------------
6746 procedure Generate_Range_Check
6747 (N : Node_Id;
6748 Target_Type : Entity_Id;
6749 Reason : RT_Exception_Code)
6751 Loc : constant Source_Ptr := Sloc (N);
6752 Source_Type : constant Entity_Id := Etype (N);
6753 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
6754 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
6756 procedure Convert_And_Check_Range;
6757 -- Convert the conversion operand to the target base type and save in
6758 -- a temporary. Then check the converted value against the range of the
6759 -- target subtype.
6761 -----------------------------
6762 -- Convert_And_Check_Range --
6763 -----------------------------
6765 procedure Convert_And_Check_Range is
6766 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
6767 Conv_Node : Node_Id;
6769 begin
6770 -- For enumeration types with non-standard representation this is a
6771 -- direct conversion from the enumeration type to the target integer
6772 -- type, which is treated by the back end as a normal integer type
6773 -- conversion, treating the enumeration type as an integer, which is
6774 -- exactly what we want. We set Conversion_OK to make sure that the
6775 -- analyzer does not complain about what otherwise might be an
6776 -- illegal conversion.
6778 if Is_Enumeration_Type (Source_Base_Type)
6779 and then Present (Enum_Pos_To_Rep (Source_Base_Type))
6780 and then Is_Integer_Type (Target_Base_Type)
6781 then
6782 Conv_Node :=
6783 OK_Convert_To
6784 (Typ => Target_Base_Type,
6785 Expr => Duplicate_Subexpr (N));
6787 -- Common case
6789 else
6790 Conv_Node :=
6791 Make_Type_Conversion (Loc,
6792 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
6793 Expression => Duplicate_Subexpr (N));
6794 end if;
6796 -- We make a temporary to hold the value of the converted value
6797 -- (converted to the base type), and then do the test against this
6798 -- temporary. The conversion itself is replaced by an occurrence of
6799 -- Tnn and followed by the explicit range check. Note that checks
6800 -- are suppressed for this code, since we don't want a recursive
6801 -- range check popping up.
6803 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
6804 -- [constraint_error when Tnn not in Target_Type]
6806 Insert_Actions (N, New_List (
6807 Make_Object_Declaration (Loc,
6808 Defining_Identifier => Tnn,
6809 Object_Definition => New_Occurrence_Of (Target_Base_Type, Loc),
6810 Constant_Present => True,
6811 Expression => Conv_Node),
6813 Make_Raise_Constraint_Error (Loc,
6814 Condition =>
6815 Make_Not_In (Loc,
6816 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
6817 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6818 Reason => Reason)),
6819 Suppress => All_Checks);
6821 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
6823 -- Set the type of N, because the declaration for Tnn might not
6824 -- be analyzed yet, as is the case if N appears within a record
6825 -- declaration, as a discriminant constraint or expression.
6827 Set_Etype (N, Target_Base_Type);
6828 end Convert_And_Check_Range;
6830 -- Start of processing for Generate_Range_Check
6832 begin
6833 -- First special case, if the source type is already within the range
6834 -- of the target type, then no check is needed (probably we should have
6835 -- stopped Do_Range_Check from being set in the first place, but better
6836 -- late than never in preventing junk code and junk flag settings.
6838 if In_Subrange_Of (Source_Type, Target_Type)
6840 -- We do NOT apply this if the source node is a literal, since in this
6841 -- case the literal has already been labeled as having the subtype of
6842 -- the target.
6844 and then not
6845 (Nkind_In (N, N_Integer_Literal, N_Real_Literal, N_Character_Literal)
6846 or else
6847 (Is_Entity_Name (N)
6848 and then Ekind (Entity (N)) = E_Enumeration_Literal))
6849 then
6850 Set_Do_Range_Check (N, False);
6851 return;
6852 end if;
6854 -- Here a check is needed. If the expander is not active, or if we are
6855 -- in GNATProve mode, then simply set the Do_Range_Check flag and we
6856 -- are done. In both these cases, we just want to see the range check
6857 -- flag set, we do not want to generate the explicit range check code.
6859 if GNATprove_Mode or else not Expander_Active then
6860 Set_Do_Range_Check (N, True);
6861 return;
6862 end if;
6864 -- Here we will generate an explicit range check, so we don't want to
6865 -- set the Do_Range check flag, since the range check is taken care of
6866 -- by the code we will generate.
6868 Set_Do_Range_Check (N, False);
6870 -- Force evaluation of the node, so that it does not get evaluated twice
6871 -- (once for the check, once for the actual reference). Such a double
6872 -- evaluation is always a potential source of inefficiency, and is
6873 -- functionally incorrect in the volatile case.
6875 -- We skip the evaluation of attribute references because, after these
6876 -- runtime checks are generated, the expander may need to rewrite this
6877 -- node (for example, see Attribute_Max_Size_In_Storage_Elements in
6878 -- Expand_N_Attribute_Reference).
6880 if Nkind (N) /= N_Attribute_Reference
6881 and then (not Is_Entity_Name (N)
6882 or else Treat_As_Volatile (Entity (N)))
6883 then
6884 Force_Evaluation (N, Mode => Strict);
6885 end if;
6887 -- The easiest case is when Source_Base_Type and Target_Base_Type are
6888 -- the same since in this case we can simply do a direct check of the
6889 -- value of N against the bounds of Target_Type.
6891 -- [constraint_error when N not in Target_Type]
6893 -- Note: this is by far the most common case, for example all cases of
6894 -- checks on the RHS of assignments are in this category, but not all
6895 -- cases are like this. Notably conversions can involve two types.
6897 if Source_Base_Type = Target_Base_Type then
6899 -- Insert the explicit range check. Note that we suppress checks for
6900 -- this code, since we don't want a recursive range check popping up.
6902 Insert_Action (N,
6903 Make_Raise_Constraint_Error (Loc,
6904 Condition =>
6905 Make_Not_In (Loc,
6906 Left_Opnd => Duplicate_Subexpr (N),
6907 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6908 Reason => Reason),
6909 Suppress => All_Checks);
6911 -- Next test for the case where the target type is within the bounds
6912 -- of the base type of the source type, since in this case we can
6913 -- simply convert these bounds to the base type of T to do the test.
6915 -- [constraint_error when N not in
6916 -- Source_Base_Type (Target_Type'First)
6917 -- ..
6918 -- Source_Base_Type(Target_Type'Last))]
6920 -- The conversions will always work and need no check
6922 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
6923 -- of converting from an enumeration value to an integer type, such as
6924 -- occurs for the case of generating a range check on Enum'Val(Exp)
6925 -- (which used to be handled by gigi). This is OK, since the conversion
6926 -- itself does not require a check.
6928 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
6930 -- Insert the explicit range check. Note that we suppress checks for
6931 -- this code, since we don't want a recursive range check popping up.
6933 if Is_Discrete_Type (Source_Base_Type)
6934 and then
6935 Is_Discrete_Type (Target_Base_Type)
6936 then
6937 Insert_Action (N,
6938 Make_Raise_Constraint_Error (Loc,
6939 Condition =>
6940 Make_Not_In (Loc,
6941 Left_Opnd => Duplicate_Subexpr (N),
6943 Right_Opnd =>
6944 Make_Range (Loc,
6945 Low_Bound =>
6946 Unchecked_Convert_To (Source_Base_Type,
6947 Make_Attribute_Reference (Loc,
6948 Prefix =>
6949 New_Occurrence_Of (Target_Type, Loc),
6950 Attribute_Name => Name_First)),
6952 High_Bound =>
6953 Unchecked_Convert_To (Source_Base_Type,
6954 Make_Attribute_Reference (Loc,
6955 Prefix =>
6956 New_Occurrence_Of (Target_Type, Loc),
6957 Attribute_Name => Name_Last)))),
6958 Reason => Reason),
6959 Suppress => All_Checks);
6961 -- For conversions involving at least one type that is not discrete,
6962 -- first convert to target type and then generate the range check.
6963 -- This avoids problems with values that are close to a bound of the
6964 -- target type that would fail a range check when done in a larger
6965 -- source type before converting but would pass if converted with
6966 -- rounding and then checked (such as in float-to-float conversions).
6968 else
6969 Convert_And_Check_Range;
6970 end if;
6972 -- Note that at this stage we now that the Target_Base_Type is not in
6973 -- the range of the Source_Base_Type (since even the Target_Type itself
6974 -- is not in this range). It could still be the case that Source_Type is
6975 -- in range of the target base type since we have not checked that case.
6977 -- If that is the case, we can freely convert the source to the target,
6978 -- and then test the target result against the bounds.
6980 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
6981 Convert_And_Check_Range;
6983 -- At this stage, we know that we have two scalar types, which are
6984 -- directly convertible, and where neither scalar type has a base
6985 -- range that is in the range of the other scalar type.
6987 -- The only way this can happen is with a signed and unsigned type.
6988 -- So test for these two cases:
6990 else
6991 -- Case of the source is unsigned and the target is signed
6993 if Is_Unsigned_Type (Source_Base_Type)
6994 and then not Is_Unsigned_Type (Target_Base_Type)
6995 then
6996 -- If the source is unsigned and the target is signed, then we
6997 -- know that the source is not shorter than the target (otherwise
6998 -- the source base type would be in the target base type range).
7000 -- In other words, the unsigned type is either the same size as
7001 -- the target, or it is larger. It cannot be smaller.
7003 pragma Assert
7004 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
7006 -- We only need to check the low bound if the low bound of the
7007 -- target type is non-negative. If the low bound of the target
7008 -- type is negative, then we know that we will fit fine.
7010 -- If the high bound of the target type is negative, then we
7011 -- know we have a constraint error, since we can't possibly
7012 -- have a negative source.
7014 -- With these two checks out of the way, we can do the check
7015 -- using the source type safely
7017 -- This is definitely the most annoying case.
7019 -- [constraint_error
7020 -- when (Target_Type'First >= 0
7021 -- and then
7022 -- N < Source_Base_Type (Target_Type'First))
7023 -- or else Target_Type'Last < 0
7024 -- or else N > Source_Base_Type (Target_Type'Last)];
7026 -- We turn off all checks since we know that the conversions
7027 -- will work fine, given the guards for negative values.
7029 Insert_Action (N,
7030 Make_Raise_Constraint_Error (Loc,
7031 Condition =>
7032 Make_Or_Else (Loc,
7033 Make_Or_Else (Loc,
7034 Left_Opnd =>
7035 Make_And_Then (Loc,
7036 Left_Opnd => Make_Op_Ge (Loc,
7037 Left_Opnd =>
7038 Make_Attribute_Reference (Loc,
7039 Prefix =>
7040 New_Occurrence_Of (Target_Type, Loc),
7041 Attribute_Name => Name_First),
7042 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7044 Right_Opnd =>
7045 Make_Op_Lt (Loc,
7046 Left_Opnd => Duplicate_Subexpr (N),
7047 Right_Opnd =>
7048 Convert_To (Source_Base_Type,
7049 Make_Attribute_Reference (Loc,
7050 Prefix =>
7051 New_Occurrence_Of (Target_Type, Loc),
7052 Attribute_Name => Name_First)))),
7054 Right_Opnd =>
7055 Make_Op_Lt (Loc,
7056 Left_Opnd =>
7057 Make_Attribute_Reference (Loc,
7058 Prefix => New_Occurrence_Of (Target_Type, Loc),
7059 Attribute_Name => Name_Last),
7060 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
7062 Right_Opnd =>
7063 Make_Op_Gt (Loc,
7064 Left_Opnd => Duplicate_Subexpr (N),
7065 Right_Opnd =>
7066 Convert_To (Source_Base_Type,
7067 Make_Attribute_Reference (Loc,
7068 Prefix => New_Occurrence_Of (Target_Type, Loc),
7069 Attribute_Name => Name_Last)))),
7071 Reason => Reason),
7072 Suppress => All_Checks);
7074 -- Only remaining possibility is that the source is signed and
7075 -- the target is unsigned.
7077 else
7078 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
7079 and then Is_Unsigned_Type (Target_Base_Type));
7081 -- If the source is signed and the target is unsigned, then we
7082 -- know that the target is not shorter than the source (otherwise
7083 -- the target base type would be in the source base type range).
7085 -- In other words, the unsigned type is either the same size as
7086 -- the target, or it is larger. It cannot be smaller.
7088 -- Clearly we have an error if the source value is negative since
7089 -- no unsigned type can have negative values. If the source type
7090 -- is non-negative, then the check can be done using the target
7091 -- type.
7093 -- Tnn : constant Target_Base_Type (N) := Target_Type;
7095 -- [constraint_error
7096 -- when N < 0 or else Tnn not in Target_Type];
7098 -- We turn off all checks for the conversion of N to the target
7099 -- base type, since we generate the explicit check to ensure that
7100 -- the value is non-negative
7102 declare
7103 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
7105 begin
7106 Insert_Actions (N, New_List (
7107 Make_Object_Declaration (Loc,
7108 Defining_Identifier => Tnn,
7109 Object_Definition =>
7110 New_Occurrence_Of (Target_Base_Type, Loc),
7111 Constant_Present => True,
7112 Expression =>
7113 Make_Unchecked_Type_Conversion (Loc,
7114 Subtype_Mark =>
7115 New_Occurrence_Of (Target_Base_Type, Loc),
7116 Expression => Duplicate_Subexpr (N))),
7118 Make_Raise_Constraint_Error (Loc,
7119 Condition =>
7120 Make_Or_Else (Loc,
7121 Left_Opnd =>
7122 Make_Op_Lt (Loc,
7123 Left_Opnd => Duplicate_Subexpr (N),
7124 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7126 Right_Opnd =>
7127 Make_Not_In (Loc,
7128 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
7129 Right_Opnd =>
7130 New_Occurrence_Of (Target_Type, Loc))),
7132 Reason => Reason)),
7133 Suppress => All_Checks);
7135 -- Set the Etype explicitly, because Insert_Actions may have
7136 -- placed the declaration in the freeze list for an enclosing
7137 -- construct, and thus it is not analyzed yet.
7139 Set_Etype (Tnn, Target_Base_Type);
7140 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
7141 end;
7142 end if;
7143 end if;
7144 end Generate_Range_Check;
7146 ------------------
7147 -- Get_Check_Id --
7148 ------------------
7150 function Get_Check_Id (N : Name_Id) return Check_Id is
7151 begin
7152 -- For standard check name, we can do a direct computation
7154 if N in First_Check_Name .. Last_Check_Name then
7155 return Check_Id (N - (First_Check_Name - 1));
7157 -- For non-standard names added by pragma Check_Name, search table
7159 else
7160 for J in All_Checks + 1 .. Check_Names.Last loop
7161 if Check_Names.Table (J) = N then
7162 return J;
7163 end if;
7164 end loop;
7165 end if;
7167 -- No matching name found
7169 return No_Check_Id;
7170 end Get_Check_Id;
7172 ---------------------
7173 -- Get_Discriminal --
7174 ---------------------
7176 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
7177 Loc : constant Source_Ptr := Sloc (E);
7178 D : Entity_Id;
7179 Sc : Entity_Id;
7181 begin
7182 -- The bound can be a bona fide parameter of a protected operation,
7183 -- rather than a prival encoded as an in-parameter.
7185 if No (Discriminal_Link (Entity (Bound))) then
7186 return Bound;
7187 end if;
7189 -- Climb the scope stack looking for an enclosing protected type. If
7190 -- we run out of scopes, return the bound itself.
7192 Sc := Scope (E);
7193 while Present (Sc) loop
7194 if Sc = Standard_Standard then
7195 return Bound;
7196 elsif Ekind (Sc) = E_Protected_Type then
7197 exit;
7198 end if;
7200 Sc := Scope (Sc);
7201 end loop;
7203 D := First_Discriminant (Sc);
7204 while Present (D) loop
7205 if Chars (D) = Chars (Bound) then
7206 return New_Occurrence_Of (Discriminal (D), Loc);
7207 end if;
7209 Next_Discriminant (D);
7210 end loop;
7212 return Bound;
7213 end Get_Discriminal;
7215 ----------------------
7216 -- Get_Range_Checks --
7217 ----------------------
7219 function Get_Range_Checks
7220 (Ck_Node : Node_Id;
7221 Target_Typ : Entity_Id;
7222 Source_Typ : Entity_Id := Empty;
7223 Warn_Node : Node_Id := Empty) return Check_Result
7225 begin
7226 return
7227 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
7228 end Get_Range_Checks;
7230 ------------------
7231 -- Guard_Access --
7232 ------------------
7234 function Guard_Access
7235 (Cond : Node_Id;
7236 Loc : Source_Ptr;
7237 Ck_Node : Node_Id) return Node_Id
7239 begin
7240 if Nkind (Cond) = N_Or_Else then
7241 Set_Paren_Count (Cond, 1);
7242 end if;
7244 if Nkind (Ck_Node) = N_Allocator then
7245 return Cond;
7247 else
7248 return
7249 Make_And_Then (Loc,
7250 Left_Opnd =>
7251 Make_Op_Ne (Loc,
7252 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
7253 Right_Opnd => Make_Null (Loc)),
7254 Right_Opnd => Cond);
7255 end if;
7256 end Guard_Access;
7258 -----------------------------
7259 -- Index_Checks_Suppressed --
7260 -----------------------------
7262 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
7263 begin
7264 if Present (E) and then Checks_May_Be_Suppressed (E) then
7265 return Is_Check_Suppressed (E, Index_Check);
7266 else
7267 return Scope_Suppress.Suppress (Index_Check);
7268 end if;
7269 end Index_Checks_Suppressed;
7271 ----------------
7272 -- Initialize --
7273 ----------------
7275 procedure Initialize is
7276 begin
7277 for J in Determine_Range_Cache_N'Range loop
7278 Determine_Range_Cache_N (J) := Empty;
7279 end loop;
7281 Check_Names.Init;
7283 for J in Int range 1 .. All_Checks loop
7284 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
7285 end loop;
7286 end Initialize;
7288 -------------------------
7289 -- Insert_Range_Checks --
7290 -------------------------
7292 procedure Insert_Range_Checks
7293 (Checks : Check_Result;
7294 Node : Node_Id;
7295 Suppress_Typ : Entity_Id;
7296 Static_Sloc : Source_Ptr := No_Location;
7297 Flag_Node : Node_Id := Empty;
7298 Do_Before : Boolean := False)
7300 Checks_On : constant Boolean :=
7301 not Index_Checks_Suppressed (Suppress_Typ)
7302 or else
7303 not Range_Checks_Suppressed (Suppress_Typ);
7305 Check_Node : Node_Id;
7306 Internal_Flag_Node : Node_Id := Flag_Node;
7307 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
7309 begin
7310 -- For now we just return if Checks_On is false, however this should be
7311 -- enhanced to check for an always True value in the condition and to
7312 -- generate a compilation warning???
7314 if not Expander_Active or not Checks_On then
7315 return;
7316 end if;
7318 if Static_Sloc = No_Location then
7319 Internal_Static_Sloc := Sloc (Node);
7320 end if;
7322 if No (Flag_Node) then
7323 Internal_Flag_Node := Node;
7324 end if;
7326 for J in 1 .. 2 loop
7327 exit when No (Checks (J));
7329 if Nkind (Checks (J)) = N_Raise_Constraint_Error
7330 and then Present (Condition (Checks (J)))
7331 then
7332 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
7333 Check_Node := Checks (J);
7334 Mark_Rewrite_Insertion (Check_Node);
7336 if Do_Before then
7337 Insert_Before_And_Analyze (Node, Check_Node);
7338 else
7339 Insert_After_And_Analyze (Node, Check_Node);
7340 end if;
7342 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
7343 end if;
7345 else
7346 Check_Node :=
7347 Make_Raise_Constraint_Error (Internal_Static_Sloc,
7348 Reason => CE_Range_Check_Failed);
7349 Mark_Rewrite_Insertion (Check_Node);
7351 if Do_Before then
7352 Insert_Before_And_Analyze (Node, Check_Node);
7353 else
7354 Insert_After_And_Analyze (Node, Check_Node);
7355 end if;
7356 end if;
7357 end loop;
7358 end Insert_Range_Checks;
7360 ------------------------
7361 -- Insert_Valid_Check --
7362 ------------------------
7364 procedure Insert_Valid_Check
7365 (Expr : Node_Id;
7366 Related_Id : Entity_Id := Empty;
7367 Is_Low_Bound : Boolean := False;
7368 Is_High_Bound : Boolean := False)
7370 Loc : constant Source_Ptr := Sloc (Expr);
7371 Typ : constant Entity_Id := Etype (Expr);
7372 Exp : Node_Id;
7374 begin
7375 -- Do not insert if checks off, or if not checking validity or if
7376 -- expression is known to be valid.
7378 if not Validity_Checks_On
7379 or else Range_Or_Validity_Checks_Suppressed (Expr)
7380 or else Expr_Known_Valid (Expr)
7381 then
7382 return;
7384 -- Do not insert checks within a predicate function. This will arise
7385 -- if the current unit and the predicate function are being compiled
7386 -- with validity checks enabled.
7388 elsif Present (Predicate_Function (Typ))
7389 and then Current_Scope = Predicate_Function (Typ)
7390 then
7391 return;
7393 -- If the expression is a packed component of a modular type of the
7394 -- right size, the data is always valid.
7396 elsif Nkind (Expr) = N_Selected_Component
7397 and then Present (Component_Clause (Entity (Selector_Name (Expr))))
7398 and then Is_Modular_Integer_Type (Typ)
7399 and then Modulus (Typ) = 2 ** Esize (Entity (Selector_Name (Expr)))
7400 then
7401 return;
7403 -- Do not generate a validity check when inside a generic unit as this
7404 -- is an expansion activity.
7406 elsif Inside_A_Generic then
7407 return;
7408 end if;
7410 -- If we have a checked conversion, then validity check applies to
7411 -- the expression inside the conversion, not the result, since if
7412 -- the expression inside is valid, then so is the conversion result.
7414 Exp := Expr;
7415 while Nkind (Exp) = N_Type_Conversion loop
7416 Exp := Expression (Exp);
7417 end loop;
7419 -- Do not generate a check for a variable which already validates the
7420 -- value of an assignable object.
7422 if Is_Validation_Variable_Reference (Exp) then
7423 return;
7424 end if;
7426 declare
7427 CE : Node_Id;
7428 PV : Node_Id;
7429 Var_Id : Entity_Id;
7431 begin
7432 -- If the expression denotes an assignable object, capture its value
7433 -- in a variable and replace the original expression by the variable.
7434 -- This approach has several effects:
7436 -- 1) The evaluation of the object results in only one read in the
7437 -- case where the object is atomic or volatile.
7439 -- Var ... := Object; -- read
7441 -- 2) The captured value is the one verified by attribute 'Valid.
7442 -- As a result the object is not evaluated again, which would
7443 -- result in an unwanted read in the case where the object is
7444 -- atomic or volatile.
7446 -- if not Var'Valid then -- OK, no read of Object
7448 -- if not Object'Valid then -- Wrong, extra read of Object
7450 -- 3) The captured value replaces the original object reference.
7451 -- As a result the object is not evaluated again, in the same
7452 -- vein as 2).
7454 -- ... Var ... -- OK, no read of Object
7456 -- ... Object ... -- Wrong, extra read of Object
7458 -- 4) The use of a variable to capture the value of the object
7459 -- allows the propagation of any changes back to the original
7460 -- object.
7462 -- procedure Call (Val : in out ...);
7464 -- Var : ... := Object; -- read Object
7465 -- if not Var'Valid then -- validity check
7466 -- Call (Var); -- modify Var
7467 -- Object := Var; -- update Object
7469 if Is_Variable (Exp) then
7470 Var_Id := Make_Temporary (Loc, 'T', Exp);
7472 -- Because we could be dealing with a transient scope which would
7473 -- cause our object declaration to remain unanalyzed we must do
7474 -- some manual decoration.
7476 Set_Ekind (Var_Id, E_Variable);
7477 Set_Etype (Var_Id, Typ);
7479 Insert_Action (Exp,
7480 Make_Object_Declaration (Loc,
7481 Defining_Identifier => Var_Id,
7482 Object_Definition => New_Occurrence_Of (Typ, Loc),
7483 Expression => New_Copy_Tree (Exp)),
7484 Suppress => Validity_Check);
7486 Set_Validated_Object (Var_Id, New_Copy_Tree (Exp));
7487 Rewrite (Exp, New_Occurrence_Of (Var_Id, Loc));
7488 PV := New_Occurrence_Of (Var_Id, Loc);
7490 -- Copy the Do_Range_Check flag over to the new Exp, so it doesn't
7491 -- get lost. Floating point types are handled elsewhere.
7493 if not Is_Floating_Point_Type (Typ) then
7494 Set_Do_Range_Check (Exp, Do_Range_Check (Original_Node (Exp)));
7495 end if;
7497 -- Otherwise the expression does not denote a variable. Force its
7498 -- evaluation by capturing its value in a constant. Generate:
7500 -- Temp : constant ... := Exp;
7502 else
7503 Force_Evaluation
7504 (Exp => Exp,
7505 Related_Id => Related_Id,
7506 Is_Low_Bound => Is_Low_Bound,
7507 Is_High_Bound => Is_High_Bound);
7509 PV := New_Copy_Tree (Exp);
7510 end if;
7512 -- A rather specialized test. If PV is an analyzed expression which
7513 -- is an indexed component of a packed array that has not been
7514 -- properly expanded, turn off its Analyzed flag to make sure it
7515 -- gets properly reexpanded. If the prefix is an access value,
7516 -- the dereference will be added later.
7518 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
7519 -- an analyze with the old parent pointer. This may point e.g. to
7520 -- a subprogram call, which deactivates this expansion.
7522 if Analyzed (PV)
7523 and then Nkind (PV) = N_Indexed_Component
7524 and then Is_Array_Type (Etype (Prefix (PV)))
7525 and then Present (Packed_Array_Impl_Type (Etype (Prefix (PV))))
7526 then
7527 Set_Analyzed (PV, False);
7528 end if;
7530 -- Build the raise CE node to check for validity. We build a type
7531 -- qualification for the prefix, since it may not be of the form of
7532 -- a name, and we don't care in this context!
7534 CE :=
7535 Make_Raise_Constraint_Error (Loc,
7536 Condition =>
7537 Make_Op_Not (Loc,
7538 Right_Opnd =>
7539 Make_Attribute_Reference (Loc,
7540 Prefix => PV,
7541 Attribute_Name => Name_Valid)),
7542 Reason => CE_Invalid_Data);
7544 -- Insert the validity check. Note that we do this with validity
7545 -- checks turned off, to avoid recursion, we do not want validity
7546 -- checks on the validity checking code itself.
7548 Insert_Action (Expr, CE, Suppress => Validity_Check);
7550 -- If the expression is a reference to an element of a bit-packed
7551 -- array, then it is rewritten as a renaming declaration. If the
7552 -- expression is an actual in a call, it has not been expanded,
7553 -- waiting for the proper point at which to do it. The same happens
7554 -- with renamings, so that we have to force the expansion now. This
7555 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
7556 -- and exp_ch6.adb.
7558 if Is_Entity_Name (Exp)
7559 and then Nkind (Parent (Entity (Exp))) =
7560 N_Object_Renaming_Declaration
7561 then
7562 declare
7563 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
7564 begin
7565 if Nkind (Old_Exp) = N_Indexed_Component
7566 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
7567 then
7568 Expand_Packed_Element_Reference (Old_Exp);
7569 end if;
7570 end;
7571 end if;
7572 end;
7573 end Insert_Valid_Check;
7575 -------------------------------------
7576 -- Is_Signed_Integer_Arithmetic_Op --
7577 -------------------------------------
7579 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean is
7580 begin
7581 case Nkind (N) is
7582 when N_Op_Abs
7583 | N_Op_Add
7584 | N_Op_Divide
7585 | N_Op_Expon
7586 | N_Op_Minus
7587 | N_Op_Mod
7588 | N_Op_Multiply
7589 | N_Op_Plus
7590 | N_Op_Rem
7591 | N_Op_Subtract
7593 return Is_Signed_Integer_Type (Etype (N));
7595 when N_Case_Expression
7596 | N_If_Expression
7598 return Is_Signed_Integer_Type (Etype (N));
7600 when others =>
7601 return False;
7602 end case;
7603 end Is_Signed_Integer_Arithmetic_Op;
7605 ----------------------------------
7606 -- Install_Null_Excluding_Check --
7607 ----------------------------------
7609 procedure Install_Null_Excluding_Check (N : Node_Id) is
7610 Loc : constant Source_Ptr := Sloc (Parent (N));
7611 Typ : constant Entity_Id := Etype (N);
7613 function Safe_To_Capture_In_Parameter_Value return Boolean;
7614 -- Determines if it is safe to capture Known_Non_Null status for an
7615 -- the entity referenced by node N. The caller ensures that N is indeed
7616 -- an entity name. It is safe to capture the non-null status for an IN
7617 -- parameter when the reference occurs within a declaration that is sure
7618 -- to be executed as part of the declarative region.
7620 procedure Mark_Non_Null;
7621 -- After installation of check, if the node in question is an entity
7622 -- name, then mark this entity as non-null if possible.
7624 function Safe_To_Capture_In_Parameter_Value return Boolean is
7625 E : constant Entity_Id := Entity (N);
7626 S : constant Entity_Id := Current_Scope;
7627 S_Par : Node_Id;
7629 begin
7630 if Ekind (E) /= E_In_Parameter then
7631 return False;
7632 end if;
7634 -- Two initial context checks. We must be inside a subprogram body
7635 -- with declarations and reference must not appear in nested scopes.
7637 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
7638 or else Scope (E) /= S
7639 then
7640 return False;
7641 end if;
7643 S_Par := Parent (Parent (S));
7645 if Nkind (S_Par) /= N_Subprogram_Body
7646 or else No (Declarations (S_Par))
7647 then
7648 return False;
7649 end if;
7651 declare
7652 N_Decl : Node_Id;
7653 P : Node_Id;
7655 begin
7656 -- Retrieve the declaration node of N (if any). Note that N
7657 -- may be a part of a complex initialization expression.
7659 P := Parent (N);
7660 N_Decl := Empty;
7661 while Present (P) loop
7663 -- If we have a short circuit form, and we are within the right
7664 -- hand expression, we return false, since the right hand side
7665 -- is not guaranteed to be elaborated.
7667 if Nkind (P) in N_Short_Circuit
7668 and then N = Right_Opnd (P)
7669 then
7670 return False;
7671 end if;
7673 -- Similarly, if we are in an if expression and not part of the
7674 -- condition, then we return False, since neither the THEN or
7675 -- ELSE dependent expressions will always be elaborated.
7677 if Nkind (P) = N_If_Expression
7678 and then N /= First (Expressions (P))
7679 then
7680 return False;
7681 end if;
7683 -- If within a case expression, and not part of the expression,
7684 -- then return False, since a particular dependent expression
7685 -- may not always be elaborated
7687 if Nkind (P) = N_Case_Expression
7688 and then N /= Expression (P)
7689 then
7690 return False;
7691 end if;
7693 -- While traversing the parent chain, if node N belongs to a
7694 -- statement, then it may never appear in a declarative region.
7696 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
7697 or else Nkind (P) = N_Procedure_Call_Statement
7698 then
7699 return False;
7700 end if;
7702 -- If we are at a declaration, record it and exit
7704 if Nkind (P) in N_Declaration
7705 and then Nkind (P) not in N_Subprogram_Specification
7706 then
7707 N_Decl := P;
7708 exit;
7709 end if;
7711 P := Parent (P);
7712 end loop;
7714 if No (N_Decl) then
7715 return False;
7716 end if;
7718 return List_Containing (N_Decl) = Declarations (S_Par);
7719 end;
7720 end Safe_To_Capture_In_Parameter_Value;
7722 -------------------
7723 -- Mark_Non_Null --
7724 -------------------
7726 procedure Mark_Non_Null is
7727 begin
7728 -- Only case of interest is if node N is an entity name
7730 if Is_Entity_Name (N) then
7732 -- For sure, we want to clear an indication that this is known to
7733 -- be null, since if we get past this check, it definitely is not.
7735 Set_Is_Known_Null (Entity (N), False);
7737 -- We can mark the entity as known to be non-null if either it is
7738 -- safe to capture the value, or in the case of an IN parameter,
7739 -- which is a constant, if the check we just installed is in the
7740 -- declarative region of the subprogram body. In this latter case,
7741 -- a check is decisive for the rest of the body if the expression
7742 -- is sure to be elaborated, since we know we have to elaborate
7743 -- all declarations before executing the body.
7745 -- Couldn't this always be part of Safe_To_Capture_Value ???
7747 if Safe_To_Capture_Value (N, Entity (N))
7748 or else Safe_To_Capture_In_Parameter_Value
7749 then
7750 Set_Is_Known_Non_Null (Entity (N));
7751 end if;
7752 end if;
7753 end Mark_Non_Null;
7755 -- Start of processing for Install_Null_Excluding_Check
7757 begin
7758 pragma Assert (Is_Access_Type (Typ));
7760 -- No check inside a generic, check will be emitted in instance
7762 if Inside_A_Generic then
7763 return;
7764 end if;
7766 -- No check needed if known to be non-null
7768 if Known_Non_Null (N) then
7769 return;
7770 end if;
7772 -- If known to be null, here is where we generate a compile time check
7774 if Known_Null (N) then
7776 -- Avoid generating warning message inside init procs. In SPARK mode
7777 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
7778 -- since it will be turned into an error in any case.
7780 if (not Inside_Init_Proc or else SPARK_Mode = On)
7782 -- Do not emit the warning within a conditional expression,
7783 -- where the expression might not be evaluated, and the warning
7784 -- appear as extraneous noise.
7786 and then not Within_Case_Or_If_Expression (N)
7787 then
7788 Apply_Compile_Time_Constraint_Error
7789 (N, "null value not allowed here??", CE_Access_Check_Failed);
7791 -- Remaining cases, where we silently insert the raise
7793 else
7794 Insert_Action (N,
7795 Make_Raise_Constraint_Error (Loc,
7796 Reason => CE_Access_Check_Failed));
7797 end if;
7799 Mark_Non_Null;
7800 return;
7801 end if;
7803 -- If entity is never assigned, for sure a warning is appropriate
7805 if Is_Entity_Name (N) then
7806 Check_Unset_Reference (N);
7807 end if;
7809 -- No check needed if checks are suppressed on the range. Note that we
7810 -- don't set Is_Known_Non_Null in this case (we could legitimately do
7811 -- so, since the program is erroneous, but we don't like to casually
7812 -- propagate such conclusions from erroneosity).
7814 if Access_Checks_Suppressed (Typ) then
7815 return;
7816 end if;
7818 -- No check needed for access to concurrent record types generated by
7819 -- the expander. This is not just an optimization (though it does indeed
7820 -- remove junk checks). It also avoids generation of junk warnings.
7822 if Nkind (N) in N_Has_Chars
7823 and then Chars (N) = Name_uObject
7824 and then Is_Concurrent_Record_Type
7825 (Directly_Designated_Type (Etype (N)))
7826 then
7827 return;
7828 end if;
7830 -- No check needed in interface thunks since the runtime check is
7831 -- already performed at the caller side.
7833 if Is_Thunk (Current_Scope) then
7834 return;
7835 end if;
7837 -- No check needed for the Get_Current_Excep.all.all idiom generated by
7838 -- the expander within exception handlers, since we know that the value
7839 -- can never be null.
7841 -- Is this really the right way to do this? Normally we generate such
7842 -- code in the expander with checks off, and that's how we suppress this
7843 -- kind of junk check ???
7845 if Nkind (N) = N_Function_Call
7846 and then Nkind (Name (N)) = N_Explicit_Dereference
7847 and then Nkind (Prefix (Name (N))) = N_Identifier
7848 and then Is_RTE (Entity (Prefix (Name (N))), RE_Get_Current_Excep)
7849 then
7850 return;
7851 end if;
7853 -- Otherwise install access check
7855 Insert_Action (N,
7856 Make_Raise_Constraint_Error (Loc,
7857 Condition =>
7858 Make_Op_Eq (Loc,
7859 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
7860 Right_Opnd => Make_Null (Loc)),
7861 Reason => CE_Access_Check_Failed));
7863 Mark_Non_Null;
7864 end Install_Null_Excluding_Check;
7866 -----------------------------------------
7867 -- Install_Primitive_Elaboration_Check --
7868 -----------------------------------------
7870 procedure Install_Primitive_Elaboration_Check (Subp_Body : Node_Id) is
7871 function Within_Compilation_Unit_Instance
7872 (Subp_Id : Entity_Id) return Boolean;
7873 -- Determine whether subprogram Subp_Id appears within an instance which
7874 -- acts as a compilation unit.
7876 --------------------------------------
7877 -- Within_Compilation_Unit_Instance --
7878 --------------------------------------
7880 function Within_Compilation_Unit_Instance
7881 (Subp_Id : Entity_Id) return Boolean
7883 Pack : Entity_Id;
7885 begin
7886 -- Examine the scope chain looking for a compilation-unit-level
7887 -- instance.
7889 Pack := Scope (Subp_Id);
7890 while Present (Pack) and then Pack /= Standard_Standard loop
7891 if Ekind (Pack) = E_Package
7892 and then Is_Generic_Instance (Pack)
7893 and then Nkind (Parent (Unit_Declaration_Node (Pack))) =
7894 N_Compilation_Unit
7895 then
7896 return True;
7897 end if;
7899 Pack := Scope (Pack);
7900 end loop;
7902 return False;
7903 end Within_Compilation_Unit_Instance;
7905 -- Local declarations
7907 Context : constant Node_Id := Parent (Subp_Body);
7908 Loc : constant Source_Ptr := Sloc (Subp_Body);
7909 Subp_Id : constant Entity_Id := Unique_Defining_Entity (Subp_Body);
7910 Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
7912 Decls : List_Id;
7913 Flag_Id : Entity_Id;
7914 Set_Ins : Node_Id;
7915 Set_Stmt : Node_Id;
7916 Tag_Typ : Entity_Id;
7918 -- Start of processing for Install_Primitive_Elaboration_Check
7920 begin
7921 -- Do not generate an elaboration check in compilation modes where
7922 -- expansion is not desirable.
7924 if ASIS_Mode or GNATprove_Mode then
7925 return;
7927 -- Do not generate an elaboration check if all checks have been
7928 -- suppressed.
7930 elsif Suppress_Checks then
7931 return;
7933 -- Do not generate an elaboration check if the related subprogram is
7934 -- not subjected to accessibility checks.
7936 elsif Elaboration_Checks_Suppressed (Subp_Id) then
7937 return;
7939 -- Do not generate an elaboration check if such code is not desirable
7941 elsif Restriction_Active (No_Elaboration_Code) then
7942 return;
7944 -- Do not consider subprograms which act as compilation units, because
7945 -- they cannot be the target of a dispatching call.
7947 elsif Nkind (Context) = N_Compilation_Unit then
7948 return;
7950 -- Do not consider anything other than nonabstract library-level source
7951 -- primitives.
7953 elsif not
7954 (Comes_From_Source (Subp_Id)
7955 and then Is_Library_Level_Entity (Subp_Id)
7956 and then Is_Primitive (Subp_Id)
7957 and then not Is_Abstract_Subprogram (Subp_Id))
7958 then
7959 return;
7961 -- Do not consider inlined primitives, because once the body is inlined
7962 -- the reference to the elaboration flag will be out of place and will
7963 -- result in an undefined symbol.
7965 elsif Is_Inlined (Subp_Id) or else Has_Pragma_Inline (Subp_Id) then
7966 return;
7968 -- Do not generate a duplicate elaboration check. This happens only in
7969 -- the case of primitives completed by an expression function, as the
7970 -- corresponding body is apparently analyzed and expanded twice.
7972 elsif Analyzed (Subp_Body) then
7973 return;
7975 -- Do not consider primitives which occur within an instance that acts
7976 -- as a compilation unit. Such an instance defines its spec and body out
7977 -- of order (body is first) within the tree, which causes the reference
7978 -- to the elaboration flag to appear as an undefined symbol.
7980 elsif Within_Compilation_Unit_Instance (Subp_Id) then
7981 return;
7982 end if;
7984 Tag_Typ := Find_Dispatching_Type (Subp_Id);
7986 -- Only tagged primitives may be the target of a dispatching call
7988 if No (Tag_Typ) then
7989 return;
7991 -- Do not consider finalization-related primitives, because they may
7992 -- need to be called while elaboration is taking place.
7994 elsif Is_Controlled (Tag_Typ)
7995 and then Nam_In (Chars (Subp_Id), Name_Adjust,
7996 Name_Finalize,
7997 Name_Initialize)
7998 then
7999 return;
8000 end if;
8002 -- Create the declaration of the elaboration flag. The name carries a
8003 -- unique counter in case of name overloading.
8005 Flag_Id :=
8006 Make_Defining_Identifier (Loc,
8007 Chars => New_External_Name (Chars (Subp_Id), 'E', -1));
8008 Set_Is_Frozen (Flag_Id);
8010 -- Insert the declaration of the elaboration flag in front of the
8011 -- primitive spec and analyze it in the proper context.
8013 Push_Scope (Scope (Subp_Id));
8015 -- Generate:
8016 -- E : Boolean := False;
8018 Insert_Action (Subp_Decl,
8019 Make_Object_Declaration (Loc,
8020 Defining_Identifier => Flag_Id,
8021 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
8022 Expression => New_Occurrence_Of (Standard_False, Loc)));
8023 Pop_Scope;
8025 -- Prevent the compiler from optimizing the elaboration check by killing
8026 -- the current value of the flag and the associated assignment.
8028 Set_Current_Value (Flag_Id, Empty);
8029 Set_Last_Assignment (Flag_Id, Empty);
8031 -- Add a check at the top of the body declarations to ensure that the
8032 -- elaboration flag has been set.
8034 Decls := Declarations (Subp_Body);
8036 if No (Decls) then
8037 Decls := New_List;
8038 Set_Declarations (Subp_Body, Decls);
8039 end if;
8041 -- Generate:
8042 -- if not F then
8043 -- raise Program_Error with "access before elaboration";
8044 -- end if;
8046 Prepend_To (Decls,
8047 Make_Raise_Program_Error (Loc,
8048 Condition =>
8049 Make_Op_Not (Loc,
8050 Right_Opnd => New_Occurrence_Of (Flag_Id, Loc)),
8051 Reason => PE_Access_Before_Elaboration));
8053 Analyze (First (Decls));
8055 -- Set the elaboration flag once the body has been elaborated. Insert
8056 -- the statement after the subprogram stub when the primitive body is
8057 -- a subunit.
8059 if Nkind (Context) = N_Subunit then
8060 Set_Ins := Corresponding_Stub (Context);
8061 else
8062 Set_Ins := Subp_Body;
8063 end if;
8065 -- Generate:
8066 -- E := True;
8068 Set_Stmt :=
8069 Make_Assignment_Statement (Loc,
8070 Name => New_Occurrence_Of (Flag_Id, Loc),
8071 Expression => New_Occurrence_Of (Standard_True, Loc));
8073 -- Mark the assignment statement as elaboration code. This allows the
8074 -- early call region mechanism (see Sem_Elab) to properly ignore such
8075 -- assignments even though they are non-preelaborable code.
8077 Set_Is_Elaboration_Code (Set_Stmt);
8079 Insert_After_And_Analyze (Set_Ins, Set_Stmt);
8080 end Install_Primitive_Elaboration_Check;
8082 --------------------------
8083 -- Install_Static_Check --
8084 --------------------------
8086 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
8087 Stat : constant Boolean := Is_OK_Static_Expression (R_Cno);
8088 Typ : constant Entity_Id := Etype (R_Cno);
8090 begin
8091 Rewrite (R_Cno,
8092 Make_Raise_Constraint_Error (Loc,
8093 Reason => CE_Range_Check_Failed));
8094 Set_Analyzed (R_Cno);
8095 Set_Etype (R_Cno, Typ);
8096 Set_Raises_Constraint_Error (R_Cno);
8097 Set_Is_Static_Expression (R_Cno, Stat);
8099 -- Now deal with possible local raise handling
8101 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
8102 end Install_Static_Check;
8104 -------------------------
8105 -- Is_Check_Suppressed --
8106 -------------------------
8108 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean is
8109 Ptr : Suppress_Stack_Entry_Ptr;
8111 begin
8112 -- First search the local entity suppress stack. We search this from the
8113 -- top of the stack down so that we get the innermost entry that applies
8114 -- to this case if there are nested entries.
8116 Ptr := Local_Suppress_Stack_Top;
8117 while Ptr /= null loop
8118 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8119 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8120 then
8121 return Ptr.Suppress;
8122 end if;
8124 Ptr := Ptr.Prev;
8125 end loop;
8127 -- Now search the global entity suppress table for a matching entry.
8128 -- We also search this from the top down so that if there are multiple
8129 -- pragmas for the same entity, the last one applies (not clear what
8130 -- or whether the RM specifies this handling, but it seems reasonable).
8132 Ptr := Global_Suppress_Stack_Top;
8133 while Ptr /= null loop
8134 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8135 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8136 then
8137 return Ptr.Suppress;
8138 end if;
8140 Ptr := Ptr.Prev;
8141 end loop;
8143 -- If we did not find a matching entry, then use the normal scope
8144 -- suppress value after all (actually this will be the global setting
8145 -- since it clearly was not overridden at any point). For a predefined
8146 -- check, we test the specific flag. For a user defined check, we check
8147 -- the All_Checks flag. The Overflow flag requires special handling to
8148 -- deal with the General vs Assertion case.
8150 if C = Overflow_Check then
8151 return Overflow_Checks_Suppressed (Empty);
8153 elsif C in Predefined_Check_Id then
8154 return Scope_Suppress.Suppress (C);
8156 else
8157 return Scope_Suppress.Suppress (All_Checks);
8158 end if;
8159 end Is_Check_Suppressed;
8161 ---------------------
8162 -- Kill_All_Checks --
8163 ---------------------
8165 procedure Kill_All_Checks is
8166 begin
8167 if Debug_Flag_CC then
8168 w ("Kill_All_Checks");
8169 end if;
8171 -- We reset the number of saved checks to zero, and also modify all
8172 -- stack entries for statement ranges to indicate that the number of
8173 -- checks at each level is now zero.
8175 Num_Saved_Checks := 0;
8177 -- Note: the Int'Min here avoids any possibility of J being out of
8178 -- range when called from e.g. Conditional_Statements_Begin.
8180 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
8181 Saved_Checks_Stack (J) := 0;
8182 end loop;
8183 end Kill_All_Checks;
8185 -----------------
8186 -- Kill_Checks --
8187 -----------------
8189 procedure Kill_Checks (V : Entity_Id) is
8190 begin
8191 if Debug_Flag_CC then
8192 w ("Kill_Checks for entity", Int (V));
8193 end if;
8195 for J in 1 .. Num_Saved_Checks loop
8196 if Saved_Checks (J).Entity = V then
8197 if Debug_Flag_CC then
8198 w (" Checks killed for saved check ", J);
8199 end if;
8201 Saved_Checks (J).Killed := True;
8202 end if;
8203 end loop;
8204 end Kill_Checks;
8206 ------------------------------
8207 -- Length_Checks_Suppressed --
8208 ------------------------------
8210 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
8211 begin
8212 if Present (E) and then Checks_May_Be_Suppressed (E) then
8213 return Is_Check_Suppressed (E, Length_Check);
8214 else
8215 return Scope_Suppress.Suppress (Length_Check);
8216 end if;
8217 end Length_Checks_Suppressed;
8219 -----------------------
8220 -- Make_Bignum_Block --
8221 -----------------------
8223 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id is
8224 M : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uM);
8225 begin
8226 return
8227 Make_Block_Statement (Loc,
8228 Declarations =>
8229 New_List (Build_SS_Mark_Call (Loc, M)),
8230 Handled_Statement_Sequence =>
8231 Make_Handled_Sequence_Of_Statements (Loc,
8232 Statements => New_List (Build_SS_Release_Call (Loc, M))));
8233 end Make_Bignum_Block;
8235 ----------------------------------
8236 -- Minimize_Eliminate_Overflows --
8237 ----------------------------------
8239 -- This is a recursive routine that is called at the top of an expression
8240 -- tree to properly process overflow checking for a whole subtree by making
8241 -- recursive calls to process operands. This processing may involve the use
8242 -- of bignum or long long integer arithmetic, which will change the types
8243 -- of operands and results. That's why we can't do this bottom up (since
8244 -- it would interfere with semantic analysis).
8246 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
8247 -- the operator expansion routines, as well as the expansion routines for
8248 -- if/case expression, do nothing (for the moment) except call the routine
8249 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
8250 -- routine does nothing for non top-level nodes, so at the point where the
8251 -- call is made for the top level node, the entire expression subtree has
8252 -- not been expanded, or processed for overflow. All that has to happen as
8253 -- a result of the top level call to this routine.
8255 -- As noted above, the overflow processing works by making recursive calls
8256 -- for the operands, and figuring out what to do, based on the processing
8257 -- of these operands (e.g. if a bignum operand appears, the parent op has
8258 -- to be done in bignum mode), and the determined ranges of the operands.
8260 -- After possible rewriting of a constituent subexpression node, a call is
8261 -- made to either reexpand the node (if nothing has changed) or reanalyze
8262 -- the node (if it has been modified by the overflow check processing). The
8263 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
8264 -- a recursive call into the whole overflow apparatus, an important rule
8265 -- for this call is that the overflow handling mode must be temporarily set
8266 -- to STRICT.
8268 procedure Minimize_Eliminate_Overflows
8269 (N : Node_Id;
8270 Lo : out Uint;
8271 Hi : out Uint;
8272 Top_Level : Boolean)
8274 Rtyp : constant Entity_Id := Etype (N);
8275 pragma Assert (Is_Signed_Integer_Type (Rtyp));
8276 -- Result type, must be a signed integer type
8278 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
8279 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
8281 Loc : constant Source_Ptr := Sloc (N);
8283 Rlo, Rhi : Uint;
8284 -- Ranges of values for right operand (operator case)
8286 Llo : Uint := No_Uint; -- initialize to prevent warning
8287 Lhi : Uint := No_Uint; -- initialize to prevent warning
8288 -- Ranges of values for left operand (operator case)
8290 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
8291 -- Operands and results are of this type when we convert
8293 LLLo : constant Uint := Intval (Type_Low_Bound (LLIB));
8294 LLHi : constant Uint := Intval (Type_High_Bound (LLIB));
8295 -- Bounds of Long_Long_Integer
8297 Binary : constant Boolean := Nkind (N) in N_Binary_Op;
8298 -- Indicates binary operator case
8300 OK : Boolean;
8301 -- Used in call to Determine_Range
8303 Bignum_Operands : Boolean;
8304 -- Set True if one or more operands is already of type Bignum, meaning
8305 -- that for sure (regardless of Top_Level setting) we are committed to
8306 -- doing the operation in Bignum mode (or in the case of a case or if
8307 -- expression, converting all the dependent expressions to Bignum).
8309 Long_Long_Integer_Operands : Boolean;
8310 -- Set True if one or more operands is already of type Long_Long_Integer
8311 -- which means that if the result is known to be in the result type
8312 -- range, then we must convert such operands back to the result type.
8314 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False);
8315 -- This is called when we have modified the node and we therefore need
8316 -- to reanalyze it. It is important that we reset the mode to STRICT for
8317 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
8318 -- we would reenter this routine recursively which would not be good.
8319 -- The argument Suppress is set True if we also want to suppress
8320 -- overflow checking for the reexpansion (this is set when we know
8321 -- overflow is not possible). Typ is the type for the reanalysis.
8323 procedure Reexpand (Suppress : Boolean := False);
8324 -- This is like Reanalyze, but does not do the Analyze step, it only
8325 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
8326 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
8327 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
8328 -- Note that skipping reanalysis is not just an optimization, testing
8329 -- has showed up several complex cases in which reanalyzing an already
8330 -- analyzed node causes incorrect behavior.
8332 function In_Result_Range return Boolean;
8333 -- Returns True iff Lo .. Hi are within range of the result type
8335 procedure Max (A : in out Uint; B : Uint);
8336 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
8338 procedure Min (A : in out Uint; B : Uint);
8339 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
8341 ---------------------
8342 -- In_Result_Range --
8343 ---------------------
8345 function In_Result_Range return Boolean is
8346 begin
8347 if Lo = No_Uint or else Hi = No_Uint then
8348 return False;
8350 elsif Is_OK_Static_Subtype (Etype (N)) then
8351 return Lo >= Expr_Value (Type_Low_Bound (Rtyp))
8352 and then
8353 Hi <= Expr_Value (Type_High_Bound (Rtyp));
8355 else
8356 return Lo >= Expr_Value (Type_Low_Bound (Base_Type (Rtyp)))
8357 and then
8358 Hi <= Expr_Value (Type_High_Bound (Base_Type (Rtyp)));
8359 end if;
8360 end In_Result_Range;
8362 ---------
8363 -- Max --
8364 ---------
8366 procedure Max (A : in out Uint; B : Uint) is
8367 begin
8368 if A = No_Uint or else B > A then
8369 A := B;
8370 end if;
8371 end Max;
8373 ---------
8374 -- Min --
8375 ---------
8377 procedure Min (A : in out Uint; B : Uint) is
8378 begin
8379 if A = No_Uint or else B < A then
8380 A := B;
8381 end if;
8382 end Min;
8384 ---------------
8385 -- Reanalyze --
8386 ---------------
8388 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False) is
8389 Svg : constant Overflow_Mode_Type :=
8390 Scope_Suppress.Overflow_Mode_General;
8391 Sva : constant Overflow_Mode_Type :=
8392 Scope_Suppress.Overflow_Mode_Assertions;
8393 Svo : constant Boolean :=
8394 Scope_Suppress.Suppress (Overflow_Check);
8396 begin
8397 Scope_Suppress.Overflow_Mode_General := Strict;
8398 Scope_Suppress.Overflow_Mode_Assertions := Strict;
8400 if Suppress then
8401 Scope_Suppress.Suppress (Overflow_Check) := True;
8402 end if;
8404 Analyze_And_Resolve (N, Typ);
8406 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8407 Scope_Suppress.Overflow_Mode_General := Svg;
8408 Scope_Suppress.Overflow_Mode_Assertions := Sva;
8409 end Reanalyze;
8411 --------------
8412 -- Reexpand --
8413 --------------
8415 procedure Reexpand (Suppress : Boolean := False) is
8416 Svg : constant Overflow_Mode_Type :=
8417 Scope_Suppress.Overflow_Mode_General;
8418 Sva : constant Overflow_Mode_Type :=
8419 Scope_Suppress.Overflow_Mode_Assertions;
8420 Svo : constant Boolean :=
8421 Scope_Suppress.Suppress (Overflow_Check);
8423 begin
8424 Scope_Suppress.Overflow_Mode_General := Strict;
8425 Scope_Suppress.Overflow_Mode_Assertions := Strict;
8426 Set_Analyzed (N, False);
8428 if Suppress then
8429 Scope_Suppress.Suppress (Overflow_Check) := True;
8430 end if;
8432 Expand (N);
8434 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8435 Scope_Suppress.Overflow_Mode_General := Svg;
8436 Scope_Suppress.Overflow_Mode_Assertions := Sva;
8437 end Reexpand;
8439 -- Start of processing for Minimize_Eliminate_Overflows
8441 begin
8442 -- Default initialize Lo and Hi since these are not guaranteed to be
8443 -- set otherwise.
8445 Lo := No_Uint;
8446 Hi := No_Uint;
8448 -- Case where we do not have a signed integer arithmetic operation
8450 if not Is_Signed_Integer_Arithmetic_Op (N) then
8452 -- Use the normal Determine_Range routine to get the range. We
8453 -- don't require operands to be valid, invalid values may result in
8454 -- rubbish results where the result has not been properly checked for
8455 -- overflow, that's fine.
8457 Determine_Range (N, OK, Lo, Hi, Assume_Valid => False);
8459 -- If Determine_Range did not work (can this in fact happen? Not
8460 -- clear but might as well protect), use type bounds.
8462 if not OK then
8463 Lo := Intval (Type_Low_Bound (Base_Type (Etype (N))));
8464 Hi := Intval (Type_High_Bound (Base_Type (Etype (N))));
8465 end if;
8467 -- If we don't have a binary operator, all we have to do is to set
8468 -- the Hi/Lo range, so we are done.
8470 return;
8472 -- Processing for if expression
8474 elsif Nkind (N) = N_If_Expression then
8475 declare
8476 Then_DE : constant Node_Id := Next (First (Expressions (N)));
8477 Else_DE : constant Node_Id := Next (Then_DE);
8479 begin
8480 Bignum_Operands := False;
8482 Minimize_Eliminate_Overflows
8483 (Then_DE, Lo, Hi, Top_Level => False);
8485 if Lo = No_Uint then
8486 Bignum_Operands := True;
8487 end if;
8489 Minimize_Eliminate_Overflows
8490 (Else_DE, Rlo, Rhi, Top_Level => False);
8492 if Rlo = No_Uint then
8493 Bignum_Operands := True;
8494 else
8495 Long_Long_Integer_Operands :=
8496 Etype (Then_DE) = LLIB or else Etype (Else_DE) = LLIB;
8498 Min (Lo, Rlo);
8499 Max (Hi, Rhi);
8500 end if;
8502 -- If at least one of our operands is now Bignum, we must rebuild
8503 -- the if expression to use Bignum operands. We will analyze the
8504 -- rebuilt if expression with overflow checks off, since once we
8505 -- are in bignum mode, we are all done with overflow checks.
8507 if Bignum_Operands then
8508 Rewrite (N,
8509 Make_If_Expression (Loc,
8510 Expressions => New_List (
8511 Remove_Head (Expressions (N)),
8512 Convert_To_Bignum (Then_DE),
8513 Convert_To_Bignum (Else_DE)),
8514 Is_Elsif => Is_Elsif (N)));
8516 Reanalyze (RTE (RE_Bignum), Suppress => True);
8518 -- If we have no Long_Long_Integer operands, then we are in result
8519 -- range, since it means that none of our operands felt the need
8520 -- to worry about overflow (otherwise it would have already been
8521 -- converted to long long integer or bignum). We reexpand to
8522 -- complete the expansion of the if expression (but we do not
8523 -- need to reanalyze).
8525 elsif not Long_Long_Integer_Operands then
8526 Set_Do_Overflow_Check (N, False);
8527 Reexpand;
8529 -- Otherwise convert us to long long integer mode. Note that we
8530 -- don't need any further overflow checking at this level.
8532 else
8533 Convert_To_And_Rewrite (LLIB, Then_DE);
8534 Convert_To_And_Rewrite (LLIB, Else_DE);
8535 Set_Etype (N, LLIB);
8537 -- Now reanalyze with overflow checks off
8539 Set_Do_Overflow_Check (N, False);
8540 Reanalyze (LLIB, Suppress => True);
8541 end if;
8542 end;
8544 return;
8546 -- Here for case expression
8548 elsif Nkind (N) = N_Case_Expression then
8549 Bignum_Operands := False;
8550 Long_Long_Integer_Operands := False;
8552 declare
8553 Alt : Node_Id;
8555 begin
8556 -- Loop through expressions applying recursive call
8558 Alt := First (Alternatives (N));
8559 while Present (Alt) loop
8560 declare
8561 Aexp : constant Node_Id := Expression (Alt);
8563 begin
8564 Minimize_Eliminate_Overflows
8565 (Aexp, Lo, Hi, Top_Level => False);
8567 if Lo = No_Uint then
8568 Bignum_Operands := True;
8569 elsif Etype (Aexp) = LLIB then
8570 Long_Long_Integer_Operands := True;
8571 end if;
8572 end;
8574 Next (Alt);
8575 end loop;
8577 -- If we have no bignum or long long integer operands, it means
8578 -- that none of our dependent expressions could raise overflow.
8579 -- In this case, we simply return with no changes except for
8580 -- resetting the overflow flag, since we are done with overflow
8581 -- checks for this node. We will reexpand to get the needed
8582 -- expansion for the case expression, but we do not need to
8583 -- reanalyze, since nothing has changed.
8585 if not (Bignum_Operands or Long_Long_Integer_Operands) then
8586 Set_Do_Overflow_Check (N, False);
8587 Reexpand (Suppress => True);
8589 -- Otherwise we are going to rebuild the case expression using
8590 -- either bignum or long long integer operands throughout.
8592 else
8593 declare
8594 Rtype : Entity_Id;
8595 pragma Warnings (Off, Rtype);
8596 New_Alts : List_Id;
8597 New_Exp : Node_Id;
8599 begin
8600 New_Alts := New_List;
8601 Alt := First (Alternatives (N));
8602 while Present (Alt) loop
8603 if Bignum_Operands then
8604 New_Exp := Convert_To_Bignum (Expression (Alt));
8605 Rtype := RTE (RE_Bignum);
8606 else
8607 New_Exp := Convert_To (LLIB, Expression (Alt));
8608 Rtype := LLIB;
8609 end if;
8611 Append_To (New_Alts,
8612 Make_Case_Expression_Alternative (Sloc (Alt),
8613 Actions => No_List,
8614 Discrete_Choices => Discrete_Choices (Alt),
8615 Expression => New_Exp));
8617 Next (Alt);
8618 end loop;
8620 Rewrite (N,
8621 Make_Case_Expression (Loc,
8622 Expression => Expression (N),
8623 Alternatives => New_Alts));
8625 Reanalyze (Rtype, Suppress => True);
8626 end;
8627 end if;
8628 end;
8630 return;
8631 end if;
8633 -- If we have an arithmetic operator we make recursive calls on the
8634 -- operands to get the ranges (and to properly process the subtree
8635 -- that lies below us).
8637 Minimize_Eliminate_Overflows
8638 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
8640 if Binary then
8641 Minimize_Eliminate_Overflows
8642 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
8643 end if;
8645 -- Record if we have Long_Long_Integer operands
8647 Long_Long_Integer_Operands :=
8648 Etype (Right_Opnd (N)) = LLIB
8649 or else (Binary and then Etype (Left_Opnd (N)) = LLIB);
8651 -- If either operand is a bignum, then result will be a bignum and we
8652 -- don't need to do any range analysis. As previously discussed we could
8653 -- do range analysis in such cases, but it could mean working with giant
8654 -- numbers at compile time for very little gain (the number of cases
8655 -- in which we could slip back from bignum mode is small).
8657 if Rlo = No_Uint or else (Binary and then Llo = No_Uint) then
8658 Lo := No_Uint;
8659 Hi := No_Uint;
8660 Bignum_Operands := True;
8662 -- Otherwise compute result range
8664 else
8665 Bignum_Operands := False;
8667 case Nkind (N) is
8669 -- Absolute value
8671 when N_Op_Abs =>
8672 Lo := Uint_0;
8673 Hi := UI_Max (abs Rlo, abs Rhi);
8675 -- Addition
8677 when N_Op_Add =>
8678 Lo := Llo + Rlo;
8679 Hi := Lhi + Rhi;
8681 -- Division
8683 when N_Op_Divide =>
8685 -- If the right operand can only be zero, set 0..0
8687 if Rlo = 0 and then Rhi = 0 then
8688 Lo := Uint_0;
8689 Hi := Uint_0;
8691 -- Possible bounds of division must come from dividing end
8692 -- values of the input ranges (four possibilities), provided
8693 -- zero is not included in the possible values of the right
8694 -- operand.
8696 -- Otherwise, we just consider two intervals of values for
8697 -- the right operand: the interval of negative values (up to
8698 -- -1) and the interval of positive values (starting at 1).
8699 -- Since division by 1 is the identity, and division by -1
8700 -- is negation, we get all possible bounds of division in that
8701 -- case by considering:
8702 -- - all values from the division of end values of input
8703 -- ranges;
8704 -- - the end values of the left operand;
8705 -- - the negation of the end values of the left operand.
8707 else
8708 declare
8709 Mrk : constant Uintp.Save_Mark := Mark;
8710 -- Mark so we can release the RR and Ev values
8712 Ev1 : Uint;
8713 Ev2 : Uint;
8714 Ev3 : Uint;
8715 Ev4 : Uint;
8717 begin
8718 -- Discard extreme values of zero for the divisor, since
8719 -- they will simply result in an exception in any case.
8721 if Rlo = 0 then
8722 Rlo := Uint_1;
8723 elsif Rhi = 0 then
8724 Rhi := -Uint_1;
8725 end if;
8727 -- Compute possible bounds coming from dividing end
8728 -- values of the input ranges.
8730 Ev1 := Llo / Rlo;
8731 Ev2 := Llo / Rhi;
8732 Ev3 := Lhi / Rlo;
8733 Ev4 := Lhi / Rhi;
8735 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8736 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8738 -- If the right operand can be both negative or positive,
8739 -- include the end values of the left operand in the
8740 -- extreme values, as well as their negation.
8742 if Rlo < 0 and then Rhi > 0 then
8743 Ev1 := Llo;
8744 Ev2 := -Llo;
8745 Ev3 := Lhi;
8746 Ev4 := -Lhi;
8748 Min (Lo,
8749 UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4)));
8750 Max (Hi,
8751 UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4)));
8752 end if;
8754 -- Release the RR and Ev values
8756 Release_And_Save (Mrk, Lo, Hi);
8757 end;
8758 end if;
8760 -- Exponentiation
8762 when N_Op_Expon =>
8764 -- Discard negative values for the exponent, since they will
8765 -- simply result in an exception in any case.
8767 if Rhi < 0 then
8768 Rhi := Uint_0;
8769 elsif Rlo < 0 then
8770 Rlo := Uint_0;
8771 end if;
8773 -- Estimate number of bits in result before we go computing
8774 -- giant useless bounds. Basically the number of bits in the
8775 -- result is the number of bits in the base multiplied by the
8776 -- value of the exponent. If this is big enough that the result
8777 -- definitely won't fit in Long_Long_Integer, switch to bignum
8778 -- mode immediately, and avoid computing giant bounds.
8780 -- The comparison here is approximate, but conservative, it
8781 -- only clicks on cases that are sure to exceed the bounds.
8783 if Num_Bits (UI_Max (abs Llo, abs Lhi)) * Rhi + 1 > 100 then
8784 Lo := No_Uint;
8785 Hi := No_Uint;
8787 -- If right operand is zero then result is 1
8789 elsif Rhi = 0 then
8790 Lo := Uint_1;
8791 Hi := Uint_1;
8793 else
8794 -- High bound comes either from exponentiation of largest
8795 -- positive value to largest exponent value, or from
8796 -- the exponentiation of most negative value to an
8797 -- even exponent.
8799 declare
8800 Hi1, Hi2 : Uint;
8802 begin
8803 if Lhi > 0 then
8804 Hi1 := Lhi ** Rhi;
8805 else
8806 Hi1 := Uint_0;
8807 end if;
8809 if Llo < 0 then
8810 if Rhi mod 2 = 0 then
8811 Hi2 := Llo ** Rhi;
8812 else
8813 Hi2 := Llo ** (Rhi - 1);
8814 end if;
8815 else
8816 Hi2 := Uint_0;
8817 end if;
8819 Hi := UI_Max (Hi1, Hi2);
8820 end;
8822 -- Result can only be negative if base can be negative
8824 if Llo < 0 then
8825 if Rhi mod 2 = 0 then
8826 Lo := Llo ** (Rhi - 1);
8827 else
8828 Lo := Llo ** Rhi;
8829 end if;
8831 -- Otherwise low bound is minimum ** minimum
8833 else
8834 Lo := Llo ** Rlo;
8835 end if;
8836 end if;
8838 -- Negation
8840 when N_Op_Minus =>
8841 Lo := -Rhi;
8842 Hi := -Rlo;
8844 -- Mod
8846 when N_Op_Mod =>
8847 declare
8848 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8849 -- This is the maximum absolute value of the result
8851 begin
8852 Lo := Uint_0;
8853 Hi := Uint_0;
8855 -- The result depends only on the sign and magnitude of
8856 -- the right operand, it does not depend on the sign or
8857 -- magnitude of the left operand.
8859 if Rlo < 0 then
8860 Lo := -Maxabs;
8861 end if;
8863 if Rhi > 0 then
8864 Hi := Maxabs;
8865 end if;
8866 end;
8868 -- Multiplication
8870 when N_Op_Multiply =>
8872 -- Possible bounds of multiplication must come from multiplying
8873 -- end values of the input ranges (four possibilities).
8875 declare
8876 Mrk : constant Uintp.Save_Mark := Mark;
8877 -- Mark so we can release the Ev values
8879 Ev1 : constant Uint := Llo * Rlo;
8880 Ev2 : constant Uint := Llo * Rhi;
8881 Ev3 : constant Uint := Lhi * Rlo;
8882 Ev4 : constant Uint := Lhi * Rhi;
8884 begin
8885 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8886 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8888 -- Release the Ev values
8890 Release_And_Save (Mrk, Lo, Hi);
8891 end;
8893 -- Plus operator (affirmation)
8895 when N_Op_Plus =>
8896 Lo := Rlo;
8897 Hi := Rhi;
8899 -- Remainder
8901 when N_Op_Rem =>
8902 declare
8903 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8904 -- This is the maximum absolute value of the result. Note
8905 -- that the result range does not depend on the sign of the
8906 -- right operand.
8908 begin
8909 Lo := Uint_0;
8910 Hi := Uint_0;
8912 -- Case of left operand negative, which results in a range
8913 -- of -Maxabs .. 0 for those negative values. If there are
8914 -- no negative values then Lo value of result is always 0.
8916 if Llo < 0 then
8917 Lo := -Maxabs;
8918 end if;
8920 -- Case of left operand positive
8922 if Lhi > 0 then
8923 Hi := Maxabs;
8924 end if;
8925 end;
8927 -- Subtract
8929 when N_Op_Subtract =>
8930 Lo := Llo - Rhi;
8931 Hi := Lhi - Rlo;
8933 -- Nothing else should be possible
8935 when others =>
8936 raise Program_Error;
8937 end case;
8938 end if;
8940 -- Here for the case where we have not rewritten anything (no bignum
8941 -- operands or long long integer operands), and we know the result.
8942 -- If we know we are in the result range, and we do not have Bignum
8943 -- operands or Long_Long_Integer operands, we can just reexpand with
8944 -- overflow checks turned off (since we know we cannot have overflow).
8945 -- As always the reexpansion is required to complete expansion of the
8946 -- operator, but we do not need to reanalyze, and we prevent recursion
8947 -- by suppressing the check.
8949 if not (Bignum_Operands or Long_Long_Integer_Operands)
8950 and then In_Result_Range
8951 then
8952 Set_Do_Overflow_Check (N, False);
8953 Reexpand (Suppress => True);
8954 return;
8956 -- Here we know that we are not in the result range, and in the general
8957 -- case we will move into either the Bignum or Long_Long_Integer domain
8958 -- to compute the result. However, there is one exception. If we are
8959 -- at the top level, and we do not have Bignum or Long_Long_Integer
8960 -- operands, we will have to immediately convert the result back to
8961 -- the result type, so there is no point in Bignum/Long_Long_Integer
8962 -- fiddling.
8964 elsif Top_Level
8965 and then not (Bignum_Operands or Long_Long_Integer_Operands)
8967 -- One further refinement. If we are at the top level, but our parent
8968 -- is a type conversion, then go into bignum or long long integer node
8969 -- since the result will be converted to that type directly without
8970 -- going through the result type, and we may avoid an overflow. This
8971 -- is the case for example of Long_Long_Integer (A ** 4), where A is
8972 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
8973 -- but does not fit in Integer.
8975 and then Nkind (Parent (N)) /= N_Type_Conversion
8976 then
8977 -- Here keep original types, but we need to complete analysis
8979 -- One subtlety. We can't just go ahead and do an analyze operation
8980 -- here because it will cause recursion into the whole MINIMIZED/
8981 -- ELIMINATED overflow processing which is not what we want. Here
8982 -- we are at the top level, and we need a check against the result
8983 -- mode (i.e. we want to use STRICT mode). So do exactly that.
8984 -- Also, we have not modified the node, so this is a case where
8985 -- we need to reexpand, but not reanalyze.
8987 Reexpand;
8988 return;
8990 -- Cases where we do the operation in Bignum mode. This happens either
8991 -- because one of our operands is in Bignum mode already, or because
8992 -- the computed bounds are outside the bounds of Long_Long_Integer,
8993 -- which in some cases can be indicated by Hi and Lo being No_Uint.
8995 -- Note: we could do better here and in some cases switch back from
8996 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
8997 -- 0 .. 1, but the cases are rare and it is not worth the effort.
8998 -- Failing to do this switching back is only an efficiency issue.
9000 elsif Lo = No_Uint or else Lo < LLLo or else Hi > LLHi then
9002 -- OK, we are definitely outside the range of Long_Long_Integer. The
9003 -- question is whether to move to Bignum mode, or stay in the domain
9004 -- of Long_Long_Integer, signalling that an overflow check is needed.
9006 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
9007 -- the Bignum business. In ELIMINATED mode, we will normally move
9008 -- into Bignum mode, but there is an exception if neither of our
9009 -- operands is Bignum now, and we are at the top level (Top_Level
9010 -- set True). In this case, there is no point in moving into Bignum
9011 -- mode to prevent overflow if the caller will immediately convert
9012 -- the Bignum value back to LLI with an overflow check. It's more
9013 -- efficient to stay in LLI mode with an overflow check (if needed)
9015 if Check_Mode = Minimized
9016 or else (Top_Level and not Bignum_Operands)
9017 then
9018 if Do_Overflow_Check (N) then
9019 Enable_Overflow_Check (N);
9020 end if;
9022 -- The result now has to be in Long_Long_Integer mode, so adjust
9023 -- the possible range to reflect this. Note these calls also
9024 -- change No_Uint values from the top level case to LLI bounds.
9026 Max (Lo, LLLo);
9027 Min (Hi, LLHi);
9029 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
9031 else
9032 pragma Assert (Check_Mode = Eliminated);
9034 declare
9035 Fent : Entity_Id;
9036 Args : List_Id;
9038 begin
9039 case Nkind (N) is
9040 when N_Op_Abs =>
9041 Fent := RTE (RE_Big_Abs);
9043 when N_Op_Add =>
9044 Fent := RTE (RE_Big_Add);
9046 when N_Op_Divide =>
9047 Fent := RTE (RE_Big_Div);
9049 when N_Op_Expon =>
9050 Fent := RTE (RE_Big_Exp);
9052 when N_Op_Minus =>
9053 Fent := RTE (RE_Big_Neg);
9055 when N_Op_Mod =>
9056 Fent := RTE (RE_Big_Mod);
9058 when N_Op_Multiply =>
9059 Fent := RTE (RE_Big_Mul);
9061 when N_Op_Rem =>
9062 Fent := RTE (RE_Big_Rem);
9064 when N_Op_Subtract =>
9065 Fent := RTE (RE_Big_Sub);
9067 -- Anything else is an internal error, this includes the
9068 -- N_Op_Plus case, since how can plus cause the result
9069 -- to be out of range if the operand is in range?
9071 when others =>
9072 raise Program_Error;
9073 end case;
9075 -- Construct argument list for Bignum call, converting our
9076 -- operands to Bignum form if they are not already there.
9078 Args := New_List;
9080 if Binary then
9081 Append_To (Args, Convert_To_Bignum (Left_Opnd (N)));
9082 end if;
9084 Append_To (Args, Convert_To_Bignum (Right_Opnd (N)));
9086 -- Now rewrite the arithmetic operator with a call to the
9087 -- corresponding bignum function.
9089 Rewrite (N,
9090 Make_Function_Call (Loc,
9091 Name => New_Occurrence_Of (Fent, Loc),
9092 Parameter_Associations => Args));
9093 Reanalyze (RTE (RE_Bignum), Suppress => True);
9095 -- Indicate result is Bignum mode
9097 Lo := No_Uint;
9098 Hi := No_Uint;
9099 return;
9100 end;
9101 end if;
9103 -- Otherwise we are in range of Long_Long_Integer, so no overflow
9104 -- check is required, at least not yet.
9106 else
9107 Set_Do_Overflow_Check (N, False);
9108 end if;
9110 -- Here we are not in Bignum territory, but we may have long long
9111 -- integer operands that need special handling. First a special check:
9112 -- If an exponentiation operator exponent is of type Long_Long_Integer,
9113 -- it means we converted it to prevent overflow, but exponentiation
9114 -- requires a Natural right operand, so convert it back to Natural.
9115 -- This conversion may raise an exception which is fine.
9117 if Nkind (N) = N_Op_Expon and then Etype (Right_Opnd (N)) = LLIB then
9118 Convert_To_And_Rewrite (Standard_Natural, Right_Opnd (N));
9119 end if;
9121 -- Here we will do the operation in Long_Long_Integer. We do this even
9122 -- if we know an overflow check is required, better to do this in long
9123 -- long integer mode, since we are less likely to overflow.
9125 -- Convert right or only operand to Long_Long_Integer, except that
9126 -- we do not touch the exponentiation right operand.
9128 if Nkind (N) /= N_Op_Expon then
9129 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
9130 end if;
9132 -- Convert left operand to Long_Long_Integer for binary case
9134 if Binary then
9135 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
9136 end if;
9138 -- Reset node to unanalyzed
9140 Set_Analyzed (N, False);
9141 Set_Etype (N, Empty);
9142 Set_Entity (N, Empty);
9144 -- Now analyze this new node. This reanalysis will complete processing
9145 -- for the node. In particular we will complete the expansion of an
9146 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
9147 -- we will complete any division checks (since we have not changed the
9148 -- setting of the Do_Division_Check flag).
9150 -- We do this reanalysis in STRICT mode to avoid recursion into the
9151 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
9153 declare
9154 SG : constant Overflow_Mode_Type :=
9155 Scope_Suppress.Overflow_Mode_General;
9156 SA : constant Overflow_Mode_Type :=
9157 Scope_Suppress.Overflow_Mode_Assertions;
9159 begin
9160 Scope_Suppress.Overflow_Mode_General := Strict;
9161 Scope_Suppress.Overflow_Mode_Assertions := Strict;
9163 if not Do_Overflow_Check (N) then
9164 Reanalyze (LLIB, Suppress => True);
9165 else
9166 Reanalyze (LLIB);
9167 end if;
9169 Scope_Suppress.Overflow_Mode_General := SG;
9170 Scope_Suppress.Overflow_Mode_Assertions := SA;
9171 end;
9172 end Minimize_Eliminate_Overflows;
9174 -------------------------
9175 -- Overflow_Check_Mode --
9176 -------------------------
9178 function Overflow_Check_Mode return Overflow_Mode_Type is
9179 begin
9180 if In_Assertion_Expr = 0 then
9181 return Scope_Suppress.Overflow_Mode_General;
9182 else
9183 return Scope_Suppress.Overflow_Mode_Assertions;
9184 end if;
9185 end Overflow_Check_Mode;
9187 --------------------------------
9188 -- Overflow_Checks_Suppressed --
9189 --------------------------------
9191 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
9192 begin
9193 if Present (E) and then Checks_May_Be_Suppressed (E) then
9194 return Is_Check_Suppressed (E, Overflow_Check);
9195 else
9196 return Scope_Suppress.Suppress (Overflow_Check);
9197 end if;
9198 end Overflow_Checks_Suppressed;
9200 ---------------------------------
9201 -- Predicate_Checks_Suppressed --
9202 ---------------------------------
9204 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean is
9205 begin
9206 if Present (E) and then Checks_May_Be_Suppressed (E) then
9207 return Is_Check_Suppressed (E, Predicate_Check);
9208 else
9209 return Scope_Suppress.Suppress (Predicate_Check);
9210 end if;
9211 end Predicate_Checks_Suppressed;
9213 -----------------------------
9214 -- Range_Checks_Suppressed --
9215 -----------------------------
9217 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
9218 begin
9219 if Present (E) then
9220 if Kill_Range_Checks (E) then
9221 return True;
9223 elsif Checks_May_Be_Suppressed (E) then
9224 return Is_Check_Suppressed (E, Range_Check);
9225 end if;
9226 end if;
9228 return Scope_Suppress.Suppress (Range_Check);
9229 end Range_Checks_Suppressed;
9231 -----------------------------------------
9232 -- Range_Or_Validity_Checks_Suppressed --
9233 -----------------------------------------
9235 -- Note: the coding would be simpler here if we simply made appropriate
9236 -- calls to Range/Validity_Checks_Suppressed, but that would result in
9237 -- duplicated checks which we prefer to avoid.
9239 function Range_Or_Validity_Checks_Suppressed
9240 (Expr : Node_Id) return Boolean
9242 begin
9243 -- Immediate return if scope checks suppressed for either check
9245 if Scope_Suppress.Suppress (Range_Check)
9247 Scope_Suppress.Suppress (Validity_Check)
9248 then
9249 return True;
9250 end if;
9252 -- If no expression, that's odd, decide that checks are suppressed,
9253 -- since we don't want anyone trying to do checks in this case, which
9254 -- is most likely the result of some other error.
9256 if No (Expr) then
9257 return True;
9258 end if;
9260 -- Expression is present, so perform suppress checks on type
9262 declare
9263 Typ : constant Entity_Id := Etype (Expr);
9264 begin
9265 if Checks_May_Be_Suppressed (Typ)
9266 and then (Is_Check_Suppressed (Typ, Range_Check)
9267 or else
9268 Is_Check_Suppressed (Typ, Validity_Check))
9269 then
9270 return True;
9271 end if;
9272 end;
9274 -- If expression is an entity name, perform checks on this entity
9276 if Is_Entity_Name (Expr) then
9277 declare
9278 Ent : constant Entity_Id := Entity (Expr);
9279 begin
9280 if Checks_May_Be_Suppressed (Ent) then
9281 return Is_Check_Suppressed (Ent, Range_Check)
9282 or else Is_Check_Suppressed (Ent, Validity_Check);
9283 end if;
9284 end;
9285 end if;
9287 -- If we fall through, no checks suppressed
9289 return False;
9290 end Range_Or_Validity_Checks_Suppressed;
9292 -------------------
9293 -- Remove_Checks --
9294 -------------------
9296 procedure Remove_Checks (Expr : Node_Id) is
9297 function Process (N : Node_Id) return Traverse_Result;
9298 -- Process a single node during the traversal
9300 procedure Traverse is new Traverse_Proc (Process);
9301 -- The traversal procedure itself
9303 -------------
9304 -- Process --
9305 -------------
9307 function Process (N : Node_Id) return Traverse_Result is
9308 begin
9309 if Nkind (N) not in N_Subexpr then
9310 return Skip;
9311 end if;
9313 Set_Do_Range_Check (N, False);
9315 case Nkind (N) is
9316 when N_And_Then =>
9317 Traverse (Left_Opnd (N));
9318 return Skip;
9320 when N_Attribute_Reference =>
9321 Set_Do_Overflow_Check (N, False);
9323 when N_Function_Call =>
9324 Set_Do_Tag_Check (N, False);
9326 when N_Op =>
9327 Set_Do_Overflow_Check (N, False);
9329 case Nkind (N) is
9330 when N_Op_Divide =>
9331 Set_Do_Division_Check (N, False);
9333 when N_Op_And =>
9334 Set_Do_Length_Check (N, False);
9336 when N_Op_Mod =>
9337 Set_Do_Division_Check (N, False);
9339 when N_Op_Or =>
9340 Set_Do_Length_Check (N, False);
9342 when N_Op_Rem =>
9343 Set_Do_Division_Check (N, False);
9345 when N_Op_Xor =>
9346 Set_Do_Length_Check (N, False);
9348 when others =>
9349 null;
9350 end case;
9352 when N_Or_Else =>
9353 Traverse (Left_Opnd (N));
9354 return Skip;
9356 when N_Selected_Component =>
9357 Set_Do_Discriminant_Check (N, False);
9359 when N_Type_Conversion =>
9360 Set_Do_Length_Check (N, False);
9361 Set_Do_Tag_Check (N, False);
9362 Set_Do_Overflow_Check (N, False);
9364 when others =>
9365 null;
9366 end case;
9368 return OK;
9369 end Process;
9371 -- Start of processing for Remove_Checks
9373 begin
9374 Traverse (Expr);
9375 end Remove_Checks;
9377 ----------------------------
9378 -- Selected_Length_Checks --
9379 ----------------------------
9381 function Selected_Length_Checks
9382 (Ck_Node : Node_Id;
9383 Target_Typ : Entity_Id;
9384 Source_Typ : Entity_Id;
9385 Warn_Node : Node_Id) return Check_Result
9387 Loc : constant Source_Ptr := Sloc (Ck_Node);
9388 S_Typ : Entity_Id;
9389 T_Typ : Entity_Id;
9390 Expr_Actual : Node_Id;
9391 Exptyp : Entity_Id;
9392 Cond : Node_Id := Empty;
9393 Do_Access : Boolean := False;
9394 Wnode : Node_Id := Warn_Node;
9395 Ret_Result : Check_Result := (Empty, Empty);
9396 Num_Checks : Natural := 0;
9398 procedure Add_Check (N : Node_Id);
9399 -- Adds the action given to Ret_Result if N is non-Empty
9401 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
9402 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
9403 -- Comments required ???
9405 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
9406 -- True for equal literals and for nodes that denote the same constant
9407 -- entity, even if its value is not a static constant. This includes the
9408 -- case of a discriminal reference within an init proc. Removes some
9409 -- obviously superfluous checks.
9411 function Length_E_Cond
9412 (Exptyp : Entity_Id;
9413 Typ : Entity_Id;
9414 Indx : Nat) return Node_Id;
9415 -- Returns expression to compute:
9416 -- Typ'Length /= Exptyp'Length
9418 function Length_N_Cond
9419 (Expr : Node_Id;
9420 Typ : Entity_Id;
9421 Indx : Nat) return Node_Id;
9422 -- Returns expression to compute:
9423 -- Typ'Length /= Expr'Length
9425 ---------------
9426 -- Add_Check --
9427 ---------------
9429 procedure Add_Check (N : Node_Id) is
9430 begin
9431 if Present (N) then
9433 -- For now, ignore attempt to place more than two checks ???
9434 -- This is really worrisome, are we really discarding checks ???
9436 if Num_Checks = 2 then
9437 return;
9438 end if;
9440 pragma Assert (Num_Checks <= 1);
9441 Num_Checks := Num_Checks + 1;
9442 Ret_Result (Num_Checks) := N;
9443 end if;
9444 end Add_Check;
9446 ------------------
9447 -- Get_E_Length --
9448 ------------------
9450 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
9451 SE : constant Entity_Id := Scope (E);
9452 N : Node_Id;
9453 E1 : Entity_Id := E;
9455 begin
9456 if Ekind (Scope (E)) = E_Record_Type
9457 and then Has_Discriminants (Scope (E))
9458 then
9459 N := Build_Discriminal_Subtype_Of_Component (E);
9461 if Present (N) then
9462 Insert_Action (Ck_Node, N);
9463 E1 := Defining_Identifier (N);
9464 end if;
9465 end if;
9467 if Ekind (E1) = E_String_Literal_Subtype then
9468 return
9469 Make_Integer_Literal (Loc,
9470 Intval => String_Literal_Length (E1));
9472 elsif SE /= Standard_Standard
9473 and then Ekind (Scope (SE)) = E_Protected_Type
9474 and then Has_Discriminants (Scope (SE))
9475 and then Has_Completion (Scope (SE))
9476 and then not Inside_Init_Proc
9477 then
9478 -- If the type whose length is needed is a private component
9479 -- constrained by a discriminant, we must expand the 'Length
9480 -- attribute into an explicit computation, using the discriminal
9481 -- of the current protected operation. This is because the actual
9482 -- type of the prival is constructed after the protected opera-
9483 -- tion has been fully expanded.
9485 declare
9486 Indx_Type : Node_Id;
9487 Lo : Node_Id;
9488 Hi : Node_Id;
9489 Do_Expand : Boolean := False;
9491 begin
9492 Indx_Type := First_Index (E);
9494 for J in 1 .. Indx - 1 loop
9495 Next_Index (Indx_Type);
9496 end loop;
9498 Get_Index_Bounds (Indx_Type, Lo, Hi);
9500 if Nkind (Lo) = N_Identifier
9501 and then Ekind (Entity (Lo)) = E_In_Parameter
9502 then
9503 Lo := Get_Discriminal (E, Lo);
9504 Do_Expand := True;
9505 end if;
9507 if Nkind (Hi) = N_Identifier
9508 and then Ekind (Entity (Hi)) = E_In_Parameter
9509 then
9510 Hi := Get_Discriminal (E, Hi);
9511 Do_Expand := True;
9512 end if;
9514 if Do_Expand then
9515 if not Is_Entity_Name (Lo) then
9516 Lo := Duplicate_Subexpr_No_Checks (Lo);
9517 end if;
9519 if not Is_Entity_Name (Hi) then
9520 Lo := Duplicate_Subexpr_No_Checks (Hi);
9521 end if;
9523 N :=
9524 Make_Op_Add (Loc,
9525 Left_Opnd =>
9526 Make_Op_Subtract (Loc,
9527 Left_Opnd => Hi,
9528 Right_Opnd => Lo),
9530 Right_Opnd => Make_Integer_Literal (Loc, 1));
9531 return N;
9533 else
9534 N :=
9535 Make_Attribute_Reference (Loc,
9536 Attribute_Name => Name_Length,
9537 Prefix =>
9538 New_Occurrence_Of (E1, Loc));
9540 if Indx > 1 then
9541 Set_Expressions (N, New_List (
9542 Make_Integer_Literal (Loc, Indx)));
9543 end if;
9545 return N;
9546 end if;
9547 end;
9549 else
9550 N :=
9551 Make_Attribute_Reference (Loc,
9552 Attribute_Name => Name_Length,
9553 Prefix =>
9554 New_Occurrence_Of (E1, Loc));
9556 if Indx > 1 then
9557 Set_Expressions (N, New_List (
9558 Make_Integer_Literal (Loc, Indx)));
9559 end if;
9561 return N;
9562 end if;
9563 end Get_E_Length;
9565 ------------------
9566 -- Get_N_Length --
9567 ------------------
9569 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
9570 begin
9571 return
9572 Make_Attribute_Reference (Loc,
9573 Attribute_Name => Name_Length,
9574 Prefix =>
9575 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
9576 Expressions => New_List (
9577 Make_Integer_Literal (Loc, Indx)));
9578 end Get_N_Length;
9580 -------------------
9581 -- Length_E_Cond --
9582 -------------------
9584 function Length_E_Cond
9585 (Exptyp : Entity_Id;
9586 Typ : Entity_Id;
9587 Indx : Nat) return Node_Id
9589 begin
9590 return
9591 Make_Op_Ne (Loc,
9592 Left_Opnd => Get_E_Length (Typ, Indx),
9593 Right_Opnd => Get_E_Length (Exptyp, Indx));
9594 end Length_E_Cond;
9596 -------------------
9597 -- Length_N_Cond --
9598 -------------------
9600 function Length_N_Cond
9601 (Expr : Node_Id;
9602 Typ : Entity_Id;
9603 Indx : Nat) return Node_Id
9605 begin
9606 return
9607 Make_Op_Ne (Loc,
9608 Left_Opnd => Get_E_Length (Typ, Indx),
9609 Right_Opnd => Get_N_Length (Expr, Indx));
9610 end Length_N_Cond;
9612 -----------------
9613 -- Same_Bounds --
9614 -----------------
9616 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
9617 begin
9618 return
9619 (Nkind (L) = N_Integer_Literal
9620 and then Nkind (R) = N_Integer_Literal
9621 and then Intval (L) = Intval (R))
9623 or else
9624 (Is_Entity_Name (L)
9625 and then Ekind (Entity (L)) = E_Constant
9626 and then ((Is_Entity_Name (R)
9627 and then Entity (L) = Entity (R))
9628 or else
9629 (Nkind (R) = N_Type_Conversion
9630 and then Is_Entity_Name (Expression (R))
9631 and then Entity (L) = Entity (Expression (R)))))
9633 or else
9634 (Is_Entity_Name (R)
9635 and then Ekind (Entity (R)) = E_Constant
9636 and then Nkind (L) = N_Type_Conversion
9637 and then Is_Entity_Name (Expression (L))
9638 and then Entity (R) = Entity (Expression (L)))
9640 or else
9641 (Is_Entity_Name (L)
9642 and then Is_Entity_Name (R)
9643 and then Entity (L) = Entity (R)
9644 and then Ekind (Entity (L)) = E_In_Parameter
9645 and then Inside_Init_Proc);
9646 end Same_Bounds;
9648 -- Start of processing for Selected_Length_Checks
9650 begin
9651 -- Checks will be applied only when generating code
9653 if not Expander_Active then
9654 return Ret_Result;
9655 end if;
9657 if Target_Typ = Any_Type
9658 or else Target_Typ = Any_Composite
9659 or else Raises_Constraint_Error (Ck_Node)
9660 then
9661 return Ret_Result;
9662 end if;
9664 if No (Wnode) then
9665 Wnode := Ck_Node;
9666 end if;
9668 T_Typ := Target_Typ;
9670 if No (Source_Typ) then
9671 S_Typ := Etype (Ck_Node);
9672 else
9673 S_Typ := Source_Typ;
9674 end if;
9676 if S_Typ = Any_Type or else S_Typ = Any_Composite then
9677 return Ret_Result;
9678 end if;
9680 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
9681 S_Typ := Designated_Type (S_Typ);
9682 T_Typ := Designated_Type (T_Typ);
9683 Do_Access := True;
9685 -- A simple optimization for the null case
9687 if Known_Null (Ck_Node) then
9688 return Ret_Result;
9689 end if;
9690 end if;
9692 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
9693 if Is_Constrained (T_Typ) then
9695 -- The checking code to be generated will freeze the corresponding
9696 -- array type. However, we must freeze the type now, so that the
9697 -- freeze node does not appear within the generated if expression,
9698 -- but ahead of it.
9700 Freeze_Before (Ck_Node, T_Typ);
9702 Expr_Actual := Get_Referenced_Object (Ck_Node);
9703 Exptyp := Get_Actual_Subtype (Ck_Node);
9705 if Is_Access_Type (Exptyp) then
9706 Exptyp := Designated_Type (Exptyp);
9707 end if;
9709 -- String_Literal case. This needs to be handled specially be-
9710 -- cause no index types are available for string literals. The
9711 -- condition is simply:
9713 -- T_Typ'Length = string-literal-length
9715 if Nkind (Expr_Actual) = N_String_Literal
9716 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
9717 then
9718 Cond :=
9719 Make_Op_Ne (Loc,
9720 Left_Opnd => Get_E_Length (T_Typ, 1),
9721 Right_Opnd =>
9722 Make_Integer_Literal (Loc,
9723 Intval =>
9724 String_Literal_Length (Etype (Expr_Actual))));
9726 -- General array case. Here we have a usable actual subtype for
9727 -- the expression, and the condition is built from the two types
9728 -- (Do_Length):
9730 -- T_Typ'Length /= Exptyp'Length or else
9731 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
9732 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
9733 -- ...
9735 elsif Is_Constrained (Exptyp) then
9736 declare
9737 Ndims : constant Nat := Number_Dimensions (T_Typ);
9739 L_Index : Node_Id;
9740 R_Index : Node_Id;
9741 L_Low : Node_Id;
9742 L_High : Node_Id;
9743 R_Low : Node_Id;
9744 R_High : Node_Id;
9745 L_Length : Uint;
9746 R_Length : Uint;
9747 Ref_Node : Node_Id;
9749 begin
9750 -- At the library level, we need to ensure that the type of
9751 -- the object is elaborated before the check itself is
9752 -- emitted. This is only done if the object is in the
9753 -- current compilation unit, otherwise the type is frozen
9754 -- and elaborated in its unit.
9756 if Is_Itype (Exptyp)
9757 and then
9758 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
9759 and then
9760 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
9761 and then In_Open_Scopes (Scope (Exptyp))
9762 then
9763 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
9764 Set_Itype (Ref_Node, Exptyp);
9765 Insert_Action (Ck_Node, Ref_Node);
9766 end if;
9768 L_Index := First_Index (T_Typ);
9769 R_Index := First_Index (Exptyp);
9771 for Indx in 1 .. Ndims loop
9772 if not (Nkind (L_Index) = N_Raise_Constraint_Error
9773 or else
9774 Nkind (R_Index) = N_Raise_Constraint_Error)
9775 then
9776 Get_Index_Bounds (L_Index, L_Low, L_High);
9777 Get_Index_Bounds (R_Index, R_Low, R_High);
9779 -- Deal with compile time length check. Note that we
9780 -- skip this in the access case, because the access
9781 -- value may be null, so we cannot know statically.
9783 if not Do_Access
9784 and then Compile_Time_Known_Value (L_Low)
9785 and then Compile_Time_Known_Value (L_High)
9786 and then Compile_Time_Known_Value (R_Low)
9787 and then Compile_Time_Known_Value (R_High)
9788 then
9789 if Expr_Value (L_High) >= Expr_Value (L_Low) then
9790 L_Length := Expr_Value (L_High) -
9791 Expr_Value (L_Low) + 1;
9792 else
9793 L_Length := UI_From_Int (0);
9794 end if;
9796 if Expr_Value (R_High) >= Expr_Value (R_Low) then
9797 R_Length := Expr_Value (R_High) -
9798 Expr_Value (R_Low) + 1;
9799 else
9800 R_Length := UI_From_Int (0);
9801 end if;
9803 if L_Length > R_Length then
9804 Add_Check
9805 (Compile_Time_Constraint_Error
9806 (Wnode, "too few elements for}??", T_Typ));
9808 elsif L_Length < R_Length then
9809 Add_Check
9810 (Compile_Time_Constraint_Error
9811 (Wnode, "too many elements for}??", T_Typ));
9812 end if;
9814 -- The comparison for an individual index subtype
9815 -- is omitted if the corresponding index subtypes
9816 -- statically match, since the result is known to
9817 -- be true. Note that this test is worth while even
9818 -- though we do static evaluation, because non-static
9819 -- subtypes can statically match.
9821 elsif not
9822 Subtypes_Statically_Match
9823 (Etype (L_Index), Etype (R_Index))
9825 and then not
9826 (Same_Bounds (L_Low, R_Low)
9827 and then Same_Bounds (L_High, R_High))
9828 then
9829 Evolve_Or_Else
9830 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
9831 end if;
9833 Next (L_Index);
9834 Next (R_Index);
9835 end if;
9836 end loop;
9837 end;
9839 -- Handle cases where we do not get a usable actual subtype that
9840 -- is constrained. This happens for example in the function call
9841 -- and explicit dereference cases. In these cases, we have to get
9842 -- the length or range from the expression itself, making sure we
9843 -- do not evaluate it more than once.
9845 -- Here Ck_Node is the original expression, or more properly the
9846 -- result of applying Duplicate_Expr to the original tree, forcing
9847 -- the result to be a name.
9849 else
9850 declare
9851 Ndims : constant Nat := Number_Dimensions (T_Typ);
9853 begin
9854 -- Build the condition for the explicit dereference case
9856 for Indx in 1 .. Ndims loop
9857 Evolve_Or_Else
9858 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
9859 end loop;
9860 end;
9861 end if;
9862 end if;
9863 end if;
9865 -- Construct the test and insert into the tree
9867 if Present (Cond) then
9868 if Do_Access then
9869 Cond := Guard_Access (Cond, Loc, Ck_Node);
9870 end if;
9872 Add_Check
9873 (Make_Raise_Constraint_Error (Loc,
9874 Condition => Cond,
9875 Reason => CE_Length_Check_Failed));
9876 end if;
9878 return Ret_Result;
9879 end Selected_Length_Checks;
9881 ---------------------------
9882 -- Selected_Range_Checks --
9883 ---------------------------
9885 function Selected_Range_Checks
9886 (Ck_Node : Node_Id;
9887 Target_Typ : Entity_Id;
9888 Source_Typ : Entity_Id;
9889 Warn_Node : Node_Id) return Check_Result
9891 Loc : constant Source_Ptr := Sloc (Ck_Node);
9892 S_Typ : Entity_Id;
9893 T_Typ : Entity_Id;
9894 Expr_Actual : Node_Id;
9895 Exptyp : Entity_Id;
9896 Cond : Node_Id := Empty;
9897 Do_Access : Boolean := False;
9898 Wnode : Node_Id := Warn_Node;
9899 Ret_Result : Check_Result := (Empty, Empty);
9900 Num_Checks : Natural := 0;
9902 procedure Add_Check (N : Node_Id);
9903 -- Adds the action given to Ret_Result if N is non-Empty
9905 function Discrete_Range_Cond
9906 (Expr : Node_Id;
9907 Typ : Entity_Id) return Node_Id;
9908 -- Returns expression to compute:
9909 -- Low_Bound (Expr) < Typ'First
9910 -- or else
9911 -- High_Bound (Expr) > Typ'Last
9913 function Discrete_Expr_Cond
9914 (Expr : Node_Id;
9915 Typ : Entity_Id) return Node_Id;
9916 -- Returns expression to compute:
9917 -- Expr < Typ'First
9918 -- or else
9919 -- Expr > Typ'Last
9921 function Get_E_First_Or_Last
9922 (Loc : Source_Ptr;
9923 E : Entity_Id;
9924 Indx : Nat;
9925 Nam : Name_Id) return Node_Id;
9926 -- Returns an attribute reference
9927 -- E'First or E'Last
9928 -- with a source location of Loc.
9930 -- Nam is Name_First or Name_Last, according to which attribute is
9931 -- desired. If Indx is non-zero, it is passed as a literal in the
9932 -- Expressions of the attribute reference (identifying the desired
9933 -- array dimension).
9935 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
9936 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
9937 -- Returns expression to compute:
9938 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
9940 function Range_E_Cond
9941 (Exptyp : Entity_Id;
9942 Typ : Entity_Id;
9943 Indx : Nat)
9944 return Node_Id;
9945 -- Returns expression to compute:
9946 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
9948 function Range_Equal_E_Cond
9949 (Exptyp : Entity_Id;
9950 Typ : Entity_Id;
9951 Indx : Nat) return Node_Id;
9952 -- Returns expression to compute:
9953 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
9955 function Range_N_Cond
9956 (Expr : Node_Id;
9957 Typ : Entity_Id;
9958 Indx : Nat) return Node_Id;
9959 -- Return expression to compute:
9960 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
9962 ---------------
9963 -- Add_Check --
9964 ---------------
9966 procedure Add_Check (N : Node_Id) is
9967 begin
9968 if Present (N) then
9970 -- For now, ignore attempt to place more than 2 checks ???
9972 if Num_Checks = 2 then
9973 return;
9974 end if;
9976 pragma Assert (Num_Checks <= 1);
9977 Num_Checks := Num_Checks + 1;
9978 Ret_Result (Num_Checks) := N;
9979 end if;
9980 end Add_Check;
9982 -------------------------
9983 -- Discrete_Expr_Cond --
9984 -------------------------
9986 function Discrete_Expr_Cond
9987 (Expr : Node_Id;
9988 Typ : Entity_Id) return Node_Id
9990 begin
9991 return
9992 Make_Or_Else (Loc,
9993 Left_Opnd =>
9994 Make_Op_Lt (Loc,
9995 Left_Opnd =>
9996 Convert_To (Base_Type (Typ),
9997 Duplicate_Subexpr_No_Checks (Expr)),
9998 Right_Opnd =>
9999 Convert_To (Base_Type (Typ),
10000 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
10002 Right_Opnd =>
10003 Make_Op_Gt (Loc,
10004 Left_Opnd =>
10005 Convert_To (Base_Type (Typ),
10006 Duplicate_Subexpr_No_Checks (Expr)),
10007 Right_Opnd =>
10008 Convert_To
10009 (Base_Type (Typ),
10010 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
10011 end Discrete_Expr_Cond;
10013 -------------------------
10014 -- Discrete_Range_Cond --
10015 -------------------------
10017 function Discrete_Range_Cond
10018 (Expr : Node_Id;
10019 Typ : Entity_Id) return Node_Id
10021 LB : Node_Id := Low_Bound (Expr);
10022 HB : Node_Id := High_Bound (Expr);
10024 Left_Opnd : Node_Id;
10025 Right_Opnd : Node_Id;
10027 begin
10028 if Nkind (LB) = N_Identifier
10029 and then Ekind (Entity (LB)) = E_Discriminant
10030 then
10031 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10032 end if;
10034 Left_Opnd :=
10035 Make_Op_Lt (Loc,
10036 Left_Opnd =>
10037 Convert_To
10038 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
10040 Right_Opnd =>
10041 Convert_To
10042 (Base_Type (Typ),
10043 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
10045 if Nkind (HB) = N_Identifier
10046 and then Ekind (Entity (HB)) = E_Discriminant
10047 then
10048 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10049 end if;
10051 Right_Opnd :=
10052 Make_Op_Gt (Loc,
10053 Left_Opnd =>
10054 Convert_To
10055 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
10057 Right_Opnd =>
10058 Convert_To
10059 (Base_Type (Typ),
10060 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
10062 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
10063 end Discrete_Range_Cond;
10065 -------------------------
10066 -- Get_E_First_Or_Last --
10067 -------------------------
10069 function Get_E_First_Or_Last
10070 (Loc : Source_Ptr;
10071 E : Entity_Id;
10072 Indx : Nat;
10073 Nam : Name_Id) return Node_Id
10075 Exprs : List_Id;
10076 begin
10077 if Indx > 0 then
10078 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
10079 else
10080 Exprs := No_List;
10081 end if;
10083 return Make_Attribute_Reference (Loc,
10084 Prefix => New_Occurrence_Of (E, Loc),
10085 Attribute_Name => Nam,
10086 Expressions => Exprs);
10087 end Get_E_First_Or_Last;
10089 -----------------
10090 -- Get_N_First --
10091 -----------------
10093 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
10094 begin
10095 return
10096 Make_Attribute_Reference (Loc,
10097 Attribute_Name => Name_First,
10098 Prefix =>
10099 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10100 Expressions => New_List (
10101 Make_Integer_Literal (Loc, Indx)));
10102 end Get_N_First;
10104 ----------------
10105 -- Get_N_Last --
10106 ----------------
10108 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
10109 begin
10110 return
10111 Make_Attribute_Reference (Loc,
10112 Attribute_Name => Name_Last,
10113 Prefix =>
10114 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10115 Expressions => New_List (
10116 Make_Integer_Literal (Loc, Indx)));
10117 end Get_N_Last;
10119 ------------------
10120 -- Range_E_Cond --
10121 ------------------
10123 function Range_E_Cond
10124 (Exptyp : Entity_Id;
10125 Typ : Entity_Id;
10126 Indx : Nat) return Node_Id
10128 begin
10129 return
10130 Make_Or_Else (Loc,
10131 Left_Opnd =>
10132 Make_Op_Lt (Loc,
10133 Left_Opnd =>
10134 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10135 Right_Opnd =>
10136 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10138 Right_Opnd =>
10139 Make_Op_Gt (Loc,
10140 Left_Opnd =>
10141 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10142 Right_Opnd =>
10143 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10144 end Range_E_Cond;
10146 ------------------------
10147 -- Range_Equal_E_Cond --
10148 ------------------------
10150 function Range_Equal_E_Cond
10151 (Exptyp : Entity_Id;
10152 Typ : Entity_Id;
10153 Indx : Nat) return Node_Id
10155 begin
10156 return
10157 Make_Or_Else (Loc,
10158 Left_Opnd =>
10159 Make_Op_Ne (Loc,
10160 Left_Opnd =>
10161 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10162 Right_Opnd =>
10163 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10165 Right_Opnd =>
10166 Make_Op_Ne (Loc,
10167 Left_Opnd =>
10168 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10169 Right_Opnd =>
10170 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10171 end Range_Equal_E_Cond;
10173 ------------------
10174 -- Range_N_Cond --
10175 ------------------
10177 function Range_N_Cond
10178 (Expr : Node_Id;
10179 Typ : Entity_Id;
10180 Indx : Nat) return Node_Id
10182 begin
10183 return
10184 Make_Or_Else (Loc,
10185 Left_Opnd =>
10186 Make_Op_Lt (Loc,
10187 Left_Opnd =>
10188 Get_N_First (Expr, Indx),
10189 Right_Opnd =>
10190 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10192 Right_Opnd =>
10193 Make_Op_Gt (Loc,
10194 Left_Opnd =>
10195 Get_N_Last (Expr, Indx),
10196 Right_Opnd =>
10197 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10198 end Range_N_Cond;
10200 -- Start of processing for Selected_Range_Checks
10202 begin
10203 -- Checks will be applied only when generating code. In GNATprove mode,
10204 -- we do not apply the checks, but we still call Selected_Range_Checks
10205 -- to possibly issue errors on SPARK code when a run-time error can be
10206 -- detected at compile time.
10208 if not Expander_Active and not GNATprove_Mode then
10209 return Ret_Result;
10210 end if;
10212 if Target_Typ = Any_Type
10213 or else Target_Typ = Any_Composite
10214 or else Raises_Constraint_Error (Ck_Node)
10215 then
10216 return Ret_Result;
10217 end if;
10219 if No (Wnode) then
10220 Wnode := Ck_Node;
10221 end if;
10223 T_Typ := Target_Typ;
10225 if No (Source_Typ) then
10226 S_Typ := Etype (Ck_Node);
10227 else
10228 S_Typ := Source_Typ;
10229 end if;
10231 if S_Typ = Any_Type or else S_Typ = Any_Composite then
10232 return Ret_Result;
10233 end if;
10235 -- The order of evaluating T_Typ before S_Typ seems to be critical
10236 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
10237 -- in, and since Node can be an N_Range node, it might be invalid.
10238 -- Should there be an assert check somewhere for taking the Etype of
10239 -- an N_Range node ???
10241 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
10242 S_Typ := Designated_Type (S_Typ);
10243 T_Typ := Designated_Type (T_Typ);
10244 Do_Access := True;
10246 -- A simple optimization for the null case
10248 if Known_Null (Ck_Node) then
10249 return Ret_Result;
10250 end if;
10251 end if;
10253 -- For an N_Range Node, check for a null range and then if not
10254 -- null generate a range check action.
10256 if Nkind (Ck_Node) = N_Range then
10258 -- There's no point in checking a range against itself
10260 if Ck_Node = Scalar_Range (T_Typ) then
10261 return Ret_Result;
10262 end if;
10264 declare
10265 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
10266 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
10267 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
10268 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
10270 LB : Node_Id := Low_Bound (Ck_Node);
10271 HB : Node_Id := High_Bound (Ck_Node);
10272 Known_LB : Boolean := False;
10273 Known_HB : Boolean := False;
10275 Null_Range : Boolean;
10276 Out_Of_Range_L : Boolean;
10277 Out_Of_Range_H : Boolean;
10279 begin
10280 -- Compute what is known at compile time
10282 if Known_T_LB and Known_T_HB then
10283 if Compile_Time_Known_Value (LB) then
10284 Known_LB := True;
10286 -- There's no point in checking that a bound is within its
10287 -- own range so pretend that it is known in this case. First
10288 -- deal with low bound.
10290 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
10291 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
10292 then
10293 LB := T_LB;
10294 Known_LB := True;
10295 end if;
10297 -- Likewise for the high bound
10299 if Compile_Time_Known_Value (HB) then
10300 Known_HB := True;
10302 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
10303 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
10304 then
10305 HB := T_HB;
10306 Known_HB := True;
10307 end if;
10308 end if;
10310 -- Check for case where everything is static and we can do the
10311 -- check at compile time. This is skipped if we have an access
10312 -- type, since the access value may be null.
10314 -- ??? This code can be improved since you only need to know that
10315 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
10316 -- compile time to emit pertinent messages.
10318 if Known_T_LB and Known_T_HB and Known_LB and Known_HB
10319 and not Do_Access
10320 then
10321 -- Floating-point case
10323 if Is_Floating_Point_Type (S_Typ) then
10324 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
10325 Out_Of_Range_L :=
10326 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
10327 or else
10328 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
10330 Out_Of_Range_H :=
10331 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
10332 or else
10333 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
10335 -- Fixed or discrete type case
10337 else
10338 Null_Range := Expr_Value (HB) < Expr_Value (LB);
10339 Out_Of_Range_L :=
10340 (Expr_Value (LB) < Expr_Value (T_LB))
10341 or else
10342 (Expr_Value (LB) > Expr_Value (T_HB));
10344 Out_Of_Range_H :=
10345 (Expr_Value (HB) > Expr_Value (T_HB))
10346 or else
10347 (Expr_Value (HB) < Expr_Value (T_LB));
10348 end if;
10350 if not Null_Range then
10351 if Out_Of_Range_L then
10352 if No (Warn_Node) then
10353 Add_Check
10354 (Compile_Time_Constraint_Error
10355 (Low_Bound (Ck_Node),
10356 "static value out of range of}??", T_Typ));
10358 else
10359 Add_Check
10360 (Compile_Time_Constraint_Error
10361 (Wnode,
10362 "static range out of bounds of}??", T_Typ));
10363 end if;
10364 end if;
10366 if Out_Of_Range_H then
10367 if No (Warn_Node) then
10368 Add_Check
10369 (Compile_Time_Constraint_Error
10370 (High_Bound (Ck_Node),
10371 "static value out of range of}??", T_Typ));
10373 else
10374 Add_Check
10375 (Compile_Time_Constraint_Error
10376 (Wnode,
10377 "static range out of bounds of}??", T_Typ));
10378 end if;
10379 end if;
10380 end if;
10382 else
10383 declare
10384 LB : Node_Id := Low_Bound (Ck_Node);
10385 HB : Node_Id := High_Bound (Ck_Node);
10387 begin
10388 -- If either bound is a discriminant and we are within the
10389 -- record declaration, it is a use of the discriminant in a
10390 -- constraint of a component, and nothing can be checked
10391 -- here. The check will be emitted within the init proc.
10392 -- Before then, the discriminal has no real meaning.
10393 -- Similarly, if the entity is a discriminal, there is no
10394 -- check to perform yet.
10396 -- The same holds within a discriminated synchronized type,
10397 -- where the discriminant may constrain a component or an
10398 -- entry family.
10400 if Nkind (LB) = N_Identifier
10401 and then Denotes_Discriminant (LB, True)
10402 then
10403 if Current_Scope = Scope (Entity (LB))
10404 or else Is_Concurrent_Type (Current_Scope)
10405 or else Ekind (Entity (LB)) /= E_Discriminant
10406 then
10407 return Ret_Result;
10408 else
10409 LB :=
10410 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10411 end if;
10412 end if;
10414 if Nkind (HB) = N_Identifier
10415 and then Denotes_Discriminant (HB, True)
10416 then
10417 if Current_Scope = Scope (Entity (HB))
10418 or else Is_Concurrent_Type (Current_Scope)
10419 or else Ekind (Entity (HB)) /= E_Discriminant
10420 then
10421 return Ret_Result;
10422 else
10423 HB :=
10424 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10425 end if;
10426 end if;
10428 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
10429 Set_Paren_Count (Cond, 1);
10431 Cond :=
10432 Make_And_Then (Loc,
10433 Left_Opnd =>
10434 Make_Op_Ge (Loc,
10435 Left_Opnd =>
10436 Convert_To (Base_Type (Etype (HB)),
10437 Duplicate_Subexpr_No_Checks (HB)),
10438 Right_Opnd =>
10439 Convert_To (Base_Type (Etype (LB)),
10440 Duplicate_Subexpr_No_Checks (LB))),
10441 Right_Opnd => Cond);
10442 end;
10443 end if;
10444 end;
10446 elsif Is_Scalar_Type (S_Typ) then
10448 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
10449 -- except the above simply sets a flag in the node and lets
10450 -- gigi generate the check base on the Etype of the expression.
10451 -- Sometimes, however we want to do a dynamic check against an
10452 -- arbitrary target type, so we do that here.
10454 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
10455 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10457 -- For literals, we can tell if the constraint error will be
10458 -- raised at compile time, so we never need a dynamic check, but
10459 -- if the exception will be raised, then post the usual warning,
10460 -- and replace the literal with a raise constraint error
10461 -- expression. As usual, skip this for access types
10463 elsif Compile_Time_Known_Value (Ck_Node) and then not Do_Access then
10464 declare
10465 LB : constant Node_Id := Type_Low_Bound (T_Typ);
10466 UB : constant Node_Id := Type_High_Bound (T_Typ);
10468 Out_Of_Range : Boolean;
10469 Static_Bounds : constant Boolean :=
10470 Compile_Time_Known_Value (LB)
10471 and Compile_Time_Known_Value (UB);
10473 begin
10474 -- Following range tests should use Sem_Eval routine ???
10476 if Static_Bounds then
10477 if Is_Floating_Point_Type (S_Typ) then
10478 Out_Of_Range :=
10479 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
10480 or else
10481 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
10483 -- Fixed or discrete type
10485 else
10486 Out_Of_Range :=
10487 Expr_Value (Ck_Node) < Expr_Value (LB)
10488 or else
10489 Expr_Value (Ck_Node) > Expr_Value (UB);
10490 end if;
10492 -- Bounds of the type are static and the literal is out of
10493 -- range so output a warning message.
10495 if Out_Of_Range then
10496 if No (Warn_Node) then
10497 Add_Check
10498 (Compile_Time_Constraint_Error
10499 (Ck_Node,
10500 "static value out of range of}??", T_Typ));
10502 else
10503 Add_Check
10504 (Compile_Time_Constraint_Error
10505 (Wnode,
10506 "static value out of range of}??", T_Typ));
10507 end if;
10508 end if;
10510 else
10511 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10512 end if;
10513 end;
10515 -- Here for the case of a non-static expression, we need a runtime
10516 -- check unless the source type range is guaranteed to be in the
10517 -- range of the target type.
10519 else
10520 if not In_Subrange_Of (S_Typ, T_Typ) then
10521 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10522 end if;
10523 end if;
10524 end if;
10526 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
10527 if Is_Constrained (T_Typ) then
10529 Expr_Actual := Get_Referenced_Object (Ck_Node);
10530 Exptyp := Get_Actual_Subtype (Expr_Actual);
10532 if Is_Access_Type (Exptyp) then
10533 Exptyp := Designated_Type (Exptyp);
10534 end if;
10536 -- String_Literal case. This needs to be handled specially be-
10537 -- cause no index types are available for string literals. The
10538 -- condition is simply:
10540 -- T_Typ'Length = string-literal-length
10542 if Nkind (Expr_Actual) = N_String_Literal then
10543 null;
10545 -- General array case. Here we have a usable actual subtype for
10546 -- the expression, and the condition is built from the two types
10548 -- T_Typ'First < Exptyp'First or else
10549 -- T_Typ'Last > Exptyp'Last or else
10550 -- T_Typ'First(1) < Exptyp'First(1) or else
10551 -- T_Typ'Last(1) > Exptyp'Last(1) or else
10552 -- ...
10554 elsif Is_Constrained (Exptyp) then
10555 declare
10556 Ndims : constant Nat := Number_Dimensions (T_Typ);
10558 L_Index : Node_Id;
10559 R_Index : Node_Id;
10561 begin
10562 L_Index := First_Index (T_Typ);
10563 R_Index := First_Index (Exptyp);
10565 for Indx in 1 .. Ndims loop
10566 if not (Nkind (L_Index) = N_Raise_Constraint_Error
10567 or else
10568 Nkind (R_Index) = N_Raise_Constraint_Error)
10569 then
10570 -- Deal with compile time length check. Note that we
10571 -- skip this in the access case, because the access
10572 -- value may be null, so we cannot know statically.
10574 if not
10575 Subtypes_Statically_Match
10576 (Etype (L_Index), Etype (R_Index))
10577 then
10578 -- If the target type is constrained then we
10579 -- have to check for exact equality of bounds
10580 -- (required for qualified expressions).
10582 if Is_Constrained (T_Typ) then
10583 Evolve_Or_Else
10584 (Cond,
10585 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
10586 else
10587 Evolve_Or_Else
10588 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
10589 end if;
10590 end if;
10592 Next (L_Index);
10593 Next (R_Index);
10594 end if;
10595 end loop;
10596 end;
10598 -- Handle cases where we do not get a usable actual subtype that
10599 -- is constrained. This happens for example in the function call
10600 -- and explicit dereference cases. In these cases, we have to get
10601 -- the length or range from the expression itself, making sure we
10602 -- do not evaluate it more than once.
10604 -- Here Ck_Node is the original expression, or more properly the
10605 -- result of applying Duplicate_Expr to the original tree,
10606 -- forcing the result to be a name.
10608 else
10609 declare
10610 Ndims : constant Nat := Number_Dimensions (T_Typ);
10612 begin
10613 -- Build the condition for the explicit dereference case
10615 for Indx in 1 .. Ndims loop
10616 Evolve_Or_Else
10617 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
10618 end loop;
10619 end;
10620 end if;
10622 else
10623 -- For a conversion to an unconstrained array type, generate an
10624 -- Action to check that the bounds of the source value are within
10625 -- the constraints imposed by the target type (RM 4.6(38)). No
10626 -- check is needed for a conversion to an access to unconstrained
10627 -- array type, as 4.6(24.15/2) requires the designated subtypes
10628 -- of the two access types to statically match.
10630 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
10631 and then not Do_Access
10632 then
10633 declare
10634 Opnd_Index : Node_Id;
10635 Targ_Index : Node_Id;
10636 Opnd_Range : Node_Id;
10638 begin
10639 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
10640 Targ_Index := First_Index (T_Typ);
10641 while Present (Opnd_Index) loop
10643 -- If the index is a range, use its bounds. If it is an
10644 -- entity (as will be the case if it is a named subtype
10645 -- or an itype created for a slice) retrieve its range.
10647 if Is_Entity_Name (Opnd_Index)
10648 and then Is_Type (Entity (Opnd_Index))
10649 then
10650 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
10651 else
10652 Opnd_Range := Opnd_Index;
10653 end if;
10655 if Nkind (Opnd_Range) = N_Range then
10656 if Is_In_Range
10657 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10658 Assume_Valid => True)
10659 and then
10660 Is_In_Range
10661 (High_Bound (Opnd_Range), Etype (Targ_Index),
10662 Assume_Valid => True)
10663 then
10664 null;
10666 -- If null range, no check needed
10668 elsif
10669 Compile_Time_Known_Value (High_Bound (Opnd_Range))
10670 and then
10671 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
10672 and then
10673 Expr_Value (High_Bound (Opnd_Range)) <
10674 Expr_Value (Low_Bound (Opnd_Range))
10675 then
10676 null;
10678 elsif Is_Out_Of_Range
10679 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10680 Assume_Valid => True)
10681 or else
10682 Is_Out_Of_Range
10683 (High_Bound (Opnd_Range), Etype (Targ_Index),
10684 Assume_Valid => True)
10685 then
10686 Add_Check
10687 (Compile_Time_Constraint_Error
10688 (Wnode, "value out of range of}??", T_Typ));
10690 else
10691 Evolve_Or_Else
10692 (Cond,
10693 Discrete_Range_Cond
10694 (Opnd_Range, Etype (Targ_Index)));
10695 end if;
10696 end if;
10698 Next_Index (Opnd_Index);
10699 Next_Index (Targ_Index);
10700 end loop;
10701 end;
10702 end if;
10703 end if;
10704 end if;
10706 -- Construct the test and insert into the tree
10708 if Present (Cond) then
10709 if Do_Access then
10710 Cond := Guard_Access (Cond, Loc, Ck_Node);
10711 end if;
10713 Add_Check
10714 (Make_Raise_Constraint_Error (Loc,
10715 Condition => Cond,
10716 Reason => CE_Range_Check_Failed));
10717 end if;
10719 return Ret_Result;
10720 end Selected_Range_Checks;
10722 -------------------------------
10723 -- Storage_Checks_Suppressed --
10724 -------------------------------
10726 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
10727 begin
10728 if Present (E) and then Checks_May_Be_Suppressed (E) then
10729 return Is_Check_Suppressed (E, Storage_Check);
10730 else
10731 return Scope_Suppress.Suppress (Storage_Check);
10732 end if;
10733 end Storage_Checks_Suppressed;
10735 ---------------------------
10736 -- Tag_Checks_Suppressed --
10737 ---------------------------
10739 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
10740 begin
10741 if Present (E)
10742 and then Checks_May_Be_Suppressed (E)
10743 then
10744 return Is_Check_Suppressed (E, Tag_Check);
10745 else
10746 return Scope_Suppress.Suppress (Tag_Check);
10747 end if;
10748 end Tag_Checks_Suppressed;
10750 ---------------------------------------
10751 -- Validate_Alignment_Check_Warnings --
10752 ---------------------------------------
10754 procedure Validate_Alignment_Check_Warnings is
10755 begin
10756 for J in Alignment_Warnings.First .. Alignment_Warnings.Last loop
10757 declare
10758 AWR : Alignment_Warnings_Record
10759 renames Alignment_Warnings.Table (J);
10760 begin
10761 if Known_Alignment (AWR.E)
10762 and then AWR.A mod Alignment (AWR.E) = 0
10763 then
10764 Delete_Warning_And_Continuations (AWR.W);
10765 end if;
10766 end;
10767 end loop;
10768 end Validate_Alignment_Check_Warnings;
10770 --------------------------
10771 -- Validity_Check_Range --
10772 --------------------------
10774 procedure Validity_Check_Range
10775 (N : Node_Id;
10776 Related_Id : Entity_Id := Empty)
10778 begin
10779 if Validity_Checks_On and Validity_Check_Operands then
10780 if Nkind (N) = N_Range then
10781 Ensure_Valid
10782 (Expr => Low_Bound (N),
10783 Related_Id => Related_Id,
10784 Is_Low_Bound => True);
10786 Ensure_Valid
10787 (Expr => High_Bound (N),
10788 Related_Id => Related_Id,
10789 Is_High_Bound => True);
10790 end if;
10791 end if;
10792 end Validity_Check_Range;
10794 --------------------------------
10795 -- Validity_Checks_Suppressed --
10796 --------------------------------
10798 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
10799 begin
10800 if Present (E) and then Checks_May_Be_Suppressed (E) then
10801 return Is_Check_Suppressed (E, Validity_Check);
10802 else
10803 return Scope_Suppress.Suppress (Validity_Check);
10804 end if;
10805 end Validity_Checks_Suppressed;
10807 end Checks;