Add initial version of C++17 <memory_resource> header
[official-gcc.git] / gcc / ada / checks.adb
blob0af436f0d708a7e23f8f828f141c79719b5343bb
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);
1878 begin
1879 if Expander_Active
1880 and then not Backend_Divide_Checks_On_Target
1881 and then Check_Needed (Right, Division_Check)
1882 then
1883 -- See if division by zero possible, and if so generate test. This
1884 -- part of the test is not controlled by the -gnato switch, since
1885 -- it is a Division_Check and not an Overflow_Check.
1887 if Do_Division_Check (N) then
1888 Set_Do_Division_Check (N, False);
1890 if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
1891 if Is_Floating_Point_Type (Etype (N)) then
1892 Insert_Action (N,
1893 Make_Raise_Constraint_Error (Loc,
1894 Condition =>
1895 Make_Op_Eq (Loc,
1896 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1897 Right_Opnd => Make_Real_Literal (Loc, Ureal_0)),
1898 Reason => CE_Divide_By_Zero));
1900 else
1901 Insert_Action (N,
1902 Make_Raise_Constraint_Error (Loc,
1903 Condition =>
1904 Make_Op_Eq (Loc,
1905 Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
1906 Right_Opnd => Make_Integer_Literal (Loc, 0)),
1907 Reason => CE_Divide_By_Zero));
1908 end if;
1909 end if;
1910 end if;
1911 end if;
1912 end Apply_Division_Check;
1914 ----------------------------------
1915 -- Apply_Float_Conversion_Check --
1916 ----------------------------------
1918 -- Let F and I be the source and target types of the conversion. The RM
1919 -- specifies that a floating-point value X is rounded to the nearest
1920 -- integer, with halfway cases being rounded away from zero. The rounded
1921 -- value of X is checked against I'Range.
1923 -- The catch in the above paragraph is that there is no good way to know
1924 -- whether the round-to-integer operation resulted in overflow. A remedy is
1925 -- to perform a range check in the floating-point domain instead, however:
1927 -- (1) The bounds may not be known at compile time
1928 -- (2) The check must take into account rounding or truncation.
1929 -- (3) The range of type I may not be exactly representable in F.
1930 -- (4) For the rounding case, The end-points I'First - 0.5 and
1931 -- I'Last + 0.5 may or may not be in range, depending on the
1932 -- sign of I'First and I'Last.
1933 -- (5) X may be a NaN, which will fail any comparison
1935 -- The following steps correctly convert X with rounding:
1937 -- (1) If either I'First or I'Last is not known at compile time, use
1938 -- I'Base instead of I in the next three steps and perform a
1939 -- regular range check against I'Range after conversion.
1940 -- (2) If I'First - 0.5 is representable in F then let Lo be that
1941 -- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
1942 -- F'Machine (I'First) and let Lo_OK be (Lo >= I'First).
1943 -- In other words, take one of the closest floating-point numbers
1944 -- (which is an integer value) to I'First, and see if it is in
1945 -- range or not.
1946 -- (3) If I'Last + 0.5 is representable in F then let Hi be that value
1947 -- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
1948 -- F'Machine (I'Last) and let Hi_OK be (Hi <= I'Last).
1949 -- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
1950 -- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
1952 -- For the truncating case, replace steps (2) and (3) as follows:
1953 -- (2) If I'First > 0, then let Lo be F'Pred (I'First) and let Lo_OK
1954 -- be False. Otherwise, let Lo be F'Succ (I'First - 1) and let
1955 -- Lo_OK be True.
1956 -- (3) If I'Last < 0, then let Hi be F'Succ (I'Last) and let Hi_OK
1957 -- be False. Otherwise let Hi be F'Pred (I'Last + 1) and let
1958 -- Hi_OK be True.
1960 procedure Apply_Float_Conversion_Check
1961 (Ck_Node : Node_Id;
1962 Target_Typ : Entity_Id)
1964 LB : constant Node_Id := Type_Low_Bound (Target_Typ);
1965 HB : constant Node_Id := Type_High_Bound (Target_Typ);
1966 Loc : constant Source_Ptr := Sloc (Ck_Node);
1967 Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
1968 Target_Base : constant Entity_Id :=
1969 Implementation_Base_Type (Target_Typ);
1971 Par : constant Node_Id := Parent (Ck_Node);
1972 pragma Assert (Nkind (Par) = N_Type_Conversion);
1973 -- Parent of check node, must be a type conversion
1975 Truncate : constant Boolean := Float_Truncate (Par);
1976 Max_Bound : constant Uint :=
1977 UI_Expon
1978 (Machine_Radix_Value (Expr_Type),
1979 Machine_Mantissa_Value (Expr_Type) - 1) - 1;
1981 -- Largest bound, so bound plus or minus half is a machine number of F
1983 Ifirst, Ilast : Uint;
1984 -- Bounds of integer type
1986 Lo, Hi : Ureal;
1987 -- Bounds to check in floating-point domain
1989 Lo_OK, Hi_OK : Boolean;
1990 -- True iff Lo resp. Hi belongs to I'Range
1992 Lo_Chk, Hi_Chk : Node_Id;
1993 -- Expressions that are False iff check fails
1995 Reason : RT_Exception_Code;
1997 begin
1998 -- We do not need checks if we are not generating code (i.e. the full
1999 -- expander is not active). In SPARK mode, we specifically don't want
2000 -- the frontend to expand these checks, which are dealt with directly
2001 -- in the formal verification backend.
2003 if not Expander_Active then
2004 return;
2005 end if;
2007 if not Compile_Time_Known_Value (LB)
2008 or not Compile_Time_Known_Value (HB)
2009 then
2010 declare
2011 -- First check that the value falls in the range of the base type,
2012 -- to prevent overflow during conversion and then perform a
2013 -- regular range check against the (dynamic) bounds.
2015 pragma Assert (Target_Base /= Target_Typ);
2017 Temp : constant Entity_Id := Make_Temporary (Loc, 'T', Par);
2019 begin
2020 Apply_Float_Conversion_Check (Ck_Node, Target_Base);
2021 Set_Etype (Temp, Target_Base);
2023 Insert_Action (Parent (Par),
2024 Make_Object_Declaration (Loc,
2025 Defining_Identifier => Temp,
2026 Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
2027 Expression => New_Copy_Tree (Par)),
2028 Suppress => All_Checks);
2030 Insert_Action (Par,
2031 Make_Raise_Constraint_Error (Loc,
2032 Condition =>
2033 Make_Not_In (Loc,
2034 Left_Opnd => New_Occurrence_Of (Temp, Loc),
2035 Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
2036 Reason => CE_Range_Check_Failed));
2037 Rewrite (Par, New_Occurrence_Of (Temp, Loc));
2039 return;
2040 end;
2041 end if;
2043 -- Get the (static) bounds of the target type
2045 Ifirst := Expr_Value (LB);
2046 Ilast := Expr_Value (HB);
2048 -- A simple optimization: if the expression is a universal literal,
2049 -- we can do the comparison with the bounds and the conversion to
2050 -- an integer type statically. The range checks are unchanged.
2052 if Nkind (Ck_Node) = N_Real_Literal
2053 and then Etype (Ck_Node) = Universal_Real
2054 and then Is_Integer_Type (Target_Typ)
2055 and then Nkind (Parent (Ck_Node)) = N_Type_Conversion
2056 then
2057 declare
2058 Int_Val : constant Uint := UR_To_Uint (Realval (Ck_Node));
2060 begin
2061 if Int_Val <= Ilast and then Int_Val >= Ifirst then
2063 -- Conversion is safe
2065 Rewrite (Parent (Ck_Node),
2066 Make_Integer_Literal (Loc, UI_To_Int (Int_Val)));
2067 Analyze_And_Resolve (Parent (Ck_Node), Target_Typ);
2068 return;
2069 end if;
2070 end;
2071 end if;
2073 -- Check against lower bound
2075 if Truncate and then Ifirst > 0 then
2076 Lo := Pred (Expr_Type, UR_From_Uint (Ifirst));
2077 Lo_OK := False;
2079 elsif Truncate then
2080 Lo := Succ (Expr_Type, UR_From_Uint (Ifirst - 1));
2081 Lo_OK := True;
2083 elsif abs (Ifirst) < Max_Bound then
2084 Lo := UR_From_Uint (Ifirst) - Ureal_Half;
2085 Lo_OK := (Ifirst > 0);
2087 else
2088 Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
2089 Lo_OK := (Lo >= UR_From_Uint (Ifirst));
2090 end if;
2092 if Lo_OK then
2094 -- Lo_Chk := (X >= Lo)
2096 Lo_Chk := Make_Op_Ge (Loc,
2097 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2098 Right_Opnd => Make_Real_Literal (Loc, Lo));
2100 else
2101 -- Lo_Chk := (X > Lo)
2103 Lo_Chk := Make_Op_Gt (Loc,
2104 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2105 Right_Opnd => Make_Real_Literal (Loc, Lo));
2106 end if;
2108 -- Check against higher bound
2110 if Truncate and then Ilast < 0 then
2111 Hi := Succ (Expr_Type, UR_From_Uint (Ilast));
2112 Hi_OK := False;
2114 elsif Truncate then
2115 Hi := Pred (Expr_Type, UR_From_Uint (Ilast + 1));
2116 Hi_OK := True;
2118 elsif abs (Ilast) < Max_Bound then
2119 Hi := UR_From_Uint (Ilast) + Ureal_Half;
2120 Hi_OK := (Ilast < 0);
2121 else
2122 Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
2123 Hi_OK := (Hi <= UR_From_Uint (Ilast));
2124 end if;
2126 if Hi_OK then
2128 -- Hi_Chk := (X <= Hi)
2130 Hi_Chk := Make_Op_Le (Loc,
2131 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2132 Right_Opnd => Make_Real_Literal (Loc, Hi));
2134 else
2135 -- Hi_Chk := (X < Hi)
2137 Hi_Chk := Make_Op_Lt (Loc,
2138 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
2139 Right_Opnd => Make_Real_Literal (Loc, Hi));
2140 end if;
2142 -- If the bounds of the target type are the same as those of the base
2143 -- type, the check is an overflow check as a range check is not
2144 -- performed in these cases.
2146 if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
2147 and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
2148 then
2149 Reason := CE_Overflow_Check_Failed;
2150 else
2151 Reason := CE_Range_Check_Failed;
2152 end if;
2154 -- Raise CE if either conditions does not hold
2156 Insert_Action (Ck_Node,
2157 Make_Raise_Constraint_Error (Loc,
2158 Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
2159 Reason => Reason));
2160 end Apply_Float_Conversion_Check;
2162 ------------------------
2163 -- Apply_Length_Check --
2164 ------------------------
2166 procedure Apply_Length_Check
2167 (Ck_Node : Node_Id;
2168 Target_Typ : Entity_Id;
2169 Source_Typ : Entity_Id := Empty)
2171 begin
2172 Apply_Selected_Length_Checks
2173 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2174 end Apply_Length_Check;
2176 -------------------------------------
2177 -- Apply_Parameter_Aliasing_Checks --
2178 -------------------------------------
2180 procedure Apply_Parameter_Aliasing_Checks
2181 (Call : Node_Id;
2182 Subp : Entity_Id)
2184 Loc : constant Source_Ptr := Sloc (Call);
2186 function May_Cause_Aliasing
2187 (Formal_1 : Entity_Id;
2188 Formal_2 : Entity_Id) return Boolean;
2189 -- Determine whether two formal parameters can alias each other
2190 -- depending on their modes.
2192 function Original_Actual (N : Node_Id) return Node_Id;
2193 -- The expander may replace an actual with a temporary for the sake of
2194 -- side effect removal. The temporary may hide a potential aliasing as
2195 -- it does not share the address of the actual. This routine attempts
2196 -- to retrieve the original actual.
2198 procedure Overlap_Check
2199 (Actual_1 : Node_Id;
2200 Actual_2 : Node_Id;
2201 Formal_1 : Entity_Id;
2202 Formal_2 : Entity_Id;
2203 Check : in out Node_Id);
2204 -- Create a check to determine whether Actual_1 overlaps with Actual_2.
2205 -- If detailed exception messages are enabled, the check is augmented to
2206 -- provide information about the names of the corresponding formals. See
2207 -- the body for details. Actual_1 and Actual_2 denote the two actuals to
2208 -- be tested. Formal_1 and Formal_2 denote the corresponding formals.
2209 -- Check contains all and-ed simple tests generated so far or remains
2210 -- unchanged in the case of detailed exception messaged.
2212 ------------------------
2213 -- May_Cause_Aliasing --
2214 ------------------------
2216 function May_Cause_Aliasing
2217 (Formal_1 : Entity_Id;
2218 Formal_2 : Entity_Id) return Boolean
2220 begin
2221 -- The following combination cannot lead to aliasing
2223 -- Formal 1 Formal 2
2224 -- IN IN
2226 if Ekind (Formal_1) = E_In_Parameter
2227 and then
2228 Ekind (Formal_2) = E_In_Parameter
2229 then
2230 return False;
2232 -- The following combinations may lead to aliasing
2234 -- Formal 1 Formal 2
2235 -- IN OUT
2236 -- IN IN OUT
2237 -- OUT IN
2238 -- OUT IN OUT
2239 -- OUT OUT
2241 else
2242 return True;
2243 end if;
2244 end May_Cause_Aliasing;
2246 ---------------------
2247 -- Original_Actual --
2248 ---------------------
2250 function Original_Actual (N : Node_Id) return Node_Id is
2251 begin
2252 if Nkind (N) = N_Type_Conversion then
2253 return Expression (N);
2255 -- The expander created a temporary to capture the result of a type
2256 -- conversion where the expression is the real actual.
2258 elsif Nkind (N) = N_Identifier
2259 and then Present (Original_Node (N))
2260 and then Nkind (Original_Node (N)) = N_Type_Conversion
2261 then
2262 return Expression (Original_Node (N));
2263 end if;
2265 return N;
2266 end Original_Actual;
2268 -------------------
2269 -- Overlap_Check --
2270 -------------------
2272 procedure Overlap_Check
2273 (Actual_1 : Node_Id;
2274 Actual_2 : Node_Id;
2275 Formal_1 : Entity_Id;
2276 Formal_2 : Entity_Id;
2277 Check : in out Node_Id)
2279 Cond : Node_Id;
2280 ID_Casing : constant Casing_Type :=
2281 Identifier_Casing (Source_Index (Current_Sem_Unit));
2283 begin
2284 -- Generate:
2285 -- Actual_1'Overlaps_Storage (Actual_2)
2287 Cond :=
2288 Make_Attribute_Reference (Loc,
2289 Prefix => New_Copy_Tree (Original_Actual (Actual_1)),
2290 Attribute_Name => Name_Overlaps_Storage,
2291 Expressions =>
2292 New_List (New_Copy_Tree (Original_Actual (Actual_2))));
2294 -- Generate the following check when detailed exception messages are
2295 -- enabled:
2297 -- if Actual_1'Overlaps_Storage (Actual_2) then
2298 -- raise Program_Error with <detailed message>;
2299 -- end if;
2301 if Exception_Extra_Info then
2302 Start_String;
2304 -- Do not generate location information for internal calls
2306 if Comes_From_Source (Call) then
2307 Store_String_Chars (Build_Location_String (Loc));
2308 Store_String_Char (' ');
2309 end if;
2311 Store_String_Chars ("aliased parameters, actuals for """);
2313 Get_Name_String (Chars (Formal_1));
2314 Set_Casing (ID_Casing);
2315 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2317 Store_String_Chars (""" and """);
2319 Get_Name_String (Chars (Formal_2));
2320 Set_Casing (ID_Casing);
2321 Store_String_Chars (Name_Buffer (1 .. Name_Len));
2323 Store_String_Chars (""" overlap");
2325 Insert_Action (Call,
2326 Make_If_Statement (Loc,
2327 Condition => Cond,
2328 Then_Statements => New_List (
2329 Make_Raise_Statement (Loc,
2330 Name =>
2331 New_Occurrence_Of (Standard_Program_Error, Loc),
2332 Expression => Make_String_Literal (Loc, End_String)))));
2334 -- Create a sequence of overlapping checks by and-ing them all
2335 -- together.
2337 else
2338 if No (Check) then
2339 Check := Cond;
2340 else
2341 Check :=
2342 Make_And_Then (Loc,
2343 Left_Opnd => Check,
2344 Right_Opnd => Cond);
2345 end if;
2346 end if;
2347 end Overlap_Check;
2349 -- Local variables
2351 Actual_1 : Node_Id;
2352 Actual_2 : Node_Id;
2353 Check : Node_Id;
2354 Formal_1 : Entity_Id;
2355 Formal_2 : Entity_Id;
2356 Orig_Act_1 : Node_Id;
2357 Orig_Act_2 : Node_Id;
2359 -- Start of processing for Apply_Parameter_Aliasing_Checks
2361 begin
2362 Check := Empty;
2364 Actual_1 := First_Actual (Call);
2365 Formal_1 := First_Formal (Subp);
2366 while Present (Actual_1) and then Present (Formal_1) loop
2367 Orig_Act_1 := Original_Actual (Actual_1);
2369 -- Ensure that the actual is an object that is not passed by value.
2370 -- Elementary types are always passed by value, therefore actuals of
2371 -- such types cannot lead to aliasing. An aggregate is an object in
2372 -- Ada 2012, but an actual that is an aggregate cannot overlap with
2373 -- another actual. A type that is By_Reference (such as an array of
2374 -- controlled types) is not subject to the check because any update
2375 -- will be done in place and a subsequent read will always see the
2376 -- correct value, see RM 6.2 (12/3).
2378 if Nkind (Orig_Act_1) = N_Aggregate
2379 or else (Nkind (Orig_Act_1) = N_Qualified_Expression
2380 and then Nkind (Expression (Orig_Act_1)) = N_Aggregate)
2381 then
2382 null;
2384 elsif Is_Object_Reference (Orig_Act_1)
2385 and then not Is_Elementary_Type (Etype (Orig_Act_1))
2386 and then not Is_By_Reference_Type (Etype (Orig_Act_1))
2387 then
2388 Actual_2 := Next_Actual (Actual_1);
2389 Formal_2 := Next_Formal (Formal_1);
2390 while Present (Actual_2) and then Present (Formal_2) loop
2391 Orig_Act_2 := Original_Actual (Actual_2);
2393 -- The other actual we are testing against must also denote
2394 -- a non pass-by-value object. Generate the check only when
2395 -- the mode of the two formals may lead to aliasing.
2397 if Is_Object_Reference (Orig_Act_2)
2398 and then not Is_Elementary_Type (Etype (Orig_Act_2))
2399 and then May_Cause_Aliasing (Formal_1, Formal_2)
2400 then
2401 Remove_Side_Effects (Actual_1);
2402 Remove_Side_Effects (Actual_2);
2404 Overlap_Check
2405 (Actual_1 => Actual_1,
2406 Actual_2 => Actual_2,
2407 Formal_1 => Formal_1,
2408 Formal_2 => Formal_2,
2409 Check => Check);
2410 end if;
2412 Next_Actual (Actual_2);
2413 Next_Formal (Formal_2);
2414 end loop;
2415 end if;
2417 Next_Actual (Actual_1);
2418 Next_Formal (Formal_1);
2419 end loop;
2421 -- Place a simple check right before the call
2423 if Present (Check) and then not Exception_Extra_Info then
2424 Insert_Action (Call,
2425 Make_Raise_Program_Error (Loc,
2426 Condition => Check,
2427 Reason => PE_Aliased_Parameters));
2428 end if;
2429 end Apply_Parameter_Aliasing_Checks;
2431 -------------------------------------
2432 -- Apply_Parameter_Validity_Checks --
2433 -------------------------------------
2435 procedure Apply_Parameter_Validity_Checks (Subp : Entity_Id) is
2436 Subp_Decl : Node_Id;
2438 procedure Add_Validity_Check
2439 (Formal : Entity_Id;
2440 Prag_Nam : Name_Id;
2441 For_Result : Boolean := False);
2442 -- Add a single 'Valid[_Scalar] check which verifies the initialization
2443 -- of Formal. Prag_Nam denotes the pre or post condition pragma name.
2444 -- Set flag For_Result when to verify the result of a function.
2446 ------------------------
2447 -- Add_Validity_Check --
2448 ------------------------
2450 procedure Add_Validity_Check
2451 (Formal : Entity_Id;
2452 Prag_Nam : Name_Id;
2453 For_Result : Boolean := False)
2455 procedure Build_Pre_Post_Condition (Expr : Node_Id);
2456 -- Create a pre/postcondition pragma that tests expression Expr
2458 ------------------------------
2459 -- Build_Pre_Post_Condition --
2460 ------------------------------
2462 procedure Build_Pre_Post_Condition (Expr : Node_Id) is
2463 Loc : constant Source_Ptr := Sloc (Subp);
2464 Decls : List_Id;
2465 Prag : Node_Id;
2467 begin
2468 Prag :=
2469 Make_Pragma (Loc,
2470 Chars => Prag_Nam,
2471 Pragma_Argument_Associations => New_List (
2472 Make_Pragma_Argument_Association (Loc,
2473 Chars => Name_Check,
2474 Expression => Expr)));
2476 -- Add a message unless exception messages are suppressed
2478 if not Exception_Locations_Suppressed then
2479 Append_To (Pragma_Argument_Associations (Prag),
2480 Make_Pragma_Argument_Association (Loc,
2481 Chars => Name_Message,
2482 Expression =>
2483 Make_String_Literal (Loc,
2484 Strval => "failed "
2485 & Get_Name_String (Prag_Nam)
2486 & " from "
2487 & Build_Location_String (Loc))));
2488 end if;
2490 -- Insert the pragma in the tree
2492 if Nkind (Parent (Subp_Decl)) = N_Compilation_Unit then
2493 Add_Global_Declaration (Prag);
2494 Analyze (Prag);
2496 -- PPC pragmas associated with subprogram bodies must be inserted
2497 -- in the declarative part of the body.
2499 elsif Nkind (Subp_Decl) = N_Subprogram_Body then
2500 Decls := Declarations (Subp_Decl);
2502 if No (Decls) then
2503 Decls := New_List;
2504 Set_Declarations (Subp_Decl, Decls);
2505 end if;
2507 Prepend_To (Decls, Prag);
2508 Analyze (Prag);
2510 -- For subprogram declarations insert the PPC pragma right after
2511 -- the declarative node.
2513 else
2514 Insert_After_And_Analyze (Subp_Decl, Prag);
2515 end if;
2516 end Build_Pre_Post_Condition;
2518 -- Local variables
2520 Loc : constant Source_Ptr := Sloc (Subp);
2521 Typ : constant Entity_Id := Etype (Formal);
2522 Check : Node_Id;
2523 Nam : Name_Id;
2525 -- Start of processing for Add_Validity_Check
2527 begin
2528 -- For scalars, generate 'Valid test
2530 if Is_Scalar_Type (Typ) then
2531 Nam := Name_Valid;
2533 -- For any non-scalar with scalar parts, generate 'Valid_Scalars test
2535 elsif Scalar_Part_Present (Typ) then
2536 Nam := Name_Valid_Scalars;
2538 -- No test needed for other cases (no scalars to test)
2540 else
2541 return;
2542 end if;
2544 -- Step 1: Create the expression to verify the validity of the
2545 -- context.
2547 Check := New_Occurrence_Of (Formal, Loc);
2549 -- When processing a function result, use 'Result. Generate
2550 -- Context'Result
2552 if For_Result then
2553 Check :=
2554 Make_Attribute_Reference (Loc,
2555 Prefix => Check,
2556 Attribute_Name => Name_Result);
2557 end if;
2559 -- Generate:
2560 -- Context['Result]'Valid[_Scalars]
2562 Check :=
2563 Make_Attribute_Reference (Loc,
2564 Prefix => Check,
2565 Attribute_Name => Nam);
2567 -- Step 2: Create a pre or post condition pragma
2569 Build_Pre_Post_Condition (Check);
2570 end Add_Validity_Check;
2572 -- Local variables
2574 Formal : Entity_Id;
2575 Subp_Spec : Node_Id;
2577 -- Start of processing for Apply_Parameter_Validity_Checks
2579 begin
2580 -- Extract the subprogram specification and declaration nodes
2582 Subp_Spec := Parent (Subp);
2584 if Nkind (Subp_Spec) = N_Defining_Program_Unit_Name then
2585 Subp_Spec := Parent (Subp_Spec);
2586 end if;
2588 Subp_Decl := Parent (Subp_Spec);
2590 if not Comes_From_Source (Subp)
2592 -- Do not process formal subprograms because the corresponding actual
2593 -- will receive the proper checks when the instance is analyzed.
2595 or else Is_Formal_Subprogram (Subp)
2597 -- Do not process imported subprograms since pre and postconditions
2598 -- are never verified on routines coming from a different language.
2600 or else Is_Imported (Subp)
2601 or else Is_Intrinsic_Subprogram (Subp)
2603 -- The PPC pragmas generated by this routine do not correspond to
2604 -- source aspects, therefore they cannot be applied to abstract
2605 -- subprograms.
2607 or else Nkind (Subp_Decl) = N_Abstract_Subprogram_Declaration
2609 -- Do not consider subprogram renaminds because the renamed entity
2610 -- already has the proper PPC pragmas.
2612 or else Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
2614 -- Do not process null procedures because there is no benefit of
2615 -- adding the checks to a no action routine.
2617 or else (Nkind (Subp_Spec) = N_Procedure_Specification
2618 and then Null_Present (Subp_Spec))
2619 then
2620 return;
2621 end if;
2623 -- Inspect all the formals applying aliasing and scalar initialization
2624 -- checks where applicable.
2626 Formal := First_Formal (Subp);
2627 while Present (Formal) loop
2629 -- Generate the following scalar initialization checks for each
2630 -- formal parameter:
2632 -- mode IN - Pre => Formal'Valid[_Scalars]
2633 -- mode IN OUT - Pre, Post => Formal'Valid[_Scalars]
2634 -- mode OUT - Post => Formal'Valid[_Scalars]
2636 if Check_Validity_Of_Parameters then
2637 if Ekind_In (Formal, E_In_Parameter, E_In_Out_Parameter) then
2638 Add_Validity_Check (Formal, Name_Precondition, False);
2639 end if;
2641 if Ekind_In (Formal, E_In_Out_Parameter, E_Out_Parameter) then
2642 Add_Validity_Check (Formal, Name_Postcondition, False);
2643 end if;
2644 end if;
2646 Next_Formal (Formal);
2647 end loop;
2649 -- Generate following scalar initialization check for function result:
2651 -- Post => Subp'Result'Valid[_Scalars]
2653 if Check_Validity_Of_Parameters and then Ekind (Subp) = E_Function then
2654 Add_Validity_Check (Subp, Name_Postcondition, True);
2655 end if;
2656 end Apply_Parameter_Validity_Checks;
2658 ---------------------------
2659 -- Apply_Predicate_Check --
2660 ---------------------------
2662 procedure Apply_Predicate_Check
2663 (N : Node_Id;
2664 Typ : Entity_Id;
2665 Fun : Entity_Id := Empty)
2667 S : Entity_Id;
2669 begin
2670 if Predicate_Checks_Suppressed (Empty) then
2671 return;
2673 elsif Predicates_Ignored (Typ) then
2674 return;
2676 elsif Present (Predicate_Function (Typ)) then
2677 S := Current_Scope;
2678 while Present (S) and then not Is_Subprogram (S) loop
2679 S := Scope (S);
2680 end loop;
2682 -- A predicate check does not apply within internally generated
2683 -- subprograms, such as TSS functions.
2685 if Within_Internal_Subprogram then
2686 return;
2688 -- If the check appears within the predicate function itself, it
2689 -- means that the user specified a check whose formal is the
2690 -- predicated subtype itself, rather than some covering type. This
2691 -- is likely to be a common error, and thus deserves a warning.
2693 elsif Present (S) and then S = Predicate_Function (Typ) then
2694 Error_Msg_NE
2695 ("predicate check includes a call to& that requires a "
2696 & "predicate check??", Parent (N), Fun);
2697 Error_Msg_N
2698 ("\this will result in infinite recursion??", Parent (N));
2700 if Is_First_Subtype (Typ) then
2701 Error_Msg_NE
2702 ("\use an explicit subtype of& to carry the predicate",
2703 Parent (N), Typ);
2704 end if;
2706 Insert_Action (N,
2707 Make_Raise_Storage_Error (Sloc (N),
2708 Reason => SE_Infinite_Recursion));
2710 -- Here for normal case of predicate active
2712 else
2713 -- If the type has a static predicate and the expression is known
2714 -- at compile time, see if the expression satisfies the predicate.
2716 Check_Expression_Against_Static_Predicate (N, Typ);
2718 if not Expander_Active then
2719 return;
2720 end if;
2722 -- For an entity of the type, generate a call to the predicate
2723 -- function, unless its type is an actual subtype, which is not
2724 -- visible outside of the enclosing subprogram.
2726 if Is_Entity_Name (N)
2727 and then not Is_Actual_Subtype (Typ)
2728 then
2729 Insert_Action (N,
2730 Make_Predicate_Check
2731 (Typ, New_Occurrence_Of (Entity (N), Sloc (N))));
2733 -- If the expression is not an entity it may have side effects,
2734 -- and the following call will create an object declaration for
2735 -- it. We disable checks during its analysis, to prevent an
2736 -- infinite recursion.
2738 -- If the prefix is an aggregate in an assignment, apply the
2739 -- check to the LHS after assignment, rather than create a
2740 -- redundant temporary. This is only necessary in rare cases
2741 -- of array types (including strings) initialized with an
2742 -- aggregate with an "others" clause, either coming from source
2743 -- or generated by an Initialize_Scalars pragma.
2745 elsif Nkind (N) = N_Aggregate
2746 and then Nkind (Parent (N)) = N_Assignment_Statement
2747 then
2748 Insert_Action_After (Parent (N),
2749 Make_Predicate_Check
2750 (Typ, Duplicate_Subexpr (Name (Parent (N)))));
2752 else
2753 Insert_Action (N,
2754 Make_Predicate_Check
2755 (Typ, Duplicate_Subexpr (N)), Suppress => All_Checks);
2756 end if;
2757 end if;
2758 end if;
2759 end Apply_Predicate_Check;
2761 -----------------------
2762 -- Apply_Range_Check --
2763 -----------------------
2765 procedure Apply_Range_Check
2766 (Ck_Node : Node_Id;
2767 Target_Typ : Entity_Id;
2768 Source_Typ : Entity_Id := Empty)
2770 begin
2771 Apply_Selected_Range_Checks
2772 (Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
2773 end Apply_Range_Check;
2775 ------------------------------
2776 -- Apply_Scalar_Range_Check --
2777 ------------------------------
2779 -- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check flag
2780 -- off if it is already set on.
2782 procedure Apply_Scalar_Range_Check
2783 (Expr : Node_Id;
2784 Target_Typ : Entity_Id;
2785 Source_Typ : Entity_Id := Empty;
2786 Fixed_Int : Boolean := False)
2788 Parnt : constant Node_Id := Parent (Expr);
2789 S_Typ : Entity_Id;
2790 Arr : Node_Id := Empty; -- initialize to prevent warning
2791 Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
2793 Is_Subscr_Ref : Boolean;
2794 -- Set true if Expr is a subscript
2796 Is_Unconstrained_Subscr_Ref : Boolean;
2797 -- Set true if Expr is a subscript of an unconstrained array. In this
2798 -- case we do not attempt to do an analysis of the value against the
2799 -- range of the subscript, since we don't know the actual subtype.
2801 Int_Real : Boolean;
2802 -- Set to True if Expr should be regarded as a real value even though
2803 -- the type of Expr might be discrete.
2805 procedure Bad_Value (Warn : Boolean := False);
2806 -- Procedure called if value is determined to be out of range. Warn is
2807 -- True to force a warning instead of an error, even when SPARK_Mode is
2808 -- On.
2810 ---------------
2811 -- Bad_Value --
2812 ---------------
2814 procedure Bad_Value (Warn : Boolean := False) is
2815 begin
2816 Apply_Compile_Time_Constraint_Error
2817 (Expr, "value not in range of}??", CE_Range_Check_Failed,
2818 Ent => Target_Typ,
2819 Typ => Target_Typ,
2820 Warn => Warn);
2821 end Bad_Value;
2823 -- Start of processing for Apply_Scalar_Range_Check
2825 begin
2826 -- Return if check obviously not needed
2829 -- Not needed inside generic
2831 Inside_A_Generic
2833 -- Not needed if previous error
2835 or else Target_Typ = Any_Type
2836 or else Nkind (Expr) = N_Error
2838 -- Not needed for non-scalar type
2840 or else not Is_Scalar_Type (Target_Typ)
2842 -- Not needed if we know node raises CE already
2844 or else Raises_Constraint_Error (Expr)
2845 then
2846 return;
2847 end if;
2849 -- Now, see if checks are suppressed
2851 Is_Subscr_Ref :=
2852 Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
2854 if Is_Subscr_Ref then
2855 Arr := Prefix (Parnt);
2856 Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
2858 if Is_Access_Type (Arr_Typ) then
2859 Arr_Typ := Designated_Type (Arr_Typ);
2860 end if;
2861 end if;
2863 if not Do_Range_Check (Expr) then
2865 -- Subscript reference. Check for Index_Checks suppressed
2867 if Is_Subscr_Ref then
2869 -- Check array type and its base type
2871 if Index_Checks_Suppressed (Arr_Typ)
2872 or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
2873 then
2874 return;
2876 -- Check array itself if it is an entity name
2878 elsif Is_Entity_Name (Arr)
2879 and then Index_Checks_Suppressed (Entity (Arr))
2880 then
2881 return;
2883 -- Check expression itself if it is an entity name
2885 elsif Is_Entity_Name (Expr)
2886 and then Index_Checks_Suppressed (Entity (Expr))
2887 then
2888 return;
2889 end if;
2891 -- All other cases, check for Range_Checks suppressed
2893 else
2894 -- Check target type and its base type
2896 if Range_Checks_Suppressed (Target_Typ)
2897 or else Range_Checks_Suppressed (Base_Type (Target_Typ))
2898 then
2899 return;
2901 -- Check expression itself if it is an entity name
2903 elsif Is_Entity_Name (Expr)
2904 and then Range_Checks_Suppressed (Entity (Expr))
2905 then
2906 return;
2908 -- If Expr is part of an assignment statement, then check left
2909 -- side of assignment if it is an entity name.
2911 elsif Nkind (Parnt) = N_Assignment_Statement
2912 and then Is_Entity_Name (Name (Parnt))
2913 and then Range_Checks_Suppressed (Entity (Name (Parnt)))
2914 then
2915 return;
2916 end if;
2917 end if;
2918 end if;
2920 -- Do not set range checks if they are killed
2922 if Nkind (Expr) = N_Unchecked_Type_Conversion
2923 and then Kill_Range_Check (Expr)
2924 then
2925 return;
2926 end if;
2928 -- Do not set range checks for any values from System.Scalar_Values
2929 -- since the whole idea of such values is to avoid checking them.
2931 if Is_Entity_Name (Expr)
2932 and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
2933 then
2934 return;
2935 end if;
2937 -- Now see if we need a check
2939 if No (Source_Typ) then
2940 S_Typ := Etype (Expr);
2941 else
2942 S_Typ := Source_Typ;
2943 end if;
2945 if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
2946 return;
2947 end if;
2949 Is_Unconstrained_Subscr_Ref :=
2950 Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
2952 -- Special checks for floating-point type
2954 if Is_Floating_Point_Type (S_Typ) then
2956 -- Always do a range check if the source type includes infinities and
2957 -- the target type does not include infinities. We do not do this if
2958 -- range checks are killed.
2959 -- If the expression is a literal and the bounds of the type are
2960 -- static constants it may be possible to optimize the check.
2962 if Has_Infinities (S_Typ)
2963 and then not Has_Infinities (Target_Typ)
2964 then
2965 -- If the expression is a literal and the bounds of the type are
2966 -- static constants it may be possible to optimize the check.
2968 if Nkind (Expr) = N_Real_Literal then
2969 declare
2970 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
2971 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
2973 begin
2974 if Compile_Time_Known_Value (Tlo)
2975 and then Compile_Time_Known_Value (Thi)
2976 and then Expr_Value_R (Expr) >= Expr_Value_R (Tlo)
2977 and then Expr_Value_R (Expr) <= Expr_Value_R (Thi)
2978 then
2979 return;
2980 else
2981 Enable_Range_Check (Expr);
2982 end if;
2983 end;
2985 else
2986 Enable_Range_Check (Expr);
2987 end if;
2988 end if;
2989 end if;
2991 -- Return if we know expression is definitely in the range of the target
2992 -- type as determined by Determine_Range. Right now we only do this for
2993 -- discrete types, and not fixed-point or floating-point types.
2995 -- The additional less-precise tests below catch these cases
2997 -- In GNATprove_Mode, also deal with the case of a conversion from
2998 -- floating-point to integer. It is only possible because analysis
2999 -- in GNATprove rules out the possibility of a NaN or infinite value.
3001 -- Note: skip this if we are given a source_typ, since the point of
3002 -- supplying a Source_Typ is to stop us looking at the expression.
3003 -- We could sharpen this test to be out parameters only ???
3005 if Is_Discrete_Type (Target_Typ)
3006 and then (Is_Discrete_Type (Etype (Expr))
3007 or else (GNATprove_Mode
3008 and then Is_Floating_Point_Type (Etype (Expr))))
3009 and then not Is_Unconstrained_Subscr_Ref
3010 and then No (Source_Typ)
3011 then
3012 declare
3013 Thi : constant Node_Id := Type_High_Bound (Target_Typ);
3014 Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
3016 begin
3017 if Compile_Time_Known_Value (Tlo)
3018 and then Compile_Time_Known_Value (Thi)
3019 then
3020 declare
3021 OK : Boolean := False; -- initialize to prevent warning
3022 Hiv : constant Uint := Expr_Value (Thi);
3023 Lov : constant Uint := Expr_Value (Tlo);
3024 Hi : Uint := No_Uint;
3025 Lo : Uint := No_Uint;
3027 begin
3028 -- If range is null, we for sure have a constraint error (we
3029 -- don't even need to look at the value involved, since all
3030 -- possible values will raise CE).
3032 if Lov > Hiv then
3034 -- When SPARK_Mode is On, force a warning instead of
3035 -- an error in that case, as this likely corresponds
3036 -- to deactivated code.
3038 Bad_Value (Warn => SPARK_Mode = On);
3040 -- In GNATprove mode, we enable the range check so that
3041 -- GNATprove will issue a message if it cannot be proved.
3043 if GNATprove_Mode then
3044 Enable_Range_Check (Expr);
3045 end if;
3047 return;
3048 end if;
3050 -- Otherwise determine range of value
3052 if Is_Discrete_Type (Etype (Expr)) then
3053 Determine_Range
3054 (Expr, OK, Lo, Hi, Assume_Valid => True);
3056 -- When converting a float to an integer type, determine the
3057 -- range in real first, and then convert the bounds using
3058 -- UR_To_Uint which correctly rounds away from zero when
3059 -- half way between two integers, as required by normal
3060 -- Ada 95 rounding semantics. It is only possible because
3061 -- analysis in GNATprove rules out the possibility of a NaN
3062 -- or infinite value.
3064 elsif GNATprove_Mode
3065 and then Is_Floating_Point_Type (Etype (Expr))
3066 then
3067 declare
3068 Hir : Ureal;
3069 Lor : Ureal;
3071 begin
3072 Determine_Range_R
3073 (Expr, OK, Lor, Hir, Assume_Valid => True);
3075 if OK then
3076 Lo := UR_To_Uint (Lor);
3077 Hi := UR_To_Uint (Hir);
3078 end if;
3079 end;
3080 end if;
3082 if OK then
3084 -- If definitely in range, all OK
3086 if Lo >= Lov and then Hi <= Hiv then
3087 return;
3089 -- If definitely not in range, warn
3091 elsif Lov > Hi or else Hiv < Lo then
3093 -- Ignore out of range values for System.Priority in
3094 -- CodePeer mode since the actual target compiler may
3095 -- provide a wider range.
3097 if not CodePeer_Mode
3098 or else Target_Typ /= RTE (RE_Priority)
3099 then
3100 Bad_Value;
3101 end if;
3103 return;
3105 -- Otherwise we don't know
3107 else
3108 null;
3109 end if;
3110 end if;
3111 end;
3112 end if;
3113 end;
3114 end if;
3116 Int_Real :=
3117 Is_Floating_Point_Type (S_Typ)
3118 or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
3120 -- Check if we can determine at compile time whether Expr is in the
3121 -- range of the target type. Note that if S_Typ is within the bounds
3122 -- of Target_Typ then this must be the case. This check is meaningful
3123 -- only if this is not a conversion between integer and real types.
3125 if not Is_Unconstrained_Subscr_Ref
3126 and then Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
3127 and then
3128 (In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
3130 -- Also check if the expression itself is in the range of the
3131 -- target type if it is a known at compile time value. We skip
3132 -- this test if S_Typ is set since for OUT and IN OUT parameters
3133 -- the Expr itself is not relevant to the checking.
3135 or else
3136 (No (Source_Typ)
3137 and then Is_In_Range (Expr, Target_Typ,
3138 Assume_Valid => True,
3139 Fixed_Int => Fixed_Int,
3140 Int_Real => Int_Real)))
3141 then
3142 return;
3144 elsif Is_Out_Of_Range (Expr, Target_Typ,
3145 Assume_Valid => True,
3146 Fixed_Int => Fixed_Int,
3147 Int_Real => Int_Real)
3148 then
3149 Bad_Value;
3150 return;
3152 -- Floating-point case
3153 -- In the floating-point case, we only do range checks if the type is
3154 -- constrained. We definitely do NOT want range checks for unconstrained
3155 -- types, since we want to have infinities, except when
3156 -- Check_Float_Overflow is set.
3158 elsif Is_Floating_Point_Type (S_Typ) then
3159 if Is_Constrained (S_Typ) or else Check_Float_Overflow then
3160 Enable_Range_Check (Expr);
3161 end if;
3163 -- For all other cases we enable a range check unconditionally
3165 else
3166 Enable_Range_Check (Expr);
3167 return;
3168 end if;
3169 end Apply_Scalar_Range_Check;
3171 ----------------------------------
3172 -- Apply_Selected_Length_Checks --
3173 ----------------------------------
3175 procedure Apply_Selected_Length_Checks
3176 (Ck_Node : Node_Id;
3177 Target_Typ : Entity_Id;
3178 Source_Typ : Entity_Id;
3179 Do_Static : Boolean)
3181 Checks_On : constant Boolean :=
3182 not Index_Checks_Suppressed (Target_Typ)
3183 or else
3184 not Length_Checks_Suppressed (Target_Typ);
3186 Loc : constant Source_Ptr := Sloc (Ck_Node);
3188 Cond : Node_Id;
3189 R_Cno : Node_Id;
3190 R_Result : Check_Result;
3192 begin
3193 -- Only apply checks when generating code
3195 -- Note: this means that we lose some useful warnings if the expander
3196 -- is not active.
3198 if not Expander_Active then
3199 return;
3200 end if;
3202 R_Result :=
3203 Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3205 for J in 1 .. 2 loop
3206 R_Cno := R_Result (J);
3207 exit when No (R_Cno);
3209 -- A length check may mention an Itype which is attached to a
3210 -- subsequent node. At the top level in a package this can cause
3211 -- an order-of-elaboration problem, so we make sure that the itype
3212 -- is referenced now.
3214 if Ekind (Current_Scope) = E_Package
3215 and then Is_Compilation_Unit (Current_Scope)
3216 then
3217 Ensure_Defined (Target_Typ, Ck_Node);
3219 if Present (Source_Typ) then
3220 Ensure_Defined (Source_Typ, Ck_Node);
3222 elsif Is_Itype (Etype (Ck_Node)) then
3223 Ensure_Defined (Etype (Ck_Node), Ck_Node);
3224 end if;
3225 end if;
3227 -- If the item is a conditional raise of constraint error, then have
3228 -- a look at what check is being performed and ???
3230 if Nkind (R_Cno) = N_Raise_Constraint_Error
3231 and then Present (Condition (R_Cno))
3232 then
3233 Cond := Condition (R_Cno);
3235 -- Case where node does not now have a dynamic check
3237 if not Has_Dynamic_Length_Check (Ck_Node) then
3239 -- If checks are on, just insert the check
3241 if Checks_On then
3242 Insert_Action (Ck_Node, R_Cno);
3244 if not Do_Static then
3245 Set_Has_Dynamic_Length_Check (Ck_Node);
3246 end if;
3248 -- If checks are off, then analyze the length check after
3249 -- temporarily attaching it to the tree in case the relevant
3250 -- condition can be evaluated at compile time. We still want a
3251 -- compile time warning in this case.
3253 else
3254 Set_Parent (R_Cno, Ck_Node);
3255 Analyze (R_Cno);
3256 end if;
3257 end if;
3259 -- Output a warning if the condition is known to be True
3261 if Is_Entity_Name (Cond)
3262 and then Entity (Cond) = Standard_True
3263 then
3264 Apply_Compile_Time_Constraint_Error
3265 (Ck_Node, "wrong length for array of}??",
3266 CE_Length_Check_Failed,
3267 Ent => Target_Typ,
3268 Typ => Target_Typ);
3270 -- If we were only doing a static check, or if checks are not
3271 -- on, then we want to delete the check, since it is not needed.
3272 -- We do this by replacing the if statement by a null statement
3274 elsif Do_Static or else not Checks_On then
3275 Remove_Warning_Messages (R_Cno);
3276 Rewrite (R_Cno, Make_Null_Statement (Loc));
3277 end if;
3279 else
3280 Install_Static_Check (R_Cno, Loc);
3281 end if;
3282 end loop;
3283 end Apply_Selected_Length_Checks;
3285 ---------------------------------
3286 -- Apply_Selected_Range_Checks --
3287 ---------------------------------
3289 procedure Apply_Selected_Range_Checks
3290 (Ck_Node : Node_Id;
3291 Target_Typ : Entity_Id;
3292 Source_Typ : Entity_Id;
3293 Do_Static : Boolean)
3295 Checks_On : constant Boolean :=
3296 not Index_Checks_Suppressed (Target_Typ)
3297 or else
3298 not Range_Checks_Suppressed (Target_Typ);
3300 Loc : constant Source_Ptr := Sloc (Ck_Node);
3302 Cond : Node_Id;
3303 R_Cno : Node_Id;
3304 R_Result : Check_Result;
3306 begin
3307 -- Only apply checks when generating code. In GNATprove mode, we do not
3308 -- apply the checks, but we still call Selected_Range_Checks to possibly
3309 -- issue errors on SPARK code when a run-time error can be detected at
3310 -- compile time.
3312 if not GNATprove_Mode then
3313 if not Expander_Active or not Checks_On then
3314 return;
3315 end if;
3316 end if;
3318 R_Result :=
3319 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
3321 if GNATprove_Mode then
3322 return;
3323 end if;
3325 for J in 1 .. 2 loop
3326 R_Cno := R_Result (J);
3327 exit when No (R_Cno);
3329 -- The range check requires runtime evaluation. Depending on what its
3330 -- triggering condition is, the check may be converted into a compile
3331 -- time constraint check.
3333 if Nkind (R_Cno) = N_Raise_Constraint_Error
3334 and then Present (Condition (R_Cno))
3335 then
3336 Cond := Condition (R_Cno);
3338 -- Insert the range check before the related context. Note that
3339 -- this action analyses the triggering condition.
3341 Insert_Action (Ck_Node, R_Cno);
3343 -- This old code doesn't make sense, why is the context flagged as
3344 -- requiring dynamic range checks now in the middle of generating
3345 -- them ???
3347 if not Do_Static then
3348 Set_Has_Dynamic_Range_Check (Ck_Node);
3349 end if;
3351 -- The triggering condition evaluates to True, the range check
3352 -- can be converted into a compile time constraint check.
3354 if Is_Entity_Name (Cond)
3355 and then Entity (Cond) = Standard_True
3356 then
3357 -- Since an N_Range is technically not an expression, we have
3358 -- to set one of the bounds to C_E and then just flag the
3359 -- N_Range. The warning message will point to the lower bound
3360 -- and complain about a range, which seems OK.
3362 if Nkind (Ck_Node) = N_Range then
3363 Apply_Compile_Time_Constraint_Error
3364 (Low_Bound (Ck_Node),
3365 "static range out of bounds of}??",
3366 CE_Range_Check_Failed,
3367 Ent => Target_Typ,
3368 Typ => Target_Typ);
3370 Set_Raises_Constraint_Error (Ck_Node);
3372 else
3373 Apply_Compile_Time_Constraint_Error
3374 (Ck_Node,
3375 "static value out of range of}??",
3376 CE_Range_Check_Failed,
3377 Ent => Target_Typ,
3378 Typ => Target_Typ);
3379 end if;
3381 -- If we were only doing a static check, or if checks are not
3382 -- on, then we want to delete the check, since it is not needed.
3383 -- We do this by replacing the if statement by a null statement
3385 elsif Do_Static then
3386 Remove_Warning_Messages (R_Cno);
3387 Rewrite (R_Cno, Make_Null_Statement (Loc));
3388 end if;
3390 -- The range check raises Constraint_Error explicitly
3392 else
3393 Install_Static_Check (R_Cno, Loc);
3394 end if;
3395 end loop;
3396 end Apply_Selected_Range_Checks;
3398 -------------------------------
3399 -- Apply_Static_Length_Check --
3400 -------------------------------
3402 procedure Apply_Static_Length_Check
3403 (Expr : Node_Id;
3404 Target_Typ : Entity_Id;
3405 Source_Typ : Entity_Id := Empty)
3407 begin
3408 Apply_Selected_Length_Checks
3409 (Expr, Target_Typ, Source_Typ, Do_Static => True);
3410 end Apply_Static_Length_Check;
3412 -------------------------------------
3413 -- Apply_Subscript_Validity_Checks --
3414 -------------------------------------
3416 procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
3417 Sub : Node_Id;
3419 begin
3420 pragma Assert (Nkind (Expr) = N_Indexed_Component);
3422 -- Loop through subscripts
3424 Sub := First (Expressions (Expr));
3425 while Present (Sub) loop
3427 -- Check one subscript. Note that we do not worry about enumeration
3428 -- type with holes, since we will convert the value to a Pos value
3429 -- for the subscript, and that convert will do the necessary validity
3430 -- check.
3432 Ensure_Valid (Sub, Holes_OK => True);
3434 -- Move to next subscript
3436 Sub := Next (Sub);
3437 end loop;
3438 end Apply_Subscript_Validity_Checks;
3440 ----------------------------------
3441 -- Apply_Type_Conversion_Checks --
3442 ----------------------------------
3444 procedure Apply_Type_Conversion_Checks (N : Node_Id) is
3445 Target_Type : constant Entity_Id := Etype (N);
3446 Target_Base : constant Entity_Id := Base_Type (Target_Type);
3447 Expr : constant Node_Id := Expression (N);
3449 Expr_Type : constant Entity_Id := Underlying_Type (Etype (Expr));
3450 -- Note: if Etype (Expr) is a private type without discriminants, its
3451 -- full view might have discriminants with defaults, so we need the
3452 -- full view here to retrieve the constraints.
3454 begin
3455 if Inside_A_Generic then
3456 return;
3458 -- Skip these checks if serious errors detected, there are some nasty
3459 -- situations of incomplete trees that blow things up.
3461 elsif Serious_Errors_Detected > 0 then
3462 return;
3464 -- Never generate discriminant checks for Unchecked_Union types
3466 elsif Present (Expr_Type)
3467 and then Is_Unchecked_Union (Expr_Type)
3468 then
3469 return;
3471 -- Scalar type conversions of the form Target_Type (Expr) require a
3472 -- range check if we cannot be sure that Expr is in the base type of
3473 -- Target_Typ and also that Expr is in the range of Target_Typ. These
3474 -- are not quite the same condition from an implementation point of
3475 -- view, but clearly the second includes the first.
3477 elsif Is_Scalar_Type (Target_Type) then
3478 declare
3479 Conv_OK : constant Boolean := Conversion_OK (N);
3480 -- If the Conversion_OK flag on the type conversion is set and no
3481 -- floating-point type is involved in the type conversion then
3482 -- fixed-point values must be read as integral values.
3484 Float_To_Int : constant Boolean :=
3485 Is_Floating_Point_Type (Expr_Type)
3486 and then Is_Integer_Type (Target_Type);
3488 begin
3489 if not Overflow_Checks_Suppressed (Target_Base)
3490 and then not Overflow_Checks_Suppressed (Target_Type)
3491 and then not
3492 In_Subrange_Of (Expr_Type, Target_Base, Fixed_Int => Conv_OK)
3493 and then not Float_To_Int
3494 then
3495 -- A small optimization: the attribute 'Pos applied to an
3496 -- enumeration type has a known range, even though its type is
3497 -- Universal_Integer. So in numeric conversions it is usually
3498 -- within range of the target integer type. Use the static
3499 -- bounds of the base types to check. Disable this optimization
3500 -- in case of a generic formal discrete type, because we don't
3501 -- necessarily know the upper bound yet.
3503 if Nkind (Expr) = N_Attribute_Reference
3504 and then Attribute_Name (Expr) = Name_Pos
3505 and then Is_Enumeration_Type (Etype (Prefix (Expr)))
3506 and then not Is_Generic_Type (Etype (Prefix (Expr)))
3507 and then Is_Integer_Type (Target_Type)
3508 then
3509 declare
3510 Enum_T : constant Entity_Id :=
3511 Root_Type (Etype (Prefix (Expr)));
3512 Int_T : constant Entity_Id := Base_Type (Target_Type);
3513 Last_I : constant Uint :=
3514 Intval (High_Bound (Scalar_Range (Int_T)));
3515 Last_E : Uint;
3517 begin
3518 -- Character types have no explicit literals, so we use
3519 -- the known number of characters in the type.
3521 if Root_Type (Enum_T) = Standard_Character then
3522 Last_E := UI_From_Int (255);
3524 elsif Enum_T = Standard_Wide_Character
3525 or else Enum_T = Standard_Wide_Wide_Character
3526 then
3527 Last_E := UI_From_Int (65535);
3529 else
3530 Last_E :=
3531 Enumeration_Pos
3532 (Entity (High_Bound (Scalar_Range (Enum_T))));
3533 end if;
3535 if Last_E <= Last_I then
3536 null;
3538 else
3539 Activate_Overflow_Check (N);
3540 end if;
3541 end;
3543 else
3544 Activate_Overflow_Check (N);
3545 end if;
3546 end if;
3548 if not Range_Checks_Suppressed (Target_Type)
3549 and then not Range_Checks_Suppressed (Expr_Type)
3550 then
3551 if Float_To_Int
3552 and then not GNATprove_Mode
3553 then
3554 Apply_Float_Conversion_Check (Expr, Target_Type);
3555 else
3556 Apply_Scalar_Range_Check
3557 (Expr, Target_Type, Fixed_Int => Conv_OK);
3559 -- If the target type has predicates, we need to indicate
3560 -- the need for a check, even if Determine_Range finds that
3561 -- the value is within bounds. This may be the case e.g for
3562 -- a division with a constant denominator.
3564 if Has_Predicates (Target_Type) then
3565 Enable_Range_Check (Expr);
3566 end if;
3567 end if;
3568 end if;
3569 end;
3571 elsif Comes_From_Source (N)
3572 and then not Discriminant_Checks_Suppressed (Target_Type)
3573 and then Is_Record_Type (Target_Type)
3574 and then Is_Derived_Type (Target_Type)
3575 and then not Is_Tagged_Type (Target_Type)
3576 and then not Is_Constrained (Target_Type)
3577 and then Present (Stored_Constraint (Target_Type))
3578 then
3579 -- An unconstrained derived type may have inherited discriminant.
3580 -- Build an actual discriminant constraint list using the stored
3581 -- constraint, to verify that the expression of the parent type
3582 -- satisfies the constraints imposed by the (unconstrained) derived
3583 -- type. This applies to value conversions, not to view conversions
3584 -- of tagged types.
3586 declare
3587 Loc : constant Source_Ptr := Sloc (N);
3588 Cond : Node_Id;
3589 Constraint : Elmt_Id;
3590 Discr_Value : Node_Id;
3591 Discr : Entity_Id;
3593 New_Constraints : constant Elist_Id := New_Elmt_List;
3594 Old_Constraints : constant Elist_Id :=
3595 Discriminant_Constraint (Expr_Type);
3597 begin
3598 Constraint := First_Elmt (Stored_Constraint (Target_Type));
3599 while Present (Constraint) loop
3600 Discr_Value := Node (Constraint);
3602 if Is_Entity_Name (Discr_Value)
3603 and then Ekind (Entity (Discr_Value)) = E_Discriminant
3604 then
3605 Discr := Corresponding_Discriminant (Entity (Discr_Value));
3607 if Present (Discr)
3608 and then Scope (Discr) = Base_Type (Expr_Type)
3609 then
3610 -- Parent is constrained by new discriminant. Obtain
3611 -- Value of original discriminant in expression. If the
3612 -- new discriminant has been used to constrain more than
3613 -- one of the stored discriminants, this will provide the
3614 -- required consistency check.
3616 Append_Elmt
3617 (Make_Selected_Component (Loc,
3618 Prefix =>
3619 Duplicate_Subexpr_No_Checks
3620 (Expr, Name_Req => True),
3621 Selector_Name =>
3622 Make_Identifier (Loc, Chars (Discr))),
3623 New_Constraints);
3625 else
3626 -- Discriminant of more remote ancestor ???
3628 return;
3629 end if;
3631 -- Derived type definition has an explicit value for this
3632 -- stored discriminant.
3634 else
3635 Append_Elmt
3636 (Duplicate_Subexpr_No_Checks (Discr_Value),
3637 New_Constraints);
3638 end if;
3640 Next_Elmt (Constraint);
3641 end loop;
3643 -- Use the unconstrained expression type to retrieve the
3644 -- discriminants of the parent, and apply momentarily the
3645 -- discriminant constraint synthesized above.
3647 Set_Discriminant_Constraint (Expr_Type, New_Constraints);
3648 Cond := Build_Discriminant_Checks (Expr, Expr_Type);
3649 Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
3651 Insert_Action (N,
3652 Make_Raise_Constraint_Error (Loc,
3653 Condition => Cond,
3654 Reason => CE_Discriminant_Check_Failed));
3655 end;
3657 -- For arrays, checks are set now, but conversions are applied during
3658 -- expansion, to take into accounts changes of representation. The
3659 -- checks become range checks on the base type or length checks on the
3660 -- subtype, depending on whether the target type is unconstrained or
3661 -- constrained. Note that the range check is put on the expression of a
3662 -- type conversion, while the length check is put on the type conversion
3663 -- itself.
3665 elsif Is_Array_Type (Target_Type) then
3666 if Is_Constrained (Target_Type) then
3667 Set_Do_Length_Check (N);
3668 else
3669 Set_Do_Range_Check (Expr);
3670 end if;
3671 end if;
3672 end Apply_Type_Conversion_Checks;
3674 ----------------------------------------------
3675 -- Apply_Universal_Integer_Attribute_Checks --
3676 ----------------------------------------------
3678 procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
3679 Loc : constant Source_Ptr := Sloc (N);
3680 Typ : constant Entity_Id := Etype (N);
3682 begin
3683 if Inside_A_Generic then
3684 return;
3686 -- Nothing to do if checks are suppressed
3688 elsif Range_Checks_Suppressed (Typ)
3689 and then Overflow_Checks_Suppressed (Typ)
3690 then
3691 return;
3693 -- Nothing to do if the attribute does not come from source. The
3694 -- internal attributes we generate of this type do not need checks,
3695 -- and furthermore the attempt to check them causes some circular
3696 -- elaboration orders when dealing with packed types.
3698 elsif not Comes_From_Source (N) then
3699 return;
3701 -- If the prefix is a selected component that depends on a discriminant
3702 -- the check may improperly expose a discriminant instead of using
3703 -- the bounds of the object itself. Set the type of the attribute to
3704 -- the base type of the context, so that a check will be imposed when
3705 -- needed (e.g. if the node appears as an index).
3707 elsif Nkind (Prefix (N)) = N_Selected_Component
3708 and then Ekind (Typ) = E_Signed_Integer_Subtype
3709 and then Depends_On_Discriminant (Scalar_Range (Typ))
3710 then
3711 Set_Etype (N, Base_Type (Typ));
3713 -- Otherwise, replace the attribute node with a type conversion node
3714 -- whose expression is the attribute, retyped to universal integer, and
3715 -- whose subtype mark is the target type. The call to analyze this
3716 -- conversion will set range and overflow checks as required for proper
3717 -- detection of an out of range value.
3719 else
3720 Set_Etype (N, Universal_Integer);
3721 Set_Analyzed (N, True);
3723 Rewrite (N,
3724 Make_Type_Conversion (Loc,
3725 Subtype_Mark => New_Occurrence_Of (Typ, Loc),
3726 Expression => Relocate_Node (N)));
3728 Analyze_And_Resolve (N, Typ);
3729 return;
3730 end if;
3731 end Apply_Universal_Integer_Attribute_Checks;
3733 -------------------------------------
3734 -- Atomic_Synchronization_Disabled --
3735 -------------------------------------
3737 -- Note: internally Disable/Enable_Atomic_Synchronization is implemented
3738 -- using a bogus check called Atomic_Synchronization. This is to make it
3739 -- more convenient to get exactly the same semantics as [Un]Suppress.
3741 function Atomic_Synchronization_Disabled (E : Entity_Id) return Boolean is
3742 begin
3743 -- If debug flag d.e is set, always return False, i.e. all atomic sync
3744 -- looks enabled, since it is never disabled.
3746 if Debug_Flag_Dot_E then
3747 return False;
3749 -- If debug flag d.d is set then always return True, i.e. all atomic
3750 -- sync looks disabled, since it always tests True.
3752 elsif Debug_Flag_Dot_D then
3753 return True;
3755 -- If entity present, then check result for that entity
3757 elsif Present (E) and then Checks_May_Be_Suppressed (E) then
3758 return Is_Check_Suppressed (E, Atomic_Synchronization);
3760 -- Otherwise result depends on current scope setting
3762 else
3763 return Scope_Suppress.Suppress (Atomic_Synchronization);
3764 end if;
3765 end Atomic_Synchronization_Disabled;
3767 -------------------------------
3768 -- Build_Discriminant_Checks --
3769 -------------------------------
3771 function Build_Discriminant_Checks
3772 (N : Node_Id;
3773 T_Typ : Entity_Id) return Node_Id
3775 Loc : constant Source_Ptr := Sloc (N);
3776 Cond : Node_Id;
3777 Disc : Elmt_Id;
3778 Disc_Ent : Entity_Id;
3779 Dref : Node_Id;
3780 Dval : Node_Id;
3782 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
3784 --------------------------------
3785 -- Aggregate_Discriminant_Val --
3786 --------------------------------
3788 function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
3789 Assoc : Node_Id;
3791 begin
3792 -- The aggregate has been normalized with named associations. We use
3793 -- the Chars field to locate the discriminant to take into account
3794 -- discriminants in derived types, which carry the same name as those
3795 -- in the parent.
3797 Assoc := First (Component_Associations (N));
3798 while Present (Assoc) loop
3799 if Chars (First (Choices (Assoc))) = Chars (Disc) then
3800 return Expression (Assoc);
3801 else
3802 Next (Assoc);
3803 end if;
3804 end loop;
3806 -- Discriminant must have been found in the loop above
3808 raise Program_Error;
3809 end Aggregate_Discriminant_Val;
3811 -- Start of processing for Build_Discriminant_Checks
3813 begin
3814 -- Loop through discriminants evolving the condition
3816 Cond := Empty;
3817 Disc := First_Elmt (Discriminant_Constraint (T_Typ));
3819 -- For a fully private type, use the discriminants of the parent type
3821 if Is_Private_Type (T_Typ)
3822 and then No (Full_View (T_Typ))
3823 then
3824 Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
3825 else
3826 Disc_Ent := First_Discriminant (T_Typ);
3827 end if;
3829 while Present (Disc) loop
3830 Dval := Node (Disc);
3832 if Nkind (Dval) = N_Identifier
3833 and then Ekind (Entity (Dval)) = E_Discriminant
3834 then
3835 Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
3836 else
3837 Dval := Duplicate_Subexpr_No_Checks (Dval);
3838 end if;
3840 -- If we have an Unchecked_Union node, we can infer the discriminants
3841 -- of the node.
3843 if Is_Unchecked_Union (Base_Type (T_Typ)) then
3844 Dref := New_Copy (
3845 Get_Discriminant_Value (
3846 First_Discriminant (T_Typ),
3847 T_Typ,
3848 Stored_Constraint (T_Typ)));
3850 elsif Nkind (N) = N_Aggregate then
3851 Dref :=
3852 Duplicate_Subexpr_No_Checks
3853 (Aggregate_Discriminant_Val (Disc_Ent));
3855 else
3856 Dref :=
3857 Make_Selected_Component (Loc,
3858 Prefix =>
3859 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
3860 Selector_Name => Make_Identifier (Loc, Chars (Disc_Ent)));
3862 Set_Is_In_Discriminant_Check (Dref);
3863 end if;
3865 Evolve_Or_Else (Cond,
3866 Make_Op_Ne (Loc,
3867 Left_Opnd => Dref,
3868 Right_Opnd => Dval));
3870 Next_Elmt (Disc);
3871 Next_Discriminant (Disc_Ent);
3872 end loop;
3874 return Cond;
3875 end Build_Discriminant_Checks;
3877 ------------------
3878 -- Check_Needed --
3879 ------------------
3881 function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
3882 N : Node_Id;
3883 P : Node_Id;
3884 K : Node_Kind;
3885 L : Node_Id;
3886 R : Node_Id;
3888 function Left_Expression (Op : Node_Id) return Node_Id;
3889 -- Return the relevant expression from the left operand of the given
3890 -- short circuit form: this is LO itself, except if LO is a qualified
3891 -- expression, a type conversion, or an expression with actions, in
3892 -- which case this is Left_Expression (Expression (LO)).
3894 ---------------------
3895 -- Left_Expression --
3896 ---------------------
3898 function Left_Expression (Op : Node_Id) return Node_Id is
3899 LE : Node_Id := Left_Opnd (Op);
3900 begin
3901 while Nkind_In (LE, N_Qualified_Expression,
3902 N_Type_Conversion,
3903 N_Expression_With_Actions)
3904 loop
3905 LE := Expression (LE);
3906 end loop;
3908 return LE;
3909 end Left_Expression;
3911 -- Start of processing for Check_Needed
3913 begin
3914 -- Always check if not simple entity
3916 if Nkind (Nod) not in N_Has_Entity
3917 or else not Comes_From_Source (Nod)
3918 then
3919 return True;
3920 end if;
3922 -- Look up tree for short circuit
3924 N := Nod;
3925 loop
3926 P := Parent (N);
3927 K := Nkind (P);
3929 -- Done if out of subexpression (note that we allow generated stuff
3930 -- such as itype declarations in this context, to keep the loop going
3931 -- since we may well have generated such stuff in complex situations.
3932 -- Also done if no parent (probably an error condition, but no point
3933 -- in behaving nasty if we find it).
3935 if No (P)
3936 or else (K not in N_Subexpr and then Comes_From_Source (P))
3937 then
3938 return True;
3940 -- Or/Or Else case, where test is part of the right operand, or is
3941 -- part of one of the actions associated with the right operand, and
3942 -- the left operand is an equality test.
3944 elsif K = N_Op_Or then
3945 exit when N = Right_Opnd (P)
3946 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3948 elsif K = N_Or_Else then
3949 exit when (N = Right_Opnd (P)
3950 or else
3951 (Is_List_Member (N)
3952 and then List_Containing (N) = Actions (P)))
3953 and then Nkind (Left_Expression (P)) = N_Op_Eq;
3955 -- Similar test for the And/And then case, where the left operand
3956 -- is an inequality test.
3958 elsif K = N_Op_And then
3959 exit when N = Right_Opnd (P)
3960 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3962 elsif K = N_And_Then then
3963 exit when (N = Right_Opnd (P)
3964 or else
3965 (Is_List_Member (N)
3966 and then List_Containing (N) = Actions (P)))
3967 and then Nkind (Left_Expression (P)) = N_Op_Ne;
3968 end if;
3970 N := P;
3971 end loop;
3973 -- If we fall through the loop, then we have a conditional with an
3974 -- appropriate test as its left operand, so look further.
3976 L := Left_Expression (P);
3978 -- L is an "=" or "/=" operator: extract its operands
3980 R := Right_Opnd (L);
3981 L := Left_Opnd (L);
3983 -- Left operand of test must match original variable
3985 if Nkind (L) not in N_Has_Entity or else Entity (L) /= Entity (Nod) then
3986 return True;
3987 end if;
3989 -- Right operand of test must be key value (zero or null)
3991 case Check is
3992 when Access_Check =>
3993 if not Known_Null (R) then
3994 return True;
3995 end if;
3997 when Division_Check =>
3998 if not Compile_Time_Known_Value (R)
3999 or else Expr_Value (R) /= Uint_0
4000 then
4001 return True;
4002 end if;
4004 when others =>
4005 raise Program_Error;
4006 end case;
4008 -- Here we have the optimizable case, warn if not short-circuited
4010 if K = N_Op_And or else K = N_Op_Or then
4011 Error_Msg_Warn := SPARK_Mode /= On;
4013 case Check is
4014 when Access_Check =>
4015 if GNATprove_Mode then
4016 Error_Msg_N
4017 ("Constraint_Error might have been raised (access check)",
4018 Parent (Nod));
4019 else
4020 Error_Msg_N
4021 ("Constraint_Error may be raised (access check)??",
4022 Parent (Nod));
4023 end if;
4025 when Division_Check =>
4026 if GNATprove_Mode then
4027 Error_Msg_N
4028 ("Constraint_Error might have been raised (zero divide)",
4029 Parent (Nod));
4030 else
4031 Error_Msg_N
4032 ("Constraint_Error may be raised (zero divide)??",
4033 Parent (Nod));
4034 end if;
4036 when others =>
4037 raise Program_Error;
4038 end case;
4040 if K = N_Op_And then
4041 Error_Msg_N -- CODEFIX
4042 ("use `AND THEN` instead of AND??", P);
4043 else
4044 Error_Msg_N -- CODEFIX
4045 ("use `OR ELSE` instead of OR??", P);
4046 end if;
4048 -- If not short-circuited, we need the check
4050 return True;
4052 -- If short-circuited, we can omit the check
4054 else
4055 return False;
4056 end if;
4057 end Check_Needed;
4059 -----------------------------------
4060 -- Check_Valid_Lvalue_Subscripts --
4061 -----------------------------------
4063 procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
4064 begin
4065 -- Skip this if range checks are suppressed
4067 if Range_Checks_Suppressed (Etype (Expr)) then
4068 return;
4070 -- Only do this check for expressions that come from source. We assume
4071 -- that expander generated assignments explicitly include any necessary
4072 -- checks. Note that this is not just an optimization, it avoids
4073 -- infinite recursions.
4075 elsif not Comes_From_Source (Expr) then
4076 return;
4078 -- For a selected component, check the prefix
4080 elsif Nkind (Expr) = N_Selected_Component then
4081 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4082 return;
4084 -- Case of indexed component
4086 elsif Nkind (Expr) = N_Indexed_Component then
4087 Apply_Subscript_Validity_Checks (Expr);
4089 -- Prefix may itself be or contain an indexed component, and these
4090 -- subscripts need checking as well.
4092 Check_Valid_Lvalue_Subscripts (Prefix (Expr));
4093 end if;
4094 end Check_Valid_Lvalue_Subscripts;
4096 ----------------------------------
4097 -- Null_Exclusion_Static_Checks --
4098 ----------------------------------
4100 procedure Null_Exclusion_Static_Checks
4101 (N : Node_Id;
4102 Comp : Node_Id := Empty;
4103 Array_Comp : Boolean := False)
4105 Has_Null : constant Boolean := Has_Null_Exclusion (N);
4106 Kind : constant Node_Kind := Nkind (N);
4107 Error_Nod : Node_Id;
4108 Expr : Node_Id;
4109 Typ : Entity_Id;
4111 begin
4112 pragma Assert
4113 (Nkind_In (Kind, N_Component_Declaration,
4114 N_Discriminant_Specification,
4115 N_Function_Specification,
4116 N_Object_Declaration,
4117 N_Parameter_Specification));
4119 if Kind = N_Function_Specification then
4120 Typ := Etype (Defining_Entity (N));
4121 else
4122 Typ := Etype (Defining_Identifier (N));
4123 end if;
4125 case Kind is
4126 when N_Component_Declaration =>
4127 if Present (Access_Definition (Component_Definition (N))) then
4128 Error_Nod := Component_Definition (N);
4129 else
4130 Error_Nod := Subtype_Indication (Component_Definition (N));
4131 end if;
4133 when N_Discriminant_Specification =>
4134 Error_Nod := Discriminant_Type (N);
4136 when N_Function_Specification =>
4137 Error_Nod := Result_Definition (N);
4139 when N_Object_Declaration =>
4140 Error_Nod := Object_Definition (N);
4142 when N_Parameter_Specification =>
4143 Error_Nod := Parameter_Type (N);
4145 when others =>
4146 raise Program_Error;
4147 end case;
4149 if Has_Null then
4151 -- Enforce legality rule 3.10 (13): A null exclusion can only be
4152 -- applied to an access [sub]type.
4154 if not Is_Access_Type (Typ) then
4155 Error_Msg_N
4156 ("`NOT NULL` allowed only for an access type", Error_Nod);
4158 -- Enforce legality rule RM 3.10(14/1): A null exclusion can only
4159 -- be applied to a [sub]type that does not exclude null already.
4161 elsif Can_Never_Be_Null (Typ) and then Comes_From_Source (Typ) then
4162 Error_Msg_NE
4163 ("`NOT NULL` not allowed (& already excludes null)",
4164 Error_Nod, Typ);
4165 end if;
4166 end if;
4168 -- Check that null-excluding objects are always initialized, except for
4169 -- deferred constants, for which the expression will appear in the full
4170 -- declaration.
4172 if Kind = N_Object_Declaration
4173 and then No (Expression (N))
4174 and then not Constant_Present (N)
4175 and then not No_Initialization (N)
4176 then
4177 if Present (Comp) then
4179 -- Specialize the warning message to indicate that we are dealing
4180 -- with an uninitialized composite object that has a defaulted
4181 -- null-excluding component.
4183 Error_Msg_Name_1 := Chars (Defining_Identifier (Comp));
4184 Error_Msg_Name_2 := Chars (Defining_Identifier (N));
4186 Discard_Node
4187 (Compile_Time_Constraint_Error
4188 (N => N,
4189 Msg =>
4190 "(Ada 2005) null-excluding component % of object % must "
4191 & "be initialized??",
4192 Ent => Defining_Identifier (Comp)));
4194 -- This is a case of an array with null-excluding components, so
4195 -- indicate that in the warning.
4197 elsif Array_Comp then
4198 Discard_Node
4199 (Compile_Time_Constraint_Error
4200 (N => N,
4201 Msg =>
4202 "(Ada 2005) null-excluding array components must "
4203 & "be initialized??",
4204 Ent => Defining_Identifier (N)));
4206 -- Normal case of object of a null-excluding access type
4208 else
4209 -- Add an expression that assigns null. This node is needed by
4210 -- Apply_Compile_Time_Constraint_Error, which will replace this
4211 -- with a Constraint_Error node.
4213 Set_Expression (N, Make_Null (Sloc (N)));
4214 Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
4216 Apply_Compile_Time_Constraint_Error
4217 (N => Expression (N),
4218 Msg =>
4219 "(Ada 2005) null-excluding objects must be initialized??",
4220 Reason => CE_Null_Not_Allowed);
4221 end if;
4222 end if;
4224 -- Check that a null-excluding component, formal or object is not being
4225 -- assigned a null value. Otherwise generate a warning message and
4226 -- replace Expression (N) by an N_Constraint_Error node.
4228 if Kind /= N_Function_Specification then
4229 Expr := Expression (N);
4231 if Present (Expr) and then Known_Null (Expr) then
4232 case Kind is
4233 when N_Component_Declaration
4234 | N_Discriminant_Specification
4236 Apply_Compile_Time_Constraint_Error
4237 (N => Expr,
4238 Msg =>
4239 "(Ada 2005) null not allowed in null-excluding "
4240 & "components??",
4241 Reason => CE_Null_Not_Allowed);
4243 when N_Object_Declaration =>
4244 Apply_Compile_Time_Constraint_Error
4245 (N => Expr,
4246 Msg =>
4247 "(Ada 2005) null not allowed in null-excluding "
4248 & "objects??",
4249 Reason => CE_Null_Not_Allowed);
4251 when N_Parameter_Specification =>
4252 Apply_Compile_Time_Constraint_Error
4253 (N => Expr,
4254 Msg =>
4255 "(Ada 2005) null not allowed in null-excluding "
4256 & "formals??",
4257 Reason => CE_Null_Not_Allowed);
4259 when others =>
4260 null;
4261 end case;
4262 end if;
4263 end if;
4264 end Null_Exclusion_Static_Checks;
4266 ----------------------------------
4267 -- Conditional_Statements_Begin --
4268 ----------------------------------
4270 procedure Conditional_Statements_Begin is
4271 begin
4272 Saved_Checks_TOS := Saved_Checks_TOS + 1;
4274 -- If stack overflows, kill all checks, that way we know to simply reset
4275 -- the number of saved checks to zero on return. This should never occur
4276 -- in practice.
4278 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4279 Kill_All_Checks;
4281 -- In the normal case, we just make a new stack entry saving the current
4282 -- number of saved checks for a later restore.
4284 else
4285 Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
4287 if Debug_Flag_CC then
4288 w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
4289 Num_Saved_Checks);
4290 end if;
4291 end if;
4292 end Conditional_Statements_Begin;
4294 --------------------------------
4295 -- Conditional_Statements_End --
4296 --------------------------------
4298 procedure Conditional_Statements_End is
4299 begin
4300 pragma Assert (Saved_Checks_TOS > 0);
4302 -- If the saved checks stack overflowed, then we killed all checks, so
4303 -- setting the number of saved checks back to zero is correct. This
4304 -- should never occur in practice.
4306 if Saved_Checks_TOS > Saved_Checks_Stack'Last then
4307 Num_Saved_Checks := 0;
4309 -- In the normal case, restore the number of saved checks from the top
4310 -- stack entry.
4312 else
4313 Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
4315 if Debug_Flag_CC then
4316 w ("Conditional_Statements_End: Num_Saved_Checks = ",
4317 Num_Saved_Checks);
4318 end if;
4319 end if;
4321 Saved_Checks_TOS := Saved_Checks_TOS - 1;
4322 end Conditional_Statements_End;
4324 -------------------------
4325 -- Convert_From_Bignum --
4326 -------------------------
4328 function Convert_From_Bignum (N : Node_Id) return Node_Id is
4329 Loc : constant Source_Ptr := Sloc (N);
4331 begin
4332 pragma Assert (Is_RTE (Etype (N), RE_Bignum));
4334 -- Construct call From Bignum
4336 return
4337 Make_Function_Call (Loc,
4338 Name =>
4339 New_Occurrence_Of (RTE (RE_From_Bignum), Loc),
4340 Parameter_Associations => New_List (Relocate_Node (N)));
4341 end Convert_From_Bignum;
4343 -----------------------
4344 -- Convert_To_Bignum --
4345 -----------------------
4347 function Convert_To_Bignum (N : Node_Id) return Node_Id is
4348 Loc : constant Source_Ptr := Sloc (N);
4350 begin
4351 -- Nothing to do if Bignum already except call Relocate_Node
4353 if Is_RTE (Etype (N), RE_Bignum) then
4354 return Relocate_Node (N);
4356 -- Otherwise construct call to To_Bignum, converting the operand to the
4357 -- required Long_Long_Integer form.
4359 else
4360 pragma Assert (Is_Signed_Integer_Type (Etype (N)));
4361 return
4362 Make_Function_Call (Loc,
4363 Name =>
4364 New_Occurrence_Of (RTE (RE_To_Bignum), Loc),
4365 Parameter_Associations => New_List (
4366 Convert_To (Standard_Long_Long_Integer, Relocate_Node (N))));
4367 end if;
4368 end Convert_To_Bignum;
4370 ---------------------
4371 -- Determine_Range --
4372 ---------------------
4374 Cache_Size : constant := 2 ** 10;
4375 type Cache_Index is range 0 .. Cache_Size - 1;
4376 -- Determine size of below cache (power of 2 is more efficient)
4378 Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
4379 Determine_Range_Cache_V : array (Cache_Index) of Boolean;
4380 Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
4381 Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
4382 Determine_Range_Cache_Lo_R : array (Cache_Index) of Ureal;
4383 Determine_Range_Cache_Hi_R : array (Cache_Index) of Ureal;
4384 -- The above arrays are used to implement a small direct cache for
4385 -- Determine_Range and Determine_Range_R calls. Because of the way these
4386 -- subprograms recursively traces subexpressions, and because overflow
4387 -- checking calls the routine on the way up the tree, a quadratic behavior
4388 -- can otherwise be encountered in large expressions. The cache entry for
4389 -- node N is stored in the (N mod Cache_Size) entry, and can be validated
4390 -- by checking the actual node value stored there. The Range_Cache_V array
4391 -- records the setting of Assume_Valid for the cache entry.
4393 procedure Determine_Range
4394 (N : Node_Id;
4395 OK : out Boolean;
4396 Lo : out Uint;
4397 Hi : out Uint;
4398 Assume_Valid : Boolean := False)
4400 Typ : Entity_Id := Etype (N);
4401 -- Type to use, may get reset to base type for possibly invalid entity
4403 Lo_Left : Uint;
4404 Hi_Left : Uint;
4405 -- Lo and Hi bounds of left operand
4407 Lo_Right : Uint := No_Uint;
4408 Hi_Right : Uint := No_Uint;
4409 -- Lo and Hi bounds of right (or only) operand
4411 Bound : Node_Id;
4412 -- Temp variable used to hold a bound node
4414 Hbound : Uint;
4415 -- High bound of base type of expression
4417 Lor : Uint;
4418 Hir : Uint;
4419 -- Refined values for low and high bounds, after tightening
4421 OK1 : Boolean;
4422 -- Used in lower level calls to indicate if call succeeded
4424 Cindex : Cache_Index;
4425 -- Used to search cache
4427 Btyp : Entity_Id;
4428 -- Base type
4430 function OK_Operands return Boolean;
4431 -- Used for binary operators. Determines the ranges of the left and
4432 -- right operands, and if they are both OK, returns True, and puts
4433 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4435 -----------------
4436 -- OK_Operands --
4437 -----------------
4439 function OK_Operands return Boolean is
4440 begin
4441 Determine_Range
4442 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4444 if not OK1 then
4445 return False;
4446 end if;
4448 Determine_Range
4449 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4450 return OK1;
4451 end OK_Operands;
4453 -- Start of processing for Determine_Range
4455 begin
4456 -- Prevent junk warnings by initializing range variables
4458 Lo := No_Uint;
4459 Hi := No_Uint;
4460 Lor := No_Uint;
4461 Hir := No_Uint;
4463 -- For temporary constants internally generated to remove side effects
4464 -- we must use the corresponding expression to determine the range of
4465 -- the expression. But note that the expander can also generate
4466 -- constants in other cases, including deferred constants.
4468 if Is_Entity_Name (N)
4469 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
4470 and then Ekind (Entity (N)) = E_Constant
4471 and then Is_Internal_Name (Chars (Entity (N)))
4472 then
4473 if Present (Expression (Parent (Entity (N)))) then
4474 Determine_Range
4475 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
4477 elsif Present (Full_View (Entity (N))) then
4478 Determine_Range
4479 (Expression (Parent (Full_View (Entity (N)))),
4480 OK, Lo, Hi, Assume_Valid);
4482 else
4483 OK := False;
4484 end if;
4485 return;
4486 end if;
4488 -- If type is not defined, we can't determine its range
4490 if No (Typ)
4492 -- We don't deal with anything except discrete types
4494 or else not Is_Discrete_Type (Typ)
4496 -- Ignore type for which an error has been posted, since range in
4497 -- this case may well be a bogosity deriving from the error. Also
4498 -- ignore if error posted on the reference node.
4500 or else Error_Posted (N) or else Error_Posted (Typ)
4501 then
4502 OK := False;
4503 return;
4504 end if;
4506 -- For all other cases, we can determine the range
4508 OK := True;
4510 -- If value is compile time known, then the possible range is the one
4511 -- value that we know this expression definitely has.
4513 if Compile_Time_Known_Value (N) then
4514 Lo := Expr_Value (N);
4515 Hi := Lo;
4516 return;
4517 end if;
4519 -- Return if already in the cache
4521 Cindex := Cache_Index (N mod Cache_Size);
4523 if Determine_Range_Cache_N (Cindex) = N
4524 and then
4525 Determine_Range_Cache_V (Cindex) = Assume_Valid
4526 then
4527 Lo := Determine_Range_Cache_Lo (Cindex);
4528 Hi := Determine_Range_Cache_Hi (Cindex);
4529 return;
4530 end if;
4532 -- Otherwise, start by finding the bounds of the type of the expression,
4533 -- the value cannot be outside this range (if it is, then we have an
4534 -- overflow situation, which is a separate check, we are talking here
4535 -- only about the expression value).
4537 -- First a check, never try to find the bounds of a generic type, since
4538 -- these bounds are always junk values, and it is only valid to look at
4539 -- the bounds in an instance.
4541 if Is_Generic_Type (Typ) then
4542 OK := False;
4543 return;
4544 end if;
4546 -- First step, change to use base type unless we know the value is valid
4548 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
4549 or else Assume_No_Invalid_Values
4550 or else Assume_Valid
4551 then
4552 null;
4553 else
4554 Typ := Underlying_Type (Base_Type (Typ));
4555 end if;
4557 -- Retrieve the base type. Handle the case where the base type is a
4558 -- private enumeration type.
4560 Btyp := Base_Type (Typ);
4562 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
4563 Btyp := Full_View (Btyp);
4564 end if;
4566 -- We use the actual bound unless it is dynamic, in which case use the
4567 -- corresponding base type bound if possible. If we can't get a bound
4568 -- then we figure we can't determine the range (a peculiar case, that
4569 -- perhaps cannot happen, but there is no point in bombing in this
4570 -- optimization circuit.
4572 -- First the low bound
4574 Bound := Type_Low_Bound (Typ);
4576 if Compile_Time_Known_Value (Bound) then
4577 Lo := Expr_Value (Bound);
4579 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
4580 Lo := Expr_Value (Type_Low_Bound (Btyp));
4582 else
4583 OK := False;
4584 return;
4585 end if;
4587 -- Now the high bound
4589 Bound := Type_High_Bound (Typ);
4591 -- We need the high bound of the base type later on, and this should
4592 -- always be compile time known. Again, it is not clear that this
4593 -- can ever be false, but no point in bombing.
4595 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
4596 Hbound := Expr_Value (Type_High_Bound (Btyp));
4597 Hi := Hbound;
4599 else
4600 OK := False;
4601 return;
4602 end if;
4604 -- If we have a static subtype, then that may have a tighter bound so
4605 -- use the upper bound of the subtype instead in this case.
4607 if Compile_Time_Known_Value (Bound) then
4608 Hi := Expr_Value (Bound);
4609 end if;
4611 -- We may be able to refine this value in certain situations. If any
4612 -- refinement is possible, then Lor and Hir are set to possibly tighter
4613 -- bounds, and OK1 is set to True.
4615 case Nkind (N) is
4617 -- For unary plus, result is limited by range of operand
4619 when N_Op_Plus =>
4620 Determine_Range
4621 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
4623 -- For unary minus, determine range of operand, and negate it
4625 when N_Op_Minus =>
4626 Determine_Range
4627 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4629 if OK1 then
4630 Lor := -Hi_Right;
4631 Hir := -Lo_Right;
4632 end if;
4634 -- For binary addition, get range of each operand and do the
4635 -- addition to get the result range.
4637 when N_Op_Add =>
4638 if OK_Operands then
4639 Lor := Lo_Left + Lo_Right;
4640 Hir := Hi_Left + Hi_Right;
4641 end if;
4643 -- Division is tricky. The only case we consider is where the right
4644 -- operand is a positive constant, and in this case we simply divide
4645 -- the bounds of the left operand
4647 when N_Op_Divide =>
4648 if OK_Operands then
4649 if Lo_Right = Hi_Right
4650 and then Lo_Right > 0
4651 then
4652 Lor := Lo_Left / Lo_Right;
4653 Hir := Hi_Left / Lo_Right;
4654 else
4655 OK1 := False;
4656 end if;
4657 end if;
4659 -- For binary subtraction, get range of each operand and do the worst
4660 -- case subtraction to get the result range.
4662 when N_Op_Subtract =>
4663 if OK_Operands then
4664 Lor := Lo_Left - Hi_Right;
4665 Hir := Hi_Left - Lo_Right;
4666 end if;
4668 -- For MOD, if right operand is a positive constant, then result must
4669 -- be in the allowable range of mod results.
4671 when N_Op_Mod =>
4672 if OK_Operands then
4673 if Lo_Right = Hi_Right
4674 and then Lo_Right /= 0
4675 then
4676 if Lo_Right > 0 then
4677 Lor := Uint_0;
4678 Hir := Lo_Right - 1;
4680 else -- Lo_Right < 0
4681 Lor := Lo_Right + 1;
4682 Hir := Uint_0;
4683 end if;
4685 else
4686 OK1 := False;
4687 end if;
4688 end if;
4690 -- For REM, if right operand is a positive constant, then result must
4691 -- be in the allowable range of mod results.
4693 when N_Op_Rem =>
4694 if OK_Operands then
4695 if Lo_Right = Hi_Right and then Lo_Right /= 0 then
4696 declare
4697 Dval : constant Uint := (abs Lo_Right) - 1;
4699 begin
4700 -- The sign of the result depends on the sign of the
4701 -- dividend (but not on the sign of the divisor, hence
4702 -- the abs operation above).
4704 if Lo_Left < 0 then
4705 Lor := -Dval;
4706 else
4707 Lor := Uint_0;
4708 end if;
4710 if Hi_Left < 0 then
4711 Hir := Uint_0;
4712 else
4713 Hir := Dval;
4714 end if;
4715 end;
4717 else
4718 OK1 := False;
4719 end if;
4720 end if;
4722 -- Attribute reference cases
4724 when N_Attribute_Reference =>
4725 case Attribute_Name (N) is
4727 -- For Pos/Val attributes, we can refine the range using the
4728 -- possible range of values of the attribute expression.
4730 when Name_Pos
4731 | Name_Val
4733 Determine_Range
4734 (First (Expressions (N)), OK1, Lor, Hir, Assume_Valid);
4736 -- For Length attribute, use the bounds of the corresponding
4737 -- index type to refine the range.
4739 when Name_Length =>
4740 declare
4741 Atyp : Entity_Id := Etype (Prefix (N));
4742 Inum : Nat;
4743 Indx : Node_Id;
4745 LL, LU : Uint;
4746 UL, UU : Uint;
4748 begin
4749 if Is_Access_Type (Atyp) then
4750 Atyp := Designated_Type (Atyp);
4751 end if;
4753 -- For string literal, we know exact value
4755 if Ekind (Atyp) = E_String_Literal_Subtype then
4756 OK := True;
4757 Lo := String_Literal_Length (Atyp);
4758 Hi := String_Literal_Length (Atyp);
4759 return;
4760 end if;
4762 -- Otherwise check for expression given
4764 if No (Expressions (N)) then
4765 Inum := 1;
4766 else
4767 Inum :=
4768 UI_To_Int (Expr_Value (First (Expressions (N))));
4769 end if;
4771 Indx := First_Index (Atyp);
4772 for J in 2 .. Inum loop
4773 Indx := Next_Index (Indx);
4774 end loop;
4776 -- If the index type is a formal type or derived from
4777 -- one, the bounds are not static.
4779 if Is_Generic_Type (Root_Type (Etype (Indx))) then
4780 OK := False;
4781 return;
4782 end if;
4784 Determine_Range
4785 (Type_Low_Bound (Etype (Indx)), OK1, LL, LU,
4786 Assume_Valid);
4788 if OK1 then
4789 Determine_Range
4790 (Type_High_Bound (Etype (Indx)), OK1, UL, UU,
4791 Assume_Valid);
4793 if OK1 then
4795 -- The maximum value for Length is the biggest
4796 -- possible gap between the values of the bounds.
4797 -- But of course, this value cannot be negative.
4799 Hir := UI_Max (Uint_0, UU - LL + 1);
4801 -- For constrained arrays, the minimum value for
4802 -- Length is taken from the actual value of the
4803 -- bounds, since the index will be exactly of this
4804 -- subtype.
4806 if Is_Constrained (Atyp) then
4807 Lor := UI_Max (Uint_0, UL - LU + 1);
4809 -- For an unconstrained array, the minimum value
4810 -- for length is always zero.
4812 else
4813 Lor := Uint_0;
4814 end if;
4815 end if;
4816 end if;
4817 end;
4819 -- No special handling for other attributes
4820 -- Probably more opportunities exist here???
4822 when others =>
4823 OK1 := False;
4825 end case;
4827 when N_Type_Conversion =>
4829 -- For type conversion from one discrete type to another, we can
4830 -- refine the range using the converted value.
4832 if Is_Discrete_Type (Etype (Expression (N))) then
4833 Determine_Range (Expression (N), OK1, Lor, Hir, Assume_Valid);
4835 -- When converting a float to an integer type, determine the range
4836 -- in real first, and then convert the bounds using UR_To_Uint
4837 -- which correctly rounds away from zero when half way between two
4838 -- integers, as required by normal Ada 95 rounding semantics. It
4839 -- is only possible because analysis in GNATprove rules out the
4840 -- possibility of a NaN or infinite value.
4842 elsif GNATprove_Mode
4843 and then Is_Floating_Point_Type (Etype (Expression (N)))
4844 then
4845 declare
4846 Lor_Real, Hir_Real : Ureal;
4847 begin
4848 Determine_Range_R (Expression (N), OK1, Lor_Real, Hir_Real,
4849 Assume_Valid);
4851 if OK1 then
4852 Lor := UR_To_Uint (Lor_Real);
4853 Hir := UR_To_Uint (Hir_Real);
4854 end if;
4855 end;
4857 else
4858 OK1 := False;
4859 end if;
4861 -- Nothing special to do for all other expression kinds
4863 when others =>
4864 OK1 := False;
4865 Lor := No_Uint;
4866 Hir := No_Uint;
4867 end case;
4869 -- At this stage, if OK1 is true, then we know that the actual result of
4870 -- the computed expression is in the range Lor .. Hir. We can use this
4871 -- to restrict the possible range of results.
4873 if OK1 then
4875 -- If the refined value of the low bound is greater than the type
4876 -- low bound, then reset it to the more restrictive value. However,
4877 -- we do NOT do this for the case of a modular type where the
4878 -- possible upper bound on the value is above the base type high
4879 -- bound, because that means the result could wrap.
4881 if Lor > Lo
4882 and then not (Is_Modular_Integer_Type (Typ) and then Hir > Hbound)
4883 then
4884 Lo := Lor;
4885 end if;
4887 -- Similarly, if the refined value of the high bound is less than the
4888 -- value so far, then reset it to the more restrictive value. Again,
4889 -- we do not do this if the refined low bound is negative for a
4890 -- modular type, since this would wrap.
4892 if Hir < Hi
4893 and then not (Is_Modular_Integer_Type (Typ) and then Lor < Uint_0)
4894 then
4895 Hi := Hir;
4896 end if;
4897 end if;
4899 -- Set cache entry for future call and we are all done
4901 Determine_Range_Cache_N (Cindex) := N;
4902 Determine_Range_Cache_V (Cindex) := Assume_Valid;
4903 Determine_Range_Cache_Lo (Cindex) := Lo;
4904 Determine_Range_Cache_Hi (Cindex) := Hi;
4905 return;
4907 -- If any exception occurs, it means that we have some bug in the compiler,
4908 -- possibly triggered by a previous error, or by some unforeseen peculiar
4909 -- occurrence. However, this is only an optimization attempt, so there is
4910 -- really no point in crashing the compiler. Instead we just decide, too
4911 -- bad, we can't figure out a range in this case after all.
4913 exception
4914 when others =>
4916 -- Debug flag K disables this behavior (useful for debugging)
4918 if Debug_Flag_K then
4919 raise;
4920 else
4921 OK := False;
4922 Lo := No_Uint;
4923 Hi := No_Uint;
4924 return;
4925 end if;
4926 end Determine_Range;
4928 -----------------------
4929 -- Determine_Range_R --
4930 -----------------------
4932 procedure Determine_Range_R
4933 (N : Node_Id;
4934 OK : out Boolean;
4935 Lo : out Ureal;
4936 Hi : out Ureal;
4937 Assume_Valid : Boolean := False)
4939 Typ : Entity_Id := Etype (N);
4940 -- Type to use, may get reset to base type for possibly invalid entity
4942 Lo_Left : Ureal;
4943 Hi_Left : Ureal;
4944 -- Lo and Hi bounds of left operand
4946 Lo_Right : Ureal := No_Ureal;
4947 Hi_Right : Ureal := No_Ureal;
4948 -- Lo and Hi bounds of right (or only) operand
4950 Bound : Node_Id;
4951 -- Temp variable used to hold a bound node
4953 Hbound : Ureal;
4954 -- High bound of base type of expression
4956 Lor : Ureal;
4957 Hir : Ureal;
4958 -- Refined values for low and high bounds, after tightening
4960 OK1 : Boolean;
4961 -- Used in lower level calls to indicate if call succeeded
4963 Cindex : Cache_Index;
4964 -- Used to search cache
4966 Btyp : Entity_Id;
4967 -- Base type
4969 function OK_Operands return Boolean;
4970 -- Used for binary operators. Determines the ranges of the left and
4971 -- right operands, and if they are both OK, returns True, and puts
4972 -- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left.
4974 function Round_Machine (B : Ureal) return Ureal;
4975 -- B is a real bound. Round it using mode Round_Even.
4977 -----------------
4978 -- OK_Operands --
4979 -----------------
4981 function OK_Operands return Boolean is
4982 begin
4983 Determine_Range_R
4984 (Left_Opnd (N), OK1, Lo_Left, Hi_Left, Assume_Valid);
4986 if not OK1 then
4987 return False;
4988 end if;
4990 Determine_Range_R
4991 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
4992 return OK1;
4993 end OK_Operands;
4995 -------------------
4996 -- Round_Machine --
4997 -------------------
4999 function Round_Machine (B : Ureal) return Ureal is
5000 begin
5001 return Machine (Typ, B, Round_Even, N);
5002 end Round_Machine;
5004 -- Start of processing for Determine_Range_R
5006 begin
5007 -- Prevent junk warnings by initializing range variables
5009 Lo := No_Ureal;
5010 Hi := No_Ureal;
5011 Lor := No_Ureal;
5012 Hir := No_Ureal;
5014 -- For temporary constants internally generated to remove side effects
5015 -- we must use the corresponding expression to determine the range of
5016 -- the expression. But note that the expander can also generate
5017 -- constants in other cases, including deferred constants.
5019 if Is_Entity_Name (N)
5020 and then Nkind (Parent (Entity (N))) = N_Object_Declaration
5021 and then Ekind (Entity (N)) = E_Constant
5022 and then Is_Internal_Name (Chars (Entity (N)))
5023 then
5024 if Present (Expression (Parent (Entity (N)))) then
5025 Determine_Range_R
5026 (Expression (Parent (Entity (N))), OK, Lo, Hi, Assume_Valid);
5028 elsif Present (Full_View (Entity (N))) then
5029 Determine_Range_R
5030 (Expression (Parent (Full_View (Entity (N)))),
5031 OK, Lo, Hi, Assume_Valid);
5033 else
5034 OK := False;
5035 end if;
5037 return;
5038 end if;
5040 -- If type is not defined, we can't determine its range
5042 if No (Typ)
5044 -- We don't deal with anything except IEEE floating-point types
5046 or else not Is_Floating_Point_Type (Typ)
5047 or else Float_Rep (Typ) /= IEEE_Binary
5049 -- Ignore type for which an error has been posted, since range in
5050 -- this case may well be a bogosity deriving from the error. Also
5051 -- ignore if error posted on the reference node.
5053 or else Error_Posted (N) or else Error_Posted (Typ)
5054 then
5055 OK := False;
5056 return;
5057 end if;
5059 -- For all other cases, we can determine the range
5061 OK := True;
5063 -- If value is compile time known, then the possible range is the one
5064 -- value that we know this expression definitely has.
5066 if Compile_Time_Known_Value (N) then
5067 Lo := Expr_Value_R (N);
5068 Hi := Lo;
5069 return;
5070 end if;
5072 -- Return if already in the cache
5074 Cindex := Cache_Index (N mod Cache_Size);
5076 if Determine_Range_Cache_N (Cindex) = N
5077 and then
5078 Determine_Range_Cache_V (Cindex) = Assume_Valid
5079 then
5080 Lo := Determine_Range_Cache_Lo_R (Cindex);
5081 Hi := Determine_Range_Cache_Hi_R (Cindex);
5082 return;
5083 end if;
5085 -- Otherwise, start by finding the bounds of the type of the expression,
5086 -- the value cannot be outside this range (if it is, then we have an
5087 -- overflow situation, which is a separate check, we are talking here
5088 -- only about the expression value).
5090 -- First a check, never try to find the bounds of a generic type, since
5091 -- these bounds are always junk values, and it is only valid to look at
5092 -- the bounds in an instance.
5094 if Is_Generic_Type (Typ) then
5095 OK := False;
5096 return;
5097 end if;
5099 -- First step, change to use base type unless we know the value is valid
5101 if (Is_Entity_Name (N) and then Is_Known_Valid (Entity (N)))
5102 or else Assume_No_Invalid_Values
5103 or else Assume_Valid
5104 then
5105 null;
5106 else
5107 Typ := Underlying_Type (Base_Type (Typ));
5108 end if;
5110 -- Retrieve the base type. Handle the case where the base type is a
5111 -- private type.
5113 Btyp := Base_Type (Typ);
5115 if Is_Private_Type (Btyp) and then Present (Full_View (Btyp)) then
5116 Btyp := Full_View (Btyp);
5117 end if;
5119 -- We use the actual bound unless it is dynamic, in which case use the
5120 -- corresponding base type bound if possible. If we can't get a bound
5121 -- then we figure we can't determine the range (a peculiar case, that
5122 -- perhaps cannot happen, but there is no point in bombing in this
5123 -- optimization circuit).
5125 -- First the low bound
5127 Bound := Type_Low_Bound (Typ);
5129 if Compile_Time_Known_Value (Bound) then
5130 Lo := Expr_Value_R (Bound);
5132 elsif Compile_Time_Known_Value (Type_Low_Bound (Btyp)) then
5133 Lo := Expr_Value_R (Type_Low_Bound (Btyp));
5135 else
5136 OK := False;
5137 return;
5138 end if;
5140 -- Now the high bound
5142 Bound := Type_High_Bound (Typ);
5144 -- We need the high bound of the base type later on, and this should
5145 -- always be compile time known. Again, it is not clear that this
5146 -- can ever be false, but no point in bombing.
5148 if Compile_Time_Known_Value (Type_High_Bound (Btyp)) then
5149 Hbound := Expr_Value_R (Type_High_Bound (Btyp));
5150 Hi := Hbound;
5152 else
5153 OK := False;
5154 return;
5155 end if;
5157 -- If we have a static subtype, then that may have a tighter bound so
5158 -- use the upper bound of the subtype instead in this case.
5160 if Compile_Time_Known_Value (Bound) then
5161 Hi := Expr_Value_R (Bound);
5162 end if;
5164 -- We may be able to refine this value in certain situations. If any
5165 -- refinement is possible, then Lor and Hir are set to possibly tighter
5166 -- bounds, and OK1 is set to True.
5168 case Nkind (N) is
5170 -- For unary plus, result is limited by range of operand
5172 when N_Op_Plus =>
5173 Determine_Range_R
5174 (Right_Opnd (N), OK1, Lor, Hir, Assume_Valid);
5176 -- For unary minus, determine range of operand, and negate it
5178 when N_Op_Minus =>
5179 Determine_Range_R
5180 (Right_Opnd (N), OK1, Lo_Right, Hi_Right, Assume_Valid);
5182 if OK1 then
5183 Lor := -Hi_Right;
5184 Hir := -Lo_Right;
5185 end if;
5187 -- For binary addition, get range of each operand and do the
5188 -- addition to get the result range.
5190 when N_Op_Add =>
5191 if OK_Operands then
5192 Lor := Round_Machine (Lo_Left + Lo_Right);
5193 Hir := Round_Machine (Hi_Left + Hi_Right);
5194 end if;
5196 -- For binary subtraction, get range of each operand and do the worst
5197 -- case subtraction to get the result range.
5199 when N_Op_Subtract =>
5200 if OK_Operands then
5201 Lor := Round_Machine (Lo_Left - Hi_Right);
5202 Hir := Round_Machine (Hi_Left - Lo_Right);
5203 end if;
5205 -- For multiplication, get range of each operand and do the
5206 -- four multiplications to get the result range.
5208 when N_Op_Multiply =>
5209 if OK_Operands then
5210 declare
5211 M1 : constant Ureal := Round_Machine (Lo_Left * Lo_Right);
5212 M2 : constant Ureal := Round_Machine (Lo_Left * Hi_Right);
5213 M3 : constant Ureal := Round_Machine (Hi_Left * Lo_Right);
5214 M4 : constant Ureal := Round_Machine (Hi_Left * Hi_Right);
5216 begin
5217 Lor := UR_Min (UR_Min (M1, M2), UR_Min (M3, M4));
5218 Hir := UR_Max (UR_Max (M1, M2), UR_Max (M3, M4));
5219 end;
5220 end if;
5222 -- For division, consider separately the cases where the right
5223 -- operand is positive or negative. Otherwise, the right operand
5224 -- can be arbitrarily close to zero, so the result is likely to
5225 -- be unbounded in one direction, do not attempt to compute it.
5227 when N_Op_Divide =>
5228 if OK_Operands then
5230 -- Right operand is positive
5232 if Lo_Right > Ureal_0 then
5234 -- If the low bound of the left operand is negative, obtain
5235 -- the overall low bound by dividing it by the smallest
5236 -- value of the right operand, and otherwise by the largest
5237 -- value of the right operand.
5239 if Lo_Left < Ureal_0 then
5240 Lor := Round_Machine (Lo_Left / Lo_Right);
5241 else
5242 Lor := Round_Machine (Lo_Left / Hi_Right);
5243 end if;
5245 -- If the high bound of the left operand is negative, obtain
5246 -- the overall high bound by dividing it by the largest
5247 -- value of the right operand, and otherwise by the
5248 -- smallest value of the right operand.
5250 if Hi_Left < Ureal_0 then
5251 Hir := Round_Machine (Hi_Left / Hi_Right);
5252 else
5253 Hir := Round_Machine (Hi_Left / Lo_Right);
5254 end if;
5256 -- Right operand is negative
5258 elsif Hi_Right < Ureal_0 then
5260 -- If the low bound of the left operand is negative, obtain
5261 -- the overall low bound by dividing it by the largest
5262 -- value of the right operand, and otherwise by the smallest
5263 -- value of the right operand.
5265 if Lo_Left < Ureal_0 then
5266 Lor := Round_Machine (Lo_Left / Hi_Right);
5267 else
5268 Lor := Round_Machine (Lo_Left / Lo_Right);
5269 end if;
5271 -- If the high bound of the left operand is negative, obtain
5272 -- the overall high bound by dividing it by the smallest
5273 -- value of the right operand, and otherwise by the
5274 -- largest value of the right operand.
5276 if Hi_Left < Ureal_0 then
5277 Hir := Round_Machine (Hi_Left / Lo_Right);
5278 else
5279 Hir := Round_Machine (Hi_Left / Hi_Right);
5280 end if;
5282 else
5283 OK1 := False;
5284 end if;
5285 end if;
5287 when N_Type_Conversion =>
5289 -- For type conversion from one floating-point type to another, we
5290 -- can refine the range using the converted value.
5292 if Is_Floating_Point_Type (Etype (Expression (N))) then
5293 Determine_Range_R (Expression (N), OK1, Lor, Hir, Assume_Valid);
5295 -- When converting an integer to a floating-point type, determine
5296 -- the range in integer first, and then convert the bounds.
5298 elsif Is_Discrete_Type (Etype (Expression (N))) then
5299 declare
5300 Hir_Int : Uint;
5301 Lor_Int : Uint;
5303 begin
5304 Determine_Range
5305 (Expression (N), OK1, Lor_Int, Hir_Int, Assume_Valid);
5307 if OK1 then
5308 Lor := Round_Machine (UR_From_Uint (Lor_Int));
5309 Hir := Round_Machine (UR_From_Uint (Hir_Int));
5310 end if;
5311 end;
5313 else
5314 OK1 := False;
5315 end if;
5317 -- Nothing special to do for all other expression kinds
5319 when others =>
5320 OK1 := False;
5321 Lor := No_Ureal;
5322 Hir := No_Ureal;
5323 end case;
5325 -- At this stage, if OK1 is true, then we know that the actual result of
5326 -- the computed expression is in the range Lor .. Hir. We can use this
5327 -- to restrict the possible range of results.
5329 if OK1 then
5331 -- If the refined value of the low bound is greater than the type
5332 -- low bound, then reset it to the more restrictive value.
5334 if Lor > Lo then
5335 Lo := Lor;
5336 end if;
5338 -- Similarly, if the refined value of the high bound is less than the
5339 -- value so far, then reset it to the more restrictive value.
5341 if Hir < Hi then
5342 Hi := Hir;
5343 end if;
5344 end if;
5346 -- Set cache entry for future call and we are all done
5348 Determine_Range_Cache_N (Cindex) := N;
5349 Determine_Range_Cache_V (Cindex) := Assume_Valid;
5350 Determine_Range_Cache_Lo_R (Cindex) := Lo;
5351 Determine_Range_Cache_Hi_R (Cindex) := Hi;
5352 return;
5354 -- If any exception occurs, it means that we have some bug in the compiler,
5355 -- possibly triggered by a previous error, or by some unforeseen peculiar
5356 -- occurrence. However, this is only an optimization attempt, so there is
5357 -- really no point in crashing the compiler. Instead we just decide, too
5358 -- bad, we can't figure out a range in this case after all.
5360 exception
5361 when others =>
5363 -- Debug flag K disables this behavior (useful for debugging)
5365 if Debug_Flag_K then
5366 raise;
5367 else
5368 OK := False;
5369 Lo := No_Ureal;
5370 Hi := No_Ureal;
5371 return;
5372 end if;
5373 end Determine_Range_R;
5375 ------------------------------------
5376 -- Discriminant_Checks_Suppressed --
5377 ------------------------------------
5379 function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
5380 begin
5381 if Present (E) then
5382 if Is_Unchecked_Union (E) then
5383 return True;
5384 elsif Checks_May_Be_Suppressed (E) then
5385 return Is_Check_Suppressed (E, Discriminant_Check);
5386 end if;
5387 end if;
5389 return Scope_Suppress.Suppress (Discriminant_Check);
5390 end Discriminant_Checks_Suppressed;
5392 --------------------------------
5393 -- Division_Checks_Suppressed --
5394 --------------------------------
5396 function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
5397 begin
5398 if Present (E) and then Checks_May_Be_Suppressed (E) then
5399 return Is_Check_Suppressed (E, Division_Check);
5400 else
5401 return Scope_Suppress.Suppress (Division_Check);
5402 end if;
5403 end Division_Checks_Suppressed;
5405 --------------------------------------
5406 -- Duplicated_Tag_Checks_Suppressed --
5407 --------------------------------------
5409 function Duplicated_Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
5410 begin
5411 if Present (E) and then Checks_May_Be_Suppressed (E) then
5412 return Is_Check_Suppressed (E, Duplicated_Tag_Check);
5413 else
5414 return Scope_Suppress.Suppress (Duplicated_Tag_Check);
5415 end if;
5416 end Duplicated_Tag_Checks_Suppressed;
5418 -----------------------------------
5419 -- Elaboration_Checks_Suppressed --
5420 -----------------------------------
5422 function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
5423 begin
5424 -- The complication in this routine is that if we are in the dynamic
5425 -- model of elaboration, we also check All_Checks, since All_Checks
5426 -- does not set Elaboration_Check explicitly.
5428 if Present (E) then
5429 if Kill_Elaboration_Checks (E) then
5430 return True;
5432 elsif Checks_May_Be_Suppressed (E) then
5433 if Is_Check_Suppressed (E, Elaboration_Check) then
5434 return True;
5436 elsif Dynamic_Elaboration_Checks then
5437 return Is_Check_Suppressed (E, All_Checks);
5439 else
5440 return False;
5441 end if;
5442 end if;
5443 end if;
5445 if Scope_Suppress.Suppress (Elaboration_Check) then
5446 return True;
5448 elsif Dynamic_Elaboration_Checks then
5449 return Scope_Suppress.Suppress (All_Checks);
5451 else
5452 return False;
5453 end if;
5454 end Elaboration_Checks_Suppressed;
5456 ---------------------------
5457 -- Enable_Overflow_Check --
5458 ---------------------------
5460 procedure Enable_Overflow_Check (N : Node_Id) is
5461 Typ : constant Entity_Id := Base_Type (Etype (N));
5462 Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
5463 Chk : Nat;
5464 OK : Boolean;
5465 Ent : Entity_Id;
5466 Ofs : Uint;
5467 Lo : Uint;
5468 Hi : Uint;
5470 Do_Ovflow_Check : Boolean;
5472 begin
5473 if Debug_Flag_CC then
5474 w ("Enable_Overflow_Check for node ", Int (N));
5475 Write_Str (" Source location = ");
5476 wl (Sloc (N));
5477 pg (Union_Id (N));
5478 end if;
5480 -- No check if overflow checks suppressed for type of node
5482 if Overflow_Checks_Suppressed (Etype (N)) then
5483 return;
5485 -- Nothing to do for unsigned integer types, which do not overflow
5487 elsif Is_Modular_Integer_Type (Typ) then
5488 return;
5489 end if;
5491 -- This is the point at which processing for STRICT mode diverges
5492 -- from processing for MINIMIZED/ELIMINATED modes. This divergence is
5493 -- probably more extreme that it needs to be, but what is going on here
5494 -- is that when we introduced MINIMIZED/ELIMINATED modes, we wanted
5495 -- to leave the processing for STRICT mode untouched. There were
5496 -- two reasons for this. First it avoided any incompatible change of
5497 -- behavior. Second, it guaranteed that STRICT mode continued to be
5498 -- legacy reliable.
5500 -- The big difference is that in STRICT mode there is a fair amount of
5501 -- circuitry to try to avoid setting the Do_Overflow_Check flag if we
5502 -- know that no check is needed. We skip all that in the two new modes,
5503 -- since really overflow checking happens over a whole subtree, and we
5504 -- do the corresponding optimizations later on when applying the checks.
5506 if Mode in Minimized_Or_Eliminated then
5507 if not (Overflow_Checks_Suppressed (Etype (N)))
5508 and then not (Is_Entity_Name (N)
5509 and then Overflow_Checks_Suppressed (Entity (N)))
5510 then
5511 Activate_Overflow_Check (N);
5512 end if;
5514 if Debug_Flag_CC then
5515 w ("Minimized/Eliminated mode");
5516 end if;
5518 return;
5519 end if;
5521 -- Remainder of processing is for STRICT case, and is unchanged from
5522 -- earlier versions preceding the addition of MINIMIZED/ELIMINATED.
5524 -- Nothing to do if the range of the result is known OK. We skip this
5525 -- for conversions, since the caller already did the check, and in any
5526 -- case the condition for deleting the check for a type conversion is
5527 -- different.
5529 if Nkind (N) /= N_Type_Conversion then
5530 Determine_Range (N, OK, Lo, Hi, Assume_Valid => True);
5532 -- Note in the test below that we assume that the range is not OK
5533 -- if a bound of the range is equal to that of the type. That's not
5534 -- quite accurate but we do this for the following reasons:
5536 -- a) The way that Determine_Range works, it will typically report
5537 -- the bounds of the value as being equal to the bounds of the
5538 -- type, because it either can't tell anything more precise, or
5539 -- does not think it is worth the effort to be more precise.
5541 -- b) It is very unusual to have a situation in which this would
5542 -- generate an unnecessary overflow check (an example would be
5543 -- a subtype with a range 0 .. Integer'Last - 1 to which the
5544 -- literal value one is added).
5546 -- c) The alternative is a lot of special casing in this routine
5547 -- which would partially duplicate Determine_Range processing.
5549 if OK then
5550 Do_Ovflow_Check := True;
5552 -- Note that the following checks are quite deliberately > and <
5553 -- rather than >= and <= as explained above.
5555 if Lo > Expr_Value (Type_Low_Bound (Typ))
5556 and then
5557 Hi < Expr_Value (Type_High_Bound (Typ))
5558 then
5559 Do_Ovflow_Check := False;
5561 -- Despite the comments above, it is worth dealing specially with
5562 -- division specially. The only case where integer division can
5563 -- overflow is (largest negative number) / (-1). So we will do
5564 -- an extra range analysis to see if this is possible.
5566 elsif Nkind (N) = N_Op_Divide then
5567 Determine_Range
5568 (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5570 if OK and then Lo > Expr_Value (Type_Low_Bound (Typ)) then
5571 Do_Ovflow_Check := False;
5573 else
5574 Determine_Range
5575 (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True);
5577 if OK and then (Lo > Uint_Minus_1
5578 or else
5579 Hi < Uint_Minus_1)
5580 then
5581 Do_Ovflow_Check := False;
5582 end if;
5583 end if;
5584 end if;
5586 -- If no overflow check required, we are done
5588 if not Do_Ovflow_Check then
5589 if Debug_Flag_CC then
5590 w ("No overflow check required");
5591 end if;
5593 return;
5594 end if;
5595 end if;
5596 end if;
5598 -- If not in optimizing mode, set flag and we are done. We are also done
5599 -- (and just set the flag) if the type is not a discrete type, since it
5600 -- is not worth the effort to eliminate checks for other than discrete
5601 -- types. In addition, we take this same path if we have stored the
5602 -- maximum number of checks possible already (a very unlikely situation,
5603 -- but we do not want to blow up).
5605 if Optimization_Level = 0
5606 or else not Is_Discrete_Type (Etype (N))
5607 or else Num_Saved_Checks = Saved_Checks'Last
5608 then
5609 Activate_Overflow_Check (N);
5611 if Debug_Flag_CC then
5612 w ("Optimization off");
5613 end if;
5615 return;
5616 end if;
5618 -- Otherwise evaluate and check the expression
5620 Find_Check
5621 (Expr => N,
5622 Check_Type => 'O',
5623 Target_Type => Empty,
5624 Entry_OK => OK,
5625 Check_Num => Chk,
5626 Ent => Ent,
5627 Ofs => Ofs);
5629 if Debug_Flag_CC then
5630 w ("Called Find_Check");
5631 w (" OK = ", OK);
5633 if OK then
5634 w (" Check_Num = ", Chk);
5635 w (" Ent = ", Int (Ent));
5636 Write_Str (" Ofs = ");
5637 pid (Ofs);
5638 end if;
5639 end if;
5641 -- If check is not of form to optimize, then set flag and we are done
5643 if not OK then
5644 Activate_Overflow_Check (N);
5645 return;
5646 end if;
5648 -- If check is already performed, then return without setting flag
5650 if Chk /= 0 then
5651 if Debug_Flag_CC then
5652 w ("Check suppressed!");
5653 end if;
5655 return;
5656 end if;
5658 -- Here we will make a new entry for the new check
5660 Activate_Overflow_Check (N);
5661 Num_Saved_Checks := Num_Saved_Checks + 1;
5662 Saved_Checks (Num_Saved_Checks) :=
5663 (Killed => False,
5664 Entity => Ent,
5665 Offset => Ofs,
5666 Check_Type => 'O',
5667 Target_Type => Empty);
5669 if Debug_Flag_CC then
5670 w ("Make new entry, check number = ", Num_Saved_Checks);
5671 w (" Entity = ", Int (Ent));
5672 Write_Str (" Offset = ");
5673 pid (Ofs);
5674 w (" Check_Type = O");
5675 w (" Target_Type = Empty");
5676 end if;
5678 -- If we get an exception, then something went wrong, probably because of
5679 -- an error in the structure of the tree due to an incorrect program. Or
5680 -- it may be a bug in the optimization circuit. In either case the safest
5681 -- thing is simply to set the check flag unconditionally.
5683 exception
5684 when others =>
5685 Activate_Overflow_Check (N);
5687 if Debug_Flag_CC then
5688 w (" exception occurred, overflow flag set");
5689 end if;
5691 return;
5692 end Enable_Overflow_Check;
5694 ------------------------
5695 -- Enable_Range_Check --
5696 ------------------------
5698 procedure Enable_Range_Check (N : Node_Id) is
5699 Chk : Nat;
5700 OK : Boolean;
5701 Ent : Entity_Id;
5702 Ofs : Uint;
5703 Ttyp : Entity_Id;
5704 P : Node_Id;
5706 begin
5707 -- Return if unchecked type conversion with range check killed. In this
5708 -- case we never set the flag (that's what Kill_Range_Check is about).
5710 if Nkind (N) = N_Unchecked_Type_Conversion
5711 and then Kill_Range_Check (N)
5712 then
5713 return;
5714 end if;
5716 -- Do not set range check flag if parent is assignment statement or
5717 -- object declaration with Suppress_Assignment_Checks flag set
5719 if Nkind_In (Parent (N), N_Assignment_Statement, N_Object_Declaration)
5720 and then Suppress_Assignment_Checks (Parent (N))
5721 then
5722 return;
5723 end if;
5725 -- Check for various cases where we should suppress the range check
5727 -- No check if range checks suppressed for type of node
5729 if Present (Etype (N)) and then Range_Checks_Suppressed (Etype (N)) then
5730 return;
5732 -- No check if node is an entity name, and range checks are suppressed
5733 -- for this entity, or for the type of this entity.
5735 elsif Is_Entity_Name (N)
5736 and then (Range_Checks_Suppressed (Entity (N))
5737 or else Range_Checks_Suppressed (Etype (Entity (N))))
5738 then
5739 return;
5741 -- No checks if index of array, and index checks are suppressed for
5742 -- the array object or the type of the array.
5744 elsif Nkind (Parent (N)) = N_Indexed_Component then
5745 declare
5746 Pref : constant Node_Id := Prefix (Parent (N));
5747 begin
5748 if Is_Entity_Name (Pref)
5749 and then Index_Checks_Suppressed (Entity (Pref))
5750 then
5751 return;
5752 elsif Index_Checks_Suppressed (Etype (Pref)) then
5753 return;
5754 end if;
5755 end;
5756 end if;
5758 -- Debug trace output
5760 if Debug_Flag_CC then
5761 w ("Enable_Range_Check for node ", Int (N));
5762 Write_Str (" Source location = ");
5763 wl (Sloc (N));
5764 pg (Union_Id (N));
5765 end if;
5767 -- If not in optimizing mode, set flag and we are done. We are also done
5768 -- (and just set the flag) if the type is not a discrete type, since it
5769 -- is not worth the effort to eliminate checks for other than discrete
5770 -- types. In addition, we take this same path if we have stored the
5771 -- maximum number of checks possible already (a very unlikely situation,
5772 -- but we do not want to blow up).
5774 if Optimization_Level = 0
5775 or else No (Etype (N))
5776 or else not Is_Discrete_Type (Etype (N))
5777 or else Num_Saved_Checks = Saved_Checks'Last
5778 then
5779 Activate_Range_Check (N);
5781 if Debug_Flag_CC then
5782 w ("Optimization off");
5783 end if;
5785 return;
5786 end if;
5788 -- Otherwise find out the target type
5790 P := Parent (N);
5792 -- For assignment, use left side subtype
5794 if Nkind (P) = N_Assignment_Statement
5795 and then Expression (P) = N
5796 then
5797 Ttyp := Etype (Name (P));
5799 -- For indexed component, use subscript subtype
5801 elsif Nkind (P) = N_Indexed_Component then
5802 declare
5803 Atyp : Entity_Id;
5804 Indx : Node_Id;
5805 Subs : Node_Id;
5807 begin
5808 Atyp := Etype (Prefix (P));
5810 if Is_Access_Type (Atyp) then
5811 Atyp := Designated_Type (Atyp);
5813 -- If the prefix is an access to an unconstrained array,
5814 -- perform check unconditionally: it depends on the bounds of
5815 -- an object and we cannot currently recognize whether the test
5816 -- may be redundant.
5818 if not Is_Constrained (Atyp) then
5819 Activate_Range_Check (N);
5820 return;
5821 end if;
5823 -- Ditto if prefix is simply an unconstrained array. We used
5824 -- to think this case was OK, if the prefix was not an explicit
5825 -- dereference, but we have now seen a case where this is not
5826 -- true, so it is safer to just suppress the optimization in this
5827 -- case. The back end is getting better at eliminating redundant
5828 -- checks in any case, so the loss won't be important.
5830 elsif Is_Array_Type (Atyp)
5831 and then not Is_Constrained (Atyp)
5832 then
5833 Activate_Range_Check (N);
5834 return;
5835 end if;
5837 Indx := First_Index (Atyp);
5838 Subs := First (Expressions (P));
5839 loop
5840 if Subs = N then
5841 Ttyp := Etype (Indx);
5842 exit;
5843 end if;
5845 Next_Index (Indx);
5846 Next (Subs);
5847 end loop;
5848 end;
5850 -- For now, ignore all other cases, they are not so interesting
5852 else
5853 if Debug_Flag_CC then
5854 w (" target type not found, flag set");
5855 end if;
5857 Activate_Range_Check (N);
5858 return;
5859 end if;
5861 -- Evaluate and check the expression
5863 Find_Check
5864 (Expr => N,
5865 Check_Type => 'R',
5866 Target_Type => Ttyp,
5867 Entry_OK => OK,
5868 Check_Num => Chk,
5869 Ent => Ent,
5870 Ofs => Ofs);
5872 if Debug_Flag_CC then
5873 w ("Called Find_Check");
5874 w ("Target_Typ = ", Int (Ttyp));
5875 w (" OK = ", OK);
5877 if OK then
5878 w (" Check_Num = ", Chk);
5879 w (" Ent = ", Int (Ent));
5880 Write_Str (" Ofs = ");
5881 pid (Ofs);
5882 end if;
5883 end if;
5885 -- If check is not of form to optimize, then set flag and we are done
5887 if not OK then
5888 if Debug_Flag_CC then
5889 w (" expression not of optimizable type, flag set");
5890 end if;
5892 Activate_Range_Check (N);
5893 return;
5894 end if;
5896 -- If check is already performed, then return without setting flag
5898 if Chk /= 0 then
5899 if Debug_Flag_CC then
5900 w ("Check suppressed!");
5901 end if;
5903 return;
5904 end if;
5906 -- Here we will make a new entry for the new check
5908 Activate_Range_Check (N);
5909 Num_Saved_Checks := Num_Saved_Checks + 1;
5910 Saved_Checks (Num_Saved_Checks) :=
5911 (Killed => False,
5912 Entity => Ent,
5913 Offset => Ofs,
5914 Check_Type => 'R',
5915 Target_Type => Ttyp);
5917 if Debug_Flag_CC then
5918 w ("Make new entry, check number = ", Num_Saved_Checks);
5919 w (" Entity = ", Int (Ent));
5920 Write_Str (" Offset = ");
5921 pid (Ofs);
5922 w (" Check_Type = R");
5923 w (" Target_Type = ", Int (Ttyp));
5924 pg (Union_Id (Ttyp));
5925 end if;
5927 -- If we get an exception, then something went wrong, probably because of
5928 -- an error in the structure of the tree due to an incorrect program. Or
5929 -- it may be a bug in the optimization circuit. In either case the safest
5930 -- thing is simply to set the check flag unconditionally.
5932 exception
5933 when others =>
5934 Activate_Range_Check (N);
5936 if Debug_Flag_CC then
5937 w (" exception occurred, range flag set");
5938 end if;
5940 return;
5941 end Enable_Range_Check;
5943 ------------------
5944 -- Ensure_Valid --
5945 ------------------
5947 procedure Ensure_Valid
5948 (Expr : Node_Id;
5949 Holes_OK : Boolean := False;
5950 Related_Id : Entity_Id := Empty;
5951 Is_Low_Bound : Boolean := False;
5952 Is_High_Bound : Boolean := False)
5954 Typ : constant Entity_Id := Etype (Expr);
5956 begin
5957 -- Ignore call if we are not doing any validity checking
5959 if not Validity_Checks_On then
5960 return;
5962 -- Ignore call if range or validity checks suppressed on entity or type
5964 elsif Range_Or_Validity_Checks_Suppressed (Expr) then
5965 return;
5967 -- No check required if expression is from the expander, we assume the
5968 -- expander will generate whatever checks are needed. Note that this is
5969 -- not just an optimization, it avoids infinite recursions.
5971 -- Unchecked conversions must be checked, unless they are initialized
5972 -- scalar values, as in a component assignment in an init proc.
5974 -- In addition, we force a check if Force_Validity_Checks is set
5976 elsif not Comes_From_Source (Expr)
5977 and then not
5978 (Nkind (Expr) = N_Identifier
5979 and then Present (Renamed_Object (Entity (Expr)))
5980 and then Comes_From_Source (Renamed_Object (Entity (Expr))))
5981 and then not Force_Validity_Checks
5982 and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
5983 or else Kill_Range_Check (Expr))
5984 then
5985 return;
5987 -- No check required if expression is known to have valid value
5989 elsif Expr_Known_Valid (Expr) then
5990 return;
5992 -- No check needed within a generated predicate function. Validity
5993 -- of input value will have been checked earlier.
5995 elsif Ekind (Current_Scope) = E_Function
5996 and then Is_Predicate_Function (Current_Scope)
5997 then
5998 return;
6000 -- Ignore case of enumeration with holes where the flag is set not to
6001 -- worry about holes, since no special validity check is needed
6003 elsif Is_Enumeration_Type (Typ)
6004 and then Has_Non_Standard_Rep (Typ)
6005 and then Holes_OK
6006 then
6007 return;
6009 -- No check required on the left-hand side of an assignment
6011 elsif Nkind (Parent (Expr)) = N_Assignment_Statement
6012 and then Expr = Name (Parent (Expr))
6013 then
6014 return;
6016 -- No check on a universal real constant. The context will eventually
6017 -- convert it to a machine number for some target type, or report an
6018 -- illegality.
6020 elsif Nkind (Expr) = N_Real_Literal
6021 and then Etype (Expr) = Universal_Real
6022 then
6023 return;
6025 -- If the expression denotes a component of a packed boolean array,
6026 -- no possible check applies. We ignore the old ACATS chestnuts that
6027 -- involve Boolean range True..True.
6029 -- Note: validity checks are generated for expressions that yield a
6030 -- scalar type, when it is possible to create a value that is outside of
6031 -- the type. If this is a one-bit boolean no such value exists. This is
6032 -- an optimization, and it also prevents compiler blowing up during the
6033 -- elaboration of improperly expanded packed array references.
6035 elsif Nkind (Expr) = N_Indexed_Component
6036 and then Is_Bit_Packed_Array (Etype (Prefix (Expr)))
6037 and then Root_Type (Etype (Expr)) = Standard_Boolean
6038 then
6039 return;
6041 -- For an expression with actions, we want to insert the validity check
6042 -- on the final Expression.
6044 elsif Nkind (Expr) = N_Expression_With_Actions then
6045 Ensure_Valid (Expression (Expr));
6046 return;
6048 -- An annoying special case. If this is an out parameter of a scalar
6049 -- type, then the value is not going to be accessed, therefore it is
6050 -- inappropriate to do any validity check at the call site.
6052 else
6053 -- Only need to worry about scalar types
6055 if Is_Scalar_Type (Typ) then
6056 declare
6057 P : Node_Id;
6058 N : Node_Id;
6059 E : Entity_Id;
6060 F : Entity_Id;
6061 A : Node_Id;
6062 L : List_Id;
6064 begin
6065 -- Find actual argument (which may be a parameter association)
6066 -- and the parent of the actual argument (the call statement)
6068 N := Expr;
6069 P := Parent (Expr);
6071 if Nkind (P) = N_Parameter_Association then
6072 N := P;
6073 P := Parent (N);
6074 end if;
6076 -- Only need to worry if we are argument of a procedure call
6077 -- since functions don't have out parameters. If this is an
6078 -- indirect or dispatching call, get signature from the
6079 -- subprogram type.
6081 if Nkind (P) = N_Procedure_Call_Statement then
6082 L := Parameter_Associations (P);
6084 if Is_Entity_Name (Name (P)) then
6085 E := Entity (Name (P));
6086 else
6087 pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
6088 E := Etype (Name (P));
6089 end if;
6091 -- Only need to worry if there are indeed actuals, and if
6092 -- this could be a procedure call, otherwise we cannot get a
6093 -- match (either we are not an argument, or the mode of the
6094 -- formal is not OUT). This test also filters out the
6095 -- generic case.
6097 if Is_Non_Empty_List (L) and then Is_Subprogram (E) then
6099 -- This is the loop through parameters, looking for an
6100 -- OUT parameter for which we are the argument.
6102 F := First_Formal (E);
6103 A := First (L);
6104 while Present (F) loop
6105 if Ekind (F) = E_Out_Parameter and then A = N then
6106 return;
6107 end if;
6109 Next_Formal (F);
6110 Next (A);
6111 end loop;
6112 end if;
6113 end if;
6114 end;
6115 end if;
6116 end if;
6118 -- If this is a boolean expression, only its elementary operands need
6119 -- checking: if they are valid, a boolean or short-circuit operation
6120 -- with them will be valid as well.
6122 if Base_Type (Typ) = Standard_Boolean
6123 and then
6124 (Nkind (Expr) in N_Op or else Nkind (Expr) in N_Short_Circuit)
6125 then
6126 return;
6127 end if;
6129 -- If we fall through, a validity check is required
6131 Insert_Valid_Check (Expr, Related_Id, Is_Low_Bound, Is_High_Bound);
6133 if Is_Entity_Name (Expr)
6134 and then Safe_To_Capture_Value (Expr, Entity (Expr))
6135 then
6136 Set_Is_Known_Valid (Entity (Expr));
6137 end if;
6138 end Ensure_Valid;
6140 ----------------------
6141 -- Expr_Known_Valid --
6142 ----------------------
6144 function Expr_Known_Valid (Expr : Node_Id) return Boolean is
6145 Typ : constant Entity_Id := Etype (Expr);
6147 begin
6148 -- Non-scalar types are always considered valid, since they never give
6149 -- rise to the issues of erroneous or bounded error behavior that are
6150 -- the concern. In formal reference manual terms the notion of validity
6151 -- only applies to scalar types. Note that even when packed arrays are
6152 -- represented using modular types, they are still arrays semantically,
6153 -- so they are also always valid (in particular, the unused bits can be
6154 -- random rubbish without affecting the validity of the array value).
6156 if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Impl_Type (Typ) then
6157 return True;
6159 -- If no validity checking, then everything is considered valid
6161 elsif not Validity_Checks_On then
6162 return True;
6164 -- Floating-point types are considered valid unless floating-point
6165 -- validity checks have been specifically turned on.
6167 elsif Is_Floating_Point_Type (Typ)
6168 and then not Validity_Check_Floating_Point
6169 then
6170 return True;
6172 -- If the expression is the value of an object that is known to be
6173 -- valid, then clearly the expression value itself is valid.
6175 elsif Is_Entity_Name (Expr)
6176 and then Is_Known_Valid (Entity (Expr))
6178 -- Exclude volatile variables
6180 and then not Treat_As_Volatile (Entity (Expr))
6181 then
6182 return True;
6184 -- References to discriminants are always considered valid. The value
6185 -- of a discriminant gets checked when the object is built. Within the
6186 -- record, we consider it valid, and it is important to do so, since
6187 -- otherwise we can try to generate bogus validity checks which
6188 -- reference discriminants out of scope. Discriminants of concurrent
6189 -- types are excluded for the same reason.
6191 elsif Is_Entity_Name (Expr)
6192 and then Denotes_Discriminant (Expr, Check_Concurrent => True)
6193 then
6194 return True;
6196 -- If the type is one for which all values are known valid, then we are
6197 -- sure that the value is valid except in the slightly odd case where
6198 -- the expression is a reference to a variable whose size has been
6199 -- explicitly set to a value greater than the object size.
6201 elsif Is_Known_Valid (Typ) then
6202 if Is_Entity_Name (Expr)
6203 and then Ekind (Entity (Expr)) = E_Variable
6204 and then Esize (Entity (Expr)) > Esize (Typ)
6205 then
6206 return False;
6207 else
6208 return True;
6209 end if;
6211 -- Integer and character literals always have valid values, where
6212 -- appropriate these will be range checked in any case.
6214 elsif Nkind_In (Expr, N_Integer_Literal, N_Character_Literal) then
6215 return True;
6217 -- If we have a type conversion or a qualification of a known valid
6218 -- value, then the result will always be valid.
6220 elsif Nkind_In (Expr, N_Type_Conversion, N_Qualified_Expression) then
6221 return Expr_Known_Valid (Expression (Expr));
6223 -- Case of expression is a non-floating-point operator. In this case we
6224 -- can assume the result is valid the generated code for the operator
6225 -- will include whatever checks are needed (e.g. range checks) to ensure
6226 -- validity. This assumption does not hold for the floating-point case,
6227 -- since floating-point operators can generate Infinite or NaN results
6228 -- which are considered invalid.
6230 -- Historical note: in older versions, the exemption of floating-point
6231 -- types from this assumption was done only in cases where the parent
6232 -- was an assignment, function call or parameter association. Presumably
6233 -- the idea was that in other contexts, the result would be checked
6234 -- elsewhere, but this list of cases was missing tests (at least the
6235 -- N_Object_Declaration case, as shown by a reported missing validity
6236 -- check), and it is not clear why function calls but not procedure
6237 -- calls were tested for. It really seems more accurate and much
6238 -- safer to recognize that expressions which are the result of a
6239 -- floating-point operator can never be assumed to be valid.
6241 elsif Nkind (Expr) in N_Op and then not Is_Floating_Point_Type (Typ) then
6242 return True;
6244 -- The result of a membership test is always valid, since it is true or
6245 -- false, there are no other possibilities.
6247 elsif Nkind (Expr) in N_Membership_Test then
6248 return True;
6250 -- For all other cases, we do not know the expression is valid
6252 else
6253 return False;
6254 end if;
6255 end Expr_Known_Valid;
6257 ----------------
6258 -- Find_Check --
6259 ----------------
6261 procedure Find_Check
6262 (Expr : Node_Id;
6263 Check_Type : Character;
6264 Target_Type : Entity_Id;
6265 Entry_OK : out Boolean;
6266 Check_Num : out Nat;
6267 Ent : out Entity_Id;
6268 Ofs : out Uint)
6270 function Within_Range_Of
6271 (Target_Type : Entity_Id;
6272 Check_Type : Entity_Id) return Boolean;
6273 -- Given a requirement for checking a range against Target_Type, and
6274 -- and a range Check_Type against which a check has already been made,
6275 -- determines if the check against check type is sufficient to ensure
6276 -- that no check against Target_Type is required.
6278 ---------------------
6279 -- Within_Range_Of --
6280 ---------------------
6282 function Within_Range_Of
6283 (Target_Type : Entity_Id;
6284 Check_Type : Entity_Id) return Boolean
6286 begin
6287 if Target_Type = Check_Type then
6288 return True;
6290 else
6291 declare
6292 Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
6293 Thi : constant Node_Id := Type_High_Bound (Target_Type);
6294 Clo : constant Node_Id := Type_Low_Bound (Check_Type);
6295 Chi : constant Node_Id := Type_High_Bound (Check_Type);
6297 begin
6298 if (Tlo = Clo
6299 or else (Compile_Time_Known_Value (Tlo)
6300 and then
6301 Compile_Time_Known_Value (Clo)
6302 and then
6303 Expr_Value (Clo) >= Expr_Value (Tlo)))
6304 and then
6305 (Thi = Chi
6306 or else (Compile_Time_Known_Value (Thi)
6307 and then
6308 Compile_Time_Known_Value (Chi)
6309 and then
6310 Expr_Value (Chi) <= Expr_Value (Clo)))
6311 then
6312 return True;
6313 else
6314 return False;
6315 end if;
6316 end;
6317 end if;
6318 end Within_Range_Of;
6320 -- Start of processing for Find_Check
6322 begin
6323 -- Establish default, in case no entry is found
6325 Check_Num := 0;
6327 -- Case of expression is simple entity reference
6329 if Is_Entity_Name (Expr) then
6330 Ent := Entity (Expr);
6331 Ofs := Uint_0;
6333 -- Case of expression is entity + known constant
6335 elsif Nkind (Expr) = N_Op_Add
6336 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6337 and then Is_Entity_Name (Left_Opnd (Expr))
6338 then
6339 Ent := Entity (Left_Opnd (Expr));
6340 Ofs := Expr_Value (Right_Opnd (Expr));
6342 -- Case of expression is entity - known constant
6344 elsif Nkind (Expr) = N_Op_Subtract
6345 and then Compile_Time_Known_Value (Right_Opnd (Expr))
6346 and then Is_Entity_Name (Left_Opnd (Expr))
6347 then
6348 Ent := Entity (Left_Opnd (Expr));
6349 Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
6351 -- Any other expression is not of the right form
6353 else
6354 Ent := Empty;
6355 Ofs := Uint_0;
6356 Entry_OK := False;
6357 return;
6358 end if;
6360 -- Come here with expression of appropriate form, check if entity is an
6361 -- appropriate one for our purposes.
6363 if (Ekind (Ent) = E_Variable
6364 or else Is_Constant_Object (Ent))
6365 and then not Is_Library_Level_Entity (Ent)
6366 then
6367 Entry_OK := True;
6368 else
6369 Entry_OK := False;
6370 return;
6371 end if;
6373 -- See if there is matching check already
6375 for J in reverse 1 .. Num_Saved_Checks loop
6376 declare
6377 SC : Saved_Check renames Saved_Checks (J);
6378 begin
6379 if SC.Killed = False
6380 and then SC.Entity = Ent
6381 and then SC.Offset = Ofs
6382 and then SC.Check_Type = Check_Type
6383 and then Within_Range_Of (Target_Type, SC.Target_Type)
6384 then
6385 Check_Num := J;
6386 return;
6387 end if;
6388 end;
6389 end loop;
6391 -- If we fall through entry was not found
6393 return;
6394 end Find_Check;
6396 ---------------------------------
6397 -- Generate_Discriminant_Check --
6398 ---------------------------------
6400 -- Note: the code for this procedure is derived from the
6401 -- Emit_Discriminant_Check Routine in trans.c.
6403 procedure Generate_Discriminant_Check (N : Node_Id) is
6404 Loc : constant Source_Ptr := Sloc (N);
6405 Pref : constant Node_Id := Prefix (N);
6406 Sel : constant Node_Id := Selector_Name (N);
6408 Orig_Comp : constant Entity_Id :=
6409 Original_Record_Component (Entity (Sel));
6410 -- The original component to be checked
6412 Discr_Fct : constant Entity_Id :=
6413 Discriminant_Checking_Func (Orig_Comp);
6414 -- The discriminant checking function
6416 Discr : Entity_Id;
6417 -- One discriminant to be checked in the type
6419 Real_Discr : Entity_Id;
6420 -- Actual discriminant in the call
6422 Pref_Type : Entity_Id;
6423 -- Type of relevant prefix (ignoring private/access stuff)
6425 Args : List_Id;
6426 -- List of arguments for function call
6428 Formal : Entity_Id;
6429 -- Keep track of the formal corresponding to the actual we build for
6430 -- each discriminant, in order to be able to perform the necessary type
6431 -- conversions.
6433 Scomp : Node_Id;
6434 -- Selected component reference for checking function argument
6436 begin
6437 Pref_Type := Etype (Pref);
6439 -- Force evaluation of the prefix, so that it does not get evaluated
6440 -- twice (once for the check, once for the actual reference). Such a
6441 -- double evaluation is always a potential source of inefficiency, and
6442 -- is functionally incorrect in the volatile case, or when the prefix
6443 -- may have side effects. A nonvolatile entity or a component of a
6444 -- nonvolatile entity requires no evaluation.
6446 if Is_Entity_Name (Pref) then
6447 if Treat_As_Volatile (Entity (Pref)) then
6448 Force_Evaluation (Pref, Name_Req => True);
6449 end if;
6451 elsif Treat_As_Volatile (Etype (Pref)) then
6452 Force_Evaluation (Pref, Name_Req => True);
6454 elsif Nkind (Pref) = N_Selected_Component
6455 and then Is_Entity_Name (Prefix (Pref))
6456 then
6457 null;
6459 else
6460 Force_Evaluation (Pref, Name_Req => True);
6461 end if;
6463 -- For a tagged type, use the scope of the original component to
6464 -- obtain the type, because ???
6466 if Is_Tagged_Type (Scope (Orig_Comp)) then
6467 Pref_Type := Scope (Orig_Comp);
6469 -- For an untagged derived type, use the discriminants of the parent
6470 -- which have been renamed in the derivation, possibly by a one-to-many
6471 -- discriminant constraint. For untagged type, initially get the Etype
6472 -- of the prefix
6474 else
6475 if Is_Derived_Type (Pref_Type)
6476 and then Number_Discriminants (Pref_Type) /=
6477 Number_Discriminants (Etype (Base_Type (Pref_Type)))
6478 then
6479 Pref_Type := Etype (Base_Type (Pref_Type));
6480 end if;
6481 end if;
6483 -- We definitely should have a checking function, This routine should
6484 -- not be called if no discriminant checking function is present.
6486 pragma Assert (Present (Discr_Fct));
6488 -- Create the list of the actual parameters for the call. This list
6489 -- is the list of the discriminant fields of the record expression to
6490 -- be discriminant checked.
6492 Args := New_List;
6493 Formal := First_Formal (Discr_Fct);
6494 Discr := First_Discriminant (Pref_Type);
6495 while Present (Discr) loop
6497 -- If we have a corresponding discriminant field, and a parent
6498 -- subtype is present, then we want to use the corresponding
6499 -- discriminant since this is the one with the useful value.
6501 if Present (Corresponding_Discriminant (Discr))
6502 and then Ekind (Pref_Type) = E_Record_Type
6503 and then Present (Parent_Subtype (Pref_Type))
6504 then
6505 Real_Discr := Corresponding_Discriminant (Discr);
6506 else
6507 Real_Discr := Discr;
6508 end if;
6510 -- Construct the reference to the discriminant
6512 Scomp :=
6513 Make_Selected_Component (Loc,
6514 Prefix =>
6515 Unchecked_Convert_To (Pref_Type,
6516 Duplicate_Subexpr (Pref)),
6517 Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
6519 -- Manually analyze and resolve this selected component. We really
6520 -- want it just as it appears above, and do not want the expander
6521 -- playing discriminal games etc with this reference. Then we append
6522 -- the argument to the list we are gathering.
6524 Set_Etype (Scomp, Etype (Real_Discr));
6525 Set_Analyzed (Scomp, True);
6526 Append_To (Args, Convert_To (Etype (Formal), Scomp));
6528 Next_Formal_With_Extras (Formal);
6529 Next_Discriminant (Discr);
6530 end loop;
6532 -- Now build and insert the call
6534 Insert_Action (N,
6535 Make_Raise_Constraint_Error (Loc,
6536 Condition =>
6537 Make_Function_Call (Loc,
6538 Name => New_Occurrence_Of (Discr_Fct, Loc),
6539 Parameter_Associations => Args),
6540 Reason => CE_Discriminant_Check_Failed));
6541 end Generate_Discriminant_Check;
6543 ---------------------------
6544 -- Generate_Index_Checks --
6545 ---------------------------
6547 procedure Generate_Index_Checks (N : Node_Id) is
6549 function Entity_Of_Prefix return Entity_Id;
6550 -- Returns the entity of the prefix of N (or Empty if not found)
6552 ----------------------
6553 -- Entity_Of_Prefix --
6554 ----------------------
6556 function Entity_Of_Prefix return Entity_Id is
6557 P : Node_Id;
6559 begin
6560 P := Prefix (N);
6561 while not Is_Entity_Name (P) loop
6562 if not Nkind_In (P, N_Selected_Component,
6563 N_Indexed_Component)
6564 then
6565 return Empty;
6566 end if;
6568 P := Prefix (P);
6569 end loop;
6571 return Entity (P);
6572 end Entity_Of_Prefix;
6574 -- Local variables
6576 Loc : constant Source_Ptr := Sloc (N);
6577 A : constant Node_Id := Prefix (N);
6578 A_Ent : constant Entity_Id := Entity_Of_Prefix;
6579 Sub : Node_Id;
6581 -- Start of processing for Generate_Index_Checks
6583 begin
6584 -- Ignore call if the prefix is not an array since we have a serious
6585 -- error in the sources. Ignore it also if index checks are suppressed
6586 -- for array object or type.
6588 if not Is_Array_Type (Etype (A))
6589 or else (Present (A_Ent) and then Index_Checks_Suppressed (A_Ent))
6590 or else Index_Checks_Suppressed (Etype (A))
6591 then
6592 return;
6594 -- The indexed component we are dealing with contains 'Loop_Entry in its
6595 -- prefix. This case arises when analysis has determined that constructs
6596 -- such as
6598 -- Prefix'Loop_Entry (Expr)
6599 -- Prefix'Loop_Entry (Expr1, Expr2, ... ExprN)
6601 -- require rewriting for error detection purposes. A side effect of this
6602 -- action is the generation of index checks that mention 'Loop_Entry.
6603 -- Delay the generation of the check until 'Loop_Entry has been properly
6604 -- expanded. This is done in Expand_Loop_Entry_Attributes.
6606 elsif Nkind (Prefix (N)) = N_Attribute_Reference
6607 and then Attribute_Name (Prefix (N)) = Name_Loop_Entry
6608 then
6609 return;
6610 end if;
6612 -- Generate a raise of constraint error with the appropriate reason and
6613 -- a condition of the form:
6615 -- Base_Type (Sub) not in Array'Range (Subscript)
6617 -- Note that the reason we generate the conversion to the base type here
6618 -- is that we definitely want the range check to take place, even if it
6619 -- looks like the subtype is OK. Optimization considerations that allow
6620 -- us to omit the check have already been taken into account in the
6621 -- setting of the Do_Range_Check flag earlier on.
6623 Sub := First (Expressions (N));
6625 -- Handle string literals
6627 if Ekind (Etype (A)) = E_String_Literal_Subtype then
6628 if Do_Range_Check (Sub) then
6629 Set_Do_Range_Check (Sub, False);
6631 -- For string literals we obtain the bounds of the string from the
6632 -- associated subtype.
6634 Insert_Action (N,
6635 Make_Raise_Constraint_Error (Loc,
6636 Condition =>
6637 Make_Not_In (Loc,
6638 Left_Opnd =>
6639 Convert_To (Base_Type (Etype (Sub)),
6640 Duplicate_Subexpr_Move_Checks (Sub)),
6641 Right_Opnd =>
6642 Make_Attribute_Reference (Loc,
6643 Prefix => New_Occurrence_Of (Etype (A), Loc),
6644 Attribute_Name => Name_Range)),
6645 Reason => CE_Index_Check_Failed));
6646 end if;
6648 -- General case
6650 else
6651 declare
6652 A_Idx : Node_Id := Empty;
6653 A_Range : Node_Id;
6654 Ind : Nat;
6655 Num : List_Id;
6656 Range_N : Node_Id;
6658 begin
6659 A_Idx := First_Index (Etype (A));
6660 Ind := 1;
6661 while Present (Sub) loop
6662 if Do_Range_Check (Sub) then
6663 Set_Do_Range_Check (Sub, False);
6665 -- Force evaluation except for the case of a simple name of
6666 -- a nonvolatile entity.
6668 if not Is_Entity_Name (Sub)
6669 or else Treat_As_Volatile (Entity (Sub))
6670 then
6671 Force_Evaluation (Sub);
6672 end if;
6674 if Nkind (A_Idx) = N_Range then
6675 A_Range := A_Idx;
6677 elsif Nkind (A_Idx) = N_Identifier
6678 or else Nkind (A_Idx) = N_Expanded_Name
6679 then
6680 A_Range := Scalar_Range (Entity (A_Idx));
6682 else pragma Assert (Nkind (A_Idx) = N_Subtype_Indication);
6683 A_Range := Range_Expression (Constraint (A_Idx));
6684 end if;
6686 -- For array objects with constant bounds we can generate
6687 -- the index check using the bounds of the type of the index
6689 if Present (A_Ent)
6690 and then Ekind (A_Ent) = E_Variable
6691 and then Is_Constant_Bound (Low_Bound (A_Range))
6692 and then Is_Constant_Bound (High_Bound (A_Range))
6693 then
6694 Range_N :=
6695 Make_Attribute_Reference (Loc,
6696 Prefix =>
6697 New_Occurrence_Of (Etype (A_Idx), Loc),
6698 Attribute_Name => Name_Range);
6700 -- For arrays with non-constant bounds we cannot generate
6701 -- the index check using the bounds of the type of the index
6702 -- since it may reference discriminants of some enclosing
6703 -- type. We obtain the bounds directly from the prefix
6704 -- object.
6706 else
6707 if Ind = 1 then
6708 Num := No_List;
6709 else
6710 Num := New_List (Make_Integer_Literal (Loc, Ind));
6711 end if;
6713 Range_N :=
6714 Make_Attribute_Reference (Loc,
6715 Prefix =>
6716 Duplicate_Subexpr_Move_Checks (A, Name_Req => True),
6717 Attribute_Name => Name_Range,
6718 Expressions => Num);
6719 end if;
6721 Insert_Action (N,
6722 Make_Raise_Constraint_Error (Loc,
6723 Condition =>
6724 Make_Not_In (Loc,
6725 Left_Opnd =>
6726 Convert_To (Base_Type (Etype (Sub)),
6727 Duplicate_Subexpr_Move_Checks (Sub)),
6728 Right_Opnd => Range_N),
6729 Reason => CE_Index_Check_Failed));
6730 end if;
6732 A_Idx := Next_Index (A_Idx);
6733 Ind := Ind + 1;
6734 Next (Sub);
6735 end loop;
6736 end;
6737 end if;
6738 end Generate_Index_Checks;
6740 --------------------------
6741 -- Generate_Range_Check --
6742 --------------------------
6744 procedure Generate_Range_Check
6745 (N : Node_Id;
6746 Target_Type : Entity_Id;
6747 Reason : RT_Exception_Code)
6749 Loc : constant Source_Ptr := Sloc (N);
6750 Source_Type : constant Entity_Id := Etype (N);
6751 Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
6752 Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
6754 procedure Convert_And_Check_Range;
6755 -- Convert the conversion operand to the target base type and save in
6756 -- a temporary. Then check the converted value against the range of the
6757 -- target subtype.
6759 -----------------------------
6760 -- Convert_And_Check_Range --
6761 -----------------------------
6763 procedure Convert_And_Check_Range is
6764 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
6766 begin
6767 -- We make a temporary to hold the value of the converted value
6768 -- (converted to the base type), and then do the test against this
6769 -- temporary. The conversion itself is replaced by an occurrence of
6770 -- Tnn and followed by the explicit range check. Note that checks
6771 -- are suppressed for this code, since we don't want a recursive
6772 -- range check popping up.
6774 -- Tnn : constant Target_Base_Type := Target_Base_Type (N);
6775 -- [constraint_error when Tnn not in Target_Type]
6777 Insert_Actions (N, New_List (
6778 Make_Object_Declaration (Loc,
6779 Defining_Identifier => Tnn,
6780 Object_Definition => New_Occurrence_Of (Target_Base_Type, Loc),
6781 Constant_Present => True,
6782 Expression =>
6783 Make_Type_Conversion (Loc,
6784 Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
6785 Expression => Duplicate_Subexpr (N))),
6787 Make_Raise_Constraint_Error (Loc,
6788 Condition =>
6789 Make_Not_In (Loc,
6790 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
6791 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6792 Reason => Reason)),
6793 Suppress => All_Checks);
6795 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
6797 -- Set the type of N, because the declaration for Tnn might not
6798 -- be analyzed yet, as is the case if N appears within a record
6799 -- declaration, as a discriminant constraint or expression.
6801 Set_Etype (N, Target_Base_Type);
6802 end Convert_And_Check_Range;
6804 -- Start of processing for Generate_Range_Check
6806 begin
6807 -- First special case, if the source type is already within the range
6808 -- of the target type, then no check is needed (probably we should have
6809 -- stopped Do_Range_Check from being set in the first place, but better
6810 -- late than never in preventing junk code and junk flag settings.
6812 if In_Subrange_Of (Source_Type, Target_Type)
6814 -- We do NOT apply this if the source node is a literal, since in this
6815 -- case the literal has already been labeled as having the subtype of
6816 -- the target.
6818 and then not
6819 (Nkind_In (N, N_Integer_Literal, N_Real_Literal, N_Character_Literal)
6820 or else
6821 (Is_Entity_Name (N)
6822 and then Ekind (Entity (N)) = E_Enumeration_Literal))
6823 then
6824 Set_Do_Range_Check (N, False);
6825 return;
6826 end if;
6828 -- Here a check is needed. If the expander is not active, or if we are
6829 -- in GNATProve mode, then simply set the Do_Range_Check flag and we
6830 -- are done. In both these cases, we just want to see the range check
6831 -- flag set, we do not want to generate the explicit range check code.
6833 if GNATprove_Mode or else not Expander_Active then
6834 Set_Do_Range_Check (N, True);
6835 return;
6836 end if;
6838 -- Here we will generate an explicit range check, so we don't want to
6839 -- set the Do_Range check flag, since the range check is taken care of
6840 -- by the code we will generate.
6842 Set_Do_Range_Check (N, False);
6844 -- Force evaluation of the node, so that it does not get evaluated twice
6845 -- (once for the check, once for the actual reference). Such a double
6846 -- evaluation is always a potential source of inefficiency, and is
6847 -- functionally incorrect in the volatile case.
6849 -- We skip the evaluation of attribute references because, after these
6850 -- runtime checks are generated, the expander may need to rewrite this
6851 -- node (for example, see Attribute_Max_Size_In_Storage_Elements in
6852 -- Expand_N_Attribute_Reference).
6854 if Nkind (N) /= N_Attribute_Reference
6855 and then (not Is_Entity_Name (N)
6856 or else Treat_As_Volatile (Entity (N)))
6857 then
6858 Force_Evaluation (N, Mode => Strict);
6859 end if;
6861 -- The easiest case is when Source_Base_Type and Target_Base_Type are
6862 -- the same since in this case we can simply do a direct check of the
6863 -- value of N against the bounds of Target_Type.
6865 -- [constraint_error when N not in Target_Type]
6867 -- Note: this is by far the most common case, for example all cases of
6868 -- checks on the RHS of assignments are in this category, but not all
6869 -- cases are like this. Notably conversions can involve two types.
6871 if Source_Base_Type = Target_Base_Type then
6873 -- Insert the explicit range check. Note that we suppress checks for
6874 -- this code, since we don't want a recursive range check popping up.
6876 Insert_Action (N,
6877 Make_Raise_Constraint_Error (Loc,
6878 Condition =>
6879 Make_Not_In (Loc,
6880 Left_Opnd => Duplicate_Subexpr (N),
6881 Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
6882 Reason => Reason),
6883 Suppress => All_Checks);
6885 -- Next test for the case where the target type is within the bounds
6886 -- of the base type of the source type, since in this case we can
6887 -- simply convert these bounds to the base type of T to do the test.
6889 -- [constraint_error when N not in
6890 -- Source_Base_Type (Target_Type'First)
6891 -- ..
6892 -- Source_Base_Type(Target_Type'Last))]
6894 -- The conversions will always work and need no check
6896 -- Unchecked_Convert_To is used instead of Convert_To to handle the case
6897 -- of converting from an enumeration value to an integer type, such as
6898 -- occurs for the case of generating a range check on Enum'Val(Exp)
6899 -- (which used to be handled by gigi). This is OK, since the conversion
6900 -- itself does not require a check.
6902 elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
6904 -- Insert the explicit range check. Note that we suppress checks for
6905 -- this code, since we don't want a recursive range check popping up.
6907 if Is_Discrete_Type (Source_Base_Type)
6908 and then
6909 Is_Discrete_Type (Target_Base_Type)
6910 then
6911 Insert_Action (N,
6912 Make_Raise_Constraint_Error (Loc,
6913 Condition =>
6914 Make_Not_In (Loc,
6915 Left_Opnd => Duplicate_Subexpr (N),
6917 Right_Opnd =>
6918 Make_Range (Loc,
6919 Low_Bound =>
6920 Unchecked_Convert_To (Source_Base_Type,
6921 Make_Attribute_Reference (Loc,
6922 Prefix =>
6923 New_Occurrence_Of (Target_Type, Loc),
6924 Attribute_Name => Name_First)),
6926 High_Bound =>
6927 Unchecked_Convert_To (Source_Base_Type,
6928 Make_Attribute_Reference (Loc,
6929 Prefix =>
6930 New_Occurrence_Of (Target_Type, Loc),
6931 Attribute_Name => Name_Last)))),
6932 Reason => Reason),
6933 Suppress => All_Checks);
6935 -- For conversions involving at least one type that is not discrete,
6936 -- first convert to target type and then generate the range check.
6937 -- This avoids problems with values that are close to a bound of the
6938 -- target type that would fail a range check when done in a larger
6939 -- source type before converting but would pass if converted with
6940 -- rounding and then checked (such as in float-to-float conversions).
6942 else
6943 Convert_And_Check_Range;
6944 end if;
6946 -- Note that at this stage we now that the Target_Base_Type is not in
6947 -- the range of the Source_Base_Type (since even the Target_Type itself
6948 -- is not in this range). It could still be the case that Source_Type is
6949 -- in range of the target base type since we have not checked that case.
6951 -- If that is the case, we can freely convert the source to the target,
6952 -- and then test the target result against the bounds.
6954 elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
6955 Convert_And_Check_Range;
6957 -- At this stage, we know that we have two scalar types, which are
6958 -- directly convertible, and where neither scalar type has a base
6959 -- range that is in the range of the other scalar type.
6961 -- The only way this can happen is with a signed and unsigned type.
6962 -- So test for these two cases:
6964 else
6965 -- Case of the source is unsigned and the target is signed
6967 if Is_Unsigned_Type (Source_Base_Type)
6968 and then not Is_Unsigned_Type (Target_Base_Type)
6969 then
6970 -- If the source is unsigned and the target is signed, then we
6971 -- know that the source is not shorter than the target (otherwise
6972 -- the source base type would be in the target base type range).
6974 -- In other words, the unsigned type is either the same size as
6975 -- the target, or it is larger. It cannot be smaller.
6977 pragma Assert
6978 (Esize (Source_Base_Type) >= Esize (Target_Base_Type));
6980 -- We only need to check the low bound if the low bound of the
6981 -- target type is non-negative. If the low bound of the target
6982 -- type is negative, then we know that we will fit fine.
6984 -- If the high bound of the target type is negative, then we
6985 -- know we have a constraint error, since we can't possibly
6986 -- have a negative source.
6988 -- With these two checks out of the way, we can do the check
6989 -- using the source type safely
6991 -- This is definitely the most annoying case.
6993 -- [constraint_error
6994 -- when (Target_Type'First >= 0
6995 -- and then
6996 -- N < Source_Base_Type (Target_Type'First))
6997 -- or else Target_Type'Last < 0
6998 -- or else N > Source_Base_Type (Target_Type'Last)];
7000 -- We turn off all checks since we know that the conversions
7001 -- will work fine, given the guards for negative values.
7003 Insert_Action (N,
7004 Make_Raise_Constraint_Error (Loc,
7005 Condition =>
7006 Make_Or_Else (Loc,
7007 Make_Or_Else (Loc,
7008 Left_Opnd =>
7009 Make_And_Then (Loc,
7010 Left_Opnd => Make_Op_Ge (Loc,
7011 Left_Opnd =>
7012 Make_Attribute_Reference (Loc,
7013 Prefix =>
7014 New_Occurrence_Of (Target_Type, Loc),
7015 Attribute_Name => Name_First),
7016 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7018 Right_Opnd =>
7019 Make_Op_Lt (Loc,
7020 Left_Opnd => Duplicate_Subexpr (N),
7021 Right_Opnd =>
7022 Convert_To (Source_Base_Type,
7023 Make_Attribute_Reference (Loc,
7024 Prefix =>
7025 New_Occurrence_Of (Target_Type, Loc),
7026 Attribute_Name => Name_First)))),
7028 Right_Opnd =>
7029 Make_Op_Lt (Loc,
7030 Left_Opnd =>
7031 Make_Attribute_Reference (Loc,
7032 Prefix => New_Occurrence_Of (Target_Type, Loc),
7033 Attribute_Name => Name_Last),
7034 Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
7036 Right_Opnd =>
7037 Make_Op_Gt (Loc,
7038 Left_Opnd => Duplicate_Subexpr (N),
7039 Right_Opnd =>
7040 Convert_To (Source_Base_Type,
7041 Make_Attribute_Reference (Loc,
7042 Prefix => New_Occurrence_Of (Target_Type, Loc),
7043 Attribute_Name => Name_Last)))),
7045 Reason => Reason),
7046 Suppress => All_Checks);
7048 -- Only remaining possibility is that the source is signed and
7049 -- the target is unsigned.
7051 else
7052 pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
7053 and then Is_Unsigned_Type (Target_Base_Type));
7055 -- If the source is signed and the target is unsigned, then we
7056 -- know that the target is not shorter than the source (otherwise
7057 -- the target base type would be in the source base type range).
7059 -- In other words, the unsigned type is either the same size as
7060 -- the target, or it is larger. It cannot be smaller.
7062 -- Clearly we have an error if the source value is negative since
7063 -- no unsigned type can have negative values. If the source type
7064 -- is non-negative, then the check can be done using the target
7065 -- type.
7067 -- Tnn : constant Target_Base_Type (N) := Target_Type;
7069 -- [constraint_error
7070 -- when N < 0 or else Tnn not in Target_Type];
7072 -- We turn off all checks for the conversion of N to the target
7073 -- base type, since we generate the explicit check to ensure that
7074 -- the value is non-negative
7076 declare
7077 Tnn : constant Entity_Id := Make_Temporary (Loc, 'T', N);
7079 begin
7080 Insert_Actions (N, New_List (
7081 Make_Object_Declaration (Loc,
7082 Defining_Identifier => Tnn,
7083 Object_Definition =>
7084 New_Occurrence_Of (Target_Base_Type, Loc),
7085 Constant_Present => True,
7086 Expression =>
7087 Make_Unchecked_Type_Conversion (Loc,
7088 Subtype_Mark =>
7089 New_Occurrence_Of (Target_Base_Type, Loc),
7090 Expression => Duplicate_Subexpr (N))),
7092 Make_Raise_Constraint_Error (Loc,
7093 Condition =>
7094 Make_Or_Else (Loc,
7095 Left_Opnd =>
7096 Make_Op_Lt (Loc,
7097 Left_Opnd => Duplicate_Subexpr (N),
7098 Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
7100 Right_Opnd =>
7101 Make_Not_In (Loc,
7102 Left_Opnd => New_Occurrence_Of (Tnn, Loc),
7103 Right_Opnd =>
7104 New_Occurrence_Of (Target_Type, Loc))),
7106 Reason => Reason)),
7107 Suppress => All_Checks);
7109 -- Set the Etype explicitly, because Insert_Actions may have
7110 -- placed the declaration in the freeze list for an enclosing
7111 -- construct, and thus it is not analyzed yet.
7113 Set_Etype (Tnn, Target_Base_Type);
7114 Rewrite (N, New_Occurrence_Of (Tnn, Loc));
7115 end;
7116 end if;
7117 end if;
7118 end Generate_Range_Check;
7120 ------------------
7121 -- Get_Check_Id --
7122 ------------------
7124 function Get_Check_Id (N : Name_Id) return Check_Id is
7125 begin
7126 -- For standard check name, we can do a direct computation
7128 if N in First_Check_Name .. Last_Check_Name then
7129 return Check_Id (N - (First_Check_Name - 1));
7131 -- For non-standard names added by pragma Check_Name, search table
7133 else
7134 for J in All_Checks + 1 .. Check_Names.Last loop
7135 if Check_Names.Table (J) = N then
7136 return J;
7137 end if;
7138 end loop;
7139 end if;
7141 -- No matching name found
7143 return No_Check_Id;
7144 end Get_Check_Id;
7146 ---------------------
7147 -- Get_Discriminal --
7148 ---------------------
7150 function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
7151 Loc : constant Source_Ptr := Sloc (E);
7152 D : Entity_Id;
7153 Sc : Entity_Id;
7155 begin
7156 -- The bound can be a bona fide parameter of a protected operation,
7157 -- rather than a prival encoded as an in-parameter.
7159 if No (Discriminal_Link (Entity (Bound))) then
7160 return Bound;
7161 end if;
7163 -- Climb the scope stack looking for an enclosing protected type. If
7164 -- we run out of scopes, return the bound itself.
7166 Sc := Scope (E);
7167 while Present (Sc) loop
7168 if Sc = Standard_Standard then
7169 return Bound;
7170 elsif Ekind (Sc) = E_Protected_Type then
7171 exit;
7172 end if;
7174 Sc := Scope (Sc);
7175 end loop;
7177 D := First_Discriminant (Sc);
7178 while Present (D) loop
7179 if Chars (D) = Chars (Bound) then
7180 return New_Occurrence_Of (Discriminal (D), Loc);
7181 end if;
7183 Next_Discriminant (D);
7184 end loop;
7186 return Bound;
7187 end Get_Discriminal;
7189 ----------------------
7190 -- Get_Range_Checks --
7191 ----------------------
7193 function Get_Range_Checks
7194 (Ck_Node : Node_Id;
7195 Target_Typ : Entity_Id;
7196 Source_Typ : Entity_Id := Empty;
7197 Warn_Node : Node_Id := Empty) return Check_Result
7199 begin
7200 return
7201 Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Warn_Node);
7202 end Get_Range_Checks;
7204 ------------------
7205 -- Guard_Access --
7206 ------------------
7208 function Guard_Access
7209 (Cond : Node_Id;
7210 Loc : Source_Ptr;
7211 Ck_Node : Node_Id) return Node_Id
7213 begin
7214 if Nkind (Cond) = N_Or_Else then
7215 Set_Paren_Count (Cond, 1);
7216 end if;
7218 if Nkind (Ck_Node) = N_Allocator then
7219 return Cond;
7221 else
7222 return
7223 Make_And_Then (Loc,
7224 Left_Opnd =>
7225 Make_Op_Ne (Loc,
7226 Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
7227 Right_Opnd => Make_Null (Loc)),
7228 Right_Opnd => Cond);
7229 end if;
7230 end Guard_Access;
7232 -----------------------------
7233 -- Index_Checks_Suppressed --
7234 -----------------------------
7236 function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
7237 begin
7238 if Present (E) and then Checks_May_Be_Suppressed (E) then
7239 return Is_Check_Suppressed (E, Index_Check);
7240 else
7241 return Scope_Suppress.Suppress (Index_Check);
7242 end if;
7243 end Index_Checks_Suppressed;
7245 ----------------
7246 -- Initialize --
7247 ----------------
7249 procedure Initialize is
7250 begin
7251 for J in Determine_Range_Cache_N'Range loop
7252 Determine_Range_Cache_N (J) := Empty;
7253 end loop;
7255 Check_Names.Init;
7257 for J in Int range 1 .. All_Checks loop
7258 Check_Names.Append (Name_Id (Int (First_Check_Name) + J - 1));
7259 end loop;
7260 end Initialize;
7262 -------------------------
7263 -- Insert_Range_Checks --
7264 -------------------------
7266 procedure Insert_Range_Checks
7267 (Checks : Check_Result;
7268 Node : Node_Id;
7269 Suppress_Typ : Entity_Id;
7270 Static_Sloc : Source_Ptr := No_Location;
7271 Flag_Node : Node_Id := Empty;
7272 Do_Before : Boolean := False)
7274 Checks_On : constant Boolean :=
7275 not Index_Checks_Suppressed (Suppress_Typ)
7276 or else
7277 not Range_Checks_Suppressed (Suppress_Typ);
7279 Check_Node : Node_Id;
7280 Internal_Flag_Node : Node_Id := Flag_Node;
7281 Internal_Static_Sloc : Source_Ptr := Static_Sloc;
7283 begin
7284 -- For now we just return if Checks_On is false, however this should be
7285 -- enhanced to check for an always True value in the condition and to
7286 -- generate a compilation warning???
7288 if not Expander_Active or not Checks_On then
7289 return;
7290 end if;
7292 if Static_Sloc = No_Location then
7293 Internal_Static_Sloc := Sloc (Node);
7294 end if;
7296 if No (Flag_Node) then
7297 Internal_Flag_Node := Node;
7298 end if;
7300 for J in 1 .. 2 loop
7301 exit when No (Checks (J));
7303 if Nkind (Checks (J)) = N_Raise_Constraint_Error
7304 and then Present (Condition (Checks (J)))
7305 then
7306 if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
7307 Check_Node := Checks (J);
7308 Mark_Rewrite_Insertion (Check_Node);
7310 if Do_Before then
7311 Insert_Before_And_Analyze (Node, Check_Node);
7312 else
7313 Insert_After_And_Analyze (Node, Check_Node);
7314 end if;
7316 Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
7317 end if;
7319 else
7320 Check_Node :=
7321 Make_Raise_Constraint_Error (Internal_Static_Sloc,
7322 Reason => CE_Range_Check_Failed);
7323 Mark_Rewrite_Insertion (Check_Node);
7325 if Do_Before then
7326 Insert_Before_And_Analyze (Node, Check_Node);
7327 else
7328 Insert_After_And_Analyze (Node, Check_Node);
7329 end if;
7330 end if;
7331 end loop;
7332 end Insert_Range_Checks;
7334 ------------------------
7335 -- Insert_Valid_Check --
7336 ------------------------
7338 procedure Insert_Valid_Check
7339 (Expr : Node_Id;
7340 Related_Id : Entity_Id := Empty;
7341 Is_Low_Bound : Boolean := False;
7342 Is_High_Bound : Boolean := False)
7344 Loc : constant Source_Ptr := Sloc (Expr);
7345 Typ : constant Entity_Id := Etype (Expr);
7346 Exp : Node_Id;
7348 begin
7349 -- Do not insert if checks off, or if not checking validity or if
7350 -- expression is known to be valid.
7352 if not Validity_Checks_On
7353 or else Range_Or_Validity_Checks_Suppressed (Expr)
7354 or else Expr_Known_Valid (Expr)
7355 then
7356 return;
7358 -- Do not insert checks within a predicate function. This will arise
7359 -- if the current unit and the predicate function are being compiled
7360 -- with validity checks enabled.
7362 elsif Present (Predicate_Function (Typ))
7363 and then Current_Scope = Predicate_Function (Typ)
7364 then
7365 return;
7367 -- If the expression is a packed component of a modular type of the
7368 -- right size, the data is always valid.
7370 elsif Nkind (Expr) = N_Selected_Component
7371 and then Present (Component_Clause (Entity (Selector_Name (Expr))))
7372 and then Is_Modular_Integer_Type (Typ)
7373 and then Modulus (Typ) = 2 ** Esize (Entity (Selector_Name (Expr)))
7374 then
7375 return;
7377 -- Do not generate a validity check when inside a generic unit as this
7378 -- is an expansion activity.
7380 elsif Inside_A_Generic then
7381 return;
7382 end if;
7384 -- If we have a checked conversion, then validity check applies to
7385 -- the expression inside the conversion, not the result, since if
7386 -- the expression inside is valid, then so is the conversion result.
7388 Exp := Expr;
7389 while Nkind (Exp) = N_Type_Conversion loop
7390 Exp := Expression (Exp);
7391 end loop;
7393 -- Do not generate a check for a variable which already validates the
7394 -- value of an assignable object.
7396 if Is_Validation_Variable_Reference (Exp) then
7397 return;
7398 end if;
7400 declare
7401 CE : Node_Id;
7402 PV : Node_Id;
7403 Var_Id : Entity_Id;
7405 begin
7406 -- If the expression denotes an assignable object, capture its value
7407 -- in a variable and replace the original expression by the variable.
7408 -- This approach has several effects:
7410 -- 1) The evaluation of the object results in only one read in the
7411 -- case where the object is atomic or volatile.
7413 -- Var ... := Object; -- read
7415 -- 2) The captured value is the one verified by attribute 'Valid.
7416 -- As a result the object is not evaluated again, which would
7417 -- result in an unwanted read in the case where the object is
7418 -- atomic or volatile.
7420 -- if not Var'Valid then -- OK, no read of Object
7422 -- if not Object'Valid then -- Wrong, extra read of Object
7424 -- 3) The captured value replaces the original object reference.
7425 -- As a result the object is not evaluated again, in the same
7426 -- vein as 2).
7428 -- ... Var ... -- OK, no read of Object
7430 -- ... Object ... -- Wrong, extra read of Object
7432 -- 4) The use of a variable to capture the value of the object
7433 -- allows the propagation of any changes back to the original
7434 -- object.
7436 -- procedure Call (Val : in out ...);
7438 -- Var : ... := Object; -- read Object
7439 -- if not Var'Valid then -- validity check
7440 -- Call (Var); -- modify Var
7441 -- Object := Var; -- update Object
7443 if Is_Variable (Exp) then
7444 Var_Id := Make_Temporary (Loc, 'T', Exp);
7446 -- Because we could be dealing with a transient scope which would
7447 -- cause our object declaration to remain unanalyzed we must do
7448 -- some manual decoration.
7450 Set_Ekind (Var_Id, E_Variable);
7451 Set_Etype (Var_Id, Typ);
7453 Insert_Action (Exp,
7454 Make_Object_Declaration (Loc,
7455 Defining_Identifier => Var_Id,
7456 Object_Definition => New_Occurrence_Of (Typ, Loc),
7457 Expression => New_Copy_Tree (Exp)),
7458 Suppress => Validity_Check);
7460 Set_Validated_Object (Var_Id, New_Copy_Tree (Exp));
7461 Rewrite (Exp, New_Occurrence_Of (Var_Id, Loc));
7462 PV := New_Occurrence_Of (Var_Id, Loc);
7464 -- Copy the Do_Range_Check flag over to the new Exp, so it doesn't
7465 -- get lost. Floating point types are handled elsewhere.
7467 if not Is_Floating_Point_Type (Typ) then
7468 Set_Do_Range_Check (Exp, Do_Range_Check (Original_Node (Exp)));
7469 end if;
7471 -- Otherwise the expression does not denote a variable. Force its
7472 -- evaluation by capturing its value in a constant. Generate:
7474 -- Temp : constant ... := Exp;
7476 else
7477 Force_Evaluation
7478 (Exp => Exp,
7479 Related_Id => Related_Id,
7480 Is_Low_Bound => Is_Low_Bound,
7481 Is_High_Bound => Is_High_Bound);
7483 PV := New_Copy_Tree (Exp);
7484 end if;
7486 -- A rather specialized test. If PV is an analyzed expression which
7487 -- is an indexed component of a packed array that has not been
7488 -- properly expanded, turn off its Analyzed flag to make sure it
7489 -- gets properly reexpanded. If the prefix is an access value,
7490 -- the dereference will be added later.
7492 -- The reason this arises is that Duplicate_Subexpr_No_Checks did
7493 -- an analyze with the old parent pointer. This may point e.g. to
7494 -- a subprogram call, which deactivates this expansion.
7496 if Analyzed (PV)
7497 and then Nkind (PV) = N_Indexed_Component
7498 and then Is_Array_Type (Etype (Prefix (PV)))
7499 and then Present (Packed_Array_Impl_Type (Etype (Prefix (PV))))
7500 then
7501 Set_Analyzed (PV, False);
7502 end if;
7504 -- Build the raise CE node to check for validity. We build a type
7505 -- qualification for the prefix, since it may not be of the form of
7506 -- a name, and we don't care in this context!
7508 CE :=
7509 Make_Raise_Constraint_Error (Loc,
7510 Condition =>
7511 Make_Op_Not (Loc,
7512 Right_Opnd =>
7513 Make_Attribute_Reference (Loc,
7514 Prefix => PV,
7515 Attribute_Name => Name_Valid)),
7516 Reason => CE_Invalid_Data);
7518 -- Insert the validity check. Note that we do this with validity
7519 -- checks turned off, to avoid recursion, we do not want validity
7520 -- checks on the validity checking code itself.
7522 Insert_Action (Expr, CE, Suppress => Validity_Check);
7524 -- If the expression is a reference to an element of a bit-packed
7525 -- array, then it is rewritten as a renaming declaration. If the
7526 -- expression is an actual in a call, it has not been expanded,
7527 -- waiting for the proper point at which to do it. The same happens
7528 -- with renamings, so that we have to force the expansion now. This
7529 -- non-local complication is due to code in exp_ch2,adb, exp_ch4.adb
7530 -- and exp_ch6.adb.
7532 if Is_Entity_Name (Exp)
7533 and then Nkind (Parent (Entity (Exp))) =
7534 N_Object_Renaming_Declaration
7535 then
7536 declare
7537 Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
7538 begin
7539 if Nkind (Old_Exp) = N_Indexed_Component
7540 and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
7541 then
7542 Expand_Packed_Element_Reference (Old_Exp);
7543 end if;
7544 end;
7545 end if;
7546 end;
7547 end Insert_Valid_Check;
7549 -------------------------------------
7550 -- Is_Signed_Integer_Arithmetic_Op --
7551 -------------------------------------
7553 function Is_Signed_Integer_Arithmetic_Op (N : Node_Id) return Boolean is
7554 begin
7555 case Nkind (N) is
7556 when N_Op_Abs
7557 | N_Op_Add
7558 | N_Op_Divide
7559 | N_Op_Expon
7560 | N_Op_Minus
7561 | N_Op_Mod
7562 | N_Op_Multiply
7563 | N_Op_Plus
7564 | N_Op_Rem
7565 | N_Op_Subtract
7567 return Is_Signed_Integer_Type (Etype (N));
7569 when N_Case_Expression
7570 | N_If_Expression
7572 return Is_Signed_Integer_Type (Etype (N));
7574 when others =>
7575 return False;
7576 end case;
7577 end Is_Signed_Integer_Arithmetic_Op;
7579 ----------------------------------
7580 -- Install_Null_Excluding_Check --
7581 ----------------------------------
7583 procedure Install_Null_Excluding_Check (N : Node_Id) is
7584 Loc : constant Source_Ptr := Sloc (Parent (N));
7585 Typ : constant Entity_Id := Etype (N);
7587 function Safe_To_Capture_In_Parameter_Value return Boolean;
7588 -- Determines if it is safe to capture Known_Non_Null status for an
7589 -- the entity referenced by node N. The caller ensures that N is indeed
7590 -- an entity name. It is safe to capture the non-null status for an IN
7591 -- parameter when the reference occurs within a declaration that is sure
7592 -- to be executed as part of the declarative region.
7594 procedure Mark_Non_Null;
7595 -- After installation of check, if the node in question is an entity
7596 -- name, then mark this entity as non-null if possible.
7598 function Safe_To_Capture_In_Parameter_Value return Boolean is
7599 E : constant Entity_Id := Entity (N);
7600 S : constant Entity_Id := Current_Scope;
7601 S_Par : Node_Id;
7603 begin
7604 if Ekind (E) /= E_In_Parameter then
7605 return False;
7606 end if;
7608 -- Two initial context checks. We must be inside a subprogram body
7609 -- with declarations and reference must not appear in nested scopes.
7611 if (Ekind (S) /= E_Function and then Ekind (S) /= E_Procedure)
7612 or else Scope (E) /= S
7613 then
7614 return False;
7615 end if;
7617 S_Par := Parent (Parent (S));
7619 if Nkind (S_Par) /= N_Subprogram_Body
7620 or else No (Declarations (S_Par))
7621 then
7622 return False;
7623 end if;
7625 declare
7626 N_Decl : Node_Id;
7627 P : Node_Id;
7629 begin
7630 -- Retrieve the declaration node of N (if any). Note that N
7631 -- may be a part of a complex initialization expression.
7633 P := Parent (N);
7634 N_Decl := Empty;
7635 while Present (P) loop
7637 -- If we have a short circuit form, and we are within the right
7638 -- hand expression, we return false, since the right hand side
7639 -- is not guaranteed to be elaborated.
7641 if Nkind (P) in N_Short_Circuit
7642 and then N = Right_Opnd (P)
7643 then
7644 return False;
7645 end if;
7647 -- Similarly, if we are in an if expression and not part of the
7648 -- condition, then we return False, since neither the THEN or
7649 -- ELSE dependent expressions will always be elaborated.
7651 if Nkind (P) = N_If_Expression
7652 and then N /= First (Expressions (P))
7653 then
7654 return False;
7655 end if;
7657 -- If within a case expression, and not part of the expression,
7658 -- then return False, since a particular dependent expression
7659 -- may not always be elaborated
7661 if Nkind (P) = N_Case_Expression
7662 and then N /= Expression (P)
7663 then
7664 return False;
7665 end if;
7667 -- While traversing the parent chain, if node N belongs to a
7668 -- statement, then it may never appear in a declarative region.
7670 if Nkind (P) in N_Statement_Other_Than_Procedure_Call
7671 or else Nkind (P) = N_Procedure_Call_Statement
7672 then
7673 return False;
7674 end if;
7676 -- If we are at a declaration, record it and exit
7678 if Nkind (P) in N_Declaration
7679 and then Nkind (P) not in N_Subprogram_Specification
7680 then
7681 N_Decl := P;
7682 exit;
7683 end if;
7685 P := Parent (P);
7686 end loop;
7688 if No (N_Decl) then
7689 return False;
7690 end if;
7692 return List_Containing (N_Decl) = Declarations (S_Par);
7693 end;
7694 end Safe_To_Capture_In_Parameter_Value;
7696 -------------------
7697 -- Mark_Non_Null --
7698 -------------------
7700 procedure Mark_Non_Null is
7701 begin
7702 -- Only case of interest is if node N is an entity name
7704 if Is_Entity_Name (N) then
7706 -- For sure, we want to clear an indication that this is known to
7707 -- be null, since if we get past this check, it definitely is not.
7709 Set_Is_Known_Null (Entity (N), False);
7711 -- We can mark the entity as known to be non-null if either it is
7712 -- safe to capture the value, or in the case of an IN parameter,
7713 -- which is a constant, if the check we just installed is in the
7714 -- declarative region of the subprogram body. In this latter case,
7715 -- a check is decisive for the rest of the body if the expression
7716 -- is sure to be elaborated, since we know we have to elaborate
7717 -- all declarations before executing the body.
7719 -- Couldn't this always be part of Safe_To_Capture_Value ???
7721 if Safe_To_Capture_Value (N, Entity (N))
7722 or else Safe_To_Capture_In_Parameter_Value
7723 then
7724 Set_Is_Known_Non_Null (Entity (N));
7725 end if;
7726 end if;
7727 end Mark_Non_Null;
7729 -- Start of processing for Install_Null_Excluding_Check
7731 begin
7732 pragma Assert (Is_Access_Type (Typ));
7734 -- No check inside a generic, check will be emitted in instance
7736 if Inside_A_Generic then
7737 return;
7738 end if;
7740 -- No check needed if known to be non-null
7742 if Known_Non_Null (N) then
7743 return;
7744 end if;
7746 -- If known to be null, here is where we generate a compile time check
7748 if Known_Null (N) then
7750 -- Avoid generating warning message inside init procs. In SPARK mode
7751 -- we can go ahead and call Apply_Compile_Time_Constraint_Error
7752 -- since it will be turned into an error in any case.
7754 if (not Inside_Init_Proc or else SPARK_Mode = On)
7756 -- Do not emit the warning within a conditional expression,
7757 -- where the expression might not be evaluated, and the warning
7758 -- appear as extraneous noise.
7760 and then not Within_Case_Or_If_Expression (N)
7761 then
7762 Apply_Compile_Time_Constraint_Error
7763 (N, "null value not allowed here??", CE_Access_Check_Failed);
7765 -- Remaining cases, where we silently insert the raise
7767 else
7768 Insert_Action (N,
7769 Make_Raise_Constraint_Error (Loc,
7770 Reason => CE_Access_Check_Failed));
7771 end if;
7773 Mark_Non_Null;
7774 return;
7775 end if;
7777 -- If entity is never assigned, for sure a warning is appropriate
7779 if Is_Entity_Name (N) then
7780 Check_Unset_Reference (N);
7781 end if;
7783 -- No check needed if checks are suppressed on the range. Note that we
7784 -- don't set Is_Known_Non_Null in this case (we could legitimately do
7785 -- so, since the program is erroneous, but we don't like to casually
7786 -- propagate such conclusions from erroneosity).
7788 if Access_Checks_Suppressed (Typ) then
7789 return;
7790 end if;
7792 -- No check needed for access to concurrent record types generated by
7793 -- the expander. This is not just an optimization (though it does indeed
7794 -- remove junk checks). It also avoids generation of junk warnings.
7796 if Nkind (N) in N_Has_Chars
7797 and then Chars (N) = Name_uObject
7798 and then Is_Concurrent_Record_Type
7799 (Directly_Designated_Type (Etype (N)))
7800 then
7801 return;
7802 end if;
7804 -- No check needed in interface thunks since the runtime check is
7805 -- already performed at the caller side.
7807 if Is_Thunk (Current_Scope) then
7808 return;
7809 end if;
7811 -- No check needed for the Get_Current_Excep.all.all idiom generated by
7812 -- the expander within exception handlers, since we know that the value
7813 -- can never be null.
7815 -- Is this really the right way to do this? Normally we generate such
7816 -- code in the expander with checks off, and that's how we suppress this
7817 -- kind of junk check ???
7819 if Nkind (N) = N_Function_Call
7820 and then Nkind (Name (N)) = N_Explicit_Dereference
7821 and then Nkind (Prefix (Name (N))) = N_Identifier
7822 and then Is_RTE (Entity (Prefix (Name (N))), RE_Get_Current_Excep)
7823 then
7824 return;
7825 end if;
7827 -- Otherwise install access check
7829 Insert_Action (N,
7830 Make_Raise_Constraint_Error (Loc,
7831 Condition =>
7832 Make_Op_Eq (Loc,
7833 Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
7834 Right_Opnd => Make_Null (Loc)),
7835 Reason => CE_Access_Check_Failed));
7837 Mark_Non_Null;
7838 end Install_Null_Excluding_Check;
7840 -----------------------------------------
7841 -- Install_Primitive_Elaboration_Check --
7842 -----------------------------------------
7844 procedure Install_Primitive_Elaboration_Check (Subp_Body : Node_Id) is
7845 function Within_Compilation_Unit_Instance
7846 (Subp_Id : Entity_Id) return Boolean;
7847 -- Determine whether subprogram Subp_Id appears within an instance which
7848 -- acts as a compilation unit.
7850 --------------------------------------
7851 -- Within_Compilation_Unit_Instance --
7852 --------------------------------------
7854 function Within_Compilation_Unit_Instance
7855 (Subp_Id : Entity_Id) return Boolean
7857 Pack : Entity_Id;
7859 begin
7860 -- Examine the scope chain looking for a compilation-unit-level
7861 -- instance.
7863 Pack := Scope (Subp_Id);
7864 while Present (Pack) and then Pack /= Standard_Standard loop
7865 if Ekind (Pack) = E_Package
7866 and then Is_Generic_Instance (Pack)
7867 and then Nkind (Parent (Unit_Declaration_Node (Pack))) =
7868 N_Compilation_Unit
7869 then
7870 return True;
7871 end if;
7873 Pack := Scope (Pack);
7874 end loop;
7876 return False;
7877 end Within_Compilation_Unit_Instance;
7879 -- Local declarations
7881 Context : constant Node_Id := Parent (Subp_Body);
7882 Loc : constant Source_Ptr := Sloc (Subp_Body);
7883 Subp_Id : constant Entity_Id := Unique_Defining_Entity (Subp_Body);
7884 Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
7886 Decls : List_Id;
7887 Flag_Id : Entity_Id;
7888 Set_Ins : Node_Id;
7889 Set_Stmt : Node_Id;
7890 Tag_Typ : Entity_Id;
7892 -- Start of processing for Install_Primitive_Elaboration_Check
7894 begin
7895 -- Do not generate an elaboration check in compilation modes where
7896 -- expansion is not desirable.
7898 if ASIS_Mode or GNATprove_Mode then
7899 return;
7901 -- Do not generate an elaboration check if all checks have been
7902 -- suppressed.
7904 elsif Suppress_Checks then
7905 return;
7907 -- Do not generate an elaboration check if the related subprogram is
7908 -- not subjected to accessibility checks.
7910 elsif Elaboration_Checks_Suppressed (Subp_Id) then
7911 return;
7913 -- Do not generate an elaboration check if such code is not desirable
7915 elsif Restriction_Active (No_Elaboration_Code) then
7916 return;
7918 -- Do not consider subprograms which act as compilation units, because
7919 -- they cannot be the target of a dispatching call.
7921 elsif Nkind (Context) = N_Compilation_Unit then
7922 return;
7924 -- Do not consider anything other than nonabstract library-level source
7925 -- primitives.
7927 elsif not
7928 (Comes_From_Source (Subp_Id)
7929 and then Is_Library_Level_Entity (Subp_Id)
7930 and then Is_Primitive (Subp_Id)
7931 and then not Is_Abstract_Subprogram (Subp_Id))
7932 then
7933 return;
7935 -- Do not consider inlined primitives, because once the body is inlined
7936 -- the reference to the elaboration flag will be out of place and will
7937 -- result in an undefined symbol.
7939 elsif Is_Inlined (Subp_Id) or else Has_Pragma_Inline (Subp_Id) then
7940 return;
7942 -- Do not generate a duplicate elaboration check. This happens only in
7943 -- the case of primitives completed by an expression function, as the
7944 -- corresponding body is apparently analyzed and expanded twice.
7946 elsif Analyzed (Subp_Body) then
7947 return;
7949 -- Do not consider primitives which occur within an instance that acts
7950 -- as a compilation unit. Such an instance defines its spec and body out
7951 -- of order (body is first) within the tree, which causes the reference
7952 -- to the elaboration flag to appear as an undefined symbol.
7954 elsif Within_Compilation_Unit_Instance (Subp_Id) then
7955 return;
7956 end if;
7958 Tag_Typ := Find_Dispatching_Type (Subp_Id);
7960 -- Only tagged primitives may be the target of a dispatching call
7962 if No (Tag_Typ) then
7963 return;
7965 -- Do not consider finalization-related primitives, because they may
7966 -- need to be called while elaboration is taking place.
7968 elsif Is_Controlled (Tag_Typ)
7969 and then Nam_In (Chars (Subp_Id), Name_Adjust,
7970 Name_Finalize,
7971 Name_Initialize)
7972 then
7973 return;
7974 end if;
7976 -- Create the declaration of the elaboration flag. The name carries a
7977 -- unique counter in case of name overloading.
7979 Flag_Id :=
7980 Make_Defining_Identifier (Loc,
7981 Chars => New_External_Name (Chars (Subp_Id), 'E', -1));
7982 Set_Is_Frozen (Flag_Id);
7984 -- Insert the declaration of the elaboration flag in front of the
7985 -- primitive spec and analyze it in the proper context.
7987 Push_Scope (Scope (Subp_Id));
7989 -- Generate:
7990 -- E : Boolean := False;
7992 Insert_Action (Subp_Decl,
7993 Make_Object_Declaration (Loc,
7994 Defining_Identifier => Flag_Id,
7995 Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc),
7996 Expression => New_Occurrence_Of (Standard_False, Loc)));
7997 Pop_Scope;
7999 -- Prevent the compiler from optimizing the elaboration check by killing
8000 -- the current value of the flag and the associated assignment.
8002 Set_Current_Value (Flag_Id, Empty);
8003 Set_Last_Assignment (Flag_Id, Empty);
8005 -- Add a check at the top of the body declarations to ensure that the
8006 -- elaboration flag has been set.
8008 Decls := Declarations (Subp_Body);
8010 if No (Decls) then
8011 Decls := New_List;
8012 Set_Declarations (Subp_Body, Decls);
8013 end if;
8015 -- Generate:
8016 -- if not F then
8017 -- raise Program_Error with "access before elaboration";
8018 -- end if;
8020 Prepend_To (Decls,
8021 Make_Raise_Program_Error (Loc,
8022 Condition =>
8023 Make_Op_Not (Loc,
8024 Right_Opnd => New_Occurrence_Of (Flag_Id, Loc)),
8025 Reason => PE_Access_Before_Elaboration));
8027 Analyze (First (Decls));
8029 -- Set the elaboration flag once the body has been elaborated. Insert
8030 -- the statement after the subprogram stub when the primitive body is
8031 -- a subunit.
8033 if Nkind (Context) = N_Subunit then
8034 Set_Ins := Corresponding_Stub (Context);
8035 else
8036 Set_Ins := Subp_Body;
8037 end if;
8039 -- Generate:
8040 -- E := True;
8042 Set_Stmt :=
8043 Make_Assignment_Statement (Loc,
8044 Name => New_Occurrence_Of (Flag_Id, Loc),
8045 Expression => New_Occurrence_Of (Standard_True, Loc));
8047 -- Mark the assignment statement as elaboration code. This allows the
8048 -- early call region mechanism (see Sem_Elab) to properly ignore such
8049 -- assignments even though they are non-preelaborable code.
8051 Set_Is_Elaboration_Code (Set_Stmt);
8053 Insert_After_And_Analyze (Set_Ins, Set_Stmt);
8054 end Install_Primitive_Elaboration_Check;
8056 --------------------------
8057 -- Install_Static_Check --
8058 --------------------------
8060 procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
8061 Stat : constant Boolean := Is_OK_Static_Expression (R_Cno);
8062 Typ : constant Entity_Id := Etype (R_Cno);
8064 begin
8065 Rewrite (R_Cno,
8066 Make_Raise_Constraint_Error (Loc,
8067 Reason => CE_Range_Check_Failed));
8068 Set_Analyzed (R_Cno);
8069 Set_Etype (R_Cno, Typ);
8070 Set_Raises_Constraint_Error (R_Cno);
8071 Set_Is_Static_Expression (R_Cno, Stat);
8073 -- Now deal with possible local raise handling
8075 Possible_Local_Raise (R_Cno, Standard_Constraint_Error);
8076 end Install_Static_Check;
8078 -------------------------
8079 -- Is_Check_Suppressed --
8080 -------------------------
8082 function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean is
8083 Ptr : Suppress_Stack_Entry_Ptr;
8085 begin
8086 -- First search the local entity suppress stack. We search this from the
8087 -- top of the stack down so that we get the innermost entry that applies
8088 -- to this case if there are nested entries.
8090 Ptr := Local_Suppress_Stack_Top;
8091 while Ptr /= null loop
8092 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8093 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8094 then
8095 return Ptr.Suppress;
8096 end if;
8098 Ptr := Ptr.Prev;
8099 end loop;
8101 -- Now search the global entity suppress table for a matching entry.
8102 -- We also search this from the top down so that if there are multiple
8103 -- pragmas for the same entity, the last one applies (not clear what
8104 -- or whether the RM specifies this handling, but it seems reasonable).
8106 Ptr := Global_Suppress_Stack_Top;
8107 while Ptr /= null loop
8108 if (Ptr.Entity = Empty or else Ptr.Entity = E)
8109 and then (Ptr.Check = All_Checks or else Ptr.Check = C)
8110 then
8111 return Ptr.Suppress;
8112 end if;
8114 Ptr := Ptr.Prev;
8115 end loop;
8117 -- If we did not find a matching entry, then use the normal scope
8118 -- suppress value after all (actually this will be the global setting
8119 -- since it clearly was not overridden at any point). For a predefined
8120 -- check, we test the specific flag. For a user defined check, we check
8121 -- the All_Checks flag. The Overflow flag requires special handling to
8122 -- deal with the General vs Assertion case.
8124 if C = Overflow_Check then
8125 return Overflow_Checks_Suppressed (Empty);
8127 elsif C in Predefined_Check_Id then
8128 return Scope_Suppress.Suppress (C);
8130 else
8131 return Scope_Suppress.Suppress (All_Checks);
8132 end if;
8133 end Is_Check_Suppressed;
8135 ---------------------
8136 -- Kill_All_Checks --
8137 ---------------------
8139 procedure Kill_All_Checks is
8140 begin
8141 if Debug_Flag_CC then
8142 w ("Kill_All_Checks");
8143 end if;
8145 -- We reset the number of saved checks to zero, and also modify all
8146 -- stack entries for statement ranges to indicate that the number of
8147 -- checks at each level is now zero.
8149 Num_Saved_Checks := 0;
8151 -- Note: the Int'Min here avoids any possibility of J being out of
8152 -- range when called from e.g. Conditional_Statements_Begin.
8154 for J in 1 .. Int'Min (Saved_Checks_TOS, Saved_Checks_Stack'Last) loop
8155 Saved_Checks_Stack (J) := 0;
8156 end loop;
8157 end Kill_All_Checks;
8159 -----------------
8160 -- Kill_Checks --
8161 -----------------
8163 procedure Kill_Checks (V : Entity_Id) is
8164 begin
8165 if Debug_Flag_CC then
8166 w ("Kill_Checks for entity", Int (V));
8167 end if;
8169 for J in 1 .. Num_Saved_Checks loop
8170 if Saved_Checks (J).Entity = V then
8171 if Debug_Flag_CC then
8172 w (" Checks killed for saved check ", J);
8173 end if;
8175 Saved_Checks (J).Killed := True;
8176 end if;
8177 end loop;
8178 end Kill_Checks;
8180 ------------------------------
8181 -- Length_Checks_Suppressed --
8182 ------------------------------
8184 function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
8185 begin
8186 if Present (E) and then Checks_May_Be_Suppressed (E) then
8187 return Is_Check_Suppressed (E, Length_Check);
8188 else
8189 return Scope_Suppress.Suppress (Length_Check);
8190 end if;
8191 end Length_Checks_Suppressed;
8193 -----------------------
8194 -- Make_Bignum_Block --
8195 -----------------------
8197 function Make_Bignum_Block (Loc : Source_Ptr) return Node_Id is
8198 M : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uM);
8199 begin
8200 return
8201 Make_Block_Statement (Loc,
8202 Declarations =>
8203 New_List (Build_SS_Mark_Call (Loc, M)),
8204 Handled_Statement_Sequence =>
8205 Make_Handled_Sequence_Of_Statements (Loc,
8206 Statements => New_List (Build_SS_Release_Call (Loc, M))));
8207 end Make_Bignum_Block;
8209 ----------------------------------
8210 -- Minimize_Eliminate_Overflows --
8211 ----------------------------------
8213 -- This is a recursive routine that is called at the top of an expression
8214 -- tree to properly process overflow checking for a whole subtree by making
8215 -- recursive calls to process operands. This processing may involve the use
8216 -- of bignum or long long integer arithmetic, which will change the types
8217 -- of operands and results. That's why we can't do this bottom up (since
8218 -- it would interfere with semantic analysis).
8220 -- What happens is that if MINIMIZED/ELIMINATED mode is in effect then
8221 -- the operator expansion routines, as well as the expansion routines for
8222 -- if/case expression, do nothing (for the moment) except call the routine
8223 -- to apply the overflow check (Apply_Arithmetic_Overflow_Check). That
8224 -- routine does nothing for non top-level nodes, so at the point where the
8225 -- call is made for the top level node, the entire expression subtree has
8226 -- not been expanded, or processed for overflow. All that has to happen as
8227 -- a result of the top level call to this routine.
8229 -- As noted above, the overflow processing works by making recursive calls
8230 -- for the operands, and figuring out what to do, based on the processing
8231 -- of these operands (e.g. if a bignum operand appears, the parent op has
8232 -- to be done in bignum mode), and the determined ranges of the operands.
8234 -- After possible rewriting of a constituent subexpression node, a call is
8235 -- made to either reexpand the node (if nothing has changed) or reanalyze
8236 -- the node (if it has been modified by the overflow check processing). The
8237 -- Analyzed_Flag is set to False before the reexpand/reanalyze. To avoid
8238 -- a recursive call into the whole overflow apparatus, an important rule
8239 -- for this call is that the overflow handling mode must be temporarily set
8240 -- to STRICT.
8242 procedure Minimize_Eliminate_Overflows
8243 (N : Node_Id;
8244 Lo : out Uint;
8245 Hi : out Uint;
8246 Top_Level : Boolean)
8248 Rtyp : constant Entity_Id := Etype (N);
8249 pragma Assert (Is_Signed_Integer_Type (Rtyp));
8250 -- Result type, must be a signed integer type
8252 Check_Mode : constant Overflow_Mode_Type := Overflow_Check_Mode;
8253 pragma Assert (Check_Mode in Minimized_Or_Eliminated);
8255 Loc : constant Source_Ptr := Sloc (N);
8257 Rlo, Rhi : Uint;
8258 -- Ranges of values for right operand (operator case)
8260 Llo : Uint := No_Uint; -- initialize to prevent warning
8261 Lhi : Uint := No_Uint; -- initialize to prevent warning
8262 -- Ranges of values for left operand (operator case)
8264 LLIB : constant Entity_Id := Base_Type (Standard_Long_Long_Integer);
8265 -- Operands and results are of this type when we convert
8267 LLLo : constant Uint := Intval (Type_Low_Bound (LLIB));
8268 LLHi : constant Uint := Intval (Type_High_Bound (LLIB));
8269 -- Bounds of Long_Long_Integer
8271 Binary : constant Boolean := Nkind (N) in N_Binary_Op;
8272 -- Indicates binary operator case
8274 OK : Boolean;
8275 -- Used in call to Determine_Range
8277 Bignum_Operands : Boolean;
8278 -- Set True if one or more operands is already of type Bignum, meaning
8279 -- that for sure (regardless of Top_Level setting) we are committed to
8280 -- doing the operation in Bignum mode (or in the case of a case or if
8281 -- expression, converting all the dependent expressions to Bignum).
8283 Long_Long_Integer_Operands : Boolean;
8284 -- Set True if one or more operands is already of type Long_Long_Integer
8285 -- which means that if the result is known to be in the result type
8286 -- range, then we must convert such operands back to the result type.
8288 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False);
8289 -- This is called when we have modified the node and we therefore need
8290 -- to reanalyze it. It is important that we reset the mode to STRICT for
8291 -- this reanalysis, since if we leave it in MINIMIZED or ELIMINATED mode
8292 -- we would reenter this routine recursively which would not be good.
8293 -- The argument Suppress is set True if we also want to suppress
8294 -- overflow checking for the reexpansion (this is set when we know
8295 -- overflow is not possible). Typ is the type for the reanalysis.
8297 procedure Reexpand (Suppress : Boolean := False);
8298 -- This is like Reanalyze, but does not do the Analyze step, it only
8299 -- does a reexpansion. We do this reexpansion in STRICT mode, so that
8300 -- instead of reentering the MINIMIZED/ELIMINATED mode processing, we
8301 -- follow the normal expansion path (e.g. converting A**4 to A**2**2).
8302 -- Note that skipping reanalysis is not just an optimization, testing
8303 -- has showed up several complex cases in which reanalyzing an already
8304 -- analyzed node causes incorrect behavior.
8306 function In_Result_Range return Boolean;
8307 -- Returns True iff Lo .. Hi are within range of the result type
8309 procedure Max (A : in out Uint; B : Uint);
8310 -- If A is No_Uint, sets A to B, else to UI_Max (A, B)
8312 procedure Min (A : in out Uint; B : Uint);
8313 -- If A is No_Uint, sets A to B, else to UI_Min (A, B)
8315 ---------------------
8316 -- In_Result_Range --
8317 ---------------------
8319 function In_Result_Range return Boolean is
8320 begin
8321 if Lo = No_Uint or else Hi = No_Uint then
8322 return False;
8324 elsif Is_OK_Static_Subtype (Etype (N)) then
8325 return Lo >= Expr_Value (Type_Low_Bound (Rtyp))
8326 and then
8327 Hi <= Expr_Value (Type_High_Bound (Rtyp));
8329 else
8330 return Lo >= Expr_Value (Type_Low_Bound (Base_Type (Rtyp)))
8331 and then
8332 Hi <= Expr_Value (Type_High_Bound (Base_Type (Rtyp)));
8333 end if;
8334 end In_Result_Range;
8336 ---------
8337 -- Max --
8338 ---------
8340 procedure Max (A : in out Uint; B : Uint) is
8341 begin
8342 if A = No_Uint or else B > A then
8343 A := B;
8344 end if;
8345 end Max;
8347 ---------
8348 -- Min --
8349 ---------
8351 procedure Min (A : in out Uint; B : Uint) is
8352 begin
8353 if A = No_Uint or else B < A then
8354 A := B;
8355 end if;
8356 end Min;
8358 ---------------
8359 -- Reanalyze --
8360 ---------------
8362 procedure Reanalyze (Typ : Entity_Id; Suppress : Boolean := False) is
8363 Svg : constant Overflow_Mode_Type :=
8364 Scope_Suppress.Overflow_Mode_General;
8365 Sva : constant Overflow_Mode_Type :=
8366 Scope_Suppress.Overflow_Mode_Assertions;
8367 Svo : constant Boolean :=
8368 Scope_Suppress.Suppress (Overflow_Check);
8370 begin
8371 Scope_Suppress.Overflow_Mode_General := Strict;
8372 Scope_Suppress.Overflow_Mode_Assertions := Strict;
8374 if Suppress then
8375 Scope_Suppress.Suppress (Overflow_Check) := True;
8376 end if;
8378 Analyze_And_Resolve (N, Typ);
8380 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8381 Scope_Suppress.Overflow_Mode_General := Svg;
8382 Scope_Suppress.Overflow_Mode_Assertions := Sva;
8383 end Reanalyze;
8385 --------------
8386 -- Reexpand --
8387 --------------
8389 procedure Reexpand (Suppress : Boolean := False) is
8390 Svg : constant Overflow_Mode_Type :=
8391 Scope_Suppress.Overflow_Mode_General;
8392 Sva : constant Overflow_Mode_Type :=
8393 Scope_Suppress.Overflow_Mode_Assertions;
8394 Svo : constant Boolean :=
8395 Scope_Suppress.Suppress (Overflow_Check);
8397 begin
8398 Scope_Suppress.Overflow_Mode_General := Strict;
8399 Scope_Suppress.Overflow_Mode_Assertions := Strict;
8400 Set_Analyzed (N, False);
8402 if Suppress then
8403 Scope_Suppress.Suppress (Overflow_Check) := True;
8404 end if;
8406 Expand (N);
8408 Scope_Suppress.Suppress (Overflow_Check) := Svo;
8409 Scope_Suppress.Overflow_Mode_General := Svg;
8410 Scope_Suppress.Overflow_Mode_Assertions := Sva;
8411 end Reexpand;
8413 -- Start of processing for Minimize_Eliminate_Overflows
8415 begin
8416 -- Default initialize Lo and Hi since these are not guaranteed to be
8417 -- set otherwise.
8419 Lo := No_Uint;
8420 Hi := No_Uint;
8422 -- Case where we do not have a signed integer arithmetic operation
8424 if not Is_Signed_Integer_Arithmetic_Op (N) then
8426 -- Use the normal Determine_Range routine to get the range. We
8427 -- don't require operands to be valid, invalid values may result in
8428 -- rubbish results where the result has not been properly checked for
8429 -- overflow, that's fine.
8431 Determine_Range (N, OK, Lo, Hi, Assume_Valid => False);
8433 -- If Determine_Range did not work (can this in fact happen? Not
8434 -- clear but might as well protect), use type bounds.
8436 if not OK then
8437 Lo := Intval (Type_Low_Bound (Base_Type (Etype (N))));
8438 Hi := Intval (Type_High_Bound (Base_Type (Etype (N))));
8439 end if;
8441 -- If we don't have a binary operator, all we have to do is to set
8442 -- the Hi/Lo range, so we are done.
8444 return;
8446 -- Processing for if expression
8448 elsif Nkind (N) = N_If_Expression then
8449 declare
8450 Then_DE : constant Node_Id := Next (First (Expressions (N)));
8451 Else_DE : constant Node_Id := Next (Then_DE);
8453 begin
8454 Bignum_Operands := False;
8456 Minimize_Eliminate_Overflows
8457 (Then_DE, Lo, Hi, Top_Level => False);
8459 if Lo = No_Uint then
8460 Bignum_Operands := True;
8461 end if;
8463 Minimize_Eliminate_Overflows
8464 (Else_DE, Rlo, Rhi, Top_Level => False);
8466 if Rlo = No_Uint then
8467 Bignum_Operands := True;
8468 else
8469 Long_Long_Integer_Operands :=
8470 Etype (Then_DE) = LLIB or else Etype (Else_DE) = LLIB;
8472 Min (Lo, Rlo);
8473 Max (Hi, Rhi);
8474 end if;
8476 -- If at least one of our operands is now Bignum, we must rebuild
8477 -- the if expression to use Bignum operands. We will analyze the
8478 -- rebuilt if expression with overflow checks off, since once we
8479 -- are in bignum mode, we are all done with overflow checks.
8481 if Bignum_Operands then
8482 Rewrite (N,
8483 Make_If_Expression (Loc,
8484 Expressions => New_List (
8485 Remove_Head (Expressions (N)),
8486 Convert_To_Bignum (Then_DE),
8487 Convert_To_Bignum (Else_DE)),
8488 Is_Elsif => Is_Elsif (N)));
8490 Reanalyze (RTE (RE_Bignum), Suppress => True);
8492 -- If we have no Long_Long_Integer operands, then we are in result
8493 -- range, since it means that none of our operands felt the need
8494 -- to worry about overflow (otherwise it would have already been
8495 -- converted to long long integer or bignum). We reexpand to
8496 -- complete the expansion of the if expression (but we do not
8497 -- need to reanalyze).
8499 elsif not Long_Long_Integer_Operands then
8500 Set_Do_Overflow_Check (N, False);
8501 Reexpand;
8503 -- Otherwise convert us to long long integer mode. Note that we
8504 -- don't need any further overflow checking at this level.
8506 else
8507 Convert_To_And_Rewrite (LLIB, Then_DE);
8508 Convert_To_And_Rewrite (LLIB, Else_DE);
8509 Set_Etype (N, LLIB);
8511 -- Now reanalyze with overflow checks off
8513 Set_Do_Overflow_Check (N, False);
8514 Reanalyze (LLIB, Suppress => True);
8515 end if;
8516 end;
8518 return;
8520 -- Here for case expression
8522 elsif Nkind (N) = N_Case_Expression then
8523 Bignum_Operands := False;
8524 Long_Long_Integer_Operands := False;
8526 declare
8527 Alt : Node_Id;
8529 begin
8530 -- Loop through expressions applying recursive call
8532 Alt := First (Alternatives (N));
8533 while Present (Alt) loop
8534 declare
8535 Aexp : constant Node_Id := Expression (Alt);
8537 begin
8538 Minimize_Eliminate_Overflows
8539 (Aexp, Lo, Hi, Top_Level => False);
8541 if Lo = No_Uint then
8542 Bignum_Operands := True;
8543 elsif Etype (Aexp) = LLIB then
8544 Long_Long_Integer_Operands := True;
8545 end if;
8546 end;
8548 Next (Alt);
8549 end loop;
8551 -- If we have no bignum or long long integer operands, it means
8552 -- that none of our dependent expressions could raise overflow.
8553 -- In this case, we simply return with no changes except for
8554 -- resetting the overflow flag, since we are done with overflow
8555 -- checks for this node. We will reexpand to get the needed
8556 -- expansion for the case expression, but we do not need to
8557 -- reanalyze, since nothing has changed.
8559 if not (Bignum_Operands or Long_Long_Integer_Operands) then
8560 Set_Do_Overflow_Check (N, False);
8561 Reexpand (Suppress => True);
8563 -- Otherwise we are going to rebuild the case expression using
8564 -- either bignum or long long integer operands throughout.
8566 else
8567 declare
8568 Rtype : Entity_Id;
8569 pragma Warnings (Off, Rtype);
8570 New_Alts : List_Id;
8571 New_Exp : Node_Id;
8573 begin
8574 New_Alts := New_List;
8575 Alt := First (Alternatives (N));
8576 while Present (Alt) loop
8577 if Bignum_Operands then
8578 New_Exp := Convert_To_Bignum (Expression (Alt));
8579 Rtype := RTE (RE_Bignum);
8580 else
8581 New_Exp := Convert_To (LLIB, Expression (Alt));
8582 Rtype := LLIB;
8583 end if;
8585 Append_To (New_Alts,
8586 Make_Case_Expression_Alternative (Sloc (Alt),
8587 Actions => No_List,
8588 Discrete_Choices => Discrete_Choices (Alt),
8589 Expression => New_Exp));
8591 Next (Alt);
8592 end loop;
8594 Rewrite (N,
8595 Make_Case_Expression (Loc,
8596 Expression => Expression (N),
8597 Alternatives => New_Alts));
8599 Reanalyze (Rtype, Suppress => True);
8600 end;
8601 end if;
8602 end;
8604 return;
8605 end if;
8607 -- If we have an arithmetic operator we make recursive calls on the
8608 -- operands to get the ranges (and to properly process the subtree
8609 -- that lies below us).
8611 Minimize_Eliminate_Overflows
8612 (Right_Opnd (N), Rlo, Rhi, Top_Level => False);
8614 if Binary then
8615 Minimize_Eliminate_Overflows
8616 (Left_Opnd (N), Llo, Lhi, Top_Level => False);
8617 end if;
8619 -- Record if we have Long_Long_Integer operands
8621 Long_Long_Integer_Operands :=
8622 Etype (Right_Opnd (N)) = LLIB
8623 or else (Binary and then Etype (Left_Opnd (N)) = LLIB);
8625 -- If either operand is a bignum, then result will be a bignum and we
8626 -- don't need to do any range analysis. As previously discussed we could
8627 -- do range analysis in such cases, but it could mean working with giant
8628 -- numbers at compile time for very little gain (the number of cases
8629 -- in which we could slip back from bignum mode is small).
8631 if Rlo = No_Uint or else (Binary and then Llo = No_Uint) then
8632 Lo := No_Uint;
8633 Hi := No_Uint;
8634 Bignum_Operands := True;
8636 -- Otherwise compute result range
8638 else
8639 Bignum_Operands := False;
8641 case Nkind (N) is
8643 -- Absolute value
8645 when N_Op_Abs =>
8646 Lo := Uint_0;
8647 Hi := UI_Max (abs Rlo, abs Rhi);
8649 -- Addition
8651 when N_Op_Add =>
8652 Lo := Llo + Rlo;
8653 Hi := Lhi + Rhi;
8655 -- Division
8657 when N_Op_Divide =>
8659 -- If the right operand can only be zero, set 0..0
8661 if Rlo = 0 and then Rhi = 0 then
8662 Lo := Uint_0;
8663 Hi := Uint_0;
8665 -- Possible bounds of division must come from dividing end
8666 -- values of the input ranges (four possibilities), provided
8667 -- zero is not included in the possible values of the right
8668 -- operand.
8670 -- Otherwise, we just consider two intervals of values for
8671 -- the right operand: the interval of negative values (up to
8672 -- -1) and the interval of positive values (starting at 1).
8673 -- Since division by 1 is the identity, and division by -1
8674 -- is negation, we get all possible bounds of division in that
8675 -- case by considering:
8676 -- - all values from the division of end values of input
8677 -- ranges;
8678 -- - the end values of the left operand;
8679 -- - the negation of the end values of the left operand.
8681 else
8682 declare
8683 Mrk : constant Uintp.Save_Mark := Mark;
8684 -- Mark so we can release the RR and Ev values
8686 Ev1 : Uint;
8687 Ev2 : Uint;
8688 Ev3 : Uint;
8689 Ev4 : Uint;
8691 begin
8692 -- Discard extreme values of zero for the divisor, since
8693 -- they will simply result in an exception in any case.
8695 if Rlo = 0 then
8696 Rlo := Uint_1;
8697 elsif Rhi = 0 then
8698 Rhi := -Uint_1;
8699 end if;
8701 -- Compute possible bounds coming from dividing end
8702 -- values of the input ranges.
8704 Ev1 := Llo / Rlo;
8705 Ev2 := Llo / Rhi;
8706 Ev3 := Lhi / Rlo;
8707 Ev4 := Lhi / Rhi;
8709 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8710 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8712 -- If the right operand can be both negative or positive,
8713 -- include the end values of the left operand in the
8714 -- extreme values, as well as their negation.
8716 if Rlo < 0 and then Rhi > 0 then
8717 Ev1 := Llo;
8718 Ev2 := -Llo;
8719 Ev3 := Lhi;
8720 Ev4 := -Lhi;
8722 Min (Lo,
8723 UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4)));
8724 Max (Hi,
8725 UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4)));
8726 end if;
8728 -- Release the RR and Ev values
8730 Release_And_Save (Mrk, Lo, Hi);
8731 end;
8732 end if;
8734 -- Exponentiation
8736 when N_Op_Expon =>
8738 -- Discard negative values for the exponent, since they will
8739 -- simply result in an exception in any case.
8741 if Rhi < 0 then
8742 Rhi := Uint_0;
8743 elsif Rlo < 0 then
8744 Rlo := Uint_0;
8745 end if;
8747 -- Estimate number of bits in result before we go computing
8748 -- giant useless bounds. Basically the number of bits in the
8749 -- result is the number of bits in the base multiplied by the
8750 -- value of the exponent. If this is big enough that the result
8751 -- definitely won't fit in Long_Long_Integer, switch to bignum
8752 -- mode immediately, and avoid computing giant bounds.
8754 -- The comparison here is approximate, but conservative, it
8755 -- only clicks on cases that are sure to exceed the bounds.
8757 if Num_Bits (UI_Max (abs Llo, abs Lhi)) * Rhi + 1 > 100 then
8758 Lo := No_Uint;
8759 Hi := No_Uint;
8761 -- If right operand is zero then result is 1
8763 elsif Rhi = 0 then
8764 Lo := Uint_1;
8765 Hi := Uint_1;
8767 else
8768 -- High bound comes either from exponentiation of largest
8769 -- positive value to largest exponent value, or from
8770 -- the exponentiation of most negative value to an
8771 -- even exponent.
8773 declare
8774 Hi1, Hi2 : Uint;
8776 begin
8777 if Lhi > 0 then
8778 Hi1 := Lhi ** Rhi;
8779 else
8780 Hi1 := Uint_0;
8781 end if;
8783 if Llo < 0 then
8784 if Rhi mod 2 = 0 then
8785 Hi2 := Llo ** Rhi;
8786 else
8787 Hi2 := Llo ** (Rhi - 1);
8788 end if;
8789 else
8790 Hi2 := Uint_0;
8791 end if;
8793 Hi := UI_Max (Hi1, Hi2);
8794 end;
8796 -- Result can only be negative if base can be negative
8798 if Llo < 0 then
8799 if Rhi mod 2 = 0 then
8800 Lo := Llo ** (Rhi - 1);
8801 else
8802 Lo := Llo ** Rhi;
8803 end if;
8805 -- Otherwise low bound is minimum ** minimum
8807 else
8808 Lo := Llo ** Rlo;
8809 end if;
8810 end if;
8812 -- Negation
8814 when N_Op_Minus =>
8815 Lo := -Rhi;
8816 Hi := -Rlo;
8818 -- Mod
8820 when N_Op_Mod =>
8821 declare
8822 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8823 -- This is the maximum absolute value of the result
8825 begin
8826 Lo := Uint_0;
8827 Hi := Uint_0;
8829 -- The result depends only on the sign and magnitude of
8830 -- the right operand, it does not depend on the sign or
8831 -- magnitude of the left operand.
8833 if Rlo < 0 then
8834 Lo := -Maxabs;
8835 end if;
8837 if Rhi > 0 then
8838 Hi := Maxabs;
8839 end if;
8840 end;
8842 -- Multiplication
8844 when N_Op_Multiply =>
8846 -- Possible bounds of multiplication must come from multiplying
8847 -- end values of the input ranges (four possibilities).
8849 declare
8850 Mrk : constant Uintp.Save_Mark := Mark;
8851 -- Mark so we can release the Ev values
8853 Ev1 : constant Uint := Llo * Rlo;
8854 Ev2 : constant Uint := Llo * Rhi;
8855 Ev3 : constant Uint := Lhi * Rlo;
8856 Ev4 : constant Uint := Lhi * Rhi;
8858 begin
8859 Lo := UI_Min (UI_Min (Ev1, Ev2), UI_Min (Ev3, Ev4));
8860 Hi := UI_Max (UI_Max (Ev1, Ev2), UI_Max (Ev3, Ev4));
8862 -- Release the Ev values
8864 Release_And_Save (Mrk, Lo, Hi);
8865 end;
8867 -- Plus operator (affirmation)
8869 when N_Op_Plus =>
8870 Lo := Rlo;
8871 Hi := Rhi;
8873 -- Remainder
8875 when N_Op_Rem =>
8876 declare
8877 Maxabs : constant Uint := UI_Max (abs Rlo, abs Rhi) - 1;
8878 -- This is the maximum absolute value of the result. Note
8879 -- that the result range does not depend on the sign of the
8880 -- right operand.
8882 begin
8883 Lo := Uint_0;
8884 Hi := Uint_0;
8886 -- Case of left operand negative, which results in a range
8887 -- of -Maxabs .. 0 for those negative values. If there are
8888 -- no negative values then Lo value of result is always 0.
8890 if Llo < 0 then
8891 Lo := -Maxabs;
8892 end if;
8894 -- Case of left operand positive
8896 if Lhi > 0 then
8897 Hi := Maxabs;
8898 end if;
8899 end;
8901 -- Subtract
8903 when N_Op_Subtract =>
8904 Lo := Llo - Rhi;
8905 Hi := Lhi - Rlo;
8907 -- Nothing else should be possible
8909 when others =>
8910 raise Program_Error;
8911 end case;
8912 end if;
8914 -- Here for the case where we have not rewritten anything (no bignum
8915 -- operands or long long integer operands), and we know the result.
8916 -- If we know we are in the result range, and we do not have Bignum
8917 -- operands or Long_Long_Integer operands, we can just reexpand with
8918 -- overflow checks turned off (since we know we cannot have overflow).
8919 -- As always the reexpansion is required to complete expansion of the
8920 -- operator, but we do not need to reanalyze, and we prevent recursion
8921 -- by suppressing the check.
8923 if not (Bignum_Operands or Long_Long_Integer_Operands)
8924 and then In_Result_Range
8925 then
8926 Set_Do_Overflow_Check (N, False);
8927 Reexpand (Suppress => True);
8928 return;
8930 -- Here we know that we are not in the result range, and in the general
8931 -- case we will move into either the Bignum or Long_Long_Integer domain
8932 -- to compute the result. However, there is one exception. If we are
8933 -- at the top level, and we do not have Bignum or Long_Long_Integer
8934 -- operands, we will have to immediately convert the result back to
8935 -- the result type, so there is no point in Bignum/Long_Long_Integer
8936 -- fiddling.
8938 elsif Top_Level
8939 and then not (Bignum_Operands or Long_Long_Integer_Operands)
8941 -- One further refinement. If we are at the top level, but our parent
8942 -- is a type conversion, then go into bignum or long long integer node
8943 -- since the result will be converted to that type directly without
8944 -- going through the result type, and we may avoid an overflow. This
8945 -- is the case for example of Long_Long_Integer (A ** 4), where A is
8946 -- of type Integer, and the result A ** 4 fits in Long_Long_Integer
8947 -- but does not fit in Integer.
8949 and then Nkind (Parent (N)) /= N_Type_Conversion
8950 then
8951 -- Here keep original types, but we need to complete analysis
8953 -- One subtlety. We can't just go ahead and do an analyze operation
8954 -- here because it will cause recursion into the whole MINIMIZED/
8955 -- ELIMINATED overflow processing which is not what we want. Here
8956 -- we are at the top level, and we need a check against the result
8957 -- mode (i.e. we want to use STRICT mode). So do exactly that.
8958 -- Also, we have not modified the node, so this is a case where
8959 -- we need to reexpand, but not reanalyze.
8961 Reexpand;
8962 return;
8964 -- Cases where we do the operation in Bignum mode. This happens either
8965 -- because one of our operands is in Bignum mode already, or because
8966 -- the computed bounds are outside the bounds of Long_Long_Integer,
8967 -- which in some cases can be indicated by Hi and Lo being No_Uint.
8969 -- Note: we could do better here and in some cases switch back from
8970 -- Bignum mode to normal mode, e.g. big mod 2 must be in the range
8971 -- 0 .. 1, but the cases are rare and it is not worth the effort.
8972 -- Failing to do this switching back is only an efficiency issue.
8974 elsif Lo = No_Uint or else Lo < LLLo or else Hi > LLHi then
8976 -- OK, we are definitely outside the range of Long_Long_Integer. The
8977 -- question is whether to move to Bignum mode, or stay in the domain
8978 -- of Long_Long_Integer, signalling that an overflow check is needed.
8980 -- Obviously in MINIMIZED mode we stay with LLI, since we are not in
8981 -- the Bignum business. In ELIMINATED mode, we will normally move
8982 -- into Bignum mode, but there is an exception if neither of our
8983 -- operands is Bignum now, and we are at the top level (Top_Level
8984 -- set True). In this case, there is no point in moving into Bignum
8985 -- mode to prevent overflow if the caller will immediately convert
8986 -- the Bignum value back to LLI with an overflow check. It's more
8987 -- efficient to stay in LLI mode with an overflow check (if needed)
8989 if Check_Mode = Minimized
8990 or else (Top_Level and not Bignum_Operands)
8991 then
8992 if Do_Overflow_Check (N) then
8993 Enable_Overflow_Check (N);
8994 end if;
8996 -- The result now has to be in Long_Long_Integer mode, so adjust
8997 -- the possible range to reflect this. Note these calls also
8998 -- change No_Uint values from the top level case to LLI bounds.
9000 Max (Lo, LLLo);
9001 Min (Hi, LLHi);
9003 -- Otherwise we are in ELIMINATED mode and we switch to Bignum mode
9005 else
9006 pragma Assert (Check_Mode = Eliminated);
9008 declare
9009 Fent : Entity_Id;
9010 Args : List_Id;
9012 begin
9013 case Nkind (N) is
9014 when N_Op_Abs =>
9015 Fent := RTE (RE_Big_Abs);
9017 when N_Op_Add =>
9018 Fent := RTE (RE_Big_Add);
9020 when N_Op_Divide =>
9021 Fent := RTE (RE_Big_Div);
9023 when N_Op_Expon =>
9024 Fent := RTE (RE_Big_Exp);
9026 when N_Op_Minus =>
9027 Fent := RTE (RE_Big_Neg);
9029 when N_Op_Mod =>
9030 Fent := RTE (RE_Big_Mod);
9032 when N_Op_Multiply =>
9033 Fent := RTE (RE_Big_Mul);
9035 when N_Op_Rem =>
9036 Fent := RTE (RE_Big_Rem);
9038 when N_Op_Subtract =>
9039 Fent := RTE (RE_Big_Sub);
9041 -- Anything else is an internal error, this includes the
9042 -- N_Op_Plus case, since how can plus cause the result
9043 -- to be out of range if the operand is in range?
9045 when others =>
9046 raise Program_Error;
9047 end case;
9049 -- Construct argument list for Bignum call, converting our
9050 -- operands to Bignum form if they are not already there.
9052 Args := New_List;
9054 if Binary then
9055 Append_To (Args, Convert_To_Bignum (Left_Opnd (N)));
9056 end if;
9058 Append_To (Args, Convert_To_Bignum (Right_Opnd (N)));
9060 -- Now rewrite the arithmetic operator with a call to the
9061 -- corresponding bignum function.
9063 Rewrite (N,
9064 Make_Function_Call (Loc,
9065 Name => New_Occurrence_Of (Fent, Loc),
9066 Parameter_Associations => Args));
9067 Reanalyze (RTE (RE_Bignum), Suppress => True);
9069 -- Indicate result is Bignum mode
9071 Lo := No_Uint;
9072 Hi := No_Uint;
9073 return;
9074 end;
9075 end if;
9077 -- Otherwise we are in range of Long_Long_Integer, so no overflow
9078 -- check is required, at least not yet.
9080 else
9081 Set_Do_Overflow_Check (N, False);
9082 end if;
9084 -- Here we are not in Bignum territory, but we may have long long
9085 -- integer operands that need special handling. First a special check:
9086 -- If an exponentiation operator exponent is of type Long_Long_Integer,
9087 -- it means we converted it to prevent overflow, but exponentiation
9088 -- requires a Natural right operand, so convert it back to Natural.
9089 -- This conversion may raise an exception which is fine.
9091 if Nkind (N) = N_Op_Expon and then Etype (Right_Opnd (N)) = LLIB then
9092 Convert_To_And_Rewrite (Standard_Natural, Right_Opnd (N));
9093 end if;
9095 -- Here we will do the operation in Long_Long_Integer. We do this even
9096 -- if we know an overflow check is required, better to do this in long
9097 -- long integer mode, since we are less likely to overflow.
9099 -- Convert right or only operand to Long_Long_Integer, except that
9100 -- we do not touch the exponentiation right operand.
9102 if Nkind (N) /= N_Op_Expon then
9103 Convert_To_And_Rewrite (LLIB, Right_Opnd (N));
9104 end if;
9106 -- Convert left operand to Long_Long_Integer for binary case
9108 if Binary then
9109 Convert_To_And_Rewrite (LLIB, Left_Opnd (N));
9110 end if;
9112 -- Reset node to unanalyzed
9114 Set_Analyzed (N, False);
9115 Set_Etype (N, Empty);
9116 Set_Entity (N, Empty);
9118 -- Now analyze this new node. This reanalysis will complete processing
9119 -- for the node. In particular we will complete the expansion of an
9120 -- exponentiation operator (e.g. changing A ** 2 to A * A), and also
9121 -- we will complete any division checks (since we have not changed the
9122 -- setting of the Do_Division_Check flag).
9124 -- We do this reanalysis in STRICT mode to avoid recursion into the
9125 -- MINIMIZED/ELIMINATED handling, since we are now done with that.
9127 declare
9128 SG : constant Overflow_Mode_Type :=
9129 Scope_Suppress.Overflow_Mode_General;
9130 SA : constant Overflow_Mode_Type :=
9131 Scope_Suppress.Overflow_Mode_Assertions;
9133 begin
9134 Scope_Suppress.Overflow_Mode_General := Strict;
9135 Scope_Suppress.Overflow_Mode_Assertions := Strict;
9137 if not Do_Overflow_Check (N) then
9138 Reanalyze (LLIB, Suppress => True);
9139 else
9140 Reanalyze (LLIB);
9141 end if;
9143 Scope_Suppress.Overflow_Mode_General := SG;
9144 Scope_Suppress.Overflow_Mode_Assertions := SA;
9145 end;
9146 end Minimize_Eliminate_Overflows;
9148 -------------------------
9149 -- Overflow_Check_Mode --
9150 -------------------------
9152 function Overflow_Check_Mode return Overflow_Mode_Type is
9153 begin
9154 if In_Assertion_Expr = 0 then
9155 return Scope_Suppress.Overflow_Mode_General;
9156 else
9157 return Scope_Suppress.Overflow_Mode_Assertions;
9158 end if;
9159 end Overflow_Check_Mode;
9161 --------------------------------
9162 -- Overflow_Checks_Suppressed --
9163 --------------------------------
9165 function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
9166 begin
9167 if Present (E) and then Checks_May_Be_Suppressed (E) then
9168 return Is_Check_Suppressed (E, Overflow_Check);
9169 else
9170 return Scope_Suppress.Suppress (Overflow_Check);
9171 end if;
9172 end Overflow_Checks_Suppressed;
9174 ---------------------------------
9175 -- Predicate_Checks_Suppressed --
9176 ---------------------------------
9178 function Predicate_Checks_Suppressed (E : Entity_Id) return Boolean is
9179 begin
9180 if Present (E) and then Checks_May_Be_Suppressed (E) then
9181 return Is_Check_Suppressed (E, Predicate_Check);
9182 else
9183 return Scope_Suppress.Suppress (Predicate_Check);
9184 end if;
9185 end Predicate_Checks_Suppressed;
9187 -----------------------------
9188 -- Range_Checks_Suppressed --
9189 -----------------------------
9191 function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
9192 begin
9193 if Present (E) then
9194 if Kill_Range_Checks (E) then
9195 return True;
9197 elsif Checks_May_Be_Suppressed (E) then
9198 return Is_Check_Suppressed (E, Range_Check);
9199 end if;
9200 end if;
9202 return Scope_Suppress.Suppress (Range_Check);
9203 end Range_Checks_Suppressed;
9205 -----------------------------------------
9206 -- Range_Or_Validity_Checks_Suppressed --
9207 -----------------------------------------
9209 -- Note: the coding would be simpler here if we simply made appropriate
9210 -- calls to Range/Validity_Checks_Suppressed, but that would result in
9211 -- duplicated checks which we prefer to avoid.
9213 function Range_Or_Validity_Checks_Suppressed
9214 (Expr : Node_Id) return Boolean
9216 begin
9217 -- Immediate return if scope checks suppressed for either check
9219 if Scope_Suppress.Suppress (Range_Check)
9221 Scope_Suppress.Suppress (Validity_Check)
9222 then
9223 return True;
9224 end if;
9226 -- If no expression, that's odd, decide that checks are suppressed,
9227 -- since we don't want anyone trying to do checks in this case, which
9228 -- is most likely the result of some other error.
9230 if No (Expr) then
9231 return True;
9232 end if;
9234 -- Expression is present, so perform suppress checks on type
9236 declare
9237 Typ : constant Entity_Id := Etype (Expr);
9238 begin
9239 if Checks_May_Be_Suppressed (Typ)
9240 and then (Is_Check_Suppressed (Typ, Range_Check)
9241 or else
9242 Is_Check_Suppressed (Typ, Validity_Check))
9243 then
9244 return True;
9245 end if;
9246 end;
9248 -- If expression is an entity name, perform checks on this entity
9250 if Is_Entity_Name (Expr) then
9251 declare
9252 Ent : constant Entity_Id := Entity (Expr);
9253 begin
9254 if Checks_May_Be_Suppressed (Ent) then
9255 return Is_Check_Suppressed (Ent, Range_Check)
9256 or else Is_Check_Suppressed (Ent, Validity_Check);
9257 end if;
9258 end;
9259 end if;
9261 -- If we fall through, no checks suppressed
9263 return False;
9264 end Range_Or_Validity_Checks_Suppressed;
9266 -------------------
9267 -- Remove_Checks --
9268 -------------------
9270 procedure Remove_Checks (Expr : Node_Id) is
9271 function Process (N : Node_Id) return Traverse_Result;
9272 -- Process a single node during the traversal
9274 procedure Traverse is new Traverse_Proc (Process);
9275 -- The traversal procedure itself
9277 -------------
9278 -- Process --
9279 -------------
9281 function Process (N : Node_Id) return Traverse_Result is
9282 begin
9283 if Nkind (N) not in N_Subexpr then
9284 return Skip;
9285 end if;
9287 Set_Do_Range_Check (N, False);
9289 case Nkind (N) is
9290 when N_And_Then =>
9291 Traverse (Left_Opnd (N));
9292 return Skip;
9294 when N_Attribute_Reference =>
9295 Set_Do_Overflow_Check (N, False);
9297 when N_Function_Call =>
9298 Set_Do_Tag_Check (N, False);
9300 when N_Op =>
9301 Set_Do_Overflow_Check (N, False);
9303 case Nkind (N) is
9304 when N_Op_Divide =>
9305 Set_Do_Division_Check (N, False);
9307 when N_Op_And =>
9308 Set_Do_Length_Check (N, False);
9310 when N_Op_Mod =>
9311 Set_Do_Division_Check (N, False);
9313 when N_Op_Or =>
9314 Set_Do_Length_Check (N, False);
9316 when N_Op_Rem =>
9317 Set_Do_Division_Check (N, False);
9319 when N_Op_Xor =>
9320 Set_Do_Length_Check (N, False);
9322 when others =>
9323 null;
9324 end case;
9326 when N_Or_Else =>
9327 Traverse (Left_Opnd (N));
9328 return Skip;
9330 when N_Selected_Component =>
9331 Set_Do_Discriminant_Check (N, False);
9333 when N_Type_Conversion =>
9334 Set_Do_Length_Check (N, False);
9335 Set_Do_Tag_Check (N, False);
9336 Set_Do_Overflow_Check (N, False);
9338 when others =>
9339 null;
9340 end case;
9342 return OK;
9343 end Process;
9345 -- Start of processing for Remove_Checks
9347 begin
9348 Traverse (Expr);
9349 end Remove_Checks;
9351 ----------------------------
9352 -- Selected_Length_Checks --
9353 ----------------------------
9355 function Selected_Length_Checks
9356 (Ck_Node : Node_Id;
9357 Target_Typ : Entity_Id;
9358 Source_Typ : Entity_Id;
9359 Warn_Node : Node_Id) return Check_Result
9361 Loc : constant Source_Ptr := Sloc (Ck_Node);
9362 S_Typ : Entity_Id;
9363 T_Typ : Entity_Id;
9364 Expr_Actual : Node_Id;
9365 Exptyp : Entity_Id;
9366 Cond : Node_Id := Empty;
9367 Do_Access : Boolean := False;
9368 Wnode : Node_Id := Warn_Node;
9369 Ret_Result : Check_Result := (Empty, Empty);
9370 Num_Checks : Natural := 0;
9372 procedure Add_Check (N : Node_Id);
9373 -- Adds the action given to Ret_Result if N is non-Empty
9375 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
9376 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
9377 -- Comments required ???
9379 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
9380 -- True for equal literals and for nodes that denote the same constant
9381 -- entity, even if its value is not a static constant. This includes the
9382 -- case of a discriminal reference within an init proc. Removes some
9383 -- obviously superfluous checks.
9385 function Length_E_Cond
9386 (Exptyp : Entity_Id;
9387 Typ : Entity_Id;
9388 Indx : Nat) return Node_Id;
9389 -- Returns expression to compute:
9390 -- Typ'Length /= Exptyp'Length
9392 function Length_N_Cond
9393 (Expr : Node_Id;
9394 Typ : Entity_Id;
9395 Indx : Nat) return Node_Id;
9396 -- Returns expression to compute:
9397 -- Typ'Length /= Expr'Length
9399 ---------------
9400 -- Add_Check --
9401 ---------------
9403 procedure Add_Check (N : Node_Id) is
9404 begin
9405 if Present (N) then
9407 -- For now, ignore attempt to place more than two checks ???
9408 -- This is really worrisome, are we really discarding checks ???
9410 if Num_Checks = 2 then
9411 return;
9412 end if;
9414 pragma Assert (Num_Checks <= 1);
9415 Num_Checks := Num_Checks + 1;
9416 Ret_Result (Num_Checks) := N;
9417 end if;
9418 end Add_Check;
9420 ------------------
9421 -- Get_E_Length --
9422 ------------------
9424 function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
9425 SE : constant Entity_Id := Scope (E);
9426 N : Node_Id;
9427 E1 : Entity_Id := E;
9429 begin
9430 if Ekind (Scope (E)) = E_Record_Type
9431 and then Has_Discriminants (Scope (E))
9432 then
9433 N := Build_Discriminal_Subtype_Of_Component (E);
9435 if Present (N) then
9436 Insert_Action (Ck_Node, N);
9437 E1 := Defining_Identifier (N);
9438 end if;
9439 end if;
9441 if Ekind (E1) = E_String_Literal_Subtype then
9442 return
9443 Make_Integer_Literal (Loc,
9444 Intval => String_Literal_Length (E1));
9446 elsif SE /= Standard_Standard
9447 and then Ekind (Scope (SE)) = E_Protected_Type
9448 and then Has_Discriminants (Scope (SE))
9449 and then Has_Completion (Scope (SE))
9450 and then not Inside_Init_Proc
9451 then
9452 -- If the type whose length is needed is a private component
9453 -- constrained by a discriminant, we must expand the 'Length
9454 -- attribute into an explicit computation, using the discriminal
9455 -- of the current protected operation. This is because the actual
9456 -- type of the prival is constructed after the protected opera-
9457 -- tion has been fully expanded.
9459 declare
9460 Indx_Type : Node_Id;
9461 Lo : Node_Id;
9462 Hi : Node_Id;
9463 Do_Expand : Boolean := False;
9465 begin
9466 Indx_Type := First_Index (E);
9468 for J in 1 .. Indx - 1 loop
9469 Next_Index (Indx_Type);
9470 end loop;
9472 Get_Index_Bounds (Indx_Type, Lo, Hi);
9474 if Nkind (Lo) = N_Identifier
9475 and then Ekind (Entity (Lo)) = E_In_Parameter
9476 then
9477 Lo := Get_Discriminal (E, Lo);
9478 Do_Expand := True;
9479 end if;
9481 if Nkind (Hi) = N_Identifier
9482 and then Ekind (Entity (Hi)) = E_In_Parameter
9483 then
9484 Hi := Get_Discriminal (E, Hi);
9485 Do_Expand := True;
9486 end if;
9488 if Do_Expand then
9489 if not Is_Entity_Name (Lo) then
9490 Lo := Duplicate_Subexpr_No_Checks (Lo);
9491 end if;
9493 if not Is_Entity_Name (Hi) then
9494 Lo := Duplicate_Subexpr_No_Checks (Hi);
9495 end if;
9497 N :=
9498 Make_Op_Add (Loc,
9499 Left_Opnd =>
9500 Make_Op_Subtract (Loc,
9501 Left_Opnd => Hi,
9502 Right_Opnd => Lo),
9504 Right_Opnd => Make_Integer_Literal (Loc, 1));
9505 return N;
9507 else
9508 N :=
9509 Make_Attribute_Reference (Loc,
9510 Attribute_Name => Name_Length,
9511 Prefix =>
9512 New_Occurrence_Of (E1, Loc));
9514 if Indx > 1 then
9515 Set_Expressions (N, New_List (
9516 Make_Integer_Literal (Loc, Indx)));
9517 end if;
9519 return N;
9520 end if;
9521 end;
9523 else
9524 N :=
9525 Make_Attribute_Reference (Loc,
9526 Attribute_Name => Name_Length,
9527 Prefix =>
9528 New_Occurrence_Of (E1, Loc));
9530 if Indx > 1 then
9531 Set_Expressions (N, New_List (
9532 Make_Integer_Literal (Loc, Indx)));
9533 end if;
9535 return N;
9536 end if;
9537 end Get_E_Length;
9539 ------------------
9540 -- Get_N_Length --
9541 ------------------
9543 function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
9544 begin
9545 return
9546 Make_Attribute_Reference (Loc,
9547 Attribute_Name => Name_Length,
9548 Prefix =>
9549 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
9550 Expressions => New_List (
9551 Make_Integer_Literal (Loc, Indx)));
9552 end Get_N_Length;
9554 -------------------
9555 -- Length_E_Cond --
9556 -------------------
9558 function Length_E_Cond
9559 (Exptyp : Entity_Id;
9560 Typ : Entity_Id;
9561 Indx : Nat) return Node_Id
9563 begin
9564 return
9565 Make_Op_Ne (Loc,
9566 Left_Opnd => Get_E_Length (Typ, Indx),
9567 Right_Opnd => Get_E_Length (Exptyp, Indx));
9568 end Length_E_Cond;
9570 -------------------
9571 -- Length_N_Cond --
9572 -------------------
9574 function Length_N_Cond
9575 (Expr : Node_Id;
9576 Typ : Entity_Id;
9577 Indx : Nat) return Node_Id
9579 begin
9580 return
9581 Make_Op_Ne (Loc,
9582 Left_Opnd => Get_E_Length (Typ, Indx),
9583 Right_Opnd => Get_N_Length (Expr, Indx));
9584 end Length_N_Cond;
9586 -----------------
9587 -- Same_Bounds --
9588 -----------------
9590 function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
9591 begin
9592 return
9593 (Nkind (L) = N_Integer_Literal
9594 and then Nkind (R) = N_Integer_Literal
9595 and then Intval (L) = Intval (R))
9597 or else
9598 (Is_Entity_Name (L)
9599 and then Ekind (Entity (L)) = E_Constant
9600 and then ((Is_Entity_Name (R)
9601 and then Entity (L) = Entity (R))
9602 or else
9603 (Nkind (R) = N_Type_Conversion
9604 and then Is_Entity_Name (Expression (R))
9605 and then Entity (L) = Entity (Expression (R)))))
9607 or else
9608 (Is_Entity_Name (R)
9609 and then Ekind (Entity (R)) = E_Constant
9610 and then Nkind (L) = N_Type_Conversion
9611 and then Is_Entity_Name (Expression (L))
9612 and then Entity (R) = Entity (Expression (L)))
9614 or else
9615 (Is_Entity_Name (L)
9616 and then Is_Entity_Name (R)
9617 and then Entity (L) = Entity (R)
9618 and then Ekind (Entity (L)) = E_In_Parameter
9619 and then Inside_Init_Proc);
9620 end Same_Bounds;
9622 -- Start of processing for Selected_Length_Checks
9624 begin
9625 -- Checks will be applied only when generating code
9627 if not Expander_Active then
9628 return Ret_Result;
9629 end if;
9631 if Target_Typ = Any_Type
9632 or else Target_Typ = Any_Composite
9633 or else Raises_Constraint_Error (Ck_Node)
9634 then
9635 return Ret_Result;
9636 end if;
9638 if No (Wnode) then
9639 Wnode := Ck_Node;
9640 end if;
9642 T_Typ := Target_Typ;
9644 if No (Source_Typ) then
9645 S_Typ := Etype (Ck_Node);
9646 else
9647 S_Typ := Source_Typ;
9648 end if;
9650 if S_Typ = Any_Type or else S_Typ = Any_Composite then
9651 return Ret_Result;
9652 end if;
9654 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
9655 S_Typ := Designated_Type (S_Typ);
9656 T_Typ := Designated_Type (T_Typ);
9657 Do_Access := True;
9659 -- A simple optimization for the null case
9661 if Known_Null (Ck_Node) then
9662 return Ret_Result;
9663 end if;
9664 end if;
9666 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
9667 if Is_Constrained (T_Typ) then
9669 -- The checking code to be generated will freeze the corresponding
9670 -- array type. However, we must freeze the type now, so that the
9671 -- freeze node does not appear within the generated if expression,
9672 -- but ahead of it.
9674 Freeze_Before (Ck_Node, T_Typ);
9676 Expr_Actual := Get_Referenced_Object (Ck_Node);
9677 Exptyp := Get_Actual_Subtype (Ck_Node);
9679 if Is_Access_Type (Exptyp) then
9680 Exptyp := Designated_Type (Exptyp);
9681 end if;
9683 -- String_Literal case. This needs to be handled specially be-
9684 -- cause no index types are available for string literals. The
9685 -- condition is simply:
9687 -- T_Typ'Length = string-literal-length
9689 if Nkind (Expr_Actual) = N_String_Literal
9690 and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
9691 then
9692 Cond :=
9693 Make_Op_Ne (Loc,
9694 Left_Opnd => Get_E_Length (T_Typ, 1),
9695 Right_Opnd =>
9696 Make_Integer_Literal (Loc,
9697 Intval =>
9698 String_Literal_Length (Etype (Expr_Actual))));
9700 -- General array case. Here we have a usable actual subtype for
9701 -- the expression, and the condition is built from the two types
9702 -- (Do_Length):
9704 -- T_Typ'Length /= Exptyp'Length or else
9705 -- T_Typ'Length (2) /= Exptyp'Length (2) or else
9706 -- T_Typ'Length (3) /= Exptyp'Length (3) or else
9707 -- ...
9709 elsif Is_Constrained (Exptyp) then
9710 declare
9711 Ndims : constant Nat := Number_Dimensions (T_Typ);
9713 L_Index : Node_Id;
9714 R_Index : Node_Id;
9715 L_Low : Node_Id;
9716 L_High : Node_Id;
9717 R_Low : Node_Id;
9718 R_High : Node_Id;
9719 L_Length : Uint;
9720 R_Length : Uint;
9721 Ref_Node : Node_Id;
9723 begin
9724 -- At the library level, we need to ensure that the type of
9725 -- the object is elaborated before the check itself is
9726 -- emitted. This is only done if the object is in the
9727 -- current compilation unit, otherwise the type is frozen
9728 -- and elaborated in its unit.
9730 if Is_Itype (Exptyp)
9731 and then
9732 Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
9733 and then
9734 not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
9735 and then In_Open_Scopes (Scope (Exptyp))
9736 then
9737 Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
9738 Set_Itype (Ref_Node, Exptyp);
9739 Insert_Action (Ck_Node, Ref_Node);
9740 end if;
9742 L_Index := First_Index (T_Typ);
9743 R_Index := First_Index (Exptyp);
9745 for Indx in 1 .. Ndims loop
9746 if not (Nkind (L_Index) = N_Raise_Constraint_Error
9747 or else
9748 Nkind (R_Index) = N_Raise_Constraint_Error)
9749 then
9750 Get_Index_Bounds (L_Index, L_Low, L_High);
9751 Get_Index_Bounds (R_Index, R_Low, R_High);
9753 -- Deal with compile time length check. Note that we
9754 -- skip this in the access case, because the access
9755 -- value may be null, so we cannot know statically.
9757 if not Do_Access
9758 and then Compile_Time_Known_Value (L_Low)
9759 and then Compile_Time_Known_Value (L_High)
9760 and then Compile_Time_Known_Value (R_Low)
9761 and then Compile_Time_Known_Value (R_High)
9762 then
9763 if Expr_Value (L_High) >= Expr_Value (L_Low) then
9764 L_Length := Expr_Value (L_High) -
9765 Expr_Value (L_Low) + 1;
9766 else
9767 L_Length := UI_From_Int (0);
9768 end if;
9770 if Expr_Value (R_High) >= Expr_Value (R_Low) then
9771 R_Length := Expr_Value (R_High) -
9772 Expr_Value (R_Low) + 1;
9773 else
9774 R_Length := UI_From_Int (0);
9775 end if;
9777 if L_Length > R_Length then
9778 Add_Check
9779 (Compile_Time_Constraint_Error
9780 (Wnode, "too few elements for}??", T_Typ));
9782 elsif L_Length < R_Length then
9783 Add_Check
9784 (Compile_Time_Constraint_Error
9785 (Wnode, "too many elements for}??", T_Typ));
9786 end if;
9788 -- The comparison for an individual index subtype
9789 -- is omitted if the corresponding index subtypes
9790 -- statically match, since the result is known to
9791 -- be true. Note that this test is worth while even
9792 -- though we do static evaluation, because non-static
9793 -- subtypes can statically match.
9795 elsif not
9796 Subtypes_Statically_Match
9797 (Etype (L_Index), Etype (R_Index))
9799 and then not
9800 (Same_Bounds (L_Low, R_Low)
9801 and then Same_Bounds (L_High, R_High))
9802 then
9803 Evolve_Or_Else
9804 (Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
9805 end if;
9807 Next (L_Index);
9808 Next (R_Index);
9809 end if;
9810 end loop;
9811 end;
9813 -- Handle cases where we do not get a usable actual subtype that
9814 -- is constrained. This happens for example in the function call
9815 -- and explicit dereference cases. In these cases, we have to get
9816 -- the length or range from the expression itself, making sure we
9817 -- do not evaluate it more than once.
9819 -- Here Ck_Node is the original expression, or more properly the
9820 -- result of applying Duplicate_Expr to the original tree, forcing
9821 -- the result to be a name.
9823 else
9824 declare
9825 Ndims : constant Nat := Number_Dimensions (T_Typ);
9827 begin
9828 -- Build the condition for the explicit dereference case
9830 for Indx in 1 .. Ndims loop
9831 Evolve_Or_Else
9832 (Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
9833 end loop;
9834 end;
9835 end if;
9836 end if;
9837 end if;
9839 -- Construct the test and insert into the tree
9841 if Present (Cond) then
9842 if Do_Access then
9843 Cond := Guard_Access (Cond, Loc, Ck_Node);
9844 end if;
9846 Add_Check
9847 (Make_Raise_Constraint_Error (Loc,
9848 Condition => Cond,
9849 Reason => CE_Length_Check_Failed));
9850 end if;
9852 return Ret_Result;
9853 end Selected_Length_Checks;
9855 ---------------------------
9856 -- Selected_Range_Checks --
9857 ---------------------------
9859 function Selected_Range_Checks
9860 (Ck_Node : Node_Id;
9861 Target_Typ : Entity_Id;
9862 Source_Typ : Entity_Id;
9863 Warn_Node : Node_Id) return Check_Result
9865 Loc : constant Source_Ptr := Sloc (Ck_Node);
9866 S_Typ : Entity_Id;
9867 T_Typ : Entity_Id;
9868 Expr_Actual : Node_Id;
9869 Exptyp : Entity_Id;
9870 Cond : Node_Id := Empty;
9871 Do_Access : Boolean := False;
9872 Wnode : Node_Id := Warn_Node;
9873 Ret_Result : Check_Result := (Empty, Empty);
9874 Num_Checks : Natural := 0;
9876 procedure Add_Check (N : Node_Id);
9877 -- Adds the action given to Ret_Result if N is non-Empty
9879 function Discrete_Range_Cond
9880 (Expr : Node_Id;
9881 Typ : Entity_Id) return Node_Id;
9882 -- Returns expression to compute:
9883 -- Low_Bound (Expr) < Typ'First
9884 -- or else
9885 -- High_Bound (Expr) > Typ'Last
9887 function Discrete_Expr_Cond
9888 (Expr : Node_Id;
9889 Typ : Entity_Id) return Node_Id;
9890 -- Returns expression to compute:
9891 -- Expr < Typ'First
9892 -- or else
9893 -- Expr > Typ'Last
9895 function Get_E_First_Or_Last
9896 (Loc : Source_Ptr;
9897 E : Entity_Id;
9898 Indx : Nat;
9899 Nam : Name_Id) return Node_Id;
9900 -- Returns an attribute reference
9901 -- E'First or E'Last
9902 -- with a source location of Loc.
9904 -- Nam is Name_First or Name_Last, according to which attribute is
9905 -- desired. If Indx is non-zero, it is passed as a literal in the
9906 -- Expressions of the attribute reference (identifying the desired
9907 -- array dimension).
9909 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
9910 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
9911 -- Returns expression to compute:
9912 -- N'First or N'Last using Duplicate_Subexpr_No_Checks
9914 function Range_E_Cond
9915 (Exptyp : Entity_Id;
9916 Typ : Entity_Id;
9917 Indx : Nat)
9918 return Node_Id;
9919 -- Returns expression to compute:
9920 -- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
9922 function Range_Equal_E_Cond
9923 (Exptyp : Entity_Id;
9924 Typ : Entity_Id;
9925 Indx : Nat) return Node_Id;
9926 -- Returns expression to compute:
9927 -- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
9929 function Range_N_Cond
9930 (Expr : Node_Id;
9931 Typ : Entity_Id;
9932 Indx : Nat) return Node_Id;
9933 -- Return expression to compute:
9934 -- Expr'First < Typ'First or else Expr'Last > Typ'Last
9936 ---------------
9937 -- Add_Check --
9938 ---------------
9940 procedure Add_Check (N : Node_Id) is
9941 begin
9942 if Present (N) then
9944 -- For now, ignore attempt to place more than 2 checks ???
9946 if Num_Checks = 2 then
9947 return;
9948 end if;
9950 pragma Assert (Num_Checks <= 1);
9951 Num_Checks := Num_Checks + 1;
9952 Ret_Result (Num_Checks) := N;
9953 end if;
9954 end Add_Check;
9956 -------------------------
9957 -- Discrete_Expr_Cond --
9958 -------------------------
9960 function Discrete_Expr_Cond
9961 (Expr : Node_Id;
9962 Typ : Entity_Id) return Node_Id
9964 begin
9965 return
9966 Make_Or_Else (Loc,
9967 Left_Opnd =>
9968 Make_Op_Lt (Loc,
9969 Left_Opnd =>
9970 Convert_To (Base_Type (Typ),
9971 Duplicate_Subexpr_No_Checks (Expr)),
9972 Right_Opnd =>
9973 Convert_To (Base_Type (Typ),
9974 Get_E_First_Or_Last (Loc, Typ, 0, Name_First))),
9976 Right_Opnd =>
9977 Make_Op_Gt (Loc,
9978 Left_Opnd =>
9979 Convert_To (Base_Type (Typ),
9980 Duplicate_Subexpr_No_Checks (Expr)),
9981 Right_Opnd =>
9982 Convert_To
9983 (Base_Type (Typ),
9984 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last))));
9985 end Discrete_Expr_Cond;
9987 -------------------------
9988 -- Discrete_Range_Cond --
9989 -------------------------
9991 function Discrete_Range_Cond
9992 (Expr : Node_Id;
9993 Typ : Entity_Id) return Node_Id
9995 LB : Node_Id := Low_Bound (Expr);
9996 HB : Node_Id := High_Bound (Expr);
9998 Left_Opnd : Node_Id;
9999 Right_Opnd : Node_Id;
10001 begin
10002 if Nkind (LB) = N_Identifier
10003 and then Ekind (Entity (LB)) = E_Discriminant
10004 then
10005 LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10006 end if;
10008 Left_Opnd :=
10009 Make_Op_Lt (Loc,
10010 Left_Opnd =>
10011 Convert_To
10012 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
10014 Right_Opnd =>
10015 Convert_To
10016 (Base_Type (Typ),
10017 Get_E_First_Or_Last (Loc, Typ, 0, Name_First)));
10019 if Nkind (HB) = N_Identifier
10020 and then Ekind (Entity (HB)) = E_Discriminant
10021 then
10022 HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10023 end if;
10025 Right_Opnd :=
10026 Make_Op_Gt (Loc,
10027 Left_Opnd =>
10028 Convert_To
10029 (Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
10031 Right_Opnd =>
10032 Convert_To
10033 (Base_Type (Typ),
10034 Get_E_First_Or_Last (Loc, Typ, 0, Name_Last)));
10036 return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
10037 end Discrete_Range_Cond;
10039 -------------------------
10040 -- Get_E_First_Or_Last --
10041 -------------------------
10043 function Get_E_First_Or_Last
10044 (Loc : Source_Ptr;
10045 E : Entity_Id;
10046 Indx : Nat;
10047 Nam : Name_Id) return Node_Id
10049 Exprs : List_Id;
10050 begin
10051 if Indx > 0 then
10052 Exprs := New_List (Make_Integer_Literal (Loc, UI_From_Int (Indx)));
10053 else
10054 Exprs := No_List;
10055 end if;
10057 return Make_Attribute_Reference (Loc,
10058 Prefix => New_Occurrence_Of (E, Loc),
10059 Attribute_Name => Nam,
10060 Expressions => Exprs);
10061 end Get_E_First_Or_Last;
10063 -----------------
10064 -- Get_N_First --
10065 -----------------
10067 function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
10068 begin
10069 return
10070 Make_Attribute_Reference (Loc,
10071 Attribute_Name => Name_First,
10072 Prefix =>
10073 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10074 Expressions => New_List (
10075 Make_Integer_Literal (Loc, Indx)));
10076 end Get_N_First;
10078 ----------------
10079 -- Get_N_Last --
10080 ----------------
10082 function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
10083 begin
10084 return
10085 Make_Attribute_Reference (Loc,
10086 Attribute_Name => Name_Last,
10087 Prefix =>
10088 Duplicate_Subexpr_No_Checks (N, Name_Req => True),
10089 Expressions => New_List (
10090 Make_Integer_Literal (Loc, Indx)));
10091 end Get_N_Last;
10093 ------------------
10094 -- Range_E_Cond --
10095 ------------------
10097 function Range_E_Cond
10098 (Exptyp : Entity_Id;
10099 Typ : Entity_Id;
10100 Indx : Nat) return Node_Id
10102 begin
10103 return
10104 Make_Or_Else (Loc,
10105 Left_Opnd =>
10106 Make_Op_Lt (Loc,
10107 Left_Opnd =>
10108 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10109 Right_Opnd =>
10110 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10112 Right_Opnd =>
10113 Make_Op_Gt (Loc,
10114 Left_Opnd =>
10115 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10116 Right_Opnd =>
10117 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10118 end Range_E_Cond;
10120 ------------------------
10121 -- Range_Equal_E_Cond --
10122 ------------------------
10124 function Range_Equal_E_Cond
10125 (Exptyp : Entity_Id;
10126 Typ : Entity_Id;
10127 Indx : Nat) return Node_Id
10129 begin
10130 return
10131 Make_Or_Else (Loc,
10132 Left_Opnd =>
10133 Make_Op_Ne (Loc,
10134 Left_Opnd =>
10135 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_First),
10136 Right_Opnd =>
10137 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10139 Right_Opnd =>
10140 Make_Op_Ne (Loc,
10141 Left_Opnd =>
10142 Get_E_First_Or_Last (Loc, Exptyp, Indx, Name_Last),
10143 Right_Opnd =>
10144 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10145 end Range_Equal_E_Cond;
10147 ------------------
10148 -- Range_N_Cond --
10149 ------------------
10151 function Range_N_Cond
10152 (Expr : Node_Id;
10153 Typ : Entity_Id;
10154 Indx : Nat) return Node_Id
10156 begin
10157 return
10158 Make_Or_Else (Loc,
10159 Left_Opnd =>
10160 Make_Op_Lt (Loc,
10161 Left_Opnd =>
10162 Get_N_First (Expr, Indx),
10163 Right_Opnd =>
10164 Get_E_First_Or_Last (Loc, Typ, Indx, Name_First)),
10166 Right_Opnd =>
10167 Make_Op_Gt (Loc,
10168 Left_Opnd =>
10169 Get_N_Last (Expr, Indx),
10170 Right_Opnd =>
10171 Get_E_First_Or_Last (Loc, Typ, Indx, Name_Last)));
10172 end Range_N_Cond;
10174 -- Start of processing for Selected_Range_Checks
10176 begin
10177 -- Checks will be applied only when generating code. In GNATprove mode,
10178 -- we do not apply the checks, but we still call Selected_Range_Checks
10179 -- to possibly issue errors on SPARK code when a run-time error can be
10180 -- detected at compile time.
10182 if not Expander_Active and not GNATprove_Mode then
10183 return Ret_Result;
10184 end if;
10186 if Target_Typ = Any_Type
10187 or else Target_Typ = Any_Composite
10188 or else Raises_Constraint_Error (Ck_Node)
10189 then
10190 return Ret_Result;
10191 end if;
10193 if No (Wnode) then
10194 Wnode := Ck_Node;
10195 end if;
10197 T_Typ := Target_Typ;
10199 if No (Source_Typ) then
10200 S_Typ := Etype (Ck_Node);
10201 else
10202 S_Typ := Source_Typ;
10203 end if;
10205 if S_Typ = Any_Type or else S_Typ = Any_Composite then
10206 return Ret_Result;
10207 end if;
10209 -- The order of evaluating T_Typ before S_Typ seems to be critical
10210 -- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
10211 -- in, and since Node can be an N_Range node, it might be invalid.
10212 -- Should there be an assert check somewhere for taking the Etype of
10213 -- an N_Range node ???
10215 if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
10216 S_Typ := Designated_Type (S_Typ);
10217 T_Typ := Designated_Type (T_Typ);
10218 Do_Access := True;
10220 -- A simple optimization for the null case
10222 if Known_Null (Ck_Node) then
10223 return Ret_Result;
10224 end if;
10225 end if;
10227 -- For an N_Range Node, check for a null range and then if not
10228 -- null generate a range check action.
10230 if Nkind (Ck_Node) = N_Range then
10232 -- There's no point in checking a range against itself
10234 if Ck_Node = Scalar_Range (T_Typ) then
10235 return Ret_Result;
10236 end if;
10238 declare
10239 T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
10240 T_HB : constant Node_Id := Type_High_Bound (T_Typ);
10241 Known_T_LB : constant Boolean := Compile_Time_Known_Value (T_LB);
10242 Known_T_HB : constant Boolean := Compile_Time_Known_Value (T_HB);
10244 LB : Node_Id := Low_Bound (Ck_Node);
10245 HB : Node_Id := High_Bound (Ck_Node);
10246 Known_LB : Boolean := False;
10247 Known_HB : Boolean := False;
10249 Null_Range : Boolean;
10250 Out_Of_Range_L : Boolean;
10251 Out_Of_Range_H : Boolean;
10253 begin
10254 -- Compute what is known at compile time
10256 if Known_T_LB and Known_T_HB then
10257 if Compile_Time_Known_Value (LB) then
10258 Known_LB := True;
10260 -- There's no point in checking that a bound is within its
10261 -- own range so pretend that it is known in this case. First
10262 -- deal with low bound.
10264 elsif Ekind (Etype (LB)) = E_Signed_Integer_Subtype
10265 and then Scalar_Range (Etype (LB)) = Scalar_Range (T_Typ)
10266 then
10267 LB := T_LB;
10268 Known_LB := True;
10269 end if;
10271 -- Likewise for the high bound
10273 if Compile_Time_Known_Value (HB) then
10274 Known_HB := True;
10276 elsif Ekind (Etype (HB)) = E_Signed_Integer_Subtype
10277 and then Scalar_Range (Etype (HB)) = Scalar_Range (T_Typ)
10278 then
10279 HB := T_HB;
10280 Known_HB := True;
10281 end if;
10282 end if;
10284 -- Check for case where everything is static and we can do the
10285 -- check at compile time. This is skipped if we have an access
10286 -- type, since the access value may be null.
10288 -- ??? This code can be improved since you only need to know that
10289 -- the two respective bounds (LB & T_LB or HB & T_HB) are known at
10290 -- compile time to emit pertinent messages.
10292 if Known_T_LB and Known_T_HB and Known_LB and Known_HB
10293 and not Do_Access
10294 then
10295 -- Floating-point case
10297 if Is_Floating_Point_Type (S_Typ) then
10298 Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
10299 Out_Of_Range_L :=
10300 (Expr_Value_R (LB) < Expr_Value_R (T_LB))
10301 or else
10302 (Expr_Value_R (LB) > Expr_Value_R (T_HB));
10304 Out_Of_Range_H :=
10305 (Expr_Value_R (HB) > Expr_Value_R (T_HB))
10306 or else
10307 (Expr_Value_R (HB) < Expr_Value_R (T_LB));
10309 -- Fixed or discrete type case
10311 else
10312 Null_Range := Expr_Value (HB) < Expr_Value (LB);
10313 Out_Of_Range_L :=
10314 (Expr_Value (LB) < Expr_Value (T_LB))
10315 or else
10316 (Expr_Value (LB) > Expr_Value (T_HB));
10318 Out_Of_Range_H :=
10319 (Expr_Value (HB) > Expr_Value (T_HB))
10320 or else
10321 (Expr_Value (HB) < Expr_Value (T_LB));
10322 end if;
10324 if not Null_Range then
10325 if Out_Of_Range_L then
10326 if No (Warn_Node) then
10327 Add_Check
10328 (Compile_Time_Constraint_Error
10329 (Low_Bound (Ck_Node),
10330 "static value out of range of}??", T_Typ));
10332 else
10333 Add_Check
10334 (Compile_Time_Constraint_Error
10335 (Wnode,
10336 "static range out of bounds of}??", T_Typ));
10337 end if;
10338 end if;
10340 if Out_Of_Range_H then
10341 if No (Warn_Node) then
10342 Add_Check
10343 (Compile_Time_Constraint_Error
10344 (High_Bound (Ck_Node),
10345 "static value out of range of}??", T_Typ));
10347 else
10348 Add_Check
10349 (Compile_Time_Constraint_Error
10350 (Wnode,
10351 "static range out of bounds of}??", T_Typ));
10352 end if;
10353 end if;
10354 end if;
10356 else
10357 declare
10358 LB : Node_Id := Low_Bound (Ck_Node);
10359 HB : Node_Id := High_Bound (Ck_Node);
10361 begin
10362 -- If either bound is a discriminant and we are within the
10363 -- record declaration, it is a use of the discriminant in a
10364 -- constraint of a component, and nothing can be checked
10365 -- here. The check will be emitted within the init proc.
10366 -- Before then, the discriminal has no real meaning.
10367 -- Similarly, if the entity is a discriminal, there is no
10368 -- check to perform yet.
10370 -- The same holds within a discriminated synchronized type,
10371 -- where the discriminant may constrain a component or an
10372 -- entry family.
10374 if Nkind (LB) = N_Identifier
10375 and then Denotes_Discriminant (LB, True)
10376 then
10377 if Current_Scope = Scope (Entity (LB))
10378 or else Is_Concurrent_Type (Current_Scope)
10379 or else Ekind (Entity (LB)) /= E_Discriminant
10380 then
10381 return Ret_Result;
10382 else
10383 LB :=
10384 New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
10385 end if;
10386 end if;
10388 if Nkind (HB) = N_Identifier
10389 and then Denotes_Discriminant (HB, True)
10390 then
10391 if Current_Scope = Scope (Entity (HB))
10392 or else Is_Concurrent_Type (Current_Scope)
10393 or else Ekind (Entity (HB)) /= E_Discriminant
10394 then
10395 return Ret_Result;
10396 else
10397 HB :=
10398 New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
10399 end if;
10400 end if;
10402 Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
10403 Set_Paren_Count (Cond, 1);
10405 Cond :=
10406 Make_And_Then (Loc,
10407 Left_Opnd =>
10408 Make_Op_Ge (Loc,
10409 Left_Opnd =>
10410 Convert_To (Base_Type (Etype (HB)),
10411 Duplicate_Subexpr_No_Checks (HB)),
10412 Right_Opnd =>
10413 Convert_To (Base_Type (Etype (LB)),
10414 Duplicate_Subexpr_No_Checks (LB))),
10415 Right_Opnd => Cond);
10416 end;
10417 end if;
10418 end;
10420 elsif Is_Scalar_Type (S_Typ) then
10422 -- This somewhat duplicates what Apply_Scalar_Range_Check does,
10423 -- except the above simply sets a flag in the node and lets
10424 -- gigi generate the check base on the Etype of the expression.
10425 -- Sometimes, however we want to do a dynamic check against an
10426 -- arbitrary target type, so we do that here.
10428 if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
10429 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10431 -- For literals, we can tell if the constraint error will be
10432 -- raised at compile time, so we never need a dynamic check, but
10433 -- if the exception will be raised, then post the usual warning,
10434 -- and replace the literal with a raise constraint error
10435 -- expression. As usual, skip this for access types
10437 elsif Compile_Time_Known_Value (Ck_Node) and then not Do_Access then
10438 declare
10439 LB : constant Node_Id := Type_Low_Bound (T_Typ);
10440 UB : constant Node_Id := Type_High_Bound (T_Typ);
10442 Out_Of_Range : Boolean;
10443 Static_Bounds : constant Boolean :=
10444 Compile_Time_Known_Value (LB)
10445 and Compile_Time_Known_Value (UB);
10447 begin
10448 -- Following range tests should use Sem_Eval routine ???
10450 if Static_Bounds then
10451 if Is_Floating_Point_Type (S_Typ) then
10452 Out_Of_Range :=
10453 (Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
10454 or else
10455 (Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
10457 -- Fixed or discrete type
10459 else
10460 Out_Of_Range :=
10461 Expr_Value (Ck_Node) < Expr_Value (LB)
10462 or else
10463 Expr_Value (Ck_Node) > Expr_Value (UB);
10464 end if;
10466 -- Bounds of the type are static and the literal is out of
10467 -- range so output a warning message.
10469 if Out_Of_Range then
10470 if No (Warn_Node) then
10471 Add_Check
10472 (Compile_Time_Constraint_Error
10473 (Ck_Node,
10474 "static value out of range of}??", T_Typ));
10476 else
10477 Add_Check
10478 (Compile_Time_Constraint_Error
10479 (Wnode,
10480 "static value out of range of}??", T_Typ));
10481 end if;
10482 end if;
10484 else
10485 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10486 end if;
10487 end;
10489 -- Here for the case of a non-static expression, we need a runtime
10490 -- check unless the source type range is guaranteed to be in the
10491 -- range of the target type.
10493 else
10494 if not In_Subrange_Of (S_Typ, T_Typ) then
10495 Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
10496 end if;
10497 end if;
10498 end if;
10500 if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
10501 if Is_Constrained (T_Typ) then
10503 Expr_Actual := Get_Referenced_Object (Ck_Node);
10504 Exptyp := Get_Actual_Subtype (Expr_Actual);
10506 if Is_Access_Type (Exptyp) then
10507 Exptyp := Designated_Type (Exptyp);
10508 end if;
10510 -- String_Literal case. This needs to be handled specially be-
10511 -- cause no index types are available for string literals. The
10512 -- condition is simply:
10514 -- T_Typ'Length = string-literal-length
10516 if Nkind (Expr_Actual) = N_String_Literal then
10517 null;
10519 -- General array case. Here we have a usable actual subtype for
10520 -- the expression, and the condition is built from the two types
10522 -- T_Typ'First < Exptyp'First or else
10523 -- T_Typ'Last > Exptyp'Last or else
10524 -- T_Typ'First(1) < Exptyp'First(1) or else
10525 -- T_Typ'Last(1) > Exptyp'Last(1) or else
10526 -- ...
10528 elsif Is_Constrained (Exptyp) then
10529 declare
10530 Ndims : constant Nat := Number_Dimensions (T_Typ);
10532 L_Index : Node_Id;
10533 R_Index : Node_Id;
10535 begin
10536 L_Index := First_Index (T_Typ);
10537 R_Index := First_Index (Exptyp);
10539 for Indx in 1 .. Ndims loop
10540 if not (Nkind (L_Index) = N_Raise_Constraint_Error
10541 or else
10542 Nkind (R_Index) = N_Raise_Constraint_Error)
10543 then
10544 -- Deal with compile time length check. Note that we
10545 -- skip this in the access case, because the access
10546 -- value may be null, so we cannot know statically.
10548 if not
10549 Subtypes_Statically_Match
10550 (Etype (L_Index), Etype (R_Index))
10551 then
10552 -- If the target type is constrained then we
10553 -- have to check for exact equality of bounds
10554 -- (required for qualified expressions).
10556 if Is_Constrained (T_Typ) then
10557 Evolve_Or_Else
10558 (Cond,
10559 Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
10560 else
10561 Evolve_Or_Else
10562 (Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
10563 end if;
10564 end if;
10566 Next (L_Index);
10567 Next (R_Index);
10568 end if;
10569 end loop;
10570 end;
10572 -- Handle cases where we do not get a usable actual subtype that
10573 -- is constrained. This happens for example in the function call
10574 -- and explicit dereference cases. In these cases, we have to get
10575 -- the length or range from the expression itself, making sure we
10576 -- do not evaluate it more than once.
10578 -- Here Ck_Node is the original expression, or more properly the
10579 -- result of applying Duplicate_Expr to the original tree,
10580 -- forcing the result to be a name.
10582 else
10583 declare
10584 Ndims : constant Nat := Number_Dimensions (T_Typ);
10586 begin
10587 -- Build the condition for the explicit dereference case
10589 for Indx in 1 .. Ndims loop
10590 Evolve_Or_Else
10591 (Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
10592 end loop;
10593 end;
10594 end if;
10596 else
10597 -- For a conversion to an unconstrained array type, generate an
10598 -- Action to check that the bounds of the source value are within
10599 -- the constraints imposed by the target type (RM 4.6(38)). No
10600 -- check is needed for a conversion to an access to unconstrained
10601 -- array type, as 4.6(24.15/2) requires the designated subtypes
10602 -- of the two access types to statically match.
10604 if Nkind (Parent (Ck_Node)) = N_Type_Conversion
10605 and then not Do_Access
10606 then
10607 declare
10608 Opnd_Index : Node_Id;
10609 Targ_Index : Node_Id;
10610 Opnd_Range : Node_Id;
10612 begin
10613 Opnd_Index := First_Index (Get_Actual_Subtype (Ck_Node));
10614 Targ_Index := First_Index (T_Typ);
10615 while Present (Opnd_Index) loop
10617 -- If the index is a range, use its bounds. If it is an
10618 -- entity (as will be the case if it is a named subtype
10619 -- or an itype created for a slice) retrieve its range.
10621 if Is_Entity_Name (Opnd_Index)
10622 and then Is_Type (Entity (Opnd_Index))
10623 then
10624 Opnd_Range := Scalar_Range (Entity (Opnd_Index));
10625 else
10626 Opnd_Range := Opnd_Index;
10627 end if;
10629 if Nkind (Opnd_Range) = N_Range then
10630 if Is_In_Range
10631 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10632 Assume_Valid => True)
10633 and then
10634 Is_In_Range
10635 (High_Bound (Opnd_Range), Etype (Targ_Index),
10636 Assume_Valid => True)
10637 then
10638 null;
10640 -- If null range, no check needed
10642 elsif
10643 Compile_Time_Known_Value (High_Bound (Opnd_Range))
10644 and then
10645 Compile_Time_Known_Value (Low_Bound (Opnd_Range))
10646 and then
10647 Expr_Value (High_Bound (Opnd_Range)) <
10648 Expr_Value (Low_Bound (Opnd_Range))
10649 then
10650 null;
10652 elsif Is_Out_Of_Range
10653 (Low_Bound (Opnd_Range), Etype (Targ_Index),
10654 Assume_Valid => True)
10655 or else
10656 Is_Out_Of_Range
10657 (High_Bound (Opnd_Range), Etype (Targ_Index),
10658 Assume_Valid => True)
10659 then
10660 Add_Check
10661 (Compile_Time_Constraint_Error
10662 (Wnode, "value out of range of}??", T_Typ));
10664 else
10665 Evolve_Or_Else
10666 (Cond,
10667 Discrete_Range_Cond
10668 (Opnd_Range, Etype (Targ_Index)));
10669 end if;
10670 end if;
10672 Next_Index (Opnd_Index);
10673 Next_Index (Targ_Index);
10674 end loop;
10675 end;
10676 end if;
10677 end if;
10678 end if;
10680 -- Construct the test and insert into the tree
10682 if Present (Cond) then
10683 if Do_Access then
10684 Cond := Guard_Access (Cond, Loc, Ck_Node);
10685 end if;
10687 Add_Check
10688 (Make_Raise_Constraint_Error (Loc,
10689 Condition => Cond,
10690 Reason => CE_Range_Check_Failed));
10691 end if;
10693 return Ret_Result;
10694 end Selected_Range_Checks;
10696 -------------------------------
10697 -- Storage_Checks_Suppressed --
10698 -------------------------------
10700 function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
10701 begin
10702 if Present (E) and then Checks_May_Be_Suppressed (E) then
10703 return Is_Check_Suppressed (E, Storage_Check);
10704 else
10705 return Scope_Suppress.Suppress (Storage_Check);
10706 end if;
10707 end Storage_Checks_Suppressed;
10709 ---------------------------
10710 -- Tag_Checks_Suppressed --
10711 ---------------------------
10713 function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
10714 begin
10715 if Present (E)
10716 and then Checks_May_Be_Suppressed (E)
10717 then
10718 return Is_Check_Suppressed (E, Tag_Check);
10719 else
10720 return Scope_Suppress.Suppress (Tag_Check);
10721 end if;
10722 end Tag_Checks_Suppressed;
10724 ---------------------------------------
10725 -- Validate_Alignment_Check_Warnings --
10726 ---------------------------------------
10728 procedure Validate_Alignment_Check_Warnings is
10729 begin
10730 for J in Alignment_Warnings.First .. Alignment_Warnings.Last loop
10731 declare
10732 AWR : Alignment_Warnings_Record
10733 renames Alignment_Warnings.Table (J);
10734 begin
10735 if Known_Alignment (AWR.E)
10736 and then AWR.A mod Alignment (AWR.E) = 0
10737 then
10738 Delete_Warning_And_Continuations (AWR.W);
10739 end if;
10740 end;
10741 end loop;
10742 end Validate_Alignment_Check_Warnings;
10744 --------------------------
10745 -- Validity_Check_Range --
10746 --------------------------
10748 procedure Validity_Check_Range
10749 (N : Node_Id;
10750 Related_Id : Entity_Id := Empty)
10752 begin
10753 if Validity_Checks_On and Validity_Check_Operands then
10754 if Nkind (N) = N_Range then
10755 Ensure_Valid
10756 (Expr => Low_Bound (N),
10757 Related_Id => Related_Id,
10758 Is_Low_Bound => True);
10760 Ensure_Valid
10761 (Expr => High_Bound (N),
10762 Related_Id => Related_Id,
10763 Is_High_Bound => True);
10764 end if;
10765 end if;
10766 end Validity_Check_Range;
10768 --------------------------------
10769 -- Validity_Checks_Suppressed --
10770 --------------------------------
10772 function Validity_Checks_Suppressed (E : Entity_Id) return Boolean is
10773 begin
10774 if Present (E) and then Checks_May_Be_Suppressed (E) then
10775 return Is_Check_Suppressed (E, Validity_Check);
10776 else
10777 return Scope_Suppress.Suppress (Validity_Check);
10778 end if;
10779 end Validity_Checks_Suppressed;
10781 end Checks;